1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/web-BK_mE1SZ.js","assets/index-BAkwu9Px.js","assets/index-CYn1QV1R.css","assets/web-BPRVA1HR.js","assets/web-CAOshhXL.js","assets/base-wowigLDP.js","assets/native-BS7H3cZc.js","assets/index-C5PPNdDI.js"])))=>i.map(i=>d[i]); 2var bY=Object.defineProperty;var fT=e=>{throw TypeError(e)};var vY=(e,t,n)=>t in e?bY(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var _c=(e,t,n)=>vY(e,typeof t!="symbol"?t+"":t,n),mT=(e,t,n)=>t.has(e)||fT("Cannot "+n);var Ys=(e,t,n)=>(mT(e,t,"read from private field"),n?n.call(e):t.get(e)),pT=(e,t,n)=>t.has(e)?fT("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Yw=(e,t,n,r)=>(mT(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);import{g as r6,$ as Le,a as Oh,c as rc,b as s6,d as Pe,_ as wY,e as Uv,f as Yl,h as _Y,i as kY,r as p,s as jY,j as NY,u as ki,k as s,L as st,l as _e,C as Xt,R as nt,m as SY,n as B,o as hf,p as Rt,P as fi,q as zc,M as js,t as Ns,v as La,w as ma,x as hc,y as Oa,A as os,E as Qt,z as da,B as W,X as Bn,S as Ht,D as Uh,F as y2,G as a6,H as Fa,I as b2,J as v2,K as fc,N as zv,U as Xp,O as Bl,Q as si,T as w2,V as jn,W as Ba,Y as i6,Z as CY,a0 as _o,a1 as EY,a2 as AY,a3 as TY,a4 as OY,a5 as IY,a6 as PY,a7 as RY,a8 as Dr,a9 as hl,aa as ff,ab as du,ac as oa,ad as op,ae as o6,af as l6,ag as DY,ah as ji,ai as cs,aj as Jp,ak as MY,al as Wv,am as _2,an as fn,ao as Kv,ap as $Y,aq as LY,ar as FY,as as c6,at as BY,au as UY,av as zY,aw as WY,ax as KY,ay as HY,az as VY,aA as qY,aB as xT,aC as GY,aD as YY,aE as u6,aF as ZY,aG as Yt,aH as V,aI as de,aJ as ge,aK as un,aL as gT,aM as k2,aN as d6,aO as XY,aP as Hv,aQ as Xi,aR as Yn,aS as dt,aT as JY,aU as cn,aV as Re,aW as it,aX as tu,aY as Ni,aZ as hu,a_ as j2,a$ as gd,b0 as nu,b1 as mc,b2 as Id,b3 as Vv,b4 as Tt,b5 as Ca,b6 as ld,b7 as He,b8 as pc,b9 as QY,ba as eZ,bb as tZ,bc as nZ,bd as yT,be as h6,bf as Ui,bg as Qp,bh as f6,bi as m6,bj as p6,bk as qv,bl as x6,bm as g6,bn as Gv,bo as bT,bp as rZ,bq as sZ,br as aZ,bs as iZ,bt as oZ}from"./index-BAkwu9Px.js";function y6(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,a])=>t.indexOf(+r)===-1).map(([r,a])=>a)}function eN(e,t){return typeof t=="bigint"?t.toString():t}function Yv(e){return{get value(){{const t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function N2(e){return e==null}function S2(e){const t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function lZ(e,t){const n=e/t,r=Math.round(n),a=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<a?0:n-r}const vT=Symbol("evaluating");
vendor: 5,214 bytes, line 2
2function ln(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==vT)return r===void 0&&(r=vT,r=n()),r},set(a){Object.defineProperty(e,t,{value:a})},configurable:!0})}function Pd(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function fu(...e){const t={};for(const n of e){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function wT(e){return JSON.stringify(e)}function cZ(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const b6="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function lp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}const uZ=Yv(()=>{var e;if(r6.jitless||typeof navigator<"u"&&((e=navigator==null?void 0:navigator.userAgent)!=null&&e.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function zh(e){if(lp(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(lp(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function v6(e){return zh(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const dZ=new Set(["string","number","symbol"]);function Wh(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mu(e,t,n){const r=new e._zod.constr(t??e._zod.def);return(!t||n!=null&&n.parent)&&(r._zod.parent=e),r}function _t(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function hZ(e){return Object.keys(e).filter(t=>e[t]._zod.optin==="optional"&&e[t]._zod.optout==="optional")}const fZ={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function mZ(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=fu(e._zod.def,{get shape(){const o={};for(const l in t){if(!(l in n.shape))throw new Error(`Unrecognized key: "${l}"`);t[l]&&(o[l]=n.shape[l])}return Pd(this,"shape",o),o},checks:[]});return mu(e,i)}function pZ(e,t){const n=e._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=fu(e._zod.def,{get shape(){const o={...e._zod.def.shape};for(const l in t){if(!(l in n.shape))throw new Error(`Unrecognized key: "${l}"`);t[l]&&delete o[l]}return Pd(this,"shape",o),o},checks:[]});return mu(e,i)}function xZ(e,t){if(!zh(t))throw new Error("Invalid input to extend: expected a plain object");const n=e._zod.def.checks;if(n&&n.length>0){const i=e._zod.def.shape;for(const o in t)if(Object.getOwnPropertyDescriptor(i,o)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const a=fu(e._zod.def,{get shape(){const i={...e._zod.def.shape,...t};return Pd(this,"shape",i),i}});return mu(e,a)}function gZ(e,t){if(!zh(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=fu(e._zod.def,{get shape(){const r={...e._zod.def.shape,...t};return Pd(this,"shape",r),r}});return mu(e,n)}function yZ(e,t){var r;if((r=e._zod.def.checks)!=null&&r.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=fu(e._zod.def,{get shape(){const a={...e._zod.def.shape,...t._zod.def.shape};return Pd(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return mu(e,n)}function bZ(e,t,n){const a=t._zod.def.checks;if(a&&a.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const o=fu(t._zod.def,{get shape(){const l=t._zod.def.shape,c={...l};if(n)for(const u in n){if(!(u in l))throw new Error(`Unrecognized key: "${u}"`);n[u]&&(c[u]=e?new e({type:"optional",innerType:l[u]}):l[u])}else for(const u in l)c[u]=e?new e({type:"optional",innerType:l[u]}):l[u];return Pd(this,"shape",c),c},checks:[]});return mu(t,o)}function vZ(e,t,n){const r=fu(t._zod.def,{get shape(){const a=t._zod.def.shape,i={...a};if(n)for(const o in n){if(!(o in i))throw new Error(`Unrecognized key: "${o}"`);n[o]&&(i[o]=new e({type:"nonoptional",innerType:a[o]}))}else for(const o in a)i[o]=new e({type:"nonoptional",innerType:a[o]});return Pd(this,"shape",i),i}});return mu(t,r)}function kh(e,t=0){var n;if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(((n=e.issues[r])==null?void 0:n.continue)!==!0)return!0;return!1}function wZ(e,t=0){var n;if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(((n=e.issues[r])==null?void 0:n.continue)===!1)return!0;return!1}function jh(e,t){return t.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function tg(e){return typeof e=="string"?e:e==null?void 0:e.message}function sc(e,t,n){var c,u,d,h,f,m;
2const r=e.message?e.message:tg((d=(u=(c=e.inst)==null?void 0:c._zod.def)==null?void 0:u.error)==null?void 0:d.call(u,e))??tg((h=t==null?void 0:t.error)==null?void 0:h.call(t,e))??tg((f=n.customError)==null?void 0:f.call(n,e))??tg((m=n.localeError)==null?void 0:m.call(n,e))??"Invalid input",{inst:a,continue:i,input:o,...l}=e;return l.path??(l.path=[]),l.message=r,t!=null&&t.reportInput&&(l.input=o),l}function C2(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function cp(...e){const[t,n,r]=e;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const w6=(e,t)=>{e.name="$ZodError",Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,eN,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},_6=Le("$ZodError",w6),k6=Le("$ZodError",w6,{Parent:Error});function _Z(e,t=n=>n.message){const n={},r=[];for(const a of e.issues)a.path.length>0?(n[a.path[0]]=n[a.path[0]]||[],n[a.path[0]].push(t(a))):r.push(t(a));return{formErrors:r,fieldErrors:n}}function kZ(e,t=n=>n.message){const n={_errors:[]},r=(a,i=[])=>{for(const o of a.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(l=>r({issues:l},[...i,...o.path]));else if(o.code==="invalid_key")r({issues:o.issues},[...i,...o.path]);else if(o.code==="invalid_element")r({issues:o.issues},[...i,...o.path]);else{const l=[...i,...o.path];if(l.length===0)n._errors.push(t(o));else{let c=n,u=0;for(;u<l.length;){const d=l[u];u===l.length-1?(c[d]=c[d]||{_errors:[]},c[d]._errors.push(t(o))):c[d]=c[d]||{_errors:[]},c=c[d],u++}}}};return r(e),n}const E2=e=>(t,n,r,a)=>{const i=r?{...r,async:!1}:{async:!1},o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise)throw new Oh;if(o.issues.length){const l=new((a==null?void 0:a.Err)??e)(o.issues.map(c=>sc(c,i,rc())));throw b6(l,a==null?void 0:a.callee),l}return o.value},A2=e=>async(t,n,r,a)=>{const i=r?{...r,async:!0}:{async:!0};let o=t._zod.run({value:n,issues:[]},i);if(o instanceof Promise&&(o=await o),o.issues.length){const l=new((a==null?void 0:a.Err)??e)(o.issues.map(c=>sc(c,i,rc())));throw b6(l,a==null?void 0:a.callee),l}return o.value},Zv=e=>(t,n,r)=>{const a=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise)throw new Oh;return i.issues.length?{success:!1,error:new(e??_6)(i.issues.map(o=>sc(o,a,rc())))}:{success:!0,data:i.value}},jZ=Zv(k6),Xv=e=>async(t,n,r)=>{const a=r?{...r,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},a);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new e(i.issues.map(o=>sc(o,a,rc())))}:{success:!0,data:i.value}},NZ=Xv(k6),SZ=e=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return E2(e)(t,n,a)},CZ=e=>(t,n,r)=>E2(e)(t,n,r),EZ=e=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return A2(e)(t,n,a)},AZ=e=>async(t,n,r)=>A2(e)(t,n,r),TZ=e=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return Zv(e)(t,n,a)},OZ=e=>(t,n,r)=>Zv(e)(t,n,r),IZ=e=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return Xv(e)(t,n,a)},PZ=e=>async(t,n,r)=>Xv(e)(t,n,r),RZ=/^[cC][0-9a-z]{6,}$/,DZ=/^[0-9a-z]+$/,MZ=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,$Z=/^[0-9a-vA-V]{20}$/,LZ=/^[A-Za-z0-9]{27}$/,FZ=/^[a-zA-Z0-9_-]{21}$/,BZ=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,UZ=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,_T=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,zZ=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,WZ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function KZ(){return new RegExp(WZ,"u")}const HZ=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,VZ=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,qZ=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,GZ=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,YZ=/^$|^(?:[0-9a-zA-Z+/]{4}
vendor: 50,110 bytes, lines 2-65
2)*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,j6=/^[A-Za-z0-9_-]*$/,ZZ=/^https?$/,XZ=/^\+[1-9]\d{6,14}$/,N6="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",JZ=new RegExp(`^${N6}$`);function S6(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function QZ(e){return new RegExp(`^${S6(e)}$`)}function eX(e){const t=S6({precision:e.precision}),n=["Z"];e.local&&n.push(""),e.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${N6}T(?:${r})$`)}const tX=e=>{const t=e?`[\\s\\S]{${(e==null?void 0:e.minimum)??0},${(e==null?void 0:e.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},nX=/^-?\d+$/,C6=/^-?\d+(?:\.\d+)?$/,rX=/^(?:true|false)$/i,sX=/^null$/i,aX=/^[^A-Z]*$/,iX=/^[^a-z]*$/,ii=Le("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),E6={number:"number",bigint:"bigint",object:"date"},A6=Le("$ZodCheckLessThan",(e,t)=>{ii.init(e,t);const n=E6[typeof t.value];e._zod.onattach.push(r=>{const a=r._zod.bag,i=(t.inclusive?a.maximum:a.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<i&&(t.inclusive?a.maximum=t.value:a.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),T6=Le("$ZodCheckGreaterThan",(e,t)=>{ii.init(e,t);const n=E6[typeof t.value];e._zod.onattach.push(r=>{const a=r._zod.bag,i=(t.inclusive?a.minimum:a.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?a.minimum=t.value:a.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),oX=Le("$ZodCheckMultipleOf",(e,t)=>{ii.init(e,t),e._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):lZ(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),lX=Le("$ZodCheckNumberFormat",(e,t)=>{var o;ii.init(e,t),t.format=t.format||"float64";const n=(o=t.format)==null?void 0:o.includes("int"),r=n?"int":"number",[a,i]=fZ[t.format];e._zod.onattach.push(l=>{const c=l._zod.bag;c.format=t.format,c.minimum=a,c.maximum=i,n&&(c.pattern=nX)}),e._zod.check=l=>{const c=l.value;if(n){if(!Number.isInteger(c)){l.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:c,inst:e});return}if(!Number.isSafeInteger(c)){c>0?l.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort}):l.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}c<a&&l.issues.push({origin:"number",input:c,code:"too_small",minimum:a,inclusive:!0,inst:e,continue:!t.abort}),c>i&&l.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),cX=Le("$ZodCheckMaxLength",(e,t)=>{var n;ii.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!N2(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<a&&(r._zod.bag.maximum=t.maximum)}),e._zod.check=r=>{const a=r.value;if(a.length<=t.maximum)return;const o=C2(a);r.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),uX=Le("$ZodCheckMinLength",(e,t)=>{var n;ii.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!N2(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>a&&(r._zod.bag.minimum=t.minimum)}),e._zod.check=r=>{const a=r.value;if(a.length>=t.minimum)return;const o=C2(a);r.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:e,continue:!t.abort})}}),dX=Le("$ZodCheckLengthEquals",(e,t)=>{var n;ii.init(e,t),(n=e._zod.def).when??(n.when=r=>{const a=r.value;return!N2(a)&&a.length!==void 0}),e._zod.onattach.push(r=>{const a=r._zod.bag;a.minimum=t.length,a.maximum=t.length,a.length=t.length}),e._zod.check=r=>{const a=r.value,i=a.length;if(i===t.length)return;const o=C2(a),l=i>t.length;r.issues.push({origin:o,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Jv=Le("$ZodCheckStringFormat",(e,t)=>{var n,r;ii.init(e,t),e._zod.onattach.push(a=>{const i=a._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=a=>{t.pattern.lastIndex=0,!t.pattern.test(a.value)&&a.issues.push({origin:"string",code:"invalid_format",format:t.format,input:a.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),hX=Le("$ZodCheckRegex",(e,t)=>{Jv.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),fX=Le("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=aX),Jv.init(e,t)}),mX=Le("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=iX),Jv.init(e,t)}),pX=Le("$ZodCheckIncludes",(e,t)=>{ii.init(e,t);const n=Wh(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(a=>{const i=a._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),e._zod.check=a=>{a.value.includes(t.includes,t.position)||a.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:a.value,inst:e,continue:!t.abort})}}),xX=Le("$ZodCheckStartsWith",(e,t)=>{ii.init(e,t);const n=new RegExp(`^${Wh(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),e._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),gX=Le("$ZodCheckEndsWith",(e,t)=>{ii.init(e,t);const n=new RegExp(`.*${Wh(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),e._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),yX=Le("$ZodCheckOverwrite",(e,t)=>{ii.init(e,t),e._zod.check=n=>{n.value=t.tx(n.value)}});class bX{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(` 3`).filter(o=>o),a=Math.min(...r.map(o=>o.length-o.trimStart().length)),i=r.map(o=>o.slice(a)).map(o=>" ".repeat(this.indent*2)+o);for(const o of i)this.content.push(o)}compile(){const t=Function,n=this==null?void 0:this.args,a=[...((this==null?void 0:this.content)??[""]).map(i=>` ${i}`)];return new t(...n,a.join(` 4`))}}const vX={major:4,minor:4,patch:3},ar=Le("$ZodType",(e,t)=>{var a;var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=vX;const r=[...e._zod.def.checks??[]];e._zod.traits.has("$ZodCheck")&&r.unshift(e);for(const i of r)for(const o of i._zod.onattach)o(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),(a=e._zod.deferred)==null||a.push(()=>{e._zod.run=e._zod.parse});else{const i=(l,c,u)=>{let d=kh(l),h;for(const f of c){if(f._zod.def.when){if(wZ(l)||!f._zod.def.when(l))continue}else if(d)continue;const m=l.issues.length,x=f._zod.check(l);if(x instanceof Promise&&(u==null?void 0:u.async)===!1)throw new Oh;if(h||x instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await x,l.issues.length!==m&&(d||(d=kh(l,m)))});else{if(l.issues.length===m)continue;d||(d=kh(l,m))}}return h?h.then(()=>l):l},o=(l,c,u)=>{if(kh(l))return l.aborted=!0,l;const d=i(c,r,u);if(d instanceof Promise){if(u.async===!1)throw new Oh;return d.then(h=>e._zod.parse(h,u))}return e._zod.parse(d,u)};e._zod.run=(l,c)=>{if(c.skipChecks)return e._zod.parse(l,c);if(c.direction==="backward"){const d=e._zod.parse({value:l.value,issues:[]},{...c,skipChecks:!0});return d instanceof Promise?d.then(h=>o(h,l,c)):o(d,l,c)}const u=e._zod.parse(l,c);if(u instanceof Promise){if(c.async===!1)throw new Oh;return u.then(d=>i(d,r,c))}return i(u,r,c)}}ln(e,"~standard",()=>({validate:i=>{var o;try{const l=jZ(e,i);return l.success?{value:l.data}:{issues:(o=l.error)==null?void 0:o.issues}}catch{return NZ(e,i).then(c=>{var u;return c.success?{value:c.data}:{issues:(u=c.error)==null?void 0:u.issues}})}},vendor:"zod",version:1}))}),T2=Le("$ZodString",(e,t)=>{var n;ar.init(e,t),e._zod.pattern=[...((n=e==null?void 0:e._zod.bag)==null?void 0:n.patterns)??[]].pop()??tX(e._zod.bag),e._zod.parse=(r,a)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),hr=Le("$ZodStringFormat",(e,t)=>{Jv.init(e,t),T2.init(e,t)}),wX=Le("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=UZ),hr.init(e,t)}),_X=Le("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=_T(r))}else t.pattern??(t.pattern=_T());hr.init(e,t)}),kX=Le("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=zZ),hr.init(e,t)}),jX=Le("$ZodURL",(e,t)=>{hr.init(e,t),e._zod.check=n=>{var r;try{const a=n.value.trim();if(!t.normalize&&((r=t.protocol)==null?void 0:r.source)===ZZ.source&&!/^https?:\/\//i.test(a)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}const i=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),t.normalize?n.value=i.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),NX=Le("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=KZ()),hr.init(e,t)}),SX=Le("$ZodNanoID",(e,t)=>{t.pattern??(t.pattern=FZ),hr.init(e,t)}),CX=Le("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=RZ),hr.init(e,t)}),EX=Le("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=DZ),hr.init(e,t)}),AX=Le("$ZodULID",(e,t)=>{t.pattern??(t.pattern=MZ),hr.init(e,t)}),TX=Le("$ZodXID",(e,t)=>{t.pattern??(t.pattern=$Z),hr.init(e,t)}),OX=Le("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=LZ),hr.init(e,t)}),IX=Le("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=eX(t)),hr.init(e,t)}),PX=Le("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=JZ),hr.init(e,t)}),RX=Le("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=QZ(t)),hr.init(e,t)}),DX=Le("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=BZ),hr.init(e,t)}),MX=Le("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=HZ),hr.init(e,t),e._zod.bag.format="ipv4"}),$X=Le("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=VZ),hr.init(e,t),e._zod.bag.format="ipv6",e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}}),LX=Le("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=qZ),hr.init(e,t)}),FX=Le("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=GZ),hr.init(e,t),e._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[a,i]=r;if(!i)throw new Error;const o=Number(i);if(`${o}`!==i)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${a}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}}});function O6(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}const BX=Le("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=YZ),hr.init(e,t),e._zod.bag.contentEncoding="base64",e._zod.check=n=>{O6(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}});function UX(e){if(!j6.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return O6(n)}const zX=Le("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=j6),hr.init(e,t),e._zod.bag.contentEncoding="base64url",e._zod.check=n=>{UX(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),WX=Le("$ZodE164",(e,t)=>{t.pattern??(t.pattern=XZ),hr.init(e,t)});function KX(e,t=null){try{const n=e.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const a=JSON.parse(atob(r));return!("typ"in a&&(a==null?void 0:a.typ)!=="JWT"||!a.alg||t&&(!("alg"in a)||a.alg!==t))}catch{return!1}}const HX=Le("$ZodJWT",(e,t)=>{hr.init(e,t),e._zod.check=n=>{KX(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),I6=Le("$ZodNumber",(e,t)=>{ar.init(e,t),e._zod.pattern=e._zod.bag.pattern??C6,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const a=n.value;if(typeof a=="number"&&!Number.isNaN(a)&&Number.isFinite(a))return n;const i=typeof a=="number"?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:a,inst:e,...i?{received:i}:{}}),n}}),VX=Le("$ZodNumberFormat",(e,t)=>{lX.init(e,t),I6.init(e,t)}),qX=Le("$ZodBoolean",(e,t)=>{ar.init(e,t),e._zod.pattern=rX,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const a=n.value;return typeof a=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:a,inst:e}),n}}),GX=Le("$ZodNull",(e,t)=>{ar.init(e,t),e._zod.pattern=sX,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{const a=n.value;return a===null||n.issues.push({expected:"null",code:"invalid_type",input:a,inst:e}),n}}),YX=Le("$ZodUnknown",(e,t)=>{ar.init(e,t),e._zod.parse=n=>n}),ZX=Le("$ZodNever",(e,t)=>{ar.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});function kT(e,t,n){e.issues.length&&t.issues.push(...jh(n,e.issues)),t.value[n]=e.value}const XX=Le("$ZodArray",(e,t)=>{ar.init(e,t),e._zod.parse=(n,r)=>{const a=n.value;if(!Array.isArray(a))return n.issues.push({expected:"array",code:"invalid_type",input:a,inst:e}),n;n.value=Array(a.length);const i=[];for(let o=0;o<a.length;o++){const l=a[o],c=t.element._zod.run({value:l,issues:[]},r);c instanceof Promise?i.push(c.then(u=>kT(u,n,o))):kT(c,n,o)}return i.length?Promise.all(i).then(()=>n):n}});function Yy(e,t,n,r,a,i){const o=n in r;if(e.issues.length){if(a&&i&&!o)return;t.issues.push(...jh(n,e.issues))}if(!o&&!a){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}function P6(e){var r,a,i,o;const t=Object.keys(e.shape);for(const l of t)if(!((o=(i=(a=(r=e.shape)==null?void 0:r[l])==null?void 0:a._zod)==null?void 0:i.traits)!=null&&o.has("$ZodType")))throw new Error(`Invalid element at key "${l}": expected a Zod schema`);const n=hZ(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function R6(e,t,n,r,a,i){const o=[],l=a.keySet,c=a.catchall._zod,u=c.def.type,d=c.optin==="optional",h=c.optout==="optional";for(const f in t){if(f==="__proto__"||l.has(f))continue;if(u==="never"){o.push(f);continue}const m=c.run({value:t[f],issues:[]},r);m instanceof Promise?e.push(m.then(x=>Yy(x,n,f,t,d,h))):Yy(m,n,f,t,d,h)}return o.length&&n.issues.push({code:"unrecognized_keys",keys:o,input:t,inst:i}),e.length?Promise.all(e).then(()=>n):n}const JX=Le("$ZodObject",(e,t)=>{ar.init(e,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!(n!=null&&n.get)){const l=t.shape;Object.defineProperty(t,"shape",{get:()=>{const c={...l};return Object.defineProperty(t,"shape",{value:c}),c}})}const r=Yv(()=>P6(t));ln(e._zod,"propValues",()=>{const l=t.shape,c={};for(const u in l){const d=l[u]._zod;if(d.values){c[u]??(c[u]=new Set);for(const h of d.values)c[u].add(h)}}return c});const a=lp,i=t.catchall;let o;e._zod.parse=(l,c)=>{o??(o=r.value);const u=l.value;if(!a(u))return l.issues.push({expected:"object",code:"invalid_type",input:u,inst:e}),l;l.value={};const d=[],h=o.shape;for(const f of o.keys){const m=h[f],x=m._zod.optin==="optional",g=m._zod.optout==="optional",y=m._zod.run({value:u[f],issues:[]},c);y instanceof Promise?d.push(y.then(b=>Yy(b,l,f,u,x,g))):Yy(y,l,f,u,x,g)}return i?R6(d,u,l,c,r.value,e):d.length?Promise.all(d).then(()=>l):l}}),QX=Le("$ZodObjectJIT",(e,t)=>{JX.init(e,t);const n=e._zod.parse,r=Yv(()=>P6(t)),a=f=>{var w,_;const m=new bX(["shape","payload","ctx"]),x=r.value,g=k=>{const j=wT(k);return`shape[${j}]._zod.run({ value: input[${j}], issues: [] }, ctx)`};m.write("const input = payload.value;");const y=Object.create(null);let b=0;for(const k of x.keys)y[k]=`key_${b++}`;m.write("const newResult = {};");for(const k of x.keys){const j=y[k],N=wT(k),E=f[k],A=((w=E==null?void 0:E._zod)==null?void 0:w.optin)==="optional",C=((_=E==null?void 0:E._zod)==null?void 0:_.optout)==="optional";m.write(`const ${j} = ${g(k)};`),A&&C?m.write(` 5 if (${j}.issues.length) { 6 if (${N} in input) { 7 payload.issues = payload.issues.concat(${j}.issues.map(iss => ({ 8 ...iss, 9 path: iss.path ? [${N}, ...iss.path] : [${N}] 10 }))); 11 } 12 } 13 14 if (${j}.value === undefined) { 15 if (${N} in input) { 16 newResult[${N}] = undefined; 17 } 18 } else { 19 newResult[${N}] = ${j}.value; 20 } 21 22 `):A?m.write(` 23 if (${j}.issues.length) { 24 payload.issues = payload.issues.concat(${j}.issues.map(iss => ({ 25 ...iss, 26 path: iss.path ? [${N}, ...iss.path] : [${N}] 27 }))); 28 } 29 30 if (${j}.value === undefined) { 31 if (${N} in input) { 32 newResult[${N}] = undefined; 33 } 34 } else { 35 newResult[${N}] = ${j}.value; 36 } 37 38 `):m.write(` 39 const ${j}_present = ${N} in input; 40 if (${j}.issues.length) { 41 payload.issues = payload.issues.concat(${j}.issues.map(iss => ({ 42 ...iss, 43 path: iss.path ? [${N}, ...iss.path] : [${N}] 44 }))); 45 } 46 if (!${j}_present && !${j}.issues.length) { 47 payload.issues.push({ 48 code: "invalid_type", 49 expected: "nonoptional", 50 input: undefined, 51 path: [${N}] 52 }); 53 } 54 55 if (${j}_present) { 56 if (${j}.value === undefined) { 57 newResult[${N}] = undefined; 58 } else { 59 newResult[${N}] = ${j}.value; 60 } 61 } 62 63 `)}m.write("payload.value = newResult;"),m.write("return payload;");const v=m.compile();return(k,j)=>v(f,k,j)};let i;const o=lp,l=!r6.jitless,u=l&&uZ.value,d=t.catchall;let h;e._zod.parse=(f,m)=>{h??(h=r.value);const x=f.value;return o(x)?l&&u&&(m==null?void 0:m.async)===!1&&m.jitless!==!0?(i||(i=a(t.shape)),f=i(f,m),d?R6([],x,f,m,h,e):f):n(f,m):(f.issues.push({expected:"object",code:"invalid_type",input:x,inst:e}),f)}});function jT(e,t,n,r){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const a=e.filter(i=>!kh(i));return a.length===1?(t.value=a[0].value,a[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(i=>i.issues.map(o=>sc(o,r,rc())))}),t)}const D6=Le("$ZodUnion",(e,t)=>{ar.init(e,t),ln(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ln(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ln(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),ln(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(a=>a._zod.pattern);return new RegExp(`^(${r.map(a=>S2(a.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,a)=>{if(n)return n(r,a);let i=!1;const o=[];for(const l of t.options){const c=l._zod.run({value:r.value,issues:[]},a);if(c instanceof Promise)o.push(c),i=!0;else{if(c.issues.length===0)return c;o.push(c)}}return i?Promise.all(o).then(l=>jT(l,r,e,a)):jT(o,r,e,a)}}),eJ=Le("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,D6.init(e,t);const n=e._zod.parse;ln(e._zod,"propValues",()=>{const a={};for(const i of t.options){const o=i._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(i)}"`);for(const[l,c]of Object.entries(o)){a[l]||(a[l]=new Set);for(const u of c)a[l].add(u)}}return a});const r=Yv(()=>{var o;const a=t.options,i=new Map;for(const l of a){const c=(o=l._zod.propValues)==null?void 0:o[t.discriminator];if(!c||c.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(l)}"`);for(const u of c){if(i.has(u))throw new Error(`Duplicate discriminator value "${String(u)}"`);i.set(u,l)}}return i});e._zod.parse=(a,i)=>{const o=a.value;if(!lp(o))return a.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),a;const l=r.value.get(o==null?void 0:o[t.discriminator]);return l?l._zod.run(a,i):t.unionFallback||i.direction==="backward"?n(a,i):(a.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(r.value.keys()),input:o,path:[t.discriminator],inst:e}),a)}}),tJ=Le("$ZodIntersection",(e,t)=>{ar.init(e,t),e._zod.parse=(n,r)=>{const a=n.value,i=t.left._zod.run({value:a,issues:[]},r),o=t.right._zod.run({value:a,issues:[]},r);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([c,u])=>NT(n,c,u)):NT(n,i,o)}});function tN(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(zh(e)&&zh(t)){const n=Object.keys(t),r=Object.keys(e).filter(i=>n.indexOf(i)!==-1),a={...e,...t};for(const i of r){const o=tN(e[i],t[i]);if(!o.valid)return{valid:!1,mergeErrorPath:[i,...o.mergeErrorPath]};a[i]=o.data}return{valid:!0,data:a}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const a=e[r],i=t[r],o=tN(a,i);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function NT(e,t,n){const r=new Map;let a;for(const l of t.issues)if(l.code==="unrecognized_keys"){a??(a=l);for(const c of l.keys)r.has(c)||r.set(c,{}),r.get(c).l=!0}else e.issues.push(l);for(const l of n.issues)if(l.code==="unrecognized_keys")for(const c of l.keys)r.has(c)||r.set(c,{}),r.get(c).r=!0;else e.issues.push(l);const i=[...r].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(i.length&&a&&e.issues.push({...a,keys:i}),kh(e))return e;const o=tN(t.value,n.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const nJ=Le("$ZodRecord",(e,t)=>{ar.init(e,t),e._zod.parse=(n,r)=>{const a=n.value;if(!zh(a))return n.issues.push({expected:"record",code:"invalid_type",input:a,inst:e}),n;const i=[],o=t.keyType._zod.values;if(o){n.value={};const l=new Set;for(const u of o)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){l.add(typeof u=="number"?u.toString():u);const d=t.keyType._zod.run({value:u,issues:[]},r);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(d.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:d.issues.map(m=>sc(m,r,rc())),input:u,path:[u],inst:e});continue}const h=d.value,f=t.valueType._zod.run({value:a[u],issues:[]},r);f instanceof Promise?i.push(f.then(m=>{m.issues.length&&n.issues.push(...jh(u,m.issues)),n.value[h]=m.value})):(f.issues.length&&n.issues.push(...jh(u,f.issues)),n.value[h]=f.value)}let c;for(const u in a)l.has(u)||(c=c??[],c.push(u));c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:a,inst:e,keys:c})}else{n.value={};for(const l of Reflect.ownKeys(a)){if(l==="__proto__"||!Object.prototype.propertyIsEnumerable.call(a,l))continue;let c=t.keyType._zod.run({value:l,issues:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof l=="string"&&C6.test(l)&&c.issues.length){const h=t.keyType._zod.run({value:Number(l),issues:[]},r);if(h instanceof Promise)throw new Error("Async schemas not supported in object keys currently");h.issues.length===0&&(c=h)}if(c.issues.length){t.mode==="loose"?n.value[l]=a[l]:n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(h=>sc(h,r,rc())),input:l,path:[l],inst:e});continue}const d=t.valueType._zod.run({value:a[l],issues:[]},r);d instanceof Promise?i.push(d.then(h=>{h.issues.length&&n.issues.push(...jh(l,h.issues)),n.value[c.value]=h.value})):(d.issues.length&&n.issues.push(...jh(l,d.issues)),n.value[c.value]=d.value)}}return i.length?Promise.all(i).then(()=>n):n}}),rJ=Le("$ZodEnum",(e,t)=>{ar.init(e,t);const n=y6(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(a=>dZ.has(typeof a)).map(a=>typeof a=="string"?Wh(a):a.toString()).join("|")})$`),e._zod.parse=(a,i)=>{const o=a.value;return r.has(o)||a.issues.push({code:"invalid_value",values:n,input:o,inst:e}),a}}),sJ=Le("$ZodLiteral",(e,t)=>{if(ar.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Wh(r):r?Wh(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,a)=>{const i=r.value;return n.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}}),aJ=Le("$ZodTransform",(e,t)=>{ar.init(e,t),e._zod.optin="optional",e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new s6(e.constructor.name);const a=t.transform(n.value,n);if(r.async)return(a instanceof Promise?a:Promise.resolve(a)).then(o=>(n.value=o,n.fallback=!0,n));if(a instanceof Promise)throw new Oh;return n.value=a,n.fallback=!0,n}});function ST(e,t){return t===void 0&&(e.issues.length||e.fallback)?{issues:[],value:void 0}:e}const M6=Le("$ZodOptional",(e,t)=>{ar.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ln(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ln(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${S2(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const a=n.value,i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(o=>ST(o,a)):ST(i,a)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),iJ=Le("$ZodExactOptional",(e,t)=>{M6.init(e,t),ln(e._zod,"values",()=>t.innerType._zod.values),ln(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),oJ=Le("$ZodNullable",(e,t)=>{ar.init(e,t),ln(e._zod,"optin",()=>t.innerType._zod.optin),ln(e._zod,"optout",()=>t.innerType._zod.optout),ln(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${S2(n.source)}|null)$`):void 0}),ln(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),lJ=Le("$ZodDefault",(e,t)=>{ar.init(e,t),e._zod.optin="optional",ln(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(i=>CT(i,t)):CT(a,t)}});function CT(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const cJ=Le("$ZodPrefault",(e,t)=>{ar.init(e,t),e._zod.optin="optional",ln(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),uJ=Le("$ZodNonOptional",(e,t)=>{ar.init(e,t),ln(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(i=>ET(i,e)):ET(a,e)}});function ET(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const dJ=Le("$ZodCatch",(e,t)=>{ar.init(e,t),e._zod.optin="optional",ln(e._zod,"optout",()=>t.innerType._zod.optout),ln(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(o=>sc(o,r,rc()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=a.value,a.issues.length&&(n.value=t.catchValue({...n,error:{issues:a.issues.map(i=>sc(i,r,rc()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),hJ=Le("$ZodPipe",(e,t)=>{ar.init(e,t),ln(e._zod,"values",()=>t.in._zod.values),ln(e._zod,"optin",()=>t.in._zod.optin),ln(e._zod,"optout",()=>t.out._zod.optout),ln(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const i=t.out._zod.run(n,r);return i instanceof Promise?i.then(o=>ng(o,t.in,r)):ng(i,t.in,r)}const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(i=>ng(i,t.out,r)):ng(a,t.out,r)}});function ng(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues,fallback:e.fallback},n)}const fJ=Le("$ZodReadonly",(e,t)=>{ar.init(e,t),ln(e._zod,"propValues",()=>t.innerType._zod.propValues),ln(e._zod,"values",()=>t.innerType._zod.values),ln(e._zod,"optin",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),ln(e._zod,"optout",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optout}),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(AT):AT(a)}});function AT(e){return e.value=Object.freeze(e.value),e}const mJ=Le("$ZodLazy",(e,t)=>{ar.init(e,t),ln(e._zod,"innerType",()=>{const n=t;return n._cachedInner||(n._cachedInner=t.getter()),n._cachedInner}),ln(e._zod,"pattern",()=>{var n,r;return(r=(n=e._zod.innerType)==null?void 0:n._zod)==null?void 0:r.pattern}),ln(e._zod,"propValues",()=>{var n,r;return(r=(n=e._zod.innerType)==null?void 0:n._zod)==null?void 0:r.propValues}),ln(e._zod,"optin",()=>{var n,r;return((r=(n=e._zod.innerType)==null?void 0:n._zod)==null?void 0:r.optin)??void 0}),ln(e._zod,"optout",()=>{var n,r;return((r=(n=e._zod.innerType)==null?void 0:n._zod)==null?void 0:r.optout)??void 0}),e._zod.parse=(n,r)=>e._zod.innerType._zod.run(n,r)}),pJ=Le("$ZodCustom",(e,t)=>{ii.init(e,t),ar.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,a=t.fn(r);if(a instanceof Promise)return a.then(i=>TT(i,n,r,e));TT(a,n,r,e)}});function TT(e,t,n,r){if(!e){const a={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(a.params=r._zod.def.params),t.issues.push(cp(a))}}var OT;class xJ{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const a={...r,...this._map.get(t)};return Object.keys(a).length?a:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function gJ(){return new xJ}(OT=globalThis).__zod_globalRegistry??(OT.__zod_globalRegistry=gJ());const Rm=globalThis.__zod_globalRegistry;function yJ(e,t){return new e({type:"string",..._t(t)})}function bJ(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,..._t(t)})}function IT(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,..._t(t)})}function vJ(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,..._t(t)})}function wJ(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",..._t(t)})}function _J(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",..._t(t)})}function kJ(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",..._t(t)})}function jJ(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,..._t(t)})}function NJ(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,..._t(t)})}function SJ(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,..._t(t)})}function CJ(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,..._t(t)})}function EJ(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,..._t(t)})}function AJ(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,..._t(t)})}function TJ(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,..._t(t)})}function OJ(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,..._t(t)})}function IJ(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,..._t(t)})}function PJ(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,..._t(t)})}function RJ(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,..._t(t)})}function DJ(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,..._t(t)})}function MJ(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,..._t(t)})}function $J(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,..._t(t)})}function LJ(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,..._t(t)})}function FJ(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,..._t(t)})}function BJ(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,..._t(t)})}function UJ(e,t){return new e({type:"string",format:"date",check:"string_format",..._t(t)})}function zJ(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,..._t(t)})}function WJ(e,t){return new e({type:"string",format:"duration",check:"string_format",..._t(t)})}function KJ(e,t){return new e({type:"number",checks:[],..._t(t)})}function HJ(e,t){return new e({type:"number",coerce:!0,checks:[],..._t(t)})}function VJ(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",..._t(t)})}function qJ(e,t){return new e({type:"boolean",..._t(t)})}function GJ(e,t){return new e({type:"null",..._t(t)})}function YJ(e){return new e({type:"unknown"})}function ZJ(e,t){return new e({type:"never",..._t(t)})}function PT(e,t){return new A6({check:"less_than",..._t(t),value:e,inclusive:!1})}function Zw(e,t){return new A6({check:"less_than",..._t(t),value:e,inclusive:!0})}function RT(e,t){return new T6({check:"greater_than",..._t(t),value:e,inclusive:!1})}function Xw(e,t){return new T6({check:"greater_than",..._t(t),value:e,inclusive:!0})}function DT(e,t){return new oX({check:"multiple_of",..._t(t),value:e})}function $6(e,t){return new cX({check:"max_length",..._t(t),maximum:e})}function Zy(e,t){return new uX({check:"min_length",..._t(t),minimum:e})}function L6(e,t){return new dX({check:"length_equals",..._t(t),length:e})}function XJ(e,t){return new hX({check:"string_format",format:"regex",..._t(t),pattern:e})}function JJ(e){return new fX({check:"string_format",format:"lowercase",..._t(e)})}function QJ(e){return new mX({check:"string_format",format:"uppercase",..._t(e)})}function eQ(e,t){return new pX({check:"string_format",format:"includes",..._t(t),includes:e})}function tQ(e,t){return new xX({check:"string_format",format:"starts_with",..._t(t),prefix:e})}function nQ(e,t){return new gX({check:"string_format",format:"ends_with",..._t(t),suffix:e})}function mf(e){return new yX({check:"overwrite",tx:e})}function rQ(e){return mf(t=>t.normalize(e))}function sQ(){return mf(e=>e.trim())}function aQ(){return mf(e=>e.toLowerCase())}function iQ(){return mf(e=>e.toUpperCase())}function oQ(){return mf(e=>cZ(e))}function lQ(e,t,n){return new e({type:"array",element:t,..._t(n)})}function cQ(e,t,n){return new e({type:"custom",check:"custom",fn:t,..._t(n)})}function uQ(e,t){const n=dQ(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(cp(a,r.value,n._zod.def));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),r.issues.push(cp(i))}},e(r.value,r)),t);return n}function dQ(e,t){const n=new ii({check:"custom",..._t(t)});return n._zod.check=e,n}function F6(e){let t=(e==null?void 0:e.target)??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:(e==null?void 0:e.metadata)??Rm,target:t,unrepresentable:(e==null?void 0:e.unrepresentable)??"throw",override:(e==null?void 0:e.override)??(()=>{}),io:(e==null?void 0:e.io)??"output",counter:0,seen:new Map,cycles:(e==null?void 0:e.cycles)??"ref",reused:(e==null?void 0:e.reused)??"inline",external:(e==null?void 0:e.external)??void 0}}function Wr(e,t,n={path:[],schemaPath:[]}){var d,h;var r;const a=e._zod.def,i=t.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;const o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);const l=(h=(d=e._zod).toJSONSchema)==null?void 0:h.call(d);if(l)o.schema=l;else{const f={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,f);else{const x=o.schema,g=t.processors[a.type];if(!g)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);g(e,t,x,f)}const m=e._zod.parent;m&&(o.ref||(o.ref=m),Wr(m,t,f),t.seen.get(m).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io==="input"&&_a(e)&&(delete o.schema.examples,delete o.schema.default),t.io==="input"&&"_prefault"in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function B6(e,t){var o,l,c,u;const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const d of e.seen.entries()){const h=(o=e.metadataRegistry.get(d[0]))==null?void 0:o.id;if(h){const f=r.get(h);if(f&&f!==d[0])throw new Error(`Duplicate schema id "${h}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(h,d[0])}}const a=d=>{var g;const h=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const y=(g=e.external.registry.get(d[0]))==null?void 0:g.id,b=e.external.uri??(w=>w);if(y)return{ref:b(y)};const v=d[1].defId??d[1].schema.id??`schema${e.counter++}`;return d[1].defId=v,{defId:v,ref:`${b("__shared")}#/${h}/${v}`}}if(d[1]===n)return{ref:"#"};const m=`#/${h}/`,x=d[1].schema.id??`__schema${e.counter++}`;return{defId:x,ref:m+x}},i=d=>{if(d[1].schema.$ref)return;const h=d[1],{ref:f,defId:m}=a(d);h.def={...h.schema},m&&(h.defId=m);const x=h.schema;for(const g in x)delete x[g];x.$ref=f};if(e.cycles==="throw")for(const d of e.seen.entries()){const h=d[1];if(h.cycle)throw new Error(`Cycle detected: #/${(l=h.cycle)==null?void 0:l.join("/")}/<root> 64 65Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const d of e.seen.entries()){const h=d[1];if(t===d[0]){i(d);continue}if(e.external){const m=(c=e.external.registry.get(d[0]))==null?void 0:c.id;if(t!==d[0]&&m){i(d);continue}}if((u=e.metadataRegistry.get(d[0]))==null?void 0:u.id){i(d);continue}if(h.cycle){i(d);continue}if(h.count>1&&e.reused==="ref"){i(d);continue}}}function U6(e,t){var l,c,u,d;const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=h=>{const f=e.seen.get(h);if(f.ref===null)return;const m=f.def??f.schema,x={...m},g=f.ref;if(f.ref=null,g){r(g);const b=e.seen.get(g),v=b.schema;if(v.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(m.allOf=m.allOf??[],m.allOf.push(v)):Object.assign(m,v),Object.assign(m,x),h._zod.parent===g)for(const _ in m)_==="$ref"||_==="allOf"||_ in x||delete m[_];if(v.$ref&&b.def)for(const _ in m)_==="$ref"||_==="allOf"||_ in b.def&&JSON.stringify(m[_])===JSON.stringify(b.def[_])&&delete m[_]}const y=h._zod.parent;if(y&&y!==g){r(y);const b=e.seen.get(y);if(b!=null&&b.schema.$ref&&(m.$ref=b.schema.$ref,b.def))for(const v in m)v==="$ref"||v==="allOf"||v in b.def&&JSON.stringify(m[v])===JSON.stringify(b.def[v])&&delete m[v]}e.override({zodSchema:h,jsonSchema:m,path:f.path??[]})};for(const h of[...e.seen.entries()].reverse())r(h[0]);const a={};if(e.target==="draft-2020-12"?a.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?a.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?a.$schema="http://json-schema.org/draft-04/schema#":e.target,(l=e.external)!=null&&l.uri){const h=(c=e.external.registry.get(t))==null?void 0:c.id;if(!h)throw new Error("Schema is missing an `id` property");a.$id=e.external.uri(h)}Object.assign(a,n.def??n.schema);const i=(u=e.metadataRegistry.get(t))==null?void 0:u.id;i!==void 0&&a.id===i&&delete a.id;const o=((d=e.external)==null?void 0:d.defs)??{};for(const h of e.seen.entries()){const f=h[1];f.def&&f.defId&&(f.def.id===f.defId&&delete f.def.id,o[f.defId]=f.def)}e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?a.$defs=o:a.definitions=o);try{const h=JSON.parse(JSON.stringify(a));return Object.defineProperty(h,"~standard",{value:{...t["~standard"],jsonSchema:{input:Xy(t,"input",e.processors),output:Xy(t,"output",e.processors)}},enumerable:!1,writable:!1}),h}catch{throw new Error("Error converting schema to JSON.")}}function _a(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return _a(r.element,n);if(r.type==="set")return _a(r.valueType,n);if(r.type==="lazy")return _a(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return _a(r.innerType,n);if(r.type==="intersection")return _a(r.left,n)||_a(r.right,n);if(r.type==="record"||r.type==="map")return _a(r.keyType,n)||_a(r.valueType,n);if(r.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:_a(r.in,n)||_a(r.out,n);if(r.type==="object"){for(const a in r.shape)if(_a(r.shape[a],n))return!0;return!1}if(r.type==="union"){for(const a of r.options)if(_a(a,n))return!0;return!1}if(r.type==="tuple"){for(const a of r.items)if(_a(a,n))return!0;return!!(r.rest&&_a(r.rest,n))}return!1}const hQ=(e,t={})=>n=>{const r=F6({...n,processors:t});return Wr(e,r),B6(r,e),U6(r,e)},Xy=(e,t,n={})=>r=>{const{libraryOptions:a,target:i}=r??{},o=F6({...a??{},target:i,io:t,processors:n});return Wr(e,o),B6(o,e),U6(o,e)},fQ={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},mQ=(e,t,n,r)=>{const a=n;a.type="string";const{minimum:i,maximum:o,format:l,patterns:c,contentEncoding:u}=e._zod.bag;if(typeof i=="number"&&(a.minLength=i),typeof o=="number"&&(a.maxLength=o),l&&(a.format=fQ[l]??l,a.format===""&&delete a.format,l==="time"&&delete a.format),u&&(a.contentEncoding=u),c&&c.size>0){const d=[...c];d.length===1?a.pattern=d[0].source:d.length>1&&(a.allOf=[...d.map(h=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},pQ=(e,t,n,r)=>{const a=n,{minimum:i,maximum:o,format:l,multipleOf:c,exclusiveMaximum:u,exclusiveMinimum:d}=e._zod.bag;typeof l=="string"&&l.includes("int")?a.type="integer":a.type="number";const h=typeof d=="number"&&d>=(i??Number.NEGATIVE_INFINITY),f=typeof u=="number"&&u<=(o??Number.POSITIVE_INFINITY),m=t.target==="draft-04"||t.target==="openapi-3.0";h?m?(a.minimum=d,a.exclusiveMinimum=!0):a.exclusiveMinimum=d:typeof i=="number"&&(a.minimum=i),f?m?(a.maximum=u,a.exclusiveMaximum=!0):a.exclusiveMaximum=u:typeof o=="number"&&(a.maximum=o),typeof c=="number"&&(a.multipleOf=c)},xQ=(e,t,n,r)=>{n.type="boolean"},gQ=(e,t,n,r)=>{t.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},yQ=(e,t,n,r)=>{n.not={}},bQ=(e,t,n,r)=>{},vQ=(e,t,n,r)=>{const a=e._zod.def,i=y6(a.entries);i.every(o=>typeof o=="number")&&(n.type="number"),i.every(o=>typeof o=="string")&&(n.type="string"),n.enum=i},wQ=(e,t,n,r)=>{const a=e._zod.def,i=[];for(const o of a.values)if(o===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(o))}else i.push(o);if(i.length!==0)if(i.length===1){const o=i[0];n.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[o]:n.const=o}else i.every(o=>typeof o=="number")&&(n.type="number"),i.every(o=>typeof o=="string")&&(n.type="string"),i.every(o=>typeof o=="boolean")&&(n.type="boolean"),i.every(o=>o===null)&&(n.type="null"),n.enum=i},_Q=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},kQ=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},jQ=(e,t,n,r)=>{const a=n,i=e._zod.def,{minimum:o,maximum:l}=e._zod.bag;typeof o=="number"&&(a.minItems=o),typeof l=="number"&&(a.maxItems=l),a.type="array",a.items=Wr(i.element,t,{...r,path:[...r.path,"items"]})},NQ=(e,t,n,r)=>{var u;const a=n,i=e._zod.def;a.type="object",a.properties={};const o=i.shape;for(const d in o)a.properties[d]=Wr(o[d],t,{...r,path:[...r.path,"properties",d]});const l=new Set(Object.keys(o)),c=new Set([...l].filter(d=>{const h=i.shape[d]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));c.size>0&&(a.required=Array.from(c)),((u=i.catchall)==null?void 0:u._zod.def.type)==="never"?a.additionalProperties=!1:i.catchall?i.catchall&&(a.additionalProperties=Wr(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},SQ=(e,t,n,r)=>{const a=e._zod.def,i=a.inclusive===!1,o=a.options.map((l,c)=>Wr(l,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=o:n.anyOf=o},CQ=(e,t,n,r)=>{const a=e._zod.def,i=Wr(a.left,t,{...r,path:[...r.path,"allOf",0]}),o=Wr(a.right,t,{...r,path:[...r.path,"allOf",1]}),l=u=>"allOf"in u&&Object.keys(u).length===1,c=[...l(i)?i.allOf:[i],...l(o)?o.allOf:[o]];n.allOf=c},EQ=(e,t,n,r)=>{const a=n,i=e._zod.def;a.type="object";const o=i.keyType,l=o._zod.bag,c=l==null?void 0:l.patterns;if(i.mode==="loose"&&c&&c.size>0){const d=Wr(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});a.patternProperties={};for(const h of c)a.patternProperties[h.source]=d}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(a.propertyNames=Wr(i.keyType,t,{...r,path:[...r.path,"propertyNames"]})),a.additionalProperties=Wr(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const u=o._zod.values;if(u){const d=[...u].filter(h=>typeof h=="string"||typeof h=="number");d.length>0&&(a.required=d)}},AQ=(e,t,n,r)=>{const a=e._zod.def,i=Wr(a.innerType,t,r),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=a.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},TQ=(e,t,n,r)=>{const a=e._zod.def;Wr(a.innerType,t,r);const i=t.seen.get(e);i.ref=a.innerType},OQ=(e,t,n,r)=>{const a=e._zod.def;Wr(a.innerType,t,r);const i=t.seen.get(e);i.ref=a.innerType,n.default=JSON.parse(JSON.stringify(a.defaultValue))},IQ=(e,t,n,r)=>{const a=e._zod.def;Wr(a.innerType,t,r);const i=t.seen.get(e);i.ref=a.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(a.defaultValue)))},PQ=(e,t,n,r)=>{const a=e._zod.def;Wr(a.innerType,t,r);const i=t.seen.get(e);i.ref=a.innerType;let o;try{o=a.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o},RQ=(e,t,n,r)=>{const a=e._zod.def,i=a.in._zod.traits.has("$ZodTransform"),o=t.io==="input"?i?a.out:a.in:a.out;Wr(o,t,r);const l=t.seen.get(e);l.ref=o},DQ=(e,t,n,r)=>{const a=e._zod.def;Wr(a.innerType,t,r);const i=t.seen.get(e);i.ref=a.innerType,n.readOnly=!0},z6=(e,t,n,r)=>{const a=e._zod.def;Wr(a.innerType,t,r);const i=t.seen.get(e);i.ref=a.innerType},MQ=(e,t,n,r)=>{const a=e._zod.innerType;Wr(a,t,r);const i=t.seen.get(e);i.ref=a},$Q=Le("ZodISODateTime",(e,t)=>{IX.init(e,t),Sr.init(e,t)});function LQ(e){return BJ($Q,e)}const FQ=Le("ZodISODate",(e,t)=>
vendor: 4,794 bytes, line 65
65{PX.init(e,t),Sr.init(e,t)});function BQ(e){return UJ(FQ,e)}const UQ=Le("ZodISOTime",(e,t)=>{RX.init(e,t),Sr.init(e,t)});function zQ(e){return zJ(UQ,e)}const WQ=Le("ZodISODuration",(e,t)=>{DX.init(e,t),Sr.init(e,t)});function KQ(e){return WJ(WQ,e)}const HQ=(e,t)=>{_6.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>kZ(e,n)},flatten:{value:n=>_Z(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,eN,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,eN,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ji=Le("ZodError",HQ,{Parent:Error}),VQ=E2(Ji),qQ=A2(Ji),GQ=Zv(Ji),YQ=Xv(Ji),ZQ=SZ(Ji),XQ=CZ(Ji),JQ=EZ(Ji),QQ=AZ(Ji),eee=TZ(Ji),tee=OZ(Ji),nee=IZ(Ji),ree=PZ(Ji),MT=new WeakMap;function ex(e,t,n){const r=Object.getPrototypeOf(e);let a=MT.get(r);if(a||(a=new Set,MT.set(r,a)),!a.has(t)){a.add(t);for(const i in n){const o=n[i];Object.defineProperty(r,i,{configurable:!0,enumerable:!1,get(){const l=o.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:l}),l},set(l){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:l})}})}}}const ir=Le("ZodType",(e,t)=>(ar.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Xy(e,"input"),output:Xy(e,"output")}}),e.toJSONSchema=hQ(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.parse=(n,r)=>VQ(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>GQ(e,n,r),e.parseAsync=async(n,r)=>qQ(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>YQ(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>ZQ(e,n,r),e.decode=(n,r)=>XQ(e,n,r),e.encodeAsync=async(n,r)=>JQ(e,n,r),e.decodeAsync=async(n,r)=>QQ(e,n,r),e.safeEncode=(n,r)=>eee(e,n,r),e.safeDecode=(n,r)=>tee(e,n,r),e.safeEncodeAsync=async(n,r)=>nee(e,n,r),e.safeDecodeAsync=async(n,r)=>ree(e,n,r),ex(e,"ZodType",{check(...n){const r=this.def;return this.clone(fu(r,{checks:[...r.checks??[],...n.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return mu(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(Qee(n,r))},superRefine(n,r){return this.check(ete(n,r))},overwrite(n){return this.check(mf(n))},optional(){return BT(this)},exactOptional(){return Lee(this)},nullable(){return UT(this)},nullish(){return BT(UT(this))},nonoptional(n){return Kee(this,n)},array(){return Nr(this)},or(n){return pf([this,n])},and(n){return Pee(this,n)},transform(n){return zT(this,Mee(n))},default(n){return Uee(this,n)},prefault(n){return Wee(this,n)},catch(n){return Vee(this,n)},pipe(n){return zT(this,n)},readonly(){return Yee(this)},describe(n){const r=this.clone();return Rm.add(r,{description:n}),r},meta(...n){if(n.length===0)return Rm.get(this);const r=this.clone();return Rm.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(e,"description",{get(){var n;return(n=Rm.get(e))==null?void 0:n.description},configurable:!0}),e)),W6=Le("_ZodString",(e,t)=>{T2.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(r,a,i)=>mQ(e,r,a);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,ex(e,"_ZodString",{regex(...r){return this.check(XJ(...r))},includes(...r){return this.check(eQ(...r))},startsWith(...r){return this.check(tQ(...r))},endsWith(...r){return this.check(nQ(...r))},min(...r){return this.check(Zy(...r))},max(...r){return this.check($6(...r))},length(...r){return this.check(L6(...r))},nonempty(...r){return this.check(Zy(1,...r))},lowercase(r){return this.check(JJ(r))},uppercase(r){return this.check(QJ(r))},trim(){return this.check(sQ())},normalize(...r){return this.check(rQ(...r))},toLowerCase(){return this.check(aQ())},toUpperCase(){return this.check(iQ())},slugify(){return this.check(oQ())}})}),see=Le("ZodString",(e,t)=>{T2.init(e,t),W6.init(e,t),e.email=n=>e.check(bJ(aee,n)),e.url=n=>e.check(jJ(iee,n)),e.jwt=n=>e.check(FJ(wee,n)),e.emoji=n=>e.check(NJ(oee,n)),e.guid=n=>e.check(IT($T,n)),e.uuid=n=>e.check(vJ(rg,n)),e.uuidv4=n=>e.check(wJ(rg,n)),e.uuidv6=n=>e.check(_J(rg,n)),e.uuidv7=n=>e.check(kJ(rg,n)),e.nanoid=n=>e.check(SJ(lee,n)),e.guid=n=>e.check(IT($T,n)),e.cuid=n=>e.check(CJ(cee,n)),e.cuid2=n=>e.check(EJ(uee,n)),e.ulid=n=>e.check(AJ(dee,n)),e.base64=n=>e.check(MJ(yee,n)),e.base64url=n=>e.check($J(bee,n)),e.xid=n=>e.check(TJ(hee,n)),e.ksuid=n=>e.check(OJ(fee,n)),e.ipv4=n=>e.check(IJ(mee,n)),e.ipv6=n=>e.check(PJ(pee,n)),e.cidrv4=n=>e.check(RJ(xee,n)),e.cidrv6=n=>e.check(DJ(gee,n)),e.e164=n=>e.check(LJ(vee,n)),e.datetime=n=>e.check(LQ(n)),e.date=n=>e.check(BQ(n)),e.time=n=>e.check(zQ(n)),e.duration=n=>
65e.check(KQ(n))});function Be(e){return yJ(see,e)}const Sr=Le("ZodStringFormat",(e,t)=>{hr.init(e,t),W6.init(e,t)}),aee=Le("ZodEmail",(e,t)=>{kX.init(e,t),Sr.init(e,t)}),$T=Le("ZodGUID",(e,t)=>{wX.init(e,t),Sr.init(e,t)}),rg=Le("ZodUUID",(e,t)=>{_X.init(e,t),Sr.init(e,t)}),iee=Le("ZodURL",(e,t)=>{jX.init(e,t),Sr.init(e,t)}),oee=Le("ZodEmoji",(e,t)=>{NX.init(e,t),Sr.init(e,t)}),lee=Le("ZodNanoID",(e,t)=>{SX.init(e,t),Sr.init(e,t)}),cee=Le("ZodCUID",(e,t)=>{CX.init(e,t),Sr.init(e,t)}),uee=Le("ZodCUID2",(e,t)=>{EX.init(e,t),Sr.init(e,t)}),dee=Le("ZodULID",(e,t)=>{AX.init(e,t),Sr.init(e,t)}),hee=Le("ZodXID",(e,t)=>{TX.init(e,t),Sr.init(e,t)}),fee=Le("ZodKSUID",(e,t)=>{OX.init(e,t),Sr.init(e,t)}),mee=Le("ZodIPv4",(e,t)=>{MX.init(e,t),Sr.init(e,t)}),pee=Le("ZodIPv6",(e,t)=>{$X.init(e,t),Sr.init(e,t)}),xee=Le("ZodCIDRv4",(e,t)=>{LX.init(e,t),Sr.init(e,t)}),gee=Le("ZodCIDRv6",(e,t)=>{FX.init(e,t),Sr.init(e,t)}),yee=Le("ZodBase64",(e,t)=>{BX.init(e,t),Sr.init(e,t)}),bee=Le("ZodBase64URL",(e,t)=>{zX.init(e,t),Sr.init(e,t)}),vee=Le("ZodE164",(e,t)=>{WX.init(e,t),Sr.init(e,t)}),wee=Le("ZodJWT",(e,t)=>{HX.init(e,t),Sr.init(e,t)}),O2=Le("ZodNumber",(e,t)=>{I6.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(r,a,i)=>pQ(e,r,a),ex(e,"ZodNumber",{gt(r,a){return this.check(RT(r,a))},gte(r,a){return this.check(Xw(r,a))},min(r,a){return this.check(Xw(r,a))},lt(r,a){return this.check(PT(r,a))},lte(r,a){return this.check(Zw(r,a))},max(r,a){return this.check(Zw(r,a))},int(r){return this.check(LT(r))},safe(r){return this.check(LT(r))},positive(r){return this.check(RT(0,r))},nonnegative(r){return this.check(Xw(0,r))},negative(r){return this.check(PT(0,r))},nonpositive(r){return this.check(Zw(0,r))},multipleOf(r,a){return this.check(DT(r,a))},step(r,a){return this.check(DT(r,a))},finite(){return this}});const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Ur(e){return KJ(O2,e)}const _ee=Le("ZodNumberFormat",(e,t)=>{VX.init(e,t),O2.init(e,t)});function LT(e){return VJ(_ee,e)}const kee=Le("ZodBoolean",(e,t)=>{qX.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>xQ(e,n,r)});function ac(e){return qJ(kee,e)}const jee=Le("ZodNull",(e,t)=>{GX.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>gQ(e,n,r)});function Nee(e){return GJ(jee,e)}const See=Le("ZodUnknown",(e,t)=>{YX.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>bQ()});function nN(){return YJ(See)}const Cee=Le("ZodNever",(e,t)=>{ZX.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>yQ(e,n,r)});function Eee(e){return ZJ(Cee,e)}const Aee=Le("ZodArray",(e,t)=>{XX.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>jQ(e,n,r,a),e.element=t.element,ex(e,"ZodArray",{min(n,r){return this.check(Zy(n,r))},nonempty(n){return this.check(Zy(1,n))},max(n,r){return this.check($6(n,r))},length(n,r){return this.check(L6(n,r))},unwrap(){return this.element}})});function Nr(e,t){return lQ(Aee,e,t)}const Tee=Le("ZodObject",(e,t)=>{QX.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>NQ(e,n,r,a),ln(e,"shape",()=>t.shape),ex(e,"ZodObject",{keyof(){return Ia(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:nN()})},loose(){return this.clone({...this._zod.def,catchall:nN()})},strict(){return this.clone({...this._zod.def,catchall:Eee()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return xZ(this,n)},safeExtend(n){return gZ(this,n)},merge(n){return yZ(this,n)},pick(n){return mZ(this,n)},omit(n){return pZ(this,n)},partial(...n){return bZ(V6,this,n[0])},required(...n){return vZ(q6,this,n[0])}})});function Dt(e,t){const n={type:"object",shape:e??{},..._t(t)};return new Tee(n)}const K6=Le("ZodUnion",(e,t)=>{D6.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>SQ(e,n,r,a),e.options=t.options});function pf(e,t){return new K6({type:"union",options:e,..._t(t)})}const Oee=Le("ZodDiscriminatedUnion",(e,t)=>{K6.init(e,t),eJ.init(e,t)});function H6(e,t,n){return new Oee({type:"union",options:t,discriminator:e,..._t(n)})}const Iee=Le("ZodIntersection",(e,t)=>{tJ.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>CQ(e,n,r,a)});
65function Pee(e,t){return new Iee({type:"intersection",left:e,right:t})}const FT=Le("ZodRecord",(e,t)=>{nJ.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>EQ(e,n,r,a),e.keyType=t.keyType,e.valueType=t.valueType});function I2(e,t,n){return!t||!t._zod?new FT({type:"record",keyType:Be(),valueType:e,..._t(t)}):new FT({type:"record",keyType:e,valueType:t,..._t(n)})}const rN=Le("ZodEnum",(e,t)=>{rJ.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(r,a,i)=>vQ(e,r,a),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,a)=>{const i={};for(const o of r)if(n.has(o))i[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new rN({...t,checks:[],..._t(a),entries:i})},e.exclude=(r,a)=>{const i={...t.entries};for(const o of r)if(n.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new rN({...t,checks:[],..._t(a),entries:i})}});function Ia(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new rN({type:"enum",entries:n,..._t(t)})}const Ree=Le("ZodLiteral",(e,t)=>{sJ.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>wQ(e,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if
vendor: 7,887 bytes, lines 65-125
65(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function kn(e,t){return new Ree({type:"literal",values:Array.isArray(e)?e:[e],..._t(t)})}const Dee=Le("ZodTransform",(e,t)=>{aJ.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>kQ(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new s6(e.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(cp(i,n.value,t));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),n.issues.push(cp(o))}};const a=t.transform(n.value,n);return a instanceof Promise?a.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=a,n.fallback=!0,n)}});function Mee(e){return new Dee({type:"transform",transform:e})}const V6=Le("ZodOptional",(e,t)=>{M6.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>z6(e,n,r,a),e.unwrap=()=>e._zod.def.innerType});function BT(e){return new V6({type:"optional",innerType:e})}const $ee=Le("ZodExactOptional",(e,t)=>{iJ.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>z6(e,n,r,a),e.unwrap=()=>e._zod.def.innerType});function Lee(e){return new $ee({type:"optional",innerType:e})}const Fee=Le("ZodNullable",(e,t)=>{oJ.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>AQ(e,n,r,a),e.unwrap=()=>e._zod.def.innerType});function UT(e){return new Fee({type:"nullable",innerType:e})}const Bee=Le("ZodDefault",(e,t)=>{lJ.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>OQ(e,n,r,a),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Uee(e,t){return new Bee({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():v6(t)}})}const zee=Le("ZodPrefault",(e,t)=>{cJ.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>IQ(e,n,r,a),e.unwrap=()=>e._zod.def.innerType});function Wee(e,t){return new zee({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():v6(t)}})}const q6=Le("ZodNonOptional",(e,t)=>{uJ.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>TQ(e,n,r,a),e.unwrap=()=>e._zod.def.innerType});function Kee(e,t){return new q6({type:"nonoptional",innerType:e,..._t(t)})}const Hee=Le("ZodCatch",(e,t)=>{dJ.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>PQ(e,n,r,a),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Vee(e,t){return new Hee({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const qee=Le("ZodPipe",(e,t)=>{hJ.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>RQ(e,n,r,a),e.in=t.in,e.out=t.out});function zT(e,t){return new qee({type:"pipe",in:e,out:t})}const Gee=Le("ZodReadonly",(e,t)=>{fJ.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>DQ(e,n,r,a),e.unwrap=()=>e._zod.def.innerType});function Yee(e){return new Gee({type:"readonly",innerType:e})}const Zee=Le("ZodLazy",(e,t)=>{mJ.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>MQ(e,n,r,a),e.unwrap=()=>e._zod.def.getter()});function Xee(e){return new Zee({type:"lazy",getter:e})}const Jee=Le("ZodCustom",(e,t)=>{pJ.init(e,t),ir.init(e,t),e._zod.processJSONSchema=(n,r,a)=>_Q(e,n)});function Qee(e,t={}){return cQ(Jee,e,t)}function ete(e,t){return uQ(e,t)}function Jy(e){return HJ(O2,e)}/** 66 * @license lucide-react v0.577.0 - ISC 67 * 68 * This source code is licensed under the ISC license. 69 * See the LICENSE file in the root directory of this source tree. 70 */const tte=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],Kh=Pe("activity",tte);/** 71 * @license lucide-react v0.577.0 - ISC 72 * 73 * This source code is licensed under the ISC license. 74 * See the LICENSE file in the root directory of this source tree. 75 */const nte=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]],G6=Pe("archive-restore",nte);/** 76 * @license lucide-react v0.577.0 - ISC 77 * 78 * This source code is licensed under the ISC license. 79 * See the LICENSE file in the root directory of this source tree. 80 */const rte=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],Y6=Pe("archive",rte);/** 81 * @license lucide-react v0.577.0 - ISC 82 * 83 * This source code is licensed under the ISC license. 84 * See the LICENSE file in the root directory of this source tree. 85 */const ste=[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]],WT=Pe("arrow-left-right",ste);/** 86 * @license lucide-react v0.577.0 - ISC 87 * 88 * This source code is licensed under the ISC license. 89 * See the LICENSE file in the root directory of this source tree. 90 */const ate=[["path",{d:"m16 3 4 4-4 4",key:"1x1c3m"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"m8 21-4-4 4-4",key:"h9nckh"}],["path",{d:"M4 17h16",key:"g4d7ey"}]],ite=Pe("arrow-right-left",ate);/** 91 * @license lucide-react v0.577.0 - ISC 92 * 93 * This source code is licensed under the ISC license. 94 * See the LICENSE file in the root directory of this source tree. 95 */const ote=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],lte=Pe("arrow-up-right",ote);/** 96 * @license lucide-react v0.577.0 - ISC 97 * 98 * This source code is licensed under the ISC license. 99 * See the LICENSE file in the root directory of this source tree. 100 */const cte=[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],cd=Pe("badge-check",cte);/** 101 * @license lucide-react v0.577.0 - ISC 102 * 103 * This source code is licensed under the ISC license. 104 * See the LICENSE file in the root directory of this source tree. 105 */const ute=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M4.929 4.929 19.07 19.071",key:"196cmz"}]],dte=Pe("ban",ute);/** 106 * @license lucide-react v0.577.0 - ISC 107 * 108 * This source code is licensed under the ISC license. 109 * See the LICENSE file in the root directory of this source tree. 110 */const hte=[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M6 12h.01M18 12h.01",key:"113zkx"}]],P2=Pe("banknote",hte);/** 111 * @license lucide-react v0.577.0 - ISC 112 * 113 * This source code is licensed under the ISC license. 114 * See the LICENSE file in the root directory of this source tree. 115 */const fte=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],mte=Pe("bell-off",fte);/** 116 * @license lucide-react v0.577.0 - ISC 117 * 118 * This source code is licensed under the ISC license. 119 * See the LICENSE file in the root directory of this source tree. 120 */const pte=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]],Z6=Pe("bell",pte);/** 121 * @license lucide-react v0.577.0 - ISC 122 * 123 * This source code is licensed under the ISC license. 124 * See the LICENSE file in the root directory of this source tree. 125 */const xte=[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M8 11h8",key:"vwpz6n"}],["path",{d:"M8 7h6",key:"1f0q6e"}]],Qv=Pe("book-text",xte);
125/** 126 * @license lucide-react v0.577.0 - ISC 127 * 128 * This source code is licensed under the ISC license. 129 * See the LICENSE file in the root directory of this source tree. 130 */const gte=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z",key:"oz39mx"}],["path",{d:"m9 10 2 2 4-4",key:"1gnqz4"}]],yte=Pe("bookmark-check",gte);/** 131 * @license lucide-react v0.577.0 - ISC 132 * 133 * This source code is licensed under the ISC license. 134 * See the LICENSE file in the root directory of this source tree. 135 */const bte=[["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M15 10H9",key:"o6yqo3"}],["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z",key:"oz39mx"}]],vte=Pe("bookmark-plus",bte);/** 136 * @license lucide-react v0.577.0 - ISC 137 * 138 * This source code is licensed under the ISC license. 139 * See the LICENSE file in the root directory of this source tree. 140 */const wte=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z",key:"oz39mx"}]],e0=Pe("bookmark",wte);/** 141 * @license lucide-react v0.577.0 - ISC 142 * 143 * This source code is licensed under the ISC license. 144 * See the LICENSE file in the root directory of this source tree. 145 */const _te=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],X6=Pe("bot",_te);/** 146 * @license lucide-react v0.577.0 - ISC 147 * 148 * This source code is licensed under the ISC license. 149 * See the LICENSE file in the root directory of this source tree. 150 */const kte=[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]],xf=Pe("briefcase",kte);/** 151 * @license lucide-react v0.577.0 - ISC 152 * 153 * This source code is licensed under the ISC license. 154 * See the LICENSE file in the root directory of this source tree. 155 */const jte=[["path",{d:"M10 12h4",key:"a56b0p"}],["path",{d:"M10 8h4",key:"1sr2af"}],["path",{d:"M14 21v-3a2 2 0 0 0-4 0v3",key:"1rgiei"}],["path",{d:"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",key:"secmi2"}],["path",{d:"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16",key:"16ra0t"}]],R2=Pe("building-2",jte);/** 156 * @license lucide-react v0.577.0 - ISC 157 * 158 * This source code is licensed under the ISC license. 159 * See the LICENSE file in the root directory of this source tree. 160 */const Nte=[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]],KT=Pe("calculator",Nte);/** 161 * @license lucide-react v0.577.0 - ISC 162 * 163 * This source code is licensed under the ISC license. 164 * See the LICENSE file in the root directory of this source tree. 165 */const Ste=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]],yd=Pe("calendar-days",Ste);/** 166 * @license lucide-react v0.577.0 - ISC 167 * 168 * This source code is licensed under the ISC license. 169 * See the LICENSE file in the root directory of this source tree. 170 */const Cte=[["path",{d:"M14.564 14.558a3 3 0 1 1-4.122-4.121",key:"1rnrzw"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M20 20H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 .819-.175",key:"1x3arw"}],["path",{d:"M9.695 4.024A2 2 0 0 1 10.004 4h3.993a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v7.344",key:"1i84u0"}]],Ete=Pe("camera-off",Cte);/** 171 * @license lucide-react v0.577.0 - ISC 172 * 173 * This source code is licensed under the ISC license. 174 * See the LICENSE file in the root directory of this source tree. 175 */const Ate=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z",key:"18u6gg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]],up=Pe("camera",Ate);/** 176 * @license lucide-react v0.577.0 - ISC 177 * 178 * This source code is licensed under the ISC license. 179 * See the LICENSE file in the root directory of this source tree. 180 */const Tte=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Ote=Pe("check-check",Tte);/** 181 * @license lucide-react v0.577.0 - ISC 182 * 183 * This source code is licensed under the ISC license. 184 * See the LICENSE file in the root directory of this source tree. 185 */const Ite=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Pn=Pe("chevron-down",Ite);
185/** 186 * @license lucide-react v0.577.0 - ISC 187 * 188 * This source code is licensed under the ISC license. 189 * See the LICENSE file in the root directory of this source tree. 190 */const Pte=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],ud=Pe("chevron-left",Pte);/** 191 * @license lucide-react v0.577.0 - ISC 192 * 193 * This source code is licensed under the ISC license. 194 * See the LICENSE file in the root directory of this source tree. 195 */const Rte=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],fr=Pe("chevron-right",Rte);/** 196 * @license lucide-react v0.577.0 - ISC 197 * 198 * This source code is licensed under the ISC license. 199 * See the LICENSE file in the root directory of this source tree. 200 */const Dte=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],t0=Pe("chevron-up",Dte);/** 201 * @license lucide-react v0.577.0 - ISC 202 * 203 * This source code is licensed under the ISC license. 204 * See the LICENSE file in the root directory of this source tree. 205 */const Mte=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],J6=Pe("chevrons-up-down",Mte);/** 206 * @license lucide-react v0.577.0 - ISC 207 * 208 * This source code is licensed under the ISC license. 209 * See the LICENSE file in the root directory of this source tree. 210 */const $te=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],yt=Pe("circle-alert",$te);/** 211 * @license lucide-react v0.577.0 - ISC 212 * 213 * This source code is licensed under the ISC license. 214 * See the LICENSE file in the root directory of this source tree. 215 */const Lte=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"m8 12 4 4 4-4",key:"k98ssh"}]],Fte=Pe("circle-arrow-down",Lte);/** 216 * @license lucide-react v0.577.0 - ISC 217 * 218 * This source code is licensed under the ISC license. 219 * See the LICENSE file in the root directory of this source tree. 220 */const Bte=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}]],Ute=Pe("circle-arrow-up",Bte);/** 221 * @license lucide-react v0.577.0 - ISC 222 * 223 * This source code is licensed under the ISC license. 224 * See the LICENSE file in the root directory of this source tree. 225 */const zte=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]],Wte=Pe("circle-plus",zte);/** 226 * @license lucide-react v0.577.0 - ISC 227 * 228 * This source code is licensed under the ISC license. 229 * See the LICENSE file in the root directory of this source tree. 230 */const Kte=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],Hte=Pe("circle-question-mark",Kte);/** 231 * @license lucide-react v0.577.0 - ISC 232 * 233 * This source code is licensed under the ISC license. 234 * See the LICENSE file in the root directory of this source tree. 235 */const Vte=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],qte=Pe("circle-stop",Vte);/** 236 * @license lucide-react v0.577.0 - ISC 237 * 238 * This source code is licensed under the ISC license. 239 * See the LICENSE file in the root directory of this source tree. 240 */const Gte=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],Q6=Pe("circle-x",Gte);/** 241 * @license lucide-react v0.577.0 - ISC 242 * 243 * This source code is licensed under the ISC license. 244 * See the LICENSE file in the root directory of this source tree. 245 */const Yte=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],D2=Pe("circle",Yte);/** 246 * @license lucide-react v0.577.0 - ISC 247 * 248 * This source code is licensed under the ISC license. 249 * See the LICENSE file in the root directory of this source tree. 250 */const Zte=[["path",{d:"m12.296 3.464 3.02 3.956",key:"qash78"}],["path",{d:"M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3z",key:"1h7j8b"}],["path",{d:"M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"4lm6w1"}],["path",{d:"m6.18 5.276 3.1 3.899",key:"zjj9t3"}]],M2=Pe("clapperboard",Zte);/** 251 * @license lucide-react v0.577.0 - ISC 252 * 253 * This source code is licensed under the ISC license. 254 * See the LICENSE file in the root directory of this source tree.
255 */const Xte=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]],n0=Pe("clipboard-list",Xte);/** 256 * @license lucide-react v0.577.0 - ISC 257 * 258 * This source code is licensed under the ISC license. 259 * See the LICENSE file in the root directory of this source tree. 260 */const Jte=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],pu=Pe("clock",Jte);/** 261 * @license lucide-react v0.577.0 - ISC 262 * 263 * This source code is licensed under the ISC license. 264 * See the LICENSE file in the root directory of this source tree. 265 */const Qte=[["path",{d:"M13.744 17.736a6 6 0 1 1-7.48-7.48",key:"bq4yh3"}],["path",{d:"M15 6h1v4",key:"11y1tn"}],["path",{d:"m6.134 14.768.866-.5 2 3.464",key:"17snzx"}],["circle",{cx:"16",cy:"8",r:"6",key:"14bfc9"}]],eF=Pe("coins",Qte);/** 266 * @license lucide-react v0.577.0 - ISC 267 * 268 * This source code is licensed under the ISC license. 269 * See the LICENSE file in the root directory of this source tree. 270 */const ene=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]],$2=Pe("columns-3",ene);/** 271 * @license lucide-react v0.577.0 - ISC 272 * 273 * This source code is licensed under the ISC license. 274 * See the LICENSE file in the root directory of this source tree. 275 */const tne=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],bi=Pe("copy",tne);/** 276 * @license lucide-react v0.577.0 - ISC 277 * 278 * This source code is licensed under the ISC license. 279 * See the LICENSE file in the root directory of this source tree. 280 */const nne=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]],tx=Pe("credit-card",nne);/** 281 * @license lucide-react v0.577.0 - ISC 282 * 283 * This source code is licensed under the ISC license. 284 * See the LICENSE file in the root directory of this source tree. 285 */const rne=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"22",x2:"18",y1:"12",y2:"12",key:"l9bcsi"}],["line",{x1:"6",x2:"2",y1:"12",y2:"12",key:"13hhkx"}],["line",{x1:"12",x2:"12",y1:"6",y2:"2",key:"10w3f3"}],["line",{x1:"12",x2:"12",y1:"22",y2:"18",key:"15g9kq"}]],L2=Pe("crosshair",rne);/** 286 * @license lucide-react v0.577.0 - ISC 287 * 288 * This source code is licensed under the ISC license. 289 * See the LICENSE file in the root directory of this source tree. 290 */const sne=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],ane=Pe("dollar-sign",sne);/** 291 * @license lucide-react v0.577.0 - ISC 292 * 293 * This source code is licensed under the ISC license. 294 * See the LICENSE file in the root directory of this source tree. 295 */const ine=[["circle",{cx:"12.1",cy:"12.1",r:"1",key:"18d7e5"}]],one=Pe("dot",ine);/** 296 * @license lucide-react v0.577.0 - ISC 297 * 298 * This source code is licensed under the ISC license. 299 * See the LICENSE file in the root directory of this source tree. 300 */const lne=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],tF=Pe("ellipsis",lne);/** 301 * @license lucide-react v0.577.0 - ISC 302 * 303 * This source code is licensed under the ISC license. 304 * See the LICENSE file in the root directory of this source tree. 305 */const cne=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],F2=Pe("eye-off",cne);/** 306 * @license lucide-react v0.577.0 - ISC 307 * 308 * This source code is licensed under the ISC license. 309 * See the LICENSE file in the root directory of this source tree. 310 */const une=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],al=Pe("eye",une);/** 311 * @license lucide-react v0.577.0 - ISC 312 * 313 * This source code is licensed under the ISC license. 314 * See the LICENSE file in the root directory of this source tree. 315 */const dne=[["path",{d:"M13.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v11.5",key:"4pqfef"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M8 12v-1",key:"1ej8lb"}],["path",{d:"M8 18v-2",key:"qcmpov"}],["path",{d:"M8 7V6",key:"1nbb54"}],["circle",{cx:"8",cy:"20",r:"2",key:"ckkr5m"}]],hne=Pe("file-archive",dne);/** 316 * @license lucide-react v0.577.0 - ISC 317 * 318 * This source code is licensed under the ISC license. 319 * See the LICENSE file in the root directory of this source tree. 320 */const fne=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]],mne=Pe("file-image",fne);/** 321 * @license lucide-react v0.577.0 - ISC 322 * 323 * This source code is licensed under the ISC license. 324 * See the LICENSE file in the root directory of this source tree.
325 */const pne=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],xne=Pe("file-plus",pne);/** 326 * @license lucide-react v0.577.0 - ISC 327 * 328 * This source code is licensed under the ISC license. 329 * See the LICENSE file in the root directory of this source tree. 330 */const gne=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]],nF=Pe("file-spreadsheet",gne);/** 331 * @license lucide-react v0.577.0 - ISC 332 * 333 * This source code is licensed under the ISC license. 334 * See the LICENSE file in the root directory of this source tree. 335 */const yne=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],il=Pe("file-text",yne);/** 336 * @license lucide-react v0.577.0 - ISC 337 * 338 * This source code is licensed under the ISC license. 339 * See the LICENSE file in the root directory of this source tree. 340 */const bne=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],vne=Pe("file",bne);/** 341 * @license lucide-react v0.577.0 - ISC 342 * 343 * This source code is licensed under the ISC license. 344 * See the LICENSE file in the root directory of this source tree. 345 */const wne=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],_ne=Pe("flag",wne);/** 346 * @license lucide-react v0.577.0 - ISC 347 * 348 * This source code is licensed under the ISC license. 349 * See the LICENSE file in the root directory of this source tree. 350 */const kne=[["path",{d:"M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2",key:"18mbvz"}],["path",{d:"M6.453 15h11.094",key:"3shlmq"}],["path",{d:"M8.5 2h7",key:"csnxdl"}]],rF=Pe("flask-conical",kne);/** 351 * @license lucide-react v0.577.0 - ISC 352 * 353 * This source code is licensed under the ISC license. 354 * See the LICENSE file in the root directory of this source tree. 355 */const jne=[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]],Nne=Pe("folder-tree",jne);/** 356 * @license lucide-react v0.577.0 - ISC 357 * 358 * This source code is licensed under the ISC license. 359 * See the LICENSE file in the root directory of this source tree. 360 */const Sne=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],sF=Pe("folder",Sne);/** 361 * @license lucide-react v0.577.0 - ISC 362 * 363 * This source code is licensed under the ISC license. 364 * See the LICENSE file in the root directory of this source tree. 365 */const Cne=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],aF=Pe("funnel",Cne);/** 366 * @license lucide-react v0.577.0 - ISC 367 * 368 * This source code is licensed under the ISC license. 369 * See the LICENSE file in the root directory of this source tree. 370 */const Ene=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],iF=Pe("gauge",Ene);/** 371 * @license lucide-react v0.577.0 - ISC 372 * 373 * This source code is licensed under the ISC license. 374 * See the LICENSE file in the root directory of this source tree. 375 */const Ane=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8",key:"1sqzm4"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5",key:"kc0143"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1",key:"1hberx"}]],B2=Pe("gift",Ane);/** 376 * @license lucide-react v0.577.0 - ISC 377 * 378 * This source code is licensed under the ISC license. 379 * See the LICENSE file in the root directory of this source tree. 380 */const Tne=[["path",{d:"M15 6a9 9 0 0 0-9 9V3",key:"1cii5b"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}]],One=Pe("git-branch",Tne);/** 381 * @license lucide-react v0.577.0 - ISC 382 * 383 * This source code is licensed under the ISC license. 384 * See the LICENSE file in the root directory of this source tree. 385 */const Ine=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]],Pne=Pe("globe",Ine);/** 386 * @license lucide-react v0.577.0 - ISC 387 * 388 * This source code is licensed under the ISC license. 389 * See the LICENSE file in the root directory of this source tree. 390 */const Rne=[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]],U2=Pe("graduation-cap",Rne);/** 391 * @license lucide-react v0.577.0 - ISC 392 * 393 * This source code is licensed under the ISC license. 394 * See the LICENSE file in the root directory of this source tree. 395 */const Dne=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],r0=Pe("history",Dne);/** 396 * @license lucide-react v0.577.0 - ISC 397 * 398 * This source code is licensed under the ISC license. 399 * See the LICENSE file in the root directory of this source tree. 400 */const Mne=[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]],nx=Pe("image-off",Mne);/** 401 * @license lucide-react v0.577.0 - ISC 402 * 403 * This source code is licensed under the ISC license. 404 * See the LICENSE file in the root directory of this source tree. 405 */const $ne=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],Qy=Pe("image",$ne);/** 406 * @license lucide-react v0.577.0 - ISC 407 * 408 * This source code is licensed under the ISC license. 409 * See the LICENSE file in the root directory of this source tree. 410 */const Lne=[["path",{d:"m22 11-1.296-1.296a2.4 2.4 0 0 0-3.408 0L11 16",key:"9kzy35"}],["path",{d:"M4 8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2",ke
410y:"1t0f0t"}],["circle",{cx:"13",cy:"7",r:"1",fill:"currentColor",key:"1obus6"}],["rect",{x:"8",y:"2",width:"14",height:"14",rx:"2",key:"1gvhby"}]],Fne=Pe("images",Lne);/** 411 * @license lucide-react v0.577.0 - ISC 412 * 413 * This source code is licensed under the ISC license. 414 * See the LICENSE file in the root directory of this source tree. 415 */const Bne=[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]],oF=Pe("inbox",Bne);/** 416 * @license lucide-react v0.577.0 - ISC 417 * 418 * This source code is licensed under the ISC license. 419 * See the LICENSE file in the root directory of this source tree. 420 */const Une=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],lF=Pe("info",Une);/** 421 * @license lucide-react v0.577.0 - ISC 422 * 423 * This source code is licensed under the ISC license. 424 * See the LICENSE file in the root directory of this source tree. 425 */const zne=[["path",{d:"M10 18v-7",key:"wt116b"}],["path",{d:"M11.12 2.198a2 2 0 0 1 1.76.006l7.866 3.847c.476.233.31.949-.22.949H3.474c-.53 0-.695-.716-.22-.949z",key:"1m329m"}],["path",{d:"M14 18v-7",key:"vav6t3"}],["path",{d:"M18 18v-7",key:"aexdmj"}],["path",{d:"M3 22h18",key:"8prr45"}],["path",{d:"M6 18v-7",key:"1ivflk"}]],z2=Pe("landmark",zne);/** 426 * @license lucide-react v0.577.0 - ISC 427 * 428 * This source code is licensed under the ISC license. 429 * See the LICENSE file in the root directory of this source tree. 430 */const Wne=[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]],gf=Pe("layout-grid",Wne);/** 431 * @license lucide-react v0.577.0 - ISC 432 * 433 * This source code is licensed under the ISC license. 434 * See the LICENSE file in the root directory of this source tree. 435 */const Kne=[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]],rx=Pe("layout-dashboard",Kne);/** 436 * @license lucide-react v0.577.0 - ISC 437 * 438 * This source code is licensed under the ISC license. 439 * See the LICENSE file in the root directory of this source tree. 440 */const Hne=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.93 4.93 4.24 4.24",key:"1ymg45"}],["path",{d:"m14.83 9.17 4.24-4.24",key:"1cb5xl"}],["path",{d:"m14.83 14.83 4.24 4.24",key:"q42g0n"}],["path",{d:"m9.17 14.83-4.24 4.24",key:"bqpfvv"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}]],cF=Pe("life-buoy",Hne);/** 441 * @license lucide-react v0.577.0 - ISC 442 * 443 * This source code is licensed under the ISC license. 444 * See the LICENSE file in the root directory of this source tree. 445 */const Vne=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],qne=Pe("link-2",Vne);/** 446 * @license lucide-react v0.577.0 - ISC 447 * 448 * This source code is licensed under the ISC license. 449 * See the LICENSE file in the root directory of this source tree. 450 */const Gne=[["path",{d:"M11 5h10",key:"1cz7ny"}],["path",{d:"M11 12h10",key:"1438ji"}],["path",{d:"M11 19h10",key:"11t30w"}],["path",{d:"M4 4h1v5",key:"10yrso"}],["path",{d:"M4 9h2",key:"r1h2o0"}],["path",{d:"M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02",key:"xtkcd5"}]],Yne=Pe("list-ordered",Gne);/** 451 * @license lucide-react v0.577.0 - ISC 452 * 453 * This source code is licensed under the ISC license. 454 * See the LICENSE file in the root directory of this source tree. 455 */const Zne=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],Xne=Pe("list",Zne);/** 456 * @license lucide-react v0.577.0 - ISC 457 * 458 * This source code is licensed under the ISC license. 459 * See the LICENSE file in the root directory of this source tree. 460 */const Jne=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]],HT=Pe("lock-open",Jne);/** 461 * @license lucide-react v0.577.0 - ISC 462 * 463 * This source code is licensed under the ISC license. 464 * See the LICENSE file in the root directory of this source tree. 465 */const Qne=[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]],W2=Pe("log-out",Qne);/** 466 * @license lucide-react v0.577.0 - ISC 467 * 468 * This source code is licensed under the ISC license. 469 * See the LICENSE file in the root directory of this source tree. 470 */const ere=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],tre=Pe("menu",ere);/** 471 * @license lucide-react v0.577.0 - ISC 472 * 473 * This source code is licensed under the ISC license. 474 * See the LICENSE file in the root directory of this source tree. 475 */const nre=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],rre=Pe("message-circle",nre);
475/** 476 * @license lucide-react v0.577.0 - ISC 477 * 478 * This source code is licensed under the ISC license. 479 * See the LICENSE file in the root directory of this source tree. 480 */const sre=[["path",{d:"M14 14a2 2 0 0 0 2-2V8h-2",key:"1r06pg"}],["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M8 14a2 2 0 0 0 2-2V8H8",key:"1jzu5j"}]],VT=Pe("message-square-quote",sre);/** 481 * @license lucide-react v0.577.0 - ISC 482 * 483 * This source code is licensed under the ISC license. 484 * See the LICENSE file in the root directory of this source tree. 485 */const are=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]],Rd=Pe("message-square",are);/** 486 * @license lucide-react v0.577.0 - ISC 487 * 488 * This source code is licensed under the ISC license. 489 * See the LICENSE file in the root directory of this source tree. 490 */const ire=[["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["path",{d:"M16 2v20",key:"rotuqe"}]],ore=Pe("notebook",ire);/** 491 * @license lucide-react v0.577.0 - ISC 492 * 493 * This source code is licensed under the ISC license. 494 * See the LICENSE file in the root directory of this source tree. 495 */const lre=[["path",{d:"M12 22V12",key:"d0xqtd"}],["path",{d:"M16 17h6",key:"1ook5g"}],["path",{d:"M19 14v6",key:"1ckrd5"}],["path",{d:"M21 10.535V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.729l7 4a2 2 0 0 0 2 .001l1.675-.955",key:"28k6lz"}],["path",{d:"M3.29 7 12 12l8.71-5",key:"19ckod"}],["path",{d:"m7.5 4.27 8.997 5.148",key:"9yrvtv"}]],Gm=Pe("package-plus",lre);/** 496 * @license lucide-react v0.577.0 - ISC 497 * 498 * This source code is licensed under the ISC license. 499 * See the LICENSE file in the root directory of this source tree. 500 */const cre=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],Si=Pe("package",cre);/** 501 * @license lucide-react v0.577.0 - ISC 502 * 503 * This source code is licensed under the ISC license. 504 * See the LICENSE file in the root directory of this source tree. 505 */const ure=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]],dre=Pe("panel-left-close",ure);/** 506 * @license lucide-react v0.577.0 - ISC 507 * 508 * This source code is licensed under the ISC license. 509 * See the LICENSE file in the root directory of this source tree. 510 */const hre=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]],fre=Pe("panel-left-open",hre);/** 511 * @license lucide-react v0.577.0 - ISC 512 * 513 * This source code is licensed under the ISC license. 514 * See the LICENSE file in the root directory of this source tree. 515 */const mre=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],uF=Pe("panel-left",mre);/** 516 * @license lucide-react v0.577.0 - ISC 517 * 518 * This source code is licensed under the ISC license. 519 * See the LICENSE file in the root directory of this source tree. 520 */const pre=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],xre=Pe("panel-right",pre);/** 521 * @license lucide-react v0.577.0 - ISC 522 * 523 * This source code is licensed under the ISC license. 524 * See the LICENSE file in the root directory of this source tree. 525 */const gre=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],yre=Pe("paperclip",gre);/** 526 * @license lucide-react v0.577.0 - ISC 527 * 528 * This source code is licensed under the ISC license. 529 * See the LICENSE file in the root directory of this source tree. 530 */const bre=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],K2=Pe("pause",bre);/** 531 * @license lucide-react v0.577.0 - ISC 532 * 533 * This source code is licensed under the ISC license. 534 * See the LICENSE file in the root directory of this source tree. 535 */const vre=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],Qi=Pe("pencil",vre);/** 536 * @license lucide-react v0.577.0 - ISC 537 * 538 * This source code is licensed under the ISC license. 539 * See the LICENSE file in the root directory of this source tree. 540 */const wre=[["line",{x1:"19",x2:"5",y1:"5",y2:"19",key:"1x9vlm"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5",key:"4mh3h7"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5",key:"1mdrzq"}]],H2=Pe("percent",wre);
540/** 541 * @license lucide-react v0.577.0 - ISC 542 * 543 * This source code is licensed under the ISC license. 544 * See the LICENSE file in the root directory of this source tree. 545 */const _re=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384",key:"9njp5v"}]],dF=Pe("phone",_re);/** 546 * @license lucide-react v0.577.0 - ISC 547 * 548 * This source code is licensed under the ISC license. 549 * See the LICENSE file in the root directory of this source tree. 550 */const kre=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],bd=Pe("play",kre);/** 551 * @license lucide-react v0.577.0 - ISC 552 * 553 * This source code is licensed under the ISC license. 554 * See the LICENSE file in the root directory of this source tree. 555 */const jre=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],hF=Pe("plug",jre);/** 556 * @license lucide-react v0.577.0 - ISC 557 * 558 * This source code is licensed under the ISC license. 559 * See the LICENSE file in the root directory of this source tree. 560 */const Nre=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],In=Pe("plus",Nre);/** 561 * @license lucide-react v0.577.0 - ISC 562 * 563 * This source code is licensed under the ISC license. 564 * See the LICENSE file in the root directory of this source tree. 565 */const Sre=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],Cre=Pe("power",Sre);/** 566 * @license lucide-react v0.577.0 - ISC 567 * 568 * This source code is licensed under the ISC license. 569 * See the LICENSE file in the root directory of this source tree. 570 */const Ere=[["path",{d:"M13 16H8",key:"wsln4y"}],["path",{d:"M14 8H8",key:"1l3xfs"}],["path",{d:"M16 12H8",key:"1fr5h0"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z",key:"ycz6yz"}]],Are=Pe("receipt-text",Ere);/** 571 * @license lucide-react v0.577.0 - ISC 572 * 573 * This source code is licensed under the ISC license. 574 * See the LICENSE file in the root directory of this source tree. 575 */const Tre=[["path",{d:"M12 17V7",key:"pyj7ub"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8",key:"1elt7d"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z",key:"ycz6yz"}]],yf=Pe("receipt",Tre);/** 576 * @license lucide-react v0.577.0 - ISC 577 * 578 * This source code is licensed under the ISC license. 579 * See the LICENSE file in the root directory of this source tree. 580 */const Ore=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],pa=Pe("refresh-cw",Ore);/** 581 * @license lucide-react v0.577.0 - ISC 582 * 583 * This source code is licensed under the ISC license. 584 * See the LICENSE file in the root directory of this source tree. 585 */const Ire=[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]],Pre=Pe("repeat",Ire);/** 586 * @license lucide-react v0.577.0 - ISC 587 * 588 * This source code is licensed under the ISC license. 589 * See the LICENSE file in the root directory of this source tree. 590 */const Rre=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],vi=Pe("rotate-cw",Rre);/** 591 * @license lucide-react v0.577.0 - ISC 592 * 593 * This source code is licensed under the ISC license. 594 * See the LICENSE file in the root directory of this source tree. 595 */const Dre=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}
595],["path",{d:"M21 15H3",key:"9uk58r"}]],Mre=Pe("rows-3",Dre);/** 596 * @license lucide-react v0.577.0 - ISC 597 * 598 * This source code is licensed under the ISC license. 599 * See the LICENSE file in the root directory of this source tree. 600 */const $re=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],ko=Pe("save",$re);/** 601 * @license lucide-react v0.577.0 - ISC 602 * 603 * This source code is licensed under the ISC license. 604 * See the LICENSE file in the root directory of this source tree. 605 */const Lre=[["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"m19 8 3 8a5 5 0 0 1-6 0zV7",key:"zcdpyk"}],["path",{d:"M3 7h1a17 17 0 0 0 8-2 17 17 0 0 0 8 2h1",key:"1yorad"}],["path",{d:"m5 8 3 8a5 5 0 0 1-6 0zV7",key:"eua70x"}],["path",{d:"M7 21h10",key:"1b0cd5"}]],fF=Pe("scale",Lre);/** 606 * @license lucide-react v0.577.0 - ISC 607 * 608 * This source code is licensed under the ISC license. 609 * See the LICENSE file in the root directory of this source tree. 610 */const Fre=[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M7 12h10",key:"b7w52i"}]],Bre=Pe("scan-line",Fre);/** 611 * @license lucide-react v0.577.0 - ISC 612 * 613 * This source code is licensed under the ISC license. 614 * See the LICENSE file in the root directory of this source tree. 615 */const Ure=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],V2=Pe("send",Ure);/** 616 * @license lucide-react v0.577.0 - ISC 617 * 618 * This source code is licensed under the ISC license. 619 * See the LICENSE file in the root directory of this source tree. 620 */const zre=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],dp=Pe("settings",zre);/** 621 * @license lucide-react v0.577.0 - ISC 622 * 623 * This source code is licensed under the ISC license. 624 * See the LICENSE file in the root directory of this source tree. 625 */const Wre=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],Kre=Pe("shield-check",Wre);/** 626 * @license lucide-react v0.577.0 - ISC 627 * 628 * This source code is licensed under the ISC license. 629 * See the LICENSE file in the root directory of this source tree. 630 */const Hre=[["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}],["path",{d:"M3.103 6.034h17.794",key:"awc11p"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z",key:"o988cm"}]],sN=Pe("shopping-bag",Hre);/** 631 * @license lucide-react v0.577.0 - ISC 632 * 633 * This source code is licensed under the ISC license. 634 * See the LICENSE file in the root directory of this source tree. 635 */const Vre=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],qre=Pe("sliders-horizontal",Vre);/** 636 * @license lucide-react v0.577.0 - ISC 637 * 638 * This source code is licensed under the ISC license. 639 * See the LICENSE file in the root directory of this source tree. 640 */const Gre=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],mF=Pe("smartphone",Gre);/** 641 * @license lucide-react v0.577.0 - ISC 642 * 643 * This source code is licensed under the ISC license. 644 * See the LICENSE file in the root directory of this source tree. 645 */const Yre=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Zre=Pe("square",Yre);/** 646 * @license lucide-react v0.577.0 - ISC 647 * 648 * This source code is licensed under the ISC license. 649 * See the LICENSE file in the root directory of this source tree. 650 */const Xre=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],Jre=Pe("star",Xre);/** 651 * @license lucide-react v0.577.0 - ISC 652 * 653 * This source code is licensed under the ISC license. 654 * See the LICENSE file in the root directory of this source tree. 655 */const Qre=[["path",{d:"M21 9a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 15 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2z",key:"1dfntj"}],["path",{d:"M15 3v5a1 1 0 0 0 1 1h5",key:"6s6qgf"}]],pF=Pe("sticky-note",Qre);/** 656 * @license lucide-react v0.577.0 - ISC 657 * 658 * This source code is licensed under the ISC license. 659 * See the LICENSE file in the root directory of this source tree. 660 */const ese=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5",key:"slp6dd"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244",key:"o0xfot"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05",key:"wn3emo"}]],sx=Pe("store",ese);/** 661 * @license lucide-react v0.577.0 - ISC 662 * 663 * This source code is licensed under the ISC license. 664 * See the LICENSE file in the root directory of this source tree. 665 */const tse=[["path",{d:"M13.172 2a2 2 0 0 1 1.414.586l6.71 6.71a2.4 2.4 0 0 1 0 3.408l-4.592 4.592a2.4 2.4 0 0 1-3.408 0l-6.71-6.71A2 2 0 0 1 6 9.172V3a1 1 0 0 1 1-1z",key:"16rjxf"}],["path",{d:"M2 7v6.172a2 2 0 0 0 .586 1.414l6.71 6.71a2.4 2.4 0 0 0 3.191.193",key:"178nd4"}],["circle",{cx:"10.5",cy:"6.5",r:".5",fill:"currentColor",key:"12ikhr"}]],nse=Pe("tags",tse);/** 666 * @license lucide-react v0.577.0 - ISC 667 * 668 * This source code is licensed under the ISC license. 669 * See the LICENSE file in the root directory of this source tree. 670 */const rse=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],us=Pe("trash-2",rse);/** 671 * @license lucide-react v0.577.0 - ISC 672 * 673 * This source code is licensed under the ISC license. 674 * See the LICENSE file in the root directory of this source tree. 675 */const sse=[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]],ax=Pe("trending-down",sse);/** 676 * @license lucide-react v0.577.0 - ISC 677 * 678 * This source code is licensed under the ISC license. 679 * See the LICENSE file in the root directory of this source tree. 680 */const ase=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]],zn=Pe("triangle-alert",ase);/** 681 * @license lucide-react v0.577.0 - ISC 682 * 683 * This source code is licensed under the ISC license. 684 * See the LICENSE file in the root directory of this source tree. 685 */const ise=[["path",{d:"M10 14.66v1.626a2 2 0 0 1-.976 1.696A5 5 0 0 0 7 21.978",key:"1n3hpd"}],["path",{d:"M14 14.66v1.626a2 2 0 0 0 .976 1.696A5 5 0 0 1 17 21.978",key:"rfe1zi"}],["path",{d:"M18 9h1.5a1 1 0 0 0 0-5H18",key:"7xy6bh"}],["path",{d:"M4 22h16",key:"57wxv0"}],["path",{d:"M6 9a6 6 0 0 0 12 0V3a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1z",key:"1mhfuq"}],["path",{d:"M6 9H4.5a1 1 0 0 1 0-5H6",key:"tex48p"}]],ose=Pe("trophy",ise);/** 686 * @license lucide-react v0.577.0 - ISC 687 * 688 * This source code is licensed under the ISC license. 689 * See the LICENSE file in the root directory of this source tree. 690 */const lse=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]],qi=Pe("truck",lse);/** 691 * @license lucide-react v0.577.0 - ISC 692 * 693 * This source code is licensed under the ISC license. 694 * See the LICENSE file in the root directory of this source tree. 695 */const cse=[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]],vd=Pe("undo-2",cse);/** 696 * @license lucide-react v0.577.0 - ISC 697 * 698 * This source code is licensed under the ISC license. 699 * See the LICENSE file in the root directory of this source tree.
700 */const use=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],ti=Pe("upload",use);/** 701 * @license lucide-react v0.577.0 - ISC 702 * 703 * This source code is licensed under the ISC license. 704 * See the LICENSE file in the root directory of this source tree. 705 */const dse=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]],q2=Pe("user-plus",dse);/** 706 * @license lucide-react v0.577.0 - ISC 707 * 708 * This source code is licensed under the ISC license. 709 * See the LICENSE file in the root directory of this source tree. 710 */const hse=[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]],fse=Pe("video",hse);/** 711 * @license lucide-react v0.577.0 - ISC 712 * 713 * This source code is licensed under the ISC license. 714 * See the LICENSE file in the root directory of this source tree. 715 */const mse=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"18etb6"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4",key:"xoc0q4"}]],s0=Pe("wallet",mse);/** 716 * @license lucide-react v0.577.0 - ISC 717 * 718 * This source code is licensed under the ISC license. 719 * See the LICENSE file in the root directory of this source tree. 720 */const pse=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],xF=Pe("wrench",pse);/** 721 * @license lucide-react v0.577.0 - ISC 722 * 723 * This source code is licensed under the ISC license. 724 * See the LICENSE file in the root directory of this source tree. 725 */const xse=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],ix=Pe("zap",xse),gse=Symbol.for("@supabase/supabase-js.traceContextExtractor");function yse(){return globalThis[gse]}const bse=e=>e?(...t)=>e(...t):(...t)=>fetch(...t);class G2 extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}toJSON(){return{name:this.name,message:this.message,context:this.context}}}class vse extends G2{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class qT extends G2{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class GT extends G2{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var aN;(function(e){e.Any="any",e.ApNortheast1="ap-northeast-1",e.ApNortheast2="ap-northeast-2",e.ApSouth1="ap-south-1",e.ApSoutheast1="ap-southeast-1",e.ApSoutheast2="ap-southeast-2",e.CaCentral1="ca-central-1",e.EuCentral1="eu-central-1",e.EuWest1="eu-west-1",e.EuWest2="eu-west-2",e.EuWest3="eu-west-3",e.SaEast1="sa-east-1",e.UsEast1="us-east-1",e.UsWest1="us-west-1",e.UsWest2="us-west-2"})(aN||(aN={}));class wse{constructor(t,{headers:n={},customFetch:r,region:a=aN.Any}={}){this.url=t,this.headers=n,this.region=a,this.fetch=bse(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t){return wY(this,arguments,void 0,function*(n,r={}){var a,i;let o,l,c;try{const{headers:u,method:d,body:h,signal:f,timeout:m}=r;let x={},{region:g}=r;g||(g=this.region);const y=new URL(`${this.url}/${n}`);g&&g!=="any"&&(x["x-region"]=g,y.searchParams.set("forceFunctionRegion",g));let b;const v=!!u&&Object.keys(u).some(E=>E.toLowerCase()==="content-type");h&&!v?typeof Blob<"u"&&h instanceof Blob||h instanceof ArrayBuffer?(x["Content-Type"]="application/octet-stream",b=h):typeof h=="string"?(x["Content-Type"]="text/plain",b=h):typeof FormData<"u"&&h instanceof FormData?b=h:(x["Content-Type"]="application/json",b=JSON.stringify(h)):h&&typeof h!="string"&&!(typeof Blob<"u"&&h instanceof Blob)&&!(h instanceof ArrayBuffer)&&!(typeof FormData<"u"&&h instanceof FormData)?b=JSON.stringify(h):b=h;let w=f;m&&(l=new AbortController,o=setTimeout(()=>l.abort(),m),f?(w=l.signal,c=()=>l.abort(),f.addEventListener("abort",c)):w=l.signal);const _=yield this.fetch(y.toString(),{method:d||"POST",headers:Object.assign(Object.assign(Object.assign({},x),this.headers),u),body:b,signal:w}).catch(E=>{throw new vse(E)}),k=_.headers.get("x-relay-error");
725if(k&&k==="true")throw new qT(_);if(!_.ok)throw new GT(_);let j=((a=_.headers.get("Content-Type"))!==null&&a!==void 0?a:"text/plain").split(";")[0].trim().toLowerCase(),N;return j==="application/json"?N=yield _.json():j==="application/octet-stream"||j==="application/pdf"?N=yield _.blob():j==="text/event-stream"?N=_:j==="multipart/form-data"?N=yield _.formData():N=yield _.text(),{data:N,error:null,response:_}}catch(u){return{data:null,error:u,response:u instanceof GT||u instanceof qT?u.context:void 0}}finally{o&&clearTimeout(o),c&&((i=r.signal)===null||i===void 0||i.removeEventListener("abort",c))}})}}const gF=3,YT=e=>Math.min(1e3*2**e,3e4),_se=[520,503],yF=["GET","HEAD","OPTIONS"];var Jw=class extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};function hp(e){"@babel/helpers - typeof";return hp=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},hp(e)}function kse(e,t){if(hp(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(hp(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function jse(e){var t=kse(e,"string");return hp(t)=="symbol"?t:t+""}function Nse(e,t,n){return(t=jse(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ZT(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Nh(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?ZT(Object(n),!0).forEach(function(r){Nse(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ZT(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function XT(e,t){return new Promise(n=>{if(t!=null&&t.aborted){n();return}const r=setTimeout(()=>{t==null||t.removeEventListener("abort",a),n()},e);function a(){clearTimeout(r),n()}t==null||t.addEventListener("abort",a)})}function Sse(e,t,n,r){return!(!r||n>=gF||!yF.includes(e)||!_se.includes(t))}var Cse=class{constructor(e){var t,n,r,a,i;this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=(t=e.shouldThrowOnError)!==null&&t!==void 0?t:!1,this.signal=e.signal,this.isMaybeSingle=(n=e.isMaybeSingle)!==null&&n!==void 0?n:!1,this.shouldStripNulls=(r=e.shouldStripNulls)!==null&&r!==void 0?r:!1,this.urlLengthLimit=(a=e.urlLengthLimit)!==null&&a!==void 0?a:8e3,this.retryEnabled=(i=e.retry)!==null&&i!==void 0?i:!0,e.fetch?this.fetch=e.fetch:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get("Accept")==="text/csv")throw new Error("stripNulls() cannot be used with csv()");return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var n=this;if(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"),this.shouldStripNulls){const o=this.headers.get("Accept");o==="application/vnd.pgrst.object+json"?this.headers.set("Accept","application/vnd.pgrst.object+json;nulls=stripped"):(!o||o==="application/json")&&this.headers.set("Accept","application/vnd.pgrst.array+json;nulls=stripped")}const r=this.fetch;let i=(async()=>{let o=0;for(;;){const u={};n.headers.forEach((h,f)=>{u[f]=h}),o>0&&(u["X-Retry-Count"]=String(o));let d;try{d=await r(n.url.toString(),{method:n.method,headers:u,body:JSON.stringify(n.body,(h,f)=>typeof f=="bigint"?f.toString():f),signal:n.signal})}catch(h){if((h==null?void 0:h.name)==="AbortError"||(h==null?void 0:h.code)==="ABORT_ERR"||!yF.includes(n.method))throw h;if(n.retryEnabled&&o<gF){const f=YT(o);o++,await XT(f,n.signal);continue}throw h}if(Sse(n.method,d.status,o,n.retryEnabled)){var l,c;const h=(l=(c=d.headers)===null||c===void 0?void 0:c.get("Retry-After"))!==null&&l!==void 0?l:null,f=h!==null?Math.max(0,parseInt(h,10)||0)*1e3:YT(o);await d.text(),o++,await XT(f,n.signal);continue}return await n.processResponse(d)}})();return this.shouldThrowOnError||(i=i.catch(o=>{var l;let c="",u="",d="";const h=o==null?void 0:o.cause;if(h){var f,m,x,g;const v=(f=h==null?void 0:h.message)!==null&&f!==void 0?f:"",w=(m=h==null?void 0:h.code)!==null&&m!==void 0?m:"";c=`${(x=o==null?void 0:o.name)!==null&&x!==void 0?x:"FetchError"}: ${o==null?void 0:o.message}`,c+=` 726 727Caused by: ${(g=h==null?void 0:h.name)!==null&&g!==void 0?g:"Error"}: ${v}`,w&&(c+=` (${w})`),h!=null&&h.stack&&(c+=` 728${h.stack}`)}else{var y;c=(y=o==null?void 0:o.stack)!==null&&y!==void 0?y:""}const b=this.url.toString().length;return(o==null?void 0:o.name)==="AbortError"||(o==null?void 0:o.code)==="ABORT_ERR"?(d="",u="Request was aborted (timeout or manual cancellation)",b>this.urlLengthLimit&&(u+=`. Note: Your request URL is ${b} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):((h==null?void 0:h.name)==="HeadersOverflowError"||(h==null?void 0:h.code)==="UND_ERR_HEADERS_OVERFLOW")&&(d="",u="HTTP headers exceeded server limits (typically 16KB)",b>this.urlLengthLimit&&(u+=`. Your request URL is ${b} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${(l=o==null?void 0:o.name)!==null&&l!==void 0?l:"FetchError"}: ${o==null?void 0:o.message}`,details:c,hint:u,code:d},data:null,count:null,status:0,statusText:""}}
728)),i.then(e,t)}async processResponse(e){var t=this;let n=null,r=null,a=null,i=e.status,o=e.statusText;if(e.ok){var l,c;if(t.method!=="HEAD"){var u;const m=await e.text();if(m!=="")if(t.headers.get("Accept")==="text/csv")r=m;else if(t.headers.get("Accept")&&(!((u=t.headers.get("Accept"))===null||u===void 0)&&u.includes("application/vnd.pgrst.plan+text")))r=m;else try{r=JSON.parse(m)}catch{if(n={message:m},r=null,t.shouldThrowOnError)throw new Jw({message:m,details:"",hint:"",code:""})}}const h=(l=t.headers.get("Prefer"))===null||l===void 0?void 0:l.match(/count=(exact|planned|estimated)/),f=(c=e.headers.get("content-range"))===null||c===void 0?void 0:c.split("/");if(h&&f&&f.length>1&&(a=parseInt(f[1])),t.isMaybeSingle&&Array.isArray(r))if(r.length>1){if(n={code:"PGRST116",details:`Results contain ${r.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},r=null,a=null,i=406,o="Not Acceptable",t.shouldThrowOnError){var d;throw new Jw(Nh(Nh({},n),{},{hint:(d=n.hint)!==null&&d!==void 0?d:""}))}}else r.length===1?r=r[0]:r=null}else{const h=await e.text();try{n=JSON.parse(h),Array.isArray(n)&&e.status===404&&(r=[],n=null,i=200,o="OK")}catch{e.status===404&&h===""?(i=204,o="No Content"):n={message:h}}if(n&&t.shouldThrowOnError)throw new Jw(n)}return{success:n===null,error:n,data:r,count:a,status:i,statusText:o}}returns(){return this}overrideTypes(){return this}},Ese=class extends Cse{throwOnError(){return super.throwOnError()}select(e){let t=!1;const n=(e??"*").split("").map(r=>/\s/.test(r)&&!t?"":(r==='"'&&(t=!t),r)).join("");return this.url.searchParams.set("select",n),this.headers.append("Prefer","return=representation"),this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:r,referencedTable:a=r}={}){const i=a?`${a}.order`:"order",o=this.url.searchParams.get(i);return this.url.searchParams.set(i,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${n===void 0?"":n?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){const r=typeof n>"u"?"limit":`${n}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:r=n}={}){const a=typeof r>"u"?"offset":`${r}.offset`,i=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(a,`${e}`),this.url.searchParams.set(i,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set("Accept","application/vnd.pgrst.object+json"),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set("Accept","text/csv"),this}geojson(){return this.headers.set("Accept","application/geo+json"),this}explain({analyze:e=!1,verbose:t=!1,settings:n=!1,buffers:r=!1,wal:a=!1,format:i="text"}={}){var o;const l=[e?"analyze":null,t?"verbose":null,n?"settings":null,r?"buffers":null,a?"wal":null].filter(Boolean).join("|"),c=(o=this.headers.get("Accept"))!==null&&o!==void 0?o:"application/json";return this.headers.set("Accept",`application/vnd.pgrst.plan+${i}; for="${c}"; options=${l};`),i==="json"?this:this}rollback(){return this.headers.append("Prefer","tx=rollback"),this}returns(){return this}maxAffected(e){return this.headers.append("Prefer","handling=strict"),this.headers.append("Prefer",`max-affected=${e}`),this}};const JT=new RegExp("[,()]");var xh=class extends Ese{throwOnError(){return super.throwOnError()}eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){const n=Array.from(new Set(t)).map(r=>typeof r=="string"&&JT.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`in.(${n})`),this}notIn(e,t){const n=Array.from(new Set(t)).map(r=>typeof r=="string"&&JT.test(r)?`"${r}"`:`${r}`).join(",");return this.url.searchParams.append(e,`not.in.(${n})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:n,type:r}={}){let a="";r==="plain"?a="pl":r==="phrase"?a="ph":r==="websearch"&&(a="w");const i=n===void 0?"":`(${n})`;return this.url.searchParams.append(e,`${a}fts${i}.${t}`),this}match(e){return Object.entries(e).filter(([t,n])=>
728n!==void 0).forEach(([t,n])=>{this.url.searchParams.append(t,`eq.${n}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){const r=n?`${n}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}},Ase=class{constructor(e,{headers:t={},schema:n,fetch:r,urlLengthLimit:a=8e3,retry:i}){this.url=e,this.headers=new Headers(t),this.schema=n,this.fetch=r,this.urlLengthLimit=a,this.retry=i}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){const{head:n=!1,count:r}=t??{},a=n?"HEAD":"GET";let i=!1;const o=(e??"*").split("").map(u=>/\s/.test(u)&&!i?"":(u==='"'&&(i=!i),u)).join(""),{url:l,headers:c}=this.cloneRequestState();return l.searchParams.set("select",o),r&&c.append("Prefer",`count=${r}`),new xh({method:a,url:l,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:n=!0}={}){var r;const a="POST",{url:i,headers:o}=this.cloneRequestState();if(t&&o.append("Prefer",`count=${t}`),n||o.append("Prefer","missing=default"),Array.isArray(e)){const l=e.reduce((c,u)=>c.concat(Object.keys(u)),[]);if(l.length>0){const c=[...new Set(l)].map(u=>`"${u}"`);i.searchParams.set("columns",c.join(","))}}return new xh({method:a,url:i,headers:o,schema:this.schema,body:e,fetch:(r=this.fetch)!==null&&r!==void 0?r:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:n=!1,count:r,defaultToNull:a=!0}={}){var i;const o="POST",{url:l,headers:c}=this.cloneRequestState();if(c.append("Prefer",`resolution=${n?"ignore":"merge"}-duplicates`),t!==void 0&&l.searchParams.set("on_conflict",t),r&&c.append("Prefer",`count=${r}`),a||c.append("Prefer","missing=default"),Array.isArray(e)){const u=e.reduce((d,h)=>d.concat(Object.keys(h)),[]);if(u.length>0){const d=[...new Set(u)].map(h=>`"${h}"`);l.searchParams.set("columns",d.join(","))}}return new xh({method:o,url:l,headers:c,schema:this.schema,body:e,fetch:(i=this.fetch)!==null&&i!==void 0?i:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){var n;const r="PATCH",{url:a,headers:i}=this.cloneRequestState();return t&&i.append("Prefer",`count=${t}`),new xh({method:r,url:a,headers:i,schema:this.schema,body:e,fetch:(n=this.fetch)!==null&&n!==void 0?n:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){var t;const n="DELETE",{url:r,headers:a}=this.cloneRequestState();return e&&a.append("Prefer",`count=${e}`),new xh({method:n,url:r,headers:a,schema:this.schema,fetch:(t=this.fetch)!==null&&t!==void 0?t:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}},Tse=class bF{constructor(t,{headers:n={},schema:r,fetch:a,timeout:i,urlLengthLimit:o=8e3,retry:l}={}){this.url=t,this.headers=new Headers(n),this.schemaName=r,this.urlLengthLimit=o;const c=a??globalThis.fetch;i!==void 0&&i>0?this.fetch=(u,d)=>{const h=new AbortController,f=setTimeout(()=>h.abort(),i),m=d==null?void 0:d.signal;if(m){if(m.aborted)return clearTimeout(f),c(u,d);const x=()=>{clearTimeout(f),h.abort()};return m.addEventListener("abort",x,{once:!0}),c(u,Nh(Nh({},d),{},{signal:h.signal})).finally(()=>{clearTimeout(f),m.removeEventListener("abort",x)})}return c(u,Nh(Nh({},d),{},{signal:h.signal})).finally(()=>clearTimeout(f))}:this.fetch=c,this.retry=l}from(t){if(!t||typeof t!="string"||t.trim()==="")throw new Error("Invalid relation name: relation must be a non-empty string.");return new Ase(new URL(`${this.url}/${t}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(t){return new bF(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}rpc(t,n={},{head:r=!1,get:a=!1,count:i}={}){var o;let l;const c=new URL(`${this.url}/rpc/${t}`);let u;const d=m=>m!==null&&typeof m=="object"&&(!Array.isArray(m)||m.some(d)),h=r&&Object.values(n).some(d);h?(l="POST",u=n):r||a?(l=r?"HEAD":"GET",Object.entries(n).filter(([m,x])=>x!==void 0).map(([m,x])=>[m,Array.isArray(x)?`{${x.join(",")}}`:`${x}
728`]).forEach(([m,x])=>{c.searchParams.append(m,x)})):(l="POST",u=n);const f=new Headers(this.headers);return h?f.set("Prefer",i?`count=${i},return=minimal`:"return=minimal"):i&&f.set("Prefer",`count=${i}`),new xh({method:l,url:c,headers:f,schema:this.schemaName,body:u,fetch:(o=this.fetch)!==null&&o!==void 0?o:fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};class Ose{constructor(){}static detectEnvironment(){var t;if(typeof WebSocket<"u")return{type:"native",wsConstructor:WebSocket};const n=globalThis;if(typeof globalThis<"u"&&typeof n.WebSocket<"u")return{type:"native",wsConstructor:n.WebSocket};const r=typeof global<"u"?global:void 0;if(r&&typeof r.WebSocket<"u")return{type:"native",wsConstructor:r.WebSocket};if(typeof globalThis<"u"&&typeof n.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"&&n.EdgeRuntime||typeof navigator<"u"&&(!((t=navigator.userAgent)===null||t===void 0)&&t.includes("Vercel-Edge")))return{type:"unsupported",error:"Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.",workaround:"Use serverless functions or a different deployment target for WebSocket functionality."};const a=globalThis.process;if(a){const i=a.versions;if(i&&i.node)return{type:"unsupported",error:"Node.js detected but native WebSocket not found.",workaround:"Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option."}}return{type:"unsupported",error:"Unknown JavaScript runtime without WebSocket support.",workaround:"Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation."}}static getWebSocketConstructor(){const t=this.detectEnvironment();if(t.wsConstructor)return t.wsConstructor;let n=t.error||"WebSocket not supported in this environment.";throw t.workaround&&(n+=` 729 730Suggested solution: ${t.workaround}`),new Error(n)}static isWebSocketSupported(){try{return this.detectEnvironment().type==="native"}catch{return!1}}}const Ise="2.112.3",Pse=`realtime-js/${Ise}`,Rse="1.0.0",vF="2.0.0",Dse=vF,Mse=1e4,$se=100,Mc={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},wF={close:"phx_close",error:"phx_error",join:"phx_join",leave:"phx_leave",access_token:"access_token"},iN={connecting:"connecting",closing:"closing",closed:"closed"};class Lse{constructor(t){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT="broadcast",this.allowedMetadataKeys=[],this.allowedMetadataKeys=t??[]}encode(t,n){if(t.event===this.BROADCAST_EVENT&&!(t.payload instanceof ArrayBuffer)&&typeof t.payload.event=="string")return n(this._binaryEncodeUserBroadcastPush(t));let r=[t.join_ref,t.ref,t.topic,t.event,t.payload];return n(JSON.stringify(r))}_binaryEncodeUserBroadcastPush(t){var n;return this._isArrayBuffer((n=t.payload)===null||n===void 0?void 0:n.payload)?this._encodeBinaryUserBroadcastPush(t):this._encodeJsonUserBroadcastPush(t)}_encodeBinaryUserBroadcastPush(t){var n,r;const a=(r=(n=t.payload)===null||n===void 0?void 0:n.payload)!==null&&r!==void 0?r:new ArrayBuffer(0);return this._encodeUserBroadcastPush(t,this.BINARY_ENCODING,a)}_encodeJsonUserBroadcastPush(t){var n,r;const a=(r=(n=t.payload)===null||n===void 0?void 0:n.payload)!==null&&r!==void 0?r:{},o=new TextEncoder().encode(JSON.stringify(a)).buffer;return this._encodeUserBroadcastPush(t,this.JSON_ENCODING,o)}_encodeUserBroadcastPush(t,n,r){var a,i;const o=new TextEncoder,l=o.encode(t.topic),c=o.encode((a=t.ref)!==null&&a!==void 0?a:""),u=o.encode((i=t.join_ref)!==null&&i!==void 0?i:""),d=o.encode(t.payload.event),h=this.allowedMetadataKeys?this._pick(t.payload,this.allowedMetadataKeys):{},f=o.encode(Object.keys(h).length===0?"":JSON.stringify(h));if(u.length>255)throw new Error(`joinRef length ${u.length} exceeds maximum of 255`);if(c.length>255)throw new Error(`ref length ${c.length} exceeds maximum of 255`);if(l.length>255)throw new Error(`topic length ${l.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 m=this.USER_BROADCAST_PUSH_META_LENGTH+u.length+c.length+l.length+d.length+f.length,x=new ArrayBuffer(this.HEADER_LENGTH+m),g=new DataView(x),y=new Uint8Array(x);let b=0;g.setUint8(b++,this.KINDS.userBroadcastPush),g.setUint8(b++,u.length),g.setUint8(b++,c.length),g.setUint8(b++,l.length),g.setUint8(b++,d.length),g.setUint8(b++,f.length),g.setUint8(b++,n),y.set(u,b),b+=u.length,y.set(c,b),b+=c.length,y.set(l,b),b+=l.length,y.set(d,b),b+=d.length,y.set(f,b),b+=f.length;var v=new Uint8Array(x.byteLength+r.byteLength);return v.set(new Uint8Array(x),0),v.set(new Uint8Array(r),x.byteLength),v.buffer}decode(t,n){if(this._isArrayBuffer(t)){let r=this._binaryDecode(t);return n(r)}if(typeof t=="string"){const r=JSON.parse(t),[a,i,o,l,c]=r;
730return n({join_ref:a,ref:i,topic:o,event:l,payload:c})}return n({})}_binaryDecode(t){const n=new DataView(t),r=n.getUint8(0),a=new TextDecoder;switch(r){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(t,n,a)}}_decodeUserBroadcast(t,n,r){const a=n.getUint8(1),i=n.getUint8(2),o=n.getUint8(3),l=n.getUint8(4);let c=this.HEADER_LENGTH+4;const u=r.decode(t.slice(c,c+a));c=c+a;const d=r.decode(t.slice(c,c+i));c=c+i;const h=r.decode(t.slice(c,c+o));c=c+o;const f=t.slice(c,t.byteLength),m=l===this.JSON_ENCODING?JSON.parse(r.decode(f)):f,x={type:this.BROADCAST_EVENT,event:d,payload:m};return o>0&&(x.meta=JSON.parse(h)),{join_ref:null,ref:null,topic:u,event:this.BROADCAST_EVENT,payload:x}}_isArrayBuffer(t){var n;return t instanceof ArrayBuffer||((n=t==null?void 0:t.constructor)===null||n===void 0?void 0:n.name)==="ArrayBuffer"}_pick(t,n){return!t||typeof t!="object"?{}:Object.fromEntries(Object.entries(t).filter(([r])=>n.includes(r)))}}var Kn;(function(e){e.abstime="abstime",e.bool="bool",e.date="date",e.daterange="daterange",e.float4="float4",e.float8="float8",e.int2="int2",e.int4="int4",e.int4range="int4range",e.int8="int8",e.int8range="int8range",e.json="json",e.jsonb="jsonb",e.money="money",e.numeric="numeric",e.oid="oid",e.reltime="reltime",e.text="text",e.time="time",e.timestamp="timestamp",e.timestamptz="timestamptz",e.timetz="timetz",e.tsrange="tsrange",e.tstzrange="tstzrange"})(Kn||(Kn={}));const QT=(e,t,n={})=>{var r;const a=(r=n.skipTypes)!==null&&r!==void 0?r:[];return t?Object.keys(t).reduce((i,o)=>(i[o]=Fse(o,e,t,a),i),{}):{}},Fse=(e,t,n,r)=>{const a=t.find(l=>
730l.name===e),i=a==null?void 0:a.type,o=n[e];return i&&!r.includes(i)?_F(i,o):oN(o)},_F=(e,t)=>{if(e.charAt(0)==="_"){const n=e.slice(1,e.length);return Wse(t,n)}switch(e){case Kn.bool:return Bse(t);case Kn.float4:case Kn.float8:case Kn.int2:case Kn.int4:case Kn.int8:case Kn.numeric:case Kn.oid:return Use(t);case Kn.json:case Kn.jsonb:return zse(t);case Kn.timestamp:return Kse(t);case Kn.abstime:case Kn.date:case Kn.daterange:case Kn.int4range:case Kn.int8range:case Kn.money:case Kn.reltime:case Kn.text:case Kn.time:case Kn.timestamptz:case Kn.timetz:case Kn.tsrange:case Kn.tstzrange:return oN(t);default:return oN(t)}},oN=e=>e,Bse=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},Use=e=>{if(typeof e=="string"){const t=parseFloat(e);if(!Number.isNaN(t))return t}return e},zse=e=>{if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e},Wse=(e,t)=>{if(typeof e!="string")return e;const n=e.length-1,r=e[n];if(e[0]==="{"&&r==="}"){let i;const o=e.slice(1,n);try{i=JSON.parse("["+o+"]")}catch{i=o?o.split(","):[]}return i.map(l=>_F(t,l))}return e},Kse=e=>typeof e=="string"?e.replace(" ","T"):e,kF=e=>{const t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,"http"),t.pathname=t.pathname.replace(/\/+$/,"").replace(/\/socket\/websocket$/i,"").replace(/\/socket$/i,"").replace(/\/websocket$/i,""),t.pathname===""||t.pathname==="/"?t.pathname="/api/broadcast":t.pathname=t.pathname+"/api/broadcast",t.href};var Ih=e=>typeof e=="function"?e:function(){return e},Hse=typeof self<"u"?self:null,gh=typeof window<"u"?window:null,Ho=Hse||gh||globalThis,Vse="2.0.0",qse=1e4,Gse=1e3,Yse=100,Vo={connecting:0,open:1,closing:2,closed:3},Ka={closed:"closed",errored:"errored",joined:"joined",joining:"joining",leaving:"leaving"},Al={close:"phx_close",error:"phx_error",join:"phx_join",reply:"phx_reply",leave:"phx_leave"},lN={longpoll:"longpoll",websocket:"websocket"},Zse={complete:4},cN="base64url.bearer.phx.",sg=class{constructor(e,t,n,r){this.channel=e,this.event=t,this.payload=n||function(){return{}},this.receivedResp=null,this.timeout=r,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:t,_ref:n}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},jF=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}},Xse=class{constructor(e,t,n){this.state=Ka.closed,this.topic=e,this.params=Ih(t||{}),this.socket=n,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new sg(this,Al.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new jF(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive("ok",()=>{this.state=Ka.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(r=>r.send()),this.pushBuffer=[]}),this.joinPush.receive("error",r=>{this.state=Ka.errored,this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,r),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log("channel",`close ${this.topic}`),this.state=Ka.closed,this.socket.remove(this)}),this.onError(r=>{this.socket.hasLogger()&&this.socket.log("channel",`error ${this.topic}`,r),this.isJoining()&&this.joinPush.reset(),this.state=Ka.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive("timeout",()=>{this.socket.hasLogger()&&this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),new sg(this,Al.leave,Ih({}),this.timeout).send(),this.state=Ka.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(Al.reply,(r,a)=>{this.trigger(this.replyEventName(a),r)})}join(e=this.timeout){if(this.joinedOnce)throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance");return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}
vendor: 19,028 bytes, lines 730-731
730teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=Ka.closed,this.bindings=[]}onClose(e){this.on(Al.close,e)}onError(e){return this.on(Al.error,t=>e(t))}on(e,t){let n=this.bindingRef++;return this.bindings.push({event:e,ref:n,callback:t}),n}off(e,t){this.bindings=this.bindings.filter(n=>!(n.event===e&&(typeof t>"u"||t===n.ref)))}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,n=this.timeout){if(t=t||{},!this.joinedOnce)throw new Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let r=new sg(this,e,function(){return t},n);return this.canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=Ka.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log("channel",`leave ${this.topic}`),this.trigger(Al.close,"leave")},n=new sg(this,Al.leave,Ih({}),e);return n.receive("ok",()=>t()).receive("timeout",()=>t()),n.send(),this.canPush()||n.trigger("ok",{}),n}onMessage(e,t,n){return t}filterBindings(e,t,n){return!0}isMember(e,t,n,r){return this.topic!==e?!1:r&&r!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log("channel","dropping outdated message",{topic:e,event:t,payload:n,joinRef:r}),!1):!0}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=Ka.joining,this.joinPush.resend(e))}trigger(e,t,n,r){let a=this.onMessage(e,t,n,r);if(t&&!a)throw new Error("channel onMessage callbacks must return the payload, modified or unmodified");let i=this.bindings.filter(o=>o.event===e&&this.filterBindings(o,t,n));for(let o=0;o<i.length;o++)i[o].callback(a,n,r||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===Ka.closed}isErrored(){return this.state===Ka.errored}isJoined(){return this.state===Ka.joined}isJoining(){return this.state===Ka.joining}isLeaving(){return this.state===Ka.leaving}},eb=class{static request(e,t,n,r,a,i,o){if(Ho.XDomainRequest){let l=new Ho.XDomainRequest;return this.xdomainRequest(l,e,t,r,a,i,o)}else if(Ho.XMLHttpRequest){let l=new Ho.XMLHttpRequest;return this.xhrRequest(l,e,t,n,r,a,i,o)}else{if(Ho.fetch&&Ho.AbortController)return this.fetchRequest(e,t,n,r,a,i,o);throw new Error("No suitable XMLHttpRequest implementation found")}}static fetchRequest(e,t,n,r,a,i,o){let l={method:e,headers:n,body:r},c=null;return a&&(c=new AbortController,setTimeout(()=>c.abort(),a),l.signal=c.signal),Ho.fetch(t,l).then(u=>u.text()).then(u=>this.parseJSON(u)).then(u=>o&&o(u)).catch(u=>{u.name==="AbortError"&&i?i():o&&o(null)}),c}static xdomainRequest(e,t,n,r,a,i,o){return e.timeout=a,e.open(t,n),e.onload=()=>{let l=this.parseJSON(e.responseText);o&&o(l)},i&&(e.ontimeout=i),e.onprogress=()=>{},e.send(r),e}static xhrRequest(e,t,n,r,a,i,o,l){e.open(t,n,!0),e.timeout=i;for(let[c,u]of Object.entries(r))e.setRequestHeader(c,u);return e.onerror=()=>l&&l(null),e.onreadystatechange=()=>{if(e.readyState===Zse.complete&&l){let c=this.parseJSON(e.responseText);l(c)}},o&&(e.ontimeout=o),e.send(a),e}static parseJSON(e){if(!e||e==="")return null;try{return JSON.parse(e)}catch{return console&&console.log("failed to parse JSON response",e),null}}static serialize(e,t){let n=[];for(var r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let a=t?`${t}[${r}]`:r,i=e[r];typeof i=="object"?n.push(this.serialize(i,a)):n.push(encodeURIComponent(a)+"="+encodeURIComponent(i))}return n.join("&")}static appendParams(e,t){if(Object.keys(t).length===0)return e;let n=e.match(/\?/)?"&":"?";return`${e}${n}${this.serialize(t)}`}},Jse=e=>{let t="",n=new Uint8Array(e),r=n.byteLength;for(let a=0;a<r;a++)t+=String.fromCharCode(n[a]);return btoa(t)},qd=class{constructor(e,t){t&&t.length===2&&t[1].startsWith(cN)&&(this.authToken=atob(t[1].slice(cN.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=Vo.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace("ws://","http://").replace("wss://","https://").replace(new RegExp("(.*)/"+lN.websocket),"$1/"+lN.longpoll)}endpointURL(){return eb.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,n){this.close(e,t,n),this.readyState=Vo.connecting}ontimeout(){this.onerror("timeout"),this.closeAndRetry(1005,"timeout",!1)}isActive(){return this.readyState===Vo.open||this.readyState===Vo.connecting}poll(){const e={Accept:"application/json"};this.authToken&&(e["X-Phoenix-AuthToken"]=this.authToken),this.ajax("GET",e,null,()=>this.ontimeout(),t=>{if(t){var{status:n,token:r,messages:a}=t;if(n===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,"session_gone",!1);return}this.token=r}else n=0;switch(n){case 200:a.forEach(i=>{setTimeout(()=>this.onmessage({data:i}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=Vo.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,"forbidden",!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,"internal server error",500);break;default:throw new Error(`unhandled poll status ${n}`)}})}send(e){typeof e!="string"&&(e=Jse(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e,t=0){this.awaitingBatchAck=!0;const n=t+Yse,r=e.slice(t,n);this.ajax("POST",{"Content-Type":"application/x-ndjson"},r.join(` 731`),()=>this.onerror("timeout"),a=>{!a||a.status!==200?(this.awaitingBatchAck=!1,this.onerror(a&&a.status),this.closeAndRetry(1011,"internal server error",!1)):n<e.length?this.batchSend(e,n):this.batchBuffer.length>0?(this.batchSend(this.batchBuffer),this.batchBuffer=[]):this.awaitingBatchAck=!1})}close(e,t,n){for(let a of this.reqs)a.abort();this.readyState=Vo.closed;let r=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:n});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<"u"?this.onclose(new CloseEvent("close",r)):this.onclose(r)}ajax(e,t,n,r,a){let i,o=()=>{this.reqs.delete(i),r()};i=eb.request(e,this.endpointURL(),t,n,this.timeout,o,l=>{this.reqs.delete(i),this.isActive()&&a(l)}),this.reqs.add(i)}},Qse=class Dm{constructor(t,n={}){let r=n.events||{state:"presence_state",diff:"presence_diff"};this.state=Object.create(null),this.pendingDiffs=[],this.channel=t,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(r.state,a=>{let{onJoin:i,onLeave:o,onSync:l}=this.caller;this.joinRef=this.channel.joinRef(),this.state=Dm.syncState(this.state,a,i,o),this.pendingDiffs.forEach(c=>{this.state=Dm.syncDiff(this.state,c,i,o)}),this.pendingDiffs=[],l()}),this.channel.on(r.diff,a=>{let{onJoin:i,onLeave:o,onSync:l}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(a):(this.state=Dm.syncDiff(this.state,a,i,o),l())})}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}list(t){return Dm.list(this.state,t)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(t,n,r,a){let i=this.toNullProtoObj(this.clone(t));n=this.toNullProtoObj(n);let o=Object.create(null),l=Object.create(null);return this.map(i,(c,u)=>{n[c]||(l[c]=u)}),this.map(n,(c,u)=>{let d=i[c];if(d){let h=u.metas.map(g=>g.phx_ref),f=d.metas.map(g=>g.phx_ref),m=u.metas.filter(g=>f.indexOf(g.phx_ref)<0),x=d.metas.filter(g=>h.indexOf(g.phx_ref)<0);m.length>0&&(o[c]=u,o[c].metas=m),x.length>0&&(l[c]=this.clone(d),l[c].metas=x)}else o[c]=u}),this.syncDiff(i,{joins:o,leaves:l},r,a)}static syncDiff(t,n,r,a){t=this.toNullProtoObj(t);let{joins:i,leaves:o}=this.clone(n);return r||(r=function(){}),a||(a=function(){}),this.map(i,(l,c)=>{let u=t[l];if(t[l]=this.clone(c),u){let d=t[l].metas.map(f=>f.phx_ref),h=u.metas.filter(f=>d.indexOf(f.phx_ref)<0);t[l].metas.unshift(...h)}r(l,u,c)}),this.map(o,(l,c)=>{let u=t[l];if(!u)return;let d=c.metas.map(h=>h.phx_ref);u.metas=u.metas.filter(h=>d.indexOf(h.phx_ref)<0),a(l,u,c),u.metas.length===0&&delete t[l]}),t}static list(t,n){return n||(n=function(r,a){return a}),this.map(t,(r,a)=>n(r,a))}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static toNullProtoObj(t){if(Object.getPrototypeOf(t)===null)return t;let n=Object.create(null);return Object.getOwnPropertyNames(t).forEach(r=>{n[r]=t[r]}),n}static clone(t){return JSON.parse(JSON.stringify(t))}},ag={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[n,r,a,i,o]=JSON.parse(e);return t({join_ref:n,ref:r,topic:a,event:i,payload:o})}},binaryEncode(e){let{join_ref:t,ref:n,event:r,topic:a,payload:i}=e,o=new TextEncoder,l=o.encode(t),c=o.encode(n),u=o.encode(a),d=o.encode(r);this.assertFieldSize(l.byteLength,"join_ref"),this.assertFieldSize(c.byteLength,"ref"),this.assertFieldSize(u.byteLength,"topic"),this.assertFieldSize(d.byteLength,"event");let h=this.META_LENGTH+l.byteLength+c.byteLength+u.byteLength+d.byteLength,f=new ArrayBuffer(this.HEADER_LENGTH+h),m=new Uint8Array(f),x=new DataView(f),g=0;x.setUint8(g++,this.KINDS.push),x.setUint8(g++,l.byteLength),x.setUint8(g++,c.byteLength),x.setUint8(g++,u.byteLength),x.setUint8(g++,d.byteLength),m.set(l,g),g+=l.byteLength,m.set(c,g),g+=c.byteLength,m.set(u,g),g+=u.byteLength,m.set(d,g),g+=d.byteLength;var y=new Uint8Array(f.byteLength+i.byteLength);return y.set(m,0),y.set(new Uint8Array(i),f.byteLength),y.buffer},assertFieldSize(e,t){if(e>255)throw new Error(`unable to convert ${t} to binary: must be less than or equal to 255 bytes, but is ${e} bytes`)},binaryDecode(e){let t=new DataView(e),n=t.getUint8(0),r=new TextDecoder;switch(n){case this.KINDS.push:return this.decodePush(e,t,r);case this.KINDS.reply:return this.decodeReply(e,t,r);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,r)}},decodePush(e,t,n){let r=t.getUint8(1),a=t.getUint8(2),i=t.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,l=n.decode(e.slice(o,o+r));o=o+r;let c=n.decode(e.slice(o,o+a));o=o+a;let u=n.decode(e.slice(o,o+i));o=o+i;let d=e.slice(o,e.byteLength);return{join_ref:l,ref:null,topic:c,event:u,payload:d}},decodeReply(e,t,n){let r=t.getUint8(1),a=t.getUint8(2),i=t.getUint8(3),o=t.getUint8(4),l=this.HEADER_LENGTH+this.META_LENGTH,c=n.decode(e.slice(l,l+r));l=l+r;let u=n.decode(e.slice(l,l+a));l=l+a;let d=n.decode(e.slice(l,l+i));l=l+i;let h=n.decode(e.slice(l,l+o));l=l+o;let f=e.slice(l,e.byteLength),m={status:h,response:f};return{join_ref:c,ref:u,topic:d,event:Al.reply,payload:m}},decodeBroadcast(e,t,n){let r=t.getUint8(1),a=t.getUint8(2),i=this.HEADER_LENGTH+2,o=n.decode(e.slice(i,i+r));i=i+r;let l=n.decode(e.slice(i,i+a));i=i+a;let c=e.slice(i,e.byteLength);return{join_ref:null,ref:null,topic:o,event:l,payload:c}}},eae=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||qse,this.transport=t.transport||Ho.WebSocket||qd,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null;let n=null;try{n=Ho&&Ho.sessionStorage}catch{}this.sessionStore=t.sessionStorage||n,this.establishedConnections=0,this.defaultEncoder=ag.encode.bind(ag),this.defaultDecoder=ag.decode.bind(ag),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||"arraybuffer",this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport!==qd?(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder):(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder);let r=null;gh&&gh.addEventListener&&(gh.addEventListener("pagehide",a=>{this.conn&&(this.disconnect(),r=this.connectClock)}),gh.addEventListener("pageshow",a=>{r===this.connectClock&&(r=null,this.connect())}),gh.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=t.autoSendHeartbeat??!0,this.heartbeatCallback=t.heartbeatCallback??(()=>{}),this.rejoinAfterMs=a=>t.rejoinAfterMs?t.rejoinAfterMs(a):[1e3,2e3,5e3][a-1]||1e4,this.reconnectAfterMs=a=>t.reconnectAfterMs?t.reconnectAfterMs(a):[10,50,100,150,200,250,500,1e3,2e3][a-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(a,i,o)=>{console.log(`${a}: ${i}`,o)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=Ih(t.params||{}),this.endPoint=`${e}/${lN.websocket}`,this.vsn=t.vsn||Vse,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new jF(()=>{if(this.pageHidden){this.log("Not reconnecting as page is hidden!"),this.teardown();return}this.teardown(async()=>{t.beforeReconnect&&await t.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=t.authToken&&Ih(t.authToken)}getLongPollTransport(){return qd}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&(this.conn.close(),this.conn=null),this.transport=e}protocol(){return location.protocol.match(/^https/)?"wss":"ws"}endPointURL(){let e=eb.appendParams(eb.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return e.charAt(0)!=="/"?e:e.charAt(1)==="/"?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`}disconnect(e,t,n){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,n)}connect(e){e&&(console&&console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"),this.params=Ih(e)),!(this.conn&&!this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==qd?this.connectWithFallback(qd,this.longPollFallbackMs):this.transportConnect())}log(e,t,n){this.logger&&this.logger(e,t,n)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),n=Date.now();this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:t});let r=this.onMessage(a=>{a.ref===t&&(this.off([r]),e(Date.now()-n))});return!0}transportName(e){switch(e){case qd:return"LongPoll";default:return e.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let e;this.authToken&&(e=["phoenix",`${cN}${btoa(this.authToken()).replace(/=/g,"")}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=t=>this.onConnError(t),this.conn.onmessage=t=>this.onConnMessage(t),this.conn.onclose=t=>this.onConnClose(t)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let n=!1,r=!0,a,i,o=this.transportName(e),l=c=>{this.log("transport",`falling back to ${o}...`,c),this.off([a,i]),r=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return l("memorized");this.fallbackTimer=setTimeout(l,t),i=this.onError(c=>{this.log("transport","error",c),r&&!n&&(clearTimeout(this.fallbackTimer),l(c))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(n=!0,!r){let c=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${c}`,"true"),this.log("transport",`established ${c} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(l,t),this.ping(c=>{this.log("transport","connected to primary after",c),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log("transport",`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks("open")}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log("transport","heartbeat timeout. Attempting to re-establish connection");try{this.heartbeatCallback("timeout")}catch(e){this.log("error","error in heartbeat callback",e)}this.triggerChanError(new Error("heartbeat timeout")),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),Gse,"heartbeat timeout")}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,n){if(!this.conn)return e&&e();const r=this.conn;this.waitForBufferDone(r,()=>{t?r.close(t,n||""):r.close(),this.waitForSocketClosed(r,()=>{this.conn===r&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t,n=1){if(n===5||!e.bufferedAmount){t();return}setTimeout(()=>{this.waitForBufferDone(e,t,n+1)},150*n)}waitForSocketClosed(e,t,n=1){if(n===5||e.readyState===Vo.closed){t();return}setTimeout(()=>{this.waitForSocketClosed(e,t,n+1)},150*n)}onConnClose(e){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log("transport","close",e),this.triggerChanError(e),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks("close",e)}onConnError(e){this.hasLogger()&&this.log("transport","error",e);let t=this.transport,n=this.establishedConnections;this.triggerStateCallbacks("error",e,t,n),(t===this.transport||n>0)&&this.triggerChanError(e)}
731triggerChanError(e){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(Al.error,e)})}connectionState(){switch(this.conn&&this.conn.readyState){case Vo.connecting:return"connecting";case Vo.open:return"open";case Vo.closing:return"closing";default:return"closed"}}isConnected(){return this.connectionState()==="open"}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([n])=>e.indexOf(n)===-1)}channel(e,t={}){let n=new Xse(e,t,this);return this.channels.push(n),n}push(e){if(this.hasLogger()){let{topic:t,event:n,payload:r,ref:a,join_ref:i}=e;this.log("push",`${t} ${n} (${i}, ${a})`,r)}this.isConnected()?this.encode(e,t=>this.conn.send(t)):this.sendBuffer.push(()=>this.encode(e,t=>this.conn.send(t)))}makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}sendHeartbeat(){if(!this.isConnected()){try{this.heartbeatCallback("disconnected")}catch(e){this.log("error","error in heartbeat callback",e)}return}if(this.pendingHeartbeatRef){this.heartbeatTimeout();return}this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback("sent")}catch(e){this.log("error","error in heartbeat callback",e)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,t=>{let{topic:n,event:r,payload:a,ref:i,join_ref:o}=t;if(i&&i===this.pendingHeartbeatRef){const l=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(a.status==="ok"?"ok":"error",l)}catch(c){this.log("error","error in heartbeat callback",c)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log("receive",`${a.status||""} ${n} ${r} ${i&&"("+i+")"||""}`.trim(),a);for(let l=0;l<this.channels.length;l++){const c=this.channels[l];c.isMember(n,r,a,o)&&c.trigger(r,a,i,o)}this.triggerStateCallbacks("message",t)})}triggerStateCallbacks(e,...t){try{this.stateChangeCallbacks[e].forEach(([n,r])=>{try{r(...t)}catch(a){this.log("error",`error in ${e} callback`,a)}})}catch(n){this.log("error",`error triggering ${e} callbacks`,n)}}leaveOpenTopic(e){let t=this.channels.find(n=>n.topic===e&&(n.isJoined()||n.isJoining()));t&&(this.hasLogger()&&this.log("transport",`leaving duplicate topic "${e}"`),t.leave())}};class Ym{constructor(t,n){const r=nae(n);this.presence=new Qse(t.getChannel(),r),this.presence.onJoin((a,i,o)=>{const l=Ym.onJoinPayload(a,i,o);t.getChannel().trigger("presence",l)}),this.presence.onLeave((a,i,o)=>{const l=Ym.onLeavePayload(a,i,o);t.getChannel().trigger("presence",l)}),this.presence.onSync(()=>{t.getChannel().trigger("presence",{event:"sync"})})}get state(){return Ym.transformState(this.presence.state)}static transformState(t){return t=tae(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const a=t[r];return n[r]=jy(a),n},{})}static onJoinPayload(t,n,r){const a=eO(n),i=jy(r);return{event:"join",key:t,currentPresences:a,newPresences:i}}static onLeavePayload(t,n,r){const a=eO(n),i=jy(r);return{event:"leave",key:t,currentPresences:a,leftPresences:i}}}function jy(e){return e.metas.map(t=>{const n=Object.getOwnPropertyDescriptors(t),r=Object.defineProperties({},n);return r.presence_ref=r.phx_ref,delete r.phx_ref,delete r.phx_ref_prev,r})}function tae(e){return JSON.parse(JSON.stringify(e))}function nae(e){return(e==null?void 0:e.events)&&{events:e.events}}function eO(e){return e!=null&&e.metas?jy(e):[]}var tO;(function(e){e.SYNC="sync",e.JOIN="join",e.LEAVE="leave"})(tO||(tO={}));class rae{get state(){return this.presenceAdapter.state}constructor(t,n){this.channel=t,this.presenceAdapter=new Ym(this.channel.channelAdapter,n)}}function sae(e){if(e instanceof Error)return e;if(typeof e=="string")return new Error(e);
731if(e&&typeof e=="object"){const t=e;if(typeof t.code=="number"){const n=typeof t.reason=="string"&&t.reason?` (${t.reason})`:"";return new Error(`socket closed: ${t.code}${n}`,{cause:e})}return new Error("channel error: transport failure",{cause:e})}return new Error("channel error: connection lost")}class aae{constructor(t,n,r){const a=iae(r);this.channel=t.getSocket().channel(n,a),this.socket=t}get state(){return this.channel.state}set state(t){this.channel.state=t}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(t,n){return this.channel.on(t,n)}off(t,n){this.channel.off(t,n)}subscribe(t){return this.channel.join(t)}unsubscribe(t){return this.channel.leave(t)}teardown(){this.channel.teardown()}onClose(t){this.channel.onClose(t)}onError(t){return this.channel.onError(t)}push(t,n,r){let a;try{a=this.channel.push(t,n,r)}catch{throw new Error(`tried to push '${t}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>$se){const i=this.channel.pushBuffer.shift();i.cancelTimeout(),this.socket.log("channel",`discarded push due to buffer overflow: ${i.event}`,i.payload())}return a}updateJoinPayload(t){const n=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},n),t)}canPush(){return this.socket.isConnected()&&this.state===Mc.joined}isJoined(){return this.state===Mc.joined}isJoining(){return this.state===Mc.joining}isClosed(){return this.state===Mc.closed}
731isLeaving(){return this.state===Mc.leaving}updateFilterBindings(t){this.channel.filterBindings=t}updatePayloadTransform(t){this.channel.onMessage=t}getChannel(){return this.channel}}function iae(e){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},e.config)}}const oae=/[,()"\\]/,lae=e=>oae.test(e)||e!==e.trim(),cae=e=>`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`,nO=e=>{const t=e===null?"null":String(e);return lae(t)?cae(t):t},uae=e=>e===null?"null":String(e),dae=(e,t)=>{if(e==="in"){const n=Array.isArray(t)?t:[t];if(n.length===0)throw new Error("Realtime `in` filter requires at least one value.");return`in.(${Array.from(new Set(n)).map(a=>nO(a)).join(",")})`}return e==="is"?`is.${uae(t)}`:`${e}.${nO(t)}`};class hae{constructor(){this.filters=[]}add(t,n,r,a=!1){const i=a?"not.":"";return this.filters.push(`${t}=${i}${dae(n,r)}`),this}eq(t,n){return this.add(t,"eq",n)}neq(t,n){return this.add(t,"neq",n)}gt(t,n){return this.add(t,"gt",n)}gte(t,n){return this.add(t,"gte",n)}lt(t,n){return this.add(t,"lt",n)}lte(t,n){return this.add(t,"lte",n)}in(t,n){return this.add(t,"in",n)}like(t,n){return this.add(t,"like",n)}ilike(t,n){return this.add(t,"ilike",n)}match(t,n){return this.add(t,"match",n)}imatch(t,n){return this.add(t,"imatch",n)}is(t,n){return this.add(t,"is",n)}isDistinct(t,n){return this.add(t,"isdistinct",n)}not(t,n,r){return this.add(t,n,r,!0)}build(){return this.filters.join(",")}toString(){return this.build()}}var rO;(function(e){e.ALL="*",e.INSERT="INSERT",e.UPDATE="UPDATE",e.DELETE="DELETE"})(rO||(rO={}));var Yu;(function(e){e.BROADCAST="broadcast",e.PRESENCE="presence",e.POSTGRES_CHANGES="postgres_changes",e.SYSTEM="system"})(Yu||(Yu={}));var Tl;(function(e){e.SUBSCRIBED="SUBSCRIBED",e.TIMED_OUT="TIMED_OUT",e.CLOSED="CLOSED",e.CHANNEL_ERROR="CHANNEL_ERROR"})(Tl||(Tl={}));class Ol{get state(){return this.channelAdapter.state}set state(t){this.channelAdapter.state=t}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(t,n={config:{}},r){var a,i;if(this.topic=t,this.params=n,this.socket=r,this.bindings={},this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:"",enabled:!1},private:!1},n.config),this.channelAdapter=new aae(this.socket.socketAdapter,t,this.params),this.presence=new rae(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=kF(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&(!((i=(a=this.params.config)===null||a===void 0?void 0:a.broadcast)===null||i===void 0)&&i.replay))throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(t,n=this.timeout){var r,a,i;if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){const{config:{broadcast:o,presence:l,private:c}}=this.params,u=(a=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(m=>m.filter))!==null&&a!==void 0?a:[],d=!!this.bindings[Yu.PRESENCE]&&this.bindings[Yu.PRESENCE].length>0||((i=this.params.config.presence)===null||i===void 0?void 0:i.enabled)===!0,h={},f={broadcast:o,presence:Object.assign(Object.assign({},l),{enabled:d}),postgres_changes:u,private:c};this.socket.accessTokenValue&&(h.access_token=this.socket.accessTokenValue),this._onError(m=>{t==null||t(Tl.CHANNEL_ERROR,sae(m))}),this._onClose(()=>t==null?void 0:t(Tl.CLOSED)),this.updateJoinPayload(Object.assign({config:f},h)),this._updateFilterMessage(),this.channelAdapter.subscribe(n).receive("ok",async({postgres_changes:m})=>{if(this.socket._isManualToken()||this.socket.setAuth(),m===void 0){t==null||t(Tl.SUBSCRIBED);return}this._updatePostgresBindings(m,t)}).receive("error",m=>{this.state=Mc.errored;const x=Object.values(m).join(", ")||"error";t==null||t(Tl.CHANNEL_ERROR,new Error(x,{cause:m}))}).receive("timeout",()=>{t==null||t(Tl.TIMED_OUT)})}return this}_updatePostgresBindings(t,n){var r;const a=this.bindings.postgres_changes,i=(r=a==null?void 0:a.length)!==null&&r!==void 0?r:0,o=[];for(let l=0;l<i;l++){const c=a[l],{filter:{event:u,schema:d,table:h,filter:f}}=c,m=t&&t[l];if(m&&m.event===u&&Ol.isFilterValueEqual(m.schema,d)&&Ol.isFilterValueEqual(m.table,h)&&Ol.isFilterValueEqual(m.filter,f))o.push(Object.assign(Object.assign({},c),{id:m.id}));else{this.unsubscribe(),this.state=Mc.errored,n==null||n(Tl.CHANNEL_ERROR,new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=o,this.state!=Mc.errored&&n&&n(Tl.SUBSCRIBED)}presenceState(){return this.presence.state}async track(t,n={}){return await this.send({type:"presence",event:"track",payload:t},n)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,n,r){const a=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=t===Yu.PRESENCE||t===Yu.POSTGRES_CHANGES;if(a&&i)throw this.socket.log("channel",`cannot add \`${t}\` callbacks for ${this.topic} after \`subscribe()\`.`),new Error(`cannot add \`${t}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(t,n,r)}async httpSend(t,n,r={}){var a;if(n==null)return Promise.reject(new Error("Payload is required for httpSend()"));const i=n instanceof ArrayBuffer||ArrayBuffer.isView(n),o={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":i?"application/octet-stream":"application/json"};this.socket.accessTokenValue&&(o.Authorization=`Bearer ${this.socket.accessTokenValue}`);const l=new URL(this.broadcastEndpointURL);l.pathname+=`/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(t)}`,this.private&&l.searchParams.set("private","true");const c={method:"POST",headers:o,body:i?n:JSON.stringify(n)},u=await this._fetchWithTimeout(l.toString(),c,(a=r.timeout)!==null&&a!==void 0?a:this.timeout);if(u.status===202)return{success:!0};if(u.status===404)return Promise.reject(new Error("httpSend() requires Realtime server v2.97.0 or newer; the endpoint returned 404. Update your Supabase CLI to a recent version, or upgrade the Realtime server in your self-hosted setup. See https://github.com/supabase/supabase-js/blob/master/packages/core/realt
731ime-js/migrations/httpsend-server-version.md"));let d=u.statusText;try{const h=await u.json();d=h.error||h.message||d}catch{}return Promise.reject(new Error(d))}async send(t,n={}){var r,a;if(!this.channelAdapter.canPush()&&t.type==="broadcast"){console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.");const{event:i,payload:o}=t,l={apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"};this.socket.accessTokenValue&&(l.Authorization=`Bearer ${this.socket.accessTokenValue}`);const c={method:"POST",headers:l,body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:o,private:this.private}]})};try{const u=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(r=n.timeout)!==null&&r!==void 0?r:this.timeout);return await((a=u.body)===null||a===void 0?void 0:a.cancel()),u.ok?"ok":"error"}catch(u){return u instanceof Error&&u.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var o,l,c;const u=this.channelAdapter.push(t.type,t,n.timeout||this.timeout);t.type==="broadcast"&&!(!((c=(l=(o=this.params)===null||o===void 0?void 0:o.config)===null||l===void 0?void 0:l.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),u.receive("ok",()=>i("ok")),u.receive("error",()=>i("error")),u.receive("timeout",()=>i("timed out"))})}updateJoinPayload(t){this.channelAdapter.updateJoinPayload(t)}async unsubscribe(t=this.timeout){return new Promise(n=>{this.channelAdapter.unsubscribe(t).receive("ok",()=>n("ok")).receive("timeout",()=>n("timed out")).receive("error",()=>n("error"))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(t,n,r){const a=new AbortController,i=setTimeout(()=>a.abort(),r),o=await this.socket.fetch(t,Object.assign(Object.assign({},n),{signal:a.signal}));return clearTimeout(i),o}_on(t,n,r){var a;const i=t.toLocaleLowerCase(),o=n==null?void 0:n.filter;if((o instanceof hae||typeof o=="object"&&o!==null&&typeof o.build=="function")&&(n=Object.assign(Object.assign({},n),{filter:o.build()})),i===Yu.POSTGRES_CHANGES&&((a=this.bindings[i])===null||a===void 0?void 0:a.find(d=>Ol.isSamePostgresFilter(d.filter,n))))return this.socket.log("error",`duplicate \`postgres_changes\` binding for ${this.topic} ignored`,n),this;const l=this.channelAdapter.on(t,r),c={type:i,filter:n,callback:r,ref:l};return this.bindings[i]?this.bindings[i].push(c):this.bindings[i]=[c],this._updateFilterMessage(),this}_onClose(t){this.channelAdapter.onClose(t)}_onError(t){this.channelAdapter.onError(t)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((t,n,r)=>{var a,i,o,l,c,u,d;const h=t.event.toLocaleLowerCase();if(this._notThisChannelEvent(h,r))return!1;const f=(a=this.bindings[h])===null||a===void 0?void 0:a.find(m=>m.ref===t.ref);if(!f)return!0;if(["broadcast","presence","postgres_changes"].includes(h))if("id"in f){const m=f.id,x=(i=f.filter)===null||i===void 0?void 0:i.event;return m&&((o=n.ids)===null||o===void 0?void 0:o.includes(m))&&(x==="*"||(x==null?void 0:x.toLocaleLowerCase())===((l=n.data)===null||l===void 0?void 0:l.type.toLocaleLowerCase()))}else{const m=(u=(c=f==null?void 0:f.filter)===null||c===void 0?void 0:c.event)===null||u===void 0?void 0:u.toLocaleLowerCase();return m==="*"||m===((d=n==null?void 0:n.event)===null||d===void 0?void 0:d.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===h})}_notThisChannelEvent(t,n){const{close:r,error:a,leave:i,join:o}=wF;return n&&[r,a,i,o].includes(t)&&n!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((t,n,r)=>{if(typeof n=="object"&&"ids"in n){const a=n.data,{schema:i,table:o,commit_timestamp:l,type:c,errors:u}=a;return Object.assign(Object.assign({},{schema:i,table:o,commit_timestamp:l,eventType:c,new:{},old:{},errors:u}),this._getPayloadRecords(a))}return n})}copyBindings(t){if(this.joinedOnce)throw new Error("cannot copy bindings into joined channel");for(const n in t.bindings)for(const r of t.bindings[n])this._on(r.type,r.filter,r.callback)}static isFilterValueEqual(t,n){return(t??void 0)===(n??void 0)}static isSamePostgresFilter(t,n){var r,a,i,o;const l=(a=(r=t==null?void 0:t.select)===null||r===void 0?void 0:r.join())!==null&&a!==void 0?a:void 0,c=(o=(i=n==null?void 0:n.select)===null||i===void 0?void 0:i.join())!==null&&o!==void 0?o:void 0;return(t==null?void 0:t.event)===(n==null?void 0:n.event)&&Ol.isFilterValueEqual(t==null?void 0:t.schema,n==null?void 0:n.schema)&&Ol.isFilterValueEqual(t==null?void 0:t.table,n==null?void 0:n.table)&&Ol.isFilterValueEqual(t==null?void 0:t.filter,n==null?void 0:n.filter)&&l===c}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=QT(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=QT(t.columns,t.old_record)),n}}class fae{constructor(t,n){this.socket=new eae(t,n)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(t){this.socket.heartbeatCallback=t}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(t,n,r,a=1e4){return new Promise(i=>{setTimeout(()=>i("timeout"),a),this.socket.disconnect(()=>{t(),i("ok")},n,r)})}push(t){this.socket.push(t)}log(t,n,r){this.socket.log(t,n,r)}makeRef(){return this.socket.makeRef()}onOpen(t){this.socket.onOpen(t)}onClose(t){this.socket.onClose(t)}onError(t){this.socket.onError(t)}onMessage(t){this.socket.onMessage(t)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==iN.connecting}isDisconnecting(){return this.socket.connectionState()==iN.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}const sO={HEARTBEAT_INTERVAL:25e3},mae=[1e3,2e3,5e3,1e4],pae=1e4;function xae(){const e=new Map;return{get length(){return e.size},clear(){e.clear()},getItem(t){return e.has(t)?e.get(t):null},key(t){var n;return(n=Array.from(e.keys())[t])!==null&&n!==void 0?n:null},removeItem(t){e.delete(t)},setItem(t,n){e.set(t,String(n))}}}function gae(){try{if(typeof globalThis<"u"&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return xae()}const yae=` 732 addEventListener("message", (e) => { 733 if (e.data.event === "start") { 734 setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); 735 } 736 });`;class bae{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(t,n){var r;if(this.channels=new Array,this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint="",this.headers={},this.params={}
736,this.ref=0,this.serializer=new Lse,this._manuallySetToken=!1,this._authPromise=null,this._authGeneration=0,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=i=>i?(...o)=>i(...o):(...o)=>fetch(...o),!(!((r=n==null?void 0:n.params)===null||r===void 0)&&r.apikey))throw new Error("API key is required to connect to Realtime");this.apiKey=n.params.apikey;const a=this._initializeOptions(n);this.socketAdapter=new fae(t,a),this.httpEndpoint=kF(t),this.fetch=this._resolveFetch(n==null?void 0:n.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely("connect"),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(t){const n=t.message;throw new Error(`WebSocket not available: ${n}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(t,n){return this._cancelPendingDisconnect(),this.isDisconnecting()?"ok":await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},t,n)}getChannels(){return this.channels}async removeChannel(t){const n=await t.unsubscribe();return n==="ok"&&t.teardown(),n}async removeAllChannels(){const t=this.channels.map(async r=>{const a=await r.unsubscribe();return r.teardown(),a}),n=await Promise.all(t);return await this.disconnect(),n}log(t,n,r){this.socketAdapter.log(t,n,r)}connectionState(){return this.socketAdapter.connectionState()||iN.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(t,n={config:{}}){const r=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===r);if(a)return a;{const i=new Ol(`realtime:${t}`,n,this);return this._cancelPendingDisconnect(),this.channels.push(i),i}}push(t){this.socketAdapter.push(t)}async setAuth(t=null){const n=++this._authGeneration,r=this._performAuth(t,n);n===this._authGeneration&&(this._authPromise=r);try{await r}finally{this._authPromise===r&&(this._authPromise=null)}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(t){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(t)}_makeRef(){return this.socketAdapter.makeRef()}_remove(t){this.channels=this.channels.filter(n=>n.topic!==t.topic),this.channels.length===0&&(this.log("transport","no channels remaining, scheduling disconnect"),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){if(this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0){this.log("transport","disconnecting immediately - no channels"),this.disconnect();return}
736this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log("transport","deferred disconnect fired - no channels, disconnecting"),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log("transport",`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`)}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log("transport","pending disconnect cancelled - channel activity detected"),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(t,n){let r,a=!1;if(t)r=t,a=!0;else if(this.accessToken)try{r=await this.accessToken()}catch(i){this.log("error","Error fetching access token from callback",i),r=this.accessTokenValue}else r=this.accessTokenValue;n===this._authGeneration&&(this.accessToken?this._manuallySetToken=!1:a&&(this._manuallySetToken=!0),this.accessTokenValue!=r&&(this.accessTokenValue=r,this.channels.forEach(i=>{const o={access_token:r,version:Pse};i.updateJoinPayload(o),i.joinedOnce&&i.channelAdapter.isJoined()&&i.channelAdapter.push(wF.access_token,{access_token:r})})))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(t="general"){this._isManualToken()||this.setAuth().catch(n=>{this.log("error",`Error setting auth in ${t}`,n)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(n=>{this.log("error","error waiting for auth on connect",n)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(t=>{t.ref&&t.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(t){return(n,r)=>{n!=="disconnected"&&(n=="sent"&&this._setAuthSafely(),t&&t(n,r))}}_startWorkerHeartbeat(){this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const t=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(t),this.workerRef.onerror=n=>{this.log("worker","worker error",n.message),this._terminateWorker(),this.disconnect()},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)}_workerObjectUrl(t){let n;if(t)n=t;else{const r=new Blob([yae],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}_initializeOptions(t){var n,r,a,i,o,l,c,u,d,h,f,m;this.worker=(n=t==null?void 0:t.worker)!==null&&n!==void 0?n:!1,this.accessToken=(r=t==null?void 0:t.accessToken)!==null&&r!==void 0?r:null;const x={};x.timeout=(a=t==null?void 0:t.timeout)!==null&&a!==void 0?a:Mse,x.heartbeatIntervalMs=(i=t==null?void 0:t.heartbeatIntervalMs)!==null&&i!==void 0?i:sO.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=(o=t==null?void 0:t.disconnectOnEmptyChannelsAfterMs)!==null&&o!==void 0?o:2*((l=t==null?void 0:t.heartbeatIntervalMs)!==null&&l!==void 0?l:sO.HEARTBEAT_INTERVAL),x.transport=(c=t==null?void 0:t.transport)!==null&&c!==void 0?c:Ose.getWebSocketConstructor(),x.params=t==null?void 0:t.params,x.logger=t==null?void 0:t.logger,x.heartbeatCallback=this._wrapHeartbeatCallback(t==null?void 0:t.heartbeatCallback),x.sessionStorage=(u=t==null?void 0:t.sessionStorage)!==null&&u!==void 0?u:gae(),x.reconnectAfterMs=(d=t==null?void 0:t.reconnectAfterMs)!==null&&d!==void 0?d:(v=>mae[v-1]||pae);let g,y;const b=(h=t==null?void 0:t.vsn)!==null&&h!==void 0?h:Dse;switch(b){case Rse:g=(v,w)=>w(JSON.stringify(v)),y=(v,w)=>w(JSON.parse(v));break;case vF:g=this.serializer.encode.bind(this.serializer),y=this.serializer.decode.bind(this.serializer);break;default:throw new Error(`Unsupported serializer version: ${x.vsn}`)}if(x.vsn=b,x.encode=(f=t==null?void 0:t.encode)!==null&&f!==void 0?f:g,x.decode=(m=t==null?void 0:t.decode)!==null&&m!==void 0?m:y,x.beforeReconnect=this._reconnectAuth.bind(this),(t!=null&&t.logLevel||t!=null&&t.log_level)&&(this.logLevel=t.logLevel||t.log_level,x.params=Object.assign(Object.assign({},x.params),{log_level:this.logLevel})),this.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.workerUrl=t==null?void 0:t.workerUrl,x.autoSendHeartbeat=!this.worker}return x}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}
736var fp=class extends Error{constructor(e,t){var n;super(e),this.name="IcebergError",this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown=t.icebergType==="CommitStateUnknownException"||[500,502,504].includes(t.status)&&((n=t.icebergType)==null?void 0:n.includes("CommitState"))===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function vae(e,t,n){const r=new URL(t,e);if(n)for(const[a,i]of Object.entries(n))i!==void 0&&r.searchParams.set(a,i);return r.toString()}async function wae(e){return!e||e.type==="none"?{}:e.type==="bearer"?{Authorization:`Bearer ${e.token}`}:e.type==="header"?{[e.name]:e.value}:e.type==="custom"?await e.getHeaders():{}}function _ae(e){const t=e.fetchImpl??globalThis.fetch;return{async request({method:n,path:r,query:a,body:i,headers:o}){const l=vae(e.baseUrl,r,a),c=await wae(e.auth),u=await t(l,{method:n,headers:{...i?{"Content-Type":"application/json"}:{},...c,...o},body:i?JSON.stringify(i):void 0}),d=await u.text(),h=(u.headers.get("content-type")||"").includes("application/json"),f=h&&d?JSON.parse(d):d;if(!u.ok){const m=h?f:void 0,x=m==null?void 0:m.error;throw new fp((x==null?void 0:x.message)??`Request failed with status ${u.status}`,{status:u.status,icebergType:x==null?void 0:x.type,icebergCode:x==null?void 0:x.code,details:m})}return{status:u.status,headers:u.headers,data:f}}}}function ig(e){return e.join("�")}var kae=class{constructor(e,t=""){this.client=e,this.prefix=t}async listNamespaces(e){const t=e?{parent:ig(e.namespace)}:void 0;return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(r=>({namespace:r}))}async createNamespace(e,t){const n={namespace:e.namespace,properties:t==null?void 0:t.properties};return(await this.client.request({method:"POST",path:`${this.prefix}/namespaces`,body:n})).data}async dropNamespace(e){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${ig(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${ig(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${ig(e.namespace)}`}),!0}catch(t){if(t instanceof fp&&t.status===404)return!1;throw t}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(n){if(n instanceof fp&&n.status===409)return;throw n}}};function Gd(e){return e.join("�")}var jae=class{constructor(e,t="",n){this.client=e,this.prefix=t,this.accessDelegation=n}async listTables(e){return(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Gd(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){const n={};return this.accessDelegation&&(n["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Gd(e.namespace)}/tables`,body:t,headers:n})).data.metadata}async updateTable(e,t){const n=await this.client.request({method:"POST",path:`${this.prefix}/namespaces/${Gd(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":n.data["metadata-location"],metadata:n.data.metadata}}async dropTable(e,t){await this.client.request({method:"DELETE",path:`${this.prefix}/namespaces/${Gd(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String((t==null?void 0:t.purge)??!1)}})}async loadTable(e){const t={};return this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation),(await this.client.request({method:"GET",path:`${this.prefix}/namespaces/${Gd(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){const t={};this.accessDelegation&&(t["X-Iceberg-Access-Delegation"]=this.accessDelegation);try{return await this.client.request({method:"HEAD",path:`${this.prefix}/namespaces/${Gd(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(n){if(n instanceof fp&&n.status===404)return!1;throw n}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(n){if(n instanceof fp&&n.status===409)return await this.loadTable({namespace:e.namespace,name:t.name});throw n}}},Nae=class{constructor(e){var r;let t="v1";e.catalogName&&(t+=`/${e.catalogName}`);const n=e.baseUrl.endsWith("/")?e.baseUrl:`${e.baseUrl}/`;this.client=_ae({baseUrl:n,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=(r=e.accessDelegation)==null?void 0:r.join(","),this.namespaceOps=new kae(this.client,t),this.tableOps=new jae(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}
736async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}};function mp(e){"@babel/helpers - typeof";return mp=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},mp(e)}function Sae(e,t){if(mp(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(mp(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Cae(e){var t=Sae(e,"string");return mp(t)=="symbol"?t:t+""}function Eae(e,t,n){return(t=Cae(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function aO(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Et(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?aO(Object(n),!0).forEach(function(r){Eae(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):aO(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var a0=class extends Error{constructor(t,n="storage",r,a){super(t),this.__isStorageError=!0,this.namespace=n,this.name=n==="vectors"?"StorageVectorsError":"StorageError",this.status=r,this.statusCode=a}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function i0(e){return typeof e=="object"&&e!==null&&"__isStorageError"in e}var uN=class extends a0{constructor(e,t,n,r="storage",a){super(e,r,t,n),this.name=r==="vectors"?"StorageVectorsApiError":"StorageApiError",this.status=t,this.statusCode=n,this.code=a}toJSON(){return Et(Et({},super.toJSON()),{},{code:this.code})}},NF=class extends a0{constructor(e,t,n="storage"){super(e,n),this.name=n==="vectors"?"StorageVectorsUnknownError":"StorageUnknownError",this.originalError=t}};function tb(e,t,n){const r=Et({},e),a=t.toLowerCase();for(const i of Object.keys(r))i.toLowerCase()===a&&delete r[i];return r[a]=n,r}function Aae(e){const t={};for(const[n,r]of Object.entries(e))t[n.toLowerCase()]=r;return t}const Tae=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),Oae=e=>{if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},dN=e=>{if(Array.isArray(e))return e.map(n=>dN(n));if(typeof e=="function"||e!==Object(e))return e;const t={};return Object.entries(e).forEach(([n,r])=>{const a=n.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));t[a]=dN(r)}),t},Iae=e=>!e||typeof e!="string"||e.length===0||e.length>100||e.trim()!==e||e.includes("/")||e.includes("\\")?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(e),SF=e=>e.split("/").map(encodeURIComponent).join("/"),iO=e=>{if(typeof e=="object"&&e!==null){const t=e;if(typeof t.msg=="string")return t.msg;if(typeof t.message=="string")return t.message;if(typeof t.error_description=="string")return t.error_description;if(typeof t.error=="string")return t.error;if(typeof t.error=="object"&&t.error!==null){const n=t.error;if(typeof n.message=="string")return n.message}}return JSON.stringify(e)},Pae=async(e,t,n,r)=>{if(e!==null&&typeof e=="object"&&"json"in e&&typeof e.json=="function"){const a=e;let i=parseInt(String(a.status),10);Number.isFinite(i)||(i=500),a.json().then(o=>{const l=(o==null?void 0:o.statusCode)||(o==null?void 0:o.code)||i+"";t(new uN(iO(o),i,l,r,o==null?void 0:o.code))}).catch(()=>{const o=i+"";t(new uN(a.statusText||`HTTP ${i} error`,i,o,r))})}else t(new NF(iO(e),e,r))},Rae=(e,t,n,r)=>{const a={method:e,headers:(t==null?void 0:t.headers)||{}};if(e==="GET"||e==="HEAD"||!r)return Et(Et({},a),n);if(Oae(r)){var i;const o=(t==null?void 0:t.headers)||{};let l;for(const[c,u]of Object.entries(o))c.toLowerCase()==="content-type"&&(l=u);a.headers=tb(o,"Content-Type",(i=l)!==null&&i!==void 0?i:"application/json"),a.body=JSON.stringify(r)}else a.body=r;return t!=null&&t.duplex&&(a.duplex=t.duplex),Et(Et({},a),n)};async function Qf(e,t,n,r,a,i,o){return new Promise((l,c)=>{e(n,Rae(t,r,a,i)).then(u=>{if(!u.ok)throw u;if(r!=null&&r.noResolveJson)return u;if(o==="vectors"){const d=u.headers.get("content-type");if(u.headers.get("content-length")==="0"||u.status===204)return{};if(!d||!d.includes("application/json"))return{}}return u.json()}).then(u=>l(u)).catch(u=>Pae(u,c,r,o))})}function CF(e="storage"){return{get:async(t,n,r,a)=>Qf(t,"GET",n,r,a,void 0,e),post:async(t,n,r,a,i)=>Qf(t,"POST",n,a,i,r,e),put:async(t,n,r,a,i)=>Qf(t,"PUT",n,a,i,r,e),head:async(t,n,r,a)=>Qf(t,"HEAD",n,Et(Et({},r),{},{noResolveJson:!0}),a,void 0,e),remove:async(t,n,r,a,i)=>Qf(t,"DELETE",n,a,i,r,e)}}const Dae=CF("storage"),{get:pp,post:ho,put:hN,head:Mae,remove:xp}=Dae,mi=CF("vectors");var bf=class{constructor(e,t={},n,r="storage"){this.shouldThrowOnError=!1,this.url=e,this.headers=Aae(t),this.fetch=Tae(n),this.namespace=r}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=tb(this.headers,e,t),this}async handleOperation(e){var t=this;try{return{data:await e(),error:null}}catch(n){if(t.shouldThrowOnError)throw n;if(i0(n))return{data:null,error:n};throw n}}};let EF;EF=Symbol.toStringTag;var $ae=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[EF]="StreamDownloadBuilder",this.promise=null}
736then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var e=this;try{return{data:(await e.downloadFn()).body,error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(i0(t))return{data:null,error:t};throw t}}};let AF;AF=Symbol.toStringTag;var Lae=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[AF]="BlobDownloadBuilder",this.promise=null}asStream(){return new $ae(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||(this.promise=this.execute()),this.promise}async execute(){var e=this;try{return{data:await(await e.downloadFn()).blob(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(i0(t))return{data:null,error:t};throw t}}};const Qw={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},oO={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};var Fae=class extends bf{constructor(e,t={},n,r){super(e,t,r,"storage"),this.bucketId=n}async uploadOrUpdate(e,t,n,r){var a=this;return a.handleOperation(async()=>{let i;const o=Et(Et({},oO),r);let l=Et(Et({},a.headers),e==="POST"&&{"x-upsert":String(o.upsert)});const c=o.metadata;if(typeof Blob<"u"&&n instanceof Blob?(i=new FormData,i.append("cacheControl",o.cacheControl),c&&i.append("metadata",a.encodeMetadata(c)),i.append("",n)):typeof FormData<"u"&&n instanceof FormData?(i=n,i.has("cacheControl")||i.append("cacheControl",o.cacheControl),c&&!i.has("metadata")&&i.append("metadata",a.encodeMetadata(c))):(i=n,l["cache-control"]=`max-age=${o.cacheControl}`,l["content-type"]=o.contentType,c&&(l["x-metadata"]=a.toBase64(a.encodeMetadata(c))),(typeof ReadableStream<"u"&&i instanceof ReadableStream||i&&typeof i=="object"&&"pipe"in i&&typeof i.pipe=="function")&&!o.duplex&&(o.duplex="half")),r!=null&&r.headers)for(const[f,m]of Object.entries(r.headers))l=tb(l,f,m);const u=a._removeEmptyFolders(t),d=a._getFinalPath(u),h=await(e=="PUT"?hN:ho)(a.fetch,`${a.url}/object/${d}`,i,Et({headers:l},o!=null&&o.duplex?{duplex:o.duplex}:{}));return{path:u,id:h.Id,fullPath:h.Key}})}async upload(e,t,n){return this.uploadOrUpdate("POST",e,t,n)}async uploadToSignedUrl(e,t,n,r){var a=this;const i=a._removeEmptyFolders(e),o=a._getFinalPath(i),l=new URL(a.url+`/object/upload/sign/${o}`);return l.searchParams.set("token",t),a.handleOperation(async()=>{let c;const u=Et(Et({},oO),r);let d=Et(Et({},a.headers),{"x-upsert":String(u.upsert)});const h=u.metadata;if(typeof Blob<"u"&&n instanceof Blob?(c=new FormData,c.append("cacheControl",u.cacheControl),h&&c.append("metadata",a.encodeMetadata(h)),c.append("",n)):typeof FormData<"u"&&n instanceof FormData?(c=n,c.has("cacheControl")||c.append("cacheControl",u.cacheControl),h&&!c.has("metadata")&&c.append("metadata",a.encodeMetadata(h))):(c=n,d["cache-control"]=`max-age=${u.cacheControl}`,d["content-type"]=u.contentType,h&&(d["x-metadata"]=a.toBase64(a.encodeMetadata(h))),(typeof ReadableStream<"u"&&c instanceof ReadableStream||c&&typeof c=="object"&&"pipe"in c&&typeof c.pipe=="function")&&!u.duplex&&(u.duplex="half")),r!=null&&r.headers)for(const[f,m]of Object.entries(r.headers))d=tb(d,f,m);return{path:i,fullPath:(await hN(a.fetch,l.toString(),c,Et({headers:d},u!=null&&u.duplex?{duplex:u.duplex}:{}))).Key}})}async createSignedUploadUrl(e,t){var n=this;return n.handleOperation(async()=>{let r=n._getFinalPath(e);const a=Et({},n.headers);t!=null&&t.upsert&&(a["x-upsert"]="true");const i=await ho(n.fetch,`${n.url}/object/upload/sign/${r}`,{},{headers:a}),o=new URL(n.url+i.url),l=o.searchParams.get("token");if(!l)throw new a0("No token returned by API");return{signedUrl:o.toString(),path:e,token:l}})}async update(e,t,n){return this.uploadOrUpdate("PUT",e,t,n)}async move(e,t,n){var r=this;return r.handleOperation(async()=>await ho(r.fetch,`${r.url}/object/move`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,de
736stinationBucket:n==null?void 0:n.destinationBucket},{headers:r.headers}))}async copy(e,t,n){var r=this;return r.handleOperation(async()=>({path:(await ho(r.fetch,`${r.url}/object/copy`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n==null?void 0:n.destinationBucket},{headers:r.headers})).Key}))}async createSignedUrl(e,t,n){var r=this;return r.handleOperation(async()=>{let a=r._getFinalPath(e);const i=typeof(n==null?void 0:n.transform)=="object"&&n.transform!==null&&Object.keys(n.transform).length>0;let o=await ho(r.fetch,`${r.url}/object/sign/${a}`,Et({expiresIn:t},i?{transform:n.transform}:{}),{headers:r.headers});const l=new URLSearchParams;n!=null&&n.download&&l.set("download",n.download===!0?"":n.download),(n==null?void 0:n.cacheNonce)!=null&&l.set("cacheNonce",String(n.cacheNonce));const c=l.toString();return{signedUrl:encodeURI(`${r.url}${o.signedURL}${c?`&${c}`:""}`)}})}async createSignedUrls(e,t,n){var r=this;return r.handleOperation(async()=>{const a=await ho(r.fetch,`${r.url}/object/sign/${r.bucketId}`,{expiresIn:t,paths:e},{headers:r.headers}),i=new URLSearchParams;n!=null&&n.download&&i.set("download",n.download===!0?"":n.download),(n==null?void 0:n.cacheNonce)!=null&&i.set("cacheNonce",String(n.cacheNonce));const o=i.toString();return a.map(l=>Et(Et({},l),{},{signedUrl:l.signedURL?encodeURI(`${r.url}${l.signedURL}${o?`&${o}`:""}`):null}))})}download(e,t,n){const r=typeof(t==null?void 0:t.transform)=="object"&&t.transform!==null&&Object.keys(t.transform).length>0?"render/image/authenticated":"object",a=new URLSearchParams;t!=null&&t.transform&&this.applyTransformOptsToQuery(a,t.transform),(t==null?void 0:t.cacheNonce)!=null&&a.set("cacheNonce",String(t.cacheNonce));const i=a.toString(),o=this._getFinalPath(e),l=()=>pp(this.fetch,`${this.url}/${r}/${o}${i?`?${i}`:""}`,{headers:this.headers,noResolveJson:!0},n);return new Lae(l,this.shouldThrowOnError)}async info(e){var t=this;const n=t._getFinalPath(e);return t.handleOperation(async()=>dN(await pp(t.fetch,`${t.url}/object/info/${n}`,{headers:t.headers})))}async exists(e){var t=this;const n=t._getFinalPath(e);try{return await Mae(t.fetch,`${t.url}/object/${n}`,{headers:t.headers}),{data:!0,error:null}}catch(a){if(t.shouldThrowOnError)throw a;if(i0(a)){var r;const i=a instanceof uN?a.status:a instanceof NF?(r=a.originalError)===null||r===void 0?void 0:r.status:void 0;if(i!==void 0&&[400,404].includes(i))return{data:!1,error:a}}throw a}}getPublicUrl(e,t){const n=this._getFinalPath(e),r=new URLSearchParams;t!=null&&t.download&&r.set("download",t.download===!0?"":t.download),t!=null&&t.transform&&this.applyTransformOptsToQuery(r,t.transform),(t==null?void 0:t.cacheNonce)!=null&&r.set("cacheNonce",String(t.cacheNonce));const a=r.toString(),i=typeof(t==null?void 0:t.transform)=="object"&&t.transform!==null&&Object.keys(t.transform).length>0?"render/image":"object";return{data:{publicUrl:encodeURI(`${this.url}/${i}/public/${n}`)+(a?`?${a}`:"")}}}async remove(e){var t=this;return t.handleOperation(async()=>await xp(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async purgeCache(e,t,n){var r=this;return r.handleOperation(async()=>{const a=SF(r._getFinalPath(e)),i=new URLSearchParams;t!=null&&t.transformations&&i.set("transformations","true");const o=i.toString();return await xp(r.fetch,`${r.url}/cdn/${a}${o?`?${o}`:""}`,{},{headers:r.headers},n)})}async list(e,t,n){var r=this;return r.handleOperation(async()=>{const a=t!=null&&t.sortBy?Et(Et({},Qw.sortBy),t.sortBy):Qw.sortBy,i=Et(Et(Et({},Qw),t),{},{sortBy:a,prefix:e||""});return await ho(r.fetch,`${r.url}/object/list/${r.bucketId}`,i,{headers:r.headers},n)})}async listV2(e,t){var n=this;return n.handleOperation(async()=>{const r=Et({},e);return await ho(n.fetch,`${n.url}/object/list-v2/${n.bucketId}`,r,{headers:n.headers},t)})}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<"u"?Buffer.from(e).toString("base64"):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,"")}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}applyTransformOptsToQuery(e,t){return t.width&&e.set("width",t.width.toString()),t.height&&e.set("height",t.height.toString()),t.resize&&e.set("resize",t.resize),t.format&&e.set("format",t.format),t.quality&&e.set("qual
736ity",t.quality.toString()),e}};const Bae="2.112.3",ox={"X-Client-Info":`storage-js/${Bae}`};var Uae=class extends bf{constructor(e,t={},n,r){const a=new URL(e);r!=null&&r.useNewHostname&&/supabase\.(co|in|red)$/.test(a.hostname)&&!a.hostname.includes("storage.supabase.")&&(a.hostname=a.hostname.replace("supabase.","storage.supabase."));const i=a.href.replace(/\/$/,""),o=Et(Et({},ox),t);super(i,o,n,"storage")}async listBuckets(e){var t=this;return t.handleOperation(async()=>{const n=t.listBucketOptionsToQueryString(e);return await pp(t.fetch,`${t.url}/bucket${n}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await pp(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var n=this;return n.handleOperation(async()=>await ho(n.fetch,`${n.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async updateBucket(e,t){var n=this;return n.handleOperation(async()=>await hN(n.fetch,`${n.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:n.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await ho(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await xp(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}async purgeBucketCache(e,t,n){var r=this;return r.handleOperation(async()=>{const a=new URLSearchParams;t!=null&&t.transformations&&a.set("transformations","true");const i=a.toString();return await xp(r.fetch,`${r.url}/cdn/${SF(e)}${i?`?${i}`:""}`,{},{headers:r.headers},n)})}listBucketOptionsToQueryString(e){const t={};return e&&("limit"in e&&(t.limit=String(e.limit)),"offset"in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?"?"+new URLSearchParams(t).toString():""}},zae=class extends bf{constructor(e,t={},n){const r=e.replace(/\/$/,""),a=Et(Et({},ox),t);super(r,a,n,"storage")}async createBucket(e){var t=this;return t.handleOperation(async()=>await ho(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{const n=new URLSearchParams;(e==null?void 0:e.limit)!==void 0&&n.set("limit",e.limit.toString()),(e==null?void 0:e.offset)!==void 0&&n.set("offset",e.offset.toString()),e!=null&&e.sortColumn&&n.set("sortColumn",e.sortColumn),e!=null&&e.sortOrder&&n.set("sortOrder",e.sortOrder),e!=null&&e.search&&n.set("search",e.search);const r=n.toString(),a=r?`${t.url}/bucket?${r}`:`${t.url}/bucket`;return await pp(t.fetch,a,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await xp(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!Iae(e))throw new a0("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 Nae({baseUrl:this.url,catalogName:e,auth:{type:"custom",getHeaders:async()=>t.headers},fetch:this.fetch}),r=this.shouldThrowOnError;return new Proxy(n,{get(a,i){const o=a[i];return typeof o!="function"?o:async(...l)=>{try{return{data:await o.apply(a,l),error:null}}catch(c){if(r)throw c;return{data:null,error:c}}}}})}},Wae=class extends bf{constructor(e,t={},n){const r=e.replace(/\/$/,""),a=Et(Et({},ox),{},{"Content-Type":"application/json"},t);super(r,a,n,"vectors")}async createIndex(e){var t=this;return t.handleOperation(async()=>await mi.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var n=this;return n.handleOperation(async()=>await mi.post(n.fetch,`${n.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await mi.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var n=this;return n.handleOperation(async()=>await mi.post(n.fetch,`${n.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers})||{})}},Kae=class extends bf{constructor(e,t={},n){const r=e.replace(/\/$/,""),a=Et(Et({},ox),{},{"Content-Type":"application/json"},t);super(r,a,n,"vectors")}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw new Error("Vector batch size must be between 1 and 500 items");return t.handleOperation(async()=>await mi.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await mi.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw new Error("segmentCount must be between 1 and 16");
736if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw new Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return t.handleOperation(async()=>await mi.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await mi.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw new Error("Keys batch size must be between 1 and 500 items");return t.handleOperation(async()=>await mi.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},Hae=class extends bf{constructor(e,t={},n){const r=e.replace(/\/$/,""),a=Et(Et({},ox),{},{"Content-Type":"application/json"},t);super(r,a,n,"vectors")}async createBucket(e){var t=this;return t.handleOperation(async()=>await mi.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await mi.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await mi.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await mi.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},Vae=class extends Hae{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new qae(this.url,this.headers,e,this.fetch)}async createBucket(e){var t=()=>super.createBucket,n=this;return t().call(n,e)}async getBucket(e){var t=()=>super.getBucket,n=this;return t().call(n,e)}async listBuckets(e={}){var t=()=>super.listBuckets,n=this;return t().call(n,e)}async deleteBucket(e){var t=()=>super.deleteBucket,n=this;return t().call(n,e)}},qae=class extends Wae{constructor(e,t,n,r){super(e,t,r),this.vectorBucketName=n}async createIndex(e){var t=()=>super.createIndex,n=this;return t().call(n,Et(Et({},e),{},{vectorBucketName:n.vectorBucketName}))}async listIndexes(e={}){var t=()=>super.listIndexes,n=this;return t().call(n,Et(Et({},e),{},{vectorBucketName:n.vectorBucketName}))}async getIndex(e){var t=()=>super.getIndex,n=this;return t().call(n,n.vectorBucketName,e)}async deleteIndex(e){var t=()=>super.deleteIndex,n=this;return t().call(n,n.vectorBucketName,e)}index(e){return new Gae(this.url,this.headers,this.vectorBucketName,e,this.fetch)}}
736,Gae=class extends Kae{constructor(e,t,n,r,a){super(e,t,a),this.vectorBucketName=n,this.indexName=r}async putVectors(e){var t=()=>super.putVectors,n=this;return t().call(n,Et(Et({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async getVectors(e){var t=()=>super.getVectors,n=this;return t().call(n,Et(Et({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async listVectors(e={}){var t=()=>super.listVectors,n=this;return t().call(n,Et(Et({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async queryVectors(e){var t=()=>super.queryVectors,n=this;return t().call(n,Et(Et({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async deleteVectors(e){var t=()=>super.deleteVectors,n=this;return t().call(n,Et(Et({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}},Yae=class extends Uae{constructor(e,t={},n,r){super(e,t,n,r)}from(e){return new Fae(this.url,this.headers,e,this.fetch)}get vectors(){return new Vae(this.url+"/vector",{headers:this.headers,fetch:this.fetch})}get analytics(){return new zae(this.url+"/iceberg",this.headers,this.fetch)}};const TF="2.112.3",Il=30*1e3,Mm=3,e1=Mm*Il,Zae=2*Il,Xae="http://localhost:9999",Jae="supabase.auth.token",Qae={"X-Client-Info":`gotrue-js/${TF}`},fN="X-Supabase-Api-Version",OF={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},eie=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Zu="sb_flow_id",tie=5,nie=600*1e3;
736class gp extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}}function at(e){return typeof e=="object"&&e!==null&&"__isAuthError"in e}class rie extends gp{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function lO(e){return at(e)&&e.name==="AuthApiError"}class mo extends gp{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class fl extends gp{constructor(t,n,r,a){super(t,r,a),this.name=n,this.status=r}}class xs extends fl{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function og(e){return at(e)&&e.name==="AuthSessionMissingError"}class Yd extends fl{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class lg extends fl{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class cg extends fl{constructor(t,n=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}function sie(e){return at(e)&&e.name==="AuthImplicitGrantRedirectError"}class cO extends fl{constructor(t,n=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}}class aie extends fl{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 Ny extends fl{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function ug(e){return at(e)&&e.name==="AuthRetryableFetchError"}class uO extends fl{constructor(t="Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)"){super(t,"AuthRefreshDiscardedError",409,void 0)}}function iie(e){return at(e)&&e.name==="AuthRefreshDiscardedError"}class dO extends fl{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}}class nb extends fl{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const rb="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),hO=` 737\r=`.split(""),oie=(()=>{const e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<hO.length;t+=1)e[hO[t].charCodeAt(0)]=-2;for(let t=0;t<rb.length;t+=1)e[rb[t].charCodeAt(0)]=t;return e})();function fO(e,t,n){if(e!==null)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){const r=t.queue>>t.queuedBits-6&63;n(rb[r]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){const r=t.queue>>t.queuedBits-6&63;n(rb[r]),t.queuedBits-=6}}function IF(e,t,n){const r=oie[e];if(r>-1)for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}}function mO(e){const t=[],n=o=>{t.push(String.fromCodePoint(o))},r={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=o=>{uie(o,r,n)};for(let o=0;o<e.length;o+=1)IF(e.charCodeAt(o),a,i);return t.join("")}function lie(e,t){if(e<=127){t(e);return}else if(e<=2047){t(192|e>>6),t(128|e&63);return}else if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|e&63);return}else if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);return}throw new Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function cie(e,t){for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(r>55295&&r<=56319){const a=(r-55296)*1024&65535;r=(e.charCodeAt(n+1)-56320&65535|a)+65536,n+=1}lie(r,t)}}function uie(e,t,n){if(t.utf8seq===0){if(e<=127){n(e);return}for(let r=1;r<6;r+=1)if((e>>7-r&1)===0){t.utf8seq=r;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw new Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|e&63,t.utf8seq-=1,t.utf8seq===0&&n(t.codepoint)}}function Ph(e){const t=[],n={queue:0,queuedBits:0},r=a=>{t.push(a)};for(let a=0;a<e.length;a+=1)IF(e.charCodeAt(a),n,r);return new Uint8Array(t)}function die(e){const t=[];return cie(e,n=>t.push(n)),new Uint8Array(t)}function Xu(e){const t=[],n={queue:0,queuedBits:0},r=a=>{t.push(a)};return e.forEach(a=>fO(a,n,r)),fO(null,n,r),t.join("")}function hie(e){return Math.round(Date.now()/1e3)+e}function fie(){return Symbol("auth-callback")}const Is=()=>typeof window<"u"&&typeof document<"u",Ou={tested:!1,writable:!1},PF=()=>
737{if(!Is())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ou.tested)return Ou.writable;const e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Ou.tested=!0,Ou.writable=!0}catch{Ou.tested=!0,Ou.writable=!1}return Ou.writable};function pO(e){const t={},n=new URL(e);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((a,i)=>{t[i]=a})}catch{}return n.searchParams.forEach((r,a)=>{t[a]=r}),t}const RF=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),mie=e=>typeof e=="object"&&e!==null&&"status"in e&&"ok"in e&&"json"in e&&typeof e.json=="function",Ll=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},Js=async(e,t)=>{const n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return null}},Ja=async(e,t)=>{await e.removeItem(t)};class o0{constructor(){this.promise=new o0.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}o0.promiseConstructor=Promise;function dg(e){const t=e.split(".");if(t.length!==3)throw new nb("Invalid JWT structure");for(let r=0;r<t.length;r++)if(!eie.test(t[r]))throw new nb("JWT not in base64url format");return{header:JSON.parse(mO(t[0])),payload:JSON.parse(mO(t[1])),signature:Ph(t[2]),raw:{header:t[0],payload:t[1]}}}async function pie(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function xie(e,t){return new Promise((r,a)=>{(async()=>{for(let i=0;i<1/0;i++)try{const o=await e(i);if(!t(i,null,o)){r(o);return}}catch(o){if(!t(i,o)){a(o);return}}})()})}function DF(e){return("0"+e.toString(16)).substr(-2)}function gie(){const t=new Uint32Array(56);if(typeof crypto>"u"){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=n.length;let a="";for(let i=0;i<56;i++)a+=n.charAt(Math.floor(Math.random()*r));return a}return crypto.getRandomValues(t),Array.from(t,DF).join("")}async function yie(e){const n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n),a=new Uint8Array(r);return Array.from(a).map(i=>String.fromCharCode(i)).join("")}async function bie(e){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;const n=await yie(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}const vie=/^[a-zA-Z0-9_-]{8,64}$/;function Sy(e){return typeof e=="string"&&vie.test(e)?e:null}function wie(){if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function"){const t=new Uint8Array(16);return crypto.getRandomValues(t),Array.from(t,DF).join("")}let e="";for(let t=0;t<32;t++)e+=Math.floor(Math.random()*16).toString(16);return e}const Hh=(e,t)=>`${e}-flow-${t}-code-verifier`,yp=e=>`${e}-flows-code-verifier`;async function Y2(e,t){const n=await Js(e,yp(t));return Array.isArray(n)?n.filter(r=>Sy(r)!==null):[]}async function _ie(e,t,n,r,a){await Ll(e,Hh(t,n),r);const i=(await Y2(e,t)).filter(o=>o!==n);for(i.push(n);i.length>tie;){const o=i.shift();await Ja(e,Hh(t,o)),a==null||a(o)}await Ll(e,yp(t),i),await Ll(e,`${t}-code-verifier`,r)}async function kie(e,t,n){if(n){const a=await Js(e,Hh(t,n));return{verifier:typeof a=="string"?a:null,flowId:n}}const r=await Js(e,`${t}-code-verifier`);return{verifier:typeof r=="string"?r:null,flowId:null}}async function ao(e,t,n){const r=`${t}-code-verifier`;if(!n){await Ja(e,r);return}const a=Hh(t,n),i=await Js(e,a);await Ja(e,a);const o=await Y2(e,t),l=o.filter(c=>c!==n);l.length!==o.length&&(l.length>0?await Ll(e,yp(t),l):await Ja(e,yp(t))),i!=null&&i===await Js(e,r)&&await Ja(e,r)}async function jie(e,t){const n=await Y2(e,t);for(const r of n)await Ja(e,Hh(t,r));await Ja(e,yp(t)),await Ja(e,`${t}-code-verifier`)}function Nie(e,t){const n=e.indexOf("#");let r=n===-1?e:e.slice(0,n);const a=n===-1?"":e.slice(n),i=r.indexOf("?");if(i!==-1){const l=r.slice(0,i),c=r.slice(i+1).split("&").filter(u=>u!==""&&u!==Zu&&!u.startsWith(`${Zu}=`));r=c.length>0?`${l}?${c.join("&")}`:l}const o=r.includes("?")?"&":"?";return`${r}${o}${Zu}=${encodeURIComponent(t)}${a}`}async function Sie(e,t,n=!1,r){const a=gie();let i=a;n&&(i+="/recovery");const o=wie();await _ie(e,t,o,i,r);const l=await bie(a);return[l,a===l?"plain":"s256",o]}const Cie=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Eie(e){const t=e.headers.get(fN);if(!t||!t.match(Cie))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function Aie(e){if(!e)throw new Error("Missing exp claim");const t=Math.floor(Date.now()/1e3);if(e<=t)throw new Error("JWT has expired")}function Tie(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}const Oie=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function kl(e){if(!Oie.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function uo(e){if(!e.passkey)throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function t1(){const e={};return new Proxy(e,{get:(t,n)=>{if(n==="__isUserNotAvailableProxy")return!0;
737if(typeof n=="symbol"){const r=n.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${n}" property of the session object is not supported. Please use getUser() instead.`)},set:(t,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:(t,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 Iie(e,t){return new Proxy(e,{get:(n,r,a)=>{if(r==="__isInsecureUserWarningProxy")return!0;if(typeof r=="symbol"){const i=r.toString();if(i==="Symbol(Symbol.toPrimitive)"||i==="Symbol(Symbol.toStringTag)"||i==="Symbol(util.inspect.custom)"||i==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(n,r,a)}return!t.value&&typeof r=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),t.value=!0),Reflect.get(n,r,a)}})}function xO(e){return JSON.parse(JSON.stringify(e))}const Ku=e=>{if(typeof e=="object"&&e!==null){const t=e;if(typeof t.msg=="string")return t.msg;if(typeof t.message=="string")return t.message;if(typeof t.error_description=="string")return t.error_description;if(typeof t.error=="string")return t.error}return JSON.stringify(e)},gO=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function yO(e){var t;if(!mie(e))throw new Ny(Ku(e),0);let n;try{n=await e.json()}catch(i){throw gO.includes(e.status)?new Ny(e.statusText||`HTTP ${e.status}`,e.status):new mo(Ku(i),i)}if(gO.includes(e.status))throw new Ny(Ku(n),e.status);let r;const a=Eie(e);if(a&&a.getTime()>=OF["2024-01-01"].timestamp&&typeof n=="object"&&n&&typeof n.code=="string"?r=n.code:typeof n=="object"&&n&&typeof n.error_code=="string"&&(r=n.error_code),r){if(r==="weak_password")throw new dO(Ku(n),e.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new xs}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((i,o)=>i&&typeof o=="string",!0))throw new dO(Ku(n),e.status,n.weak_password.reasons);throw new rie(Ku(n),e.status||500,r)}const Pie=(e,t,n,r)=>{const a={method:e,headers:(t==null?void 0:t.headers)||{}};return e==="GET"?a:(a.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),a.body=JSON.stringify(r),Object.assign(Object.assign({},a),n))};async function gt(e,t,n,r){var a;const i=Object.assign({},r==null?void 0:r.headers);i[fN]||(i[fN]=OF["2024-01-01"].name),r!=null&&r.jwt&&(i.Authorization=`Bearer ${r.jwt}`);const o=(a=r==null?void 0:r.query)!==null&&a!==void 0?a:{};r!=null&&r.redirectTo&&(o.redirect_to=r.redirectTo);const l=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",c=await Rie(e,t,n+l,{headers:i,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(c):{data:Object.assign({},c),error:null}}async function Rie(e,t,n,r,a,i){const o=Pie(t,r,a,i);let l;try{l=await e(n,Object.assign({},o))}catch(c){throw new Ny(Ku(c),0)}if(l.ok||await yO(l),r!=null&&r.noResolveJson)return l;try{return await l.json()}catch(c){await yO(c)}}function Ii(e){var t;let n=null;$ie(e)&&(n=Object.assign({},e),e.expires_at||(n.expires_at=hie(e.expires_in)));const r=(t=e.user)!==null&&t!==void 0?t:typeof(e==null?void 0:e.id)=="string"?e:null;return{data:{session:n,user:r},error:null}}function bO(e){const t=Ii(e);return!t.error&&e.weak_password&&typeof e.weak_password=="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message=="string"&&e.weak_password.reasons.reduce((n,r)=>n&&typeof r=="string",!0)&&(t.data.weak_password=e.weak_password),t}function $c(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function Die(e){return{data:e,error:null}}function Mie(e){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i}=e,o=Uv(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),l={action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i},c=Object.assign({},o);return{data:{properties:l,user:c},error:null}}function vO(e){return e}function $ie(e){return!!e.access_token&&!!e.refresh_token&&!!e.expires_in}const n1=["global","local","others"];class Lie{constructor({url:t="",headers:n={},fetch:r,experimental:a}){this.url=t,this.headers=n,this.fetch=RF(r),this.experimental=a??{},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)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(t,n=n1[0]){if(n1.indexOf(n)<0)throw new Error(`@supabase/auth-js: Parameter scope must be one of ${n1.join(", ")}`);try{return await gt(this.fetch,"POST",`${this.url}/logout?scope=${n}`,{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(r){if(at(r))return{data:null,error:r};throw r}}async inviteUserByEmail(t,n={}){try{return await gt(this.fetch,"POST",`${this.url}/invite`,{body:{email:t,data:n.data},headers:this.headers,redirectTo:n.redirectTo,xform:$c})}catch(r){if(at(r))return{data:{user:null},error:r};throw r}}async generateLink(t){try{const{options:n}=t,r=Uv(t,["options"]),a=Object.assign(Object.assign({},r),n);return"newEmail"in r&&(a.new_email=r==null?void 0:r.newEmail,delete a.newEmail),await gt(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:a,headers:this.headers,xform:Mie,redirectTo:n==null?void 0:n.redirectTo})}catch(n){if(at(n))return{data:{properties:null,user:null},error:n};throw n}}async createUser(t){try{return await gt(this.fetch,"POST",`${this.url}/admin/users`,{body:t,headers:this.headers,xform:$c})}catch(n){if(at(n))return{data:{user:null},error:n};throw n}}async listUsers(t){var n,r,a,i,o,l,c;try{const u={nextPage:null,lastPage:0,total:0},d=await gt(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=t==null?void 0:t.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(i=(a=t==null?void 0:t.perPage)===null||a===void 0?void 0:a.toString())!==null&&i!==void 0?i:""},xform:vO});if(d.error)throw d.error;const h=await d.json(),f=(o=d.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(c=(l=d.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return m.length>0&&(m.forEach(x=>{const g=parseInt(x.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(x.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(at(u))return{data:{users:[]},error:u};throw u}}async getUserById(t){kl(t);try{return await gt(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:$c})}catch(n){if(at(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){kl(t);try{return await gt(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:$c})}catch(r){if(at(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){kl(t);
737try{return await gt(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:$c})}catch(r){if(at(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){kl(t.userId);try{const{data:n,error:r}=await gt(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:a=>({data:{factors:a},error:null})});return{data:n,error:r}}catch(n){if(at(n))return{data:null,error:n};throw n}}async _deleteFactor(t){kl(t.userId),kl(t.id);try{return{data:await gt(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(at(n))return{data:null,error:n};throw n}}async _listOAuthClients(t){var n,r,a,i,o,l,c;try{const u={nextPage:null,lastPage:0,total:0},d=await gt(this.fetch,"GET",`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=t==null?void 0:t.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(i=(a=t==null?void 0:t.perPage)===null||a===void 0?void 0:a.toString())!==null&&i!==void 0?i:""},xform:vO});if(d.error)throw d.error;const h=await d.json(),f=(o=d.headers.get("x-total-count"))!==null&&o!==void 0?o:0,m=(c=(l=d.headers.get("link"))===null||l===void 0?void 0:l.split(","))!==null&&c!==void 0?c:[];return m.length>0&&(m.forEach(x=>{const g=parseInt(x.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(x.split(";")[1].split("=")[1]);u[`${y}Page`]=g}),u.total=parseInt(f)),{data:Object.assign(Object.assign({},h),u),error:null}}catch(u){if(at(u))return{data:{clients:[]},error:u};throw u}}async _createOAuthClient(t){try{return await gt(this.fetch,"POST",`${this.url}/admin/oauth/clients`,{body:t,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(at(n))return{data:null,error:n};throw n}}async _getOAuthClient(t){try{return await gt(this.fetch,"GET",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(at(n))return{data:null,error:n};throw n}}async _updateOAuthClient(t,n){try{return await gt(this.fetch,"PUT",`${this.url}/admin/oauth/clients/${t}`,{body:n,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(at(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(t){try{return await gt(this.fetch,"DELETE",`${this.url}/admin/oauth/clients/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(at(n))return{data:null,error:n};throw n}}async _regenerateOAuthClientSecret(t){try{return await gt(this.fetch,"POST",`${this.url}/admin/oauth/clients/${t}/regenerate_secret`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(at(n))return{data:null,error:n};throw n}}async _listCustomProviders(t){try{const n={};return t!=null&&t.type&&(n.type=t.type),await gt(this.fetch,"GET",`${this.url}/admin/custom-providers`,{headers:this.headers,query:n,xform:r=>{var a;return{data:{providers:(a=r==null?void 0:r.providers)!==null&&a!==void 0?a:[]},error:null}}})}catch(n){if(at(n))return{data:{providers:[]},error:n};throw n}}async _createCustomProvider(t){try{return await gt(this.fetch,"POST",`${this.url}/admin/custom-providers`,{body:t,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(at(n))return{data:null,error:n};throw n}}async _getCustomProvider(t){try{return await gt(this.fetch,"GET",`${this.url}/admin/custom-providers/${t}`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(at(n))return{data:null,error:n};throw n}}async _updateCustomProvider(t,n){try{return await gt(this.fetch,"PUT",`${this.url}/admin/custom-providers/${t}`,{body:n,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(at(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(t){try{return await gt(this.fetch,"DELETE",`${this.url}/admin/custom-providers/${t}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(at(n))return{data:null,error:n};throw n}}async _adminListPasskeys(t){uo(this.experimental),kl(t.userId);try{return await gt(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/passkeys`,{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(at(n))return{data:null,error:n};throw n}}async _adminDeletePasskey(t){uo(this.experimental),kl(t.userId),kl(t.passkeyId);
737try{return await gt(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/passkeys/${t.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(at(n))return{data:null,error:n};throw n}}}function wO(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}globalThis&&PF()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug");class Fie extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}function Bie(){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 MF(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function Uie(e){return parseInt(e,16)}function zie(e){const t=new TextEncoder().encode(e);return"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function Wie(e){var t;const{chainId:n,domain:r,expirationTime:a,issuedAt:i=new Date,nonce:o,notBefore:l,requestId:c,resources:u,scheme:d,uri:h,version:f}=e;{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(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(o&&o.length<8)throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!h)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(f!=="1")throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(!((t=e.statement)===null||t===void 0)&&t.includes(` 738`))throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`)}const m=MF(e.address),x=d?`${d}://${r}
738`:r,g=e.statement?`${e.statement} 739`:"",y=`${x} wants you to sign in with your Ethereum account: 740${m} 741 742${g}`;let b=`URI: ${h} 743Version: ${f} 744Chain ID: ${n}${o?` 745Nonce: ${o}`:""} 746Issued At: ${i.toISOString()}`;if(a&&(b+=` 747Expiration Time: ${a.toISOString()}`),l&&(b+=` 748Not Before: ${l.toISOString()}`),c&&(b+=` 749Request ID: ${c}`),u){let v=` 750Resources:`;for(const w of u){if(!w||typeof w!="string")throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${w}`);v+=` 751- ${w}`}b+=v}return`${y} 752${b}`}class qr extends Error{constructor({message:t,code:n,cause:r,name:a}){var i;super(t,{cause:r}),this.__isWebAuthnError=!0,this.name=(i=a??(r instanceof Error?r.name:void 0))!==null&&i!==void 0?i:"Unknown Error",this.code=n}toJSON(){return{name:this.name,message:this.message,code:this.code}}}class sb extends qr{constructor(t,n){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n,message:t}),this.name="WebAuthnUnknownError",this.originalError=n}}function Kie({error:e,options:t}){var n,r,a;const{publicKey:i}=t;if(!i)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new qr({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(((n=i.authenticatorSelection)===null||n===void 0?void 0:n.requireResidentKey)===!0)return new qr({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if(t.mediation==="conditional"&&((r=i.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new qr({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if(((a=i.authenticatorSelection)===null||a===void 0?void 0:a.userVerification)==="required")return new qr({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if(e.name==="InvalidStateError")return new qr({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new qr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return i.pubKeyCredParams.filter(l=>l.type==="public-key").length===0?new qr({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new qr({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if(e.name==="SecurityError"){const o=window.location.hostname;if($F(o)){if(i.rp.id!==o)return new qr({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new qr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="TypeError"){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new qr({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new qr({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new qr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function Hie({error:e,options:t}){const{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new qr({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if(e.name==="NotAllowedError")return new qr({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){const r=window.location.hostname;if($F(r)){if(n.rpId!==r)return new qr({message:`The RP ID "${n.rpId}
752" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new qr({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new qr({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new qr({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}class Vie{createNewAbortSignal(){if(this.controller){const n=new Error("Cancelling existing WebAuthn API call for new one");n.name="AbortError",this.controller.abort(n)}const t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){const t=new Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0}}}const mN=new Vie;function _O(e){if(!e)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(e);const{challenge:t,user:n,excludeCredentials:r}=e,a=Uv(e,["challenge","user","excludeCredentials"]),i=Ph(t).buffer,o=Object.assign(Object.assign({},n),{id:Ph(n.id).buffer}),l=Object.assign(Object.assign({},a),{challenge:i,user:o});if(r&&r.length>0){l.excludeCredentials=new Array(r.length);for(let c=0;c<r.length;c++){const u=r[c];l.excludeCredentials[c]=Object.assign(Object.assign({},u),{id:Ph(u.id).buffer,type:u.type||"public-key",transports:u.transports})}}return l}function kO(e){if(!e)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(e);const{challenge:t,allowCredentials:n}=e,r=Uv(e,["challenge","allowCredentials"]),a=Ph(t).buffer,i=Object.assign(Object.assign({},r),{challenge:a});if(n&&n.length>0){i.allowCredentials=new Array(n.length);for(let o=0;o<n.length;o++){const l=n[o];i.allowCredentials[o]=Object.assign(Object.assign({},l),{id:Ph(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return i}function jO(e){var t;if("toJSON"in e&&typeof e.toJSON=="function")return e.toJSON();const n=e;return{id:e.id,rawId:e.id,response:{attestationObject:Xu(new Uint8Array(e.response.attestationObject)),clientDataJSON:Xu(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:(t=n.authenticatorAttachment)!==null&&t!==void 0?t:void 0}}function NO(e){var t;if("toJSON"in e&&typeof e.toJSON=="function")return e.toJSON();const n=e,r=e.getClientExtensionResults(),a=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:Xu(new Uint8Array(a.authenticatorData)),clientDataJSON:Xu(new Uint8Array(a.clientDataJSON)),signature:Xu(new Uint8Array(a.signature)),userHandle:a.userHandle?Xu(new Uint8Array(a.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:(t=n.authenticatorAttachment)!==null&&t!==void 0?t:void 0}}function $F(e){return e==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function ab(){var e,t;return!!(Is()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((e=navigator==null?void 0:navigator.credentials)===null||e===void 0?void 0:e.create)=="function"&&typeof((t=navigator==null?void 0:navigator.credentials)===null||t===void 0?void 0:t.get)=="function")}async function LF(e){try{const t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new sb("Browser returned unexpected credential type",t)}:{data:null,error:new sb("Empty credential response",t)}}catch(t){return{data:null,error:Kie({error:t,options:e})}}}async function FF(e){try{const t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new sb("Browser returned unexpected credential type",t)}:{data:null,error:new sb("Empty credential response",t)}}
752catch(t){return{data:null,error:Hie({error:t,options:e})}}}const qie={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Gie={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function ib(...e){const t=a=>a!==null&&typeof a=="object"&&!Array.isArray(a),n=a=>a instanceof ArrayBuffer||ArrayBuffer.isView(a),r={};for(const a of e)if(a)for(const i in a){const o=a[i];if(o!==void 0)if(Array.isArray(o))r[i]=o;else if(n(o))r[i]=o;else if(t(o)){const l=r[i];t(l)?r[i]=ib(l,o):r[i]=ib(o)}else r[i]=o}return r}function Yie(e,t){return ib(qie,e,t||{})}function Zie(e,t){return ib(Gie,e,t||{})}class Xie{constructor(t){this.client=t,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(t){return this.client.mfa.enroll(Object.assign(Object.assign({},t),{factorType:"webauthn"}))}async _challenge({factorId:t,webauthn:n,friendlyName:r,signal:a},i){var o;try{const{data:l,error:c}=await this.client.mfa.challenge({factorId:t,webauthn:n});if(!l)return{data:null,error:c};const u=a??mN.createNewAbortSignal();if(l.webauthn.type==="create"){const{user:d}=l.webauthn.credential_options.publicKey;if(!d.name){const h=r;if(h)d.name=`${d.id}:${h}`;else{const m=(await this.client.getUser()).data.user,x=((o=m==null?void 0:m.user_metadata)===null||o===void 0?void 0:o.name)||(m==null?void 0:m.email)||(m==null?void 0:m.id)||"User";d.name=`${d.id}:${x}`}}d.displayName||(d.displayName=d.name)}switch(l.webauthn.type){case"create":{const d=Yie(l.webauthn.credential_options.publicKey,i==null?void 0:i.create),{data:h,error:f}=await LF({publicKey:d,signal:u});return h?{data:{factorId:t,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:h}},error:null}:{data:null,error:f}}case"request":{const d=Zie(l.webauthn.credential_options.publicKey,i==null?void 0:i.request),{data:h,error:f}=await FF(Object.assign(Object.assign({},l.webauthn.credential_options),{publicKey:d,signal:u}));return h?{data:{factorId:t,challengeId:l.id,webauthn:{type:l.webauthn.type,credential_response:h}},error:null}:{data:null,error:f}}}}catch(l){return at(l)?{data:null,error:l}:{data:null,error:new mo("Unexpected error in challenge",l)}}}async _verify({challengeId:t,factorId:n,webauthn:r}){return this.client.mfa.verify({factorId:n,challengeId:t,webauthn:r})}async _authenticate({factorId:t,webauthn:{rpId:n=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:a}={}},i){if(!n)return{data:null,error:new gp("rpId is required for WebAuthn authentication")};try{if(!ab())return{data:null,error:new mo("Browser does not support WebAuthn",null)};const{data:o,error:l}=await this.challenge({factorId:t,webauthn:{rpId:n,rpOrigins:r},signal:a},{request:i});if(!o)return{data:null,error:l};const{webauthn:c}=o;return this._verify({factorId:t,challengeId:o.challengeId,webauthn:{type:c.type,rpId:n,rpOrigins:r,credential_response:c.credential_response}})}catch(o){return at(o)?{data:null,error:o}:{data:null,error:new mo("Unexpected error in authenticate",o)}}}async _register({friendlyName:t,webauthn:{rpId:n=typeof window<"u"?window.location.hostname:void 0,rpOrigins:r=typeof window<"u"?[window.location.origin]:void 0,signal:a}={}},i){if(!n)return{data:null,error:new gp("rpId is required for WebAuthn registration")};try{if(!ab())return{data:null,error:new mo("Browser does not support WebAuthn",null)};const{data:o,error:l}=await this._enroll({friendlyName:t});if(!o)return await this.client.mfa.listFactors().then(d=>{var h;return(h=d.data)===null||h===void 0?void 0:h.all.find(f=>f.factor_type==="webauthn"&&f.friendly_name===t&&f.status!=="unverified")}).then(d=>d?this.client.mfa.unenroll({factorId:d==null?void 0:d.id}):void 0),{data:null,error:l};const{data:c,error:u}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:n,rpOrigins:r},signal:a},{create:i});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:n,rpOrigins:r,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:u}}catch(o){return at(o)?{data:null,error:o}:{data:null,error:new mo("Unexpected error in register",o)}}}}Bie();const Jie={url:Xae,storageKey:Jae,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Qae,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},Zd={};class bp{get jwks(){var t,n;return(n=(t=Zd[this.storageKey])===null||t===void 0?void 0:t.jwks)!==null&&n!==void 0?n:{keys:[]}}set jwks(t){Zd[this.storageKey]=Object.assign(Object.assign({},Zd[this.storageKey]),{jwks:t})}get jwks_cached_at(){var t,n;return(n=(t=Zd[this.storageKey])===null||t===void 0?void 0:t.cachedAt)!==null&&n!==void 0?n:Number.MIN_SAFE_INTEGER}set jwks_cached_at(t){Zd[this.storageKey]=Object.assign(Object.assign({},Zd[this.storageKey]),{cachedAt:t})}constructor(t){var n,r,a;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const i=Object.assign(Object.assign({},Jie),t);if(this.storageKey=i.storageKey,this.instanceID=(n=bp.nextInstanceID[this.storageKey])!==null&&n!==void 0?n:0,bp.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug=="function"&&(this.logger=i.debug),this.instanceID>0&&Is()){const o=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(o),this.logDebugMessages&&console.trace(o)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=(r=i.experimental)!==null&&r!==void 0?r:{},this.admin=new Lie({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=RF(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock!=null&&(this.lock=i.lock),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 Xie(this)}
752,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.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:PF()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=wO(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=wO(this.memoryStorage)),Is()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(o){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",o)}(a=this.broadcastChannel)===null||a===void 0||a.addEventListener("message",async o=>{this._debug("received broadcast notification from other tab or client",o),(o.data.event==="TOKEN_REFRESHED"||o.data.event==="SIGNED_IN")&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(o.data.event,o.data.session,!1)}catch(l){this._debug("#broadcastChannel","error",l)}})}i.skipAutoInitialize||this.initialize().catch(o=>{this._debug("#initialize()","error",o)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(t){if(this.throwOnError&&t&&t.error)throw t.error;return t}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${TF}) ${new Date().toISOString()}`}_debug(...t){return this.logDebugMessages&&this.logger(this._logPrefix(),...t),this}async initialize(){var t;if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()):await this._initialize())();const n=await this.initializePromise,r=(t=this._pendingInitNotifications)!==null&&t!==void 0?t:[];this._pendingInitNotifications=null;for(const a of r)await this._notifyAllSubscribers(a.event,a.session,a.broadcast);return n}async _initialize(){var t;try{let n={},r="none";if(Is()&&(n=pO(window.location.href),this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce")),Is()&&this.detectSessionInUrl&&r!=="none"){const{data:a,error:i}=await this._getSessionFromURL(n,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),sie(i)){const c=(t=i.details)===null||t===void 0?void 0:t.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return{error:i}}const{session:o,redirectType:l}=a;return this._debug("#_initialize()","detected session in URL",o,"redirect type",l),await this._saveSession(o),setTimeout(async()=>{l==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",o):await this._notifyAllSubscribers("SIGNED_IN",o)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(n){return at(n)?this._returnResult({error:n}):this._returnResult({error:new mo("Unexpected error during initialization",n)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,a;try{const i=await gt(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(a=t==null?void 0:t.options)===null||a===void 0?void 0:a.captchaToken}},xform:Ii}),{data:o,error:l}=i;if(l||!o)return this._returnResult({data:{user:null,session:null},error:l});const c=o.session,u=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(i){if(at(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async signUp(t){var n,r,a;let i=null;try{let o;if("email"in t){const{email:h,password:f,options:m}=t;let x=null,g=null;this.flowType==="pkce"&&([x,g,i]=await this._getCodeChallengeAndMethod()),o=await gt(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(m==null?void 0:m.emailRedirectTo,i),body:{email:h,password:f,data:(n=m==null?void 0:m.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},code_challenge:x,code_challenge_method:g},xform:Ii})}else if("phone"in t){const{phone:h,password:f,options:m}=t;o=await gt(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:h,password:f,data:(r=m==null?void 0:m.data)!==null&&r!==void 0?r:{},channel:(a=m==null?void 0:m.channel)!==null&&a!==void 0?a:"sms",gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken}},xform:Ii})}else throw new lg("You must provide either an email or phone number and a password");const{data:l,error:c}=o;if(c||!l)return await ao(this.storage,this.storageKey,i),this._returnResult({data:{user:null,session:null},error:c});const u=l.session,d=l.user;return l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",u)),this._returnResult({data:{user:d,session:u},error:null})}catch(o){if(await ao(this.storage,this.storageKey,i),at(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(t){try{let n;if("email"in t){const{email:i,password:o,options:l}=t;n=await gt(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:i,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:bO})}else if("phone"in t){const{phone:i,password:o,options:l}=t;n=await gt(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:i,password:o,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken}},xform:bO})}else throw new lg("You must provide either an email or phone number and a password");const{data:r,error:a}=n;
752if(a)return this._returnResult({data:{user:null,session:null},error:a});if(!r||!r.session||!r.user){const i=new Yd;return this._returnResult({data:{user:null,session:null},error:i})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:a})}catch(n){if(at(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOAuth(t){var n,r,a,i;return await this._handleProviderSignIn(t.provider,{redirectTo:(n=t.options)===null||n===void 0?void 0:n.redirectTo,scopes:(r=t.options)===null||r===void 0?void 0:r.scopes,queryParams:(a=t.options)===null||a===void 0?void 0:a.queryParams,skipBrowserRedirect:(i=t.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(t,n){return await this.initializePromise,this.lock!=null?this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(t,n)):this._exchangeCodeForSession(t,n)}async signInWithWeb3(t){const{chain:n}=t;switch(n){case"ethereum":return await this.signInWithEthereum(t);case"solana":return await this.signInWithSolana(t);default:throw new Error(`@supabase/auth-js: Unsupported chain "${n}"`)}}async signInWithEthereum(t){var n,r,a,i,o,l,c,u,d,h,f;let m,x;if("message"in t)m=t.message,x=t.signature;else{const{chain:g,wallet:y,statement:b,options:v}=t;let w;if(Is())if(typeof y=="object")w=y;else{const A=window;if("ethereum"in A&&typeof A.ethereum=="object"&&"request"in A.ethereum&&typeof A.ethereum.request=="function")w=A.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 y!="object"||!(v!=null&&v.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");w=y}const _=new URL((n=v==null?void 0:v.url)!==null&&n!==void 0?n:window.location.href),k=await w.request({method:"eth_requestAccounts"}).then(A=>A).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 j=MF(k[0]);let N=(r=v==null?void 0:v.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!N){const A=await w.request({method:"eth_chainId"});N=Uie(A)}const E={domain:_.host,address:j,statement:b,uri:_.href,version:"1",chainId:N,nonce:(a=v==null?void 0:v.signInWithEthereum)===null||a===void 0?void 0:a.nonce,issuedAt:(o=(i=v==null?void 0:v.signInWithEthereum)===null||i===void 0?void 0:i.issuedAt)!==null&&o!==void 0?o:new Date,expirationTime:(l=v==null?void 0:v.signInWithEthereum)===null||l===void 0?void 0:l.expirationTime,notBefore:(c=v==null?void 0:v.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(u=v==null?void 0:v.signInWithEthereum)===null||u===void 0?void 0:u.requestId,resources:(d=v==null?void 0:v.signInWithEthereum)===null||d===void 0?void 0:d.resources};m=Wie(E),x=await w.request({method:"personal_sign",params:[zie(m),j]})}try{const{data:g,error:y}=await gt(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:m,signature:x},!((h=t.options)===null||h===void 0)&&h.captchaToken?{gotrue_meta_security:{captcha_token:(f=t.options)===null||f===void 0?void 0:f.captchaToken}}:null),xform:Ii});if(y)throw y;if(!g||!g.session||!g.user){const b=new Yd;return this._returnResult({data:{user:null,session:null},error:b})}return g.session&&(await this._saveSession(g.session),await this._notifyAllSubscribers("SIGNED_IN",g.session)),this._returnResult({data:Object.assign({},g),error:y})}catch(g){if(at(g))return this._returnResult({data:{user:null,session:null},error:g});throw g}}async signInWithSolana(t){var n,r,a,i,o,l,c,u,d,h,f,m;let x,g;if("message"in t)x=t.message,g=t.signature;else{const{chain:y,wallet:b,statement:v,options:w}=t;let _;if(Is())if(typeof b=="object")_=b;else{const j=window;if("solana"in j&&typeof j.solana=="object"&&("signIn"in j.solana&&typeof j.solana.signIn=="function"||"signMessage"in j.solana&&typeof j.solana.signMessage=="function"))_=j.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 b!="object"||!(w!=null&&w.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=b}const k=new URL((n=w==null?void 0:w.url)!==null&&n!==void 0?n:window.location.href);if("signIn"in _&&_.signIn){const j=await _.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},w==null?void 0:w.signInWithSolana),{version:"1",domain:k.host,uri:k.href}),v?{statement:v}:null));let N;if(Array.isArray(j)&&j[0]&&typeof j[0]=="object")N=j[0];else if(j&&typeof j=="object"&&"signedMessage"in j&&"signature"in j)N=j;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in N&&"signature"in N&&(typeof N.signedMessage=="string"||N.signedMessage instanceof Uint8Array)&&N.signature instanceof Uint8Array)x=typeof N.signedMessage=="string"?N.signedMessage:new TextDecoder().decode(N.signedMessage),g=N.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in _)||typeof _.signMessage!="function"||!("publicKey"in _)||typeof _!="object"||!_.publicKey||!("toBase58"in _.publicKey)||typeof _.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");x=[`${k.host} wants you to sign in with your Solana account:`,_.publicKey.toBase58(),...v?["",v,""]:[""],"Version: 1",`URI: ${k.href}`,`Issued At: ${(a=(r=w==null?void 0:w.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&a!==void 0?a:new Date().toISOString()}`,...!((i=w==null?void 0:w.signInWithSolana)===null||i===void 0)&&i.notBefore?[`Not Before: ${w.signInWithSolana.notBefore}`]:[],...!((o=w==null?void 0:w.signInWithSolana)===null||o===void 0)&&o.expirationTime?[`Expiration Time: ${w.signInWithSolana.expirationTime}`]:[],...!((l=w==null?void 0:w.signInWithSolana)===null||l===void 0)&&l.chainId?[`Chain ID: ${w.signInWithSolana.chainId}`]:[],...!((c=w==null?void 0:w.signInWithSolana)===null||c===void 0)&&c.nonce?[`Nonce: ${w.signInWithSolana.nonce}`]:[],...!((u=w==null?void 0:w.signInWithSolana)===null||u===void 0)&&u.requestId?[`Request ID: ${w.signInWithSolana.requestId}`]:[],...!((h=(d=w==null?void 0:w.signInWithSolana)===null||d===void 0?void 0:d.resources)===null||h===void 0)&&h.length?["Resources",...w.sign
752InWithSolana.resources.map(N=>`- ${N}`)]:[]].join(` 753`);const j=await _.signMessage(new TextEncoder().encode(x),"utf8");if(!j||!(j instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");g=j}}try{const{data:y,error:b}=await gt(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:x,signature:Xu(g)},!((f=t.options)===null||f===void 0)&&f.captchaToken?{gotrue_meta_security:{captcha_token:(m=t.options)===null||m===void 0?void 0:m.captchaToken}}:null),xform:Ii});if(b)throw b;if(!y||!y.session||!y.user){const v=new Yd;return this._returnResult({data:{user:null,session:null},error:v})}return y.session&&(await this._saveSession(y.session),await this._notifyAllSubscribers("SIGNED_IN",y.session)),this._returnResult({data:Object.assign({},y),error:b})}catch(y){if(at(y))return this._returnResult({data:{user:null,session:null},error:y});throw y}}async _exchangeCodeForSession(t,n){const r=(n==null?void 0:n.flowId)!=null,a=r?Sy(n==null?void 0:n.flowId):Is()?Sy(pO(window.location.href)[Zu]):null;r&&!a&&this._debug("#_exchangeCodeForSession()","provided flowId is not a valid flow id",n==null?void 0:n.flowId);const{verifier:i,flowId:o}=r&&!a?{verifier:null,flowId:null}:await kie(this.storage,this.storageKey,a),[l,c]=(i??"").split("/");try{if(!l&&this.flowType==="pkce")throw new aie;const{data:u,error:d}=await gt(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:l},xform:Ii});if(await ao(this.storage,this.storageKey,o),d)throw d;if(!u||!u.session||!u.user){const h=new Yd;return this._returnResult({data:{user:null,session:null,redirectType:null},error:h})}return u.session&&(await this._saveSession(u.session),await this._notifyAllSubscribers(c==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",u.session)),this._returnResult({data:Object.assign(Object.assign({},u),{redirectType:c??null}),error:d})}catch(u){if(await ao(this.storage,this.storageKey,o),at(u))return this._returnResult({data:{user:null,session:null,redirectType:null},error:u});throw u}}async signInWithIdToken(t){try{const{options:n,provider:r,token:a,access_token:i,nonce:o}=t,l=await gt(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:a,access_token:i,nonce:o,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},xform:Ii}),{data:c,error:u}=l;if(u)return this._returnResult({data:{user:null,session:null},error:u});if(!c||!c.session||!c.user){const d=new Yd;return this._returnResult({data:{user:null,session:null},error:d})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:u})}catch(n){if(at(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOtp(t){var n,r,a,i,o;let l=null;try{if("email"in t){const{email:c,options:u}=t;let d=null,h=null;this.flowType==="pkce"&&([d,h,l]=await this._getCodeChallengeAndMethod());const{error:f}=await gt(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:c,data:(n=u==null?void 0:u.data)!==null&&n!==void 0?n:{},create_user:(r=u==null?void 0:u.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken},code_challenge:d,code_challenge_method:h},redirectTo:this._maybeAppendFlowIdToRedirect(u==null?void 0:u.emailRedirectTo,l)});return this._returnResult({data:{user:null,session:null},error:f})}if("phone"in t){const{phone:c,options:u}=t,{data:d,error:h}=await gt(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:c,data:(a=u==null?void 0:u.data)!==null&&a!==void 0?a:{},create_user:(i=u==null?void 0:u.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:u==null?void 0:u.captchaToken},channel:(o=u==null?void 0:u.channel)!==null&&o!==void 0?o:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:d==null?void 0:d.message_id},error:h})}throw new lg("You must provide either an email or phone number.")}catch(c){if(await ao(this.storage,this.storageKey,l),at(c))return this._returnResult({data:{user:null,session:null},error:c});throw c}}async verifyOtp(t){var n,r;try{let a,i;"options"in t&&(a=(n=t.options)===null||n===void 0?void 0:n.redirectTo,i=(r=t.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:l}=await gt(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:Ii});if(l)throw l;if(!o)throw new Error("An error occurred on token verification.");const c=o.session,u=o.user;return c!=null&&c.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(t.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:u,session:c},error:null})}catch(a){if(at(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}}async signInWithSSO(t){var n,r,a,i;let o=null;try{let l=null,c=null;this.flowType==="pkce"&&([l,c,o]=await this._getCodeChallengeAndMethod());const u=await gt(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:this._maybeAppendFlowIdToRedirect((n=t.options)===null||n===void 0?void 0:n.redirectTo,o)}),!((r=t==null?void 0:t.options)===null||r===void 0)&&r.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:l,code_challenge_method:c}),headers:this.headers,xform:Die});return!((a=u.data)===null||a===void 0)&&a.url&&Is()&&!(!((i=t.options)===null||i===void 0)&&i.skipBrowserRedirect)&&window.location.assign(u.data.url),this._returnResult(u)}catch(l){if(await ao(this.storage,this.storageKey,o),at(l))return this._returnResult({data:null,error:l});throw l}}async reauthenticate(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate()):await this._reauthenticate()}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;if(r)throw r;if(!n)throw new xs;const{error:a}=await gt(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return this._returnResult({data:{user:null,session:null},error:a})})}catch(t){if(at(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async resend(t){let n=null;try{const r=`${this.url}/resend`;if("email"in t){const{email:a,type:i,options:o}=t;let l=null,c=null;this.flowType==="pkce"&&([l,c,n]=await this._getCodeChallengeAndMethod());const{error:u}=await gt(this.fetch,"POST",r,{headers:this.headers,body:{email:a,type:i,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken},code_challenge:l,code_challenge_method:c},redirectTo:this._maybeAppendFlowIdToRedirect(o==null?void 0:o.emailRedirectTo,n)});return u&&await ao(this.storage,this.storageKey,n),this._returnResult({data:{user:null,session:null},error:u})}else if("phone"in t){const{phone:a,type:i,options:o}=t,{data:l,error:c}=await gt(this.fetch,"POST",r,{headers:this.headers,body:{phone:a,type:i,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:l==null?void 0:l.message_id},error:c})}throw new lg("You must provide either an email or phone number and a type")}catch(r){if(await ao(this.storage,this.storageKey,n),at(r))return this._returnResult({data:{user:null,session:null},error:r});throw r}}async getSession(){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async t=>t)):await this._useSession(async t=>t)}async _acquireLock(t,n){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),a=(async()=>(await r,await n()))();return this.pendingInLock.push((async()=>{try{await a}catch{}})()),a}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=n();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const a=[...this.pendingInLock];await Promise.all(a),this.pendingInLock.splice(0,a.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{const n=await this.__loadSession();return await t(n)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lock!=null&&!this.lockAcquired&&this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let t=null;const n=await Js(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?t=n:(this._debug("#getSession()","session from storage is not val
753id"),await this._removeSession())),!t)return{data:{session:null},error:null};const r=t.expires_at?t.expires_at*1e3-Date.now()<e1:!1;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",t.expires_at),!r){if(this.userStorage){const o=await Js(this.userStorage,this.storageKey+"-user");o!=null&&o.user?t.user=o.user:t.user=t1()}if(this.storage.isServer&&t.user&&!t.user.__isUserNotAvailableProxy){const o={value:this.suppressGetSessionWarning};t.user=Iie(t.user,o),o.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:t},error:null}}const{data:a,error:i}=await this._callRefreshToken(t.refresh_token);if(i){if(!!(t.expires_at&&t.expires_at*1e3>Date.now())){const l=await Js(this.storage,this.storageKey);if(l&&l.refresh_token===t.refresh_token)return this._returnResult({data:{session:t},error:null})}return this._returnResult({data:{session:null},error:i})}return this._returnResult({data:{session:a},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(t){if(t)return await this._getUser(t);await this.initializePromise;let n;return this.lock!=null?n=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()):n=await this._getUser(),n.data.user&&(this.suppressGetSessionWarning=!0),n}async _getUser(t){try{return t?await gt(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:$c}):await this._useSession(async n=>{var r,a,i;const{data:o,error:l}=n;if(l)throw l;return!(!((r=o.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new xs}:await gt(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(a=o.session)===null||a===void 0?void 0:a.access_token)!==null&&i!==void 0?i:void 0,xform:$c})})}catch(n){if(at(n))return og(n)&&await this._removeSession(),this._returnResult({data:{user:null},error:n});throw n}}async updateUser(t,n={}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(t,n)):await this._updateUser(t,n)}async _updateUser(t,n={}){let r=null;try{return await this._useSession(async a=>{const{data:i,error:o}=a;if(o)throw o;if(!i.session)throw new xs;const l=i.session;let c=null,u=null;this.flowType==="pkce"&&t.email!=null&&([c,u,r]=await this._getCodeChallengeAndMethod());const{data:d,error:h}=await gt(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(n==null?void 0:n.emailRedirectTo,r),body:Object.assign(Object.assign({},t),{code_challenge:c,code_challenge_method:u}),jwt:l.access_token,xform:$c});if(h)throw h;return l.user=d.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),this._returnResult({data:{user:l.user},error:null})})}catch(a){if(await ao(this.storage,this.storageKey,r),at(a))return this._returnResult({data:{user:null},error:a});throw a}}async setSession(t){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(t)):await this._setSession(t)}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new xs;const n=Date.now()/1e3;let r=n,a=!0,i=null;const{payload:o}=dg(t.access_token);if(o.exp&&(r=o.exp,a=r<=n),a){const{data:l,error:c}=await this._callRefreshToken(t.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!l)return{data:{user:null,session:null},error:null};i=l}else{const{data:l,error:c}=await this._getUser(t.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});i={access_token:t.access_token,refresh_token:t.refresh_token,user:l.user,token_type:"bearer",expires_in:r-n,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return this._returnResult({data:{user:i.user,session:i},error:null})}catch(n){if(at(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}}async refreshSession(t){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(t)):await this._refreshSession(t)}async _refreshSession(t){try{return await this._useSession(async n=>{var r;if(!t){const{data:o,error:l}=n;if(l)throw l;t=(r=o.session)!==null&&r!==void 0?r:void 0}if(!(t!=null&&t.refresh_token))throw new xs;const{data:a,error:i}=await this._callRefreshToken(t.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):a?this._returnResult({data:{user:a.user,session:a},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(n){if(at(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async _getSessionFromURL(t,n){var r;try{if(!Is())throw new cg("No browser detected.");
753if(t.error||t.error_description||t.error_code)throw new cg(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(n){case"implicit":if(this.flowType==="pkce")throw new cO("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new cg("Not a valid implicit grant flow url.");break;default:}if(n==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new cO("No code detected.");const{data:w,error:_}=await this._exchangeCodeForSession(t.code,{flowId:t[Zu]});if(_)throw _;const k=new URL(window.location.href);return k.searchParams.delete("code"),k.searchParams.delete(Zu),window.history.replaceState(window.history.state,"",k.toString()),{data:{session:w.session,redirectType:(r=w.redirectType)!==null&&r!==void 0?r:null},error:null}}const{provider_token:a,provider_refresh_token:i,access_token:o,refresh_token:l,expires_in:c,expires_at:u,token_type:d}=t;if(!o||!c||!l||!d)throw new cg("No session defined in URL");const h=Math.round(Date.now()/1e3),f=parseInt(c);let m=h+f;u&&(m=parseInt(u));const x=m-h;x*1e3<=Il&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${x}s, should have been closer to ${f}s`);const g=m-f;h-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,m,h):h-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,m,h);const{data:y,error:b}=await this._getUser(o);if(b)throw b;const v={provider_token:a,provider_refresh_token:i,access_token:o,expires_in:f,expires_at:m,refresh_token:l,token_type:d,user:y.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:v,redirectType:t.type},error:null})}catch(a){if(at(a))return this._returnResult({data:{session:null,redirectType:null},error:a});throw a}}_isImplicitGrantCallback(t){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),t):!!(t.access_token||t.error||t.error_description||t.error_code)}async _isPKCECallback(t){if(!t.code)return!1;const n=Sy(t[Zu]);return n&&await Js(this.storage,Hh(this.storageKey,n))?!0:!!await Js(this.storage,`${this.storageKey}-code-verifier`)}async signOut(t={scope:"global"}){return await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(t)):await this._signOut(t)}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async n=>{var r;const a=async()=>{await this._removeSession()},{data:i,error:o}=n;if(o&&!og(o))return this._returnResult({error:o});const l=(r=i.session)===null||r===void 0?void 0:r.access_token;if(l){const{error:c}=await this.admin.signOut(l,t);if(c&&!(lO(c)&&(c.status===404||c.status===401||c.status===403)||og(c)))return t!=="others"&&await a(),this._returnResult({error:c})}return t!=="others"&&await a(),this._returnResult({error:null})})}onAuthStateChange(t){const n=fie(),r={id:n,callback:t,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,r),(async()=>(await this.initializePromise,this.lock!=null?await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(n)}):await this._emitInitialSession(n)))(),{data:{subscription:r}}}async _emitInitialSession(t){return await this._useSession(async n=>{var r,a;try{const{data:{session:i},error:o}=n;if(o)throw o;await((r=this.stateChangeEmitters.get(t))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",t,"session",i)}catch(i){await((a=this.stateChangeEmitters.get(t))===null||a===void 0?void 0:a.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",i),og(i)||ug(i)||lO(i)&&(i.code==="refresh_token_not_found"||i.code==="refresh_token_already_used"||i.code==="session_expired")?console.warn(i):console.error(i)}})}async resetPasswordForEmail(t,n={}){let r=null,a=null,i=null;this.flowType==="pkce"&&([r,a,i]=await this._getCodeChallengeAndMethod(!0));try{return await gt(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:r,code_challenge_method:a,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(n.redirectTo,i)})}catch(o){if(await ao(this.storage,this.storageKey,i),at(o))return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var t;try{const{data:n,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(t=n.user.identities)!==null&&t!==void 0?t:[]},error:null})}catch(n){if(at(n))return this._returnResult({data:null,error:n});throw n}}async linkIdentity(t){return"token"in t?this.linkIdentityIdToken(t):this.linkIdentityOAuth(t)}async linkIdentityOAuth(t){var n;let r=null;try{const{data:a,error:i}=await this._useSession(async o=>{var l,c,u,d,h;const{data:f,error:m}=o;if(m)throw m;const{url:x,flowId:g}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(l=t.options)===null||l===void 0?void 0:l.redirectTo,scopes:(c=t.options)===null||c===void 0?void 0:c.scopes,queryParams:(u=t.options)===null||u===void 0?void 0:u.queryParams,skipBrowserRedirect:!0});return r=g,await gt(this.fetch,"GET",x,{headers:this.headers,jwt:(h=(d=f.session)===null||d===void 0?void 0:d.access_token)!==null&&h!==void 0?h:void 0})});if(i)throw i;return Is()&&!(!((n=t.options)===null||n===void 0)&&n.skipBrowserRedirect)&&window.location.assign(a==null?void 0:a.url),this._returnResult({data:{provider:t.provider,url:a==null?void 0:a.url,flowId:r},error:null})}catch(a){if(at(a))return this._returnResult({data:{provider:t.provider,url:null,flowId:r},error:a});throw a}}async linkIdentityIdToken(t){return await this._useSession(async n=>{var r;try{const{error:a,data:{session:i}}=n;
753if(a)throw a;const{options:o,provider:l,token:c,access_token:u,nonce:d}=t,h=await gt(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(r=i==null?void 0:i.access_token)!==null&&r!==void 0?r:void 0,body:{provider:l,id_token:c,access_token:u,nonce:d,link_identity:!0,gotrue_meta_security:{captcha_token:o==null?void 0:o.captchaToken}},xform:Ii}),{data:f,error:m}=h;return m?this._returnResult({data:{user:null,session:null},error:m}):!f||!f.session||!f.user?this._returnResult({data:{user:null,session:null},error:new Yd}):(f.session&&(await this._saveSession(f.session),await this._notifyAllSubscribers("USER_UPDATED",f.session)),this._returnResult({data:f,error:m}))}catch(a){if(await ao(this.storage,this.storageKey,null),at(a))return this._returnResult({data:{user:null,session:null},error:a});throw a}})}async unlinkIdentity(t){try{return await this._useSession(async n=>{var r,a;const{data:i,error:o}=n;if(o)throw o;return await gt(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(a=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&a!==void 0?a:void 0})})}catch(n){if(at(n))return this._returnResult({data:null,error:n});throw n}}async _refreshAccessToken(t){const n="#_refreshAccessToken()";this._debug(n,"begin");try{const r=Date.now();return await xie(async a=>(a>0&&await pie(200*Math.pow(2,a-1)),this._debug(n,"refreshing attempt",a),await gt(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:Ii})),(a,i)=>{const o=200*Math.pow(2,a);return i&&ug(i)&&Date.now()+o-r<Il})}catch(r){if(this._debug(n,"error",r),at(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}finally{this._debug(n,"end")}}_isValidSession(t){return typeof t=="object"&&t!==null&&"access_token"in t&&"refresh_token"in t&&"expires_at"in t}async _handleProviderSignIn(t,n){const{url:r,flowId:a}=await this._getUrlForProvider(`${this.url}/authorize`,t,{redirectTo:n.redirectTo,scopes:n.scopes,queryParams:n.queryParams});return this._debug("#_handleProviderSignIn()","provider",t,"options",n,"url",r),Is()&&!n.skipBrowserRedirect&&window.location.assign(r),{data:{provider:t,url:r,flowId:a},error:null}}async _recoverAndRefresh(){var t,n;const r="#_recoverAndRefresh()";this._debug(r,"begin");try{const a=await Js(this.storage,this.storageKey);if(a&&this.userStorage){let o=await Js(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!o&&(o={user:a.user},await Ll(this.userStorage,this.storageKey+"-user",o)),a.user=(t=o==null?void 0:o.user)!==null&&t!==void 0?t:t1()}else if(a&&!a.user&&!a.user){const o=await Js(this.storage,this.storageKey+"-user");o&&(o!=null&&o.user)?(a.user=o.user,await Ja(this.storage,this.storageKey+"-user"),await Ll(this.storage,this.storageKey,a)):a.user=t1()}if(this._debug(r,"session from storage",a),!this._isValidSession(a)){this._debug(r,"session is not valid"),a!==null&&await this._removeSession();return}const i=((n=a.expires_at)!==null&&n!==void 0?n:1/0)*1e3-Date.now()<e1;if(this._debug(r,`session has${i?"":" not"} expired with margin of ${e1}s`),i){if(this.autoRefreshToken&&a.refresh_token){const{error:o}=await this._callRefreshToken(a.refresh_token);o&&(iie(o)?this._debug(r,"refresh discarded by commit guard",o):this._debug(r,"refresh failed",o))}}else if(a.user&&a.user.__isUserNotAvailableProxy===!0)try{const{data:o,error:l}=await this._getUser(a.access_token);!l&&(o!=null&&o.user)?(a.user=o.user,await this._saveSession(a),await this._notifyAllSubscribers("SIGNED_IN",a)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(o){console.error("Error getting user data:",o),this._debug(r,"error getting user data, skipping SIGNED_IN notification",o)}else await this._notifyAllSubscribers("SIGNED_IN",a)}catch(a){this._debug(r,"error",a),ug(a)?console.warn(a):console.error(a);return}finally{this._debug(r,"end")}}async _callRefreshToken(t){var n,r;if(!t)throw new xs;if(this.refreshingDeferred)return this.refreshingDeferred.promise;if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===t&&Date.now()<this.lastRefreshFailure.expiresAt)return this._debug("#_callRefreshToken()","returning c
753ached failure (cooldown active)"),this.lastRefreshFailure.result;const a="#_callRefreshToken()";this._debug(a,"begin");try{this.refreshingDeferred=new o0;const i=await Js(this.storage,this.storageKey),{data:o,error:l}=await this._refreshAccessToken(t);if(l)throw l;if(!o.session)throw new xs;const c=await Js(this.storage,this.storageKey);if(i!==null&&(c===null||c.refresh_token!==i.refresh_token)){this._debug(a,"commit guard: storage changed since refresh started, discarding rotated tokens",{startedWith:"present",nowHolds:c?"replaced":"cleared"});const f={data:null,error:new uO};return this.refreshingDeferred.resolve(f),f}const d=this._sessionRemovalEpoch;if(await this._saveSession(o.session),this._sessionRemovalEpoch!==d){this._debug(a,"commit guard (post-save): _removeSession ran during _saveSession, undoing write"),await Ja(this.storage,this.storageKey),this.userStorage&&await Ja(this.userStorage,this.storageKey+"-user");const f={data:null,error:new uO};return this.refreshingDeferred.resolve(f),f}await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);const h={data:o.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(h),h}catch(i){if(this._debug(a,"error",i),at(i)){const o={data:null,error:i};if(!ug(i)){const l=await Js(this.storage,this.storageKey);!!(l!=null&&l.expires_at&&l.expires_at*1e3>Date.now())?this._debug(a,"proactive refresh failed, access token still valid â preserving session"):await this._removeSession()}return this.lastRefreshFailure={refreshToken:t,result:o,expiresAt:Date.now()+Zae},(n=this.refreshingDeferred)===null||n===void 0||n.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(i),i}finally{this.refreshingDeferred=null,this._debug(a,"end")}}async _notifyAllSubscribers(t,n,r=!0){if(this._pendingInitNotifications!==null&&r){this._pendingInitNotifications.push({event:t,session:n,broadcast:r});return}const a=`#_notifyAllSubscribers(${t})`;this._debug(a,"begin",n,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:t,session:n});const i=[],o=Array.from(this.stateChangeEmitters.values()).map(async l=>{try{await l.callback(t,n)}catch(c){i.push(c)}});if(await Promise.all(o),i.length>0){for(let l=0;l<i.length;l+=1)console.error(i[l]);throw i[0]}}finally{this._debug(a,"end")}}async _saveSession(t){this._debug("#_saveSession()",t),this.suppressGetSessionWarning=!0;const n=Object.assign({},t),r=n.user&&n.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!r&&n.user&&await Ll(this.userStorage,this.storageKey+"-user",{user:n.user});const a=Object.assign({},n);delete a.user;const i=xO(a);await Ll(this.storage,this.storageKey,i)}else{const a=xO(n);await Ll(this.storage,this.storageKey,a)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug("#_removeSession()"),this.lastRefreshFailure=null,this.suppressGetSessionWarning=!1,await Ja(this.storage,this.storageKey),await jie(this.storage,this.storageKey),await Ja(this.storage,this.storageKey+"-user"),this.userStorage&&await Ja(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const t=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{t&&Is()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",t)}catch(n){console.error("removing visibilitychange callback failed",n)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const t=setInterval(()=>this._autoRefreshTokenTick(),Il);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t);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 t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t);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 dispose(){var t;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(t=this.broadcastChannel)===null||t===void 0||t.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug("#_autoRefreshTokenTick()","begin"),this.lock!=null){try{await this._acquireLock(0,async()=>{try{const t=Date.now();try{return await this._useSession(async n=>{const{data:{session:r}}=n;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const a=Math.floor((r.expires_at*1e3-t)/Il);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${Il}ms, refresh threshold is ${Mm} ticks`),a<=Mm&&await this._callRefreshToken(r.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(t){if(t instanceof Fie)this._debug("auto refresh token tick lock not available");else throw t}return}if(this.refreshingDeferred!==null){this._debug("#_autoRefreshTokenTick()","refresh already in flight, skipping");return}try{const t=Date.now();try{await this._useSession(async n=>{const{data:{session:r}}=n;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const a=Math.floor((r.expires_at*1e3-t)/Il);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${Il}ms, refresh threshold is ${Mm} ticks`),a<=Mm&&await this._callRefreshToken(r.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Is()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(t){this._debug("#visibilityChangedCallback","error",t)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const n=`#_onVisibilityChanged(${t})`;if(this._debug(n,"visibilityState",document.visibilityState),document.visibilityState==="visible"){if(this.autoRefreshToken&&this._startAutoRefresh(),!t)if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>
753{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()});else{if(document.visibilityState!=="visible"){this._debug(n,"visibilityState is no longer visible, skipping recovery");return}await this._recoverAndRefresh()}}else document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(t,n,r){let a=r==null?void 0:r.redirectTo,i=null,o=null,l=null;this.flowType==="pkce"&&([i,o,l]=await this._getCodeChallengeAndMethod(),a=this._maybeAppendFlowIdToRedirect(a,l));const c=[`provider=${encodeURIComponent(n)}`];if(a&&c.push(`redirect_to=${encodeURIComponent(a)}`),r!=null&&r.scopes&&c.push(`scopes=${encodeURIComponent(r.scopes)}`),i!=null&&o!=null){const u=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(o)}`});c.push(u.toString())}if(r!=null&&r.queryParams){const u=new URLSearchParams(r.queryParams);c.push(u.toString())}return r!=null&&r.skipBrowserRedirect&&c.push(`skip_http_redirect=${r.skipBrowserRedirect}`),{url:`${t}?${c.join("&")}`,flowId:l}}_maybeAppendFlowIdToRedirect(t,n){return!t||!n||!this.experimental.appendPkceFlowIdToRedirects?t??void 0:Nie(t,n)}async _getCodeChallengeAndMethod(t=!1){return Sie(this.storage,this.storageKey,t,n=>this._debug("#_getCodeChallengeAndMethod()","evicted oldest pending PKCE verifier slot",n))}async _unenroll(t){try{return await this._useSession(async n=>{var r;const{data:a,error:i}=n;return i?this._returnResult({data:null,error:i}):await gt(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(r=a==null?void 0:a.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(at(n))return this._returnResult({data:null,error:n});throw n}}async _enroll(t){try{return await this._useSession(async n=>{var r,a;const{data:i,error:o}=n;if(o)return this._returnResult({data:null,error:o});const l=Object.assign({friendly_name:t.friendlyName,factor_type:t.factorType},t.factorType==="phone"?{phone:t.phone}:t.factorType==="totp"?{issuer:t.issuer}:{}),{data:c,error:u}=await gt(this.fetch,"POST",`${this.url}/factors`,{body:l,headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return u?this._returnResult({data:null,error:u}):(t.factorType==="totp"&&c.type==="totp"&&(!((a=c==null?void 0:c.totp)===null||a===void 0)&&a.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),this._returnResult({data:c,error:null}))})}catch(n){if(at(n))return this._returnResult({data:null,error:n});throw n}}async _verify(t){const n=async()=>{try{return await this._useSession(async r=>{var a;const{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});const l=Object.assign({challenge_id:t.challengeId},"webauthn"in t?{webauthn:Object.assign(Object.assign({},t.webauthn),{credential_response:t.webauthn.type==="create"?jO(t.webauthn.credential_response):NO(t.webauthn.credential_response)})}:{code:t.code}),{data:c,error:u}=await gt(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:l,headers:this.headers,jwt:(a=i==null?void 0:i.session)===null||a===void 0?void 0:a.access_token});return u?this._returnResult({data:null,error:u}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+c.expires_in},c)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",c),this._returnResult({data:c,error:u}))})}catch(r){if(at(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,n):n()}async _challenge(t){const n=async()=>{try{return await this._useSession(async r=>{var a;const{data:i,error:o}=r;if(o)return this._returnResult({data:null,error:o});const l=await gt(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{body:t,headers:this.headers,jwt:(a=i==null?void 0:i.session)===null||a===void 0?void 0:a.access_token});if(l.error)return l;const{data:c}=l;if(c.type!=="webauthn")return{data:c,error:null};switch(c.webauthn.type){case"create":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:_O(c.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},c),{webauthn:Object.assign(Object.assign({},c.webauthn),{credential_options:Object.assign(Object.assign({},c.webauthn.credential_options),{publicKey:kO(c.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(r){if(at(r))return this._returnResult({data:null,error:r});throw r}};return this.lock!=null?this._acquireLock(this.lockAcquireTimeout,n):n()}async _challengeAndVerify(t){const{data:n,error:r}=await this._challenge({factorId:t.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:t.factorId,challengeId:n.id,code:t.code})}async _listFactors(){var t;const{data:{user:n},error:r}=await this.getUser();if(r)return{data:null,error:r};const a={all:[],phone:[],totp:[],webauthn:[]};for(const i of(t=n==null?void 0:n.factors)!==null&&t!==void 0?t:[])a.all.push(i),i.status==="verified"&&a[i.factor_type].push(i);return{data:a,error:null}}async _getAuthenticatorAssuranceLevel(t){var n,r,a,i;if(t)try{const{payload:m}=dg(t);let x=null;m.aal&&(x=m.aal);let g=x;const{data:{user:y},error:b}=await this.getUser(t);if(b)return this._returnResult({data:null,error:b});((r=(n=y==null?void 0:y.factors)===null||n===void 0?void 0:n.filter(_=>_.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(g="aal2");const w=m.amr||[];return{data:{currentLevel:x,nextLevel:g,currentAuthenticationMethods:w},error:null}}catch(m){if(at(m))return this._returnResult({data:null,error:m});throw m}const{data:{session:o},error:l}
753=await this.getSession();if(l)return this._returnResult({data:null,error:l});if(!o)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:c}=dg(o.access_token);let u=null;c.aal&&(u=c.aal);let d=u;((i=(a=o.user.factors)===null||a===void 0?void 0:a.filter(m=>m.status==="verified"))!==null&&i!==void 0?i:[]).length>0&&(d="aal2");const f=c.amr||[];return{data:{currentLevel:u,nextLevel:d,currentAuthenticationMethods:f},error:null}}async _getAuthorizationDetails(t){try{return await this._useSession(async n=>{const{data:{session:r},error:a}=n;return a?this._returnResult({data:null,error:a}):r?await gt(this.fetch,"GET",`${this.url}/oauth/authorizations/${t}`,{headers:this.headers,jwt:r.access_token,xform:i=>({data:i,error:null})}):this._returnResult({data:null,error:new xs})})}catch(n){if(at(n))return this._returnResult({data:null,error:n});throw n}}async _approveAuthorization(t,n){try{return await this._useSession(async r=>{const{data:{session:a},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!a)return this._returnResult({data:null,error:new xs});const o=await gt(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:a.access_token,body:{action:"approve"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&Is()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(at(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(t,n){try{return await this._useSession(async r=>{const{data:{session:a},error:i}=r;if(i)return this._returnResult({data:null,error:i});if(!a)return this._returnResult({data:null,error:new xs});const o=await gt(this.fetch,"POST",`${this.url}/oauth/authorizations/${t}/consent`,{headers:this.headers,jwt:a.access_token,body:{action:"deny"},xform:l=>({data:l,error:null})});return o.data&&o.data.redirect_url&&Is()&&!(n!=null&&n.skipBrowserRedirect)&&window.location.assign(o.data.redirect_url),o})}catch(r){if(at(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?await gt(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,xform:a=>({data:a,error:null})}):this._returnResult({data:null,error:new xs})})}catch(t){if(at(t))return this._returnResult({data:null,error:t});throw t}}async _revokeOAuthGrant(t){try{return await this._useSession(async n=>{const{data:{session:r},error:a}=n;return a?this._returnResult({data:null,error:a}):r?(await gt(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:r.access_token,query:{client_id:t.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new xs})})}catch(n){if(at(n))return this._returnResult({data:null,error:n});throw n}}async fetchJwk(t,n={keys:[]}){let r=n.keys.find(l=>l.kid===t);if(r)return r;const a=Date.now();if(r=this.jwks.keys.find(l=>l.kid===t),r&&this.jwks_cached_at+nie>a)return r;const{data:i,error:o}=await gt(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(o)throw o;return!i.keys||i.keys.length===0||(this.jwks=i,this.jwks_cached_at=a,r=i.keys.find(l=>l.kid===t),!r)?null:r}async getClaims(t,n={}){try{let r=t;if(!r){const{data:m,error:x}
753=await this.getSession();if(x||!m.session)return this._returnResult({data:null,error:x});r=m.session.access_token}const{header:a,payload:i,signature:o,raw:{header:l,payload:c}}=dg(r);if(!(n!=null&&n.allowExpired))try{Aie(i.exp)}catch(m){throw new nb(m instanceof Error?m.message:"JWT validation failed")}const u=!a.alg||a.alg.startsWith("HS")||!a.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(a.kid,n!=null&&n.keys?{keys:n.keys}:n==null?void 0:n.jwks);if(!u){const{error:m}=await this.getUser(r);if(m)throw m;return{data:{claims:i,header:a,signature:o},error:null}}const d=Tie(a.alg),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,o,die(`${l}.${c}`)))throw new nb("Invalid JWT signature");return{data:{claims:i,header:a,signature:o},error:null}}catch(r){if(at(r))return this._returnResult({data:null,error:r});throw r}}async signInWithPasskey(t){var n,r,a;uo(this.experimental);try{if(!ab())return this._returnResult({data:null,error:new mo("Browser does not support WebAuthn",null)});const{data:i,error:o}=await this._startPasskeyAuthentication({options:{captchaToken:(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.captchaToken}});if(o||!i)return this._returnResult({data:null,error:o});const l=kO(i.options),c=(a=(r=t==null?void 0:t.options)===null||r===void 0?void 0:r.signal)!==null&&a!==void 0?a:mN.createNewAbortSignal(),{data:u,error:d}=await FF({publicKey:l,signal:c});if(d||!u)return this._returnResult({data:null,error:d??new mo("WebAuthn ceremony failed",null)});const h=NO(u);return this._verifyPasskeyAuthentication({challengeId:i.challenge_id,credential:h})}catch(i){if(at(i))return this._returnResult({data:null,error:i});throw i}}async registerPasskey(t){var n,r;uo(this.experimental);try{if(!ab())return this._returnResult({data:null,error:new mo("Browser does not support WebAuthn",null)});const{data:a,error:i}=await this._startPasskeyRegistration();if(i||!a)return this._returnResult({data:null,error:i});const o=_O(a.options),l=(r=(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.signal)!==null&&r!==void 0?r:mN.createNewAbortSignal(),{data:c,error:u}=await LF({publicKey:o,signal:l});if(u||!c)return this._returnResult({data:null,error:u??new mo("WebAuthn ceremony failed",null)});const d=jO(c);return this._verifyPasskeyRegistration({challengeId:a.challenge_id,credential:d})}catch(a){if(at(a))return this._returnResult({data:null,error:a});throw a}}async _startPasskeyRegistration(){uo(this.experimental);try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;if(r)return this._returnResult({data:null,error:r});if(!n)return this._returnResult({data:null,error:new xs});const{data:a,error:i}=await gt(this.fetch,"POST",`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:n.access_token,body:{}});return i?this._returnResult({data:null,error:i}):this._returnResult({data:a,error:null})})}catch(t){if(at(t))return this._returnResult({data:null,error:t});throw t}}async _verifyPasskeyRegistration(t){uo(this.experimental);try{return await this._useSession(async n=>{const{data:{session:r},error:a}=n;if(a)return this._returnResult({data:null,error:a});if(!r)return this._returnResult({data:null,error:new xs});const{data:i,error:o}=await gt(this.fetch,"POST",`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:r.access_token,body:{challenge_id:t.challengeId,credential:t.credential}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(n){if(at(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyAuthentication(t){var n;uo(this.experimental);try{const{data:r,error:a}=await gt(this.fetch,"POST",`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.captchaToken}}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:r,error:null})}catch(r){if(at(r))return this._returnResult({data:null,error:r});throw r}}async _verifyPasskeyAuthentication(t){uo(this.experimental);try{const{data:n,error:r}=await gt(this.fetch,"POST",`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:t.challengeId,credential:t.credential},xform:Ii});return r?this._returnResult({data:null,error:r}):(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:n,error:null}))}catch(n){if(at(n))return this._returnResult({data:null,error:n});throw n}}async _listPasskeys(){uo(this.experimental);try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;if(r)return this._returnResult({data:null,error:r});if(!n)return this._returnResult({data:null,error:new xs});const{data:a,error:i}=await gt(this.fetch,"GET",`${this.url}/passkeys`,{headers:this.headers,jwt:n.access_token,xform:o=>({data:o,error:null})});return i?this._returnResult({data:null,error:i}):this._returnResult({data:a,error:null})})}catch(t){if(at(t))return this._returnResult({data:null,error:t});throw t}}async _updatePasskey(t){uo(this.experimental);try{return await this._useSession(async n=>{const{data:{session:r},error:a}=n;
753if(a)return this._returnResult({data:null,error:a});if(!r)return this._returnResult({data:null,error:new xs});const{data:i,error:o}=await gt(this.fetch,"PATCH",`${this.url}/passkeys/${t.passkeyId}`,{headers:this.headers,jwt:r.access_token,body:{friendly_name:t.friendlyName}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:i,error:null})})}catch(n){if(at(n))return this._returnResult({data:null,error:n});throw n}}async _deletePasskey(t){uo(this.experimental);try{return await this._useSession(async n=>{const{data:{session:r},error:a}=n;if(a)return this._returnResult({data:null,error:a});if(!r)return this._returnResult({data:null,error:new xs});const{error:i}=await gt(this.fetch,"DELETE",`${this.url}/passkeys/${t.passkeyId}`,{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return i?this._returnResult({data:null,error:i}):this._returnResult({data:null,error:null})})}catch(n){if(at(n))return this._returnResult({data:null,error:n});throw n}}}bp.nextInstanceID={};const Qie=bp,eoe="2.112.3";let $m="",ob;if(typeof Deno<"u"){var r1;$m="deno",ob=(r1=Deno.version)===null||r1===void 0?void 0:r1.deno}else if(typeof document<"u")$m="web";else if(typeof navigator<"u"&&navigator.product==="ReactNative")$m="react-native";else{var s1;$m="node";const e=globalThis.process;ob=e==null||(s1=e.version)===null||s1===void 0?void 0:s1.replace(/^v/,"")}const BF=[`runtime=${$m}`];ob&&BF.push(`runtime-version=${ob}`);const toe={"X-Client-Info":`supabase-js/${eoe}; ${BF.join("; ")}`},noe={headers:toe},roe={schema:"public"},soe={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},aoe={},ioe={enabled:!1,respectSamplingDecision:!0};function ooe(e){if(!e||typeof e!="string")return null;const t=e.split("-");if(t.length!==4)return null;const[n,r,a,i]=t;if(n.length!==2||r.length!==32||a.length!==16||i.length!==2)return null;const o=/^[0-9a-f]+$/i;return!o.test(n)||!o.test(r)||!o.test(a)||!o.test(i)||r==="00000000000000000000000000000000"||a==="0000000000000000"?null:{version:n,traceId:r,parentId:a,traceFlags:i,isSampled:(parseInt(i,16)&1)===1}}function loe(e,t){if(!e||!t||t.length===0)return!1;let n;if(e instanceof URL)n=e;else try{n=new URL(e)}catch{return!1}for(const r of t)try{if(typeof r=="string"){if(coe(n.hostname,r))return!0}else if(r instanceof RegExp){if(r.test(n.hostname))return!0}else if(typeof r=="function"&&r(n))return!0}catch{continue}return!1}function coe(e,t){if(t===e)return!0;if(t.startsWith("*.")){const n=t.slice(2);if(e.endsWith(n)&&(e===n||e.endsWith("."+n)))return!0}return!1}function uoe(e){const t=[];try{const n=new URL(e);t.push(n.hostname)}catch{}return t.push("*.supabase.co","*.supabase.in"),t.push("localhost","127.0.0.1","[::1]"),t}function vp(e){"@babel/helpers - typeof";return vp=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},vp(e)}function doe(e,t){if(vp(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(vp(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function hoe(e){var t=doe(e,"string");return vp(t)=="symbol"?t:t+""}function foe(e,t,n){return(t=hoe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function SO(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Ir(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?SO(Object(n),!0).forEach(function(r){foe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):SO(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}const moe=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),poe=()=>Headers,UF=e=>e.startsWith("sb_publishable_")||e.startsWith("sb_secret_"),xoe="sb_temp_",CO=new Set,goe=e=>{var t,n;if(!e.startsWith("sb_")||UF(e)||e.startsWith(xoe))return;const r=(t=(n=e.match(/^sb_[a-zA-Z0-9]+_/))===null||n===void 0?void 0:n[0])!==null&&t!==void 0?t:"unknown";CO.has(r)||(CO.add(r),console.warn("@supabase/supabase-js: Unrecognized Supabase API key format. The client will proceed and send this key as-is;
753 if you see authentication errors you may need to upgrade @supabase/supabase-js to a version that recognizes this key type."))},EO=(e,t,n,r,a,i)=>{const o=moe(r),l=poe(),c=(a==null?void 0:a.enabled)===!0,u=(a==null?void 0:a.respectSamplingDecision)!==!1,d=c?uoe(t):null,h=!(i!=null&&i.omitApiKeyAsBearer&&UF(e));return async(f,m)=>{const x=await n();let g=new l(m==null?void 0:m.headers);if(g.has("apikey")||g.set("apikey",e),!g.has("Authorization")){const y=x??(h?e:null);y&&g.set("Authorization",`Bearer ${y}`)}if(d){const y=yoe(f,d,u);y&&(y.traceparent&&!g.has("traceparent")&&g.set("traceparent",y.traceparent),y.tracestate&&!g.has("tracestate")&&g.set("tracestate",y.tracestate),y.baggage&&!g.has("baggage")&&g.set("baggage",y.baggage))}return o(f,Ir(Ir({},m),{},{headers:g}))}};let AO=!1,TO=!1;function yoe(e,t,n){const r=yse();if(!r)return AO||(AO=!0,console.warn("@supabase/supabase-js: tracePropagation is enabled but the tracing runtime is not loaded, so trace headers will not be attached. Add `import '@supabase/supabase-js/tracing'` at your application entry point (requires the OpenTelemetry API package to be installed). The CDN/UMD build does not support trace propagation.")),null;if(!loe(typeof e=="string"||e instanceof URL?e:e.url,t))return null;const a=r();if(!a||!a.traceparent){var i;if(!(a==null||(i=a.carrierKeys)===null||i===void 0)&&i.length&&!TO){TO=!0;const o=a.carrierKeys.includes("sentry-trace")?" Sentry detected: set `propagateTraceparent: true` in Sentry.init() to emit it.":" Configure your tracing SDK to emit W3C trace context on outgoing requests.";console.warn(`@supabase/supabase-js: tracePropagation is enabled and a tracing SDK is active, but its propagator wrote [${a.carrierKeys.join(", ")}] and no W3C traceparent header, so trace headers will not be attached.`+o)}return null}if(n){const o=ooe(a.traceparent);if(o&&!o.isSampled)return{traceparent:a.traceparent}}return a}function OO(e){return typeof e=="boolean"?{enabled:e}:e}function boe(e){return e.endsWith("/")?e:e+"/"}function voe(e,t){var n,r,a,i,o,l;const{db:c,auth:u,realtime:d,global:h}=e,{db:f,auth:m,realtime:x,global:g}=t,y=OO(e.tracePropagation),b=OO(t.tracePropagation),v={db:Ir(Ir({},f),c),auth:Ir(Ir({},m),u),realtime:Ir(Ir({},x),d),storage:{},global:Ir(Ir(Ir({},g),h),{},{headers:Ir(Ir({},(n=g==null?void 0:g.headers)!==null&&n!==void 0?n:{}),(r=h==null?void 0:h.headers)!==null&&r!==void 0?r:{})}),tracePropagation:{enabled:(a=(i=y==null?void 0:y.enabled)!==null&&i!==void 0?i:b==null?void 0:b.enabled)!==null&&a!==void 0?a:!1,respectSamplingDecision:(o=(l=y==null?void 0:y.respectSamplingDecision)!==null&&l!==void 0?l:b==null?void 0:b.respectSamplingDecision)!==null&&o!==void 0?o:!0},accessToken:async()=>""};return e.accessToken?v.accessToken=e.accessToken:delete v.accessToken,v}function woe(e){const t=e==null?void 0:e.trim();if(!t)throw new Error("supabaseUrl is required.");if(!t.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(boe(t))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var _oe=class extends Qie{constructor(e){super(e)}},koe=class{constructor(e,t,n){var r,a;this.supabaseUrl=e,this.supabaseKey=t;const i=woe(e);if(!t)throw new Error("supabaseKey is required.");goe(t),this.realtimeUrl=new URL("realtime/v1",i),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",i),this.storageUrl=new URL("storage/v1",i),this.functionsUrl=new URL("functions/v1",i);const o=`sb-${i.hostname.split(".")[0]}-auth-token`,l={db:roe,realtime:aoe,auth:Ir(Ir({},soe),{},{storageKey:o}),global:noe,tracePropagation:ioe},c=voe(n??{},l);if(this.settings=c,this.storageKey=(r=c.auth.storageKey)!==null&&r!==void 0?r:"",this.headers=(a=c.global.headers)!==null&&a!==void 0?a:{},c.accessToken)this.accessToken=c.accessToken,this.auth=new Proxy({},{get:(d,h)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`)}});else{var u;this.auth=this._initSupabaseAuthClient((u=c.auth)!==null&&u!==void 0?u:{},this.headers,c.global.fetch)}this.fetch=EO(t,e,this._getSessionToken.bind(this),c.global.fetch,c.tracePropagation),this.functionsFetch=EO(t,e,this._getSessionToken.bind(this),c.global.fetch,c.tracePropagation,{omitApiKeyAsBearer
753:!0}),this.realtime=this._initRealtimeClient(Ir({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},c.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(d=>this.realtime.setAuth(d)).catch(d=>console.warn("Failed to set initial Realtime auth token:",d)),this.rest=new Tse(new URL("rest/v1",i).href,{headers:this.headers,schema:c.db.schema,fetch:this.fetch,timeout:c.db.timeout,urlLengthLimit:c.db.urlLengthLimit,retry:c.db.retry}),this.storage=new Yae(this.storageUrl.href,this.headers,this.fetch,n==null?void 0:n.storage),c.accessToken||this._listenForAuthEvents()}get functions(){return new wse(this.functionsUrl.href,{headers:this.headers,customFetch:this.functionsFetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,n)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getSessionToken(){var e=this,t,n;if(e.accessToken)return await e.accessToken();const{data:r}=await e.auth.getSession();return(t=(n=r.session)===null||n===void 0?void 0:n.access_token)!==null&&t!==void 0?t:null}async _getAccessToken(){var e=this,t;return(t=await e._getSessionToken())!==null&&t!==void 0?t:e.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:a,storageKey:i,flowType:o,lock:l,debug:c,throwOnError:u,experimental:d,lockAcquireTimeout:h,skipAutoInitialize:f},m,x){const g={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new _oe({url:this.authUrl.href,headers:Ir(Ir({},g),m),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:a,flowType:o,lock:l,debug:c,throwOnError:u,experimental:d,fetch:x,lockAcquireTimeout:h,skipAutoInitialize:f,hasCustomAuthorizationHeader:Object.keys(this.headers).some(y=>y.toLowerCase()==="authorization")})}_initRealtimeClient(e){return new bae(this.realtimeUrl.href,Ir(Ir({},e),{},{params:Ir(Ir({},{apikey:this.supabaseKey}),e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",t==null?void 0:t.access_token)})}_handleTokenChanged(e,t,n){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN"||e==="INITIAL_SESSION")&&this.changedAccessToken!==n?(this.changedAccessToken=n,this.realtime.setAuth(n)):e==="SIGNED_OUT"&&(this.realtime.setAuth(),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const joe=(e,t,n)=>new koe(e,t,n);function Noe(){if(typeof window<"u"||globalThis.Deno!==void 0)return!1;const e=globalThis.process;if(!e)return!1;const t=e.version;if(t==null)return!1;const n=t.match(/^v(\d+)\./);return n?parseInt(n[1],10)<=20:!1}Noe()&&console.warn("â ï¸ Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715");/*! Capacitor: https://capacitorjs.com/ - MIT License */var Vh;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(Vh||(Vh={}));class a1 extends Error{constructor(t,n,r){super(t),this.message=t,this.code=n,this.data=r}}const Soe=e=>{var t,n;return e!=null&&e.androidBridge?"android":!((n=(t=e==null?void 0:e.webkit)===null||t===void 0?void 0:t.messageHandlers)===null||n===void 0)&&n.bridge?"ios":"web"},Coe=e=>{const t=e.CapacitorCustomPlatform||null,n=e.Capacitor||{},r=n.Plugins=n.Plugins||{},a=()=>t!==null?t.name:Soe(e),i=()=>a()!=="web",o=h=>{const f=u.get(h);return!!(f!=null&&f.platforms.has(a())||l(h))},l=h=>{var f;return(f=n.PluginHeaders)===null||f===void 0?void 0:f.find(m=>m.name===h)},c=h=>e.console.error(h),u=new Map,d=(h,f={})=>{const m=u.get(h);if(m)return console.warn(`Capacitor plugin "${h}" already registered. Cannot register plugins twice.`),m.proxy;const x=a(),g=l(h);let y;const b=async()=>(!y&&x in f?y=typeof f[x]=="function"?y=await f[x]():y=f[x]:t!==null&&!y&&"web"in f&&(y=typeof f.web=="function"?y=await f.web():y=f.web),y),v=(E,A)=>{var C,T;if(g){const S=g==null?void 0:g.methods.find(O=>A===O.name);if(S)return S.rtype==="promise"?O=>n.nativePromise(h,A.toString(),O):(O,R)=>n.nativeCallback(h,A.toString(),O,R);if(E)return(C=E[A])===null||C===void 0?void 0:C.bind(E)}else{if(E)return(T=E[A])===null||T===void 0?void 0:T.bind(E);throw new a1(`"${h}" plugin is not implemented on ${x}`,Vh.Unimplemented)}},w=E=>{let A;const C=(...T)=>{const S=b().then(O=>{const R=v(O,E);if(R){const I=R(...T);return A=I==null?void 0:I.remove,I}else throw new a1(`"${h}.${E}()" is not implemented on ${x}`,Vh.Unimplemented)});return E==="addListener"&&(S.remove=async()=>A()),S};return C.toString=()=>`${E.toString()}() { [capacitor code] }
753`,Object.defineProperty(C,"name",{value:E,writable:!1,configurable:!1}),C},_=w("addListener"),k=w("removeListener"),j=(E,A)=>{const C=_({eventName:E},A),T=async()=>{const O=await C;k({eventName:E,callbackId:O},A)},S=new Promise(O=>C.then(()=>O({remove:T})));return S.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await T()},S},N=new Proxy({},{get(E,A){switch(A){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return g?j:_;case"removeListener":return k;default:return w(A)}}});return r[h]=N,u.set(h,{name:h,proxy:N,platforms:new Set([...Object.keys(f),...g?[x]:[]])}),N};return n.convertFileSrc||(n.convertFileSrc=h=>h),n.getPlatform=a,n.handleError=c,n.isNativePlatform=i,n.isPluginAvailable=o,n.registerPlugin=d,n.Exception=a1,n.DEBUG=!!n.DEBUG,n.isLoggingEnabled=!!n.isLoggingEnabled,n},Eoe=e=>e.Capacitor=Coe(e),wd=Eoe(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),vf=wd.registerPlugin;class Z2{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(t,n){let r=!1;this.listeners[t]||(this.listeners[t]=[],r=!0),this.listeners[t].push(n);const i=this.windowListeners[t];i&&!i.registered&&this.addWindowListener(i),r&&this.sendRetainedArgumentsForEvent(t);const o=async()=>this.removeListener(t,n);return Promise.resolve({remove:o})}async removeAllListeners(){this.listeners={};for(const t in this.windowListeners)this.removeWindowListener(this.windowListeners[t]);this.windowListeners={}}notifyListeners(t,n,r){const a=this.listeners[t];if(!a){if(r){let i=this.retainedEventArguments[t];i||(i=[]),i.push(n),this.retainedEventArguments[t]=i}return}a.forEach(i=>i(n))}hasListeners(t){var n;return!!(!((n=this.listeners[t])===null||n===void 0)&&n.length)}registerWindowListener(t,n){this.windowListeners[n]={registered:!1,windowEventName:t,pluginEventName:n,handler:r=>{this.notifyListeners(n,r)}}}unimplemented(t="not implemented"){return new wd.Exception(t,Vh.Unimplemented)}unavailable(t="not available"){return new wd.Exception(t,Vh.Unavailable)}async removeListener(t,n){const r=this.listeners[t];if(!r)return;const a=r.indexOf(n);this.listeners[t].splice(a,1),this.listeners[t].length||this.removeWindowListener(this.windowListeners[t])}addWindowListener(t){window.addEventListener(t.windowEventName,t.handler),t.registered=!0}removeWindowListener(t){t&&(window.removeEventListener(t.windowEventName,t.handler),t.registered=!1)}sendRetainedArgumentsForEvent(t){const n=this.retainedEventArguments[t];n&&(delete this.retainedEventArguments[t],n.forEach(r=>{this.notifyListeners(t,r)}))}}const IO=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),PO=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class Aoe extends Z2{async getCookies(){const t=document.cookie,n={};return t.split(";").forEach(r=>{if(r.length<=0)return;let[a,i]=r.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");a=PO(a).trim(),i=PO(i).trim(),n[a]=i}),n}async setCookie(t){try{const n=IO(t.key),r=IO(t.value),a=t.expires?`; expires=${t.expires.replace("expires=","")}`:"",i=(t.path||"/").replace("path=",""),o=t.url!=null&&t.url.length>0?`domain=${t.url}`:"";document.cookie=`${n}=${r||""}${a}; path=${i}; ${o};`}catch(n){return Promise.reject(n)}}async deleteCookie(t){try{document.cookie=`${t.key}=; Max-Age=0`}catch(n){return Promise.reject(n)}}async clearCookies(){try{const t=document.cookie.split(";")||[];for(const n of t)document.cookie=n.replace(/^ +/,"").replace(/=.*/,`=;expires=${new Date().toUTCString()};path=/`)}catch(t){return Promise.reject(t)}}async clearAllCookies(){try{await this.clearCookies()}catch(t){return Promise.reject(t)}}}vf("CapacitorCookies",{web:()=>new Aoe});const Toe=async e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const a=r.result;t(a.indexOf(",")>=0?a.split(",")[1]:a)},r.onerror=a=>n(a),r.readAsDataURL(e)}),Ooe=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(a=>a.toLocaleLowerCase()).reduce((a,i,o)=>(a[i]=e[t[o]],a),{})},Ioe=(e,t=!0)=>e?Object.entries(e).reduce((r,a)=>{const[i,o]=a;let l,c;return Array.isArray(o)?(c="",o.forEach(u=>{l=t?encodeURIComponent(u):u,c+=`${i}=${l}&`}),c.slice(0,-1)):(l=t?encodeURIComponent(o):o,c=`${i}=${l}`),`${r}&${c}`},"").substr(1):null,Poe=(e,t={})=>{const n=Object.assign({method:e.method||"GET",headers:e.headers},t),a=Ooe(e.headers)["content-type"]||"";
753if(typeof e.data=="string")n.body=e.data;else if(a.includes("application/x-www-form-urlencoded")){const i=new URLSearchParams;for(const[o,l]of Object.entries(e.data||{}))i.set(o,l);n.body=i.toString()}else if(a.includes("multipart/form-data")||e.data instanceof FormData){const i=new FormData;if(e.data instanceof FormData)e.data.forEach((l,c)=>{i.append(c,l)});else for(const l of Object.keys(e.data))i.append(l,e.data[l]);n.body=i;const o=new Headers(n.headers);o.delete("content-type"),n.headers=o}else(a.includes("application/json")||typeof e.data=="object")&&(n.body=JSON.stringify(e.data));return n};class Roe extends Z2{async request(t){const n=Poe(t,t.webFetchExtra),r=Ioe(t.params,t.shouldEncodeUrlParams),a=r?`${t.url}?${r}`:t.url,i=await fetch(a,n),o=i.headers.get("content-type")||"";let{responseType:l="text"}=i.ok?t:{};o.includes("application/json")&&(l="json");let c,u;switch(l){case"arraybuffer":case"blob":u=await i.blob(),c=await Toe(u);break;case"json":c=await i.json();break;case"document":case"text":default:c=await i.text()}const d={};return i.headers.forEach((h,f)=>{d[f]=h}),{data:c,headers:d,status:i.status,url:i.url}}async get(t){return this.request(Object.assign(Object.assign({},t),{method:"GET"}))}async post(t){return this.request(Object.assign(Object.assign({},t),{method:"POST"}))}async put(t){return this.request(Object.assign(Object.assign({},t),{method:"PUT"}))}async patch(t){return this.request(Object.assign(Object.assign({},t),{method:"PATCH"}))}async delete(t){return this.request(Object.assign(Object.assign({},t),{method:"DELETE"}))}}vf("CapacitorHttp",{web:()=>new Roe});var RO;(function(e){e.Dark="DARK",e.Light="LIGHT",e.Default="DEFAULT"})(RO||(RO={}));var DO;(function(e){e.StatusBar="StatusBar",e.NavigationBar="NavigationBar"})(DO||(DO={}));class Doe extends Z2{async setStyle(){this.unavailable("not available for web")}async setAnimation(){this.unavailable("not available for web")}async show(){this.unavailable("not available for web")}async hide(){this.unavailable("not available for web")}}vf("SystemBars",{web:()=>new Doe});const MO=vf("App",{web:()=>Yl(()=>import("./web-BK_mE1SZ.js"),__vite__mapDeps([0,1,2])).then(e=>new e.AppWeb)}),zF=vf("Browser",{web:()=>Yl(()=>import("./web-BPRVA1HR.js"),__vite__mapDeps([3,1,2])).then(e=>new e.BrowserWeb)});var $O;(function(e){e.missingKey="missingKey",e.invalidData="invalidData",e.osError="osError",e.unknownError="unknownError"})($O||($O={}));var LO;(function(e){e[e.whenUnlocked=0]="whenUnlocked",e[e.whenUnlockedThisDeviceOnly=1]="whenUnlockedThisDeviceOnly",e[e.afterFirstUnlock=2]="afterFirstUnlock",e[e.afterFirstUnlockThisDeviceOnly=3]="afterFirstUnlockThisDeviceOnly",e[e.whenPasscodeSetThisDeviceOnly=4]="whenPasscodeSetThisDeviceOnly"})(LO||(LO={}));class mrt extends Error{constructor(t,n){super(t),this.name="StorageError",this.code=n}}const Zm=vf("SecureStorage",{web:async()=>{const e=await Yl(()=>import("./web-CAOshhXL.js"),__vite__mapDeps([4,5,1,2]));return new e.SecureStorageWeb},ios:async()=>{const e=await Yl(()=>import("./native-BS7H3cZc.js"),__vite__mapDeps([6,5,1,2]));return new e.SecureStorageNative(Zm)},android:async()=>{const e=await Yl(()=>import("./native-BS7H3cZc.js"),__vite__mapDeps([6,5,1,2]));return new e.SecureStorageNative(Zm)}}),Moe={async getItem(e){try{return await Zm.getItem(e)}catch{return null}},async setItem(e,t){await Zm.setItem(e,t)},async removeItem(e){try{await Zm.removeItem(e)}catch{}}},$oe="https://opmvesjizkkbrvkxfgtl.supabase.co",Loe="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9wbXZlc2ppemtrYnJ2a3hmZ3RsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzgzODE0ODAsImV4cCI6MjA5Mzk1NzQ4MH0.3iUKW0bsvF32PxEX8-Hl1C6zFLPWHnUiL-n2WTDWgWY";function Foe(e){try{const t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password}catch{return!1}}function Boe(e){const t=e.split(".");return t.length===3&&t.every(n=>n.length>0)}function Uoe(){const e="https://opmvesjizkkbrvkxfgtl.supabase.co".trim(),t="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im9wbXZlc2ppemtrYnJ2a3hmZ3RsIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzgzODE0ODAsImV4cCI6MjA5Mzk1NzQ4MH0.3iUKW0bsvF32PxEX8-Hl1C6zFLPWHnUiL-n2WTDWgWY".trim(),n=Foe(e)?e:"",r=Boe(t)?t:"";return n&&r?{url:n,anonKey:r}:{url:n||$oe,anonKey:r||Loe}}const{url:zoe,anonKey:Woe}=Uoe(),pN=wd.isNativePlatform(),WF="ai.gadjet.app://auth/callback";let xN=!1;const xn=joe(zoe,Woe,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!pN,flowType:"pkce",...pN?{storage:Moe}:{}}});pN&&(MO.addListener("appStateChange",({isActive:e})=>{e?xn.auth.startAutoRefresh():xn.auth.stopAutoRefresh()}),MO.addListener("appUrlOpen",async({url:e})=>
753{if(xN&&e.startsWith(WF)){xN=!1;try{const t=e.replace(/^ai\.gadjet\.app:\/\//i,"https://ai.gadjet.app/"),r=new URL(t).searchParams.get("code");r&&await xn.auth.exchangeCodeForSession(r)}catch(t){console.error("[oauth] exchangeCodeForSession failed",t)}finally{try{await zF.close()}catch{}window.location.href="/"}}}));async function KF(){var t;const{data:e}=await xn.auth.getSession();return((t=e.session)==null?void 0:t.access_token)??null}async function Koe(e,t={}){var h,f;e=e;const n=new Headers(t.headers||{}),r=X2();if(r)return n.set("X-PDF-Print-Token",r),await fetch(e,{...t,headers:n});const a=await KF();a&&n.set("Authorization",`Bearer ${a}`);const i=HF();i&&n.set("X-Impersonate-Token",i);const o=qF();o&&n.set("X-Demo-View-Token",o);const l=await fetch(e,{...t,headers:n});if(l.status===401&&i){const m=l.clone();try{const x=await m.json();typeof(x==null?void 0:x.error)=="string"&&x.error.startsWith("impersonation_")&&eC()}catch{}}if(l.status===401&&o){const m=l.clone();try{const x=await m.json();typeof(x==null?void 0:x.error)=="string"&&x.error.startsWith("demo_view_")&&rC()}catch{}}if(l.status!==401||!a)return l;const c=await xn.auth.refreshSession(),u=(f=(h=c.data)==null?void 0:h.session)==null?void 0:f.access_token;if(!u||c.error)return l;const d=new Headers(t.headers||{});return d.set("Authorization",`Bearer ${u}`),i&&d.set("X-Impersonate-Token",i),o&&d.set("X-Demo-View-Token",o),fetch(e,{...t,headers:d})}function Hoe(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}async function oe(e,t={}){const n=(t.method||"GET").toUpperCase(),r=Hoe(e);let a;try{a=await Koe(e,t)}catch(i){throw kY({method:n,url:r,error:i}),i}return a.ok||_Y({method:n,url:r,status:a.status,requestId:a.headers.get("X-Request-Id")}),a}const FO="gadjet:pdf-print-token";function X2(){if(typeof window>"u")return null;try{const e=new URLSearchParams(window.location.search);if(e.get("print")!=="1")return null;let t=null;try{t=sessionStorage.getItem(FO)}catch{t=null}const n=e.get("pdf_token");if((!t||t.length===0)&&n){t=n;try{sessionStorage.setItem(FO,n)}catch{}}if(n){e.delete("pdf_token");const r=e.toString(),a=`${window.location.pathname}${r?`?${r}`:""}${window.location.hash}`;window.history.replaceState(window.history.state,"",a)}return t&&t.length>0?t:null}catch{return null}}function Wc(){return X2()!=null}const J2="gadjet:impersonation-token",Q2="gadjet:impersonation-meta";function HF(){try{return localStorage.getItem(J2)}catch{return null}}function gN(){try{const e=localStorage.getItem(Q2);return e?JSON.parse(e):null}catch{return null}}function VF(e,t){try{localStorage.setItem(J2,e),localStorage.setItem(Q2,JSON.stringify(t)),window.dispatchEvent(new CustomEvent("gadjet:impersonation-changed"))}catch{}}function eC(){try{localStorage.removeItem(J2),localStorage.removeItem(Q2),window.dispatchEvent(new CustomEvent("gadjet:impersonation-changed"))}catch{}}const tC="gadjet:demo-view-token",nC="gadjet:demo-view-meta";function qF(){try{return localStorage.getItem(tC)}catch{return null}}function yN(){try{const e=localStorage.getItem(nC);return e?JSON.parse(e):null}catch{return null}}function GF(e,t){try{localStorage.setItem(tC,e),localStorage.setItem(nC,JSON.stringify(t)),window.dispatchEvent(new CustomEvent("gadjet:demo-view-changed"))}catch{}}function rC(){try{localStorage.removeItem(tC),localStorage.removeItem(nC),window.dispatchEvent(new CustomEvent("gadjet:demo-view-changed"))}catch{}}const Voe="/";async function l0(e=Voe){if(wd.isNativePlatform()){xN=!0;const{data:n,error:r}=await xn.auth.signInWithOAuth({provider:"google",options:{redirectTo:WF,skipBrowserRedirect:!0,queryParams:{prompt:"select_account"}}});if(r)throw r;n!=null&&n.url&&await zF.open({url:n.url});return}const{error:t}=await xn.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}${e}`,queryParams:{prompt:"select_account"}}});if(t)throw t}async function sC(e,t){const{error:n}=await xn.auth.signInWithPassword({email:e,password:t});if(n)throw n}async function aC(e,t){const{error:n}=await xn.auth.signUp({email:e,password:t,options:{emailRedirectTo:`${window.location.origin}/signup`}});if(n)throw n}async function iC(e){const{error:t}=await xn.auth.resetPasswordForEmail(e,{redirectTo:`${window.location.origin}/reset-password`});if(t)throw t}async function YF(e){const{error:t}=await xn.auth.updateUser({password:e});if(t)throw t}async function wf(){await xn.auth.signOut()}const qoe=Object.freeze(Object.defineProperty({__proto__:null,authedFetch:oe,clearDemoViewToken:rC,clearImpersonationToken:eC,getAccessToken:KF,getDemoViewMeta:yN,getDemoViewToken:qF,getImpersonationMeta:gN,getImpersonationToken:HF,getPrintToken:X2,isPrintMode:Wc,sendPasswordReset:iC,setDemoView:GF,setImpersonation:VF,signInWithEmail:sC,signInWithGoogle:l0,signOut:wf,signUpWithEmail:aC,supabase:xn,updatePassword:YF},Symbol.toStringTag,{value:"Module"}));let bN={kind:"loading"};const vN=new Set;let em=null,BO=!1;function Rh(e){bN=e;for(const t of vN)t(e)}function Goe(e,t){return(e==null?void 0:e.message)||(e==null?void 0:e.hint)||(e==null?void 0:e.error)||`HTTP ${t}`}async function Yoe(){for(let t=0;;t++){const n=t>=4;try{const r=await oe("/api/me");if(r.ok){const i=await r.json();jY({id:i.id??null,email:i.email??null,role:i.role??null,accountId:i.account_id??null}),Rh({kind:"ready",me:i});return}if(r.status===429&&t===0){await new Promise(i=>setTimeout(i,2e3));continue}if(!(r.status===401||r.status===403||r.status===408||r.status>=500)||n){const i=await r.json().catch(()=>({}));Rh({kind:"error",message:Goe(i,r.status)});return}}catch(r){if(n){Rh({kind:"error",message:(r==null?void 0:r.message)||String(r)});return}}await new Promise(r=>setTimeout(r,200*2**t))}}function wN(){return em||(em=Yoe().finally(()=>{em=null}),em)}function ZF(){XF(),wN()}function XF(){if(BO)return;BO=!0;let e=null;xn.auth.getSession().then(({data:t})=>{var n,r;e=((r=(n=t.session)==null?void 0:n.user)==null?void 0:r.id)??null,e?wN():Rh({kind:"error",message:"not_authenticated"})}),xn.auth.onAuthStateChange((t,n)=>{var a;const r=((a=n==null?void 0:n.user)==null?void 0:a.id)??null;r!==e&&(e=r,r?(Rh({kind:"loading"}),wN()):(NY(),Rh({kind:"error",message:"not_authenticated"})))})}function ai(){ZF()}function Lt(){const[e,t]=p.useState(bN);return p.useEffect(()=>(XF(),vN.add(t),t(bN),()=>{vN.delete(t)}),[]),{...e,refresh:ZF}}function xu(){const[e,t]=p.useState({kind:"loading"});return p.useEffect(()=>{let n=!0;xn.auth.getSession().then(({data:a})=>{var i;n&&((i=a.session)!=null&&i.user?t({kind:"authenticated",user:a.session.user,session:a.session}):t({kind:"anonymous"}))});const{data:r}=xn.auth.onAuthStateChange((a,i)=>{n&&(i!=null&&i.user?t({kind:"authenticated",user:i.user,session:i}):t({kind:"anonymous"}))});return()=>{n=!1,r.subscription.unsubscribe()}},[]),e}const JF="__rollup__";async function Se(e){const t=await oe(e);if(!t.ok){let n=null;try{n=await t.json()}catch{}const r=new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||`${t.status} ${e}`);throw r.code=n==null?void 0:n.error,r.status=t.status,r}return t.json()}async function jt(e,t){const n=await oe(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let r=null;try{r=await n.json()}catch{}const a=new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`${n.status} ${e}`);throw a.code=r==null?void 0:r.error,a.status=n.status,a}return n.json()}function tm(e){const t=[];return e.days!=null&&t.push(`days=${e.days}`),e.since&&t.push(`since=${e.since}`),e.until&&t.push(`until=${e.until}`),e.limit!=null&&t.push(`limit=${e.limit}`),t.length?`?${t.join("&")}`:""}function hg(e){const t=[];return e.preset&&t.push(`preset=${encodeURIComponent(e.preset)}`),e.since&&t.push(`since=${encodeURIComponent(e.since)}`),e.until&&t.push(`until=${encodeURIComponent(e.until)}`),e.payout&&t.push(`payout=${encodeURIComponent(e.payout)}`),t.length?`?${t.join("&")}`:""}function Cy(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const a=String(r.result||""),i=a.includes(",")?a.split(",")[1]:a;t({mime_type:e.type,base64_data:i})},r.onerror=()=>
753n(r.error),r.readAsDataURL(e)})}const K={sellers:()=>Se("/api/sellers"),seller:e=>Se(`/api/sellers/${e}`),kpis:e=>Se(`/api/sellers/${e}/kpis`),overviewRollup:()=>Se("/api/overview/rollup"),sellerDuties:e=>Se(`/api/sellers/${e}/duties`),courier:{bookContext:(e,t)=>{const n=t&&typeof t=="object"?t:{shipmentId:t},r=new URLSearchParams;n.shipmentId&&r.set("takealot_shipment_id",String(n.shipmentId));const a=[...n.removalOrderId!=null&&n.removalOrderId!==""?[n.removalOrderId]:[],...Array.isArray(n.removalOrderIds)?n.removalOrderIds:[]];for(const o of a)r.append("removal_order_id",String(o));const i=r.toString();return Se(`/api/sellers/${e}/courier/book-context${i?`?${i}`:""}`)},rates:(e,t)=>jt(`/api/sellers/${e}/courier/rates`,t),book:(e,t)=>jt(`/api/sellers/${e}/courier/book`,t),cancel:(e,t)=>jt(`/api/sellers/${e}/courier/bookings/${t}/cancel`,{}),bookings:(e,t={})=>{const n=new URLSearchParams;t.lane&&n.set("lane",t.lane),t.open&&n.set("open","1"),t.limit&&n.set("limit",String(t.limit));const r=n.toString();return Se(`/api/sellers/${e}/courier/bookings${r?`?${r}`:""}`)},booking:(e,t)=>Se(`/api/sellers/${e}/courier/bookings/${t}`),label:async(e,t,n=!1)=>{const r=`/api/sellers/${e}/courier/bookings/${t}/label${n?"?force=1":""}`,a=await oe(r);if(!a.ok){let o=null;try{o=await a.json()}catch{}const l=new Error((o==null?void 0:o.message)||(o==null?void 0:o.error)||`${a.status} ${r}`);throw l.code=o==null?void 0:o.error,l.status=a.status,l}if((a.headers.get("content-type")||"").toLowerCase().includes("application/pdf")){const o=await a.blob();return{ok:!0,booking:null,label_url:URL.createObjectURL(o),reused:!1}}return a.json()},refresh:(e,t)=>jt(`/api/sellers/${e}/courier/bookings/${t}/refresh`,{}),wallet:e=>Se(`/api/sellers/${e}/courier/wallet`),topup:(e,t)=>jt(`/api/sellers/${e}/courier/wallet/topup`,{amount_zar:t})},ads:{performance:(e,t=30)=>Se(`/api/ads/${e}/performance?days=${t}`),import:async(e,t,n)=>{const{mime_type:r,base64_data:a}=await Cy(t),i=await oe(`/api/ads/${e}/import`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:t.name,mime:r,base64:a,campaign_ref:n??null})}),o=await i.json().catch(()=>null);if(!o||typeof o.ok>"u")throw new Error(`POST ads import ${i.status}`);return o},decideRecommendation:async(e,t)=>{const n=await oe(`/api/ads/${e}/recommendations/decide`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>null);if(!r||typeof r.ok>"u")throw new Error(`POST ads recommendation decide ${n.status}`);return r},setAlertState:async(e,t)=>{const n=await oe(`/api/ads/${e}/alerts/state`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>null);if(!r||typeof r.ok>"u")throw new Error(`POST ads alert state ${n.status}`);return r},changeSheet:async(e,t)=>{const n=await oe(`/api/ads/${e}/change-sheet`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>null);if(!r||typeof r.ok>"u")throw new Error(`POST ads change-sheet ${n.status}`);return r},generateCreatives:async(e,t)=>{const n=await oe(`/api/ads/${e}/creatives`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||!(r!=null&&r.ok))throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`POST ads creatives ${n.status}`);return r},listCreatives:(e,t=20)=>Se(`/api/ads/${e}/creatives?limit=${t}`),targetSeeds:(e,t)=>Se(`/api/ads/${e}/targeting/seeds${t?`?q=${encodeURIComponent(t)}`:""}`),suggestTargets:async(e,t)=>{const n=await oe(`/api/ads/${e}/targeting/suggest`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||!(r!=null&&r.ok))throw new Error((r==null?void 0:r.error)||`POST targeting suggest ${n.status}`);return r},exportTargets:async(e,t)=>{const n=await oe(`/api/ads/${e}/targeting/export`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||!(r!=null&&r.ok))throw new Error((r==null?void 0:r.error)||`POST targeting export ${n.status}`);return r},targetLists:(e,t=20)=>Se(`/api/ads/${e}/targeting/lists?limit=${t}`)},sops:{catalogue:e=>Se(`/api/sellers/${e}/sops`),listRuns:e=>Se(`/api/sellers/${e}/sops/runs`),options:(e,t)=>Se(`/api/sellers/${e}/sops/${t}
753`),createRun:async(e,t)=>{const n=await oe(`/api/sellers/${e}/sops/runs`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`POST sops run ${n.status}`);return n.json()},markRun:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/sops/runs/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`PATCH sops run ${r.status}`);return r.json()}},stockReconClaims:{list:e=>Se(`/api/sellers/${e}/stock-recon-claims`),get:(e,t)=>Se(`/api/sellers/${e}/stock-recon-claims/${t}`),setInvoiceNumber:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/stock-recon-claims/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({invoice_number:n})});if(!r.ok)throw new Error(`PATCH claim ${r.status}`);return r.json()},setFiled:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/stock-recon-claims/${t}/filed`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filed:n})});if(!r.ok)throw new Error(`PATCH claim filed ${r.status}`);return r.json()},updateLine:async(e,t,n,r)=>{const a=await oe(`/api/sellers/${e}/stock-recon-claims/${t}/lines/${n}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!a.ok)throw new Error(`PATCH claim line ${a.status}`);return a.json()},regenerate:async(e,t)=>{const n=await oe(`/api/sellers/${e}/stock-recon-claims/${t}/regenerate`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok){const r=await n.json().catch(()=>null);throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`POST claim regenerate ${n.status}`)}return n.json()}},promotionDrafts:{list:(e,t)=>Se(`/api/sellers/${e}/promotion-drafts${t?`?status=${encodeURIComponent(t)}`:""}`),get:(e,t)=>Se(`/api/sellers/${e}/promotion-drafts/${t}`),updateLine:async(e,t,n,r)=>{const a=await oe(`/api/sellers/${e}/promotion-drafts/${t}/lines/${n}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!a.ok){const i=await a.json().catch(()=>null);throw new Error((i==null?void 0:i.error)||`PATCH promo draft line ${a.status}`)}return a.json()},excludeMatching:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/promotion-drafts/${t}/exclude-matching`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const a=await r.json().catch(()=>null);throw new Error((a==null?void 0:a.error)||`POST promo draft exclude-matching ${r.status}`)}return r.json()},approve:async(e,t)=>{const n=await oe(`/api/sellers/${e}/promotion-drafts/${t}/approve`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok)throw new Error(`POST promo draft approve ${n.status}`);return n.json()},requestChanges:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/promotion-drafts/${t}/request-changes`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({note:n})});if(!r.ok)throw new Error(`POST promo draft request-changes ${r.status}`);return r.json()},resend:async(e,t)=>{const n=await oe(`/api/sellers/${e}/promotion-drafts/${t}/resend`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok)throw new Error(`POST promo draft resend ${n.status}`);return n.json()},downloadWorkbook:async(e,t)=>{const n=await oe(`/api/sellers/${e}/promotion-drafts/${t}/xlsx`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!n.ok){const r=await n.json().catch(()=>null),a=new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`POST promo draft xlsx ${n.status}`);throw typeof(r==null?void 0:r.error)=="string"&&(a.code=r.error),a}return n.json()},markUploaded:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/promotion-drafts/${t}/mark-uploaded`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({xlsx_url:n??null})});if(!r.ok)throw new Error(`POST promo draft mark-uploaded ${r.status}`);return r.json()}},businessInfo:{get:e=>Se(`/api/sellers/${e}/business-info`),update:async(e,t,n,r=!1)=>{const a=await oe(`/api/sellers/${e}/business-info`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({field:t,value:n,confirm:r})}),i=await a.json().catch(()=>null);if(a.status===409&&(i!=null&&i.requires_confirmation))return{...i,ok:!1,requires_confirmation:!0};if(!a.ok)throw new Error((i==null?void 0:i.message)||(i==null?void 0:i.error)||`PATCH business-info ${a.status}`);return{ok:!0,business_info:i.business_info}},refresh:async e=>{const t=await oe(`/api/sellers/${e}/business-info/refresh`,{method:"POST",headers:{"Content-Type":"application/json"}}),n=await t.json().catch(()=>null);if(!t.ok)throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||`POST business-info refresh ${t.status}`);return n}},uploadChatAttachment:async(e,t)=>{const n=await oe(`/api/chats/${e}/attachments`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`POST chat attachment ${n.status}`);return n.json()},listingDrafts:{create:async(e,t)=>{const n=await oe(`/api/sellers/${e}/listing-drafts`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`POST listing-draft ${n.status}`);return await n.json()},get:(e,t)=>Se(`/api/sellers/${e}/listing-drafts/${t}`),list:e=>Se(`/api/sellers/${e}/listing-drafts`),submissions:e=>Se(`/api/sellers/${e}
753/catalogue-submissions`),submitTakealotDraft:async(e,t)=>{const n=await oe(`/api/sellers/${e}/catalogue-submissions/${t}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),r=await n.json().catch(()=>({}));if(!n.ok){const a=typeof(r==null?void 0:r.message)=="string"?r.message:`submit draft ${n.status}`;throw new Error(a)}return r},discard:async(e,t)=>{const n=await oe(`/api/sellers/${e}/listing-drafts/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:"abandoned"})});if(!n.ok)throw new Error(`discard listing-draft ${n.status}`);return await n.json()},patch:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/listing-drafts/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`PATCH listing-draft ${r.status}`);return await r.json()},suggestCategories:async(e,t)=>{const n=await oe(`/api/sellers/${e}/listing-drafts/${t}/suggest-categories`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"});if(!n.ok)throw new Error(`POST suggest-categories ${n.status}`);return await n.json()},searchCategories:(e,t)=>Se(`/api/sellers/${e}/listing-categories?q=${encodeURIComponent(t)}`),searchBrands:(e,t)=>Se(`/api/sellers/${e}/listing-brands?q=${encodeURIComponent(t)}`),generateAttributes:async(e,t)=>{const n=await oe(`/api/sellers/${e}/listing-drafts/${t}/generate-attributes`,{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"});if(!n.ok)throw new Error(`POST generate-attributes ${n.status}`);return await n.json()},categorySchema:(e,t)=>Se(`/api/sellers/${e}/listing-category-schema?category_id=${t}`),generate:async(e,t,n,r=!1)=>{const a=await oe(`/api/sellers/${e}/listing-drafts/${t}/generate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({element:n,brand_in_title:r})});if(!a.ok)throw new Error(`POST generate ${a.status}`);return await a.json()},submit:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/listing-drafts/${t}/submit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n!=null&&n.submit_as_draft?{submit_as_draft:!0}:{})});if(!r.ok)throw new Error(`POST submit ${r.status}`);return await r.json()},autoFix:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/listing-drafts/${t}/auto-fix`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({rejection_text:n??""})});let a={};try{a=await r.json()}catch{}if(!r.ok)throw new Error(a.message||`auto-fix ${r.status}`);return a},uploadImage:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/listing-drafts/${t}/upload-image`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`POST upload-image ${r.status}`);return await r.json()},importImageUrl:async(e,t,n,r)=>{const a=await oe(`/api/sellers/${e}/listing-drafts/${t}/import-image-url`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n,add_to_listing:r==null?void 0:r.addToListing})});if(!a.ok){let i=`import-image-url ${a.status}`;try{const o=await a.json();o!=null&&o.message&&(i=o.message)}catch{}throw new Error(i)}return await a.json()},generateImage:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/listing-drafts/${t}/generate-image`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let a=`generate-image ${r.status}`;try{const i=await r.json();i!=null&&i.message&&(a=i.message)}catch{}throw new Error(a)}return await r.json()}},overviewStorefrontHealth:e=>Se(`/api/overview/storefront-health/${e}`),overviewAdsSnapshot:e=>Se(`/api/overview/ads-snapshot/${e}`),overviewScoreboard:(e,t)=>Se(`/api/overview/scoreboard/${e}${(t==null?void 0:t.wave)==="priority"?"?wave=priority":""}`),overviewTelemetry:async(e,t)=>{try{await oe("/api/overview/telemetry",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({slug:e,event:t}),keepalive:!0})}catch{}},automationsOverview:e=>Se(`/api/sellers/${e}/automations/overview`),agents:{list:e=>Se(`/api/sellers/${e}/automations/agents`),update:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/automations/agents/${encodeURIComponent(t)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a=await r.json().catch(()=>({}));if(!r.ok){const i=new Error((a==null?void 0:a.message)||(a==null?void 0:a.error)||`PUT agent ${r.status}`);
753throw i.code=a==null?void 0:a.error,i.dependencies=a==null?void 0:a.dependencies,i}return a}},subscriptionCompetitors:(e,t)=>Se(`/api/sellers/${e}/automations/subscriptions/${t}/competitors`),experiments:{list:(e,t)=>Se(`/api/sellers/${e}/automations/experiments${t?`?status=${t}`:""}`),get:(e,t)=>Se(`/api/sellers/${e}/automations/experiments/${t}`),progress:(e,t)=>Se(`/api/sellers/${e}/automations/experiments/${t}/progress`),catalog:(e,t={})=>Se(`/api/sellers/${e}/automations/experiments/catalog?search=${encodeURIComponent(t.search??"")}&eligible_only=${t.eligibleOnly?"1":"0"}&brand=${encodeURIComponent(t.brand??"")}&limit=${t.limit??50}&offset=${t.offset??0}`),brands:e=>Se(`/api/sellers/${e}/automations/experiments/brands`),shortlist:e=>Se(`/api/sellers/${e}/automations/experiments/shortlist`),portfolio:e=>Se(`/api/sellers/${e}/automations/experiments/portfolio`),candidates:(e,t,n={})=>jt(`/api/sellers/${e}/automations/experiments/candidates`,{offer_ids:t,...n}),resuggest:(e,t,n={})=>jt(`/api/sellers/${e}/automations/experiments/resuggest`,{eligible:t,...n}),create:(e,t,n={})=>jt(`/api/sellers/${e}/automations/experiments`,{experiments:t,status:n.status,send_for_approval:n.send_for_approval}),drafts:e=>Se(`/api/sellers/${e}/automations/experiments/drafts`),context:e=>Se(`/api/sellers/${e}/automations/experiments/context`),history:(e,t,n=12)=>Se(`/api/sellers/${e}/automations/experiments/offers/${t}/history?weeks=${n}`),scheduleBatch:(e,t)=>jt(`/api/sellers/${e}/automations/experiments/batches/${t}/schedule`,{}),discardBatch:async(e,t)=>{const n=await oe(`/api/sellers/${e}/automations/experiments/batches/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`DELETE draft batch ${n.status}`);return n.json()},sendForApproval:(e,t)=>jt(`/api/sellers/${e}/automations/experiments/batches/${t}/send-for-approval`,{}),listApprovals:e=>Se(`/api/sellers/${e}/automations/experiments/approvals`),getApproval:(e,t)=>Se(`/api/sellers/${e}/automations/experiments/approvals/${t}`),approveBatch:(e,t)=>jt(`/api/sellers/${e}/automations/experiments/approvals/${t}/approve`,{}),requestApprovalChanges:(e,t,n)=>jt(`/api/sellers/${e}/automations/experiments/approvals/${t}/request-changes`,{note:n}),resendApproval:(e,t)=>jt(`/api/sellers/${e}/automations/experiments/approvals/${t}/resend`,{}),excludeApprovalSku:(e,t,n,r)=>jt(`/api/sellers/${e}/automations/experiments/approvals/${t}/exclude`,{experiment_id:n,excluded:r}),abort:(e,t)=>jt(`/api/sellers/${e}/automations/experiments/${t}/abort`,{}),decide:(e,t,n)=>jt(`/api/sellers/${e}/automations/experiments/${t}/decision`,{decision:n}),extend:(e,t,n=7)=>jt(`/api/sellers/${e}/automations/experiments/${t}/extend`,{extra_days:n}),retry:(e,t,n)=>jt(`/api/sellers/${e}/automations/experiments/${t}/retry`,{mode:n}),graduate:(e,t)=>jt(`/api/sellers/${e}/automations/experiments/${t}/graduate`,{})},profitCalc:e=>jt("/api/profit-calc",e),refreshOffer:(e,t)=>jt(`/api/sellers/${e}/offers/${t}/refresh`,{}),setSkuCost:(e,t,n)=>jt(`/api/sellers/${e}/cogs`,{sku:t,cost_excl_vat:n}),downloadCogsTemplate:async(e,{scope:t="missing",includeDisabled:n=!1}={})=>{const i=await oe(`/api/sellers/${e}/cogs/${t==="all"?"all.xlsx":"missing.xlsx"}${n?"?includeDisabled=1":""}`);if(!i.ok){const d=await i.json().catch(()=>({}));throw new Error((d==null?void 0:d.message)||(d==null?void 0:d.error)||`template download failed: ${i.status}`)}const o=await i.blob(),l=i.headers.get("Content-Disposition")||"",c=/filename="?([^"]+)"?/.exec(l),u=t==="all"?`${e}-all-costs.xlsx`:`${e}-missing-costs.xlsx`;return{blob:o,filename:(c==null?void 0:c[1])||u}},downloadMissingCogsTemplate:async(e,t=!1)=>K.downloadCogsTemplate(e,{scope:"missing",includeDisabled:t}),previewCogsImport:(e,t)=>jt(`/api/sellers/${e}/cogs/import`,{...t,dry_run:!0}),applyCogsImport:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/cogs/import`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({...t,dry_run:!1})});if(!(r.headers.get("content-type")||"").includes("text/event-stream")){const h=await r.json().catch(()=>({}));if(!r.ok){const f=new Error((h==null?void 0:h.message)||(h==null?void 0:h.error)||`${r.status}`);throw f.code=h==null?void 0:h.error,f}return h}if(!r.body)throw new Error("No response body");const i=r.body.getReader(),o=new TextDecoder;let l="",c=null;const u=h=>{const f=h.split(` 754`).find(x=>x.startsWith("data: "));if(!f)return;let m;try{m=JSON.parse(f.slice(6))}catch{return}n==null||n(m),(m.phase==="done"||m.phase==="error")&&(c=m.result??null)},d=h=>{l+=h;const f=l.split(` 755 756`);l=f.pop()??"";for(const m of f)u(m)};for(;;){const{done:h,value:f}=await i.read();if(h)break;d(o.decode(f,{stream:!0}))}if(d(o.decode()),l.trim()&&u(l),!c)throw new Error("Import finished without a result");return c},marketSellerOptions:()=>Se("/api/extension/seller_options"),addOfferFromPlid:e=>jt("/api/extension/hijack_offer",e),enrolSubscription:(e,t)=>oe(`/api/sellers/${e}/automations/subscriptions`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}).then(async n=>{const r=await n.json();if(!n.ok)throw Object.assign(new Error((r==null?void 0:r.message)||n.statusText),{status:n.status,body:r});return r}),updateSubscription:(e,t,n)=>oe(`/api/sellers/${e}/automations/subscriptions/${t}`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(n)}).then(async r=>{const a=await r.json();if(!r.ok)throw Object.assign(new Error((a==null?void 0:a.message)||r.statusText),{status:r.status,body:a});return a}),bulkUpdateSubscriptions:(e,t)=>oe(`/api/sellers/${e}/automations/subscriptions/bulk`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}).then(async n=>{const r=await n.json();if(!n.ok)throw Object.assign(new Error((r==null?void 0:r.message)||n.statusText),{status:n.status,body:r});return r}
756),previewMarginRoiFloor:(e,t,n)=>oe(`/api/sellers/${e}/automations/subscriptions/${t}/margin-floor-preview`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}).then(async r=>{const a=await r.json();if(!r.ok)throw Object.assign(new Error((a==null?void 0:a.message)||r.statusText),{status:r.status,body:a});return a}),setLeadtimeDefault:(e,t)=>oe(`/api/sellers/${e}/automations/leadtime-default`,{method:"PATCH",headers:{"content-type":"application/json"},body:JSON.stringify(t)}).then(async n=>{const r=await n.json();if(!n.ok)throw Object.assign(new Error((r==null?void 0:r.message)||n.statusText),{status:n.status,body:r});return r}),unenrolSubscription:(e,t)=>oe(`/api/sellers/${e}/automations/subscriptions/${t}`,{method:"DELETE"}).then(async n=>{const r=await n.json();if(!n.ok)throw Object.assign(new Error((r==null?void 0:r.message)||n.statusText),{status:n.status,body:r});return r}),setPauseWindow:(e,t)=>oe(`/api/sellers/${e}/automations/pause-windows`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}).then(async n=>{const r=await n.json();if(!n.ok)throw Object.assign(new Error((r==null?void 0:r.message)||n.statusText),{status:n.status,body:r});return r}),cancelPauseWindow:(e,t)=>oe(`/api/sellers/${e}/automations/pause-windows/${t}`,{method:"DELETE"}).then(async n=>{const r=await n.json();if(!n.ok)throw Object.assign(new Error((r==null?void 0:r.message)||n.statusText),{status:n.status,body:r});return r}),downloadEnrolTemplate:async e=>{const t=await oe(`/api/sellers/${e}/automations/enrol-template.xlsx`);if(!t.ok){const c=await t.json().catch(()=>({}));throw new Error((c==null?void 0:c.message)||(c==null?void 0:c.error)||`template download failed: ${t.status}`)}const n=await t.blob(),r=t.headers.get("Content-Disposition")||"",a=/filename="?([^"]+)"?/.exec(r),i=(a==null?void 0:a[1])||"repricer-enrol-template.xlsx",o=URL.createObjectURL(n),l=document.createElement("a");l.href=o,l.download=i,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(o)},enrolBatchPreview:(e,t)=>oe(`/api/sellers/${e}/automations/enrol-batch/preview`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}).then(async n=>{const r=await n.json();if(!n.ok)throw Object.assign(new Error((r==null?void 0:r.message)||n.statusText),{status:n.status,body:r});return r}),enrolBatchApply:(e,t)=>oe(`/api/sellers/${e}/automations/enrol-batch/apply`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({rows:t})}).then(async n=>{const r=await n.json();if(!n.ok)throw Object.assign(new Error((r==null?void 0:r.message)||n.statusText),{status:n.status,body:r});return r}),setWatch:(e,t)=>oe(`/api/sellers/${e}/automations/watch`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({enabled:t})}).then(async n=>{const r=await n.json();if(!n.ok)throw Object.assign(new Error((r==null?void 0:r.message)||n.statusText),{status:n.status,body:r});return r}),enrollableOffers:(e,t={})=>{const n=new URLSearchParams;t.search&&n.set("search",t.search),t.limit&&n.set("limit",String(t.limit));const r=n.toString()?`?${n.toString()}`:"";return Se(`/api/sellers/${e}/automations/enrollable-offers${r}`)},enrolOffers:(e,t)=>oe(`/api/sellers/${e}/automations/enrol-offers`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({rows:t})}).then(async n=>{const r=await n.json();if(!n.ok)throw Object.assign(new Error((r==null?void 0:r.message)||n.statusText),{status:n.status,body:r});return r}),slotPacks:()=>Se("/api/automations/slot-packs"),buySlots:(e,t)=>oe(`/api/sellers/${e}/automations/buy-slots`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)}).then(async n=>{const r=await n.json();if(!n.ok)throw Object.assign(new Error((r==null?void 0:r.message)||n.statusText),{status:n.status,body:r});return r}),activeSyncRun:async()=>{const e=await oe("/api/sync-runs/active");if(e.status===204)return null;if(!e.ok)throw new Error(`${e.status} /api/sync-runs/active`);return e.json()},syncProgress:async e=>{const t=await oe(`/api/sellers/${e}/sync-progress`);if(t.status===204)return null;if(!t.ok)throw new Error(`${t.status} /api/sellers/${e}/sync-progress`);return t.json()},jwtStatus:e=>Se(`/api/sellers/${e}/jwt-status`),syncRetry:async(e,t={})=>{const n=await oe(`/api/sellers/${e}/sync-retry`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({force:!!t.force})}),r=await n.json().catch(()=>({}));if(!n.ok)throw Object.assign(new Error((r==null?void 0:r.error)||n.statusText),{status:n.status,body:r});return r},taskAttachmentUpload:async(e,t)=>{const n=await oe("/api/task-attachments",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({mime_type:e,base64_data:t})}),r=await n.json().catch(()=>({}));if(!n.ok)throw Object.assign(new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||n.statusText),{status:n.status,body:r});return r},salesSeries:(e,t=90)=>Se(`/api/sellers/${e}/sales-series?days=${t}`),payoutHistory:(e,t=8)=>Se(`/api/sellers/${e}/payout-history?limit=${t}`),overviewPdf:async e=>{const t=await oe(`/api/sellers/${e}/overview.pdf`);if(!t.ok){let o="";try{const l=await t.json();o=(l==null?void 0:l.message)||(l==null?void 0:l.error)||""}catch{}throw new Error(`Overview PDF failed (${t.status})${o?`: ${o}`:""}`)}const n=await t.blob(),r=t.headers.get("Content-Disposition")||"",a=/filename="([^"]+)"/.exec(r),i=(a==null?void 0:a[1])||`overview-${e}.pdf`;return{blob:n,filename:i}},offers:(e,t="",n=500)=>Se(`/api/sellers/${e}/offers?q=${encodeURIComponent(t)}&limit=${n}`),searchVisibility:(e,t=7)=>Se(`/api/sellers/${e}/search-visibility?days=${t}`),searchVisibilityOverview:(e,t=7)=>Se(`/api/sellers/${e}/search-visibility/overview?days=${t}`),searchVisibilityProduct:(e,t,n=7)=>Se(`/api/sellers/${e}/search-visibility/product?sku=${encodeURIComponent(t)}&days=${n}`),catalogue:(e,t="",n=500,r=!1)=>Se(`/api/sellers/${e}/inventory/products?q=${encodeURIComponent(t)}&limit=${n}${r?"&includeDisabled=1":""}`),scanner:{lookup:(e,t)=>jt(`/api/sellers/${e}/inventory/scan/lookup`,{scanned_code:t}),commit:(e,t)=>
756jt(`/api/sellers/${e}/inventory/scan/commit`,t),attach:(e,t)=>jt(`/api/sellers/${e}/inventory/scan/attach`,t),create:(e,t)=>jt(`/api/sellers/${e}/inventory/scan/create`,t),undo:(e,t)=>jt(`/api/sellers/${e}/inventory/scan/undo`,{movement_id:t}),session:(e,t,n=50)=>Se(`/api/sellers/${e}/inventory/scan/session/${t}?limit=${n}`)},patchOffer:async(e,t,n)=>await(await oe(`/api/sellers/${e}/offers/${t}/patch`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)})).json().catch(()=>({})),sales:(e,t={})=>Se(`/api/sellers/${e}/sales${tm(t)}`),recentSales:(e,t=8)=>Se(`/api/sellers/${e}/recent-sales?limit=${t}`),storageFeeDuplicates:(e,t={})=>{const n=new URLSearchParams;t.status&&n.set("status",t.status),t.limit!=null&&n.set("limit",String(t.limit)),t.offset!=null&&n.set("offset",String(t.offset));const r=n.toString();return Se(`/api/sellers/${e}/storage-fee-duplicates${r?`?${r}`:""}`)},transactions:(e,t={})=>Se(`/api/sellers/${e}/transactions${tm(t)}${t.type?`&type=${encodeURIComponent(t.type)}`:""}`),transactionTypes:(e,t={})=>Se(`/api/sellers/${e}/transaction-types${tm(t)}`),returns:(e,t={})=>Se(`/api/sellers/${e}/returns${tm(t)}`),pickupReady:e=>Se(`/api/sellers/${e}/removal-orders/pickup-ready`),ignorePickupReady:(e,t)=>jt(`/api/sellers/${e}/removal-orders/ignore`,{removal_order_ids:t}),unignorePickupReady:(e,t)=>jt(`/api/sellers/${e}/removal-orders/unignore`,{removal_order_ids:t}),shipments:(e,t={})=>Se(`/api/sellers/${e}/shipments${tm(t)}`),shipmentDetail:(e,t)=>Se(`/api/sellers/${e}/shipments/${t}`),salesStats:(e,t=30)=>Se(`/api/sellers/${e}/sales/statistics?days=${t}`),transactionStats:(e,t=30)=>Se(`/api/sellers/${e}/transactions/statistics?days=${t}`),financialEarnings:(e,t={})=>Se(`/api/sellers/${e}/financials/earnings${hg(t)}`),financialCash:(e,t={})=>Se(`/api/sellers/${e}/financials/cash${hg(t)}`),financialProducts:(e,t={})=>Se(`/api/sellers/${e}/financials/products${hg(t)}`),financialJournal:(e,t={})=>Se(`/api/sellers/${e}/financials/journal${hg(t)}`),createFinancialCost:(e,t)=>jt(`/api/sellers/${e}/financials/journal`,t),deleteFinancialCost:(e,t,n="one")=>oe(`/api/sellers/${e}/financials/journal/${t}?scope=${n}`,{method:"DELETE"}).then(async r=>{if(!r.ok){const a=await r.json().catch(()=>null);throw new Error((a==null?void 0:a.message)||(a==null?void 0:a.error)||`${r.status}`)}return r.json()}),shipmentStats:(e,t=30)=>Se(`/api/sellers/${e}/shipments/statistics?days=${t}`),returnStats:(e,t=30)=>Se(`/api/sellers/${e}/returns/statistics?days=${t}`),inventoryStats:(e,t=30)=>Se(`/api/sellers/${e}/inventory/statistics?days=${t}`),reports:e=>Se(`/api/sellers/${e}/reports`),report:(e,t)=>Se(`/api/sellers/${e}/reports/${t}`),downloadReportPdf:async(e,t,n)=>{const r=[];n!=null&&n.title&&r.push(`title=${encodeURIComponent(n.title)}`),n!=null&&n.subtitle&&r.push(`subtitle=${encodeURIComponent(n.subtitle)}`),n!=null&&n.landscape&&r.push("landscape=1");const a=r.length?`?${r.join("&")}`:"",i=await oe(`/api/sellers/${e}/report-pdf/${t}${a}`,{headers:{Accept:"application/pdf"}});if(!i.ok){const d=await i.json().catch(()=>({}));throw new Error((d==null?void 0:d.error)||(d==null?void 0:d.message)||`report PDF failed: ${i.status}`)}const o=await i.blob(),l=i.headers.get("Content-Disposition")||"",c=/filename="?([^"]+)"?/.exec(l),u=(c==null?void 0:c[1])||(t.split("/").pop()||"report.md").replace(/\.md$/i,".pdf");return{blob:o,filename:u}},downloadExport:async(e,t,n)=>{const r=[`format=${n.format}`];n.since&&r.push(`since=${encodeURIComponent(n.since)}`),n.until&&r.push(`until=${encodeURIComponent(n.until)}`),n.month&&r.push(`month=${encodeURIComponent(n.month)}`),n.search&&r.push(`search=${encodeURIComponent(n.search)}`),n.status&&r.push(`status=${encodeURIComponent(n.status)}`),n.region&&r.push(`region=${encodeURIComponent(n.region)}`),n.reason&&r.push(`reason=${encodeURIComponent(n.reason)}`),n.type&&r.push(`type=${encodeURIComponent(n.type)}`);const a=`?${r.join("&")}`,i=n.format==="csv"?"text/csv":n.format==="pdf"?"application/pdf":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",o=await oe(`/api/sellers/${e}/exports/${t}${a}`,{headers:{Accept:i}});if(!o.ok){const x=await o.json().catch(()=>({}));throw new Error((x==null?void 0:x.error)||(x==null?void 0:x.message)||`export failed: ${o.status}`)}const l=await o.blob(),c=o.headers.get("Content-Disposition")||"",u=/filename="?([^"]+)"?/.exec(c),d=(u==null?void 0:u[1])||`${t}-${new Date().toISOString().slice(0,10)}.${n.format}`,h=o.headers.get("X-Data-As-Of"),f=o.headers.get("X-Data-Lag-Hours"),m=f==null?null:Number(f);
756return{blob:l,filename:d,dataAsOf:h,dataLagHours:Number.isFinite(m)?m:null}},downloadAmazonGtinExemption:async e=>{const t=await oe(`/api/sellers/${encodeURIComponent(e)}/inventory/amazon-gtin-exemption`,{headers:{Accept:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}});if(!t.ok){const o=await t.json().catch(()=>({}));throw new Error((o==null?void 0:o.error)||(o==null?void 0:o.message)||`export failed: ${t.status}`)}const n=await t.blob(),r=t.headers.get("Content-Disposition")||"",a=/filename="?([^"]+)"?/.exec(r),i=(a==null?void 0:a[1])||`${e}-amazon-gtin-exemption.xlsx`;return{blob:n,filename:i}},listGlobalChats:()=>Se("/api/chats"),listGroupedChats:e=>Se(`/api/chats/grouped${e!=null&&e.archived?"?archived=1":""}`),listSellerBadges:()=>Se("/api/seller-badges"),getGlobalChat:e=>Se(`/api/chats/${e}`),createGlobalChat:async()=>{const e=await oe("/api/chats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});if(!e.ok)throw new Error(`POST chat ${e.status}`);return e.json()},saveGlobalChat:async(e,t)=>{const n=await oe(`/api/chats/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`PUT chat ${n.status}`);return n.json()},renameGlobalChat:async(e,t)=>{const n=await oe(`/api/chats/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t})});if(!n.ok)throw new Error(`PATCH chat ${n.status}`);return n.json()},archiveGlobalChat:async(e,t)=>{const n=await oe(`/api/chats/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:t})});if(!n.ok)throw new Error(`PATCH chat archive ${n.status}`);return n.json()},deleteGlobalChat:async e=>{const t=await oe(`/api/chats/${e}`,{method:"DELETE"});if(!t.ok)throw new Error(`DELETE chat ${t.status}`)},listChats:e=>Se(`/api/sellers/${e}/chats`),getChat:(e,t)=>Se(`/api/sellers/${e}/chats/${t}`),createChat:async e=>{const t=await oe(`/api/sellers/${e}/chats`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});if(!t.ok)throw new Error(`POST chat ${t.status}`);return t.json()},saveChat:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/chats/${t}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok)throw new Error(`PUT chat ${r.status}`);return r.json()},renameChat:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/chats/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:n})});if(!r.ok)throw new Error(`PATCH chat ${r.status}`);return r.json()},archiveChat:async(e,t,n)=>{const r=await oe(`/api/sellers/${e}/chats/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:n})});if(!r.ok)throw new Error(`PATCH chat archive ${r.status}`);return r.json()},deleteChat:async(e,t)=>{const n=await oe(`/api/sellers/${e}/chats/${t}`,{method:"DELETE"});if(!n.ok)throw new Error(`DELETE chat ${n.status}`)},listDashboards:()=>Se("/api/dashboards"),dashboardHeadlines:e=>{const t=e!=null&&e.seller?`?seller=${encodeURIComponent(e.seller)}`:"";return Se(`/api/dashboards/headlines${t}`)},getDashboard:e=>Se(`/api/dashboards/${e}`),renderDashboard:(e,t)=>Se(`/api/dashboards/${e}/render${UO(t)}`),renderDashboardPdf:async(e,t)=>{const n=UO(t),r=await oe(`/api/dashboards/${e}/render.pdf${n}`,{headers:{Accept:"application/pdf"}});if(!r.ok){const c=await r.json().catch(()=>({}));throw new Error((c==null?void 0:c.message)||(c==null?void 0:c.error)||`PDF render failed: ${r.status}`)}const a=await r.blob(),i=r.headers.get("Content-Disposition")||"",o=/filename="?([^"]+)"?/.exec(i),l=(o==null?void 0:o[1])||`dashboard-${new Date().toISOString().slice(0,10)}.pdf`;return{blob:a,filename:l}},deleteDashboard:async e=>{const t=await oe(`/api/dashboards/${e}`,{method:"DELETE"});if(!t.ok){const n=await t.json().catch(()=>({}));throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||`DELETE dashboard ${t.status}`)}},duplicateDashboard:async(e,t)=>{const n=await oe(`/api/dashboards/${e}/duplicate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t||{})});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`Duplicate failed: ${n.status}`)}return n.json()},favoriteDashboard:async(e,t)=>{const n=await oe(`/api/dashboards/${e}/favorite`,{method:t?"POST":"DELETE"});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`${t?"POST":"DELETE"} favorite ${n.status}`)}},createDashboardChat:async()=>{const e=await oe("/api/dashboards/chats",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});if(!e.ok)throw new Error(`POST dashboard chat ${e.status}`);return e.json()},getDashboardChat:e=>Se(`/api/dashboards/chats/${e}`),saveDashboardChat:async(e,t)=>{const n=await oe(`/api/dashboards/chats/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw new Error(`PUT dashboard chat ${n.status}`);return n.json()},listScheduledTasks:()=>Se("/api/cron-jobs"),updateScheduledTask:async(e,t)=>{const n=await oe(`/api/cron-jobs/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.error)||`PUT scheduled task ${n.status}`);return r},listScheduledTaskRuns:(e,t=20)=>Se(`/api/cron-jobs/${encodeURIComponent(e)}/runs?limit=${t}`),runScheduledTaskNow:async(e,t)=>{const n=await oe(`/api/cron-jobs/${encodeURIComponent(e)}/run-now`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{slug:t}:{})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.error)||`POST run-now ${n.status}`);return r},listSkills:()=>
756Se("/api/skills"),getSkillCronStatus:()=>Se("/api/skills/cron-status"),getSkill:e=>Se(`/api/skills/${e}`),createSkill:async e=>{const t=await oe("/api/skills",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.error)||`POST skill ${t.status}`);return n},saveSkill:async(e,t)=>{const n=await oe(`/api/skills/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,originalName:e})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.error)||`PUT skill ${n.status}`);return r},deleteSkill:async e=>{const t=await oe(`/api/skills/${e}`,{method:"DELETE"});if(!t.ok)throw new Error(`DELETE skill ${t.status}`)},getMe:async()=>{const e=await oe("/api/me");if(!e.ok)throw new Error(`GET me ${e.status}`);return await e.json()},updateMe:async e=>{const t=await oe("/api/me",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.error)||`PATCH me ${t.status}`);return n},uploadAvatar:async e=>{const t=await oe("/api/me/avatar",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(await Cy(e))}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.error)||`POST avatar ${t.status}`);return n},removeAvatar:async()=>{const e=await oe("/api/me/avatar",{method:"DELETE"}),t=await e.json().catch(()=>({}));if(!e.ok)throw new Error((t==null?void 0:t.error)||`DELETE avatar ${e.status}`);return t},account:async()=>{const e=await oe("/api/account");if(!e.ok)throw new Error(`GET account ${e.status}`);return await e.json()},updateAccount:async e=>{const t=await oe("/api/account",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.error)||`PATCH account ${t.status}`);return n},uploadLogo:async e=>{const t=await oe("/api/account/logo",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(await Cy(e))}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.error)||`POST logo ${t.status}`);return n},removeLogo:async()=>{const e=await oe("/api/account/logo",{method:"DELETE"}),t=await e.json().catch(()=>({}));if(!e.ok)throw new Error((t==null?void 0:t.error)||`DELETE logo ${e.status}`);return t},getBrandKit:async()=>{const e=await oe("/api/account/brand-kit"),t=await e.json().catch(()=>({}));if(!e.ok)throw new Error((t==null?void 0:t.error)||`GET brand-kit ${e.status}`);return t},saveBrandKit:async e=>{const t=await oe("/api/account/brand-kit",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.error)||`PUT brand-kit ${t.status}`);return n},deriveBrandKit:async()=>{const e=await oe("/api/account/brand-kit/derive",{method:"POST"}),t=await e.json().catch(()=>({}));if(!e.ok)throw new Error((t==null?void 0:t.error)||`POST brand-kit derive ${e.status}`);return t},getListingImagePreset:async()=>{const e=await oe("/api/account/listing-image-preset"),t=await e.json().catch(()=>({}));if(!e.ok)throw new Error((t==null?void 0:t.error)||`GET listing-image-preset ${e.status}`);return t},saveListingImagePreset:async e=>{const t=await oe("/api/account/listing-image-preset",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({shots:e})}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||`PUT listing-image-preset ${t.status}`);return n},listMembers:async()=>{const e=await oe("/api/account/members");if(!e.ok)throw new Error(`GET members ${e.status}`);return await e.json()},inviteMember:async e=>{const t=await oe("/api/account/members/invite",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.error)||(n==null?void 0:n.message)||`POST invite ${t.status}`);return n},listStoreUsers:async()=>{const e=await oe("/api/account/store-users");if(!e.ok)throw new Error(`GET store-users ${e.status}`);return await e.json()}
756,dismissStoreUser:async e=>{const t=await oe(`/api/account/store-users/${e}/dismiss`,{method:"POST"}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.error)||`POST dismiss ${t.status}`);return n},removeMember:async e=>{const t=await oe(`/api/account/members/${e}`,{method:"DELETE"}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.error)||`DELETE member ${t.status}`);return n},updateMember:async(e,t)=>{const n=await oe(`/api/account/members/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.error)||(r==null?void 0:r.message)||`PATCH member ${n.status}`);return r},getMemberNavAccess:async e=>{const t=await oe(`/api/account/members/${e}/nav-access`),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.error)||(n==null?void 0:n.message)||`GET member nav-access ${t.status}`);return n},saveMemberNavAccess:async(e,t)=>{const n=await oe(`/api/account/members/${e}/nav-access`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({overrides:t})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.error)||(r==null?void 0:r.message)||`PUT member nav-access ${n.status}`);return r},getAccountNavRoleAccess:async()=>{const e=await oe("/api/account/nav-role-access"),t=await e.json().catch(()=>({}));if(!e.ok)throw new Error((t==null?void 0:t.error)||(t==null?void 0:t.message)||`GET nav-role-access ${e.status}`);return t},saveAccountNavRoleAccess:async e=>{const t=await oe("/api/account/nav-role-access",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({overrides:e})}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.error)||(n==null?void 0:n.message)||`PUT nav-role-access ${t.status}`);return n},acceptInvite:async e=>{const t=await oe("/api/invites/accept",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e})}),n=await t.json().catch(()=>({}));if(!t.ok){const r=new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||`POST accept ${t.status}`);throw r.code=n==null?void 0:n.error,r.status=t.status,r}return n},billingUsageSummary:async()=>{const e=await oe("/api/billing/usage-summary");if(!e.ok)throw new Error(`GET usage-summary ${e.status}`);return await e.json()},billingUsageBreakdown:async()=>{const e=await oe("/api/billing/usage-breakdown");if(!e.ok)throw new Error(`GET usage-breakdown ${e.status}`);return await e.json()},billingTopup:async(e,t)=>{const n=await oe("/api/billing/topup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pack_zar:e,return_to:t})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`topup ${n.status}`);return r},billingImagePacks:async()=>{const e=await oe("/api/billing/image-packs"),t=await e.json().catch(()=>({}));if(!e.ok)throw new Error((t==null?void 0:t.message)||(t==null?void 0:t.error)||`GET image-packs ${e.status}`);return t},billingImagePackCheckout:async(e,t)=>{const n=await oe("/api/billing/image-packs/checkout",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pack_id:e,return_to:t})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`image pack ${n.status}`);return r},billingConvertGrantToImages:async(e,t)=>{const n=await oe("/api/billing/image-packs/convert",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({images:e,confirm_below_reserve:t})}),r=await n.json().catch(()=>({}));if(!n.ok){const a=new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`convert ${n.status}`);throw a.code=r==null?void 0:r.error,a}return r},billingChangePlan:async e=>{const t=await oe("/api/billing/change-plan",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({target_plan:e})}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||`change-plan ${t.status}`);return n},billingState:async()=>{const e=await oe("/api/billing/state");if(!e.ok)throw new Error(`GET billing/state ${e.status}`);return await e.json()},initiateSubscription:async e=>{const t=await oe("/api/billing/initiate-subscription",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e?{target_plan:e}:{})}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||`initiate-subscription ${t.status}`);return n},attachTakealotKey:async(e,t)=>{const n=await oe("/api/billing/attach-takealot-key",{method:"POST",headers:{"Content-Type":"application/json"}
756,body:JSON.stringify({api_key:e,display_name_override:t||null})}),r=await n.json().catch(()=>({}));if(!n.ok){const a=new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`attach-takealot-key ${n.status}`);throw a.code=r==null?void 0:r.error,a.plan=r==null?void 0:r.plan,a.upgradeTo=(r==null?void 0:r.upgrade_to)??null,a.maxSellers=r==null?void 0:r.max_sellers,a.cloudflareBlock=!!(r!=null&&r.cloudflare_block),a.highlightPlan=(r==null?void 0:r.highlight_plan)??null,a}return r},makroConnectStatus:e=>Se(`/api/makro/connect?slug=${encodeURIComponent(e)}`),makroConnectStart:(e,t)=>jt("/api/makro/connect/start",{slug:e,display_name:t||null}),makroConnectCheck:e=>jt("/api/makro/connect/check",{slug:e}),makroPortal:e=>Se(`/api/makro/portal?slug=${encodeURIComponent(e)}`),makroPortalSync:(e,t=!1)=>jt("/api/makro/portal/sync",{slug:e,force:t}),amazonConnect:async(e="amazon_za",t)=>{const n=await oe("/api/amazon/connect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{marketplace:e,slug:t}:{marketplace:e})}),r=await n.json().catch(()=>({}));if(!n.ok){const a=new Error((r==null?void 0:r.error)||`amazon/connect ${n.status}`);throw a.code=(r==null?void 0:r.code)||(r==null?void 0:r.error),a.highlightPlan=(r==null?void 0:r.highlight_plan)??null,a}return r},amazonConnection:e=>Se(`/api/amazon/connection${e?`?slug=${encodeURIComponent(e)}`:""}`),tcsConnection:e=>Se(`/api/sellers/${encodeURIComponent(e)}/tcs/connection`),tcsConnect:(e,t)=>jt(`/api/sellers/${encodeURIComponent(e)}/tcs/connect`,{api_key:t}),tcsDisconnect:async e=>{const t=await oe(`/api/sellers/${encodeURIComponent(e)}/tcs/connect`,{method:"DELETE"}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||`tcs/connect ${t.status}`);return n},amazonConnectAppstore:async e=>{const t=await oe("/api/amazon/connect/appstore",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({marketplace:"amazon_za",...e})}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.error)||`amazon/connect/appstore ${t.status}`);return n},amazonCompleteOAuth:async e=>{const t=await oe("/api/amazon/complete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.error)||`amazon/complete ${t.status}`);return n},billingManageSubscription:async()=>{const e=await oe("/api/billing/manage-subscription",{method:"POST"}),t=await e.json().catch(()=>({}));if(!e.ok)throw new Error((t==null?void 0:t.message)||(t==null?void 0:t.error)||`manage-subscription ${e.status}`);return t},billingInvoices:async()=>{const e=await oe("/api/billing/invoices");if(!e.ok)throw new Error(`GET invoices ${e.status}`);return await e.json()},billingInvoicePdfUrl:async e=>{const t=await oe(`/api/billing/invoices/${encodeURIComponent(e)}/pdf-url`),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||`invoice pdf-url ${t.status}`);return n},patchSeller:async(e,t)=>{const n=await oe(`/api/sellers/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.error)||`PATCH seller ${n.status}`);return r},rotateSellerKey:async(e,t)=>{const n=await oe(`/api/sellers/${encodeURIComponent(e)}/rotate-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:t})}),r=await n.json().catch(()=>({}));if(!n.ok){const a=new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`rotate-key ${n.status}`);throw a.code=r==null?void 0:r.error,a.cloudflareBlock=!!(r!=null&&r.cloudflare_block),a}return r},listCredentials:async e=>{const t=await oe(`/api/sellers/${encodeURIComponent(e)}/credentials`),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||`credentials ${t.status}`);return n.credentials??[]},saveCredential:async(e,t)=>{const n=await oe(`/api/sellers/${encodeURIComponent(e)}/credentials`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`save credential ${n.status}`);return r.credential},revealCredential:async(e,t)=>{const n=await oe(`/api/sellers/${encodeURIComponent(e)}/credentials/${encodeURIComponent(t)}/reveal`,{method:"POST"}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`reveal credential ${n.status}`);return r},deleteCredential:async(e,t)=>{const n=await oe(`/api/sellers/${encodeURIComponent(e)}/credentials/${encodeURIComponent(t)}`,{method:"DELETE"}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`delete credential ${n.status}`);return r},managedAccountOverview:async e=>{const t=await oe(`/api/sellers/${encodeURIComponent(e)}/managed-account/overview`),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||`managed-account ${t.status}`);return n},reassignAm:async(e,t)=>{const n=await oe(`/api/sellers/${encodeURIComponent(e)}/managed-account/am`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({to_am:t})}
756),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`reassign AM ${n.status}`);return r},convertFromManaged:async(e,t={})=>{const n=await oe(`/api/sellers/${encodeURIComponent(e)}/convert-from-managed`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`convert from managed ${n.status}`);return r},managedAccountNotes:async e=>{const t=await oe(`/api/sellers/${encodeURIComponent(e)}/managed-account/notes`),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||`team notes ${t.status}`);return n.notes??[]},saveTeamNote:async(e,t)=>{const n=await oe(`/api/sellers/${encodeURIComponent(e)}/managed-account/notes`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`save note ${n.status}`);return r.note},deleteTeamNote:async(e,t)=>{const n=await oe(`/api/sellers/${encodeURIComponent(e)}/managed-account/notes/${encodeURIComponent(t)}`,{method:"DELETE"}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`delete note ${n.status}`);return r},setManagementStartDate:async(e,t)=>{const n=await oe(`/api/sellers/${encodeURIComponent(e)}/managed-account`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({management_started_at:t})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`set management date ${n.status}`);return r},managedAccountSchedule:async e=>{const t=await oe(`/api/sellers/${encodeURIComponent(e)}/managed-account/schedule`),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||`schedule ${t.status}`);return{cells:n.cells??[],catalogue:n.catalogue??[],marketplace:n.marketplace||"takealot"}},setScheduleCell:async(e,t)=>{const n=await oe(`/api/sellers/${encodeURIComponent(e)}/managed-account/schedule`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`set cell ${n.status}`);return r},onboardManagedAms:async()=>{const e=await oe("/api/managed-accounts/ams"),t=await e.json().catch(()=>({}));if(!e.ok)throw new Error((t==null?void 0:t.message)||(t==null?void 0:t.error)||`ams ${e.status}`);return t.ams??[]},previewManagedKey:async e=>{const t=await oe("/api/managed-accounts/preview-key",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:e})}),n=await t.json().catch(()=>({}));if(!t.ok){const r=new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||`preview-key ${t.status}`);throw r.code=n==null?void 0:n.error,r}return n},onboardManagedAccount:async e=>{const t=await oe("/api/managed-accounts/onboard",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));if(!t.ok){const r=new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||`onboard ${t.status}`);throw r.code=n==null?void 0:n.error,r.live_display_name=n==null?void 0:n.live_display_name,r}return n}};function UO(e){const t=new URLSearchParams;e!=null&&e.seller&&t.set("seller",e.seller),(e==null?void 0:e.days)!=null&&t.set("days",String(e.days)),e!=null&&e.relative&&t.set("relative",e.relative),e!=null&&e.from&&t.set("from",e.from),e!=null&&e.to&&t.set("to",e.to),e!=null&&e.landscape&&t.set("landscape","1");const n=t.toString();return n?`?${n}`:""}const QF=["promotion","replenishment","listing_upgrade","listing_creation","dc_allocation","stock_recon","customer_communication","reminder","other"];function Zoe(e={}){const t=new URLSearchParams;e.assignee&&t.set("assignee",e.assignee),e.seller_slug&&t.set("seller_slug",e.seller_slug),e.status&&t.set("status",e.status),e.type&&t.set("type",e.type),e.overdue&&t.set("overdue","1"),e.due_from&&t.set("due_from",e.due_from),e.due_to&&t.set("due_to",e.due_to),e.completed_from&&t.set("completed_from",e.completed_from),e.completed_to&&t.set("completed_to",e.completed_to),e.completed_by&&t.set("completed_by",e.completed_by),e.completed_within_days!=null&&t.set("completed_within_days",String(e.completed_within_days)),e.limit&&t.set("limit",String(e.limit));const n=t.toString();return n?`?${n}`:""}const vr={list:(e={})=>Se(`/api/tasks${Zoe(e)}`),get:e=>Se(`/api/tasks/${e}`),badge:()=>Se("/api/tasks/_meta/badge"),counts:()=>Se("/api/tasks/_meta/counts"),completionsByAccount:(e="all",t)=>Se(`/api/tasks/_meta/completions-by-account?window=${e}${t?`&assignee=${encodeURIComponent(t)}`:""}`),progressByAccount:(e="today",t)=>Se(`/api/tasks/_meta/progress-by-account?day=${e}${t?`&assignee=${encodeURIComponent(t)}`:""}`),byAm:(e="all")=>Se(`/api/tasks/_meta/by-am?window=${e}`),stats:(e="all")=>Se(`/api/tasks/_meta/stats?window=${e}`),today:(e="today")=>Se(`/api/tasks/_meta/today?day=${e}`),setDailyFloor:async e=>{const t=await oe("/api/tasks/_meta/daily-floor",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({floor:e})});if(!t.ok)throw await nn(t,"PATCH /api/tasks/_meta/daily-floor");return await t.json()},create:async e=>{const t=await oe("/api/tasks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await nn(t,"POST /api/tasks");return await t.json()},update:async(e,t)=>{const n=await oe(`/api/tasks/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw await nn(n,`PATCH /api/tasks/${e}`);return await n.json()},bulkUpdate:async(e,t)=>{const n=await oe("/api/tasks/_bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:e,patch:t})});if(!n.ok)throw await nn(n,"POST /api/tasks/_bulk");return await n.json()},remove:async e=>{const t=await oe(`/api/tasks/${e}`,{method:"DELETE"});if(!t.ok)throw await nn(t,`DELETE /api/tasks/${e}`);return t.json()},listComments:e=>Se(`/api/tasks/${e}/comments`),addComment:async(e,t,n=!1)=>{const r=await oe(`/api/tasks/${e}/comments`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:t,post_to_chat:n})});if(!r.ok)throw await nn(r,`POST /api/tasks/${e}/comments`);return await r.json()},roster:()=>Se("/api/users/am-roster")},Ul={list:e=>Se(`/api/sellers/${encodeURIComponent(e)}/exports`),remove:async e=>{const t=await oe(`/api/exports/${e}`,{method:"DELETE"});if(!t.ok&&t.status!==404)throw new Error(`DELETE /api/exports/${e} â ${t.status}`)},run:async e=>{const t=await oe("/api/exports/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`POST /api/exports/run â ${t.status}`);const n=await t.json();return{id:n.id,slug:n.slug,skill:n.skill}},download:async e=>{const t=await oe(`/api/exports/${e}`);if(!t.ok)throw new Error(`GET /api/exports/${e} â ${t.status}`);const{signed_url:n,filename:r}=await t.json(),a=document.createElement("a");a.href=n,r&&(a.download=r),a.rel="noopener",a.style.display="none",document.body.appendChild(a),a.click(),document.body.removeChild(a)}},Ey={list:()=>Se("/api/notifications"),markRead:async e=>{const t=await oe(`/api/notifications/${e}/read`,{method:"POST"});if(!t.ok)throw new Error(`POST /api/notifications/${e}/read â ${t.status}`)},markAllRead:async()=>{const e=await oe("/api/notifications/read-all",{method:"POST"});if(!e.ok)throw new Error(`POST /api/notifications/read-all â ${e.status}`)}};function eB(e){return!!(e.search&&e.search.trim()||e.stages&&e.stages.length||e.sources&&e.sources.length||e.ownerId||e.nextAction||e.staleDays&&e.staleDays>0||e.estRevMin!=null||e.estRevMax!=null||e.linked||e.region&&e.region.trim()||e.lastActivityDays&&e.lastActivityDays>0||e.hasDemoScheduled!=null)}function _N(e,t){const n=new URLSearchParams;return t&&t!=="all"&&n.set("view",t),e.search&&e.search.trim()&&n.set("search",e.search.trim()),e.stages&&e.stages.length&&n.set("stages",e.stages.join(",")),e.sources&&e.sources.length&&n.set("sources",e.
756sources.join(",")),e.ownerId&&n.set("owner_id",e.ownerId),e.nextAction&&n.set("next_action",e.nextAction),e.staleDays&&e.staleDays>0&&n.set("stale_days",String(e.staleDays)),e.estRevMin!=null&&n.set("est_rev_min",String(e.estRevMin)),e.estRevMax!=null&&n.set("est_rev_max",String(e.estRevMax)),e.linked&&n.set("linked",e.linked),e.region&&e.region.trim()&&n.set("region",e.region.trim()),e.lastActivityDays&&e.lastActivityDays>0&&n.set("last_activity_days",String(e.lastActivityDays)),e.hasDemoScheduled!=null&&n.set("has_demo_scheduled",String(e.hasDemoScheduled)),n}const Rr={listCompanies:(e="all",t={})=>{const n=_N(t,e),r=n.toString()?`?${n.toString()}`:"";return Se(`/api/crm/companies${r}`)},getCompany:e=>Se(`/api/crm/companies/${e}`),createCompany:async e=>{const t=await oe("/api/crm/companies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await nn(t,"POST /api/crm/companies");return await t.json()},updateCompany:async(e,t)=>{const n=await oe(`/api/crm/companies/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw await nn(n,`PATCH /api/crm/companies/${e}`);return await n.json()},deleteCompany:async e=>{const t=await oe(`/api/crm/companies/${e}`,{method:"DELETE"});if(!t.ok)throw await nn(t,`DELETE /api/crm/companies/${e}`);return t.json()},listContacts:e=>Se(`/api/crm/companies/${e}/contacts`),createContact:async(e,t)=>{const n=await oe(`/api/crm/companies/${e}/contacts`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw await nn(n,`POST /api/crm/companies/${e}/contacts`);return await n.json()},updateContact:async(e,t)=>{const n=await oe(`/api/crm/contacts/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw await nn(n,`PATCH /api/crm/contacts/${e}`);return await n.json()},deleteContact:async e=>{const t=await oe(`/api/crm/contacts/${e}`,{method:"DELETE"});if(!t.ok)throw await nn(t,`DELETE /api/crm/contacts/${e}`);return t.json()},listActivities:e=>Se(`/api/crm/companies/${e}/activities`),createActivity:async(e,t)=>{const n=await oe(`/api/crm/companies/${e}/activities`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw await nn(n,`POST /api/crm/companies/${e}/activities`);return await n.json()},updateActivity:async(e,t)=>{const n=await oe(`/api/crm/activities/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw await nn(n,`PATCH /api/crm/activities/${e}`);return await n.json()},deleteActivity:async e=>{const t=await oe(`/api/crm/activities/${e}`,{method:"DELETE"});if(!t.ok)throw await nn(t,`DELETE /api/crm/activities/${e}`);return t.json()},getAppProfile:e=>Se(`/api/crm/companies/${e}/app-profile`),bulkImport:async e=>{const t=await oe("/api/crm/companies/bulk-import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({rows:e})});if(!t.ok)throw await nn(t,"POST /api/crm/companies/bulk-import");return await t.json()},bulkAction:async(e,t,n={})=>{const r={action:e,payload:n};if("ids"in t)r.ids=t.ids;else{const i=_N(t.filter,t.view),o={};for(const[l,c]of i.entries())o[l]=c;r.filter=o}const a=await oe("/api/crm/companies/bulk-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!a.ok)throw await nn(a,"POST /api/crm/companies/bulk-action");return await a.json()},listSavedViews:()=>Se("/api/crm/saved-views"),createSavedView:async e=>{const t=await oe("/api/crm/saved-views",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await nn(t,"POST /api/crm/saved-views");return await t.json()},deleteSavedView:async e=>{const t=await oe(`/api/crm/saved-views/${e}`,{method:"DELETE"});if(!t.ok)throw await nn(t,`DELETE /api/crm/saved-views/${e}`);return t.json()}},Us={overview:()=>Se("/api/earn/overview"),claimReferral:e=>jt("/api/earn/claim-referral",{code:e}),submit:e=>jt("/api/earn/submit",e),mySubmissions:()=>Se("/api/earn/submissions"),reviewQueue:(e="pending")=>Se(`/api/earn/review-queue?status=${encodeURIComponent(e)}`),review:(e,t,n)=>jt(`/api/earn/review/${e}`,{decision:t,note:n}),uploadProofScreenshot:async e=>{const{mime_type:t,base64_data:n}=await Cy(e);return(await K.taskAttachmentUpload(t,n)).storage_path},sweep:e=>jt("/api/earn/sweep",{amountZar:e}),banks:()=>Se("/api/earn/banks"),bankAccount:()=>Se("/api/earn/bank-account"),saveBankAccount:e=>jt("/api/earn/bank-account",e),withdraw:e=>jt("/api/earn/withdraw",{amountZar:e}),myWithdrawals:()=>Se("/api/earn/withdrawals"),cancelWithdrawal:e=>jt(`/api/earn/withdrawal/${e}/cancel`,{}),withdrawalQueue:(e="pending")=>Se(`/api/earn/withdrawal-queue?status=${encodeURIComponent(e)}`),reviewWithdrawal:(e,t,n)=>jt(`/api/earn/withdrawal/${e}/review`,{decision:t,note:n})},$t={runSearch:async(e,t)=>{const n=await oe("/api/market-explorer/searches",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,entry_mode:(t==null?void 0:t.entryMode)??"preset"})});if(!n.ok)throw await nn(n,"POST /api/market-explorer/searches");return await n.json()},parseQuery:async e=>{const t=await oe("/api/market-explorer/searches/parse",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:e})});if(!t.ok)throw await nn(t,"POST /api/market-explorer/searches/parse");return await t.json()},getSearch:e=>Se(`/api/market-explorer/searches/${e}`),deriveSearch:async(e,t)=>{const n=await oe(`/api/market-explorer/searches/${e}/derive`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({transform:t})});if(!n.ok)throw await nn(n,`POST /api/market-explorer/searches/${e}/derive`);return await n.json()},searchCategories:e=>Se(`/api/market-explorer/categories/search?q=${encodeURIComponent(e)}`),ranksTree:e=>Se(`/api/market-explorer/ranks${e?`?parent=${encodeURIComponent(e)}`:""}`),ranksLeaf:e=>Se(`/api/market-explorer/ranks/${encodeURIComponent(e)}`),quota:()=>Se("/api/market-explorer/quota"),keyword:(e,t="takealot")=>Se(`/api/market-explorer/keyword?term=${encodeURIComponent(e)}&marketplace=${encodeURIComponent(t)}`),keywordExpand:(e,t="takealot")=>Se(`/api/market-explorer/keyword/expand?term=${encodeURIComponent(e)}&marketplace=${encodeURIComponent(t)}`),keywordDiscover:(e="takealot")=>Se(`/api/market-explorer/keyword/discover?marketplace=${encodeURIComponent(e)}`),keywordBrowse:(e={})=>{const t=new URLSearchParams;return t.set("marketplace",e.marketplace||"takealot"),e.rail&&t.set("rail",e.rail),e.hide_local===!1&&t.set("hide_local","0"),e.volume&&t.set("volume",e.volume),e.trend&&t.set("trend",e.trend),e.yoy&&t.set("yoy",e.yoy),e.words&&t.set("words",e.words),e.in_corpus&&t.set("in_corpus","1"),e.competition&&t.set("competition",e.competition),e.spike&&t.set("spike",e.spike),e.contains&&t.set("contains",e.contains),e.exclude&&t.set("exclude",e.exclude),e.department_slug&&t.set("department_slug",e.department_slug),e.category_id&&t.set("category_id",e.category_id),e.cpc_min!=null&&t.set("cpc_min",String(e.cpc_min)),e.cpc_max!=null&&t.set("cpc_max",String(e.cpc_max)),e.limit!=null&&t.set("limit",String(e.limit)),e.offset!=null&&t.set("offset",String(e.offset)),Se(`/api/market-explorer/keyword/browse?${t.toString()}`)},keywordBrowseCoverage:()=>Se("/api/market-explorer/keyword/browse/coverage"),keywordBrowseTaxonomyOptions:e=>{const t=new URLSearchParams;e&&t.set("department_slug",e);const n=t.toString();return Se(`/api/market-explorer/keyword/browse/taxonomy-options${n?`?${n}`:""}`)},keywordEnrich:async(e,t="takealot")=>{const n=await oe("/api/market-explorer/keyword/enrich",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({terms:e,marketplace:t})});if(!n.ok)throw await nn(n,"POST /api/market-explorer/keyword/enrich");return await n.json()},keywordTrack:(e,t="takealot")=>Se(`/api/market-explorer/keyword/track?keyword=${encodeURIComponent(e)}&marketplace=${encodeURIComponent(t)}`),watchlist:()=>Se("/api/market-explorer/keyword/watchlist"),watchlistAdd:async(e,t="takealot")=>{const n=await oe("/api/market-explorer/keyword/watchlist",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({keyword:e,marketplace:t})});if(!n.ok)throw await nn(n,"POST /api/market-explorer/keyword/watchlist");return await n.json()},watchlistRemove:async(e,t="takealot")=>{const n=await oe(`/api/market-explorer/keyword/watchlist?keyword=${encodeURIComponent(e)}&marketplace=${encodeURIComponent(t)}`,{method:"DELETE"});if(!n.ok)throw await nn(n,"DELETE /api/market-explorer/keyword/watchlist");return await n.json()},exportResults:async e=>{const t=await oe("/api/market-explorer/export",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await nn(t,"POST /api/market-explorer/export");const n=await t.blob(),r=URL.createObjectURL(n),a=document.createElement("a");a.href=r,a.download=e.filename||`market-explorer.${e.format}`,a.style.display="none",document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(r)},listFolders:()=>Se("/api/market-explorer/folders"),createFolder:async e=>{const t=await oe("/api/market-explorer/folders",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await nn(t,"POST /api/market-explorer/folders");return await t.json()},renameFolder:async(e,t)=>{const n=await oe(`/api/market-explorer/folders/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})});if(!n.ok)throw await nn(n,`PATCH /api/market-explorer/folders/${e}`);return await n.json()},deleteFolder:async e=>{const t=await oe(`/api/market-explorer/folders/${e}`,{method:"DELETE"});if(!t.ok)throw await nn(t,`DELETE /api/market-explorer/folders/${e}`);return await t.json()},refreshFolder:async e=>{const t=await oe(`/api/market-explorer/folders/${e}/refresh`,{method:"POST"});if(!t.ok)throw await nn(t,`POST /api/market-explorer/folders/${e}/refresh`);return await t.json()},listShortlist:()=>Se("/api/market-explorer/shortlist"),addShortlistItems:async e=>{const t=await oe("/api/market-explorer/shortlist",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({items:e})});if(!t.ok)throw await nn(t,"POST /api/market-explorer/shortlist");return await t.json()},patchShortlistItem:async(e,t)=>{const n=await oe(`/api/market-explorer/shortlist/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok)throw await nn(n,`PATCH /api/market-explorer/shortlist/${e}`);return await n.json()},removeShortlistItem:async e=>{const t=await oe(`/api/market-explorer/shortlist/${e}`,{method:"DELETE"});if(!t.ok)throw await nn(t,`DELETE /api/market-explorer/shortlist/${e}`);return await t.json()},clearShortlist:async()=>{const e=await oe("/api/market-explorer/shortlist",{method:"DELETE"});if(!e.ok)throw await nn(e,"DELETE /api/market-explorer/shortlist");return await e.json()},recordEvent:(e,t)=>
756{try{const n=JSON.stringify({event_type:e,folder_id:(t==null?void 0:t.folder_id)??null,search_id:(t==null?void 0:t.search_id)??null,payload:(t==null?void 0:t.payload)??{}});oe("/api/market-explorer/events",{method:"POST",headers:{"Content-Type":"application/json"},body:n}).catch(()=>{})}catch{}}},kN={get:e=>{const t=new URLSearchParams({seller:e.seller});return e.from&&t.set("from",e.from),e.to&&t.set("to",e.to),e.layers&&e.layers.length&&t.set("layers",e.layers.join(",")),e.showAllPromos&&t.set("show_all_promos","true"),Se(`/api/calendar?${t.toString()}`)},setPromoDone:e=>jt("/api/calendar/promo-done",{seller:e.seller,promotion_id:e.promotionId,done:e.done})};function oC(e){return!(e!=null&&e.academy_latest_at)||!e.academy_seen_at?!1:new Date(e.academy_latest_at)>new Date(e.academy_seen_at)}let fg=null;const wp={list:()=>Se("/api/academy/videos").then(e=>e.videos),markSeen:()=>jt("/api/academy/seen",{}).then(()=>{}),listCached:()=>(fg||(fg=wp.list().catch(e=>{throw fg=null,e})),fg)};async function nn(e,t){let n=e.statusText;try{const r=await e.json();n=(r==null?void 0:r.message)||(r==null?void 0:r.error)||n}catch{}return new Error(`${t} â ${e.status}: ${n}`)}async function io(e,t,n){const r=await oe(t,{method:e,headers:n===void 0?void 0:{"Content-Type":"application/json"},body:n===void 0?void 0:JSON.stringify(n)});if(!r.ok)throw await nn(r,`${e} ${t}`);return r.json()}const At={listIdeas:e=>Se(`/api/content/ideas${e?`?status=${encodeURIComponent(e)}`:""}`),createIdea:e=>jt("/api/content/ideas",e),updateIdea:(e,t)=>io("PATCH",`/api/content/ideas/${e}`,t),deleteIdea:e=>io("DELETE",`/api/content/ideas/${e}`),promoteIdea:(e,t)=>jt(`/api/content/ideas/${e}/promote`,t??{}),listPillars:e=>Se(`/api/content/pillars${e?`?status=${encodeURIComponent(e)}`:""}`),getPillar:e=>Se(`/api/content/pillars/${e}`),createPillar:e=>jt("/api/content/pillars",e),updatePillar:(e,t)=>io("PATCH",`/api/content/pillars/${e}`,t),deletePillar:e=>io("DELETE",`/api/content/pillars/${e}`),atomisePillar:e=>jt(`/api/content/pillars/${e}/atomise`,{}),listAssets:(e,t,n)=>{const r=new URLSearchParams;e&&r.set("from",e),t&&r.set("to",t),n!=null&&n.undated&&r.set("undated","true");const a=r.toString();return Se(`/api/content/assets${a?`?${a}`:""}`)},createAsset:e=>jt("/api/content/assets",e),updateAsset:(e,t)=>io("PATCH",`/api/content/assets/${e}`,t),deleteAsset:e=>io("DELETE",`/api/content/assets/${e}`),suggestedLink:e=>Se(`/api/content/assets/${e}/suggested-link`),hookSources:()=>Se("/api/content/hook-sources"),resolveHook:(e,t)=>jt(`/api/content/pillars/${e}/resolve-hook`,t),pulse:()=>Se("/api/content/pulse"),generate:e=>jt("/api/content/generate",e),getThread:e=>Se(`/api/content/assets/${e}/thread`),saveThread:(e,t)=>io("PUT",`/api/content/assets/${e}/thread`,{turns:t}),generateImage:e=>jt("/api/content/generate-image",e),listProposals:()=>Se("/api/content/proposals"),updateProposal:(e,t)=>io("PATCH",`/api/content/proposals/${e}`,t),promoteProposal:(e,t)=>jt(`/api/content/proposals/${e}/promote`,t??{}),performance:e=>{const t=new URLSearchParams;e!=null&&e.days&&t.set("days",String(e.days)),e!=null&&e.pillar_id&&t.set("pillar_id",String(e.pillar_id));const n=t.toString();return Se(`/api/content/performance${n?`?${n}`:""}`)},listReviewQueue:()=>Se("/api/content/review-queue"),listComments:e=>Se(`/api/content/assets/${e}/comments`),addComment:(e,t)=>jt(`/api/content/assets/${e}/comments`,t),resolveComment:(e,t)=>io("POST",`/api/content/assets/${e}/comments/${t}/resolve`),repurpose:()=>Se("/api/content/repurpose"),draftRepurpose:e=>jt(`/api/content/repurpose/${e}/draft`,{}),filmQueue:()=>Se("/api/content/film-queue"),generateFilmScript:e=>jt(`/api/content/film-queue/${encodeURIComponent(e)}/generate`,{}),updateFilmScript:(e,t)=>io("PATCH",`/api/content/film-queue/${encodeURIComponent(e)}`,t),getDigest:e=>Se(`/api/content/digest/${encodeURIComponent(e)}`),updateDigestItem:(e,t)=>io("PATCH",`/api/content/digest-items/${e}`,t),emailDigest:e=>jt(`/api/content/digest/${encodeURIComponent(e)}/email`,{})},Xoe=Object.freeze(Object.defineProperty({__proto__:null,ROLLUP_SCOPE:JF,SELLER_CREATABLE_TYPES:QF,academyApi:wp,api:K,calendarApi:kN,contentApi:At,crmApi:Rr,crmFiltersActive:eB,crmFiltersToParams:_N,earnApi:Us,exportsApi:Ul,hasNewAcademyVideos:oC,marketExplorerApi:$t,notificationsApi:Ey,tasksApi:vr},Symbol.toStringTag,{value:"Module"})),jN="gadjet:amazonAppstore";function Joe(e){const t=e.get("cb");
756if(t){const n={cb:t,as:e.get("as"),spid:e.get("spid")};try{sessionStorage.setItem(jN,JSON.stringify(n))}catch{}return n}try{const n=sessionStorage.getItem(jN);if(n)return JSON.parse(n)}catch{}return null}function Qoe(){try{sessionStorage.removeItem(jN)}catch{}}function NN(){const[e]=ki(),t=xu(),[n,r]=p.useState(null),a=p.useRef(!1),i=p.useRef(null);i.current===null&&(i.current=Joe(e));const o=i.current;return p.useEffect(()=>{t.kind!=="authenticated"||!o||a.current||(a.current=!0,(async()=>{try{const{redirectUrl:l}=await K.amazonConnectAppstore({amazon_callback_uri:o.cb,amazon_state:o.as});let c;try{c=new URL(l)}catch{throw new Error("Amazon returned an invalid redirect.")}if(c.protocol!=="https:")throw new Error("Refusing to follow a non-https Amazon redirect.");Qoe(),window.location.href=c.href}catch(l){r((l==null?void 0:l.message)||"Couldn't start the Amazon connection."),a.current=!1}})())},[t.kind,o]),s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface-subtle px-4",children:s.jsxs("div",{className:"max-w-md w-full bg-surface border border-outline-subtle rounded-lg shadow-sm p-8 text-center",children:[s.jsx("div",{className:"mx-auto w-12 h-12 rounded-full bg-surface-brandSubtle border border-outline-brand flex items-center justify-center mb-4",children:s.jsx(sx,{className:"w-5 h-5 text-text-brand"})}),s.jsx("h1",{className:"text-xl font-semibold text-text-primary mb-2",children:"Connect your Amazon store"}),o?n?s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-outline-error bg-surface-errorSubtle p-3 text-left text-sm text-text-error",children:[s.jsx(yt,{className:"mt-0.5 h-4 w-4 shrink-0"}),s.jsx("span",{children:n})]}),s.jsx("button",{onClick:()=>{a.current=!1,r(null),window.location.reload()},className:"text-sm font-medium text-text-body border border-outline rounded-md px-4 py-2 hover:bg-surface-subtle",children:"Try again"})]}):t.kind==="anonymous"?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-sm text-text-body mb-5",children:"Sign in or create your Gadjet account to finish connecting your Amazon store. We'll bring you right back here."}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(st,{to:"/signin",className:"rounded-md bg-intent-brand px-4 py-2 text-sm font-medium text-text-inverse hover:bg-intent-brandHover",children:"Sign in"}),s.jsx(st,{to:"/signup",className:"rounded-md border border-outline px-4 py-2 text-sm font-medium text-text-body hover:bg-surface-subtle",children:"Create an account"})]})]}):s.jsxs("p",{className:"flex items-center justify-center gap-2 py-4 text-sm text-text-body",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Redirecting you to Amazonâ¦"]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-sm text-text-body mb-4",children:"This Amazon authorization link is incomplete or has expired. Start the connection again from Gadjet."}),s.jsx(st,{to:"/",className:"text-sm font-medium text-text-brand hover:underline",children:"Go to Gadjet"})]})]})})}const SN="gadjet:amazonOAuthComplete";
756function ele(e){const t=e.get("state"),n=e.get("code"),r=e.get("error");if(t||n||r){const a={state:t||"",code:n||"",spid:e.get("spid"),error:r};try{sessionStorage.setItem(SN,JSON.stringify(a))}catch{}return a}try{const a=sessionStorage.getItem(SN);if(a)return JSON.parse(a)}catch{}return null}function i1(){try{sessionStorage.removeItem(SN)}catch{}}function CN(){const[e]=ki(),t=xu(),[n,r]=p.useState(null),[a,i]=p.useState(null),o=p.useRef(!1),l=p.useRef(null);l.current===null&&(l.current=ele(e));const c=l.current;return p.useEffect(()=>{if(!(t.kind!=="authenticated"||!c||o.current)){if(c.error){r("You didn't approve the connection on Amazon. No changes were made."),i1();return}if(!c.state||!c.code){r("This Amazon authorization link is incomplete or has expired."),i1();return}o.current=!0,(async()=>{try{const u=await K.amazonCompleteOAuth({state:c.state,code:c.code,selling_partner_id:c.spid});i1(),i(u.seller_slug)}catch(u){r((u==null?void 0:u.message)||"Couldn't finish the Amazon connection."),o.current=!1}})()}},[t.kind,c]),s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface-subtle px-4",children:s.jsxs("div",{className:"max-w-md w-full bg-surface border border-outline-subtle rounded-lg shadow-sm p-8 text-center",children:[s.jsx("div",{className:"mx-auto w-12 h-12 rounded-full bg-surface-brandSubtle border border-outline-brand flex items-center justify-center mb-4",children:s.jsx(sx,{className:"w-5 h-5 text-text-brand"})}),s.jsx("h1",{className:"text-xl font-semibold text-text-primary mb-2",children:"Connect your Amazon store"}),a?s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-outline-success bg-surface-successSubtle p-3 text-left text-sm text-text-success",children:[s.jsx(Xt,{className:"mt-0.5 h-4 w-4 shrink-0"}),s.jsx("span",{children:"Amazon is linked. We'll begin pulling your data shortly."})]}),s.jsx(st,{to:"/",className:"inline-block text-sm font-medium text-text-brand hover:underline",children:"Return to Gadjet"})]}):n?s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-outline-error bg-surface-errorSubtle p-3 text-left text-sm text-text-error",children:[s.jsx(yt,{className:"mt-0.5 h-4 w-4 shrink-0"}),s.jsx("span",{children:n})]}),s.jsx(st,{to:"/",className:"text-sm font-medium text-text-brand hover:underline",children:"Go to Gadjet"})]}):t.kind==="anonymous"?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-sm text-text-body mb-5",children:"Sign in to finish connecting your Amazon store. We'll bring you right back here."}),s.jsx("div",{className:"flex flex-col gap-2",children:s.jsx(st,{to:"/signin",className:"rounded-md bg-intent-brand px-4 py-2 text-sm font-medium text-text-inverse hover:bg-intent-brandHover",children:"Sign in"})})]}):c?s.jsxs("p",{className:"flex items-center justify-center gap-2 py-4 text-sm text-text-body",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Finishing the Amazon connectionâ¦"]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-sm text-text-body mb-4",children:"This Amazon authorization link is incomplete or has expired. Start the connection again from Gadjet."}),s.jsx(st,{to:"/",className:"text-sm font-medium text-text-brand hover:underline",children:"Go to Gadjet"})]})]})})}function tle(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const nle=e=>{switch(e){case"success":return ale;case"info":return ole;case"warning":return ile;case"error":return lle;default:return null}},rle=Array(12).fill(0),sle=({visible:e,className:t})=>nt.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},nt.createElement("div",{className:"sonner-spinner"},rle.map((n,r)=>nt.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),ale=nt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20","aria-hidden":"true"},nt.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),ile=nt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"
756currentColor",height:"20",width:"20","aria-hidden":"true"},nt.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),ole=nt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20","aria-hidden":"true"},nt.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),lle=nt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20","aria-hidden":"true"},nt.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),cle=nt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},nt.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),nt.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),ule=()=>{const[e,t]=nt.useState(document.hidden);return nt.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>document.removeEventListener("visibilitychange",n)},[]),e};let dle=1;const hle=100,zO=e=>{var t;return typeof(e==null?void 0:e.id)=="number"||(e==null||(t=e.id)==null?void 0:t.length)>0?e.id:dle++};class fle{constructor(){this.subscribe=t=>
756(this.subscribers.push(t),this.getActiveToasts().forEach(n=>t(n)),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t],this.trimHistory()},this.trimHistory=()=>{let t=this.toasts.length-hle;t<=0||(this.toasts=this.toasts.filter(n=>t>0&&this.dismissedToasts.has(n.id)?(this.dismissedToasts.delete(n.id),t--,!1):!0))},this.create=t=>{const{message:n,...r}=t,a=zO(t),i=this.pendingDismissals.get(a);i!==void 0&&(cancelAnimationFrame(i),this.pendingDismissals.delete(a),this.dismissedToasts.delete(a));const o=this.dismissedToasts.has(a),l=t.dismissible===void 0?!0:t.dismissible;return o&&(this.dismissedToasts.delete(a),this.toasts=this.toasts.filter(u=>u.id!==a)),(o?void 0:this.toasts.find(u=>u.id===a))?this.toasts=this.toasts.map(u=>u.id===a?(this.publish({...u,...t,id:a,title:n}),{...u,...t,id:a,dismissible:l,title:n}):u):this.addToast({title:n,...r,dismissible:l,id:a}),a},this.dismiss=t=>
756{if(t==null)return this.getActiveToasts().forEach(r=>{this.dismissedToasts.add(r.id),this.subscribers.forEach(a=>a({id:r.id,dismiss:!0}))}),t;this.dismissedToasts.add(t);const n=this.pendingDismissals.get(t);return n!==void 0&&cancelAnimationFrame(n),this.pendingDismissals.set(t,requestAnimationFrame(()=>{this.pendingDismissals.delete(t),this.subscribers.forEach(r=>r({id:t,dismiss:!0}))})),t},this.message=(t,n)=>this.create({...n,message:t,type:void 0}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const a=Promise.resolve(t instanceof Function?t():t);let i=r!==void 0,o;const l=a.then(async u=>{if(o=["resolve",u],nt.isValidElement(u))i=!1,this.create({id:r,type:"default",message:u});else if(ple(u)&&!u.ok){i=!1;const h=typeof n.error=="function"?await n.error(`HTTP error! status: ${u.status}`):n.error,f=typeof n.description=="function"?await n.description(`HTTP error! status: ${u.status}`):n.description,x=typeof h=="object"&&!nt.isValidElement(h)?h:{message:h};this.create({id:r,type:"error",description:f,...x})}else if(u instanceof Error){i=!1;const h=typeof n.error=="function"?await n.error(u):n.error,f=typeof n.description=="function"?await n.description(u):n.description,x=typeof h=="object"&&!nt.isValidElement(h)?h:{message:h};this.create({id:r,type:"error",description:f,...x})}else if(n.success!==void 0){i=!1;const h=typeof n.success=="function"?await n.success(u):n.success,f=typeof n.description=="function"?await n.description(u):n.description,x=typeof h=="object"&&!nt.isValidElement(h)?h:{message:h};this.create({id:r,type:"success",description:f,...x})}}).catch(async u=>{if(o=["reject",u],n.error!==void 0){i=!1;const d=typeof n.error=="function"?await n.error(u):n.error,h=typeof n.description=="function"?await n.description(u):n.description,m=typeof d=="object"&&!nt.isValidElement(d)?d:{message:d};this.create({id:r,type:"error",description:h,...m})}}).finally(()=>{i&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),c=()=>new Promise((u,d)=>l.then(()=>o[0]==="reject"?d(o[1]):u(o[1])).catch(d));return typeof r!="string"&&typeof r!="number"?{unwrap:c}:Object.assign(r,{unwrap:c})},this.custom=(t,n)=>{const r=zO(n);return this.create({...n,jsx:t(r),id:r,type:void 0}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set,this.pendingDismissals=new Map}}const Ya=new fle,mle=(e,t)=>Ya.message(e,t),ple=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",xle=mle,gle=()=>Ya.toasts,yle=()=>Ya.getActiveToasts(),fo=Object.assign(xle,{success:Ya.success,info:Ya.info,warning:Ya.warning,error:Ya.error,custom:Ya.custom,message:Ya.message,promise:Ya.promise,dismiss:Ya.dismiss,loading:Ya.loading},{getHistory:gle,getToasts:yle});tle
vendor: 14,921 bytes, line 756
756("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px;flex:1;min-width:0}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--normal-text);background:var(--normal-bg);border:1px solid var(--normal-border);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{-webkit-user-select:none;user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");
vendor: 11,480 bytes, line 756
756function mg(e){return e.label!==void 0}const ble=3,vle="24px",wle="16px",WO=4e3,_le=356,kle=14,jle=45,Nle=200;function Do(...e){return e.filter(Boolean).join(" ")}function Sle(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const Cle=e=>{var t,n,r,a,i,o,l,c,u;const{invert:d,toast:h,unstyled:f,interacting:m,setHeights:x,visibleToasts:g,heights:y,index:b,toasts:v,expanded:w,removeToast:_,defaultRichColors:k,closeButton:j,style:N,cancelButtonStyle:E,actionButtonStyle:A,className:C="",descriptionClassName:T="",duration:S,position:O,gap:R,expandByDefault:I,classNames:$,icons:P,closeButtonAriaLabel:F="Close toast"}=e,[Z,D]=nt.useState(null),[H,Y]=nt.useState(null),[M,z]=nt.useState(!1),[G,te]=nt.useState(!1),[re,L]=nt.useState(!1),[q,me]=nt.useState(!1),[ee,ne]=nt.useState(!1),[X,he]=nt.useState(0),[ae,je]=nt.useState(0),$e=nt.useRef(h.duration||S||WO),J=nt.useRef(null),Ne=nt.useRef(null),ve=b===0,Me=b+1<=g,Xe=h.type,ze=Xe??"default",Fe=h.dismissible!==!1,tt=h.className||"",fe=h.descriptionClassName||"",U=nt.useMemo(()=>y.findIndex(Ie=>Ie.toastId===h.id)||0,[y,h.id]),ce=nt.useMemo(()=>{var Ie;return(Ie=h.closeButton)!=null?Ie:j},[h.closeButton,j]),ue=nt.useMemo(()=>h.duration||S||WO,[h.duration,S]),Ee=nt.useRef(0),bt=nt.useRef(0),Ze=nt.useRef(0),vt=nt.useRef(null),[Ot,It]=O.split("-"),Ut=nt.useMemo(()=>y.reduce((Ie,Ge,ye)=>ye>=U?Ie:Ie+Ge.height,0),[y,U]),Lr=ule(),en=nt.useMemo(()=>{var Ie;return(Ie=e.swipeDirections)!=null?Ie:Sle(O)},[e.swipeDirections,O]),Hs=h.invert||d,Os=Xe==="loading";bt.current=nt.useMemo(()=>U*R+Ut,[U,Ut]),nt.useEffect(()=>{$e.current=ue},[ue]),nt.useEffect(()=>{z(!0)},[]),nt.useEffect(()=>{const Ie=Ne.current;if(Ie){const Ge=Ie.getBoundingClientRect().height;return je(Ge),x(ye=>[{toastId:h.id,height:Ge,position:h.position},...ye]),()=>x(ye=>ye.filter(ie=>ie.toastId!==h.id))}},[x,h.id]),nt.useLayoutEffect(()=>{if(!M)return;const Ie=Ne.current,Ge=Ie.style.height;Ie.style.height="auto";const ye=Ie.getBoundingClientRect().height;Ie.style.height=Ge,je(ye),x(ie=>ie.find(xe=>xe.toastId===h.id)?ie.map(xe=>xe.toastId===h.id?{...xe,height:ye}:xe):[{toastId:h.id,height:ye,position:h.position},...ie])},[M,h.title,h.description,x,h.id,h.jsx,h.action,h.cancel]);const gr=nt.useCallback(()=>{te(!0),he(bt.current),x(Ie=>Ie.filter(Ge=>Ge.toastId!==h.id)),setTimeout(()=>{_(h)},Nle)},[h,_,x,bt]);nt.useEffect(()=>{if(h.promise&&Xe==="loading"||h.duration===1/0||h.type==="loading")return;let Ie;return w||m||Lr?(()=>{if(Ze.current<Ee.current){const ie=new Date().getTime()-Ee.current;$e.current=$e.current-ie}Ze.current=new Date().getTime()})():(()=>{$e.current!==1/0&&(Ee.current=new Date().getTime(),Ie=setTimeout(()=>{h.onAutoClose==null||h.onAutoClose.call(h,h),gr()},$e.current))})(),()=>clearTimeout(Ie)},[w,m,h,Xe,Lr,gr]),nt.useEffect(()=>{h.delete&&(gr(),h.onDismiss==null||h.onDismiss.call(h,h))},[gr,h.delete]);function Vs(){var Ie;if(P!=null&&P.loading){var Ge;return nt.createElement("div",{className:Do($==null?void 0:$.loader,h==null||(Ge=h.classNames)==null?void 0:Ge.loader,"sonner-loader"),"data-visible":Xe==="loading"},P.loading)}return nt.createElement(sle,{className:Do($==null?void 0:$.loader,h==null||(Ie=h.classNames)==null?void 0:Ie.loader),visible:Xe==="loading"})}const Xn=h.icon||(P==null?void 0:P[Xe])||nle(Xe);var le,De;return nt.createElement("li",{tabIndex:0,ref:Ne,className:Do(C,tt,$==null?void 0:$.toast,h==null||(t=h.classNames)==null?void 0:t.toast,$==null?void 0:$[ze],h==null||(n=h.classNames)==null?void 0:n[ze]),"data-sonner-toast":"","data-rich-colors":(le=h.richColors)!=null?le:k,"data-styled":!(h.jsx||h.unstyled||f),"data-mounted":M,"data-promise":!!h.promise,"data-swiped":ee,"data-removed":G,"data-visible":Me,"data-y-position":Ot,"data-x-position":It,"data-index":b,"data-front":ve,"data-swiping":re,"data-dismissible":Fe,"data-type":Xe,"data-invert":Hs,"data-swipe-out":q,"data-swipe-direction":H,"data-expanded":!!(w||I&&M),"data-testid":h.testId,style:{"--index":b,"--toasts-before":b,"--z-index":v.length-b,"--offset":`${G?X:bt.current}px`,"--initial-height":I?"auto":`${ae}px`,...N,...h.style},onDragEnd:()=>{L(!1),D(null),vt.current=null},onPointerDown:Ie=>{Ie.button!==2&&(Os||!Fe||(J.current=new Date,he(bt.current),Ie.target.setPointerCapture(Ie.pointerId),Ie.target.tagName!=="BUTTON"&&(L(!0),vt.current={x:Ie.clientX,y:Ie.clientY})))},onPointerUp:()=>{var Ie,Ge,ye;if(q||!Fe)return;vt.current=null;const ie=Number(((Ie=Ne.current)==null?void 0:Ie.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),pe=Number(((Ge=Ne.current)==null?void 0:Ge.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),xe=new Date().getTime()-((ye=J.current)==null?void 0:ye.getTime()),Ke=Z==="x"?ie:pe,St=Math.abs(Ke)/xe;if((Z==="x"?en.includes(ie>0?"right":"left"):en.includes(pe>0?"bottom":"top"))&&(Math.abs(Ke)>=jle||St>.11)){he(bt.current),h.onDismiss==null||h.onDismiss.call(h,h),Y(Z==="x"?ie>0?"right":"left":pe>0?"down":"up"),gr(),me(!0);return}else{var yn,no;(yn=Ne.current)==null||yn.style.setProperty("--swipe-amount-x","0px"),(no=Ne.current)==null||no.style.setProperty("--swipe-amount-y","0px")}ne(!1),L(!1),D(null)},onPointerMove:Ie=>{var Ge,ye,ie;if(!vt.current||!Fe||((Ge=window.getSelection())==null?void 0:Ge.toString().length)>0)return;const xe=Ie.clientY-vt.current.y,Ke=Ie.clientX-vt.current.x;!Z&&(Math.abs(Ke)>1||Math.abs(xe)>1)&&D(Math.abs(Ke)>Math.abs(xe)?"x":"y");let St={x:0,y:0};const Jt=yn=>1/(1.5+Math.abs(yn)/20);if(Z==="y"){if(en.includes("top")||en.includes("bottom"))if(en.includes("top")&&xe<0||en.includes("bottom")&&xe>0)St.y=xe;else{const yn=xe*Jt(xe);St.y=Math.abs(yn)<Math.abs(xe)?yn:xe}}else if(Z==="x"&&(en.includes("left")||en.includes("right")))if(en.includes("left")&&Ke<0||en.includes("right")&&Ke>0)St.x=Ke;else{const yn=Ke*Jt(Ke);St.x=Math.abs(yn)<Math.abs(Ke)?yn:Ke}(Math.abs(St.x)>0||Math.abs(St.y)>0)&&ne(!0),(ye=Ne.current)==null||ye.style.setProperty("--swipe-amount-x",`${St.x}px`),(ie=Ne.current)==null||ie.style.setProperty("--swipe-amount-y",`${St.y}px`)}},ce&&!h.jsx&&Xe!=="loading"?nt.createElement("button",{"aria-label":F,"data-disabled":Os,"data-close-button":!0,onClick:Os||!Fe?()=>{}:()=>{gr(),h.onDismiss==null||h.onDismiss.call(h,h)},className:Do($==null?void 0:$.closeButton,h==null||(r=h.classNames)==null?void 0:r.closeButton)},(De=P==null?void 0:P.close)!=null?De:cle):null,(Xe||h.icon||h.promise)&&h.icon!==null&&((P==null?void 0:P[Xe])!==null||h.icon)?nt.createElement("div",{"data-icon":"",className:Do($==null?void 0:$.icon,h==null||(a=h.classNames)==null?void 0:a.icon)},Xe==="loading"?h.icon||Vs():h.promise?Vs():null,Xe!=="loading"?Xn:null):null,nt.createElement("div",{"data-content":"",className:Do($==null?void 0:$.content,h==null||(i=h.classNames)==null?void 0:i.content)},nt.createElement("div",{"data-title":"",className:Do($==null?void 0:$.title,h==null||(o=h.classNames)==null?void 0:o.title)},h.jsx?h.jsx:typeof h.title=="function"?h.title():h.title),h.description?nt.createElement("div",{"data-description":"",className:Do(T,fe,$==null?void 0:$.description,h==null||(l=h.classNames)==null?void 0:l.description)},typeof h.description=="function"?h.description():h.description):null),nt.isValidElement(h.cancel)?h.cancel:h.cancel&&mg(h.cancel)?nt.createElement("button",{"data-button":!0,"data-cancel":!0,style:h.cancelButtonStyle||E,onClick:Ie=>{mg(h.cancel)&&Fe&&(h.cancel.onClick==null||h.cancel.onClick.call(h.cancel,Ie),gr())},className:Do($==null?void 0:$.cancelButton,h==null||(c=h.classNames)==null?void 0:c.cancelButton)},h.cancel.label):null,nt.isValidElement(h.action)?h.action:h.action&&mg(h.action)?nt.createElement("button",{"data-button":!0,"data-action":!0,style:h.actionButtonStyle||A,onClick:Ie=>{mg(h.action)&&(h.action.onClick==null||h.action.onClick.call(h.action,Ie),!Ie.defaultPrevented&&gr())},className:Do($==null?void 0:$.actionButton,h==null||(u=h.classNames)==null?void 0:u.actionButton)},h.action.label):null)};function KO(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function Ele(e,t){const n={};return[e,t].forEach((r,a)=>{const i=a===1,o=i?"--mobile-offset":"--offset",l=i?wle:vle;function c(u){["top","right","bottom","left"].forEach(d=>{n[`${o}-${d}`]=typeof u=="number"?`${u}px`:u})}typeof r=="number"||typeof r=="string"?c(r):typeof r=="object"?["top","right","bottom","left"].forEach(u=>{r[u]===void 0?n[`${o}-${u}`]=l:n[`${o}-${u}`]=typeof r[u]=="number"?`${r[u]}px`:r[u]}):c(l)}),n}const Ale=nt.forwardRef(function(t,n){const{id:r,invert:a,position:i="bottom-right",hotkey:o=["altKey","KeyT"],expand:l,closeButton:c,className:u,offset:d,mobileOffset:h,theme:f="light",richColors:m,duration:x,style:g,visibleToasts:y=ble,toastOptions:b,dir:v=KO(),gap:w=kle,icons:_,customAriaLabel:k,containerAriaLabel:j="Notifications"}=t,[N,E]=nt.useState([]),A=nt.useMemo(()=>r?N.filter(z=>z.toasterId===r):N.filter(z=>!z.toasterId),[N,r]),C=nt.useMemo(()=>Array.from(new Set([i].concat(A.filter(z=>z.position).map(z=>z.position)))),[A,i]),[T,S]=nt.useState([]),[O,R]=nt.useState(!1),[I,$]=nt.useState(!1),[P,F]=nt.useState(f!=="system"?f:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Z=nt.useRef(null),D=o.join("+").replace(/Key/g,"").replace(/Digit/g,""),H=nt.useRef(null),Y=nt.useRef(!1),M=nt.useCallback(z=>{E(G=>{var te;return(te=G.find(re=>re.id===z.id))!=null&&te.delete||Ya.dismiss(z.id),G.filter(({id:re})=>re!==z.id)})},[]);return nt.useEffect(()=>Ya.subscribe(z=>{if(z.dismiss){requestAnimationFrame(()=>{E(G=>G.map(te=>te.id===z.id?{...te,delete:!0}:te))});return}setTimeout(()=>{SY.flushSync(()=>{E(G=>{const te=G.findIndex(re=>re.id===z.id);return te!==-1?[...G.slice(0,te),{...G[te],...z},...G.slice(te+1)]:[z,...G]})})})}),[]),nt.useEffect(()=>{if(f!=="system"){F(f);return}if(f==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?F("dark"):F("light")),typeof window>"u")return;const z=window.matchMedia("(prefers-color-scheme: dark)");try{z.addEventListener("change",({matches:G})=>{F(G?"dark":"light")})}catch{z.addListener(({matches:te})=>{try{F(te?"dark":"light")}catch(re){console.error(re)}})}},[f]),nt.useEffect(()=>{N.length<=1&&R(!1)},[N]),nt.useEffect(()=>{const z=G=>{var te;if(o.length>0&&o.every(q=>G[q]||G.code===q)){var L;R(!0),(L=Z.current)==null||L.focus()}G.code==="Escape"&&(document.activeElement===Z.current||(te=Z.current)!=null&&te.contains(document.activeElement))&&R(!1)};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[o]),nt.useEffect(()=>{if(Z.current)return()=>{H.current&&(H.current.focus({preventScroll:!0}),H.current=null,Y.current=!1)}},[Z.current]),nt.createElement("section",{ref:n,"aria-label":k??`${j} ${D}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0,"data-react-aria-top-layer":!0},C.map((z,G)=>{var te;const[re,L]=z.split("-");return A.length?nt.createElement("ol",{key:z,dir:v==="auto"?KO():v,tabIndex:-1,ref:Z,className:u,"data-sonner-toaster":!0,"data-sonner-theme":P,"data-y-position":re,"data-x-position":L,style:{"--front-toast-height":`${((te=T[0])==null?void 0:te.height)||0}px`,"--width":`${_le}px`,"--gap":`${w}px`,...g,...Ele(d,h)},onBlur:q=>{Y.current&&!q.currentTarget.contains(q.relatedTarget)&&(Y.current=!1,H.
756current&&(H.current.focus({preventScroll:!0}),H.current=null))},onFocus:q=>{q.target instanceof HTMLElement&&q.target.dataset.dismissible==="false"||Y.current||(Y.current=!0,H.current=q.relatedTarget)},onMouseEnter:()=>R(!0),onMouseMove:()=>R(!0),onMouseLeave:()=>{I||R(!1)},onDragEnd:()=>R(!1),onPointerDown:q=>{q.target instanceof HTMLElement&&q.target.dataset.dismissible==="false"||$(!0)},onPointerUp:()=>$(!1)},A.filter(q=>!q.position&&G===0||q.position===z).map((q,me)=>{var ee,ne;return nt.createElement(Cle,{key:q.id,icons:_,index:me,toast:q,defaultRichColors:m,duration:(ee=b==null?void 0:b.duration)!=null?ee:x,className:b==null?void 0:b.className,descriptionClassName:b==null?void 0:b.descriptionClassName,invert:a,visibleToasts:y,closeButton:(ne=b==null?void 0:b.closeButton)!=null?ne:c,interacting:I,position:z,style:b==null?void 0:b.style,unstyled:b==null?void 0:b.unstyled,classNames:b==null?void 0:b.classNames,cancelButtonStyle:b==null?void 0:b.cancelButtonStyle,actionButtonStyle:b==null?void 0:b.actionButtonStyle,closeButtonAriaLabel:b==null?void 0:b.closeButtonAriaLabel,removeToast:M,toasts:A.filter(X=>X.position==q.position),heights:T.filter(X=>X.position==q.position),setHeights:S,expandByDefault:l,gap:w,expanded:O,swipeDirections:t.swipeDirections})})):null}))}),c0={takealot:{label:"Takealot",short:"T",bg:"#0a7ef2",fg:"#ffffff"},amazon_za:{label:"Amazon",short:"a",bg:"#232f3e",fg:"#ff9900"},amazon_us:{label:"Amazon",short:"a",bg:"#232f3e",fg:"#ff9900"},makro:{label:"Makro",short:"M",bg:"#e2001a",fg:"#ffffff"},shopify:{label:"Shopify",short:"S",bg:"#5a8f2f",fg:"#ffffff"}},Tle={sm:20,md:26,lg:32};function Ole(e){return typeof e=="string"?Tle[e]:e}function _p(e){var t;return e?((t=c0[e])==null?void 0:t.label)??e:"Other"}function _f(e){return!!e&&String(e).startsWith("amazon")}function kp(e){if(e==null||String(e).trim()==="")return null;const t=String(e).toUpperCase();return t==="DEFAULT"||t==="MFN"?"FBM":"FBA"}function Ile(e){var n;if(!e)return"Listings";const t=(n=c0[e])==null?void 0:n.label;return t?`${t} Listings`:"Listings"}function kf({marketplace:e,size:t=14,showLabel:n,meta:r,className:a}){const i=e?c0[e]:null;if(!i)return null;const o=Ole(t),l=s.jsx("span",{"aria-hidden":n?!0:void 0,style:{backgroundColor:i.bg,color:i.fg,width:o,height:o,fontSize:Math.max(8,Math.round(o*.5))},className:"shrink-0 rounded-sm grid place-items-center font-bold leading-none",children:i.short});return n?s.jsxs("span",{className:B("inline-flex items-center gap-2 min-w-0",a),children:[l,s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block text-body-sm font-medium text-text-primary whitespace-nowrap",children:i.label}),r&&s.jsx("span",{className:"block text-body-xs text-text-secondary whitespace-nowrap",children:r})]})]}):s.jsx("span",{title:i.label,role:"img","aria-label":i.label,className:a,children:l})}const Ple=hf("inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full font-semibold",{variants:{size:{24:"h-6 w-6 text-body-xs",28:"h-7 w-7 text-body-xs",32:"h-8 w-8 text-body-xs",40:"h-10 w-10 text-body-sm"},tone:{neutral:"bg-surface-sunken text-text-body",self:"bg-surface-brandSubtle text-text-brand"}},defaultVariants:{size:32,tone:"neutral"}});function tB(e){const t=e.includes("@")?e.split("@")[0]??"":e.trim(),n=t.split(/[._\s-]+/).filter(Boolean);return n.length>=2?(n[0][0]+n[1][0]).toUpperCase():t?t.slice(0,2).toUpperCase():"??"}const lC=p.forwardRef(({className:e,size:t,tone:n,src:r,initials:a,alt:i="",...o},l)=>{const[c,u]=p.useState(!1),d=!!r&&!c;return p.useEffect(()=>{u(!1)},[r]),s.jsx("span",{ref:l,className:B(Ple({size:t,tone:n}),e),...o,children:d?s.jsx("img",{src:r??void 0,alt:i,className:"h-full w-full object-cover",onError:()=>u(!0)}):a})});lC.displayName="Avatar";const Rle=[[/^\/sellers\/[^/]+\/automations(\/|$)/,"seller.automations"],[/^\/sellers\/[^/]+\/sales(\/|$)/,"seller.sales"],[/^\/sellers\/[^/]+\/inventory(\/|$)/,"seller.inventory"],[/^\/sellers\/[^/]+\/shipments(\/|$)/,"seller.shipments"],[/^\/sellers\/[^/]+\/returns(\/|$)/,"seller.returns"],[/^\/sellers\/[^/]+\/transactions(\/|$)/,"seller.transactions"],[/^\/sellers\/[^/]+\/tasks(\/|$)/,"seller.tasks"],[/^\/sellers\/[^/]+\/chats(\/|$)/,"agent"],[/^\/settings\/stores\/[^/]+/,"seller.settings"],[/^\/overview(\/|$)/,"overview"],[/^\/agent(\/|$)/,"agent"],[/^\/crm(\/|$)/,"crm"],[/^\/calendar(\/|$)/,"calendar"],[/^\/tasks(\/|$)/,"tasks"],[/^\/skills(\/|$)/,"skills"],[/^\/dashboards(\/|$)/,"reports"],[/^\/market-explorer(\/|$)/,"market-explorer"],[/^\/sops(\/|$)/,"sops"],[/^\/approvals(\/|$)/,"sops"],[/^\/ads(\/|$)/,"ads"],[/^\/earn(\/|$)/,"earn"],[/^\/content(\/|$)/,"content"]];function Dle(e){for(const[t,n]of Rle)if(t.test(e))return n;return null}function Kc(e,t){return e?e[t]!==!1:!0}function Mle(e,t,n){const r=t?[...n?[[`/overview/${n}`,"overview"]]:[],["/dashboards","reports"],["/agent","agent"]]:[["/agent","agent"],["/overview","overview"],["/dashboards","reports"],["/content","content"]];for(const[a,i]of r)if(Kc(e,i))return a;return"/dashboards"}function $le(e){return e==="super_admin"||e==="am"||e==="content_creator"}function Lle(){const[e,t]=p.useState(()=>yN());return p.useEffect(()=>{function n(){t(yN())}return window.addEventListener("storage",n),window.addEventListener("gadjet:demo-view-changed",n),()=>{window.removeEventListener("storage",n),window.removeEventListener("gadjet:demo-view-changed",n)}},[]),e}async function Fle(){const e=await oe("/api/demo-view/enter",{method:"POST"});if(!e.ok){const r=await e.json().catch(()=>({}));throw new Error((r==null?void 0:r.message)||(r==null?void 0:r.error)||`HTTP ${e.status}`)}const t=await e.json(),n={expires_at:t.expires_at};return GF(t.token,n),ai(),n}async function Ble(){try{await oe("/api/demo-view/exit",{method:"POST"})}catch{}rC(),ai()}const HO="(max-width: 767px)";function Ule(){const[e,t]=p.useState(()=>typeof window>"u"?!1:window.matchMedia(HO).matches);return p.useEffect(()=>{if(typeof window>"u")return;const n=window.matchMedia(HO),r=a=>t(a.matches);return n.addEventListener?n.addEventListener("change",r):n.addListener(r),t(n.matches),(
756)=>{n.removeEventListener?n.removeEventListener("change",r):n.removeListener(r)}},[]),e}const u0="new";function Ju(e){return e===u0}function qo(e){return!e||e===u0?null:e}function Zl(){return`/agent/${u0}`}function cC(e){return`/sellers/${e}/chats/${u0}`}function zle(e){const t=String(e||"").replace(/\/+$/,"")||"/";return t==="/agent"||/^\/sellers\/[^/]+\/chats$/.test(t)||/^\/sellers\/[^/]+\/reports$/.test(t)}function jf(){const e=Rt(),t=Lt();return function(r,a){if((t.kind==="ready"?t.me.role:null)==="seller_user"){const c=t.kind==="ready"?t.me.allowed_slugs??[]:[],u=a&&c.includes(a)?a:c[0]??null;if(!u){e("/agent");return}(async()=>{try{const d=await K.createChat(u);sessionStorage.setItem(`gadjet:seed:${d.id}`,r),e(`/sellers/${u}/chats/${d.id}`)}catch(d){console.error("seeded chat creation failed",d),e(`/sellers/${u}/chats`)}})();return}const l=new URLSearchParams({prompt:r});a&&l.set("seller",a),e(`${Zl()}?${l.toString()}`)}}function Wle(){return wd.isNativePlatform()}function wr(){return Wle()}const Hc="This app does not take payments. Sign in with a Gadjet account that already has a plan, or finish billing in a browser on the Gadjet website.",VO=["starter","business","empire"];function nB({highlight:e=null,hideStarter:t=!1,busy:n=!1,onPick:r,reason:a}){const i=t?VO.filter(o=>o!=="starter"):VO;return s.jsxs("div",{className:"space-y-3",children:[a?s.jsx("p",{className:"text-sm text-text-secondary",children:a}):null,s.jsx("div",{className:"grid gap-2",children:i.map(o=>{const l=fi[o],c=e===o;return s.jsxs("button",{type:"button",disabled:n,onClick:()=>r(o),className:B("flex min-h-11 w-full items-center justify-between rounded-lg border px-4 py-3 text-left disabled:opacity-60",c?"border-outline-brand bg-surface-brandSubtle":"border-outline-subtle bg-surface hover:border-outline-brand"),children:[s.jsxs("span",{children:[s.jsxs("span",{className:"block text-sm font-medium text-text-primary",children:[l.displayName,c?s.jsx("span",{className:"ml-2 text-xs font-normal text-text-brand",children:"Recommended"}):null]}),s.jsxs("span",{className:"block text-xs text-text-tertiary",children:["R",zc(l.priceZar),"/mo · ",l.maxSellers," store",l.maxSellers===1?"":"s"," · R",zc(l.monthlyGrantZar)," chat credits"]})]}),n&&c?s.jsx(_e,{className:"h-4 w-4 shrink-0 animate-spin text-text-tertiary"}):s.jsx("span",{className:"text-xs font-medium text-text-brand",children:"Choose"})]},o)})})]})}const Xm=fi,Kle=5e3,Hle=180*1e3;function Vle(e){return e==="starter"?"business":e==="business"?"empire":null}function qle({open:e,onOpenChange:t,onConnected:n,resumeAfterPayment:r=!1}){var Z;const a=Rt(),[i,o]=p.useState("loading"),[l,c]=p.useState(!1),[u,d]=p.useState(null),[h,f]=p.useState(null),[m,x]=p.useState(""),[g,y]=p.useState(""),[b,v]=p.useState(null),[w,_]=p.useState(null),[k,j]=p.useState(null),N=(h==null?void 0:h.account_type)??"starter",E=((Z=Xm[N])==null?void 0:Z.maxSellers)??null,A=Vle(N),C=p.useCallback(async()=>{var H;o("loading"),d(null);const D=r?"pay-waiting":"key";try{const Y=await K.billingState();if(Y.kind!=="customer"){f(null),o(D);return}if(f(Y),Y.subscription_status==="past_due"){o("update-card");return}const M=Y.billing_program==="complimentary_under_100k";if(r&&Y.subscription_status!=="active"){o("pay-waiting");return}if(Y.subscription_status==="active"){const z=((H=Xm[Y.account_type])==null?void 0:H.maxSellers)??null,G=z!==null&&Y.seller_count>=z;o(G?"capped":"choose");return}if(M&&Y.seller_count>=1){_("business"),j("Free plan includes one Takealot store. Upgrade to add another store or Amazon."),o("pick-plan");return}if(Y.seller_count>0&&!M){_("business"),j("Last 30 days of Takealot sales are R100k or more. Pick a plan to unlock your workspace."),o("pick-plan");return}o("key")}catch{f(null),o(D)}},[r]);p.useEffect(()=>{e&&(x(""),y(""),v(null),c(!1),C())},[e,C]);const T=p.useRef(()=>{});T.current=()=>{C()};const S=p.useCallback(async()=>{var D;try{const H=await K.billingState();if(H.kind==="customer"&&H.subscription_status==="active"){f(H);const Y=((D=Xm[H.account_type])==null?void 0:D.maxSellers)??null,M=Y!==null&&H.seller_count>=Y;return o(M?"capped":"choose"),!0}}catch{}return!1},[]);p.useEffect(()=>{if(i!=="pay-waiting")return;let D=!1;const H=()=>{D||S()};window.addEventListener("focus",H);const Y=setInterval(H,Kle),M=setTimeout(()=>{D=!0,clearInterval(Y)},Hle);return()=>{D=!0,window.removeEventListener("focus",H),clearInterval(Y),clearTimeout(
756M)}},[i,S]);async function O(D="starter"){c(!0),d(null);try{const H=await K.initiateSubscription(D);if(H.manage_url){window.open(H.manage_url,"_blank","noopener,noreferrer"),o("pay-waiting");return}H.authorization_url&&window.open(H.authorization_url,"_blank","noopener,noreferrer"),o("pay-waiting")}catch(H){d({message:(H==null?void 0:H.message)||"Couldn't start checkout."})}finally{c(!1)}}async function R(){c(!0),d(null);try{const{link:D}=await K.billingManageSubscription();window.open(D,"_blank","noopener,noreferrer"),o("pay-waiting")}catch(D){d({message:(D==null?void 0:D.message)||"Couldn't open Paystack."})}finally{c(!1)}}async function I(){const D=m.trim();if(!D){d({message:"Paste your Takealot Marketplace API key first."});return}c(!0),d(null);try{const H=await K.attachTakealotKey(D,g.trim()||void 0);if(v({slug:H.slug,display_name:H.display_name}),window.dispatchEvent(new CustomEvent("gadjet:chat-saved")),H.requires_plan){_(H.highlight_plan||"business"),j("Store connected. Last 30 days of Takealot sales are R100k or more â pick a plan to unlock dashboards."),o("pick-plan");return}o("done"),n==null||n({slug:H.slug,display_name:H.display_name})}catch(H){const Y=H;Y.code==="plan_cap_reached"?(await C(),o("capped")):Y.code==="subscription_required"?(_(Y.highlightPlan||"business"),j(Y.message||"Pick a plan to continue."),o("pick-plan")):d({code:Y.code,message:Zle(Y)})}finally{c(!1)}}async function $(){c(!0),d(null);try{const{consentUrl:D}=await K.amazonConnect("amazon_za");window.location.href=D}catch(D){const H=D;H.code==="subscription_required"?(_(H.highlightPlan||"business"),j(H.message||"Amazon requires a paid plan. Starter and Free are Takealot-only."),o("pick-plan")):d({message:H.message||"Couldn't start the Amazon connection."}),c(!1)}}async function P(D){c(!0),d(null);try{await K.billingChangePlan(D),await C()}catch(H){d({message:(H==null?void 0:H.message)||"Couldn't change your plan."})}finally{c(!1)}}function F(){b&&a(`/sellers/${b.slug}/chats`),t(!1)}return s.jsx(js,{open:e,onOpenChange:t,children:s.jsxs(Ns,{size:i==="key"?"xl":"md",children:[s.jsxs(La,{children:[s.jsxs(ma,{className:"flex items-center gap-2",children:[s.jsx("span",{className:"inline-flex h-7 w-7 items-center justify-center rounded-full bg-surface-brandSubtle text-text-brand",children:s.jsx(sx,{className:"h-4 w-4"})}),i==="done"?"Store connected":i==="key"?"Connect your Takealot store":"Connect a store"]}),i!=="done"&&s.jsx(hc,{children:Yle(i)})]}),s.jsxs(Oa,{className:"min-h-[120px]",children:[u&&s.jsxs("div",{className:"mb-4 flex items-start gap-2 rounded-lg border border-outline-error bg-surface-errorSubtle p-3 text-sm text-text-error",children:[s.jsx(yt,{className:"mt-0.5 h-4 w-4 shrink-0"}),s.jsx("span",{children:u.message})]}),i==="loading"&&s.jsxs("div",{className:"flex items-center gap-2 py-6 text-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Checking your accountâ¦"]}),i==="pick-plan"&&(wr()?s.jsx("p",{className:"text-sm text-text-secondary",children:Hc}):s.jsx(nB,{highlight:w,hideStarter:w==="business",busy:l,reason:k||void 0,onPick:D=>void O(D)})),i==="update-card"&&s.jsx("div",{className:"space-y-3 text-sm text-text-secondary",children:s.jsx("p",{children:wr()?Hc:"Last payment failed. Update the card on file to resume your plan â don't start a new subscription."})}),i==="pay-waiting"&&s.jsxs("div",{className:"space-y-3 py-2 text-sm text-text-secondary",children:[r&&s.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-outline-success bg-surface-successSubtle p-3 text-text-success",children:[s.jsx(Xt,{className:"mt-0.5 h-4 w-4 shrink-0"}),s.jsx("span",{children:"Payment received."})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"}),r?"Confirming your subscriptionâ¦":"Waiting for your payment to clearâ¦"]}),s.jsx("p",{children:r?"This takes a few seconds. We'll move you to the next step automatically.":"Complete the payment in the Paystack tab. This page updates automatically within a few seconds of payment."}),s.jsx("button",{type:"button",onClick:()=>void S(),className:"text-text-brand underline hover:no-underline",children:"I've paid â check now"})]}),i==="choose"&&s.jsxs("div",{className:"space-y-2.5",children:[s.jsxs("button",{type:"button",onClick:()=>o("key"),disabled:l,className:"flex min-h-11 w-full items-center justify-between rounded-lg border border-outline-subtle bg-surface px-4 py-3 text-left hover:border-outline-brand disabled:opacity-60",children:[s.jsxs("span",{children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary",children:"Takealot"}),s.jsx("span",{className:"block text-xs text-text-tertiary",children:"Paste your Marketplace API key"})]}),s.jsx(os,{className:"h-4 w-4 shrink-0 text-text-tertiary"})]}),s.jsxs("button",{type:"button",onClick:()=>void $(),disabled:l,className:"flex min-h-11 w-full items-center justify-between rounded-lg border border-outline-subtle bg-surface px-4 py-3 text-left hover:border-outline-brand disabled:opacity-60",children:[s.jsxs("span",{children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary",children:"Amazon"}),s.jsx("span",{className:"block text-xs text-text-tertiary",children:"Authorize on Amazon Seller Central (South Africa)"})]}),l?s.jsx(_e,{className:"h-4 w-4 shrink-0 animate-spin text-text-tertiary"}):s.jsx(Qt,{className:"h-4 w-4 shrink-0 text-text-tertiary"})]})]}),i==="key"&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("figure",{className:"overflow-hidden rounded-lg border border-outline-subtle bg-black",children:[s.jsx("video",{src:"/videos/takealot-api-key.mp4",poster:"/videos/takealot-api-key-poster.jpg",controls:!0,playsInl
756ine:!0,preload:"metadata",className:"aspect-video w-full","aria-label":"How to generate your Takealot Marketplace API key",children:s.jsx("track",{kind:"captions",src:"/videos/takealot-api-key.vtt",srcLang:"en",label:"English"})}),s.jsx("figcaption",{className:"border-t border-outline-subtle bg-surface px-3 py-2 text-xs text-text-secondary",children:"How to generate your key on sellers.takealot.com, then paste it below."})]}),s.jsx("label",{className:"block text-sm font-medium text-text-primary",children:"Takealot Marketplace API key"}),s.jsx("textarea",{value:m,onChange:D=>x(D.target.value),placeholder:"Paste the API key from seller.takealot.com â Integrations â API",rows:3,autoFocus:!0,className:"w-full resize-none rounded-lg border border-outline-subtle bg-surface px-3 py-2 text-sm text-text-primary outline-none focus:border-outline-brand"}),s.jsx("input",{type:"text",value:g,onChange:D=>y(D.target.value),placeholder:"Display name (optional â defaults to your Takealot store name)",className:"w-full rounded-lg border border-outline-subtle bg-surface px-3 py-2 text-sm text-text-primary outline-none focus:border-outline-brand"}),s.jsx("p",{className:"text-xs text-text-tertiary",children:"We validate the key with Takealot and never show it again once saved."})]}),i==="capped"&&(wr()?s.jsx("p",{className:"text-sm text-text-secondary",children:Hc}):s.jsx(Gle,{plan:N,cap:E,upgradeTo:A,busy:l,onUpgrade:P})),i==="done"&&b&&s.jsxs("div",{className:"space-y-3 py-2 text-sm text-text-secondary",children:[s.jsxs("div",{className:"flex items-center gap-2 text-text-success",children:[s.jsx(Xt,{className:"h-5 w-5"}),s.jsxs("span",{className:"font-medium text-text-primary",children:["Connected to ",b.display_name]})]}),s.jsx("p",{children:"Initial sync is queued â your dashboards and reports populate in about 3 minutes."})]})]}),s.jsxs(da,{children:[i==="update-card"&&!wr()&&s.jsxs(W,{onClick:R,disabled:l,children:[l?s.jsx(_e,{className:"mr-2 h-4 w-4 animate-spin"}):s.jsx(Qt,{className:"mr-2 h-4 w-4"}),"Update payment"]}),i==="key"&&s.jsxs(W,{onClick:I,disabled:l,children:[l&&s.jsx(_e,{className:"mr-2 h-4 w-4 animate-spin"}),"Connect store"]}),i==="done"&&s.jsxs(s.Fragment,{children:[s.jsx(W,{variant:"outline",intent:"neutral",onClick:()=>t(!1),children:"Close"}),s.jsxs(W,{onClick:F,children:["Go to my store",s.jsx(os,{className:"ml-2 h-4 w-4"})]})]})]})]})})}function Gle({plan:e,cap:t,upgradeTo:n,busy:r,onUpgrade:a}){var l;const i=((l=Xm[e])==null?void 0:l.displayName)??e;if(!n)return s.jsxs("div",{className:"space-y-2 py-2 text-sm text-text-secondary",children:[s.jsxs("p",{children:["You've connected all ",t," stores on your"," ",s.jsx("span",{className:"font-medium text-text-primary",children:i})," plan â the most we offer self-serve."]}),s.jsxs("p",{children:["Need more?"," ",s.jsx("a",{className:"text-text-brand underline",href:"mailto:[email protected]",children:"[email protected]"})]})]});const o=Xm[n];return s.jsxs("div",{className:"space-y-3 py-1 text-sm text-text-secondary",children:[s.jsxs("p",{children:["Your ",s.jsx("span",{className:"font-medium text-text-primary",children:i})," plan is full at ",t," store",t===1?"":"s",". Upgrade to"," ",s.jsx("span",{className:"font-medium text-text-primary",children:o.displayName})," ","(R",zc(o.priceZar),"/mo) to connect up to ",o.maxSellers," stores, then add this one."]}),s.jsx("p",{className:"text-xs text-text-tertiary",children:"Any unspent monthly credits are moved into top-up credits when you change plan, so you keep what you've paid for."}),s.jsxs(W,{onClick:()=>a(n),disabled:r,children:[r&&s.jsx(_e,{className:"mr-2 h-4 w-4 animate-spin"}),"Upgrade to ",o.displayName]})]})}function Yle(e){switch(e){case"pick-plan":return"Choose a plan to continue.";case"pay-waiting":return"Waiting for Paystack to confirm your payment.";case"update-card":return"Update your card to resume, then connect your store.";case"choose":return"Pick the marketplace you want to connect.";case"key":return"Paste your Takealot Marketplace API key to finish.";case"capped":return"Your plan's store limit has been reached.";default:return""}}function Zle(e){switch(e.code){case"takealot_auth":return"Takealot rejected that key. Double-check you copied the Marketplace API key correctly (it's under Integrations â API).";case"cloudflare_block":return"Takealot temporarily blocked the check. Wait a minute and try again.";case"seller_already_attached":return"This Takealot store is already connected to Gadjet. Contact [email protected] if that's not right.";case"seller_registration_incomplete":case"seller_not_active":return e.message;default:return e.message||"Couldn't connect your store. Try again or c
756ontact [email protected]."}}function Xle(e,t,n){const r={description:n==null?void 0:n.description,duration:n==null?void 0:n.duration,action:n==null?void 0:n.action};switch(e){case"success":return fo.success(t,r);case"error":return fo.error(t,r);case"info":return fo.info(t,r);case"warning":return fo.warning(t,r);case"loading":return fo.loading(t,r)}}const Ae=Object.assign(Xle,{success:(e,t)=>fo.success(e,t),error:(e,t)=>fo.error(e,t),info:(e,t)=>fo.info(e,t),warning:(e,t)=>fo.warning(e,t),loading:(e,t)=>fo.loading(e,t),dismiss:e=>fo.dismiss(e)}),rB=p.createContext(null);function Jle({children:e,onConnected:t}){const[n,r]=p.useState(!1),[a,i]=p.useState(!1),[o,l]=ki(),c=p.useCallback(h=>{i(!!(h!=null&&h.resumeAfterPayment)),r(!0)},[]),u=p.useCallback(h=>{r(h),h||i(!1)},[]);p.useEffect(()=>{if(o.get("paystack")!=="subscribed")return;Ae.success("Payment received â let's connect your store.",{description:"Paste your Takealot API key to finish setup."}),c({resumeAfterPayment:!0});const h=new URLSearchParams(o);h.delete("paystack"),l(h,{replace:!0})},[]);const d=p.useMemo(()=>({openConnectStore:c}),[c]);return s.jsxs(rB.Provider,{value:d,children:[e,s.jsx(qle,{open:n,onOpenChange:u,onConnected:t,resumeAfterPayment:a})]})}function d0(){return p.useContext(rB)??{openConnectStore:t=>{}}}function sB(e){const[t,n]=p.useState(null),r=p.useRef();return r.current||(r.current=Math.random().toString(36).slice(2,10)),p.useEffect(()=>{if(!e){n(null);return}let a=!0,i=null;function o(){K.syncProgress(e).then(d=>{a&&n(d)}).catch(()=>{})}const l=()=>{document.hidden||o()};l();const c=setInterval(l,15e3);document.addEventListener("visibilitychange",l);const u=xn.channel(`sync-runs-${e}-${r.current}`).on("postgres_changes",{event:"*",schema:"public",table:"sync_runs",filter:`seller_slug=eq.${e}`},()=>{i&&clearTimeout(i),i=setTimeout(()=>{l(),i=null},200)}).subscribe();return()=>{a=!1,i&&clearTimeout(i),clearInterval(c),document.removeEventListener("visibilitychange",l),xn.removeChannel(u)}},[e]),t}const Qle={brand:"bg-intent-brand",success:"bg-intent-success",warning:"bg-intent-warning",error:"bg-intent-error",info:"bg-intent-info"},Nf=p.forwardRef(({className:e,value:t,valueLabel:n,intent:r="brand",...a},i)=>{const o=Number.isFinite(t)?Math.max(0,Math.min(100,t)):0;return s.jsxs("div",{ref:i,className:B("flex items-center gap-2",e),...a,children:[s.jsx("div",{role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(o),"aria-valuetext":n,className:"h-1.5 min-w-0 flex-1 overflow-hidden rounded-full bg-surface-sunken",children:s.jsx("div",{className:B("h-full rounded-full transition-[width] duration-500 ease-out",Qle[r]),style:{width:`${o}%`}})}),s.jsx("span",{className:"shrink-0 tabular-nums text-body-sm text-text-secondary",children:n})]})});Nf.displayName="Progress";const aB={info:{container:"bg-surface-infoSubtle border-b border-outline-info text-text-info",iconColor:"text-text-info",button:"bg-intent-info hover:bg-intent-infoHover text-text-inverse"},soft:{container:"bg-surface-warningSubtle border-b border-outline-warning text-text-warning",iconColor:"text-text-warning",button:"bg-intent-warning hover:bg-intent-warningHover text-text-inverse"},strong:{container:"bg-warning-400 border-b border-warning-600 text-warning-950",iconColor:"text-text-warning",button:"bg-warning-900 hover:bg-warning-950 text-text-inverse"},success:{container:"bg-surface-successSubtle border-b border-outline-success text-text-success",iconColor:"text-text-success",button:"bg-intent-success hover:bg-intent-successHover text-text-inverse"},error:{container:"bg-surface-errorSubtle border-b border-outline-error text-text-error",iconColor:"text-text-error",button:"bg-intent-error hover:bg-intent-errorHover text-text-inverse"}};function ece({children:e}){return s.jsx("div",{className:"empty:hidden",children:e})}function Sf({tone:e,icon:t,children:n,action:r,onDismiss:a}){const i=aB[e];return s.jsxs("div",{className:B("px-4 py-2 text-sm flex items-center gap-3",i.container),children:[s.jsx("span",{className:B("shrink-0 inline-flex items-center",i.iconColor),children:t}),s.jsx("span",{className:"flex-1 min-w-0 truncate",children:n}),r,a&&s.jsx(iB,{onClick:a})]})}function iB({onClick:e}){return s.jsx("button",{type:"button",onClick:e,title:"Dismiss","aria-label":"Dismiss",className:"shrink-0 p-1 rounded text-current opacity-70 hover:opacity-100 hover:bg-surface-inverse/10",children:s.jsx(Bn,{className:"w-3.5 h-3.5"})})}function lx({tone:e,onClick:t,disabled:n,children:r}){const a=aB[e];return s.jsx("button",{type:"button",onClick:t,disabled:n,className:B("shrink-0 inline-flex items-center gap-1.5 rounded-md px-3 py-1 text-xs font-medium disabled:opacity-60",a.button),children:r})}const tce=new Set(["token_already_used","token_expired","worker_shutdown","worker_restart","cloudflare","rate_limit","timeout","redeem_unavailable","redeem_failed","redeem_network"]),nce=6e4,rce=3e4;function oB({slug:e,detail:t="full"}){const n=hce(t==="stack"&&!e),r=e??n,a=sB(r),[i,o]=p.useState(!1);return p.useEffect(()=>{if(t!=="stack")return;function l(){o(!1)}return window.addEventListener("gadjet:sync-started",l),()=>window.removeEventListener("gadjet:sync-started",l)},[t]),t==="stack"&&i||!r||!a||sce(a)?null:t==="stack"?s.jsx(ace,{progress:a,onDismiss:()=>o(!0)}):t==="compact"?s.jsx(uce,{progress:a}):s.jsx(cce,{slug:r,progress:a})}function sce(e){return e.status==="completed"&&!!e.finished_at&&Date.now()-new Date(e.finished_at).getTime()>rce}function ace({progress:e,onDismiss:t}){const n=e.status==="errored"?"error":e.status==="completed"?"success":"info",r=e.status==="running"?s.jsx(pa,{className:"w-4 h-4 animate-spin"}):e.status==="completed"?s.jsx(Xt,{className:"w-4 h-4"}):s.jsx(yt,{className:"w-4 h-4"});return s.jsx(Sf,{tone:n,icon:r,onDismiss:t,children:uC(e)})}const ice={worker_shutdown:{title:"Sync interrupted during a system update",detail:"Will resume automatically â no action needed."}
756,worker_restart:{title:"Sync interrupted",detail:"Will resume automatically â no action needed."},cloudflare:{title:"Takealot's security layer is throttling us",detail:"We'll retry in about an hour."},rate_limit:{title:"Takealot rate-limited the request",detail:"We'll retry shortly."},auth:{title:"Takealot rejected the API key",detail:"The key may have been rotated. Reattach it from settings."},timeout:{title:"Sync took longer than expected",detail:"It will resume on the next scheduled run."},token_already_used:{title:"Sync token expired",detail:"Click Retry â we'll mint a fresh token and re-run."},token_expired:{title:"Sync token expired",detail:"Will resume automatically â no action needed."},redeem_unavailable:{title:"Sync couldn't start",detail:"A brief system blip blocked the run. We'll retry shortly."},redeem_failed:{title:"Sync couldn't start",detail:"A brief system blip blocked the run. We'll retry shortly."},redeem_network:{title:"Sync couldn't start",detail:"A brief system blip blocked the run. We'll retry shortly."},operator_drain:{title:"Sync paused by support",detail:"Contact your account manager if this persists."}};function Ay(e){const t=e.error_kind||"",n=ice[t];return n||{title:"Sync didn't finish",detail:e.error_message||void 0}}function uC(e){if(e.status==="errored")return Ay(e).title;if(e.status==="completed")return`Sync complete (${Dh(e.total_seconds||e.elapsed_seconds)})`;const t=e.current_phase||e.phases_planned[0]||"starting",n=oce(e),r=n?`Syncing ${t} (${n})â¦`:`Syncing ${t}â¦`;return e.elapsed_seconds>0?`${r} · ${Dh(e.elapsed_seconds)}`:r}function oce(e){var r;if(e.status!=="running"||!e.current_phase)return null;const t=e.current_phase.split("+"),n=[];for(const a of t){const i=(r=e.phase_counts)==null?void 0:r[a];i!=null&&i>0&&n.push(dC(i))}return n.length>0?n.join("+"):null}function o1({slug:e,label:t="Retry sync",busyLabel:n="Retryingâ¦",force:r=!1}){const[a,i]=p.useState(!1),[o,l]=p.useState(null);async function c(){if(!a){i(!0),l(null);try{const u=await K.syncRetry(e,{force:r});u.deduped?l("A sync is already in flight â watch this banner."):u.queued?l("Sync re-queued. The banner will update as it picks up."):l(u.error||"Couldn't re-queue the sync.")}catch(u){l(`Retry failed: ${u instanceof Error?u.message:String(u)}`)}finally{i(!1)}}}return s.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[s.jsxs("button",{type:"button",onClick:c,disabled:a,className:B("inline-flex items-center gap-1 rounded-md border px-2 py-0.5 text-xs font-medium","border-outline-error bg-surface text-text-error","hover:bg-surface-errorSubtle disabled:opacity-50 disabled:cursor-not-allowed"),children:[s.jsx(pa,{className:B("h-3 w-3",a&&"animate-spin")}),a?n:t]}),o&&s.jsx("span",{className:"text-xs text-text-secondary",children:o})]})}function lce(e,t){if(e.status!=="running")return!1;const n=e.typical_seconds,r=n&&n>0?Math.max(n*8,180):900;return t>r}function cce({slug:e,progress:t}){const[n,r]=dce(t);if(lB(t.status==="running"?1e3:null),n)return null;const a=t.status==="running"?Math.max(t.elapsed_seconds,cB(t.started_at)):t.total_seconds??t.elapsed_seconds,i=t.phases_planned.length||1,o=t.phases_completed.length,l=t.status==="running"&&t.current_phase&&!t.phases_completed.includes(t.current_phase)?.5:0,c=Math.min(100,Math.round((o+l)/i*100)),u=lce(t,a);return s.jsx("div",{className:B("rounded-lg border px-4 py-3 mb-4",t.status==="errored"?"border-outline-error bg-surface-errorSubtle":t.status==="completed"?"border-outline-success bg-surface-successSubtle":"border-outline-info bg-surface-infoSubtle"),children:s.jsxs("div",{className:"flex items-start gap-2.5",children:[t.status==="running"&&s.jsx(pa,{className:"w-4 h-4 text-text-info animate-spin shrink-0 mt-0.5"}),t.status==="completed"&&s.jsx(Xt,{className:"w-4 h-4 text-text-success shrink-0 mt-0.5"}),t.status==="errored"&&s.jsx(yt,{className:"w-4 h-4 text-intent-error shrink-0 mt-0.5"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-sm font-medium text-text-primary",children:[t.status==="running"&&s.jsxs(s.Fragment,{children:["Syncing ",s.jsx("span",{className:"lowercase",children:t.current_phase||t.phases_planned[0]}),qO(t)&&s.jsxs("span",{className:"font-normal text-text-info",children:[" ","(",qO(t),")"]}),s.jsxs("span",{className:"text-text-secondary font-normal",children:[" · ",Dh(a)," elapsed"]}),t.typical_seconds&&s.jsxs("span",{className:"text-text-secondary font-normal",children:[" · typically ~",Dh(t.typical_seconds)]})]}),t.status==="completed"&&s.jsxs(s.Fragment,{children:["Sync complete",s.jsxs("span",{className:"text-text-secondary font-normal",children:[" · ",Dh(a)]})]}),t.status==="errored"&&s.jsx(s.Fragment,{children:Ay(t).title})]}),t.status==="errored"&&Ay(t).detail&&s.jsx("div",{className:"mt-0.5 text-xs text-text-error",children:Ay(t).detail}),t.status==="errored"&&tce.has(t.error_kind||"")&&s.jsx(o1,{slug:e}),t.status==="errored"&&t.error_kind==="auth"&&s.jsx(o1,{slug:e,label:"Re-attached the key? Re-sync",busyLabel:"Re-syncingâ¦"}),u&&s.jsxs("div",{className:"mt-1",children:[s.jsx("div",{className:"text-xs text-text-secondary",children:"Taking much longer than usual â this run may be stuck."}),s.jsx(o1,{slug:e,label:"Stop and retry",force:!0})]}),t.status==="running"&&t.phases_planned.length>1&&s.jsx(Nf,{className:"mt-2",value:c,valueLabel:`${c}%`,intent:"info"}),t.phases_planned.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-x-2 gap-y-1 text-body-xs",children:t.phases_planned.map(d=>{var x;const h=t.phases_completed.includes(d),f=!h&&(t.current_phase||"").includes(d),m=(x=t.phase_counts)==null?void 0:x[d];return s.jsxs("span",{className:B("inline-flex items-center gap-1 px-1.5 py-0.5 rounded",h?"text-text-success bg-surface-successSubtle":f?"text-text-info bg-surface-infoSubtle font-medium":"text-text-tertiary"),children:[h?"â":f?"âº":"â"," ",s.jsx("span",{children:d}),m!=null&&m>0&&s.jsxs("span",{className:"tabular-nums",children:[" ","(",dC(m),f?"â¦":"",")"]})]},d)})})]}),s.jsx(iB,{onClick:r})]})})}function uce({progress:e}){lB(e.status==="running"?1e3:null);const t=e.status==="running"?Math.max(e.elapsed_seconds,cB(e.started_at)):e.total_seconds??e.elapsed_seconds;return s.jsxs("div",{className:B("inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md text-xs",e.status==="errored"?"bg-surface-errorSubtle text-text-error border border-outline-error":e.status==="completed"?"bg-surface-successSubtle text-text-success border border-outline-success":"bg-surface-infoSubtle text-text-info border border-outline-info"),children:[e.status==="running"&&s.jsx(pa,{className:"w-3 h-3 animate-spin"}),e.status==="completed"&&s.jsx(Xt,{className:"w-3 h-3"}),e.status==="errored"&&s.jsx(yt,{className:"w-3 h-3"}),s.jsx("span",{children:uC(e)}),e.status==="running"&&s.jsxs("span",{className:"text-text-secondary",children:["· ",Dh(t)]})]})}function dce(e){const[t,n]=p.useState(null),r=`${e.id}:${e.status}`;return[t===r,()=>n(r)]}function hce(e){const[t,n]=p.useState(null);return p.useEffect(()=>{if(!e)return;let r=!0;function a(){document.hidden||K.activeSyncRun().then(o=>{r&&o&&n(o.slug)}).catch(()=>{})}a();const i=setInterval(a,nce);return document.addEventListener("visibilitychange",a),()=>{r=!1,clearInterval(i),document.removeEventListener("visibilitychange",a)}},[e]),p.useEffect(()=>{if(!e)return;function r(a){const i=a.detail;i!=null&&i.slug&&n(i.slug)}return window.addEventListener("gadjet:sync-started",r),()=>window.removeEventListener("gadjet:sync-started",r)},[e]),e?t:null}function lB(e){const[,t]=p.useState(0);return p.useEffect(()=>{if(e==null)return;const n=setInterval(()=>t(r=>r+1),e);return()=>clearInterval(n)},[e]),Date.now()}function cB(e,t){return Math.max(0,Math.floor((Date.now()-new Date(e).getTime())/1e3))}function dC(e){return e<1e3?String(e):e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.round(e/1e3)}k`}function qO(e){var r;if(e.status!=="running"||!e.current_phase)return null;const t=e.current_phase.split("+"),n=[];for(const a of t){const i=(r=e.phase_counts)==null?void 0:r[a];i!=null&&i>0&&n.push(`${dC(i)} ${a}`)}return n.length>0?n.join(", "):null}function Dh(e){if(e==null)return"";if(e<60)return`${e}s`;const t=Math.floor(e/60),n=e%60;return t<10?n>0?`${t}m${n}s`:`${t}m`:`${t}m`}const fce=[{id:"seller.sales",to:e=>`/sellers/${e}/sales`,label:"Sales",icon:s.jsx(fc,{className:"w-3.5 h-3.5"}),badgeKey:"sales"},{id:"seller.automations",to:e=>`/sellers/${e}/automations`,label:"Automations",icon:s.jsx(ix,{className:"w-3.5 h-3.5"})},{id:"seller.inventory",to:e=>`/sellers/${e}/inventory`,label:"Inventory",icon:s.jsx(zv,{className:"w-3.5 h-3.5"}),badgeKey:"inventory"},{id:"seller.returns",to:e=>`/sellers/${e}/returns`,label:"Returns",icon:s.jsx(vd,{className:"w-3.5 h-3.5"}),badgeKey:"returns"},{id:"seller.shipments",to:e=>`/sellers/${e}/shipments`,label:"Shipments",icon:s.jsx(qi,{className:"w-3.5 h-3.5"})},{id:"seller.transactions",to:e=>`/sellers/${e}/transactions`,label:"Transactions",icon:s.jsx(yf,{className:"w-3.5 h-3.5"}),tier:"more"},{id:"seller.tasks",to:e=>`/sellers/${e}/tasks`,label:"Tasks",icon:s.jsx(Uh,{className:"w-3.5 h-3.5"}),tier:"more"},{id:"seller.settings",to:e=>`/settings/stores/${e}`,label:"Settings",icon:s.jsx(dp,{className:"w-3.5 h-3.5"}),tier:"more"}
756],mce=[{id:"overview",to:e=>`/overview/${e}`,label:"Overview",icon:s.jsx(rx,{className:"w-3.5 h-3.5"}),end:!0},{id:"seller.automations",to:e=>`/sellers/${e}/automations`,label:"Automations",icon:s.jsx(ix,{className:"w-3.5 h-3.5"})},{id:"seller.sales",to:e=>`/sellers/${e}/sales`,label:"Sales",icon:s.jsx(fc,{className:"w-3.5 h-3.5"}),badgeKey:"sales"},{id:"seller.inventory",to:e=>`/sellers/${e}/inventory`,label:"Inventory",icon:s.jsx(zv,{className:"w-3.5 h-3.5"}),badgeKey:"inventory"},{id:"seller.shipments",to:e=>`/sellers/${e}/shipments`,label:"Shipments",icon:s.jsx(qi,{className:"w-3.5 h-3.5"})},{id:"seller.returns",to:e=>`/sellers/${e}/returns`,label:"Returns",icon:s.jsx(vd,{className:"w-3.5 h-3.5"}),badgeKey:"returns"},{id:"seller.transactions",to:e=>`/sellers/${e}/transactions`,label:"Transactions",icon:s.jsx(yf,{className:"w-3.5 h-3.5"})},{id:"seller.settings",to:e=>`/settings/stores/${e}`,label:"Store settings",icon:s.jsx(dp,{className:"w-3.5 h-3.5"})}];function pce(e){const[t,n]=p.useState(0);return p.useEffect(()=>{if(e!=="super_admin"&&e!=="am"){n(0);return}let r=!0;function a(){vr.badge().then(l=>{r&&n(l.count)}).catch(()=>{})}function i(){document.hidden||a()}i();const o=setInterval(i,3e4);return document.addEventListener("visibilitychange",i),()=>{r=!1,clearInterval(o),document.removeEventListener("visibilitychange",i)}},[e]),t}function xce({sellers:e,sellerBadges:t={},activeSlug:n,drawerOpen:r=!1,onCloseDrawer:a,collapsed:i=!1}){Rt();const o=Lt(),[l,c]=p.useState({}),[u,d]=p.useState(""),[h,f]=p.useState(null),[m,x]=p.useState(null),g=pce(o.kind==="ready"?o.me.role:null),[y,b]=p.useState(null),v=(y==null?void 0:y.slug)??null,w=sB(v),_=w?uC(w):"Syncing nowâ¦",k=o.kind==="ready"?o.me.role:null,j=k==="seller_user",N=j||k==="content_creator",E=o.kind==="ready"?o.me.nav_visibility??null:null,A=ne=>Kc(E,ne),C=p.useMemo(()=>fce.filter(ne=>Kc(E,ne.id)),[E]),T=p.useMemo(()=>mce.filter(ne=>Kc(E,ne.id)),[E]),S=o.kind==="ready"&&!!o.me.is_demo_mode,O=o.kind==="ready"&&!!o.me.is_demo_showcase,R=o.kind==="ready"&&oC(o.me),I=N&&e!==null&&e.length===1,$=N&&e!==null&&e.length>1,P=I?e[0]:null,F=jf();function Z(ne){a==null||a(),F(ne)}const{openConnectStore:D}=d0();function H(){a==null||a(),j?D():F("I'd like to add a new seller account.")}p.useEffect(()=>{if(!(r||!i))return;let X=!1;const he=async()=>{try{const{authedFetch:$e}=await Yl(async()=>{const{authedFetch:Me}=await Promise.resolve().then(()=>qoe);return{authedFetch:Me}},void 0),J=await $e("/api/sync-status");if(!J.ok)return;const Ne=await J.json();if(X)return;const ve=Ne==null?void 0:Ne.current_sync;ve!=null&&ve.slug&&typeof(ve==null?void 0:ve.started_at)=="number"?b({slug:ve.slug,started_at:ve.started_at,kind:typeof ve.kind=="string"?ve.kind:"all"}):b(null)}catch{}},ae=()=>{document.hidden||he()};ae();const je=window.setInterval(ae,5e3);return document.addEventListener("visibilitychange",ae),()=>{X=!0,window.clearInterval(je),document.removeEventListener("visibilitychange",ae)}},[r,i]),p.useEffect(()=>{let ne=!1;return(async()=>{try{const{api:X}=await Yl(async()=>{const{api:ae}=await Promise.resolve().then(()=>Xoe);return{api:ae}},void 0),he=await X.account();if(ne)return;(he==null?void 0:he.kind)==="customer"&&(he.business_name&&f(he.business_name),x(he.logo_url??null))}catch{}})(),()=>{ne=!0}},[]),p.useEffect(()=>{n&&c(ne=>({...ne,[n]:!0}))},[n]);const Y=p.useMemo(()=>{if(!e)return null;const ne=u.toLowerCase().trim();return ne?e.filter(X=>X.display_name.toLowerCase().includes(ne)||X.slug.toLowerCase().includes(ne)):e},[e,u]),M=o.kind==="ready"?o.me.display_name:null,[z]=p.useState("all"),[G,te]=p.useState({}),re=p.useMemo(()=>Y?N||z==="all"?Y:z==="me"?Y.filter(ne=>ne.account_owner===M):Y.filter(ne=>ne.account_owner===z):null,[Y,z,M,N]),L=p.useMemo(()=>{if(N||z!=="all"||!re)return null;const ne=new Map;for(const he of re){const ae=he.account_owner||"__unassigned",je=he.account_owner_label||he.account_owner||"Unassigned";ne.has(ae)||ne.set(ae,{label:je,sellers:[]}),ne.get(ae).sellers.push(he)}const X=Array.from(ne.keys()).sort((he,ae)=>he===M?-1:ae===M||he==="__unassigned"?1:ae==="__unassigned"?-1:ne.get(he).label.localeCompare(ne.get(ae).label));return{groups:ne,keys:X}},[re,z,M,N]),q=Ule(),me=i&&!q,ee=k==="super_admin"||j;return s.jsx("aside",{"aria-hidden":r?!1:void 0,className:B("shrink-0 border-r border-outline-subtle flex flex-col bg-surface","fixed inset-y-0 left-0 z-drawer-content w-[280px] pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)] transition-transform duration-200 ease-out",r?"translate-x-0":"-translate-x-full","md:static md:translate-x-0 md:transition-none md:z-auto",i?"md:w-[56px]":"md:w-[260px]"),children:me?s.jsx(vce,{workspaceName:h,workspaceLogo:m,activeSync:y,sellers:e,canAddSeller:ee,isSellerUser:j,role:k,navVis:E,onAddSeller:H,onLeaveFeedback:()=>Z("I'd like to leave some feedback for the Gadjet team."),onSupport:()=>Z("I need some help â please pass this on to the Gadjet team if you can't resolve it.")}):s.jsxs(s.Fragment,{children:[s.jsxs(st,{to:"/settings",onClick:a,className:"flex items-center gap-3 px-4 py-4 hover:bg-surface-subtle border-b border-outline-subtle text-left no-underline",children:[s.jsx(uB,{logo:m,name:h}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary truncate",children:h||"Gadjet HQ"}),s.jsx("div",{className:"text-xs text-text-secondary",children:k==="super_admin"?"Admin":"Workspace"})]}),s.jsx(J6,{className:"w-4 h-4 text-text-tertiary"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto scrollbar-on-hover py-3 px-2",children:[!I&&A("overview")&&s.jsx(Mo,{to:"/overview",end:!0,icon:s.jsx(Kh,{className:"w-4 h-4"}),onClick:a,children:"Overview"}),A("agent")&&s.jsx(Mo,{to:"/agent",icon:s.jsx(Ht,{className:"w-4 h-4"}),onClick:a,children:"Agent"}),A("crm")&&s.jsx(Mo,{to:"/crm",icon:s.jsx(xf,{className:"w-4 h-4"}),onClick:a,children:"CRM"}),!S&&A("calendar")&&s.jsx(Mo,{to:"/calendar",icon:s.jsx(yd,{className:"w-4 h-4"}),onClick:a,children:"Calendar"}),A("tasks")&&s.jsx(Mo,{to:"/tasks",icon:s.jsx(Uh,{className:"w-4 h-4"}),onClick:a,badge:g,children:"Tasks"}),A("reports")&&s.jsx(Mo,{to:"/dashboards",icon:s.jsx(rx,{className:"w-4 h-4"}),onClick:a,children:"Reports"}),A("market-explorer")&&s.jsx(Mo,{to:"/market-explorer",icon:s.jsx(y2,{className:"w-4 h-4"}),onClick:a,children:"Market Explorer"}),(!S||O)&&A("sops")&&s.jsx(Mo,{to:"/sops",icon:s.jsx(Uh,{className:"w-4 h-4"}),onClick:a,children:"SOPs"}),!S&&A("ads")&&s.jsx(Mo,{to:"/ads",icon:s.jsx(a6,{className:"w-4 h-4"}),onClick:a,children:"Ads"}),A("content")&&s.jsx(Mo,{to:"/content",icon:s.jsx(M2,{className:"w-4 h-4"}),onClick:a,children:"Content"}),I&&P&&s.jsx(kce,{seller:P,views:T,badges:t[P.slug],isSyncing:v===P.slug,syncingTitle:_,onClose:a}),!I&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mt-5 px-2 mb-2 flex items-center gap-1.5",children:[e&&e.length>5?s.jsxs("div",{className:"relative flex-1",children:[s.jsx(Fa,{className:b2}),s.jsx("input",{value:u,onChange:ne=>d(ne.target.value),placeholder:"Find sellerâ¦",className:`w-full rounded-md border border-outline-subtle bg-surface-subtle py-1.5 pr-2 text-xs focus:border-outline-brand focus:bg-surface focus:outline-none focus-visible:shadow-focus ${v2}`})]}):s.jsx("div",{className:"flex-1"}),ee&&s.jsx("button",{onClick:H,className:"shrink-0 p-1.5 rounded-md border border-outline-subtle text-text-tertiary hover:text-text-secondary hover:bg-surface-subtle",title:$?"Connect another store":"Add a new seller","aria-label":"Add a new seller",children:s.jsx(In,{className:"w-3.5 h-3.5"})})]}),!e&&s.jsx("div",{className:"px-3 py-2 text-xs text-text-tertiary",children:"Loadingâ¦"}),(Y==null?void 0:Y.length)===0&&s.jsx("div",{className:"px-3 py-2 text-xs text-text-tertiary",children:"No matches."})]}),!I&&(L?L.keys.map(ne=>{const X=L.groups.get(ne),he=ne===M,ae=G[ne]??he;return s.jsxs("div",{className:"mb-1",children:[s.jsxs("button",{type:"button",onClick:()=>te(je=>({...je,[ne]:!ae})),className:"w-full flex items-center gap-1.5 px-2 py-1 rounded-md text-body-xs font-semibold uppercase tracking-wider text-text-tertiary hover:text-text-secondary hover:bg-surface-subtle",children:[ae?s.jsx(Pn,{className:"w-3 h-3 shrink-0"}):s.jsx(fr,{className:"w-3 h-3 shrink-0"}),s.jsx("span",{className:"flex-1 text-left truncate",children:X.label}),s.jsx("span",{className:"normal-case font-normal tabular-nums text-text-tertiary",children:X.sellers.length})]}),ae&&X.sellers.map(je=>GO(je,l,c,n,t,v,_,C,a))]},`grp-${ne}`)}):re==null?void 0:re.map(ne=>GO(ne,l,c,n,t,v,_,C,a)))]}),y&&s.jsx(wce,{sync:y,sellers:e,onClose:a}),s.jsxs("div",{className:"border-t border-outline-subtle px-2 py-2",children:[s.jsx(l1,{icon:s.jsx(U2,{className:"w-4 h-4"}),to:"/academy",onClick:a,dot:R,children:"Academy"}),s.jsx(l1,{icon:s.jsx(cF,{className:"w-4 h-4"}),onClick:()=>Z("I need some help â please pass this on to the Gadjet team if you can't resolve it."),children:"Support"}),A("earn")&&s.jsx(l1,{icon:s.jsx(B2,{className:"w-4 h-4"}),to:"/earn",onClick:a,children:"Earn"}),s.jsx(yce,{})]})]})})}function GO(e,t,n,r,a,i,o,l,c){var g,y,b;const u=t[e.slug]??r===e.slug,d=r===e.slug,h=i===e.slug,f=((g=e.health)==null?void 0:g.color)??(e.status==="active"?"emerald":"slate"),m=h?"text-brand-500 animate-pulse":f==="emerald"?"text-intent-success":f==="amber"?"text-intent-warning":f==="red"?"text-intent-error":"text-text-tertiary",x=h?o:(y=e.health)!=null&&y.detail?`${e.health.label} · ${e.health.detail}`:((b=e.health)==null?void 0:b.label)??e.status;return s.jsxs("div",{className:"mb-0.5",children:[s.jsxs("div",{className:B("group w-full flex items-center gap-0.5 pr-1 rounded-md hover:bg-surface-sunken",d?"text-text-primary":"text-text-body"),children:[s.jsx("button",{onClick:()=>n(v=>({...v,[e.slug]:!u})),"aria-label":u?`Collapse ${e.display_name}`:`Expand ${e.display_name}`,className:"p-1 rounded text-text-tertiary hover:text-text-body shrink-0",children:u?s.jsx(Pn,{className:"w-3.5 h-3.5"}):s.jsx(fr,{className:"w-3.5 h-3.5"})}),s.jsxs(si,{to:`/overview/${e.slug}`,end:!0,onClick:()=>{n(v=>({...v,[e.slug]:!0})),c==null||c()},className:"flex-1 min-w-0 flex items-center gap-1.5 px-1 py-2 md:py-1 text-body-sm text-left rounded-md",children:[s.jsx("span",{className:"shrink-0 flex items-center",title:x,children:s.jsx(R2,{className:B("w-3.5 h-3.5",m)})}),s.jsx(kf,{marketplace:e.marketplace}),s.jsx("span",{title:e.display_name,className:B("flex-1 truncate",d&&"font-semibold"),children:e.display_name}),s.jsx(jce,{badges:a[e.slug]})]}),s.jsx(si,{to:`/settings/stores/${e.slug}`,onClick:c,title:"Seller settings","aria-label":`${e.display_name}
756 settings`,className:"opacity-0 group-hover:opacity-100 focus:opacity-100 p-1 rounded text-text-tertiary hover:text-text-body hover:bg-surface-sunken shrink-0",children:s.jsx(tF,{className:"w-3.5 h-3.5"})})]}),u&&s.jsx(gce,{views:l,slug:e.slug,badges:a[e.slug],onCloseDrawer:c})]},e.slug)}function gce({views:e,slug:t,badges:n,onCloseDrawer:r}){const[a,i]=p.useState(!1),o=e.filter(u=>u.tier!=="more"),l=e.filter(u=>u.tier==="more"),c=u=>{const d=u.badgeKey?n==null?void 0:n[u.badgeKey]:void 0;return s.jsxs(si,{to:u.to(t),end:u.end,onClick:r,className:({isActive:h})=>B("flex items-center gap-2 px-2 py-2 md:py-1 rounded-md text-body-sm",h?"bg-surface-sunken text-text-primary font-medium":"text-text-secondary hover:bg-surface-subtle"),children:[u.icon,s.jsx("span",{className:"flex-1",children:u.label}),d&&s.jsx(dB,{badge:d})]},u.id)};return s.jsxs("div",{className:"ml-3.5 pl-3 border-l border-outline-faint my-0.5",children:[o.map(c),a&&l.map(c),l.length>0&&s.jsxs("button",{type:"button",onClick:()=>i(u=>!u),"aria-expanded":a,className:"w-full flex items-center gap-2 px-2 py-2 md:py-1 rounded-md text-body-sm text-text-tertiary hover:text-text-secondary hover:bg-surface-subtle",children:[a?s.jsx(Pn,{className:"w-3.5 h-3.5"}):s.jsx(fr,{className:"w-3.5 h-3.5"}),s.jsx("span",{className:"flex-1 text-left",children:a?"Show less":`More (${l.length})`})]})]})}function yce(){var h;const e=xu(),t=Lt(),n=Lle(),r=t.kind==="ready"?t.me.role:null,a=$le(r),i=!!n,o=a||i,l=t.kind==="ready"?t.me.avatar_url??null:null,c=e.kind==="authenticated"?e.user.email??"":"",u=tB(c),d=e.kind==="authenticated"?((h=e.user.user_metadata)==null?void 0:h.full_name)||c.split("@")[0]:"";return s.jsxs("div",{className:"mt-2 mx-2 border-t border-outline-faint pt-3 pb-1",children:[o&&s.jsx("div",{className:"mb-2",children:i?s.jsxs("button",{onClick:()=>{Ble().catch(()=>{})},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 rounded text-body-xs font-medium text-text-brand bg-surface-brandSubtle hover:bg-surface-brandSubtle/70",title:"Return to your normal view",children:[s.jsx(Zre,{className:"w-3 h-3"}),"Exit demo view"]}):s.jsxs("button",{onClick:()=>{Fle().catch(()=>{})},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 rounded text-body-xs font-medium text-text-secondary hover:text-text-primary hover:bg-surface-sunken",title:"See the product as a seller would",children:[s.jsx(bd,{className:"w-3 h-3"}),"Enter demo view"]})}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs(si,{to:"/settings/profile",className:"flex-1 min-w-0 flex items-center gap-2 px-1 py-1 rounded hover:bg-surface-sunken",children:[s.jsx(lC,{size:28,src:l,initials:u,tone:"self",alt:""}),s.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[s.jsx("div",{className:"text-xs font-semibold text-text-primary truncate",children:d||"â"}),s.jsx("div",{className:"text-body-xs text-text-secondary truncate",children:c||"(not signed in)"})]})]}),s.jsx("button",{onClick:()=>wf(),title:"Sign out",className:"p-1 text-text-tertiary hover:text-text-body rounded hover:bg-surface-sunken",children:s.jsx(W2,{className:"w-3.5 h-3.5"})})]})]})}function bce({children:e,className:t=""}){return s.jsx("div",{className:B("px-2 mb-1 text-body-xs font-semibold uppercase tracking-wider text-text-tertiary",t),children:e})}function uB({logo:e,name:t}){return e?s.jsx("img",{src:e,alt:"",className:"w-8 h-8 rounded-lg object-cover shrink-0"}):!t||t==="Gadjet HQ"?s.jsx(w2,{variant:"mark",height:32}):s.jsx("div",{className:"w-8 h-8 rounded-lg bg-intent-brand text-text-inverse flex items-center justify-center font-semibold text-sm shrink-0",children:t.slice(0,1).toUpperCase()})}function vce({workspaceName:e,workspaceLogo:t,activeSync:n,sellers:r,canAddSeller:a,isSellerUser:i,role:o,navVis:l,onAddSeller:c,onLeaveFeedback:u,onSupport:d}){const h=xu(),f=Lt(),m=f.kind==="ready"?f.me.avatar_url??null:null,x=f.kind==="ready"&&!!f.me.is_demo_mode,g=f.kind==="ready"&&oC(f.me),y=k=>Kc(l,k),b=h.kind==="authenticated"?h.user.email??"":"",v=tB(b),w=n?r==null?void 0:r.find(k=>k.slug===n.slug):null,_=n?`Syncing ${(w==null?void 0:w.display_name)||n.slug} · ${n.kind==="all"?"Full sync":`Refreshing ${n.kind}`}`:null;return s.jsxs(s.Fragment,{children:[s.jsx(st,{to:"/settings",title:e||"Gadjet HQ",className:"flex items-center justify-center py-3 border-b border-outline-subtle hover:bg-surface-subtle",children:s.jsx(uB,{logo:t,name:e})}),s.jsxs("div",{className:"flex-1 overflow-y-auto scrollbar-on-hover py-3 flex flex-col items-center gap-1",children:[y("overview")&&s.jsx(Ha,{to:"/overview",label:"Overview",icon:s.jsx(Kh,{className:"w-4 h-4"})}),y("agent")&&s.jsx(Ha,{to:"/agent",label:"Agent",icon:s.jsx(Ht,{className:"w-4 h-4"})}),y("crm")&&s.jsx(Ha,{to:"/crm",label:"CRM",icon:s.jsx(xf,{className:"w-4 h-4"})}),!x&&y("calendar")&&s.jsx(Ha,{to:"/calendar",label:"Calendar",icon:s.jsx(yd,{className:"w-4 h-4"})}),y("earn")&&s.jsx(Ha,{to:"/earn",label:"Earn",icon:s.jsx(B2,{className:"w-4 h-4"})}),y("content")&&s.jsx(Ha,{to:"/content",label:"Content",icon:s.jsx(M2,{className:"w-4 h-4"})}),o==="super_admin"&&s.jsx(Ha,{to:"/settings/admin/skills",label:"Skills",icon:s.jsx(Qv,{className:"w-4 h-4"})}),o==="super_admin"&&s.jsx(Ha,{to:"/cron-jobs",label:"Scheduled tasks",icon:s.jsx(pu,{className:"w-4 h-4"})}),o==="super_admin"&&s.jsx(Ha,{to:"/settings/admin/dashboard",label:"Dashboard",icon:s.jsx(Kh,{className:"w-4 h-4"})}),o==="super_admin"&&s.jsx(Ha,{to:"/settings/admin/users",label:"Users",icon:s.jsx(Xp,{className:"w-4 h-4"})}),o==="super_admin"&&s.jsx(Ha,{to:"/settings/admin/ai-spend",label:"AI Spend",
756icon:s.jsx(eF,{className:"w-4 h-4"})}),o==="super_admin"&&s.jsx(Ha,{to:"/settings/admin/lockout",label:"Lockout",icon:s.jsx(Bl,{className:"w-4 h-4"})}),y("reports")&&s.jsx(Ha,{to:"/dashboards",label:"Reports",icon:s.jsx(rx,{className:"w-4 h-4"})}),y("market-explorer")&&s.jsx(Ha,{to:"/market-explorer",label:"Market Explorer",icon:s.jsx(y2,{className:"w-4 h-4"})}),a&&s.jsx("button",{onClick:c,title:"Add a new seller (opens the agent)","aria-label":"Add a new seller",className:"mt-2 w-9 h-9 flex items-center justify-center rounded-md text-text-secondary hover:text-text-primary hover:bg-surface-sunken",children:s.jsx(In,{className:"w-4 h-4"})})]}),n&&s.jsx(st,{to:`/sellers/${n.slug}`,title:_??"Sync in progress",className:"mx-auto mb-1 w-9 h-9 flex items-center justify-center rounded-md bg-surface-brandSubtle text-text-brand",children:s.jsx(_e,{className:"w-4 h-4 animate-spin"})}),s.jsxs("div",{className:"border-t border-outline-subtle py-2 flex flex-col items-center gap-1",children:[s.jsxs(st,{to:"/academy",title:g?"Academy â new videos":"Academy",className:"relative w-9 h-9 flex items-center justify-center rounded-md text-text-secondary hover:text-text-primary hover:bg-surface-sunken",children:[s.jsx(U2,{className:"w-4 h-4"}),g&&s.jsx("span",{"aria-hidden":"true",className:"absolute right-1.5 top-1.5 h-2 w-2 rounded-full bg-intent-brand ring-2 ring-surface"})]}),s.jsx("button",{onClick:d,title:"Support",className:"w-9 h-9 flex items-center justify-center rounded-md text-text-secondary hover:text-text-primary hover:bg-surface-sunken",children:s.jsx(cF,{className:"w-4 h-4"})}),s.jsx(si,{to:"/settings/profile",title:b||"Profile",className:"mt-1 rounded-full focus-visible:outline-none focus-visible:shadow-focus",children:s.jsx(lC,{size:32,src:m,initials:v,tone:"self",alt:""})}),s.jsx("button",{onClick:()=>wf(),title:"Sign out",className:"w-9 h-9 flex items-center justify-center rounded-md text-text-tertiary hover:text-text-primary hover:bg-surface-sunken",children:s.jsx(W2,{className:"w-3.5 h-3.5"})})]})]})}function Ha({to:e,label:t,icon:n}){return s.jsx(si,{to:e,title:t,"aria-label":t,className:({isActive:r})=>B("w-9 h-9 flex items-center justify-center rounded-md",r?"bg-surface-sunken text-text-primary":"text-text-secondary hover:text-text-primary hover:bg-surface-sunken"),children:n})}function wce({sync:e,sellers:t,onClose:n}){const[,r]=p.useState(0);p.useEffect(()=>{const c=window.setInterval(()=>r(u=>u+1),1e3);return()=>window.clearInterval(c)},[]);const a=t==null?void 0:t.find(c=>c.slug===e.slug),i=(a==null?void 0:a.display_name)||e.slug,o=Date.now()-e.started_at*1e3,l=e.kind==="all"?"Full sync":`Refreshing ${e.kind}`;return s.jsxs(si,{to:`/sellers/${e.slug}`,onClick:n,title:"Open seller while sync runs",className:"mx-2 mb-2 flex items-start gap-2 px-2 py-2 rounded-md bg-surface-brandSubtle/80 border border-outline-brand hover:bg-surface-brandSubtle text-left no-underline",children:[s.jsx(_e,{className:"w-3.5 h-3.5 text-brand-500 animate-spin mt-0.5 shrink-0"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-body-md font-medium text-text-primary truncate",children:["Syncing ",i]}),s.jsxs("div",{className:"text-body-xs text-text-brand/80 truncate",children:[l," · ",_ce(o)]})]})]})}function _ce(e){if(e<0)return"just now";const t=Math.floor(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60);return n<60?`${n}m ${t%60}s`:`${Math.floor(n/60)}h ${n%60}m`}function kce({seller:e,views:t,badges:n,isSyncing:r,syncingTitle:a,onClose:i}){var u,d,h;const o=((u=e.health)==null?void 0:u.color)??(e.status==="active"?"emerald":"slate"),l=r?"bg-brand-500 animate-pulse":o==="emerald"?"bg-intent-success":o==="amber"?"bg-intent-warning":
756o==="red"?"bg-intent-error":"bg-outline",c=r?a??"Syncing nowâ¦":(d=e.health)!=null&&d.detail?`${e.health.label} · ${e.health.detail}`:((h=e.health)==null?void 0:h.label)??e.status;return s.jsxs("div",{className:"mt-5",children:[s.jsxs("div",{className:"px-2 mb-1 flex items-center gap-1.5",children:[s.jsx(bce,{className:"mb-0 flex-1 truncate",children:e.display_name}),s.jsx("span",{className:B("w-1.5 h-1.5 rounded-full shrink-0",l),title:c})]}),s.jsx("div",{className:"px-0.5",children:t.map(f=>{const m=f.badgeKey?n==null?void 0:n[f.badgeKey]:void 0;return s.jsxs(si,{to:f.to(e.slug),end:f.end,onClick:i,className:({isActive:x})=>B("flex items-center gap-2 px-2 py-2 md:py-1.5 rounded-md text-sm",x?"bg-surface-sunken text-text-primary font-medium":"text-text-secondary hover:bg-surface-subtle"),children:[f.icon,s.jsx("span",{className:"flex-1",children:f.label}),m&&s.jsx(dB,{badge:m})]},f.id)})})]})}function jce({badges:e}){if(!e)return null;const t=[];let n=!1;return e.sales&&(t.push(`Sales: ${e.sales.tooltip}`),e.sales.severity==="red"&&(n=!0)),e.returns&&(t.push(`Returns: ${e.returns.tooltip}`),e.returns.severity==="red"&&(n=!0)),e.inventory&&(t.push(`Inventory: ${e.inventory.tooltip}`),e.inventory.severity==="red"&&(n=!0)),t.length===0?null:s.jsx("span",{title:t.join(` 757`),className:B("shrink-0 text-body-xs font-semibold leading-none tabular-nums",n?"text-text-error":"text-text-warning"),children:t.length})}function dB({badge:e}){const t=e.severity==="red"?"text-text-error":"text-text-warning";let n="";switch(e.kind){case"drop":n=`${e.delta_pct}%`;break;case"spike":n=`+${e.delta_pct}%`;break;case"new":n=`+${e.count}`;break;case"stockout-risk":n=`${e.count} OOS`;break}return s.jsx("span",{title:e.tooltip,className:B("shrink-0 text-body-xs font-semibold leading-none tabular-nums",t),children:n})}function Mo({to:e,icon:t,children:n,end:r,disabled:a,onClick:i,badge:o}){return a?s.jsxs("button",{type:"button",disabled:!0,"aria-disabled":"true",className:"w-full text-left flex items-center gap-2 px-2 py-1.5 rounded-md text-sm text-text-tertiary cursor-not-allowed select-none disabled:bg-transparent",children:[t,s.jsx("span",{children:n}),s.jsx("span",{className:"ml-auto text-body-xs uppercase tracking-wider text-text-tertiary",children:"soon"})]}):s.jsxs(si,{to:e,end:r,onClick:i,className:({isActive:l})=>B("flex items-center gap-2 px-2 py-2.5 md:py-1.5 min-h-11 md:min-h-0 rounded-md text-body-lg md:text-sm",l?"bg-surface-sunken text-text-primary font-medium":"text-text-secondary hover:bg-surface-subtle"),children:[t,s.jsx("span",{className:"flex-1",children:n}),typeof o=="number"&&o>0&&s.jsx("span",{className:"ml-auto inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full bg-intent-info text-text-inverse text-body-xs font-semibold",children:o>99?"99+":o})]})}function l1({icon:e,children:t,onClick:n,disabled:r,to:a,dot:i}){return r?s.jsxs("button",{type:"button",disabled:!0,"aria-disabled":"true",className:"w-full text-left flex items-center gap-2 px-2 py-1.5 rounded-md text-sm text-text-tertiary cursor-not-allowed select-none",children:[e,s.jsx("span",{children:t}),s.jsx("span",{className:"ml-auto text-body-xs uppercase tracking-wider text-text-tertiary",children:"soon"})]}):a?s.jsxs(si,{to:a,onClick:n,className:({isActive:o})=>B("w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm",o?"bg-surface-sunken text-text-primary font-medium":"text-text-secondary hover:bg-surface-subtle"),children:[e,s.jsx("span",{children:t}),i&&s.jsx(YO,{})]}):s.jsxs("button",{type:"button",onClick:n,className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm text-text-secondary hover:bg-surface-subtle",children:[e,s.jsx("span",{children:t}),i&&s.jsx(YO,{})]})}function YO(){return s.jsx("span",{"aria-hidden":"true",className:"ml-auto h-2 w-2 shrink-0 rounded-full bg-intent-brand"})}function hB(e){if(!Array.isArray(e))return null;for(let t=e.length-1;t>=0;t--){const n=e[t];if(n&&n.role==="user")return{text:typeof n.content=="string"?n.content:"",attachments:Array.isArray(n.attachments)?n.attachments:[]}}return null}function ZO(e,t){return!e||e.kind!=="error"&&e.kind!=="stopped"?!1:(e.retryText||"").trim()||(e.retryAttachments||[]).length?!0:hB(t)!=null}function Nce(e){const t=String(e??"").trim();return t?/^HTTP 429\b/.test(t)||/rate limit/i.test(t)?"Too many requests. Wait a moment and try again.":/^HTTP 401\b/.test(t)||/^HTTP 403\b/.test(t)||/unauthorized|forbidden/i.test(t)?"Your session expired. Refresh the page and try again.":/^HTTP 5\d\d\b/.test(t)||/internal server/i.test(t)?"Something went wrong on our side. Try again.":/^HTTP 4\d\d\b/.test(t)?"The request could not be completed. Try again.":/failed to fetch|networkerror|load failed|network request failed/i.test(t)?"Couldn't reach the server. Check your connection and try again.":"Something went wrong. Try again.":"Something went wrong. Try again."}function Sce(e){const t=Math.max(0,Math.round(Number(e)/1e3)||0);return t<60?`${t}s`:`${Math.floor(t/60)}m ${t%60}s`}class Cce{constructor(){_c(this,"entries",new Map);
757_c(this,"streamingListeners",new Set);_c(this,"streamingIdsSnapshot",new Set)}subscribeSession(t,n){const r=this.ensureEntryShell(t);return r.listeners.add(n),()=>r.listeners.delete(n)}getSessionSnapshot(t){var n;return((n=this.entries.get(t))==null?void 0:n.session)??null}ensureEntryShell(t){let n=this.entries.get(t);return n||(n={session:{chatId:t,messages:[],status:{kind:"idle"},turnStartedAt:null},config:null,abort:null,lastTurn:null,listeners:new Set},this.entries.set(t,n),n)}subscribeStreaming(t){return this.streamingListeners.add(t),()=>this.streamingListeners.delete(t)}getStreamingSnapshot(){return this.streamingIdsSnapshot}ensure(t,n,r){const a=this.ensureEntryShell(t),i=a.config===null&&a.session.messages.length===0;a.config=n,i&&r&&r.length>0&&(a.session={...a.session,messages:r},a.listeners.forEach(o=>o()))}remove(t){var r;const n=this.entries.get(t);n&&((r=n.abort)==null||r.abort(),this.entries.delete(t),n.session.status.kind==="streaming"&&this.rebuildStreamingSnapshot())}async send(t,n,r,a){var v,w;const i=this.entries.get(t);if(!i||!i.config)throw new Error(`chatSessions.send: no session config for "${t}". Call ensure() first.`);if(i.session.status.kind==="streaming")return;const o=n.trim();if(!o&&r.length===0)return;const l=!!(a!=null&&a.skipPushUser),c=new Date().toISOString(),u={role:"user",content:o,ts:c,...r.length>0?{attachments:r}:{}},d={role:"assistant",parts:[],ts:c},h=i.session.messages,f=l?[...h,d]:[...h,u,d],m=Date.now();i.lastTurn={text:o,attachments:r},this.patchSession(t,{messages:f,status:{kind:"streaming",startedAt:m},turnStartedAt:m});const x=new AbortController;i.abort=x;const g=i.config.endpoint??"/api/chat",y=i.config.extraRequestBody(),b=(a==null?void 0:a.modelChoice)??"auto";try{const _=XO(f.slice(0,-1)),k=await oe(g,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:_,...y,...b!=="auto"?{model:b}:{}}),signal:x.signal});if(k.status===402){let j={};try{j=await k.json()}catch{}if((j==null?void 0:j.error)==="insufficient_credits"){const N=this.dropTrailingEmptyAssistant(((v=this.entries.get(t))==null?void 0:v.session.messages)??f);this.patchSession(t,{messages:N,status:{kind:"insufficient_credits",reason:j.message||"You're out of credits. Top up to keep going.",code:j.code||"credits_exhausted",retryText:o,retryAttachments:r,toppedUp:!1}});return}}if(!k.ok||!k.body)throw new Error(`HTTP ${k.status}`);await this.consumeStream(t,k.body.getReader()),((w=this.entries.get(t))==null?void 0:w.session.status.kind)==="streaming"&&(this.patchSession(t,{status:{kind:"idle"}}),await this.persistSafe(t))}catch(_){if((_==null?void 0:_.name)==="AbortError"){this.patchSession(t,{status:this.stoppedStatus(i)});return}this.patchSession(t,{status:this.errorStatus(i,(_==null?void 0:_.message)||String(_))})}finally{const _=this.entries.get(t);_&&_.abort===x&&(_.abort=null)}}stop(t){var r;const n=this.entries.get(t);n&&((r=n.abort)==null||r.abort())}retry(t){const n=this.entries.get(t);if(!n)return;const r=n.session.status;let a="",i=[];if(r.kind==="insufficient_credits")a=r.retryText,i=r.retryAttachments;else if(r.kind==="error"||r.kind==="stopped"){if(a=r.retryText||"",i=r.retryAttachments||[],!a&&i.length===0){const u=hB(n.session.messages);if(!u)return;a=u.text,i=u.attachments}}else return;const o=this.dropTrailingEmptyAssistant(n.session.messages),l=o[o.length-1],c=(l==null?void 0:l.role)==="assistant"?o.slice(0,-1):o;this.patchSession(t,{messages:c,status:{kind:"idle"}}),this.send(t,a,i,{skipPushUser:!0})}regenerate(t,n){var l;const r=this.entries.get(t);if(!r||r.session.status.kind==="streaming")return;const a=r.session.messages;if(n<0||n>=a.length||((l=a[n])==null?void 0:l.role)!=="assistant")return;let i=n-1;for(;i>=0&&a[i].role!=="user";)i--;if(i<0)return;const o=a[i];o.role==="user"&&(this.patchSession(t,{messages:a.slice(0,i+1),status:{kind:"idle"}}),this.send(t,o.content,o.attachments??[],{skipPushUser:!0}))}dismissStatus(t){this.entries.get(t)&&this.patchSession(t,{status:{kind:"idle"}})}markToppedUp(t){const n=this.entries.get(t);if(!n)return;const r=n.session.status;r.kind==="insufficient_credits"&&this.patchSession(t,{status:{...r,toppedUp:!0}})}async postDecision(t,n,r){this.updateAssistant(t,i=>i.map(o=>o.kind==="tool"&&o.id===n?{...o,confirmDecision:r}:o));const a=i=>{this.updateAssistant(t,o=>o.map(l=>l.kind==="tool"&&l.id===n?{...l,confirmDecision:null,...i!=null&&i.clearAwaiting?{awaitingConfirm:!1}:{}}:l))};try{const i=await oe("/api/chat/decide",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool_use_id:n,decision:r})});
757if(i.status===410){a({clearAwaiting:!0}),Ae.warning("Confirmation expired",{id:"chat-decide-expired",description:"Ask the agent to try that action again if you still want it."});return}i.ok||(a(),Ae.error("Couldn't send confirmation",{description:`HTTP ${i.status} â try Confirm or Cancel again.`}))}catch(i){a(),console.error("[chatSessions.postDecision] failed:",i),Ae.error("Couldn't send confirmation",{description:i instanceof Error?i.message:"Network error â try Confirm or Cancel again."})}}async submitToolInput(t,n,r,a){var f,m;const i=this.entries.get(t);if(!i||!i.config)throw new Error(`chatSessions.submitToolInput: no session config for "${t}". Call ensure() first.`);if(i.session.status.kind==="streaming")return{ok:!1,message:"Already streaming."};const o={role:"assistant",parts:[],ts:new Date().toISOString()},c=[...i.session.messages,o],u=Date.now();this.patchSession(t,{messages:c,status:{kind:"streaming",startedAt:u},turnStartedAt:u});const d=new AbortController;i.abort=d;const h=i.config.extraRequestBody();try{const x=XO(c.slice(0,-1),n),g=await oe(`/api/chats/${encodeURIComponent(t)}/tool-input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool_call_id:n,values:r,cancel:!!(a!=null&&a.cancel),messages:x,...h}),signal:d.signal});if(g.status===422){let b={};try{b=await g.json()}catch{}const v=this.dropTrailingEmptyAssistant(((f=this.entries.get(t))==null?void 0:f.session.messages)??c);return this.patchSession(t,{messages:v,status:{kind:"idle"}}),{ok:!1,errors:b.errors??{},message:b.error}}if(!g.ok||!g.body)throw new Error(`HTTP ${g.status}`);await this.consumeStream(t,g.body.getReader());const y=(m=this.entries.get(t))==null?void 0:m.session.status;return(y==null?void 0:y.kind)==="streaming"?(this.patchSession(t,{status:{kind:"idle"}}),await this.persistSafe(t),{ok:!0}):(y==null?void 0:y.kind)==="error"?{ok:!1,message:y.message}:{ok:!0}
757}catch(x){return(x==null?void 0:x.name)==="AbortError"?(this.patchSession(t,{status:this.stoppedStatus(i)}),{ok:!1,message:"aborted"}):(this.patchSession(t,{status:this.errorStatus(i,(x==null?void 0:x.message)||String(x))}),{ok:!1,message:(x==null?void 0:x.message)||String(x)})}finally{const x=this.entries.get(t);x&&x.abort===d&&(x.abort=null)}}patchSession(t,n){const r=this.entries.get(t);if(!r)return;const a=r.session.status.kind==="streaming";r.session={...r.session,...n};const i=r.session.status.kind==="streaming";r.listeners.forEach(o=>o()),a!==i&&this.rebuildStreamingSnapshot()}updateAssistant(t,n){const r=this.entries.get(t);if(!r)return;const a=r.session.messages,i=a[a.length-1];if(!i||i.role!=="assistant")return;const o={...i,parts:n(i.parts)},l=[...a.slice(0,-1),o];this.patchSession(t,{messages:l})}appendText(t,n){this.updateAssistant(t,r=>{const a=[...r],i=a[a.length-1];return(i==null?void 0:i.kind)==="text"?a[a.length-1]={...i,text:i.text+n}:a.push({kind:"text",text:n}),a})}startTool(t,n,r){this.updateAssistant(t,a=>[...a,{kind:"tool",id:n,name:r,partial_json:"",input:null,status:"running",summary:null}])}completeToolInput(t,n,r){this.updateAssistant(t,a=>a.map(i=>i.kind==="tool"&&i.id===n?{...i,input:r}:i))}finishTool(t,n,r,a){this.updateAssistant(t,i=>i.map(o=>o.kind==="tool"&&o.id===n?{...o,status:a?"error":"done",summary:r}:o))}pushSkillProgress(t,n,r){this.updateAssistant(t,a=>a.map(i=>i.kind==="tool"&&i.id===n?{...i,progress:[...i.progress||[],r]}:i))}setAwaitingConfirm(t,n,r){this.updateAssistant(t,a=>a.map(i=>i.kind==="tool"&&i.id===n?{...i,awaitingConfirm:!0,confirmInput:r}:i))}clearAwaitingConfirm(t,n){this.updateAssistant(t,r=>r.map(a=>a.kind==="tool"&&a.id===n?{...a,awaitingConfirm:!1}:a))}applyCardRepair(t,n){const r=Array.isArray(n==null?void 0:n.replacements)?n.replacements:[],a=new Set((Array.isArray(n==null?void 0:n.strip_ids)?n.strip_ids:[]).map(i=>String(i)));r.length===0&&a.size===0||this.updateAssistant(t,i=>i.map(o=>o.kind==="text"?{...o,text:Ace(o.text,r,a)}:o))}dropTrailingEmptyAssistant(t){const n=t[t.length-1];return(n==null?void 0:n.role)==="assistant"&&n.parts.length===0?t.slice(0,-1):t}parkedTurn(t){var n,r;return{retryText:((n=t.lastTurn)==null?void 0:n.text)??"",retryAttachments:((r=t.lastTurn)==null?void 0:r.attachments)??[]}}errorStatus(t,n){return{kind:"error",message:n,...this.parkedTurn(t)}}stoppedStatus(t){const n=t.session.turnStartedAt??Date.now();return{kind:"stopped",elapsedMs:Math.max(0,Date.now()-n),...this.parkedTurn(t)}}async persistSafe(t){const n=this.entries.get(t);if(!(!n||!n.config))try{await n.config.persist(n.session.messages)}catch(r){const a=r instanceof Error?r.message:String(r??"unknown error");console.error("[chatSessions.persist] failed:",r),Ae.error("Couldn't save this chat",{id:"chat-persist-failed",description:a.length>0?`${a} â reload may lose unsaved messages.`:"Reload may lose unsaved messages."})}}async consumeStream(t,n){const r=new TextDecoder;let a="";for(;;){const{value:i,done:o}=await n.read();if(o)break;a+=r.decode(i,{stream:!0});let l;for(;(l=a.indexOf(` 758 759`))!==-1;){const c=a.slice(0,l);a=a.slice(l+2);const u=Tce(c);u&&this.handleStreamEvent(t,u)}}}handleStreamEvent(t,n){var i,o,l,c,u,d,h,f,m,x,g;const r=this.entries.get(t);if(!r||!r.config)return;const a=r.config;switch(n.type){case"delta":typeof((i=n.data)==null?void 0:i.text)=="string"&&this.appendText(t,n.data.text);break;case"tool_start":(o=n.data)!=null&&o.id&&((l=n.data)!=null&&l.name)&&this.startTool(t,n.data.id,n.data.name);break;case"tool_input_complete":(c=n.data)!=null&&c.id&&(this.completeToolInput(t,n.data.id,n.data.input),(u=a.onToolInputComplete)==null||u.call(a,{id:n.data.id,name:n.data.name,input:n.data.input}));break;case"tool_result":(d=n.data)!=null&&d.id&&(this.finishTool(t,n.data.id,n.data.summary,!!n.data.is_error),(h=a.onToolResult)==null||h.call(a,{id:n.data.id,name:n.data.name,summary:n.data.summary,is_error:!!n.data.is_error}));break;case"skill_progress":if((f=n.data)!=null&&f.tool_use_id){const{tool_use_id:y,...b}=n.data;this.pushSkillProgress(t,y,b)}break;case"tool_confirm_required":(m=n.data)!=null&&m.id&&this.setAwaitingConfirm(t,n.data.id,n.data.input);break;case"tool_confirm_resolved":(x=n.data)!=null&&x.id&&this.clearAwaitingConfirm(t,n.data.id);break;case"card_repair":this.applyCardRepair(t,n.data);break;case"error":this.patchSession(t,{status:this.errorStatus(r,((g=n.data)==null?void 0:g.message)||"stream error")});break}}rebuildStreamingSnapshot(){const t=new Set;for(const[n,r]of this.entries)r.session.status.kind==="streaming"&&t.add(n);
759this.streamingIdsSnapshot=t,this.streamingListeners.forEach(n=>n())}}const Ece=`_(The download link for this file didn't bind correctly â say "regenerate" and I'll re-issue it.)_`;function Ace(e,t,n){let r=e;for(const{from:a,to:i}of t)r=r.replace(new RegExp(`(/exports/)${a}(?!\\d)`,"g"),`$1${i}`);return n.size&&(r=r.replace(/^:::download-card(?:\{([^}]*)\})?[ \t]*\n(?:[^\n]*\n)*?:::[ \t]*$/gm,(a,i)=>{var u;const o=/url=(?:"([^"]*)"|'([^']*)')/.exec(i||""),c=((u=(o?o[1]??o[2]??"":"").match(/\/exports\/(\d+)/))==null?void 0:u[1])??null;return c&&n.has(c)?Ece:a})),r}function Tce(e){const t=e.split(` 760`);let n="message",r="";for(const a of t)a.startsWith("event:")?n=a.slice(6).trim():a.startsWith("data:")&&(r+=a.slice(5).trim());if(!r)return null;try{return{type:n,data:JSON.parse(r)}}catch{return null}}function XO(e,t){return e.map(n=>{if(n.role==="user"){const a={role:"user",content:n.content};return Array.isArray(n.attachments)&&n.attachments.length>0&&(a.attachments=n.attachments),a}if(t&&n.parts.some(a=>a.kind==="tool"&&a.id===t)){const a=[];for(const i of n.parts)i.kind==="text"?i.text.length>0&&a.push({type:"text",text:i.text}):i.kind==="tool"&&i.id===t&&a.push({type:"tool_use",id:i.id,name:i.name,input:i.input??{}});return{role:"assistant",content:a}}return{role:"assistant",content:n.parts.filter(a=>a.kind==="text").map(a=>a.text).join("")}})}const fB=p.createContext(null);function Oce({children:e}){const t=p.useMemo(()=>new Cce,[]);return s.jsx(fB.Provider,{value:t,children:e})}function cx(){const e=p.useContext(fB);if(!e)throw new Error("useChatSessionsStore must be called inside <ChatSessionsProvider>");return e}function Ice(e){const t=cx();return p.useSyncExternalStore(n=>e?t.subscribeSession(e,n):()=>{},()=>e?t.getSessionSnapshot(e):null,()=>null)}function Pce(){const e=cx();return p.useSyncExternalStore(t=>e.subscribeStreaming(t),()=>e.getStreamingSnapshot(),()=>e.getStreamingSnapshot())}function Rce({open:e,title:t,busy:n,onCancel:r,onConfirm:a}){return s.jsx(js,{open:e,onOpenChange:i=>{!i&&!n&&r()},children:s.jsxs(Ns,{size:"sm",children:[s.jsxs(La,{children:[s.jsx(ma,{children:"Delete chat"}),s.jsxs(hc,{children:["Delete â",t,"â? This cannot be undone."]})]}),s.jsxs(da,{children:[s.jsx(W,{type:"button",intent:"neutral",variant:"ghost",size:"sm",onClick:r,disabled:n,children:"Cancel"}),s.jsx(W,{type:"button",intent:"destructive",size:"sm",onClick:a,disabled:n,children:n?"Deletingâ¦":"Delete"})]})]})})}const Ve={1:{fill:"bg-category-1",tint:"bg-category-1-50",text:"text-category-1-700",dot:"bg-category-1",border:"border-category-1-700/20"},2:{fill:"bg-category-2",tint:"bg-category-2-50",text:"text-category-2-700",dot:"bg-category-2",border:"border-category-2-700/20"},3:{fill:"bg-category-3",tint:"bg-category-3-50",text:"text-category-3-700",dot:"bg-category-3",border:"border-category-3-700/20"},4:{fill:"bg-category-4",tint:"bg-category-4-50",text:"text-category-4-700",dot:"bg-category-4",border:"border-category-4-700/20"},5:{fill:"bg-category-5",tint:"bg-category-5-50",text:"text-category-5-700",dot:"bg-category-5",border:"border-category-5-700/20"},6:{fill:"bg-category-6",tint:"bg-category-6-50",text:"text-category-6-700",dot:"bg-category-6",border:"border-category-6-700/20"}},JO=[1,2,3,4,5,6];function mB(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return JO[t%JO.length]}const zo=hf("inline-flex items-center gap-1.5 rounded-full text-body-sm font-medium py-0.5 px-[9px] whitespace-nowrap",{variants:{tone:{neutral:"",brand:"",success:"",warning:"",error:"",info:""},variant:{subtle:"",outline:"bg-surface border",solid:"text-text-inverse"}},compoundVariants:[{tone:"neutral",variant:"subtle",className:"bg-surface-sunken text-text-body"},{tone:"neutral",variant:"outline",className:"border-outline text-text-body"},{tone:"neutral",variant:"solid",className:"bg-gray-600 text-text-inverse"},{tone:"brand",variant:"subtle",className:"bg-surface-brandSubtle text-text-brand"},{tone:"brand",variant:"outline",className:"border-outline-brand text-text-brand"},{tone:"brand",variant:"solid",className:"bg-intent-brand text-text-inverse"},{tone:"success",variant:"subtle",className:"bg-surface-successSubtle text-text-success"},{tone:"success",variant:"outline",className:"border-outline-success text-text-success"},{tone:"success",variant:"solid",className:"bg-intent-success text-text-inverse"},{tone:"warning",variant:"subtle",className:"bg-surface-warningSubtle text-text-warning"},{tone:"warning",variant:"outline",className:"border-outline-warning text-text-warning"},{tone:"warning",variant:"solid",className:"bg-intent-warning text-text-inverse"},{tone:"error",variant:"subtle",className:"bg-surface-errorSubtle text-text-error"},{tone:"error",variant:"outline",className:"border-outline-error text-text-error"},{tone:"error",variant:"solid",className:"bg-intent-error text-text-inverse"},{tone:"info",variant:"subtle",className:"bg-surface-infoSubtle text-text-info"},{tone:"info",variant:"outline",className:"border-outline-info text-text-info"},{tone:"info",variant:"solid",className:"bg-intent-info text-text-inverse"}
760],defaultVariants:{tone:"neutral",variant:"subtle"}}),Dce={neutral:"bg-outline-strong",brand:"bg-brand-500",success:"bg-success-500",warning:"bg-warning-500",error:"bg-error-500",info:"bg-info-500"},Mce={1:{subtle:`${Ve[1].tint} ${Ve[1].text}`,outline:`bg-surface border ${Ve[1].border} ${Ve[1].text}`,solid:`${Ve[1].fill} text-text-inverse`},2:{subtle:`${Ve[2].tint} ${Ve[2].text}`,outline:`bg-surface border ${Ve[2].border} ${Ve[2].text}`,solid:`${Ve[2].fill} text-text-inverse`},3:{subtle:`${Ve[3].tint} ${Ve[3].text}`,outline:`bg-surface border ${Ve[3].border} ${Ve[3].text}`,solid:`${Ve[3].fill} text-text-inverse`},4:{subtle:`${Ve[4].tint} ${Ve[4].text}`,outline:`bg-surface border ${Ve[4].border} ${Ve[4].text}`,solid:`${Ve[4].fill} text-text-inverse`},5:{subtle:`${Ve[5].tint} ${Ve[5].text}`,outline:`bg-surface border ${Ve[5].border} ${Ve[5].text}`,solid:`${Ve[5].fill} text-text-inverse`},6:{subtle:`${Ve[6].tint} ${Ve[6].text}`,outline:`bg-surface border ${Ve[6].border} ${Ve[6].text}`,solid:`${Ve[6].fill} text-text-inverse`}},_n=p.forwardRef(({className:e,tone:t,variant:n,category:r,dot:a,children:i,...o},l)=>{const c=n??"subtle",u=t??"neutral";return s.jsxs("span",{ref:l,className:B(r?["inline-flex items-center gap-1.5 rounded-full text-body-sm font-medium py-0.5 px-[9px] whitespace-nowrap",Mce[r][c]]:zo({tone:u,variant:c}),e),...o,children:[a?s.jsx("span",{className:B("h-1.5 w-1.5 shrink-0 rounded-full",r?Ve[r].dot:Dce[u]),"aria-hidden":!0}):null,i]})});_n.displayName="Badge";function hC({q:e,setQ:t,placeholder:n,action:r}){return s.jsxs("div",{className:"border-b border-outline-subtle p-2 flex items-center gap-2 bg-surface",children:[s.jsxs("div",{className:"flex-1 relative",children:[s.jsx(Fa,{className:b2}),s.jsx("input",{value:e,onChange:a=>t(a.target.value),placeholder:n,className:`w-full rounded-md border border-outline-subtle bg-surface-subtle py-1 pr-2 text-sm focus:border-outline-brand focus:bg-surface focus:outline-none focus-visible:shadow-focus ${v2}`})]}),r]})}function $ce(e,t){const[n,r]=p.useState(""),a=p.useMemo(()=>{if(!e)return null;const i=n.toLowerCase().trim();return i?e.filter(o=>t(o,i)):e},[e,n,t]);return{q:n,setQ:r,filtered:a}}function Lce({status:e}){const t=e==="active"?"success":e==="pending"?"warning":"neutral";return s.jsx(_n,{tone:t,className:"uppercase tracking-wider",children:e})}function Fce(e){return e.replace(/^\d{4}-\d{2}-\d{2}[-_]/,"").replace(/_/g," ").replace(/\b\w/g,t=>t.toUpperCase())}function fC({mobileVisible:e=!1,children:t,className:n}){return s.jsx("section",{className:B("shrink-0 flex-col border-r border-outline-subtle bg-surface-subtle/40",e?"flex w-full md:w-[290px]":"hidden md:flex w-[290px]",n),children:t})}const QO="gadjet:agent-chat-groups-open";function Bce({mobileVisible:e=!1}){const t=Rt(),n=jn(),r=Ba(),a=n.chatId??null,i=Lt(),o=i.kind==="ready"&&i.me.role==="seller_user",l=r.pathname.match(/^\/sellers\/([^/]+)\/chats/),c=l?{kind:"seller",slug:l[1]}:{kind:"workspace"},[u,d]=p.useState(null),[h,f]=p.useState(null),[m,x]=p.useState(""),[g,y]=p.useState(!1),[b,v]=p.useState(null),[w,_]=p.useState(null),[k,j]=p.useState(!1),N=p.useRef(g);p.useEffect(()=>{N.current=g},[g]);const[E,A]=p.useState(()=>{try{const L=localStorage.getItem(QO);if(!L)return{};const q=JSON.parse(L);if(q&&typeof q=="object"&&!Array.isArray(q)){const me={};for(const[ee,ne]of Object.entries(q))typeof ne=="boolean"&&(me[ee]=ne);return me}return{}}catch{return{}}});p.useEffect(()=>{try{localStorage.setItem(QO,JSON.stringify(E))}catch{}},[E]);async function C(){try{d(await K.listGroupedChats({archived:N.current}))}catch(L){f(String((L==null?void 0:L.message)||L))}}p.useEffect(()=>{C()},[g]),p.useEffect(()=>{function L(){C()}return window.addEventListener("gadjet:chat-saved",L),()=>window.removeEventListener("gadjet:chat-saved",L)},[]),p.useEffect(()=>{let L=null;const q=xn.channel("chat-events").on("postgres_changes",{event:"INSERT",schema:"public",table:"chat_events"},()=>{L&&clearTimeout(L),L=setTimeout(()=>{C(),L=null},500)}).subscribe();return()=>{L&&clearTimeout(L),xn.removeChannel(q)}},[]);function T(L){return L in E?E[L]:L==="_workspace"||c.kind==="seller"&&c.slug===L}function S(L){A(q=>({...q,[L]:!T(L)}))}const O=p.useMemo(()=>
760{if(!u)return null;const L=m.toLowerCase().trim();return L?{workspace:u.workspace.filter(q=>q.title.toLowerCase().includes(L)),sellers:u.sellers.map(q=>({...q,chats:q.chats.filter(me=>me.title.toLowerCase().includes(L))})).filter(q=>q.chats.length>0)}:u},[u,m]);function R(){c.kind==="seller"?(window.dispatchEvent(new CustomEvent("gadjet:seller-new-chat",{detail:{slug:c.slug}})),t(cC(c.slug))):(window.dispatchEvent(new CustomEvent("gadjet:agent-new-chat")),t(Zl()))}function I(L,q){q.preventDefault(),q.stopPropagation(),_({kind:"workspace",id:L})}function $(L,q,me){me.preventDefault(),me.stopPropagation(),_({kind:"seller",slug:L,id:q})}function P(){var q,me;return!w||!u?"this chat":((me=(w.kind==="workspace"?u.workspace:((q=u.sellers.find(ee=>ee.slug===w.slug))==null?void 0:q.chats)??[]).find(ee=>ee.id===w.id))==null?void 0:me.title)||"this chat"}async function F(){if(w){j(!0);try{w.kind==="workspace"?(await K.deleteGlobalChat(w.id),re.remove(w.id),c.kind==="workspace"&&a===w.id&&t("/agent")):(await K.deleteChat(w.slug,w.id),re.remove(w.id),c.kind==="seller"&&c.slug===w.slug&&a===w.id&&t(`/sellers/${w.slug}/chats`)),_(null),C()}catch(L){f(String((L==null?void 0:L.message)||L))}finally{j(!1)}}}function Z(L,q){q.preventDefault(),q.stopPropagation(),v(L)}function D(){v(null)}async function H(L,q){v(null);try{await K.renameGlobalChat(L,q),C()}catch(me){f(String((me==null?void 0:me.message)||me))}}async function Y(L,q,me){v(null);try{await K.renameChat(L,q,me),C()}catch(ee){f(String((ee==null?void 0:ee.message)||ee))}}async function M(L,q){q.preventDefault(),q.stopPropagation();try{await K.archiveGlobalChat(L,!g),!g&&c.kind==="workspace"&&a===L&&t("/agent"),C()}catch(me){f(String((me==null?void 0:me.message)||me))}}async function z(L,q,me){me.preventDefault(),me.stopPropagation();try{await K.archiveChat(L,q,!g),!g&&c.kind==="seller"&&c.slug===L&&a===q&&t(`/sellers/${L}/chats`),C()}catch(ee){f(String((ee==null?void 0:ee.message)||ee))}}const G=O?O.workspace.length+O.sellers.reduce((L,q)=>L+q.chats.length,0):0,te=Pce(),re=cx();return s.jsxs(fC,{mobileVisible:e,children:[s.jsx(hC,{q:m,setQ:x,placeholder:"Search chatsâ¦",action:g||o&&c.kind!=="seller"?null:s.jsx("button",{type:"button",onClick:R,className:"inline-flex items-center justify-center min-h-11 min-w-11 md:min-
760h-0 md:min-w-0 p-1.5 rounded-md text-text-secondary hover:text-text-brand hover:bg-surface-brandSubtle","aria-label":c.kind==="seller"?`New chat for ${c.slug}`:"New chat",title:c.kind==="seller"?`New chat for ${c.slug}`:"New workspace chat",children:s.jsx(In,{className:"w-4 h-4"})})}),s.jsxs("button",{onClick:()=>{v(null),y(L=>!L)},className:B("flex items-center gap-1.5 px-3 py-1.5 text-body-xs border-b border-outline-subtle text-left",g?"text-text-brand bg-surface-brandSubtle":"text-text-tertiary hover:text-text-secondary hover:bg-surface-sunken/40"),children:[g?s.jsx(G6,{className:"w-3.5 h-3.5 shrink-0"}):s.jsx(Y6,{className:"w-3.5 h-3.5 shrink-0"}),g?"Viewing archived â back to active":"Show archived"]}),s.jsxs("div",{className:"flex-1 overflow-y-auto scrollbar-on-hover",children:[h&&s.jsx("div",{className:"mx-4 my-3 text-xs text-text-error bg-surface-errorSubtle border border-outline-error rounded-md p-3",children:h}),u===null&&!h&&s.jsx("div",{className:"px-4 py-3 text-xs text-text-tertiary",children:"Loadingâ¦"}),u!==null&&G===0&&s.jsx("div",{className:"px-4 py-6 text-xs text-text-tertiary",children:g?"No archived chats.":s.jsxs(s.Fragment,{children:["No chats yet â click"," ",s.jsx(In,{className:"inline w-3 h-3 align-text-bottom"})," to start one."]})}),O&&s.jsxs("div",{className:"py-2",children:[!o&&s.jsx(eI,{label:"Workspace",icon:s.jsx(Ht,{className:"w-3.5 h-3.5 text-text-brand"}),chats:O.workspace,isOpen:T("_workspace"),onToggle:()=>S("_workspace"),isActiveGroup:c.kind==="workspace",chatHref:L=>`/agent/${L}`,isActiveChat:L=>c.kind==="workspace"&&a===L,onDelete:I,onArchive:M,editingId:b,onStartRename:Z,onCommitRename:H,onCancelRename:D,showArchived:g,streamingIds:te}),O.sellers.map(L=>s.jsx(eI,{label:L.display_name,icon:s.jsx(R2,{className:"w-3.5 h-3.5 text-text-secondary"}),chats:L.chats,isOpen:T(L.slug),onToggle:()=>S(L.slug),isActiveGroup:c.kind==="seller"&&c.slug===L.slug,chatHref:q=>`/sellers/${L.slug}/chats/${q}`,isActiveChat:q=>c.kind==="seller"&&c.slug===L.slug&&a===q,onDelete:(q,me)=>$(L.slug,q,me),onArchive:(q,me)=>z(L.slug,q,me),editingId:b,onStartRename:Z,onCommitRename:(q,me)=>Y(L.slug,q,me),onCancelRename:D,showArchived:g,streamingIds:te},L.slug))]})]}),s.jsx(Rce,{open:w!==null,title:P(),busy:k,onCancel:()=>{k||_(null)},onConfirm:()=>void F()})]})}function eI({label:e,icon:t,chats:n,isOpen:r,onToggle:a,isActiveGroup:i,chatHref:o,isActiveChat:l,onDelete:c,onArchive:u,editingId:d,onStartRename:h,onCommitRename:f,onCancelRename:m,showArchived:x,streamingIds:g}){return s.jsxs("div",{className:"mb-1",children:[s.jsxs("button",{onClick:a,className:B("w-full flex items-center gap-2 px-3 py-1.5 text-sm text-left rounded-md hover:bg-surface-sunken/60",i?"text-text-primary":"text-text-body"),children:[r?s.jsx(Pn,{className:"w-3.5 h-3.5 text-text-tertiary shrink-0"}):s.jsx(fr,{className:"w-3.5 h-3.5 text-text-tertiary shrink-0"}),t,s.jsx("span",{className:B("flex-1 truncate",i&&"font-semibold"),children:e}),s.jsx("span",{className:"text-body-xs text-text-tertiary shrink-0",children:n.length})]}),r&&s.jsxs("div",{className:"ml-2 pl-1 border-l border-outline-faint mt-0.5 space-y-0.5",children:[n.length===0&&s.jsx("div",{className:"px-3 py-1.5 text-body-xs text-text-tertiary",children:"No chats yet."}),n.map(y=>{const b=l(y.id),v=g.has(y.id);return d===y.id?s.jsx(Uce,{initial:y.title,onCommit:w=>f(y.id,w),onCancel:m},y.id):s.jsxs(si,{to:o(y.id),className:B("group flex items-start gap-2 px-3 py-1.5 rounded-md text-sm mx-1",b?"bg-surface border border-outline-subtle shadow-sm":"hover:bg-surface"),children:[s.jsx(Rd,{className:"w-3.5 h-3.5 text-text-tertiary shrink-0 mt-0.5"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:"text-text-primary truncate text-body-md",children:y.title}),v&&s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500 shrink-0 animate-pulse",title:"Assistant is responding","aria-label":"Assistant is responding"})]}),s.jsxs("div",{className:"text-body-xs text-text-secondary",children:[i6(y.updated_at)," · ",y.message_count," msg"]})]}),s.jsxs("div",{className:"flex items-center gap-0.5 opacity-100 md:opacity-0 md:group-hover:opacity-100 md:focus-within:opacity-100 shrink-0 mt-0.5",children:[s.jsx("button",{onClick:w=>h(y.id,w),className:"p-2 md:p-1 text-text-tertiary hover:text-text-brand",title:"Rename chat","aria-label":"Rename chat",children:s.jsx(Qi,{className:"w-3.5 h-3.5"})}),s.jsx("button",{onClick:w=>u(y.id,w),className:"p-2 md:p-1 text-text-tertiary hover:text-text-brand",title:x?"Unarchive chat":"Archive chat","aria-label":x?"Unarchive chat":"Archive chat",children:x?s.jsx(G6,{className:"w-3.5 h-3.5"}):s.jsx(Y6,{className:"w-3.5 h-3.5"})}),s.jsx("button",{onClick:w=>c(y.id,w),className:"p-2 md:p-1 text-text-tertiary hover:text-text-error",title:"Delete chat","aria-label":"Delete chat",children:s.jsx(us,{className:"w-3.5 h-3.5"})})]})]},y.id)})]})]})}function Uce({initial:e,onCommit:t,onCancel:n}){const[r,a]=p.useState(e),i=p.useRef(!1),o=()=>
760{if(i.current)return;const c=r.trim();c&&c!==e?(i.current=!0,t(c)):(i.current=!0,n())},l=()=>{i.current||(i.current=!0,n())};return s.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 mx-1",children:[s.jsx(Rd,{className:"w-3.5 h-3.5 text-text-tertiary shrink-0"}),s.jsx("input",{autoFocus:!0,value:r,onChange:c=>a(c.target.value),onKeyDown:c=>{c.key==="Enter"?(c.preventDefault(),o()):c.key==="Escape"&&(c.preventDefault(),l())},onBlur:o,className:"flex-1 min-w-0 text-body-md bg-surface border border-outline-brand rounded px-1.5 py-0.5 focus:outline-none focus:border-outline-brand focus-visible:shadow-focus"})]})}function zce({sellers:e,activeSlug:t,error:n,mobileVisible:r=!1}){var g;const a=e==null?void 0:e.find(y=>y.slug===t),[i,o]=p.useState(null),[l,c]=p.useState(null),[u,d]=p.useState(""),h=jn(),f=Ba(),m=h["*"]&&f.pathname.includes("/reports/")?h["*"]:null;p.useEffect(()=>{o(null),c(null),K.reports(t).then(o).catch(y=>c(String(y)))},[t]);const x=p.useMemo(()=>{if(!i)return null;const y=u.toLowerCase().trim();return y?i.map(b=>({...b,items:b.items.filter(v=>v.name.toLowerCase().includes(y)||v.path.toLowerCase().includes(y))})).filter(b=>b.items.length>0):i},[i,u]);return s.jsxs(fC,{mobileVisible:r,children:[s.jsx(hC,{q:u,setQ:d,placeholder:"Search documentsâ¦"}),s.jsxs("div",{className:"flex-1 overflow-y-auto",children:[s.jsx("div",{className:"px-3 pt-3 pb-3",children:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"w-7 h-7 rounded-lg bg-surface-brandSubtle text-text-brand flex items-center justify-center font-semibold text-sm",children:((g=a==null?void 0:a.display_name)==null?void 0:g[0])??"?"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"font-semibold text-text-primary text-sm truncate",children:(a==null?void 0:a.display_name)??t}),s.jsxs("div",{className:"text-body-xs text-text-secondary",children:["AM · ",(a==null?void 0:a.account_owner_label)??"â",a!=null&&a.seller_id?` · ID ${a.seller_id}`:null]})]})]})}),s.jsxs("div",{className:"px-3 pt-3 pb-2 flex items-baseline justify-between",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Documents"}),s.jsx("span",{className:"text-xs text-text-tertiary",children:(x==null?void 0:x.reduce((y,b)=>y+b.items.length,0))??0})]}),(l||n)&&s.jsx("div",{className:"mx-3 my-3 text-xs text-text-error bg-surface-errorSubtle border border-outline-error rounded-md p-3",children:l??n}),i===null&&!l&&s.jsx("div",{className:"px-3 py-2 text-xs text-text-tertiary",children:"Loadingâ¦"}),i!==null&&(x==null?void 0:x.length)===0&&s.jsx("div",{className:"px-3 py-6 text-xs text-text-tertiary",children:"No documents yet for this seller."}),s.jsx("div",{className:"px-2 pb-4 space-y-3",children:x==null?void 0:x.map(y=>s.jsxs("div",{children:[s.jsx("div",{className:"px-3 mt-2 mb-1 text-body-xs font-semibold uppercase tracking-wider text-text-tertiary",children:y.label}),y.items.map(b=>{const v=m===b.path;return s.jsxs(si,{to:`/sellers/${t}/reports/${b.path}`,className:B("block px-3 py-2 rounded-md text-sm",v?"bg-surface border border-outline-subtle shadow-sm":"hover:bg-surface"),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(il,{className:"w-3.5 h-3.5 text-text-tertiary shrink-0"}),s.jsx("div",{className:"text-text-primary truncate flex-1",children:Fce(b.name)})]}),s.jsx("div",{className:"ml-5 text-body-xs text-text-secondary",children:i6(b.updated_at)})]},b.path)})]},y.kind))})]})]})}function Wce({sellers:e,error:t}){const{q:n,setQ:r,filtered:a}=$ce(e,(i,o)=>i.display_name.toLowerCase().includes(o)||i.slug.toLowerCase().includes(o)||i.account_owner.toLowerCase().includes(o));return s.jsxs(fC,{children:[s.jsx(hC,{q:n,setQ:r,placeholder:"Search sellersâ¦"}),s.jsxs("div",{className:"flex-1 overflow-y-auto",children:[s.jsxs("div",{className:"px-3 pt-3 pb-2 flex items-baseline gap-2",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Sellers"}),s.jsx("span",{className:"text-xs text-text-tertiary",children:(a==null?void 0:a.length)??0})]}),t&&s.jsx("div",{className:"mx-3 my-3 text-xs text-text-error bg-surface-errorSubtle border border-outline-error roun
760ded-md p-3",children:t}),a===null&&s.jsx("div",{className:"px-3 py-2 text-xs text-text-tertiary",children:"Loadingâ¦"}),(a==null?void 0:a.length)===0&&s.jsx("div",{className:"px-3 py-6 text-xs text-text-tertiary",children:"No matches."}),s.jsx("div",{className:"px-2 pb-4",children:a==null?void 0:a.map(i=>s.jsxs(si,{to:`/sellers/${i.slug}`,className:"block px-3 py-2 rounded-lg hover:bg-surface hover:shadow-sm border border-transparent hover:border-outline-subtle transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"font-medium text-text-primary text-sm truncate flex-1",children:i.display_name}),s.jsx(Lce,{status:i.status})]}),s.jsxs("div",{className:"mt-1 flex items-center gap-2 text-body-xs text-text-secondary",children:[s.jsx(One,{className:"w-3 h-3"}),s.jsxs("span",{children:["AM · ",i.account_owner_label]}),i.has_data?s.jsx("span",{className:"text-text-tertiary",children:"·"}):null,!i.has_data&&s.jsx("span",{className:"text-text-warning",children:"no data yet"})]})]},i.slug))})]})]})}function Kce({sellers:e,activeSlug:t,error:n,mobileVisible:r=!1}){const a=Ba();return a.pathname.startsWith("/agent")||!!t&&a.pathname.startsWith(`/sellers/${t}/chats`)?s.jsx(Bce,{mobileVisible:r}):t?s.jsx(zce,{sellers:e,activeSlug:t,error:n,mobileVisible:r}):s.jsx(Wce,{sellers:e,error:n})}function Hce({onMenuClick:e}){return s.jsxs("div",{className:"md:hidden sticky top-0 z-chrome flex items-center gap-1 px-1 h-12 border-b border-outline-subtle bg-surface",children:[s.jsx("button",{type:"button",onClick:e,"aria-label":"Open navigation",className:"inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-md text-text-body hover:bg-surface-sunken",children:s.jsx(uF,{className:"h-5 w-5"})}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[s.jsx(w2,{variant:"mark",height:24}),s.jsx("div",{className:"truncate text-body-md font-semibold text-text-primary",children:"Gadjet HQ"})]})]})}class Vce extends p.Component{constructor(){super(...arguments);_c(this,"state",{error:null})}static getDerivedStateFromError(n){return{error:n}}componentDidUpdate(n){n.resetKey!==this.props.resetKey&&this.state.error&&this.setState({error:null})}componentDidCatch(n,r){console.error("[ErrorBoundary]",n,r.componentStack),CY(n,{react:{componentStack:r.componentStack,route:window.location.pathname}})}render(){const{error:n}=this.state;return n?s.jsx("div",{className:"flex-1 flex items-center justify-center p-8 bg-surface-subtle/30",children:s.jsxs("div",{className:"max-w-md text-center",children:[s.jsx("div",{className:"w-12 h-12 mx-auto rounded-full bg-surface-errorSubtle text-text-error flex items-center justify-center mb-4",children:s.jsx(zn,{className:"w-6 h-6"})}),s.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:"Something broke on this page"}),s.jsx("p",{className:"mt-2 text-sm text-text-secondary",children:n.message||String(n)}),s.jsxs("button",{onClick:()=>this.setState({error:null}),className:"mt-6 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border border-outline-subtle bg-surface text-sm text-text-body hover:bg-surface-subtle",children:[s.jsx(vi,{className:"w-3.5 h-3.5"})," Try again"]})]})}):this.props.children}}function qce(){const{openConnectStore:e}=d0();return s.jsxs(Sf,{tone:"soft",icon:s.jsx(Ht,{className:"w-4 h-4"}),action:s.jsx(lx,{tone:"soft",onClick:()=>e(),children:"Connect store"}),children:["You're viewing ",s.jsx("strong",{children:"demo data"})," â connect your Takealot store to see your own."]})}function mC(){const[e,t]=p.useState(()=>gN());return p.useEffect(()=>{function n(){t(gN())}return window.addEventListener("storage",n),window.addEventListener("gadjet:impersonation-changed",n),()=>{window.removeEventListener("storage",n),window.removeEventListener("gadjet:impersonation-changed",n)}},[]),e}async function Gce(e,t){const n=await oe("/api/admin/impersonate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({user_id:e,reason:null})});if(!n.ok){const i=await n.json().catch(()=>({}));throw new Error((i==null?void 0:i.message)||(i==null?void 0:i.error)||`HTTP ${n.status}`)}const r=await n.json(),a={session_id:r.session_id,target:r.target,expires_at:r.expires_at};return VF(r.token,a),ai(),a}async function Yce(){try{await oe("/api/admin/impersonate",{method:"DELETE"})}catch{}eC(),ai()}function Zce(){const e=Lt(),t=mC(),n=e.kind==="ready"?e.me.subscription_status??null:null;return n==="past_due"?s.jsx(Xce,{showAction:!t&&!wr()}):n==="cancelled"?s.jsx(Jce,{showAction:!t&&!wr()}):null}function Xce({showAction:e}){const[t,n]=p.useState(!1),[r,a]=p.useState(null);async function i(){if(!t){n(!0),a(null);try{const{link:o}=await K.billingManageSubscription();window.open(o,"_blank","noopener,noreferrer")}catch(o){a(String((o==null?void 0:o.message)||o))}finally{n(!1)}}}return s.jsxs(Sf,{tone:"soft",icon:s.jsx(zn,{className:"w-4 h-4"}),action:e?s.jsxs(lx,{tone:"soft",onClick:i,disabled:t,children:[t?s.jsx(_e,{className:"w-3 h-3 animate-spin"}):s.jsx(tx,{className:"w-3 h-3"}
760),"Update payment"]}):void 0,children:["We couldn't charge your card. Nothing has stopped yet",r?` â ${r}`:"."]})}function Jce({showAction:e}){const[t,n]=p.useState(!1),[r,a]=p.useState(null);async function i(){if(!t){n(!0),a(null);try{const o=await K.initiateSubscription();if(o.manage_url){window.open(o.manage_url,"_blank","noopener,noreferrer");return}if(o.authorization_url){window.open(o.authorization_url,"_blank","noopener,noreferrer");return}a("Couldn't start checkout. Try Settings â Billing.")}catch(o){a(String((o==null?void 0:o.message)||o))}finally{n(!1)}}}return s.jsxs(Sf,{tone:"soft",icon:s.jsx(zn,{className:"w-4 h-4"}),action:e?s.jsxs(lx,{tone:"soft",onClick:i,disabled:t,children:[t?s.jsx(_e,{className:"w-3 h-3 animate-spin"}):s.jsx(_o,{className:"w-3 h-3"}),"Restart plan"]}):void 0,children:["Your plan has ended. Data is kept; automations have stopped",r?` â ${r}`:"."]})}function Qce(){const e=mC(),[t,n]=p.useState(!1);if(p.useEffect(()=>{if(!e)return;const i=document.title,o=e.target.display_name||e.target.email;return document.title=`[VIEW AS ${o}] ${i}`,()=>{document.title=i}},[e==null?void 0:e.target.id]),!e)return null;const r=e.target.display_name||e.target.email;async function a(){if(!t){n(!0);try{await Yce()}finally{n(!1)}}}return s.jsxs(Sf,{tone:"strong",icon:s.jsx(al,{className:"w-4 h-4"}),action:s.jsxs(lx,{tone:"strong",onClick:a,disabled:t,children:[t?s.jsx(_e,{className:"w-3 h-3 animate-spin"}):null,"Exit"]}),children:["Viewing as ",s.jsx("strong",{children:r})," ",s.jsxs("span",{className:"opacity-70",children:["(",e.target.role,") â every action is recorded under your super-admin id."]})]})}const eue=6e4;async function tue(e){try{const t=await fetch("/api/version",{signal:e,cache:"no-store"});if(!t.ok)return null;const n=await t.json();return typeof n.version=="string"?n.version:null}catch{return null}}function nue(){const[e,t]=p.useState(!1),n=p.useRef("a5f126a14ff89d15059275e02ad82c23993e7a14");return p.useEffect(()=>{if(n.current.startsWith("dev-"))return;let r=!1;const a=new AbortController,i=async()=>{if(document.hidden)return;const c=await tue(a.signal);r||!c||c!==n.current&&c!=="dev"&&t(!0)};i();const o=setInterval(i,eue),l=()=>i();return window.addEventListener("focus",l),document.addEventListener("visibilitychange",l),()=>{r=!0,a.abort(),clearInterval(o),window.removeEventListener("focus",l),document.removeEventListener("visibilitychange",l)}},[]),e?s.jsx(Sf,{tone:"info",icon:s.jsx(pa,{className:"w-4 h-4"}),action:s.jsx(lx,{tone:"info",onClick:()=>window.location.reload(),children:"Refresh"}),children:"A new version of Gadjet is available â refresh to load the latest updates."}):null}const rue=hf("fixed z-drawer-content bg-surface shadow-xl flex flex-col outline-none pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)] data-[state=open]:animate-in data-[state=open]:duration-200 data-[state=closed]:animate-out data-[state=closed]:duration-150",{variants:{side:{right:"inset-y-0 right-0 h-full border-l border-outline-subtle data-[state=open]:slide-in-from-right data-[state=closed]:slide-out-to-right",left:"inset-y-0 left-0 h-full border-r border-outline-subtle data-[state=open]:slide-in-from-left data-[state=closed]:slide-out-to-left",top:"inset-x-0 top-0 w-full border-b border-outline-subtle data-[state=open]:slide-in-from-top data-[state=closed]:slide-out-to-top",bottom:"inset-x-0 bottom-0 w-full border-t border-outline-subtle data-[state=open]:slide-in-from-bottom data-[state=closed]:slide-out-to-bottom"},size:{sm:"",md:"",lg:"",xl:""}},compoundVariants:[{side:"right",size:"sm",className:"w-80 max-w-[90vw]"},{side:"right",size:"md",className:"w-96 max-w-[90vw]"},{side:"right",size:"lg",className:"w-full md:w-[560px]"},{side:"right",size:"xl",className:"w-full md:w-[720px]"},{side:"left",size:"sm",className:"w-80 max-w-[90vw]"},{side:"left",size:"md",className:"w-96 max-w-[90vw]"},{side:"left",size:"lg",className:"w-full md:w-[560px]"},{side:"left",size:"xl",className:"w-full md:w-[720px]"},{side:"top",size:"sm",className:"h-64"},{side:"top",size:"md",className:"h-96"},{side:"top",size:"lg",className:"h-[60vh]"},{side:"top",size:"xl",className:"h-[80vh]"},{side:"bottom",size:"sm",className:"h-64"},{side:"bottom",size:"md",className:"h-96"},{side:"bottom",size:"lg",className:"h-[60vh]"},{side:"bottom",size:"xl",className:"h-[80vh]"}],defaultVariants:{side:"right",size:"md"}}),Cr=EY,mr=p.forwardRef(({className:e,side:t,size:n,children:r,hideCloseButton:a=!1,...i},o)=>s.jsxs(AY,{children:[s.jsx(TY,{className:B("fixed inset-0 z-drawer bg-surface-inverse/30","data-[state=open]:animate-in data-[state=open]:fade-in-0","data-[state=closed]:animate-out data-[state=closed]:fade-out-0")}),s.jsxs(OY,{ref:o,className:B(rue({side:t,size:n}),e),...i,children:[r,!a&&s.jsx(IY,{})]})]}));mr.displayName="DrawerContent";function Er({className:e,...t}){return s.jsx("header",{className:B("border-b border-outline-subtle px-4 py-3 shrink-0",e),...t})}function pr({className:e,...t}){return s.jsx("div",{className:B("flex-1 overflow-y-auto",e),...t})}function ml({className:e,...t}){return s.jsx("footer",{className:B("border-t border-outline-subtle px-4 py-3 flex items-center justify-end gap-2 shrink-0 bg-surface-subtle",e),...t})}const xr=p.forwardRef(({className:e,...t},n)=>s.jsx(PY,{ref:n,className:B("text-headline-sm text-text-primary",e),...t}));xr.displayName="DrawerTitle";const Mr=p.forwardRef(({className:e,...t},n)=>s.jsx(RY,{ref:n,className:B("mt-1 text-body-sm text-text-secondary",e),...t}));Mr.displayName="DrawerDescription";const pB=p.createContext(null);function sue({slug:e,children:t}
760){const[n,r]=p.useState(!1),[a,i]=p.useState(0),[o,l]=p.useState(0),c=p.useCallback(()=>r(x=>!x),[]),u=p.useCallback(()=>r(!1),[]);p.useEffect(()=>{n&&i(0)},[n]);const d=p.useRef(n);p.useEffect(()=>{d.current=n},[n]);const h=p.useRef(new Map),f=300*1e3,m=p.useCallback((x,g,y)=>{h.current.set(x,{toastId:g,label:y,createdAt:Date.now()})},[]);return p.useEffect(()=>{const x=setInterval(()=>{const g=Date.now();for(const[y,b]of h.current)g-b.createdAt>f&&(Ae.dismiss(b.toastId),h.current.delete(y))},6e4);return()=>clearInterval(x)},[]),p.useEffect(()=>{if(!e)return;let x=null;const g=xn.channel(`exports:${e}`).on("postgres_changes",{event:"*",schema:"public",table:"exports",filter:`slug=eq.${e}`},y=>{const b=y.new;if(y.eventType==="UPDATE"&&(b==null?void 0:b.id)!=null){const v=h.current.get(b.id);if(v)if(b.status==="ready"){const w=b.id;Ae.success(`${v.label} ready`,{id:v.toastId,action:{label:"Download",onClick:()=>{Ul.download(w).catch(_=>{Ae.error("Download failed",{description:_ instanceof Error?_.message:String(_)})})}}}),h.current.delete(b.id)}else b.status==="failed"&&(Ae.error(`${v.label} failed`,{id:v.toastId,description:b.failure_reason||void 0}),h.current.delete(b.id))}y.eventType==="UPDATE"&&(b==null?void 0:b.status)==="ready"&&!d.current&&i(v=>v+1),x&&clearTimeout(x),x=setTimeout(()=>{l(v=>v+1),x=null},400)}).subscribe();return()=>{x&&clearTimeout(x),xn.removeChannel(g)}},[e]),s.jsx(pB.Provider,{value:{open:n,toggle:c,close:u,newReadyCount:a,refetchTick:o,registerPendingExport:m},children:t})}function xB(){const e=p.useContext(pB);return e||{open:!1,toggle:()=>{},close:()=>{},newReadyCount:0,refetchTick:0,registerPendingExport:()=>{}}}function aue({slug:e}){const{open:t,close:n,refetchTick:r,registerPendingExport:a}=xB(),[i,o]=p.useState([]),[l,c]=p.useState(!1),[u,d]=p.useState(!1),h=p.useCallback(()=>{if(!e){o([]);return}c(!0),d(!1),Ul.list(e).then(b=>{o(b.exports),c(!1)}).catch(()=>{d(!0),c(!1)})},[e]);p.useEffect(()=>{t&&h()},[t,r,h]);const f=p.useCallback(b=>{o(v=>v.filter(w=>w.id!==b)),Ul.remove(b).catch(v=>{h(),Ae("error","Couldn't delete export",{description:v instanceof Error?v.message:String(v)})})},[h]),[m,x]=p.useState(null),g=p.useCallback(b=>{x(b),Ul.download(b).catch(v=>{Ae("error","Couldn't download export",{description:v instanceof Error?v.message:String(v)})}).finally(()=>x(null))},[]),y=p.useCallback(b=>{if(!e)return;const v=Ae.loading(`Generating ${b.label}â¦`);Ul.run({slug:e,skill:b.skill,args:b.args}).then(({id:w})=>{a(w,v,b.label)}).catch(w=>{console.error(`[exports] quick-action ${b.skill} failed:`,w),Ae.error("Couldn't start export",{id:v,description:w instanceof Error?w.message:String(w)})})},[e,a]);return s.jsx(Cr,{open:t,onOpenChange:b=>{b||n()},children:s.jsxs(mr,{side:"right",size:"md",children:[s.jsxs(Er,{children:[s.jsx(xr,{children:"Exports"}),s.jsx(Mr,{className:"sr-only",children:"Recent exports for this seller â downloadable files plus quick actions to generate new ones."})]}),s.jsx(oue,{slug:e,onAction:y}),s.jsx(pr,{children:e?l&&i.length===0?s.jsx(pg,{text:"Loadingâ¦"}):u?s.jsx(pg,{text:"Couldn't load exports. Try again."}):i.length===0?s.jsx(pg,{text:"No exports in the last 30 days."}):s.jsx("ul",{className:"divide-y divide-outline-faint",children:i.map(b=>s.jsx(lue,{row:b,onDelete:f,onDownload:g,downloading:m===b.id},b.id))}):s.jsx(pg,{text:"Select a seller to see their exports."})})]})})}const iue=[{label:"Sales (last month)",skill:"sales-export",args:"last month"},{label:"Ledger",skill:"transactions-ledger-export",args:""},{label:"Weekly payout PDF",skill:"payout-statement-pdf",args:""},{label:"VAT (last month)",skill:"vat-export",args:"last month"},{label:"Listings",skill:"listings-export",args:""}];function oue({slug:e,onAction:t}){const n=!e;return s.jsxs("div",{className:"px-4 py-3 border-b border-outline-subtle bg-surface-subtle",children:[s.jsx("div",{className:"text-body-xs uppercase tracking-wide text-text-secondary mb-2",children:"Quick actions"}),s.jsx("div",{className:"grid grid-cols-2 gap-2",children:iue.map(r=>s.jsx("button",{type:"button",disabled:n,onClick:()=>t(r),title:n?"Select a seller first":`Run ${r.skill}`,className:n?"text-xs text-left px-2 py-1.5 rounded border border-outline-subtle bg-surface text-text-tertiary cursor-not-allowed":"text-xs text-left px-2 py-1.5 rounded border border-outline-subtle bg-surface text-text-body hover:bg-surface-sunken hover:border-outline",children:r.label},r.skill))})]})}function lue({row:e,onDelete:t,onDownload:n,downloading:r}){const a=cue(e.format),i=uue(e),o=due(e.created_at);return s.jsx("li",{className:"px-4 py-3 min-h-11",children:s.jsxs("div",{className:"flex items-start gap-2.5",children:[s.jsx(a,{className:"w-4 h-4 text-text-tertiary mt-0.5 shrink-0"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-sm text-text-primary truncate",children:i}),s.jsxs("div",{className:"text-xs text-text-secondary flex items-center gap-1.5 mt-0.5",children:[s.jsx("span",{children:o}),e.skill_name&&s.jsx("span",{className:"px-1.5 py-0.5 rounded bg-surface-sunken text-text-secondary truncate max-w-[120px]",children:e.skill_name}),e.size_bytes!=null&&s.jsx("span",{className:"text-text-tertiary",children:hue(e.size_bytes)})]}),e.status==="failed"&&e.failure_reason&&s.jsxs("div",{className:"text-xs text-text-error mt-1 flex items-start gap-1",children:[s.jsx(yt,{className:"w-3 h-3 mt-0.5 shrink-0"}),s.jsx("span",{className:"truncate",children:e.failure_reason})]})]}),s.jsxs("div",{className:"shrink-0 flex items-center gap-0.5",children:[e.status==="generating"?s.jsx(_e,{className:"w-4 h-4 text-text-tertiary animate-spin","aria-label":"Generating"}):e.status==="ready"?s.jsx("button",{type:"button",onClick:()=>
760n(e.id),disabled:r,"aria-label":"Download export",className:"inline-flex h-11 w-11 md:h-auto md:w-auto items-center justify-center p-1 rounded text-text-secondary hover:text-text-primary hover:bg-surface-sunken disabled:opacity-50",title:"Download",children:r?s.jsx(_e,{className:"w-4 h-4 animate-spin"}):s.jsx(Dr,{className:"w-4 h-4"})}):null,s.jsx("button",{type:"button",onClick:()=>t(e.id),"aria-label":"Delete export",title:"Delete",className:"inline-flex h-11 w-11 md:h-auto md:w-auto items-center justify-center p-1 rounded text-text-tertiary hover:text-text-error hover:bg-surface-errorSubtle",children:s.jsx(us,{className:"w-4 h-4"})})]})]})})}function pg({text:e}){return s.jsx("div",{className:"p-6 text-sm text-text-secondary text-center",children:e})}function cue(e){return e==="xlsx"?nF:il}function uue(e){return e.relative_path?(e.relative_path.split("/").pop()||e.relative_path).replace(/\.(csv|tsv|xlsx|pdf)$/i,""):e.skill_name||`Export #${e.id}`}function due(e){const t=new Date(e),n=new Date;return t.toDateString()===n.toDateString()?t.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}):t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function hue(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(0)} KB`:`${(e/1024/1024).toFixed(1)} MB`}function fue(e,t){const n={};return(e[e.length-1]===""?[...e,""]:e).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const mue=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,pue=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,xue={};function tI(e,t){return(xue.jsx?pue:mue).test(e)}const gue=/[ \t\n\f\r]/g;function yue(e){return typeof e=="object"?e.type==="text"?nI(e.value):!1:nI(e)}function nI(e){return e.replace(gue,"")===""}class ux{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}ux.prototype.normal={};ux.prototype.property={};ux.prototype.space=void 0;function gB(e,t){const n={},r={};for(const a of e)Object.assign(n,a.property),Object.assign(r,a.normal);return new ux(n,r,t)}function EN(e){return e.toLowerCase()}class oi{constructor(t,n){this.attribute=n,this.property=t}}oi.prototype.attribute="";oi.prototype.booleanish=!1;oi.prototype.boolean=!1;oi.prototype.commaOrSpaceSeparated=!1;oi.prototype.commaSeparated=!1;oi.prototype.defined=!1;oi.prototype.mustUseProperty=!1;oi.prototype.number=!1;oi.prototype.overloadedBoolean=!1;oi.prototype.property="";oi.prototype.spaceSeparated=!1;oi.prototype.space=void 0;let bue=0;const zt=Dd(),Vr=Dd(),AN=Dd(),Je=Dd(),Hn=Dd(),Mh=Dd(),di=Dd();function Dd(){return 2**++bue}const TN=Object.freeze(Object.defineProperty({__proto__:null,boolean:zt,booleanish:Vr,commaOrSpaceSeparated:di,commaSeparated:Mh,number:Je,overloadedBoolean:AN,spaceSeparated:Hn},Symbol.toStringTag,{value:"Module"})),c1=Object.keys(TN);class pC extends oi{constructor(t,n,r,a){let i=-1;if(super(t,n),rI(this,"space",a),typeof r=="number")for(;++i<c1.length;){const o=c1[i];rI(this,c1[i],(r&TN[o])===TN[o])}}}pC.prototype.defined=!0;function rI(e,t,n){n&&(e[t]=n)}function Cf(e){const t={},n={};for(const[r,a]of Object.entries(e.properties)){const i=new pC(r,e.transform(e.attributes||{},r),a,e.space);e.mustUseProperty&&e.mustUseProperty.includes(r)&&(i.mustUseProperty=!0),t[r]=i,n[EN(r)]=r,n[EN(i.attribute)]=r}return new ux(t,n,e.space)}const yB=Cf({properties:{ariaActiveDescendant:null,ariaAtomic:Vr,ariaAutoComplete:null,ariaBusy:Vr,ariaChecked:Vr,ariaColCount:Je,ariaColIndex:Je,ariaColSpan:Je,ariaControls:Hn,ariaCurrent:null,ariaDescribedBy:Hn,ariaDetails:null,ariaDisabled:Vr,ariaDropEffect:Hn,ariaErrorMessage:null,ariaExpanded:Vr,ariaFlowTo:Hn,ariaGrabbed:Vr,ariaHasPopup:null,ariaHidden:Vr,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Hn,ariaLevel:Je,ariaLive:null,ariaModal:Vr,ariaMultiLine:Vr,ariaMultiSelectable:Vr,ariaOrientation:null,ariaOwns:Hn,ariaPlaceholder:null,ariaPosInSet:Je,ariaPressed:Vr,ariaReadOnly:Vr,ariaRelevant:null,ariaRequired:Vr,ariaRoleDescription:Hn,ariaRowCount:Je,ariaRowIndex:Je,ariaRowSpan:Je,ariaSelected:Vr,ariaSetSize:Je,ariaSort:null,ariaValueMax:Je,ariaValueMin:Je,ariaValueNow:Je,ariaValueText:null,role:null},transform(e,t){return t==="role"?t:"aria-"+t.slice(4).toLowerCase()}});function bB(e,t){return t in e?e[t]:t}function vB(e,t){return bB(e,t.toLowerCase())}const vue=Cf({attributes:{acceptcharset:"accept-charset",classname:"
760class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Mh,acceptCharset:Hn,accessKey:Hn,action:null,allow:null,allowFullScreen:zt,allowPaymentRequest:zt,allowUserMedia:zt,alt:null,as:null,async:zt,autoCapitalize:null,autoComplete:Hn,autoFocus:zt,autoPlay:zt,blocking:Hn,capture:null,charSet:null,checked:zt,cite:null,className:Hn,cols:Je,colSpan:null,content:null,contentEditable:Vr,controls:zt,controlsList:Hn,coords:Je|Mh,crossOrigin:null,data:null,dateTime:null,decoding:null,default:zt,defer:zt,dir:null,dirName:null,disabled:zt,download:AN,draggable:Vr,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:zt,formTarget:null,headers:Hn,height:Je,hidden:AN,high:Je,href:null,hrefLang:null,htmlFor:Hn,httpEquiv:Hn,id:null,imageSizes:null,imageSrcSet:null,inert:zt,inputMode:null,integrity:null,is:null,isMap:zt,itemId:null,itemProp:Hn,itemRef:Hn,itemScope:zt,itemType:Hn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:zt,low:Je,manifest:null,max:null,maxLength:Je,media:null,method:null,min:null,minLength:Je,multiple:zt,muted:zt,name:null,nonce:null,noModule:zt,noValidate:zt,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:zt,optimum:Je,pattern:null,ping:Hn,placeholder:null,playsInline:zt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:zt,referrerPolicy:null,rel:Hn,required:zt,reversed:zt,rows:Je,rowSpan:Je,sandbox:Hn,scope:null,scoped:zt,seamless:zt,selected:zt,shadowRootClonable:zt,shadowRootDelegatesFocus:zt,shadowRootMode:null,shape:null,size:Je,sizes:null,slot:null,span:Je,spellCheck:Vr,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Je,step:null,style:null,tabIndex:Je,target:null,title:null,translate:null,type:null,typeMustMatch:zt,useMap:null,value:Vr,width:Je,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Hn,axis:null,background:null,bgColor:null,border:Je,borderColor:null,bottomMargin:Je,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:zt,declare:zt,event:null,face:null,frame:null,frameBorder:null,hSpace:Je,leftMargin:Je,link:null,longDesc:null,lowSrc:null,marginHeight:Je,marginWidth:Je,noResize:zt,noHref:zt,noShade:zt,noWrap:zt,object:null,profile:null,prompt:null,rev:null,rightMargin:Je,rules:null,scheme:null,scrolling:Vr,standby:null,summary:null,text:null,topMargin:Je,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Je,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:zt,disableRemotePlayback:zt,prefix:null,property:null,results:Je,security:null,unselectable:null},space:"html",transform:vB}),wue=Cf({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRen
760dering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:di,accentHeight:Je,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Je,amplitude:Je,arabicForm:null,ascent:Je,attributeName:null,attributeType:null,azimuth:Je,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Je,by:null,calcMode:null,capHeight:Je,className:Hn,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRen
760dering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:Je,diffuseConstant:Je,direction:null,display:null,dur:null,divisor:Je,dominantBaseline:null,download:zt,dx:null,dy:null,edgeMode:null,editable:null,elevation:Je,enableBackground:null,end:null,event:null,exponent:Je,externalResourcesRequired:null,fill:null,fillOpacity:Je,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Mh,g2:Mh,glyphName:Mh,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Je,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Je,horizOriginX:Je,horizOriginY:Je,id:null,ideographic:Je,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Je,k:Je,k1:Je,k2:Je,k3:Je,k4:Je,kernelMatrix:di,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Je,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:Je,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:Je,overlineThickness:Je,paintOrder:null,panose1:null,path:null,pathLength:Je,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Hn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Je,pointsAtY:Je,pointsAtZ:Je,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:di,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:di,rev:di,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:di,requiredFeatures:di,requiredFonts:di,requiredFormats:di,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:Je,specularExponent:Je,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Je,strikethroughThickness:Je,string:null,stroke:null,strokeDashArray:di,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Je,strokeOpacity:Je,strokeWidth:null,style:null,surfaceScale:Je,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:di,tabIndex:Je,tableValues:null,target:null,targetX:Je,targetY:Je,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:di,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Je,underlineThickness:Je,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Je,values:null,vAlphabetic:Je,vMathematical:Je,vectorEffect:null,vHanging:Je,vIdeographic:Je,ver
vendor: 2,375 bytes, lines 760-761
760sion:null,vertAdvY:Je,vertOriginX:Je,vertOriginY:Je,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Je,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:bB}),wB=Cf({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,t){return"xlink:"+t.slice(5).toLowerCase()}}),_B=Cf({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:vB}),kB=Cf({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,t){return"xml:"+t.slice(3).toLowerCase()}}),_ue={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},kue=/[A-Z]/g,sI=/-[a-z]/g,jue=/^data[-\w.:]+$/i;function Nue(e,t){const n=EN(t);let r=t,a=oi;if(n in e.normal)return e.property[e.normal[n]];if(n.length>4&&n.slice(0,4)==="data"&&jue.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(sI,Cue);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!sI.test(i)){let o=i.replace(kue,Sue);o.charAt(0)!=="-"&&(o="-"+o),t="data"+o}}a=pC}return new a(r,t)}function Sue(e){return"-"+e.toLowerCase()}function Cue(e){return e.charAt(1).toUpperCase()}const Eue=gB([yB,vue,wB,_B,kB],"html"),xC=gB([yB,wue,wB,_B,kB],"svg");function Aue(e){return e.join(" ").trim()}var Xd={},u1,aI;function Tue(){if(aI)return u1;aI=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,t=/\n/g,n=/^\s*/,r=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,a=/^:\s*/,i=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,o=/^[;\s]*/,l=/^\s+|\s+$/g,c=` 761`,u="/",d="*",h="",f="comment",m="declaration";function x(y,b){if(typeof y!="string")throw new TypeError("First argument must be a string");if(!y)return[];b=b||{};var v=1,w=1;function _(R){var I=R.match(t);I&&(v+=I.length);var $=R.lastIndexOf(c);w=~$?R.length-$:w+R.length}function k(){var R={line:v,column:w};
vendor: 4,911 bytes, line 761
761return function(I){return I.position=new j(R),A(),I}}function j(R){this.start=R,this.end={line:v,column:w},this.source=b.source}j.prototype.content=y;function N(R){var I=new Error(b.source+":"+v+":"+w+": "+R);if(I.reason=R,I.filename=b.source,I.line=v,I.column=w,I.source=y,!b.silent)throw I}function E(R){var I=R.exec(y);if(I){var $=I[0];return _($),y=y.slice($.length),I}}function A(){E(n)}function C(R){var I;for(R=R||[];I=T();)I!==!1&&R.push(I);return R}function T(){var R=k();if(!(u!=y.charAt(0)||d!=y.charAt(1))){for(var I=2;h!=y.charAt(I)&&(d!=y.charAt(I)||u!=y.charAt(I+1));)++I;if(I+=2,h===y.charAt(I-1))return N("End of comment missing");var $=y.slice(2,I-2);return w+=2,_($),y=y.slice(I),w+=2,R({type:f,comment:$})}}function S(){var R=k(),I=E(r);if(I){if(T(),!E(a))return N("property missing ':'");var $=E(i),P=R({type:m,property:g(I[0].replace(e,h)),value:$?g($[0].replace(e,h)):h});return E(o),P}}function O(){var R=[];C(R);for(var I;I=S();)I!==!1&&(R.push(I),C(R));return R}return A(),O()}function g(y){return y?y.replace(l,h):h}return u1=x,u1}var iI;function Oue(){if(iI)return Xd;iI=1;var e=Xd&&Xd.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(Xd,"__esModule",{value:!0}),Xd.default=n;const t=e(Tue());function n(r,a){let i=null;if(!r||typeof r!="string")return i;const o=(0,t.default)(r),l=typeof a=="function";return o.forEach(c=>{if(c.type!=="declaration")return;const{property:u,value:d}=c;l?a(u,d,c):d&&(i=i||{},i[u]=d)}),i}return Xd}var nm={},oI;function Iue(){if(oI)return nm;oI=1,Object.defineProperty(nm,"__esModule",{value:!0}),nm.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,t=/-([a-z])/g,n=/^[^-]+$/,r=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,i=function(u){return!u||n.test(u)||e.test(u)},o=function(u,d){return d.toUpperCase()},l=function(u,d){return"".concat(d,"-")},c=function(u,d){return d===void 0&&(d={}),i(u)?u:(u=u.toLowerCase(),d.reactCompat?u=u.replace(a,l):u=u.replace(r,l),u.replace(t,o))};return nm.camelCase=c,nm}var rm,lI;function Pue(){if(lI)return rm;lI=1;var e=rm&&rm.__importDefault||function(a){return a&&a.__esModule?a:{default:a}},t=e(Oue()),n=Iue();function r(a,i){var o={};return!a||typeof a!="string"||(0,t.default)(a,function(l,c){l&&c&&(o[(0,n.camelCase)(l,i)]=c)}),o}return r.default=r,rm=r,rm}var Rue=Pue();const Due=hl(Rue),jB=NB("end"),gC=NB("start");function NB(e){return t;function t(n){const r=n&&n.position&&n.position[e]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function Mue(e){const t=gC(e),n=jB(e);if(t&&n)return{start:t,end:n}}function Jm(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?cI(e.position):"start"in e||"end"in e?cI(e):"line"in e||"column"in e?ON(e):""}function ON(e){return uI(e&&e.line)+":"+uI(e&&e.column)}function cI(e){return ON(e&&e.start)+"-"+ON(e&&e.end)}function uI(e){return e&&typeof e=="number"?e:1}class xa extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let a="",i={},o=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i={...n}),typeof t=="string"?a=t:!i.cause&&t&&(o=!0,a=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof r=="string"){const c=r.indexOf(":");c===-1?i.ruleId=r:(i.source=r.slice(0,c),i.ruleId=r.slice(c+1))}if(!i.place&&i.ancestors&&i.ancestors){const c=i.ancestors[i.ancestors.length-1];c&&(i.place=c.position)}const l=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=l?l.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=l?l.line:void 0,this.name=Jm(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=o&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}xa.prototype.file="";xa.prototype.name="";xa.prototype.reason="";xa.prototype.message="";xa.prototype.stack="";xa.prototype.column=void 0;xa.prototype.line=void 0;xa.prototype.ancestors=void 0;xa.prototype.cause=void 0;xa.prototype.fatal=void 0;xa.prototype.place=void 0;xa.prototype.ruleId=void 0;xa.prototype.source=void 0;const yC={}.hasOwnProperty,$ue=new Map,Lue=/[A-Z]/g,Fue=new Set(["table","tbody","thead","tfoot","tr"]),Bue=new Set(["td","th"]),SB="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Uue(e,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=Yue(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");
vendor: 5,388 bytes, line 761
761if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=Gue(n,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?xC:Eue,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=CB(a,e,void 0);return i&&typeof i!="string"?i:a.create(e,a.Fragment,{children:i||void 0},void 0)}function CB(e,t,n){if(t.type==="element")return zue(e,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Wue(e,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return Hue(e,t,n);if(t.type==="mdxjsEsm")return Kue(e,t);if(t.type==="root")return Vue(e,t,n);if(t.type==="text")return que(e,t)}function zue(e,t,n){const r=e.schema;let a=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(a=xC,e.schema=a),e.ancestors.push(t);const i=AB(e,t.tagName,!1),o=Zue(e,t);let l=vC(e,t);return Fue.has(t.tagName)&&(l=l.filter(function(c){return typeof c=="string"?!yue(c):!0})),EB(e,o,i,t),bC(o,l),e.ancestors.pop(),e.schema=r,e.create(t,i,o,n)}function Wue(e,t){if(t.data&&t.data.estree&&e.evaluater){const r=t.data.estree.body[0];return r.type,e.evaluater.evaluateExpression(r.expression)}jp(e,t.position)}function Kue(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);jp(e,t.position)}function Hue(e,t,n){const r=e.schema;let a=r;t.name==="svg"&&r.space==="html"&&(a=xC,e.schema=a),e.ancestors.push(t);const i=t.name===null?e.Fragment:AB(e,t.name,!0),o=Xue(e,t),l=vC(e,t);return EB(e,o,i,t),bC(o,l),e.ancestors.pop(),e.schema=r,e.create(t,i,o,n)}function Vue(e,t,n){const r={};return bC(r,vC(e,t)),e.create(t,e.Fragment,r,n)}function que(e,t){return t.value}function EB(e,t,n,r){typeof n!="string"&&n!==e.Fragment&&e.passNode&&(t.node=r)}function bC(e,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(e.children=n)}}function Gue(e,t,n){return r;function r(a,i,o,l){const u=Array.isArray(o.children)?n:t;return l?u(i,o,l):u(i,o)}}function Yue(e,t){return n;function n(r,a,i,o){const l=Array.isArray(i.children),c=gC(r);return t(a,i,o,l,{columnNumber:c?c.column-1:void 0,fileName:e,lineNumber:c?c.line:void 0},void 0)}}function Zue(e,t){const n={};let r,a;for(a in t.properties)if(a!=="children"&&yC.call(t.properties,a)){const i=Jue(e,a,t.properties[a]);if(i){const[o,l]=i;e.tableCellAlignToStyle&&o==="align"&&typeof l=="string"&&Bue.has(t.tagName)?r=l:n[o]=l}}if(r){const i=n.style||(n.style={});i[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function Xue(e,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&e.evaluater){const i=r.data.estree.body[0];i.type;const o=i.expression;o.type;const l=o.properties[0];l.type,Object.assign(n,e.evaluater.evaluateExpression(l.argument))}else jp(e,t.position);else{const a=r.name;let i;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&e.evaluater){const l=r.value.data.estree.body[0];l.type,i=e.evaluater.evaluateExpression(l.expression)}else jp(e,t.position);else i=r.value===null?!0:r.value;n[a]=i}return n}function vC(e,t){const n=[];let r=-1;const a=e.passKeys?new Map:$ue;for(;++r<t.children.length;){const i=t.children[r];let o;if(e.passKeys){const c=i.type==="element"?i.tagName:i.type==="mdxJsxFlowElement"||i.type==="mdxJsxTextElement"?i.name:void 0;if(c){const u=a.get(c)||0;o=c+"-"+u,a.set(c,u+1)}}const l=CB(e,i,o);l!==void 0&&n.push(l)}return n}function Jue(e,t,n){const r=Nue(e.schema,t);if(!(n==null||typeof n=="number"&&Number.isNaN(n))){if(Array.isArray(n)&&(n=r.commaSeparated?fue(n):Aue(n)),r.property==="style"){let a=typeof n=="object"?n:Que(e,String(n));return e.stylePropertyNameCase==="css"&&(a=ede(a)),["style",a]}return[e.elementAttributeNameCase==="react"&&r.space?_ue[r.property]||r.property:r.attribute,n]}}function Que(e,t){try{return Due(t,{reactCompat:!0})}catch(n){if(e.ignoreInvalidStyle)return{};const r=n,a=new xa("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:r,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw a.file=e.filePath||void 0,a.url=SB+"#cannot-parse-style-attribute",a}}function AB(e,t,n){let r;if(!n)r={type:"Literal",value:t};else if(t.includes(".")){const a=t.split(".");let i=-1,o;for(;++i<a.length;){const l=tI(a[i])?{type:"Identifier",name:a[i]}:{type:"Literal",value:a[i]};o=o?{type:"MemberExpression",object:o,property:l,computed:!!(i&&l.type==="Literal"),optional:!1}:l}r=o}else r=tI(t)&&!/^[a-z]/.test(t)?{type:"Identifier",name:t}:{type:"Literal",value:t};if(r.type==="Literal"){const a=r.value;return yC.call(e.components,a)?e.components[a]:a}if(e.evaluater)return e.evaluater.evaluateExpression(r);jp(e)}function jp(e,t){const n=new xa("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:t,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw n.file=e.filePath||void 0,n.url=SB+"#cannot-handle-mdx-estrees-without-createevaluater",n}function ede(e){const t={};let n;for(n in e)yC.call(e,n)&&(t[tde(n)]=e[n]);return t}function tde(e){let t=e.replace(Lue,nde);return t.slice(0,3)==="ms-"&&(t="-"+t),t}
vendor: 15,491 bytes, line 761
761function nde(e){return"-"+e.toLowerCase()}const d1={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},rde={};function wC(e,t){const n=rde,r=typeof n.includeImageAlt=="boolean"?n.includeImageAlt:!0,a=typeof n.includeHtml=="boolean"?n.includeHtml:!0;return TB(e,r,a)}function TB(e,t,n){if(sde(e)){if("value"in e)return e.type==="html"&&!n?"":e.value;if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return dI(e.children,t,n)}return Array.isArray(e)?dI(e,t,n):""}function dI(e,t,n){const r=[];let a=-1;for(;++a<e.length;)r[a]=TB(e[a],t,n);return r.join("")}function sde(e){return!!(e&&typeof e=="object")}const hI=document.createElement("i");function Np(e){const t="&"+e+";";hI.innerHTML=t;const n=hI.textContent;return n.charCodeAt(n.length-1)===59&&e!=="semi"||n===t?!1:n}function gi(e,t,n,r){const a=e.length;let i=0,o;if(t<0?t=-t>a?0:a+t:t=t>a?a:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);i<r.length;)o=r.slice(i,i+1e4),o.unshift(t,0),e.splice(...o),i+=1e4,t+=1e4}function Li(e,t){return e.length>0?(gi(e,e.length,0,t),e):t}const fI={}.hasOwnProperty;function OB(e){const t={};let n=-1;for(;++n<e.length;)ade(t,e[n]);return t}function ade(e,t){let n;for(n in t){const a=(fI.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n];let o;if(i)for(o in i){fI.call(a,o)||(a[o]=[]);const l=i[o];ide(a[o],Array.isArray(l)?l:l?[l]:[])}}}function ide(e,t){let n=-1;const r=[];for(;++n<t.length;)(t[n].add==="after"?e:r).push(t[n]);gi(e,0,0,r)}function IB(e,t){const n=Number.parseInt(e,t);return n<9||n===11||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function bo(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Na=gu(/[A-Za-z]/),sa=gu(/[\dA-Za-z]/),ode=gu(/[#-'*+\--9=?A-Z^-~]/);function lb(e){return e!==null&&(e<32||e===127)}const IN=gu(/\d/),lde=gu(/[\dA-Fa-f]/),cde=gu(/[!-/:-@[-`{-~]/);function ft(e){return e!==null&&e<-2}function on(e){return e!==null&&(e<0||e===32)}function Vt(e){return e===-2||e===-1||e===32}const ru=gu(new RegExp("\\p{P}|\\p{S}","u")),jo=gu(/\s/);function gu(e){return t;function t(n){return n!==null&&n>-1&&e.test(String.fromCharCode(n))}}function Ef(e){const t=[];let n=-1,r=0,a=0;for(;++n<e.length;){const i=e.charCodeAt(n);let o="";if(i===37&&sa(e.charCodeAt(n+1))&&sa(e.charCodeAt(n+2)))a=2;else if(i<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(i))||(o=String.fromCharCode(i));else if(i>55295&&i<57344){const l=e.charCodeAt(n+1);i<56320&&l>56319&&l<57344?(o=String.fromCharCode(i,l),a=1):o="�"}else o=String.fromCharCode(i);o&&(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+a+1,o=""),a&&(n+=a,a=0)}return t.join("")+e.slice(r)}function Bt(e,t,n,r){const a=r?r-1:Number.POSITIVE_INFINITY;let i=0;return o;function o(c){return Vt(c)?(e.enter(n),l(c)):t(c)}function l(c){return Vt(c)&&i++<a?(e.consume(c),l):(e.exit(n),t(c))}}const ude={tokenize:dde};function dde(e){const t=e.attempt(this.parser.constructs.contentInitial,r,a);let n;return t;function r(l){if(l===null){e.consume(l);return}return e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),Bt(e,t,"linePrefix")}function a(l){return e.enter("paragraph"),i(l)}function i(l){const c=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=c),n=c,o(l)}function o(l){if(l===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(l);return}return ft(l)?(e.consume(l),e.exit("chunkText"),i):(e.consume(l),o)}}const hde={tokenize:fde},mI={tokenize:mde};function fde(e){const t=this,n=[];let r=0,a,i,o;return l;function l(w){if(r<n.length){const _=n[r];return t.containerState=_[1],e.attempt(_[0].continuation,c,u)(w)}return u(w)}function c(w){if(r++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,a&&v();const _=t.events.length;let k=_,j;for(;k--;)if(t.events[k][0]==="exit"&&t.events[k][1].type==="chunkFlow"){j=t.events[k][1].end;break}b(r);let N=_;for(;N<t.events.length;)t.events[N][1].end={...j},N++;return gi(t.events,k+1,0,t.events.slice(_)),t.events.length=N,u(w)}return l(w)}function u(w){if(r===n.length){if(!a)return f(w);if(a.currentConstruct&&a.currentConstruct.concrete)return x(w);t.interrupt=!!(a.currentConstruct&&!a._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(mI,d,h)(w)}function d(w){return a&&v(),b(r),f(w)}function h(w){return t.parser.lazy[t.now().line]=r!==n.length,o=t.now().offset,x(w)}function f(w){return t.containerState={},e.attempt(mI,m,x)(w)}function m(w){return r++,n.push([t.currentConstruct,t.containerState]),f(w)}function x(w){if(w===null){a&&v(),b(0),e.consume(w);return}return a=a||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:a,contentType:"flow",previous:i}),g(w)}function g(w){if(w===null){y(e.exit("chunkFlow"),!0),b(0),e.consume(w);return}return ft(w)?(e.consume(w),y(e.exit("chunkFlow")),r=0,t.interrupt=void 0,l):(e.consume(w),g)}function y(w,_){const k=t.sliceStream(w);if(_&&k.push(null),w.previous=i,i&&(i.next=w),i=w,a.defineSkip(w.start),a.write(k),t.parser.lazy[w.start.line]){let j=a.events.length;for(;j--;)if(a.events[j][1].start.offset<o&&(!a.events[j][1].end||a.events[j][1].end.offset>o))return;const N=t.events.length;let E=N,A,C;for(;E--;)if(t.events[E][0]==="exit"&&t.events[E][1].type==="chunkFlow"){if(A){C=t.events[E][1].end;break}A=!0}for(b(r),j=N;j<t.events.length;)t.events[j][1].end={...C},j++;gi(t.events,E+1,0,t.events.slice(N)),t.events.length=j}}function b(w){let _=n.length;for(;_-- >w;){const k=n[_];t.containerState=k[1],k[0].exit.call(t,e)}n.length=w}function v(){a.write([null]),i=void 0,a=void 0,t.containerState._closeFlow=void 0}}function mde(e,t,n){return Bt(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function qh(e){if(e===null||on(e)||jo(e))return 1;if(ru(e))return 2}function h0(e,t,n){const r=[];let a=-1;for(;++a<e.length;){const i=e[a].resolveAll;i&&!r.includes(i)&&(t=i(t,n),r.push(i))}return t}const PN={name:"attention",resolveAll:pde,tokenize:xde};function pde(e,t){let n=-1,r,a,i,o,l,c,u,d;for(;++n<e.length;)if(e[n][0]==="enter"&&e[n][1].type==="attentionSequence"&&e[n][1]._close){for(r=n;r--;)if(e[r][0]==="exit"&&e[r][1].type==="attentionSequence"&&e[r][1]._open&&t.sliceSerialize(e[r][1]).charCodeAt(0)===t.sliceSerialize(e[n][1]).charCodeAt(0)){if((e[r][1]._close||e[n][1]._open)&&(e[n][1].end.offset-e[n][1].start.offset)%3&&!((e[r][1].end.offset-e[r][1].start.offset+e[n][1].end.offset-e[n][1].start.offset)%3))continue;c=e[r][1].end.offset-e[r][1].start.offset>1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1;const h={...e[r][1].end},f={...e[n][1].start};pI(h,-c),pI(f,c),o={type:c>1?"strongSequence":"emphasisSequence",start:h,end:{...e[r][1].end}},l={type:c>1?"strongSequence":"emphasisSequence",start:{...e[n][1].start},end:f},i={type:c>1?"strongText":"emphasisText",start:{...e[r][1].end},end:{...e[n][1].start}},a={type:c>1?"strong":"emphasis",start:{...o.start},end:{...l.end}},e[r][1].end={...o.start},e[n][1].start={...l.end},u=[],e[r][1].end.offset-e[r][1].start.offset&&(u=Li(u,[["enter",e[r][1],t],["exit",e[r][1],t]])),u=Li(u,[["enter",a,t],["enter",o,t],["exit",o,t],["enter",i,t]]),u=Li(u,h0(t.parser.constructs.insideSpan.null,e.slice(r+1,n),t)),u=Li(u,[["exit",i,t],["enter",l,t],["exit",l,t],["exit",a,t]]),e[n][1].end.offset-e[n][1].start.offset?(d=2,u=Li(u,[["enter",e[n][1],t],["exit",e[n][1],t]])):d=0,gi(e,r-1,n-r+3,u),n=r+u.length-d-2;break}}for(n=-1;++n<e.length;)e[n][1].type==="attentionSequence"&&(e[n][1].type="data");return e}function xde(e,t){const n=this.parser.constructs.attentionMarkers.null,r=this.previous,a=qh(r);let i;return o;function o(c){return i=c,e.enter("attentionSequence"),l(c)}function l(c){if(c===i)return e.consume(c),l;const u=e.exit("attentionSequence"),d=qh(c),h=!d||d===2&&a||n.includes(c),f=!a||a===2&&d||n.includes(r);return u._open=!!(i===42?h:h&&(a||!f)),u._close=!!(i===42?f:f&&(d||!h)),t(c)}}function pI(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const gde={name:"autolink",tokenize:yde};function yde(e,t,n){let r=0;return a;function a(m){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(m),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i}function i(m){return Na(m)?(e.consume(m),o):m===64?n(m):u(m)}function o(m){return m===43||m===45||m===46||sa(m)?(r=1,l(m)):u(m)}function l(m){return m===58?(e.consume(m),r=0,c):(m===43||m===45||m===46||sa(m))&&r++<32?(e.consume(m),l):(r=0,u(m))}function c(m){return m===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(m),e.exit("autolinkMarker"),e.exit("autolink"),t):m===null||m===32||m===60||lb(m)?n(m):(e.consume(m),c)}function u(m){return m===64?(e.consume(m),d):ode(m)?(e.consume(m),u):n(m)}function d(m){return sa(m)?h(m):n(m)}function h(m){return m===46?(e.consume(m),r=0,d):m===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(m),e.exit("autolinkMarker"),e.exit("autolink"),t):f(m)}function f(m){if((m===45||sa(m))&&r++<63){const x=m===45?f:h;return e.consume(m),x}return n(m)}}const dx={partial:!0,tokenize:bde};function bde(e,t,n){return r;function r(i){return Vt(i)?Bt(e,a,"linePrefix")(i):a(i)}function a(i){return i===null||ft(i)?t(i):n(i)}}const PB={continuation:{tokenize:wde},exit:_de,name:"blockQuote",tokenize:vde};function vde(e,t,n){const r=this;return a;function a(o){if(o===62){const l=r.containerState;return l.open||(e.enter("blockQuote",{_container:!0}),l.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(o),e.exit("blockQuoteMarker"),i}return n(o)}function i(o){return Vt(o)?(e.enter("blockQuotePrefixWhitespace"),e.consume(o),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(o))}}function wde(e,t,n){const r=this;return a;function a(o){return Vt(o)?Bt(e,i,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):i(o)}function i(o){return e.attempt(PB,t,n)(o)}}function _de(e){e.exit("blockQuote")}const RB={name:"characterEscape",tokenize:kde};function kde(e,t,n){return r;function r(i){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(i),e.exit("escapeMarker"),a}function a(i){return cde(i)?(e.enter("characterEscapeValue"),e.consume(i),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(i)}}const DB={name:"characterReference",tokenize:jde};function jde(e,t,n){const r=this;let a=0,i,o;return l;function l(h){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),c}function c(h){return h===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(h),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),i=31,o=sa,d(h))}function u(h){return h===88||h===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(h),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,o=lde,d):(e.enter("characterReferenceValue"),i=7,o=IN,d(h))}function d(h){if(h===59&&a){const f=e.exit("characterReferenceValue");return o===sa&&!Np(r.sliceSerialize(f))?n(h):(e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),e.exit("characterReference"),t)}return o(h)&&a++<i?(e.consume(h),d):n(h)}}const xI={partial:!0,tokenize:Sde},gI={concrete:!0,name:"codeFenced",tokenize:Nde};function Nde(e,t,n){const r=this,a={partial:!0,tokenize:k};let i=0,o=0,l;return c;function c(j){return u(j)}function u(j){const N=r.events[r.events.length-1];return i=N&&N[1].type==="linePrefix"?N[2].sliceSerialize(N[1],!0).length:0,l=j,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),d(j)}function d(j){return j===l?(o++,e.consume(j),d):o<3?n(j):(e.exit("codeFencedFenceSequence"),Vt(j)?Bt(e,h,"whitespace")(j):h(j))}function h(j){return j===null||ft(j)?(e.exit("codeFencedFence"),r.interrupt?t(j):e.check(xI,g,_)(j)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(j))}function f(j){return j===null||ft(j)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(j)):Vt(j)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Bt(e,m,"whitespace")(j)):j===96&&j===l?n(j):(e.consume(j),f)}function m(j){return j===null||ft(j)?h(j):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),x(j))}function x(j){return j===null||ft(j)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(j)):j===96&&j===l?n(j):(e.consume(j),x)}function g(j){return e.attempt(a,_,y)(j)}function y(j){return e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),b}function b(j){return i>0&&Vt(j)?Bt(e,v,"linePrefix",i+1)(j):v(j)}function v(j){return j===null||ft(j)?e.check(xI,g,_)(j):(e.enter("codeFlowValue"),w(j))}function w(j){return j===null||ft(j)?(e.exit("codeFlowValue"),v(j)):(e.consume(j),w)}function _(j){return e.exit("codeFenced"),t(j)}function k(j,N,E){let A=0;return C;function C(I){return j.enter("lineEnding"),j.consume(I),j.exit("lineEnding"),T}function T(I){return j.enter("codeFencedFence"),Vt(I)?Bt(j,S,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):S(I)}function S(I){return I===l?(j.enter("codeFencedFenceSequence"),O(I)):E(I)}function O(I){return I===l?(A++,j.consume(I),O):A>=o?(j.exit("codeFencedFenceSequence"),Vt(I)?Bt(j,R,"whitespace")(I):R(I)):E(I)}function R(I){return I===null||ft(I)?(j.exit("codeFencedFence"),N(I)):E(I)}}}function Sde(e,t,n){const r=this;return a;function a(o){return o===null?n(o):(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i)}function i(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}const h1={name:"codeIndented",tokenize:Ede},Cde={partial:!0,tokenize:Ade};function Ede(e,t,n){const r=this;return a;function a(u){return e.enter("codeIndented"),Bt(e,i,"linePrefix",5)(u)}function i(u){const d=r.events[r.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?o(u):n(u)}function o(u){return u===null?c(u):ft(u)?e.attempt(Cde,o,c)(u):(e.enter("codeFlowValue"),l(u))}function l(u){return u===null||ft(u)?(e.exit("codeFlowValue"),o(u)):(e.consume(u),l)}function c(u){return e.exit("codeIndented"),t(u)}}function Ade(e,t,n){const r=this;return a;function a(o){return r.parser.lazy[r.now().line]?n(o):ft(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),a):Bt(e,i,"linePrefix",5)(o)}function i(o){const l=r.events[r.events.length-1];return l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(o):ft(o)?a(o):n(o)}}const Tde={name:"codeText",previous:Ide,resolve:Ode,tokenize:Pde};function Ode(e){let t=e.length-4,n=3,r,a;if((e[n][1].type==="lineEnding"||e[n][1].type==="space")&&(e[t][1].type==="lineEnding"||e[t][1].type==="space")){for(r=n;++r<t;)if(e[r][1].type==="codeTextData"){e[n][1].type="codeTextPadding",e[t][1].type="codeTextPadding",n+=2,t-=2;break}}for(r=n-1,t++;++r<=t;)a===void 0?r!==t&&e[r][1].type!=="lineEnding"&&(a=r):(r===t||e[r][1].type==="lineEnding")&&(e[a][1].type="codeTextData",r!==a+2&&(e[a][1].end=e[r-1][1].end,e.splice(a+2,r-a-2),t-=r-a-2,r=a+2),a=void 0);return e}function Ide(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function Pde(e,t,n){let r=0,a,i;return o;
vendor: 5,785 bytes, line 761
761function o(h){return e.enter("codeText"),e.enter("codeTextSequence"),l(h)}function l(h){return h===96?(e.consume(h),r++,l):(e.exit("codeTextSequence"),c(h))}function c(h){return h===null?n(h):h===32?(e.enter("space"),e.consume(h),e.exit("space"),c):h===96?(i=e.enter("codeTextSequence"),a=0,d(h)):ft(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),c):(e.enter("codeTextData"),u(h))}function u(h){return h===null||h===32||h===96||ft(h)?(e.exit("codeTextData"),c(h)):(e.consume(h),u)}function d(h){return h===96?(e.consume(h),a++,d):a===r?(e.exit("codeTextSequence"),e.exit("codeText"),t(h)):(i.type="codeTextData",u(h))}}class Rde{constructor(t){this.left=t?[...t]:[],this.right=[]}get(t){if(t<0||t>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return t<this.left.length?this.left[t]:this.right[this.right.length-t+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(t,n){const r=n??Number.POSITIVE_INFINITY;return r<this.left.length?this.left.slice(t,r):t>this.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const a=n||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return r&&sm(this.left,r),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),sm(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),sm(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t<this.left.length){const n=this.left.splice(t,Number.POSITIVE_INFINITY);sm(this.right,n.reverse())}else{const n=this.right.splice(this.left.length+this.right.length-t,Number.POSITIVE_INFINITY);sm(this.left,n.reverse())}}}function sm(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function MB(e){const t={};let n=-1,r,a,i,o,l,c,u;const d=new Rde(e);for(;++n<d.length;){for(;n in t;)n=t[n];if(r=d.get(n),n&&r[1].type==="chunkFlow"&&d.get(n-1)[1].type==="listItemPrefix"&&(c=r[1]._tokenizer.events,i=0,i<c.length&&c[i][1].type==="lineEndingBlank"&&(i+=2),i<c.length&&c[i][1].type==="content"))for(;++i<c.length&&c[i][1].type!=="content";)c[i][1].type==="chunkText"&&(c[i][1]._isInFirstContentOfListItem=!0,i++);if(r[0]==="enter")r[1].contentType&&(Object.assign(t,Dde(d,n)),n=t[n],u=!0);else if(r[1]._container){for(i=n,a=void 0;i--;)if(o=d.get(i),o[1].type==="lineEnding"||o[1].type==="lineEndingBlank")o[0]==="enter"&&(a&&(d.get(a)[1].type="lineEndingBlank"),o[1].type="lineEnding",a=i);else if(!(o[1].type==="linePrefix"||o[1].type==="listItemIndent"))break;a&&(r[1].end={...d.get(a)[1].start},l=d.slice(a,n),l.unshift(r),d.splice(a,n-a+1,l))}}return gi(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!u}function Dde(e,t){const n=e.get(t)[1],r=e.get(t)[2];let a=t-1;const i=[];let o=n._tokenizer;o||(o=r.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const l=o.events,c=[],u={};let d,h,f=-1,m=n,x=0,g=0;const y=[g];for(;m;){for(;e.get(++a)[1]!==m;);i.push(a),m._tokenizer||(d=r.sliceStream(m),m.next||d.push(null),h&&o.defineSkip(m.start),m._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(d),m._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),h=m,m=m.next}for(m=n;++f<l.length;)l[f][0]==="exit"&&l[f-1][0]==="enter"&&l[f][1].type===l[f-1][1].type&&l[f][1].start.line!==l[f][1].end.line&&(g=f+1,y.push(g),m._tokenizer=void 0,m.previous=void 0,m=m.next);for(o.events=[],m?(m._tokenizer=void 0,m.previous=void 0):y.pop(),f=y.length;f--;){const b=l.slice(y[f],y[f+1]),v=i.pop();c.push([v,v+b.length-1]),e.splice(v,2,b)}for(c.reverse(),f=-1;++f<c.length;)u[x+c[f][0]]=x+c[f][1],x+=c[f][1]-c[f][0]-1;return u}const Mde={resolve:Lde,tokenize:Fde},$de={partial:!0,tokenize:Bde};function Lde(e){return MB(e),e}function Fde(e,t){let n;return r;function r(l){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),a(l)}function a(l){return l===null?i(l):ft(l)?e.check($de,o,i)(l):(e.consume(l),a)}function i(l){return e.exit("chunkContent"),e.exit("content"),t(l)}function o(l){return e.consume(l),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,a}}function Bde(e,t,n){const r=this;return a;function a(o){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),Bt(e,i,"linePrefix")}function i(o){if(o===null||ft(o))return n(o);const l=r.events[r.events.length-1];return!r.parser.constructs.disable.null.includes("codeIndented")&&l&&l[1].type==="linePrefix"&&l[2].sliceSerialize(l[1],!0).length>=4?t(o):e.interrupt(r.parser.constructs.flow,n,t)(o)}}function $B(e,t,n,r,a,i,o,l,c){const u=c||Number.POSITIVE_INFINITY;let d=0;return h;function h(b){return b===60?(e.enter(r),e.enter(a),e.enter(i),e.consume(b),e.exit(i),f):b===null||b===32||b===41||lb(b)?n(b):(e.enter(r),e.enter(o),e.enter(l),e.enter("chunkString",{contentType:"string"}),g(b))}function f(b){return b===62?(e.enter(i),e.consume(b),e.exit(i),e.exit(a),e.exit(r),t):(e.enter(l),e.enter("chunkString",{contentType:"string"}),m(b))}function m(b){return b===62?(e.exit("chunkString"),e.exit(l),f(b)):b===null||b===60||ft(b)?n(b):(e.consume(b),b===92?x:m)}function x(b){return b===60||b===62||b===92?(e.consume(b),m):m(b)}
vendor: 16,428 bytes, line 761
761function g(b){return!d&&(b===null||b===41||on(b))?(e.exit("chunkString"),e.exit(l),e.exit(o),e.exit(r),t(b)):d<u&&b===40?(e.consume(b),d++,g):b===41?(e.consume(b),d--,g):b===null||b===32||b===40||lb(b)?n(b):(e.consume(b),b===92?y:g)}function y(b){return b===40||b===41||b===92?(e.consume(b),g):g(b)}}function LB(e,t,n,r,a,i){const o=this;let l=0,c;return u;function u(m){return e.enter(r),e.enter(a),e.consume(m),e.exit(a),e.enter(i),d}function d(m){return l>999||m===null||m===91||m===93&&!c||m===94&&!l&&"_hiddenFootnoteSupport"in o.parser.constructs?n(m):m===93?(e.exit(i),e.enter(a),e.consume(m),e.exit(a),e.exit(r),t):ft(m)?(e.enter("lineEnding"),e.consume(m),e.exit("lineEnding"),d):(e.enter("chunkString",{contentType:"string"}),h(m))}function h(m){return m===null||m===91||m===93||ft(m)||l++>999?(e.exit("chunkString"),d(m)):(e.consume(m),c||(c=!Vt(m)),m===92?f:h)}function f(m){return m===91||m===92||m===93?(e.consume(m),l++,h):h(m)}}function FB(e,t,n,r,a,i){let o;return l;function l(f){return f===34||f===39||f===40?(e.enter(r),e.enter(a),e.consume(f),e.exit(a),o=f===40?41:f,c):n(f)}function c(f){return f===o?(e.enter(a),e.consume(f),e.exit(a),e.exit(r),t):(e.enter(i),u(f))}function u(f){return f===o?(e.exit(i),c(o)):f===null?n(f):ft(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),Bt(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),d(f))}function d(f){return f===o||f===null||ft(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?h:d)}function h(f){return f===o||f===92?(e.consume(f),d):d(f)}}function zl(e,t){let n;return r;function r(a){return ft(a)?(e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),n=!0,r):Vt(a)?Bt(e,r,n?"linePrefix":"lineSuffix")(a):t(a)}}const Ude={name:"definition",tokenize:Wde},zde={partial:!0,tokenize:Kde};function Wde(e,t,n){const r=this;let a;return i;function i(m){return e.enter("definition"),o(m)}function o(m){return LB.call(r,e,l,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(m)}function l(m){return a=bo(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),m===58?(e.enter("definitionMarker"),e.consume(m),e.exit("definitionMarker"),c):n(m)}function c(m){return on(m)?zl(e,u)(m):u(m)}function u(m){return $B(e,d,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(m)}function d(m){return e.attempt(zde,h,h)(m)}function h(m){return Vt(m)?Bt(e,f,"whitespace")(m):f(m)}function f(m){return m===null||ft(m)?(e.exit("definition"),r.parser.defined.push(a),t(m)):n(m)}}function Kde(e,t,n){return r;function r(l){return on(l)?zl(e,a)(l):n(l)}function a(l){return FB(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(l)}function i(l){return Vt(l)?Bt(e,o,"whitespace")(l):o(l)}function o(l){return l===null||ft(l)?t(l):n(l)}}const Hde={name:"hardBreakEscape",tokenize:Vde};function Vde(e,t,n){return r;function r(i){return e.enter("hardBreakEscape"),e.consume(i),a}function a(i){return ft(i)?(e.exit("hardBreakEscape"),t(i)):n(i)}}const qde={name:"headingAtx",resolve:Gde,tokenize:Yde};function Gde(e,t){let n=e.length-2,r=3,a,i;return e[r][1].type==="whitespace"&&(r+=2),n-2>r&&e[n][1].type==="whitespace"&&(n-=2),e[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&e[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(a={type:"atxHeadingText",start:e[r][1].start,end:e[n][1].end},i={type:"chunkText",start:e[r][1].start,end:e[n][1].end,contentType:"text"},gi(e,r,n-r+1,[["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t]])),e}function Yde(e,t,n){let r=0;return a;function a(d){return e.enter("atxHeading"),i(d)}function i(d){return e.enter("atxHeadingSequence"),o(d)}function o(d){return d===35&&r++<6?(e.consume(d),o):d===null||on(d)?(e.exit("atxHeadingSequence"),l(d)):n(d)}function l(d){return d===35?(e.enter("atxHeadingSequence"),c(d)):d===null||ft(d)?(e.exit("atxHeading"),t(d)):Vt(d)?Bt(e,l,"whitespace")(d):(e.enter("atxHeadingText"),u(d))}function c(d){return d===35?(e.consume(d),c):(e.exit("atxHeadingSequence"),l(d))}function u(d){return d===null||d===35||on(d)?(e.exit("atxHeadingText"),l(d)):(e.consume(d),u)}}const Zde=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],yI=["pre","script","style","textarea"],Xde={concrete:!0,name:"htmlFlow",resolveTo:ehe,tokenize:the},Jde={partial:!0,tokenize:rhe},Qde={partial:!0,tokenize:nhe};function ehe(e){let t=e.length;for(;t--&&!(e[t][0]==="enter"&&e[t][1].type==="htmlFlow"););return t>1&&e[t-2][1].type==="linePrefix"&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function the(e,t,n){const r=this;let a,i,o,l,c;return u;function u(M){return d(M)}function d(M){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(M),h}function h(M){return M===33?(e.consume(M),f):M===47?(e.consume(M),i=!0,g):M===63?(e.consume(M),a=3,r.interrupt?t:D):Na(M)?(e.consume(M),o=String.fromCharCode(M),y):n(M)}function f(M){return M===45?(e.consume(M),a=2,m):M===91?(e.consume(M),a=5,l=0,x):Na(M)?(e.consume(M),a=4,r.interrupt?t:D):n(M)}function m(M){return M===45?(e.consume(M),r.interrupt?t:D):n(M)}function x(M){const z="CDATA[";return M===z.charCodeAt(l++)?(e.consume(M),l===z.length?r.interrupt?t:S:x):n(M)}function g(M){return Na(M)?(e.consume(M),o=String.fromCharCode(M),y):n(M)}function y(M){if(M===null||M===47||M===62||on(M)){const z=M===47,G=o.toLowerCase();return!z&&!i&&yI.includes(G)?(a=1,r.interrupt?t(M):S(M)):Zde.includes(o.toLowerCase())?(a=6,z?(e.consume(M),b):r.interrupt?t(M):S(M)):(a=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(M):i?v(M):w(M))}return M===45||sa(M)?(e.consume(M),o+=String.fromCharCode(M),y):n(M)}function b(M){return M===62?(e.consume(M),r.interrupt?t:S):n(M)}function v(M){return Vt(M)?(e.consume(M),v):C(M)}function w(M){return M===47?(e.consume(M),C):M===58||M===95||Na(M)?(e.consume(M),_):Vt(M)?(e.consume(M),w):C(M)}function _(M){return M===45||M===46||M===58||M===95||sa(M)?(e.consume(M),_):k(M)}function k(M){return M===61?(e.consume(M),j):Vt(M)?(e.consume(M),k):w(M)}function j(M){return M===null||M===60||M===61||M===62||M===96?n(M):M===34||M===39?(e.consume(M),c=M,N):Vt(M)?(e.consume(M),j):E(M)}function N(M){return M===c?(e.consume(M),c=null,A):M===null||ft(M)?n(M):(e.consume(M),N)}function E(M){return M===null||M===34||M===39||M===47||M===60||M===61||M===62||M===96||on(M)?k(M):(e.consume(M),E)}function A(M){return M===47||M===62||Vt(M)?w(M):n(M)}function C(M){return M===62?(e.consume(M),T):n(M)}function T(M){return M===null||ft(M)?S(M):Vt(M)?(e.consume(M),T):n(M)}function S(M){return M===45&&a===2?(e.consume(M),$):M===60&&a===1?(e.consume(M),P):M===62&&a===4?(e.consume(M),H):M===63&&a===3?(e.consume(M),D):M===93&&a===5?(e.consume(M),Z):ft(M)&&(a===6||a===7)?(e.exit("htmlFlowData"),e.check(Jde,Y,O)(M)):M===null||ft(M)?(e.exit("htmlFlowData"),O(M)):(e.consume(M),S)}function O(M){return e.check(Qde,R,Y)(M)}function R(M){return e.enter("lineEnding"),e.consume(M),e.exit("lineEnding"),I}function I(M){return M===null||ft(M)?O(M):(e.enter("htmlFlowData"),S(M))}function $(M){return M===45?(e.consume(M),D):S(M)}function P(M){return M===47?(e.consume(M),o="",F):S(M)}function F(M){if(M===62){const z=o.toLowerCase();return yI.includes(z)?(e.consume(M),H):S(M)}return Na(M)&&o.length<8?(e.consume(M),o+=String.fromCharCode(M),F):S(M)}function Z(M){return M===93?(e.consume(M),D):S(M)}function D(M){return M===62?(e.consume(M),H):M===45&&a===2?(e.consume(M),D):S(M)}function H(M){return M===null||ft(M)?(e.exit("htmlFlowData"),Y(M)):(e.consume(M),H)}function Y(M){return e.exit("htmlFlow"),t(M)}}function nhe(e,t,n){const r=this;return a;function a(o){return ft(o)?(e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i):n(o)}function i(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}function rhe(e,t,n){return r;function r(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),e.attempt(dx,t,n)}}const she={name:"htmlText",tokenize:ahe};function ahe(e,t,n){const r=this;let a,i,o;return l;function l(D){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(D),c}function c(D){return D===33?(e.consume(D),u):D===47?(e.consume(D),k):D===63?(e.consume(D),w):Na(D)?(e.consume(D),E):n(D)}function u(D){return D===45?(e.consume(D),d):D===91?(e.consume(D),i=0,x):Na(D)?(e.consume(D),v):n(D)}function d(D){return D===45?(e.consume(D),m):n(D)}function h(D){return D===null?n(D):D===45?(e.consume(D),f):ft(D)?(o=h,P(D)):(e.consume(D),h)}function f(D){return D===45?(e.consume(D),m):h(D)}function m(D){return D===62?$(D):D===45?f(D):h(D)}function x(D){const H="CDATA[";return D===H.charCodeAt(i++)?(e.consume(D),i===H.length?g:x):n(D)}function g(D){return D===null?n(D):D===93?(e.consume(D),y):ft(D)?(o=g,P(D)):(e.consume(D),g)}function y(D){return D===93?(e.consume(D),b):g(D)}function b(D){return D===62?$(D):D===93?(e.consume(D),b):g(D)}function v(D){return D===null||D===62?$(D):ft(D)?(o=v,P(D)):(e.consume(D),v)}function w(D){return D===null?n(D):D===63?(e.consume(D),_):ft(D)?(o=w,P(D)):(e.consume(D),w)}function _(D){return D===62?$(D):w(D)}function k(D){return Na(D)?(e.consume(D),j):n(D)}function j(D){return D===45||sa(D)?(e.consume(D),j):N(D)}function N(D){return ft(D)?(o=N,P(D)):Vt(D)?(e.consume(D),N):$(D)}function E(D){return D===45||sa(D)?(e.consume(D),E):D===47||D===62||on(D)?A(D):n(D)}function A(D){return D===47?(e.consume(D),$):D===58||D===95||Na(D)?(e.consume(D),C):ft(D)?(o=A,P(D)):Vt(D)?(e.consume(D),A):$(D)}function C(D){return D===45||D===46||D===58||D===95||sa(D)?(e.consume(D),C):T(D)}function T(D){return D===61?(e.consume(D),S):ft(D)?(o=T,P(D)):Vt(D)?(e.consume(D),T):A(D)}function S(D){return D===null||D===60||D===61||D===62||D===96?n(D):D===34||D===39?(e.consume(D),a=D,O):ft(D)?(o=S,P(D)):Vt(D)?(e.consume(D),S):(e.consume(D),R)}function O(D){return D===a?(e.consume(D),a=void 0,I):D===null?n(D):ft(D)?(o=O,P(D)):(e.consume(D),O)}function R(D){return D===null||D===34||D===39||D===60||D===61||D===96?n(D):D===47||D===62||on(D)?A(D):(e.consume(D),R)}function I(D){return D===47||D===62||on(D)?A(D):n(D)}function $(D){return D===62?(e.consume(D),e.exit("htmlTextData"),e.exit("htmlText"),t):n(D)}function P(D){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(D),e.exit("lineEnding"),F}function F(D){return Vt(D)?Bt(e,Z,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(D):Z(D)}function Z(D){return e.enter("htmlTextData"),o(D)}}const _C={name:"labelEnd",resolveAll:che,resolveTo:uhe,tokenize:dhe},ihe={tokenize:hhe},ohe={tokenize:fhe},lhe={tokenize:mhe};function che(e){let t=-1;const n=[];for(;++t<e.length;){const r=e[t][1];if(n.push(e[t]),r.type==="labelImage"||r.type==="labelLink"||r.type==="labelEnd"){const a=r.type==="labelImage"?4:2;r.type="data",t+=a}}return e.length!==n.length&&gi(e,0,e.length,n),e}function uhe(e,t){let n=e.length,r=0,a,i,o,l;for(;n--;)if(a=e[n][1],i){if(a.type==="link"||a.type==="labelLink"&&a._inactive)break;e[n][0]==="enter"&&a.type==="labelLink"&&(a._inactive=!0)}else if(o){if(e[n][0]==="enter"&&(a.type==="labelImage"||a.type==="labelLink")&&!a._balanced&&(i=n,a.type!=="labelLink")){r=2;break}}else a.type==="labelEnd"&&(o=n);const c={type:e[i][1].type==="labelLink"?"link":"image",start:{...e[i][1].start},end:{...e[e.length-1][1].end}},u={type:"label",start:{...e[i][1].start},end:{...e[o][1].end}},d={type:"labelText",start:{...e[i+r+2][1].end},end:{...e[o-2][1].start}};return l=[["enter",c,t],["enter",u,t]],l=Li(l,e.slice(i+1,i+r+3)),l=Li(l,[["enter",d,t]]),l=Li(l,h0(t.parser.constructs.insideSpan.null,e.slice(i+r+4,o-3),t)),l=Li(l,[["exit",d,t],e[o-2],e[o-1],["exit",u,t]]),l=Li(l,e.slice(o+1)),l=Li(l,[["exit",c,t]]),gi(e,i,e.length,l),e}function dhe(e,t,n){const r=this;let a=r.events.length,i,o;for(;a--;)if((r.events[a][1].type==="labelImage"||r.events[a][1].type==="labelLink")&&!r.events[a][1]._balanced){i=r.events[a][1];break}return l;function l(f){return i?i._inactive?h(f):(o=r.parser.defined.includes(bo(r.sliceSerialize({start:i.end,end:r.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),c):n(f)}function c(f){return f===40?e.attempt(ihe,d,o?d:h)(f):f===91?e.attempt(ohe,d,o?u:h)(f):o?d(f):h(f)}function u(f){return e.attempt(lhe,d,h)(f)}function d(f){return t(f)}function h(f){return i._balanced=!0,n(f)}}function hhe(e,t,n){return r;function r(h){return e.enter("resource"),e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),a}function a(h){return on(h)?zl(e,i)(h):i(h)}function i(h){return h===41?d(h):$B(e,o,l,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function o(h){return on(h)?zl(e,c)(h):d(h)}function l(h){return n(h)}function c(h){return h===34||h===39||h===40?FB(e,u,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):d(h)}function u(h){return on(h)?zl(e,d)(h):d(h)}function d(h){return h===41?(e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),e.exit("resource"),t):n(h)}}function fhe(e,t,n){const r=this;return a;function a(l){return LB.call(r,e,i,o,"reference","referenceMarker","referenceString")(l)}function i(l){return r.parser.defined.includes(bo(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(l):n(l)}function o(l){return n(l)}}function mhe(e,t,n){return r;function r(i){return e.enter("reference"),e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),a}function a(i){return i===93?(e.enter("referenceMarker"),e.consume(i),e.exit("referenceMarker"),e.exit("reference"),t):n(i)}}const phe={name:"labelStartImage",resolveAll:_C.resolveAll,tokenize:xhe};function xhe(e,t,n){const r=this;return a;function a(l){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(l),e.exit("labelImageMarker"),i}function i(l){return l===91?(e.enter("labelMarker"),e.consume(l),e.exit("labelMarker"),e.exit("labelImage"),o):n(l)}function o(l){return l===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(l):t(l)}}const ghe={name:"labelStartLink",resolveAll:_C.resolveAll,tokenize:yhe};function yhe(e,t,n){const r=this;return a;function a(o){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(o),e.exit("labelMarker"),e.exit("labelLink"),i}function i(o){return o===94&&"_hiddenFootnoteSupport"in r.parser.constructs?n(o):t(o)}}const f1={name:"lineEnding",tokenize:bhe};function bhe(e,t){return n;function n(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),Bt(e,t,"linePrefix")}}const Ty={name:"thematicBreak",tokenize:vhe};function vhe(e,t,n){let r=0,a;return i;function i(u){return e.enter("thematicBreak"),o(u)}function o(u){return a=u,l(u)}function l(u){return u===a?(e.enter("thematicBreakSequence"),c(u)):r>=3&&(u===null||ft(u))?(e.exit("thematicBreak"),t(u)):n(u)}function c(u){return u===a?(e.consume(u),r++,c):(e.exit("thematicBreakSequence"),Vt(u)?Bt(e,l,"whitespace")(u):l(u))}}const qa={continuation:{tokenize:jhe},exit:She,name:"list",tokenize:khe},whe={partial:!0,tokenize:Che},_he={partial:!0,tokenize:Nhe};function khe(e,t,n){const r=this,a=r.events[r.events.length-1];let i=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,o=0;return l;function l(m){const x=r.containerState.type||(m===42||m===43||m===45?"listUnordered":"listOrdered");if(x==="listUnordered"?!r.containerState.marker||m===r.containerState.marker:IN(m)){if(r.containerState.type||(r.containerState.type=x,e.enter(x,{_container:!0})),x==="listUnordered")return e.enter("listItemPrefix"),m===42||m===45?e.check(Ty,n,u)(m):u(m);if(!r.interrupt||m===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),c(m)}return n(m)}function c(m){return IN(m)&&++o<10?(e.consume(m),c):(!r.interrupt||o<2)&&(r.containerState.marker?m===r.containerState.marker:m===41||m===46)?(e.exit("listItemValue"),u(m)):n(m)}function u(m){return e.enter("listItemMarker"),e.consume(m),e.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||m,e.check(dx,r.interrupt?n:d,e.attempt(whe,f,h))}
vendor: 5,407 bytes, line 761
761function d(m){return r.containerState.initialBlankLine=!0,i++,f(m)}function h(m){return Vt(m)?(e.enter("listItemPrefixWhitespace"),e.consume(m),e.exit("listItemPrefixWhitespace"),f):n(m)}function f(m){return r.containerState.size=i+r.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(m)}}function jhe(e,t,n){const r=this;return r.containerState._closeFlow=void 0,e.check(dx,a,i);function a(l){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,Bt(e,t,"listItemIndent",r.containerState.size+1)(l)}function i(l){return r.containerState.furtherBlankLines||!Vt(l)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(l)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(_he,t,o)(l))}function o(l){return r.containerState._closeFlow=!0,r.interrupt=void 0,Bt(e,e.attempt(qa,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l)}}function Nhe(e,t,n){const r=this;return Bt(e,a,"listItemIndent",r.containerState.size+1);function a(i){const o=r.events[r.events.length-1];return o&&o[1].type==="listItemIndent"&&o[2].sliceSerialize(o[1],!0).length===r.containerState.size?t(i):n(i)}}function She(e){e.exit(this.containerState.type)}function Che(e,t,n){const r=this;return Bt(e,a,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(i){const o=r.events[r.events.length-1];return!Vt(i)&&o&&o[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const bI={name:"setextUnderline",resolveTo:Ehe,tokenize:Ahe};function Ehe(e,t){let n=e.length,r,a,i;for(;n--;)if(e[n][0]==="enter"){if(e[n][1].type==="content"){r=n;break}e[n][1].type==="paragraph"&&(a=n)}else e[n][1].type==="content"&&e.splice(n,1),!i&&e[n][1].type==="definition"&&(i=n);const o={type:"setextHeading",start:{...e[r][1].start},end:{...e[e.length-1][1].end}};return e[a][1].type="setextHeadingText",i?(e.splice(a,0,["enter",o,t]),e.splice(i+1,0,["exit",e[r][1],t]),e[r][1].end={...e[i][1].end}):e[r][1]=o,e.push(["exit",o,t]),e}function Ahe(e,t,n){const r=this;let a;return i;function i(u){let d=r.events.length,h;for(;d--;)if(r.events[d][1].type!=="lineEnding"&&r.events[d][1].type!=="linePrefix"&&r.events[d][1].type!=="content"){h=r.events[d][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||h)?(e.enter("setextHeadingLine"),a=u,o(u)):n(u)}function o(u){return e.enter("setextHeadingLineSequence"),l(u)}function l(u){return u===a?(e.consume(u),l):(e.exit("setextHeadingLineSequence"),Vt(u)?Bt(e,c,"lineSuffix")(u):c(u))}function c(u){return u===null||ft(u)?(e.exit("setextHeadingLine"),t(u)):n(u)}}const The={tokenize:Ohe};function Ohe(e){const t=this,n=e.attempt(dx,r,e.attempt(this.parser.constructs.flowInitial,a,Bt(e,e.attempt(this.parser.constructs.flow,a,e.attempt(Mde,a)),"linePrefix")));return n;function r(i){if(i===null){e.consume(i);return}return e.enter("lineEndingBlank"),e.consume(i),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function a(i){if(i===null){e.consume(i);return}return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),t.currentConstruct=void 0,n}}const Ihe={resolveAll:UB()},Phe=BB("string"),Rhe=BB("text");function BB(e){return{resolveAll:UB(e==="text"?Dhe:void 0),tokenize:t};function t(n){const r=this,a=this.parser.constructs[e],i=n.attempt(a,o,l);return o;function o(d){return u(d)?i(d):l(d)}function l(d){if(d===null){n.consume(d);return}return n.enter("data"),n.consume(d),c}function c(d){return u(d)?(n.exit("data"),i(d)):(n.consume(d),c)}function u(d){if(d===null)return!0;const h=a[d];let f=-1;if(h)for(;++f<h.length;){const m=h[f];if(!m.previous||m.previous.call(r,r.previous))return!0}return!1}}}function UB(e){return t;function t(n,r){let a=-1,i;for(;++a<=n.length;)i===void 0?n[a]&&n[a][1].type==="data"&&(i=a,a++):(!n[a]||n[a][1].type!=="data")&&(a!==i+2&&(n[i][1].end=n[a-1][1].end,n.splice(i+2,a-i-2),a=i+2),i=void 0);return e?e(n,r):n}}function Dhe(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||e[n][1].type==="lineEnding")&&e[n-1][1].type==="data"){const r=e[n-1][1],a=t.sliceStream(r);let i=a.length,o=-1,l=0,c;for(;i--;){const u=a[i];if(typeof u=="string"){for(o=u.length;u.charCodeAt(o-1)===32;)l++,o--;if(o)break;o=-1}else if(u===-2)c=!0,l++;else if(u!==-1){i++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(l=0),l){const u={type:n===e.length||c||l<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:i?o:r.start._bufferIndex+o,_index:r.start._index+i,line:r.end.line,column:r.end.column-l,offset:r.end.offset-l},end:{...r.end}};r.end={...u.start},r.start.offset===r.end.offset?Object.assign(r,u):(e.splice(n,0,["enter",u,t],["exit",u,t]),n+=2)}n++}return e}const Mhe={42:qa,43:qa,45:qa,48:qa,49:qa,50:qa,51:qa,52:qa,53:qa,54:qa,55:qa,56:qa,57:qa,62:PB},$he={91:Ude},Lhe={[-2]:h1,[-1]:h1,32:h1},Fhe={35:qde,42:Ty,45:[bI,Ty],60:Xde,61:bI,95:Ty,96:gI,126:gI},Bhe={38:DB,92:RB},Uhe={[-5]:f1,[-4]:f1,[-3]:f1,33:phe,38:DB,42:PN,60:[gde,she],91:ghe,92:[Hde,RB],93:_C,95:PN,96:Tde},zhe={null:[PN,Ihe]},Whe={null:[42,95]},Khe={null:[]},Hhe=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:Whe,contentInitial:$he,disable:Khe,document:Mhe,flow:Fhe,flowInitial:Lhe,insideSpan:zhe,string:Bhe,text:Uhe},Symbol.toStringTag,{value:"Module"}));function Vhe(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,c
vendor: 14,731 bytes, lines 761-763
761olumn:n&&n.column||1,offset:n&&n.offset||0};const a={},i=[];let o=[],l=[];const c={attempt:N(k),check:N(j),consume:v,enter:w,exit:_,interrupt:N(j,{interrupt:!0})},u={code:null,containerState:{},defineSkip:g,events:[],now:x,parser:e,previous:null,sliceSerialize:f,sliceStream:m,write:h};let d=t.tokenize.call(u,c);return t.resolveAll&&i.push(t),u;function h(T){return o=Li(o,T),y(),o[o.length-1]!==null?[]:(E(t,0),u.events=h0(i,u.events,u),u.events)}function f(T,S){return Ghe(m(T),S)}function m(T){return qhe(o,T)}function x(){const{_bufferIndex:T,_index:S,line:O,column:R,offset:I}=r;return{_bufferIndex:T,_index:S,line:O,column:R,offset:I}}function g(T){a[T.line]=T.column,C()}function y(){let T;for(;r._index<o.length;){const S=o[r._index];if(typeof S=="string")for(T=r._index,r._bufferIndex<0&&(r._bufferIndex=0);r._index===T&&r._bufferIndex<S.length;)b(S.charCodeAt(r._bufferIndex));else b(S)}}function b(T){d=d(T)}function v(T){ft(T)?(r.line++,r.column=1,r.offset+=T===-3?2:1,C()):T!==-1&&(r.column++,r.offset++),r._bufferIndex<0?r._index++:(r._bufferIndex++,r._bufferIndex===o[r._index].length&&(r._bufferIndex=-1,r._index++)),u.previous=T}function w(T,S){const O=S||{};return O.type=T,O.start=x(),u.events.push(["enter",O,u]),l.push(O),O}function _(T){const S=l.pop();return S.end=x(),u.events.push(["exit",S,u]),S}function k(T,S){E(T,S.from)}function j(T,S){S.restore()}function N(T,S){return O;function O(R,I,$){let P,F,Z,D;return Array.isArray(R)?Y(R):"tokenize"in R?Y([R]):H(R);function H(te){return re;function re(L){const q=L!==null&&te[L],me=L!==null&&te.null,ee=[...Array.isArray(q)?q:q?[q]:[],...Array.isArray(me)?me:me?[me]:[]];return Y(ee)(L)}}function Y(te){return P=te,F=0,te.length===0?$:M(te[F])}function M(te){return re;function re(L){return D=A(),Z=te,te.partial||(u.currentConstruct=te),te.name&&u.parser.constructs.disable.null.includes(te.name)?G():te.tokenize.call(S?Object.assign(Object.create(u),S):u,c,z,G)(L)}}function z(te){return T(Z,D),I}function G(te){return D.restore(),++F<P.length?M(P[F]):$}}}function E(T,S){T.resolveAll&&!i.includes(T)&&i.push(T),T.resolve&&gi(u.events,S,u.events.length-S,T.resolve(u.events.slice(S),u)),T.resolveTo&&(u.events=T.resolveTo(u.events,u))}function A(){const T=x(),S=u.previous,O=u.currentConstruct,R=u.events.length,I=Array.from(l);return{from:R,restore:$};function $(){r=T,u.previous=S,u.currentConstruct=O,u.events.length=R,l=I,C()}}function C(){r.line in a&&r.column<2&&(r.column=a[r.line],r.offset+=a[r.line]-1)}}function qhe(e,t){const n=t.start._index,r=t.start._bufferIndex,a=t.end._index,i=t.end._bufferIndex;let o;if(n===a)o=[e[n].slice(r,i)];else{if(o=e.slice(n,a),r>-1){const l=o[0];typeof l=="string"?o[0]=l.slice(r):o.shift()}i>0&&o.push(e[a].slice(0,i))}return o}function Ghe(e,t){let n=-1;const r=[];let a;for(;++n<e.length;){const i=e[n];let o;if(typeof i=="string")o=i;else switch(i){case-5:{o="\r";break}case-4:{o=` 762`;break}case-3:{o=`\r 763`;break}case-2:{o=t?" ":" ";break}case-1:{if(!t&&a)continue;o=" ";break}default:o=String.fromCharCode(i)}a=i===-2,r.push(o)}return r.join("")}function Yhe(e){const r={constructs:OB([Hhe,...(e||{}).extensions||[]]),content:a(ude),defined:[],document:a(hde),flow:a(The),lazy:{},string:a(Phe),text:a(Rhe)};return r;function a(i){return o;function o(l){return Vhe(r,i,l)}}}function Zhe(e){for(;!MB(e););return e}const vI=/[\0\t\n\r]/g;function Xhe(){let e=1,t="",n=!0,r;return a;function a(i,o,l){const c=[];let u,d,h,f,m;for(i=t+(typeof i=="string"?i.toString():new TextDecoder(o||void 0).decode(i)),h=0,t="",n&&(i.charCodeAt(0)===65279&&h++,n=void 0);h<i.length;){if(vI.lastIndex=h,u=vI.exec(i),f=u&&u.index!==void 0?u.index:i.length,m=i.charCodeAt(f),!u){t=i.slice(h);break}if(m===10&&h===f&&r)c.push(-3),r=void 0;else switch(r&&(c.push(-5),r=void 0),h<f&&(c.push(i.slice(h,f)),e+=f-h),m){case 0:{c.push(65533),e++;break}case 9:{for(d=Math.ceil(e/4)*4,c.push(-2);e++<d;)c.push(-1);break}case 10:{c.push(-4),e=1;break}default:r=!0,e=1}h=f+1}return l&&(r&&c.push(-5),t&&c.push(t),c.push(null)),c}}const Jhe=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Qhe(e){return e.replace(Jhe,efe)}function efe(e,t,n){if(t)return t;if(n.charCodeAt(0)===35){const a=n.charCodeAt(1),i=a===120||a===88;return IB(n.slice(i?2:1),i?16:10)}return Np(n)||e}const zB={}.hasOwnProperty;function tfe(e,t,n){return t&&typeof t=="object"&&(n=t,t=void 0),nfe(n)(Zhe(Yhe(n).document().write(Xhe()(e,t,!0))))}function nfe(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(Ne),autolinkProtocol:A,autolinkEmail:A,atxHeading:i(ae),blockQuote:i(me),characterEscape:A,characterReference:A,codeFenced:i(ee),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:i(ee,o),codeText:i(ne,o),codeTextData:A,data:A,codeFlowValue:A,definition:i(X),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:i(he),hardBreakEscape:i(je),hardBreakTrailing:i(je),htmlFlow:i($e,o),htmlFlowData:A,htmlText:i($e,o),htmlTextData:A,image:i(J),label:o,link:i(Ne),listItem:i(Me),listItemValue:f,listOrdered:i(ve,h),listUnordered:i(ve),paragraph:i(Xe),reference:M,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:i(ae),strong:i(ze),thematicBreak:i(tt)},exit:{atxHeading:c(),atxHeadingSequence:k,autolink:c(),autolinkEmail:q,autolinkProtocol:L,blockQuote:c(),characterEscapeValue:C,characterReferenceMarkerHexadecimal:G,characterReferenceMarkerNumeric:G,characterReferenceValue:te,characterReference:re,codeFenced:c(y),codeFencedFence:g,codeFencedFenceInfo:m,codeFencedFenceMeta:x,codeFlowValue:C,codeIndented:c(b),codeText:c(I),codeTextData:C,data:C,definition:c(),definitionDestinationString:_,definitionLabelString:v,definitionTitleString:w,emphasis:c(),hardBreakEscape:c(S),hardBreakTrailing:c(S),htmlFlow:c(O),htmlFlowData:C,htmlText:c(R),htmlTextData:C,image:c(P),label:Z,labelText:F,lineEnding:T,link:c($),listItem:c(),listOrdered:c(),listUnordered:c(),paragraph:c(),referenceString:z,resourceDestinationString:D,resourceTitleString:H,resource:Y,setextHeading:c(E),setextHeadingLineSequence:N,setextHeadingText:j,strong:c(),thematicBreak:c()}};WB(t,(e||{}).mdastExtensions||[]);const n={};return r;function r(fe){let U={type:"root",children:[]};const ce={stack:[U],tokenStack:[],config:t,enter:l,exit:u,buffer:o,resume:d,data:n},ue=[];let Ee=-1;for(;++Ee<fe.length;)if(fe[Ee][1].type==="listOrdered"||fe[Ee][1].type==="listUnordered")if(fe[Ee][0]==="enter")ue.push(Ee);else{const bt=ue.pop();Ee=a(fe,bt,Ee)}for(Ee=-1;++Ee<fe.length;){const bt=t[fe[Ee][0]];zB.call(bt,fe[Ee][1].type)&&bt[fe[Ee][1].type].call(Object.assign({sliceSerialize:fe[Ee][2].sliceSerialize},ce),fe[Ee][1])}if(ce.tokenStack.length>0){const bt=ce.tokenStack[ce.tokenStack.length-1];(bt[1]||wI).call(ce,void 0,bt[0])}for(U.position={start:kc(fe.length>0?fe[0][1].start:{line:1,column:1,offset:0}),end:kc(fe.length>0?fe[fe.length-2][1].end:{line:1,column:1,offset:0})},Ee=-1;++Ee<t.transforms.length;)U=t.transforms[Ee](U)||U;return U}function a(fe,U,ce){let ue=U-1,Ee=-1,bt=!1,Ze,vt,Ot,It;for(;++ue<=ce;){const Ut=fe[ue];switch(Ut[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Ut[0]==="enter"?Ee++:Ee--,It=void 0;break}case"lineEndingBlank":{Ut[0]==="enter"&&(Ze&&!It&&!Ee&&!Ot&&(Ot=ue),It=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:It=void 0}if(!Ee&&Ut[0]==="enter"&&Ut[1].type==="listItemPrefix"||Ee===-1&&Ut[0]==="exit"&&(Ut[1].type==="listUnordered"||Ut[1].type==="listOrdered")){if(Ze){let Lr=ue;for(vt=void 0;Lr--;){const en=fe[Lr];if(en[1].type==="lineEnding"||en[1].type==="lineEndingBlank"){if(en[0]==="exit")continue;vt&&(fe[vt][1].type="lineEndingBlank",bt=!0),en[1].type="lineEnding",vt=Lr}else if(!(en[1].type==="linePrefix"||en[1].type==="blockQuotePrefix"||en[1].type==="blockQuotePrefixWhitespace"||en[1].type==="blockQuoteMarker"||en[1].type==="listItemIndent"))break}Ot&&(!vt||Ot<vt)&&(Ze._spread=!0),Ze.end=Object.assign({},vt?fe[vt][1].start:Ut[1].end),fe.splice(vt||ue,0,["exit",Ze,Ut[2]]),ue++,ce++}if(Ut[1].type==="listItemPrefix"){const Lr={type:"listItem",_spread:!1,start:Object.assign({},Ut[1].start),end:void 0};Ze=Lr,fe.splice(ue,0,["enter",Lr,Ut[2]]),ue++,ce++,Ot=void 0,It=!0}}}return fe[U][1]._spread=bt,ce}function i(fe,U){return ce;function ce(ue){l.call(this,fe(ue),ue),U&&U.call(this,ue)}}function o(){this.stack.push({type:"fragment",children:[]})}function l(fe,U,ce){this.stack[this.stack.length-1].children.push(fe),this.stack.push(fe),this.tokenStack.push([U,ce||void 0]),fe.position={start:kc(U.start),end:void 0}}function c(fe){return U;function U(ce){fe&&fe.call(this,ce),u.call(this,ce)}}function u(fe,U){const ce=this.stack.pop(),ue=this.tokenStack.pop();if(ue)ue[0].type!==fe.type&&(U?U.call(this,fe,ue[0]):(ue[1]||wI).call(this,fe,ue[0]));else throw new Error("Cannot close `"+fe.type+"` ("+Jm({start:fe.start,end:fe.end})+"): itâs not open");ce.position.end=kc(fe.end)}function d(){return wC(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(fe){if(this.data.expectingFirstListItemValue){const U=this.stack[this.stack.length-2];U.start=Number.parseInt(this.sliceSerialize(fe),10),this.data.expectingFirstListItemValue=void 0}}function m(){const fe=this.resume(),U=this.stack[this.stack.length-1];U.lang=fe}function x(){const fe=this.resume(),U=this.stack[this.stack.length-1];U.meta=fe}function g(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function y(){const fe=this.resume(),U=this.stack[this.stack.length-1];U.value=fe.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const fe=this.resume(),U=this.stack[this.stack.length-1];U.value=fe.replace(/(\r?\n|\r)$/g,"")}function v(fe){const U=this.resume(),ce=this.stack[this.stack.length-1];ce.label=U,ce.identifier=bo(this.sliceSerialize(fe)).toLowerCase()}function w(){const fe=this.resume(),U=this.stack[this.stack.length-1];U.title=fe}function _(){const fe=this.resume(),U=this.stack[this.stack.length-1];U.url=fe}function k(fe){const U=this.stack[this.stack.length-1];if(!U.depth){const ce=this.sliceSerialize(fe).length;U.depth=ce}}function j(){this.data.setextHeadingSlurpLineEnding=!0}function N(fe){const U=this.stack[this.stack.length-1];U.depth=this.sliceSerialize(fe).codePointAt(0)===61?1:2}function E(){this.data.setextHeadingSlurpLineEnding=void 0}function A(fe){const ce=this.stack[this.stack.length-1].children;let ue=ce[ce.length-1];(!ue||ue.type!=="text")&&(ue=Fe(),ue.position={start:kc(fe.start),end:void 0},ce.push(ue)),this.stack.push(ue)}function C(fe){const U=this.stack.pop();U.value+=this.sliceSerialize(fe),U.position.end=kc(fe.end)}function T(fe){const U=this.stack[this.stack.length-1];if(this.data.atHardBreak){const ce=U.children[U.children.length-1];ce.position.end=kc(fe.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(U.type)&&(A.call(this,fe),C.call(this,fe))}function S(){this.data.atHardBreak=!0}function O(){const fe=this.resume(),U=this.stack[this.stack.length-1];U.value=fe}function R(){const fe=this.resume(),U=this.stack[this.stack.length-1];U.value=fe}function I(){const fe=this.resume(),U=this.stack[this.stack.length-1];U.value=fe}function $(){const fe=this.stack[this.stack.length-1];if(this.data.inReference){const U=this.data.referenceType||"shortcut";fe.type+="Reference",fe.referenceType=U,delete fe.url,delete fe.title}else delete fe.identifier,delete fe.label;this.data.referenceType=void 0}function P(){const fe=this.stack[this.stack.length-1];if(this.data.inReference){const U=this.data.referenceType||"shortcut";fe.type+="Reference",fe.referenceType=U,delete fe.url,delete fe.title}else delete fe.identifier,delete fe.label;this.data.referenceType=void 0}function F(fe){const U=this.sliceSerialize(fe),ce=this.stack[this.stack.length-2];ce.label=Qhe(U),ce.identifier=bo(U).toLowerCase()}function Z(){const fe=this.stack[this.stack.length-1],U=this.resume(),ce=this.stack[this.stack.length-1];if(this.data.inReference=!0,ce.type==="link"){const ue=fe.children;ce.children=ue}else ce.alt=U}function D(){const fe=this.resume(),U=this.stack[this.stack.length-1];U.url=fe}function H(){const fe=this.resume(),U=this.stack[this.stack.length-1];U.title=fe}function Y(){this.data.inReference=void 0}function M(){this.data.referenceType="collapsed"}function z(fe){const U=this.resume(),ce=this.stack[this.stack.length-1];ce.label=U,ce.identifier=bo(this.sliceSerialize(fe)).toLowerCase(),this.data.referenceType="full"}function G(fe){this.data.characterReferenceType=fe.type}function te(fe){const U=this.sliceSerialize(fe),ce=this.data.characterReferenceType;let ue;ce?(ue=IB(U,ce==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ue=Np(U);const Ee=this.stack[this.stack.length-1];Ee.value+=ue}function re(fe){const U=this.stack.pop();U.position.end=kc(fe.end)}function L(fe){C.call(this,fe);const U=this.stack[this.stack.length-1];U.url=this.sliceSerialize(fe)}function q(fe){C.call(this,fe);const U=this.stack[this.stack.length-1];U.url="mailto:"+this.sliceSerialize(fe)}function me(){return{type:"blockquote",children:[]}}function ee(){return{type:"code",lang:null,meta:null,value:""}}function ne(){return{type:"inlineCode",value:""}}function X(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function he(){return{type:"emphasis",children:[]}}function ae(){return{type:"heading",depth:0,children:[]}}function je(){return{type:"break"}}function $e(){return{type:"html",value:""}}function J(){return{type:"image",title:null,url:"",alt:null}}function Ne(){return{type:"link",title:null,url:"",children:[]}}function ve(fe){return{type:"list",ordered:fe.type==="listOrdered",start:null,spread:fe._spread,children:[]}}function Me(fe){return{type:"listItem",spread:fe._spread,checked:null,children:[]}}function Xe(){return{type:"paragraph",children:[]}}function ze(){return{type:"strong",children:[]}}function Fe(){return{type:"text",value:""}}function tt(){return{type:"thematicBreak"}}}function kc(e){return{line:e.line,column:e.column,offset:e.offset}}function WB(e,t){let n=-1;for(;++n<t.length;){const r=t[n];Array.isArray(r)?WB(e,r):rfe(e,r)}}function rfe(e,t){let n;for(n in t)if(zB.call(t,n))switch(n){case"canContainEols":{const r=t[n];r&&e[n].push(...r);break}case"transforms":{const r=t[n];r&&e[n].push(...r);break}case"enter":case"exit":{const r=t[n];r&&Object.assign(e[n],r);break}}}function wI(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+Jm({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+Jm({start:t.start,end:t.end}
vendor: 4,533 bytes, lines 763-767
763)+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+Jm({start:t.start,end:t.end})+") is still open")}function sfe(e){const t=this;t.parser=n;function n(r){return tfe(r,{...t.data("settings"),...e,extensions:t.data("micromarkExtensions")||[],mdastExtensions:t.data("fromMarkdownExtensions")||[]})}}function afe(e,t){const n={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(t),!0)};return e.patch(t,n),e.applyData(t,n)}function ife(e,t){const n={type:"element",tagName:"br",properties:{},children:[]};return e.patch(t,n),[e.applyData(t,n),{type:"text",value:` 764`}]}function ofe(e,t){const n=t.value?t.value+` 765`:"",r={},a=t.lang?t.lang.split(/\s+/):[];a.length>0&&(r.className=["language-"+a[0]]);let i={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(i.data={meta:t.meta}),e.patch(t,i),i=e.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},e.patch(t,i),i}function lfe(e,t){const n={type:"element",tagName:"del",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function cfe(e,t){const n={type:"element",tagName:"em",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function ufe(e,t){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),a=Ef(r.toLowerCase()),i=e.footnoteOrder.indexOf(r);let o,l=e.footnoteCounts.get(r);l===void 0?(l=0,e.footnoteOrder.push(r),o=e.footnoteOrder.length):o=i+1,l+=1,e.footnoteCounts.set(r,l);const c={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+a,id:n+"fnref-"+a+(l>1?"-"+l:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(o)}]};e.patch(t,c);const u={type:"element",tagName:"sup",properties:{},children:[c]};return e.patch(t,u),e.applyData(t,u)}function dfe(e,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function hfe(e,t){if(e.options.allowDangerousHtml){const n={type:"raw",value:t.value};return e.patch(t,n),e.applyData(t,n)}}function KB(e,t){const n=t.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+r}];const a=e.all(t),i=a[0];i&&i.type==="text"?i.value="["+i.value:a.unshift({type:"text",value:"["});const o=a[a.length-1];return o&&o.type==="text"?o.value+=r:a.push({type:"text",value:r}),a}function ffe(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return KB(e,t);const a={src:Ef(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(a.title=r.title);const i={type:"element",tagName:"img",properties:a,children:[]};return e.patch(t,i),e.applyData(t,i)}function mfe(e,t){const n={src:Ef(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return e.patch(t,r),e.applyData(t,r)}function pfe(e,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};e.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return e.patch(t,r),e.applyData(t,r)}function xfe(e,t){const n=String(t.identifier).toUpperCase(),r=e.definitionById.get(n);if(!r)return KB(e,t);const a={href:Ef(r.url||"")};r.title!==null&&r.title!==void 0&&(a.title=r.title);const i={type:"element",tagName:"a",properties:a,children:e.all(t)};return e.patch(t,i),e.applyData(t,i)}function gfe(e,t){const n={href:Ef(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function yfe(e,t,n){const r=e.all(t),a=n?bfe(n):HB(t),i={},o=[];if(typeof t.checked=="boolean"){const d=r[0];let h;d&&d.type==="element"&&d.tagName==="p"?h=d:(h={type:"element",tagName:"p",properties:{},children:[]},r.unshift(h)),h.children.length>0&&h.children.unshift({type:"text",value:" "}),h.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let l=-1;for(;++l<r.length;){const d=r[l];(a||l!==0||d.type!=="element"||d.tagName!=="p")&&o.push({type:"text",value:` 766`}),d.type==="element"&&d.tagName==="p"&&!a?o.push(...d.children):o.push(d)}const c=r[r.length-1];c&&(a||c.type!=="element"||c.tagName!=="p")&&o.push({type:"text",value:` 767`});const u={type:"element",tagName:"li",properties:i,children:o};
vendor: 3,267 bytes, line 767
767return e.patch(t,u),e.applyData(t,u)}function bfe(e){let t=!1;if(e.type==="list"){t=e.spread||!1;const n=e.children;let r=-1;for(;!t&&++r<n.length;)t=HB(n[r])}return t}function HB(e){const t=e.spread;return t??e.children.length>1}function vfe(e,t){const n={},r=e.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++a<r.length;){const o=r[a];if(o.type==="element"&&o.tagName==="li"&&o.properties&&Array.isArray(o.properties.className)&&o.properties.className.includes("task-list-item")){n.className=["contains-task-list"];break}}const i={type:"element",tagName:t.ordered?"ol":"ul",properties:n,children:e.wrap(r,!0)};return e.patch(t,i),e.applyData(t,i)}function wfe(e,t){const n={type:"element",tagName:"p",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function _fe(e,t){const n={type:"root",children:e.wrap(e.all(t))};return e.patch(t,n),e.applyData(t,n)}function kfe(e,t){const n={type:"element",tagName:"strong",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}function jfe(e,t){const n=e.all(t),r=n.shift(),a=[];if(r){const o={type:"element",tagName:"thead",properties:{},children:e.wrap([r],!0)};e.patch(t.children[0],o),a.push(o)}if(n.length>0){const o={type:"element",tagName:"tbody",properties:{},children:e.wrap(n,!0)},l=gC(t.children[1]),c=jB(t.children[t.children.length-1]);l&&c&&(o.position={start:l,end:c}),a.push(o)}const i={type:"element",tagName:"table",properties:{},children:e.wrap(a,!0)};return e.patch(t,i),e.applyData(t,i)}function Nfe(e,t,n){const r=n?n.children:void 0,i=(r?r.indexOf(t):1)===0?"th":"td",o=n&&n.type==="table"?n.align:void 0,l=o?o.length:t.children.length;let c=-1;const u=[];for(;++c<l;){const h=t.children[c],f={},m=o?o[c]:void 0;m&&(f.align=m);let x={type:"element",tagName:i,properties:f,children:[]};h&&(x.children=e.all(h),e.patch(h,x),x=e.applyData(h,x)),u.push(x)}const d={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(t,d),e.applyData(t,d)}function Sfe(e,t){const n={type:"element",tagName:"td",properties:{},children:e.all(t)};return e.patch(t,n),e.applyData(t,n)}const _I=9,kI=32;function Cfe(e){const t=String(e),n=/\r?\n|\r/g;let r=n.exec(t),a=0;const i=[];for(;r;)i.push(jI(t.slice(a,r.index),a>0,!0),r[0]),a=r.index+r[0].length,r=n.exec(t);return i.push(jI(t.slice(a),a>0,!1)),i.join("")}function jI(e,t,n){let r=0,a=e.length;if(t){let i=e.codePointAt(r);for(;i===_I||i===kI;)r++,i=e.codePointAt(r)}if(n){let i=e.codePointAt(a-1);for(;i===_I||i===kI;)a--,i=e.codePointAt(a-1)}return a>r?e.slice(r,a):""}function Efe(e,t){const n={type:"text",value:Cfe(String(t.value))};return e.patch(t,n),e.applyData(t,n)}function Afe(e,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(t,n),e.applyData(t,n)}const Tfe={blockquote:afe,break:ife,code:ofe,delete:lfe,emphasis:cfe,footnoteReference:ufe,heading:dfe,html:hfe,imageReference:ffe,image:mfe,inlineCode:pfe,linkReference:xfe,link:gfe,listItem:yfe,list:vfe,paragraph:wfe,root:_fe,strong:kfe,table:jfe,tableCell:Sfe,tableRow:Nfe,text:Efe,thematicBreak:Afe,toml:xg,yaml:xg,definition:xg,footnoteDefinition:xg};function xg(){}const VB=-1,f0=0,Qm=1,cb=2,kC=3,jC=4,NC=5,SC=6,qB=7,GB=8,Ofe=typeof self=="object"?self:globalThis,NI=(e,t)=>
vendor: 4,507 bytes, line 767
767{switch(e){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+e)}return new Ofe[e](t)},Ife=(e,t)=>{const n=(a,i)=>(e.set(i,a),a),r=a=>{if(e.has(a))return e.get(a);const[i,o]=t[a];switch(i){case f0:case VB:return n(o,a);case Qm:{const l=n([],a);for(const c of o)l.push(r(c));return l}case cb:{const l=n({},a);for(const[c,u]of o)l[r(c)]=r(u);return l}case kC:return n(new Date(o),a);case jC:{const{source:l,flags:c}=o;return n(new RegExp(l,c),a)}case NC:{const l=n(new Map,a);for(const[c,u]of o)l.set(r(c),r(u));return l}case SC:{const l=n(new Set,a);for(const c of o)l.add(r(c));return l}case qB:{const{name:l,message:c}=o;return n(NI(l,c),a)}case GB:return n(BigInt(o),a);case"BigInt":return n(Object(BigInt(o)),a);case"ArrayBuffer":return n(new Uint8Array(o).buffer,o);case"DataView":{const{buffer:l}=new Uint8Array(o);return n(new DataView(l),o)}}return n(NI(i,o),a)};return r},SI=e=>Ife(new Map,e)(0),Jd="",{toString:Pfe}={},{keys:Rfe}=Object,am=e=>{const t=typeof e;if(t!=="object"||!e)return[f0,t];const n=Pfe.call(e).slice(8,-1);switch(n){case"Array":return[Qm,Jd];case"Object":return[cb,Jd];case"Date":return[kC,Jd];case"RegExp":return[jC,Jd];case"Map":return[NC,Jd];case"Set":return[SC,Jd];case"DataView":return[Qm,n]}return n.includes("Array")?[Qm,n]:n.includes("Error")?[qB,n]:[cb,n]},gg=([e,t])=>e===f0&&(t==="function"||t==="symbol"),Dfe=(e,t,n,r)=>{const a=(o,l)=>{const c=r.push(o)-1;return n.set(l,c),c},i=o=>{if(n.has(o))return n.get(o);let[l,c]=am(o);switch(l){case f0:{let d=o;switch(c){case"bigint":l=GB,d=o.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+c);d=null;break;case"undefined":return a([VB],o)}return a([l,d],o)}case Qm:{if(c){let f=o;return c==="DataView"?f=new Uint8Array(o.buffer):c==="ArrayBuffer"&&(f=new Uint8Array(o)),a([c,[...f]],o)}const d=[],h=a([l,d],o);for(const f of o)d.push(i(f));return h}case cb:{if(c)switch(c){case"BigInt":return a([c,o.toString()],o);case"Boolean":case"Number":case"String":return a([c,o.valueOf()],o)}if(t&&"toJSON"in o)return i(o.toJSON());const d=[],h=a([l,d],o);for(const f of Rfe(o))(e||!gg(am(o[f])))&&d.push([i(f),i(o[f])]);return h}case kC:return a([l,o.toISOString()],o);case jC:{const{source:d,flags:h}=o;return a([l,{source:d,flags:h}],o)}case NC:{const d=[],h=a([l,d],o);for(const[f,m]of o)(e||!(gg(am(f))||gg(am(m))))&&d.push([i(f),i(m)]);return h}case SC:{const d=[],h=a([l,d],o);for(const f of o)(e||!gg(am(f)))&&d.push(i(f));return h}}const{message:u}=o;return a([l,{name:c,message:u}],o)};return i},CI=(e,{json:t,lossy:n}={})=>{const r=[];return Dfe(!(t||n),!!t,new Map,r)(e),r},ub=typeof structuredClone=="function"?(e,t)=>t&&("json"in t||"lossy"in t)?SI(CI(e,t)):structuredClone(e):(e,t)=>SI(CI(e,t));function Mfe(e,t){const n=[{type:"text",value:"â©"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function $fe(e,t){return"Back to reference "+(e+1)+(t>1?"-"+t:"")}function Lfe(e){const t=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",n=e.options.footnoteBackContent||Mfe,r=e.options.footnoteBackLabel||$fe,a=e.options.footnoteLabel||"Footnotes",i=e.options.footnoteLabelTagName||"h2",o=e.options.footnoteLabelProperties||{className:["sr-only"]},l=[];let c=-1;for(;++c<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[c]);if(!u)continue;const d=e.all(u),h=String(u.identifier).toUpperCase(),f=Ef(h.toLowerCase());let m=0;const x=[],g=e.footnoteCounts.get(h);for(;g!==void 0&&++m<=g;){x.length>0&&x.push({type:"text",value:" "});let v=typeof n=="string"?n:n(c,m);typeof v=="string"&&(v={type:"text",value:v}),x.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+f+(m>1?"-"+m:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(c,m),className:["data-footnote-backref"]},children:Array.isArray(v)?v:[v]})}const y=d[d.length-1];if(y&&y.type==="element"&&y.tagName==="p"){const v=y.children[y.children.length-1];v&&v.type==="text"?v.value+=" ":y.children.push({type:"text",value:" "}),y.children.push(...x)}else d.push(...x);const b={type:"element",tagName:"li",properties:{id:t+"fn-"+f},children:e.wrap(d,!0)};e.patch(u,b),l.push(b)}if(l.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...ub(o),id:"footnote-label"},children:[{type:"text",value:a}]}
vendor: 5,151 bytes, lines 767-773
767,{type:"text",value:` 768`},{type:"element",tagName:"ol",properties:{},children:e.wrap(l,!0)},{type:"text",value:` 769`}]}}const hx=(function(e){if(e==null)return zfe;if(typeof e=="function")return m0(e);if(typeof e=="object")return Array.isArray(e)?Ffe(e):Bfe(e);if(typeof e=="string")return Ufe(e);throw new Error("Expected function, string, or object as test")});function Ffe(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=hx(e[n]);return m0(r);function r(...a){let i=-1;for(;++i<t.length;)if(t[i].apply(this,a))return!0;return!1}}function Bfe(e){const t=e;return m0(n);function n(r){const a=r;let i;for(i in e)if(a[i]!==t[i])return!1;return!0}}function Ufe(e){return m0(t);function t(n){return n&&n.type===e}}function m0(e){return t;function t(n,r,a){return!!(Wfe(n)&&e.call(this,n,typeof r=="number"?r:void 0,a||void 0))}}function zfe(){return!0}function Wfe(e){return e!==null&&typeof e=="object"&&"type"in e}const YB=[],Kfe=!0,RN=!1,Hfe="skip";function CC(e,t,n,r){let a;typeof t=="function"&&typeof n!="function"?(r=n,n=t):a=t;const i=hx(a),o=r?-1:1;l(e,void 0,[])();function l(c,u,d){const h=c&&typeof c=="object"?c:{};if(typeof h.type=="string"){const m=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(c.type+(m?"<"+m+">":""))+")"})}return f;function f(){let m=YB,x,g,y;if((!t||i(c,u,d[d.length-1]||void 0))&&(m=Vfe(n(c,d)),m[0]===RN))return m;if("children"in c&&c.children){const b=c;if(b.children&&m[0]!==Hfe)for(g=(r?b.children.length:-1)+o,y=d.concat(b);g>-1&&g<b.children.length;){const v=b.children[g];if(x=l(v,g,y)(),x[0]===RN)return x;g=typeof x[1]=="number"?x[1]:g+o}}return m}}}function Vfe(e){return Array.isArray(e)?e:typeof e=="number"?[Kfe,e]:e==null?YB:[e]}function p0(e,t,n,r){let a,i,o;typeof t=="function"&&typeof n!="function"?(i=void 0,o=t,a=n):(i=t,o=n,a=r),CC(e,i,l,a);function l(c,u){const d=u[u.length-1],h=d?d.children.indexOf(c):void 0;return o(c,h,d)}}const DN={}.hasOwnProperty,qfe={};function Gfe(e,t){const n=t||qfe,r=new Map,a=new Map,i=new Map,o={...Tfe,...n.handlers},l={all:u,applyData:Zfe,definitionById:r,footnoteById:a,footnoteCounts:i,footnoteOrder:[],handlers:o,one:c,options:n,patch:Yfe,wrap:Jfe};return p0(e,function(d){if(d.type==="definition"||d.type==="footnoteDefinition"){const h=d.type==="definition"?r:a,f=String(d.identifier).toUpperCase();h.has(f)||h.set(f,d)}}),l;function c(d,h){const f=d.type,m=l.handlers[f];if(DN.call(l.handlers,f)&&m)return m(l,d,h);if(l.options.passThrough&&l.options.passThrough.includes(f)){if("children"in d){const{children:g,...y}=d,b=ub(y);return b.children=l.all(d),b}return ub(d)}return(l.options.unknownHandler||Xfe)(l,d,h)}function u(d){const h=[];if("children"in d){const f=d.children;let m=-1;for(;++m<f.length;){const x=l.one(f[m],d);if(x){if(m&&f[m-1].type==="break"&&(!Array.isArray(x)&&x.type==="text"&&(x.value=EI(x.value)),!Array.isArray(x)&&x.type==="element")){const g=x.children[0];g&&g.type==="text"&&(g.value=EI(g.value))}Array.isArray(x)?h.push(...x):h.push(x)}}}return h}}function Yfe(e,t){e.position&&(t.position=Mue(e))}function Zfe(e,t){let n=t;if(e&&e.data){const r=e.data.hName,a=e.data.hChildren,i=e.data.hProperties;if(typeof r=="string")if(n.type==="element")n.tagName=r;else{const o="children"in n?n.children:[n];n={type:"element",tagName:r,properties:{},children:o}}n.type==="element"&&i&&Object.assign(n.properties,ub(i)),"children"in n&&n.children&&a!==null&&a!==void 0&&(n.children=a)}return n}function Xfe(e,t){const n=t.data||{},r="value"in t&&!(DN.call(n,"hProperties")||DN.call(n,"hChildren"))?{type:"text",value:t.value}:{type:"element",tagName:"div",properties:{},children:e.all(t)};return e.patch(t,r),e.applyData(t,r)}function Jfe(e,t){const n=[];let r=-1;for(t&&n.push({type:"text",value:` 770`});++r<e.length;)r&&n.push({type:"text",value:` 771`}),n.push(e[r]);return t&&e.length>0&&n.push({type:"text",value:` 772`}),n}function EI(e){let t=0,n=e.charCodeAt(t);for(;n===9||n===32;)t++,n=e.charCodeAt(t);return e.slice(t)}function AI(e,t){const n=Gfe(e,t),r=n.one(e,void 0),a=Lfe(n),i=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return a&&i.children.push({type:"text",value:` 773`},a),i}function Qfe(e,t){return e&&"run"in e?async function(n,r){const a=AI(n,{file:r,...t});await e.run(a,r)}:function(n,r){return AI(n,{file:r,...e||t})}}function TI(e){if(e)throw e}var m1,OI;function eme(){if(OI)return m1;OI=1;var e=Object.prototype.hasOwnProperty,t=Object.prototype.toString,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,a=function(u){return typeof Array.isArray=="function"?Array.isArray(u):t.call(u)==="[object Array]"},i=function(u){if(!u||t.call(u)!=="[object Object]")return!1;var d=e.call(u,"constructor"),h=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!d&&!h)return!1;var f;for(f in u);return typeof f>"u"||e.call(u,f)},o=function(u,d){n&&d.name==="__proto__"?n(u,d.name,{enumerable:!0,configurable:!0,value:d.newValue,writable:!0}):u[d.name]=d.newValue},l=function(u,d){if(d==="__proto__")if(e.call(u,d)){if(r)return r(u,d).value}else return;return u[d]};
vendor: 10,488 bytes, line 773
773return m1=function c(){var u,d,h,f,m,x,g=arguments[0],y=1,b=arguments.length,v=!1;for(typeof g=="boolean"&&(v=g,g=arguments[1]||{},y=2),(g==null||typeof g!="object"&&typeof g!="function")&&(g={});y<b;++y)if(u=arguments[y],u!=null)for(d in u)h=l(g,d),f=l(u,d),g!==f&&(v&&f&&(i(f)||(m=a(f)))?(m?(m=!1,x=h&&a(h)?h:[]):x=h&&i(h)?h:{},o(g,{name:d,newValue:c(v,x,f)})):typeof f<"u"&&o(g,{name:d,newValue:f}));return g},m1}var tme=eme();const p1=hl(tme);function MN(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function nme(){const e=[],t={run:n,use:r};return t;function n(...a){let i=-1;const o=a.pop();if(typeof o!="function")throw new TypeError("Expected function as last argument, not "+o);l(null,...a);function l(c,...u){const d=e[++i];let h=-1;if(c){o(c);return}for(;++h<a.length;)(u[h]===null||u[h]===void 0)&&(u[h]=a[h]);a=u,d?rme(d,l)(...u):o(null,...u)}}function r(a){if(typeof a!="function")throw new TypeError("Expected `middelware` to be a function, not "+a);return e.push(a),t}}function rme(e,t){let n;return r;function r(...o){const l=e.length>o.length;let c;l&&o.push(a);try{c=e.apply(this,o)}catch(u){const d=u;if(l&&n)throw d;return a(d)}l||(c&&c.then&&typeof c.then=="function"?c.then(i,a):c instanceof Error?a(c):i(c))}function a(o,...l){n||(n=!0,t(o,...l))}function i(o){a(null,o)}}const Ko={basename:sme,dirname:ame,extname:ime,join:ome,sep:"/"};function sme(e,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');fx(e);let n=0,r=-1,a=e.length,i;if(t===void 0||t.length===0||t.length>e.length){for(;a--;)if(e.codePointAt(a)===47){if(i){n=a+1;break}}else r<0&&(i=!0,r=a+1);return r<0?"":e.slice(n,r)}if(t===e)return"";let o=-1,l=t.length-1;for(;a--;)if(e.codePointAt(a)===47){if(i){n=a+1;break}}else o<0&&(i=!0,o=a+1),l>-1&&(e.codePointAt(a)===t.codePointAt(l--)?l<0&&(r=a):(l=-1,r=o));return n===r?r=o:r<0&&(r=e.length),e.slice(n,r)}function ame(e){if(fx(e),e.length===0)return".";let t=-1,n=e.length,r;for(;--n;)if(e.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?e.codePointAt(0)===47?"/":".":t===1&&e.codePointAt(0)===47?"//":e.slice(0,t)}function ime(e){fx(e);let t=e.length,n=-1,r=0,a=-1,i=0,o;for(;t--;){const l=e.codePointAt(t);if(l===47){if(o){r=t+1;break}continue}n<0&&(o=!0,n=t+1),l===46?a<0?a=t:i!==1&&(i=1):a>-1&&(i=-1)}return a<0||n<0||i===0||i===1&&a===n-1&&a===r+1?"":e.slice(a,n)}function ome(...e){let t=-1,n;for(;++t<e.length;)fx(e[t]),e[t]&&(n=n===void 0?e[t]:n+"/"+e[t]);return n===void 0?".":lme(n)}function lme(e){fx(e);const t=e.codePointAt(0)===47;let n=cme(e,!t);return n.length===0&&!t&&(n="."),n.length>0&&e.codePointAt(e.length-1)===47&&(n+="/"),t?"/"+n:n}function cme(e,t){let n="",r=0,a=-1,i=0,o=-1,l,c;for(;++o<=e.length;){if(o<e.length)l=e.codePointAt(o);else{if(l===47)break;l=47}if(l===47){if(!(a===o-1||i===1))if(a!==o-1&&i===2){if(n.length<2||r!==2||n.codePointAt(n.length-1)!==46||n.codePointAt(n.length-2)!==46){if(n.length>2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),a=o,i=0;continue}}else if(n.length>0){n="",r=0,a=o,i=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+e.slice(a+1,o):n=e.slice(a+1,o),r=o-a-1;a=o,i=0}else l===46&&i>-1?i++:i=-1}return n}function fx(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const ume={cwd:dme};function dme(){return"/"}function $N(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function hme(e){if(typeof e=="string")e=new URL(e);else if(!$N(e)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(e.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return fme(e)}function fme(e){if(e.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=e.pathname;let n=-1;for(;++n<t.length;)if(t.codePointAt(n)===37&&t.codePointAt(n+1)===50){const r=t.codePointAt(n+2);if(r===70||r===102){const a=new TypeError("File URL path must not include encoded / characters");throw a.code="ERR_INVALID_FILE_URL_PATH",a}}return decodeURIComponent(t)}const x1=["history","path","basename","stem","extname","dirname"];class ZB{constructor(t){let n;t?$N(t)?n={path:t}:typeof t=="string"||mme(t)?n={value:t}:n=t:n={},this.cwd="cwd"in n?"":ume.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let r=-1;for(;++r<x1.length;){const i=x1[r];i in n&&n[i]!==void 0&&n[i]!==null&&(this[i]=i==="history"?[...n[i]]:n[i])}let a;for(a in n)x1.includes(a)||(this[a]=n[a])}get basename(){return typeof this.path=="string"?Ko.basename(this.path):void 0}set basename(t){y1(t,"basename"),g1(t,"basename"),this.path=Ko.join(this.dirname||"",t)}get dirname(){return typeof this.path=="string"?Ko.dirname(this.path):void 0}set dirname(t){II(this.basename,"dirname"),this.path=Ko.join(t||"",this.basename)}get extname(){return typeof this.path=="string"?Ko.extname(this.path):void 0}set extname(t){if(g1(t,"extname"),II(this.dirname,"extname"),t){if(t.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(t.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Ko.join(this.dirname,this.stem+(t||""))}get path(){return this.history[this.history.length-1]}set path(t){$N(t)&&(t=hme(t)),y1(t,"path"),this.path!==t&&this.history.push(t)}get stem(){return typeof this.path=="string"?Ko.basename(this.path,this.extname):void 0}set stem(t){y1(t,"stem"),g1(t,"stem"),this.path=Ko.join(this.dirname||"",t+(this.extname||""))}fail(t,n,r){const a=this.message(t,n,r);throw a.fatal=!0,a}info(t,n,r){const a=this.message(t,n,r);return a.fatal=void 0,a}message(t,n,r){const a=new xa(t,n,r);return this.path&&(a.name=this.path+":"+a.name,a.file=this.path),a.fatal=!1,this.messages.push(a),a}toString(t){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(t||void 0).decode(this.value)}}function g1(e,t){if(e&&e.includes(Ko.sep))throw new Error("`"+t+"` cannot be a path: did not expect `"+Ko.sep+"`")}function y1(e,t){if(!e)throw new Error("`"+t+"` cannot be empty")}function II(e,t){if(!e)throw new Error("Setting `"+t+"` requires `path` to be set too")}function mme(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const pme=(function(e){const r=this.constructor.prototype,a=r[e],i=function(){return a.apply(i,arguments)};return Object.setPrototypeOf(i,r),i}),xme={}.hasOwnProperty;class EC extends pme{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=nme()}copy(){const t=new EC;let n=-1;for(;++n<this.attachers.length;){const r=this.attachers[n];t.use(...r)}return t.data(p1(!0,{},this.namespace)),t}data(t,n){return typeof t=="string"?arguments.length===2?(w1("data",this.frozen),this.namespace[t]=n,this):xme.call(this.namespace,t)&&this.namespace[t]||void 0:t?(w1("data",this.frozen),this.namespace=t,this):this.namespace}freeze(){if(this.frozen)return this;const t=this;for(;++this.freezeIndex<this.attachers.length;){const[n,...r]=this.attachers[this.freezeIndex];if(r[0]===!1)continue;r[0]===!0&&(r[0]=void 0);const a=n.call(t,...r);typeof a=="function"&&this.transformers.use(a)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(t){this.freeze();const n=yg(t),r=this.parser||this.Parser;return b1("parse",r),r(String(n),n)}process(t,n){const r=this;return this.freeze(),b1("process",this.parser||this.Parser),v1("process",this.compiler||this.Compiler),n?a(void 0,n):new Promise(a);function a(i,o){const l=yg(t),c=r.parse(l);r.run(c,l,function(d,h,f){if(d||!h||!f)return u(d);const m=h,x=r.stringify(m,f);bme(x)?f.value=x:f.result=x,u(d,f)});function u(d,h){d||!h?o(d):i?i(h):n(void 0,h)}}}processSync(t){let n=!1,r;return this.freeze(),b1("processSync",this.parser||this.Parser),v1("processSync",this.compiler||this.Compiler),this.process(t,a),RI("processSync","process",n),r;function a(i,o){n=!0,TI(i),r=o}}run(t,n,r){PI(t),this.freeze();const a=this.transformers;return!r&&typeof n=="function"&&(r=n,n=void 0),r?i(void 0,r):new Promise(i);function i(o,l){const c=yg(n);a.run(t,c,u);function u(d,h,f){const m=h||t;d?l(d):o?o(m):r(void 0,m,f)}}}runSync(t,n){let r=!1,a;return this.run(t,n,i),RI("runSync","run",r),a;function i(o,l){TI(o),a=l,r=!0}}stringify(t,n){this.freeze();const r=yg(n),a=this.compiler||this.Compiler;return v1("stringify",a),PI(t),a(t,r)}use(t,...n){const r=this.attachers,a=this.namespace;if(w1("use",this.frozen),t!=null)if(typeof t=="function")c(t,n);else if(typeof t=="object")Array.isArray(t)?l(t):o(t);else throw new TypeError("Expected usable value, not `"+t+"`");return this;function i(u){if(typeof u=="function")c(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[d,...h]=u;c(d,h)}else o(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function o(u){if(!("plugins"in u)&&!("settings"in u))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");l(u.plugins),u.settings&&(a.settings=p1(!0,a.settings,u.settings))}function l(u){let d=-1;if(u!=null)if(Array.isArray(u))for(;++d<u.length;){const h=u[d];i(h)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function c(u,d){let h=-1,f=-1;for(;++h<r.length;)if(r[h][0]===u){f=h;break}if(f===-1)r.push([u,...d]);else if(d.length>0){let[m,...x]=d;const g=r[f][1];MN(g)&&MN(m)&&(m=p1(!0,g,m)),r[f]=[u,m,...x]}}}}const gme=new EC().freeze();function b1(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function v1(e,t){if(typeof t!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function w1(e,t){if(t)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function PI(e){if(!MN(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}
vendor: 5,857 bytes, line 773
773function RI(e,t,n){if(!n)throw new Error("`"+e+"` finished async. Use `"+t+"` instead")}function yg(e){return yme(e)?e:new ZB(e)}function yme(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function bme(e){return typeof e=="string"||vme(e)}function vme(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const wme="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",DI=[],MI={allowDangerousHtml:!0},_me=/^(https?|ircs?|mailto|xmpp)$/i,kme=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function mx(e){const t=jme(e),n=Nme(e);return Sme(t.runSync(t.parse(n),n),e)}function jme(e){const t=e.rehypePlugins||DI,n=e.remarkPlugins||DI,r=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...MI}:MI;return gme().use(sfe).use(n).use(Qfe,r).use(t)}function Nme(e){const t=e.children||"",n=new ZB;return typeof t=="string"&&(n.value=t),n}function Sme(e,t){const n=t.allowedElements,r=t.allowElement,a=t.components,i=t.disallowedElements,o=t.skipHtml,l=t.unwrapDisallowed,c=t.urlTransform||Cme;for(const d of kme)Object.hasOwn(t,d.from)&&(""+d.from+(d.to?"use `"+d.to+"` instead":"remove it")+wme+d.id,void 0);return t.className&&(e={type:"element",tagName:"div",properties:{className:t.className},children:e.type==="root"?e.children:[e]}),p0(e,u),Uue(e,{Fragment:s.Fragment,components:a,ignoreInvalidStyle:!0,jsx:s.jsx,jsxs:s.jsxs,passKeys:!0,passNode:!0});function u(d,h,f){if(d.type==="raw"&&f&&typeof h=="number")return o?f.children.splice(h,1):f.children[h]={type:"text",value:d.value},h;if(d.type==="element"){let m;for(m in d1)if(Object.hasOwn(d1,m)&&Object.hasOwn(d.properties,m)){const x=d.properties[m],g=d1[m];(g===null||g.includes(d.tagName))&&(d.properties[m]=c(String(x||""),m,d))}}if(d.type==="element"){let m=n?!n.includes(d.tagName):i?i.includes(d.tagName):!1;if(!m&&r&&typeof h=="number"&&(m=!r(d,h,f)),m&&f&&typeof h=="number")return l&&d.children?f.children.splice(h,1,...d.children):f.children.splice(h,1),h}}}function Cme(e){const t=e.indexOf(":"),n=e.indexOf("?"),r=e.indexOf("#"),a=e.indexOf("/");return t===-1||a!==-1&&t>a||n!==-1&&t>n||r!==-1&&t>r||_me.test(e.slice(0,t))?e:""}function db(e,t){const n=String(e);if(typeof t!="string")throw new TypeError("Expected character");let r=0,a=n.indexOf(t);for(;a!==-1;)r++,a=n.indexOf(t,a+t.length);return r}function Eme(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Ame(e,t,n){const a=hx((n||{}).ignore||[]),i=Tme(t);let o=-1;for(;++o<i.length;)CC(e,"text",l);function l(u,d){let h=-1,f;for(;++h<d.length;){const m=d[h],x=f?f.children:void 0;if(a(m,x?x.indexOf(m):void 0,f))return;f=m}if(f)return c(u,d)}function c(u,d){const h=d[d.length-1],f=i[o][0],m=i[o][1];let x=0;const y=h.children.indexOf(u);let b=!1,v=[];f.lastIndex=0;let w=f.exec(u.value);for(;w;){const _=w.index,k={index:w.index,input:w.input,stack:[...d,u]};let j=m(...w,k);if(typeof j=="string"&&(j=j.length>0?{type:"text",value:j}:void 0),j===!1?f.lastIndex=_+1:(x!==_&&v.push({type:"text",value:u.value.slice(x,_)}),Array.isArray(j)?v.push(...j):j&&v.push(j),x=_+w[0].length,b=!0),!f.global)break;w=f.exec(u.value)}return b?(x<u.value.length&&v.push({type:"text",value:u.value.slice(x)}),h.children.splice(y,1,...v)):v=[u],y+v.length}}function Tme(e){const t=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const n=!e[0]||Array.isArray(e[0])?e:[e];let r=-1;for(;++r<n.length;){const a=n[r];t.push([Ome(a[0]),Ime(a[1])])}return t}function Ome(e){return typeof e=="string"?new RegExp(Eme(e),"g"):e}function Ime(e){return typeof e=="function"?e:function(){return e}}const _1="phrasing",k1=["autolink","link","image","label"];function Pme(){return{transforms:[Bme],enter:{literalAutolink:Dme,literalAutolinkEmail:j1,literalAutolinkHttp:j1,literalAutolinkWww:j1},exit:{literalAutolink:Fme,literalAutolinkEmail:Lme,literalAutolinkHttp:Mme,literalAutolinkWww:$me}}}function Rme(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:_1,notInConstruct:k1},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:_1,notInConstruct:k1},{character:":",before:"[ps]",after:"\\/",inConstruct:_1,notInConstruct:k1}]}}function Dme(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function j1(e){this.config.enter.autolinkProtocol.call(this,e)}function Mme(e){this.config.exit.autolinkProtocol.call(this,e)}function $me(e){this.config.exit.data.call(this,e);const t=this.stack[this.stack.length-1];t.type,t.url="http://"+this.sliceSerialize(e)}function Lme(e){this.config.exit.autolinkEmail.call(this,e)}function Fme(e){this.exit(e)}function Bme(e){Ame(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,Ume],[new RegExp("(?<=^|\\s|\\p{P}|\\p{S}
773)([-.\\w+]+)@([-\\w]+(?:\\.[-\\w]+)+)","gu"),zme]],{ignore:["link","linkReference"]})}function Ume(e,t,n,r,a){let i="";if(!XB(a)||(/^w/i.test(t)&&(n=t+n,t="",i="http://"),!Wme(n)))return!1;const o=Kme(n+r);if(!o[0])return!1;const l={type:"link",title:null,url:i+t+o[0],children:[{type:"text",value:t+o[0]}]};return o[1]?[l,{type:"text",value:o[1]}]:l}function zme(e,t,n,r){return!XB(r,!0)||/[-\d_]$/.test(n)?!1:{type:"link",title:null,url:"mailto:"+t+"@"+n,children:[{type:"text",value:t+"@"+n}]}}function Wme(e){const t=e.split(".");return!(t.length<2||t[t.length-1]&&(/_/.test(t[t.length-1])||!/[a-zA-Z\d]/.test(t[t.length-1]))||t[t.length-2]&&(/_/.test(t[t.length-2])||!/[a-zA-Z\d]/.test(t[t.length-2])))}function Kme(e){const t=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!t)return[e,void 0];e=e.slice(0,t.index);let n=t[0],r=n.indexOf(")");const a=db(e,"(");let i=db(e,")");for(;r!==-1&&a>i;)e+=n.slice(0,r+1),n=n.slice(r+1),r=n.indexOf(")"),i++;return[e,n]}function XB(e,t){const n=e.input.charCodeAt(e.index-1);return(e.index===0||jo(n)||ru(n))&&(!t||n!==47)}JB.peek=Qme;function Hme(){this.buffer()}function Vme(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function qme(){this.buffer()}function Gme(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function Yme(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=bo(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Zme(e){this.exit(e)}function Xme(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.type,n.identifier=bo(this.sliceSerialize(e)).toLowerCase(),n.label=t}function Jme(e){this.exit(e)}function Qme(){return"["}function JB(e,t,n,r){const a=n.createTracker(r);let i=a.move("[^");const o=n.enter("footnoteReference"),l=n.enter("reference");return i+=a.move(n.safe(n.associationId(e),{after:"]",before:i})),l(),o(),i+=a.move("]"),i}function epe(){return{enter:{gfmFootnoteCallString:Hme,gfmFootnoteCall:Vme,gfmFootnoteDefinitionLabelString:qme,gfmFootnoteDefinition:Gme},exit:{gfmFootnoteCallString:Yme,gfmFootnoteCall:Zme,gfmFootnoteDefinitionLabelString:Xme,gfmFootnoteDefinition:Jme}}}function tpe(e){let t=!1;return e&&e.firstLineBlank&&(t=!0),{handlers:{footnoteDefinition:n,footnoteReference:JB},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function n(r,a,i,o){const l=i.createTracker(o);let c=l.move("[^");const u=i.enter("footnoteDefinition"),d=i.enter("label");return c+=l.move(i.safe(i.associationId(r),{before:c,after:"]"})),d(),c+=l.move("]:"),r.children&&r.children.length>0&&(l.shift(4),c+=l.move((t?` 774`:" ")+i.indentLines(i.containerFlow(r,l.current()),t?QB:npe))),u(),c}}function npe(e,t,n){return t===0?e:QB(e,t,n)}function QB(e,t,n){return(n?"":" ")+e}const rpe=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];e7.peek=lpe;function spe(){return{canContainEols:["delete"],enter:{strikethrough:ipe},exit:{strikethrough:ope}}}function ape(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:rpe}],handlers:{delete:e7}}}function ipe(e){this.enter({type:"delete",children:[]},e)}function ope(e){this.exit(e)}function e7(e,t,n,r){const a=n.createTracker(r),i=n.enter("strikethrough");let o=a.move("~~");return o+=n.containerPhrasing(e,{...a.current(),before:o,after:"~"}),o+=a.move("~~"),i(),o}function lpe(){return"~"}function cpe(e){return e.length}function upe(e,t){const n=t||{},r=(n.align||[]).concat(),a=n.stringLength||cpe,i=[],o=[],l=[],c=[];let u=0,d=-1;for(;++d<e.length;){const g=[],y=[];let b=-1;for(e[d].length>u&&(u=e[d].length);++b<e[d].length;){const v=dpe(e[d][b]);if(n.alignDelimiters!==!1){const w=a(v);y[b]=w,(c[b]===void 0||w>c[b])&&(c[b]=w)}g.push(v)}o[d]=g,l[d]=y}let h=-1;if(typeof r=="object"&&"length"in r)for(;++h<u;)i[h]=$I(r[h]);else{const g=$I(r);for(;++h<u;)i[h]=g}h=-1;const f=[],m=[];for(;++h<u;){const g=i[h];let y="",b="";g===99?(y=":",b=":"):g===108?y=":":g===114&&(b=":");let v=n.alignDelimiters===!1?1:Math.max(1,c[h]-y.length-b.length);const w=y+"-".repeat(v)+b;n.alignDelimiters!==!1&&(v=y.length+v+b.length,v>c[h]&&(c[h]=v),m[h]=v),f[h]=w}o.splice(1,0,f),l.splice(1,0,m),d=-1;const x=[];for(;++d<o.length;){const g=o[d],y=l[d];h=-1;const b=[];for(;++h<u;){const v=g[h]||"";let w="",_="";if(n.alignDelimiters!==!1){const k=c[h]-(y[h]||0),j=i[h];j===114?w=" ".repeat(k):j===99?k%2?(w=" ".repeat(k/2+.5),_=" ".repeat(k/2-.5)):(w=" ".repeat(k/2),_=w):_=" ".repeat(k)}n.delimiterStart!==!1&&!h&&b.push("|"),n.padding!==!1&&!(n.alignDelimiters===!1&&v==="")&&(n.delimiterStart!==!1||h)&&b.push(" "),n.alignDelimiters!==!1&&b.push(w),b.push(v),n.alignDelimiters!==!1&&b.push(_),n.padding!==!1&&b.push(" "),(n.delimiterEnd!==!1||h!==u-1)&&b.push("|")}x.push(n.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return x.join(` 775`)}function dpe(e){return e==null?"":String(e)}function $I(e){const t=typeof e=="string"?e.codePointAt(0):0;return t===67||t===99?99:t===76||t===108?108:t===82||t===114?114:0}function hpe(e,t,n,r){const a=n.enter("blockquote"),i=n.createTracker(r);i.move("> "),i.shift(2);const o=n.indentLines(n.containerFlow(e,i.current()),fpe);return a(),o}function fpe(e,t,n){return">"+(n?"":" ")+e}function mpe(e,t){return LI(e,t.inConstruct,!0)&&!LI(e,t.notInConstruct,!1)}function LI(e,t,n){if(typeof t=="string"&&(t=[t]),!t||t.length===0)return n;let r=-1;for(;++r<t.length;)if(e.includes(t[r]))return!0;return!1}function FI(e,t,n,r){let a=-1;for(;++a<n.unsafe.length;)if(n.unsafe[a].character===` 776`&&mpe(n.stack,n.unsafe[a]))return/[ \t]/.test(r.before)?"":" ";return`\\ 777`}function ppe(e,t){const n=String(e);let r=n.indexOf(t),a=r,i=0,o=0;if(typeof t!="string")throw new TypeError("Expected substring");for(;r!==-1;)r===a?++i>o&&(o=i):i=1,a=r+t.length,r=n.indexOf(t,a);return o}function xpe(e,t){return!!(t.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function gpe(e){const t=e.options.fence||"`";if(t!=="`"&&t!=="~")throw new Error("Cannot serialize code with `"+t+"` for `options.fence`, expected `` ` `` or `~`");return t}function ype(e,t,n,r){const a=gpe(n),i=e.value||"",o=a==="`"?"GraveAccent":"Tilde";
vendor: 5,541 bytes, lines 777-786
777if(xpe(e,n)){const h=n.enter("codeIndented"),f=n.indentLines(i,bpe);return h(),f}const l=n.createTracker(r),c=a.repeat(Math.max(ppe(i,a)+1,3)),u=n.enter("codeFenced");let d=l.move(c);if(e.lang){const h=n.enter(`codeFencedLang${o}`);d+=l.move(n.safe(e.lang,{before:d,after:" ",encode:["`"],...l.current()})),h()}if(e.lang&&e.meta){const h=n.enter(`codeFencedMeta${o}`);d+=l.move(" "),d+=l.move(n.safe(e.meta,{before:d,after:` 778`,encode:["`"],...l.current()})),h()}return d+=l.move(` 779`),i&&(d+=l.move(i+` 780`)),d+=l.move(c),u(),d}function bpe(e,t,n){return(n?"":" ")+e}function AC(e){const t=e.options.quote||'"';if(t!=='"'&&t!=="'")throw new Error("Cannot serialize title with `"+t+"` for `options.quote`, expected `\"`, or `'`");return t}function vpe(e,t,n,r){const a=AC(n),i=a==='"'?"Quote":"Apostrophe",o=n.enter("definition");let l=n.enter("label");const c=n.createTracker(r);let u=c.move("[");return u+=c.move(n.safe(n.associationId(e),{before:u,after:"]",...c.current()})),u+=c.move("]: "),l(),!e.url||/[\0- \u007F]/.test(e.url)?(l=n.enter("destinationLiteral"),u+=c.move("<"),u+=c.move(n.safe(e.url,{before:u,after:">",...c.current()})),u+=c.move(">")):(l=n.enter("destinationRaw"),u+=c.move(n.safe(e.url,{before:u,after:e.title?" ":` 781`,...c.current()}))),l(),e.title&&(l=n.enter(`title${i}`),u+=c.move(" "+a),u+=c.move(n.safe(e.title,{before:u,after:a,...c.current()})),u+=c.move(a),l()),o(),u}function wpe(e){const t=e.options.emphasis||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize emphasis with `"+t+"` for `options.emphasis`, expected `*`, or `_`");return t}function Sp(e){return"&#x"+e.toString(16).toUpperCase()+";"}function hb(e,t,n){const r=qh(e),a=qh(t);return r===void 0?a===void 0?n==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:r===1?a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:a===void 0?{inside:!1,outside:!1}:a===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}t7.peek=_pe;function t7(e,t,n,r){const a=wpe(n),i=n.enter("emphasis"),o=n.createTracker(r),l=o.move(a);let c=o.move(n.containerPhrasing(e,{after:a,before:l,...o.current()}));const u=c.charCodeAt(0),d=hb(r.before.charCodeAt(r.before.length-1),u,a);d.inside&&(c=Sp(u)+c.slice(1));const h=c.charCodeAt(c.length-1),f=hb(r.after.charCodeAt(0),h,a);f.inside&&(c=c.slice(0,-1)+Sp(h));const m=o.move(a);return i(),n.attentionEncodeSurroundingInfo={after:f.outside,before:d.outside},l+c+m}function _pe(e,t,n){return n.options.emphasis||"*"}function kpe(e,t){let n=!1;return p0(e,function(r){if("value"in r&&/\r?\n|\r/.test(r.value)||r.type==="break")return n=!0,RN}),!!((!e.depth||e.depth<3)&&wC(e)&&(t.options.setext||n))}function jpe(e,t,n,r){const a=Math.max(Math.min(6,e.depth||1),1),i=n.createTracker(r);if(kpe(e,n)){const d=n.enter("headingSetext"),h=n.enter("phrasing"),f=n.containerPhrasing(e,{...i.current(),before:` 782`,after:` 783`});return h(),d(),f+` 784`+(a===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(` 785`))+1))}const o="#".repeat(a),l=n.enter("headingAtx"),c=n.enter("phrasing");i.move(o+" ");let u=n.containerPhrasing(e,{before:"# ",after:` 786`,...i.current()});return/^[\t ]/.test(u)&&(u=Sp(u.charCodeAt(0))+u.slice(1)),u=u?o+" "+u:o,n.options.closeAtx&&(u+=" "+o),c(),l(),u}n7.peek=Npe;function n7(e){return e.value||""}function Npe(){return"<"}r7.peek=Spe;function r7(e,t,n,r){const a=AC(n),i=a==='"'?"Quote":"Apostrophe",o=n.enter("image");let l=n.enter("label");const c=n.createTracker(r);let u=c.move("![");return u+=c.move(n.safe(e.alt,{before:u,after:"]",...c.current()})),u+=c.move("]("),l(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(l=n.enter("destinationLiteral"),u+=c.move("<"),u+=c.move(n.safe(e.url,{before:u,after:">",...c.current()})),u+=c.move(">")):(l=n.enter("destinationRaw"),u+=c.move(n.safe(e.url,{before:u,after:e.title?" ":")",...c.current()}))),l(),e.title&&(l=n.enter(`title${i}`),u+=c.move(" "+a),u+=c.move(n.safe(e.title,{before:u,after:a,...c.current()})),u+=c.move(a),l()),u+=c.move(")"),o(),u}function Spe(){return"!"}s7.peek=Cpe;function s7(e,t,n,r){const a=e.referenceType,i=n.enter("imageReference");let o=n.enter("label");const l=n.createTracker(r);let c=l.move("![");const u=n.safe(e.alt,{before:c,after:"]",...l.current()});c+=l.move(u+"]["),o();const d=n.stack;n.stack=[],o=n.enter("reference");const h=n.safe(n.associationId(e),{before:c,after:"]",...l.current()});return o(),n.stack=d,i(),a==="full"||!u||u!==h?c+=l.move(h+"]"):a==="shortcut"?c=c.slice(0,-1):c+=l.move("]"),c}function Cpe(){return"!"}a7.peek=Epe;function a7(e,t,n){let r=e.value||"",a="`",i=-1;for(;new RegExp("(^|[^`])"+a+"([^`]|$)").test(r);)a+="`";for(/[^ \r\n]/.test(r)&&(/^[ \r\n]/.test(r)&&/[ \r\n]$/.test(r)||/^`|`$/.test(r))&&(r=" "+r+" ");++i<n.unsafe.length;){const o=n.unsafe[i],l=n.compilePattern(o);let c;if(o.atBreak)for(;c=l.exec(r);){let u=c.index;r.charCodeAt(u)===10&&r.charCodeAt(u-1)===13&&u--,r=r.slice(0,u)+" "+r.slice(c.index+1)}}return a+r+a}function Epe(){return"`"}function i7(e,t){const n=wC(e);return!!(!t.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(n===e.url||"mailto:"+n===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}o7.peek=Ape;function o7(e,t,n,r){const a=AC(n),i=a==='"'?"Quote":"Apostrophe",o=n.createTracker(r);let l,c;if(i7(e,n)){const d=n.stack;n.stack=[],l=n.enter("autolink");let h=o.move("<");return h+=o.move(n.containerPhrasing(e,{before:h,after:">",...o.current()})),h+=o.move(">
786"),l(),n.stack=d,h}l=n.enter("link"),c=n.enter("label");let u=o.move("[");return u+=o.move(n.containerPhrasing(e,{before:u,after:"](",...o.current()})),u+=o.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=n.enter("destinationLiteral"),u+=o.move("<"),u+=o.move(n.safe(e.url,{before:u,after:">",...o.current()})),u+=o.move(">")):(c=n.enter("destinationRaw"),u+=o.move(n.safe(e.url,{before:u,after:e.title?" ":")",...o.current()}))),c(),e.title&&(c=n.enter(`title${i}`),u+=o.move(" "+a),u+=o.move(n.safe(e.title,{before:u,after:a,...o.current()})),u+=o.move(a),c()),u+=o.move(")"),l(),u}function Ape(e,t,n){return i7(e,n)?"<":"["}l7.peek=Tpe;function l7(e,t,n,r){const a=e.referenceType,i=n.enter("linkReference");let o=n.enter("label");const l=n.createTracker(r);let c=l.move("[");const u=n.containerPhrasing(e,{before:c,after:"]",...l.current()});c+=l.move(u+"]["),o();const d=n.stack;n.stack=[],o=n.enter("reference");const h=n.safe(n.associationId(e),{before:c,after:"]",...l.current()});return o(),n.stack=d,i(),a==="full"||!u||u!==h?c+=l.move(h+"]"):a==="shortcut"?c=c.slice(0,-1):c+=l.move("]"),c}function Tpe(){return"["}function TC(e){const t=e.options.bullet||"*";if(t!=="*"&&t!=="+"&&t!=="-")throw new Error("Cannot serialize items with `"+t+"` for `options.bullet`, expected `*`, `+`, or `-`");return t}function Ope(e){const t=TC(e),n=e.options.bulletOther;if(!n)return t==="*"?"-":"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(n===t)throw new Error("Expected `bullet` (`"+t+"`) and `bulletOther` (`"+n+"`) to be different");return n}function Ipe(e){const t=e.options.bulletOrdered||".";if(t!=="."&&t!==")")throw new Error("Cannot serialize items with `"+t+"` for `options.bulletOrdered`, expected `.` or `)`");return t}function c7(e){const t=e.options.rule||"*";if(t!=="*"&&t!=="-"&&t!=="_")throw new Error("Cannot serialize rules with `"+t+"` for `options.rule`, expected `*`, `-`, or `_`");return t}function Ppe(e,t,n,r){const a=n.enter("list"),i=n.bulletCurrent;let o=e.ordered?Ipe(n):TC(n);const l=e.ordered?o==="."?")":".":Ope(n);let c=t&&n.bulletLastUsed?o===n.bulletLastUsed:!1;if(!e.ordered){const d=e.children?e.children[0]:void 0;if((o==="*"||o==="-")&&d&&(!d.children||!d.children[0])&&n.stack[n.stack.length-1]==="list"&&n.stack[n.stack.length-2]==="listItem"&&n.stack[n.stack.length-3]==="list"&&n.stack[n.stack.length-4]==="listItem"&&n.indexStack[n.indexStack.length-1]===0&&n.indexStack[n.indexStack.length-2]===0&&n.indexStack[n.indexStack.length-3]===0&&(c=!0),c7(n)===o&&d){let h=-1;for(;++h<e.children.length;){const f=e.children[h];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){c=!0;break}}}}c&&(o=l),n.bulletCurrent=o;const u=n.containerFlow(e,r);return n.bulletLastUsed=o,n.bulletCurrent=i,a(),u}function Rpe(e){const t=e.options.listItemIndent||"one";
vendor: 7,011 bytes, lines 786-788
786if(t!=="tab"&&t!=="one"&&t!=="mixed")throw new Error("Cannot serialize items with `"+t+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return t}function Dpe(e,t,n,r){const a=Rpe(n);let i=n.bulletCurrent||TC(n);t&&t.type==="list"&&t.ordered&&(i=(typeof t.start=="number"&&t.start>-1?t.start:1)+(n.options.incrementListMarker===!1?0:t.children.indexOf(e))+i);let o=i.length+1;(a==="tab"||a==="mixed"&&(t&&t.type==="list"&&t.spread||e.spread))&&(o=Math.ceil(o/4)*4);const l=n.createTracker(r);l.move(i+" ".repeat(o-i.length)),l.shift(o);const c=n.enter("listItem"),u=n.indentLines(n.containerFlow(e,l.current()),d);return c(),u;function d(h,f,m){return f?(m?"":" ".repeat(o))+h:(m?i:i+" ".repeat(o-i.length))+h}}function Mpe(e,t,n,r){const a=n.enter("paragraph"),i=n.enter("phrasing"),o=n.containerPhrasing(e,r);return i(),a(),o}const $pe=hx(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function Lpe(e,t,n,r){return(e.children.some(function(o){return $pe(o)})?n.containerPhrasing:n.containerFlow).call(n,e,r)}function Fpe(e){const t=e.options.strong||"*";if(t!=="*"&&t!=="_")throw new Error("Cannot serialize strong with `"+t+"` for `options.strong`, expected `*`, or `_`");return t}u7.peek=Bpe;function u7(e,t,n,r){const a=Fpe(n),i=n.enter("strong"),o=n.createTracker(r),l=o.move(a+a);let c=o.move(n.containerPhrasing(e,{after:a,before:l,...o.current()}));const u=c.charCodeAt(0),d=hb(r.before.charCodeAt(r.before.length-1),u,a);d.inside&&(c=Sp(u)+c.slice(1));const h=c.charCodeAt(c.length-1),f=hb(r.after.charCodeAt(0),h,a);f.inside&&(c=c.slice(0,-1)+Sp(h));const m=o.move(a+a);return i(),n.attentionEncodeSurroundingInfo={after:f.outside,before:d.outside},l+c+m}function Bpe(e,t,n){return n.options.strong||"*"}function Upe(e,t,n,r){return n.safe(e.value,r)}function zpe(e){const t=e.options.ruleRepetition||3;if(t<3)throw new Error("Cannot serialize rules with repetition `"+t+"` for `options.ruleRepetition`, expected `3` or more");return t}function Wpe(e,t,n){const r=(c7(n)+(n.options.ruleSpaces?" ":"")).repeat(zpe(n));return n.options.ruleSpaces?r.slice(0,-1):r}const d7={blockquote:hpe,break:FI,code:ype,definition:vpe,emphasis:t7,hardBreak:FI,heading:jpe,html:n7,image:r7,imageReference:s7,inlineCode:a7,link:o7,linkReference:l7,list:Ppe,listItem:Dpe,paragraph:Mpe,root:Lpe,strong:u7,text:Upe,thematicBreak:Wpe};function Kpe(){return{enter:{table:Hpe,tableData:BI,tableHeader:BI,tableRow:qpe},exit:{codeText:Gpe,table:Vpe,tableData:N1,tableHeader:N1,tableRow:N1}}}function Hpe(e){const t=e._align;this.enter({type:"table",align:t.map(function(n){return n==="none"?null:n}),children:[]},e),this.data.inTable=!0}function Vpe(e){this.exit(e),this.data.inTable=void 0}function qpe(e){this.enter({type:"tableRow",children:[]},e)}function N1(e){this.exit(e)}function BI(e){this.enter({type:"tableCell",children:[]},e)}function Gpe(e){let t=this.resume();this.data.inTable&&(t=t.replace(/\\([\\|])/g,Ype));const n=this.stack[this.stack.length-1];n.type,n.value=t,this.exit(e)}function Ype(e,t){return t==="|"?t:e}function Zpe(e){const t=e||{},n=t.tableCellPadding,r=t.tablePipeAlign,a=t.stringLength,i=n?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:` 787`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:o,tableCell:c,tableRow:l}};function o(m,x,g,y){return u(d(m,g,y),m.align)}function l(m,x,g,y){const b=h(m,g,y),v=u([b]);return v.slice(0,v.indexOf(` 788`))}function c(m,x,g,y){const b=g.enter("tableCell"),v=g.enter("phrasing"),w=g.containerPhrasing(m,{...y,before:i,after:i});return v(),b(),w}function u(m,x){return upe(m,{align:x,alignDelimiters:r,padding:n,stringLength:a})}function d(m,x,g){const y=m.children;let b=-1;const v=[],w=x.enter("table");for(;++b<y.length;)v[b]=h(y[b],x,g);return w(),v}function h(m,x,g){const y=m.children;let b=-1;const v=[],w=x.enter("tableRow");for(;++b<y.length;)v[b]=c(y[b],m,x,g);return w(),v}function f(m,x,g){let y=d7.inlineCode(m,x,g);return g.stack.includes("tableCell")&&(y=y.replace(/\|/g,"\\$&")),y}}function Xpe(){return{exit:{taskListCheckValueChecked:UI,taskListCheckValueUnchecked:UI,paragraph:Qpe}}}function Jpe(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:exe}}}function UI(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function Qpe(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const r=n.children[0];if(r&&r.type==="text"){const a=t.children;let i=-1,o;for(;++i<a.length;){const l=a[i];if(l.type==="paragraph"){o=l;break}}o===n&&(r.value=r.value.slice(1),r.value.length===0?n.children.shift():n.position&&r.position&&typeof r.position.start.offset=="number"&&(r.position.start.column++,r.position.start.offset++,n.position.start=Object.assign({},r.position.start)))}}this.exit(e)}function exe(e,t,n,r){const a=e.children[0],i=typeof e.checked=="boolean"&&a&&a.type==="paragraph",o="["+(e.checked?"x":" ")+"] ",l=n.createTracker(r);i&&l.move(o);let c=d7.listItem(e,t,n,{...r,...l.current()});return i&&(c=c.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),c;function u(d){return d+o}}function txe(){return[Pme(),epe(),spe(),Kpe(),Xpe()]}function nxe(e){return{extensions:[Rme(),tpe(e),ape(),Zpe(e),Jpe()]}}const rxe={tokenize:cxe,partial:!0},h7={tokenize:uxe,partial:!0},f7={tokenize:dxe,partial:!0},m7={tokenize:hxe,partial:!0},sxe={tokenize:fxe,partial:!0},p7={name:"wwwAutolink",tokenize:oxe,previous:g7},x7={name:"protocolAutolink",tokenize:lxe,previous:y7},xc={name:"emailAutolink",tokenize:ixe,previous:b7},pl={};function axe(){return{text:pl}}let Iu=48;for(;Iu<123;)pl[Iu]=xc,Iu++,Iu===58?Iu=65:Iu===91&&(Iu=97);pl[43]=xc;pl[45]=xc;pl[46]=xc;pl[95]=xc;pl[72]=[xc,x7];pl[104]=[xc,x7];pl[87]=[xc,p7];pl[119]=[xc,p7];function ixe(e,t,n){const r=this;let a,i;return o;function o(h){return!LN(h)||!b7.call(r,r.previous)||OC(r.events)?n(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),l(h))}function l(h){return LN(h)?(e.consume(h),l):h===64?(e.consume(h),c):n(h)}function c(h){return h===46?e.check(sxe,d,u)(h):h===45||h===95||sa(h)?(i=!0,e.consume(h),c):d(h)}function u(h){return e.consume(h),a=!0,c}function d(h){return i&&a&&Na(r.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(h)):n(h)}}function oxe(e,t,n){const r=this;return a;function a(o){return o!==87&&o!==119||!g7.call(r,r.previous)||OC(r.events)?n(o):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(rxe,e.attempt(h7,e.attempt(f7,i),n),n)(o))}function i(o){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(o)}}function lxe(e,t,n){const r=this;let a="",i=!1;return o;
vendor: 7,898 bytes, line 788
788function o(h){return(h===72||h===104)&&y7.call(r,r.previous)&&!OC(r.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),a+=String.fromCodePoint(h),e.consume(h),l):n(h)}function l(h){if(Na(h)&&a.length<5)return a+=String.fromCodePoint(h),e.consume(h),l;if(h===58){const f=a.toLowerCase();if(f==="http"||f==="https")return e.consume(h),c}return n(h)}function c(h){return h===47?(e.consume(h),i?u:(i=!0,c)):n(h)}function u(h){return h===null||lb(h)||on(h)||jo(h)||ru(h)?n(h):e.attempt(h7,e.attempt(f7,d),n)(h)}function d(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(h)}}function cxe(e,t,n){let r=0;return a;function a(o){return(o===87||o===119)&&r<3?(r++,e.consume(o),a):o===46&&r===3?(e.consume(o),i):n(o)}function i(o){return o===null?n(o):t(o)}}function uxe(e,t,n){let r,a,i;return o;function o(u){return u===46||u===95?e.check(m7,c,l)(u):u===null||on(u)||jo(u)||u!==45&&ru(u)?c(u):(i=!0,e.consume(u),o)}function l(u){return u===95?r=!0:(a=r,r=void 0),e.consume(u),o}function c(u){return a||r||!i?n(u):t(u)}}function dxe(e,t){let n=0,r=0;return a;function a(o){return o===40?(n++,e.consume(o),a):o===41&&r<n?i(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?e.check(m7,t,i)(o):o===null||on(o)||jo(o)?t(o):(e.consume(o),a)}function i(o){return o===41&&r++,e.consume(o),a}}function hxe(e,t,n){return r;function r(l){return l===33||l===34||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===63||l===95||l===126?(e.consume(l),r):l===38?(e.consume(l),i):l===93?(e.consume(l),a):l===60||l===null||on(l)||jo(l)?t(l):n(l)}function a(l){return l===null||l===40||l===91||on(l)||jo(l)?t(l):r(l)}function i(l){return Na(l)?o(l):n(l)}function o(l){return l===59?(e.consume(l),r):Na(l)?(e.consume(l),o):n(l)}}function fxe(e,t,n){return r;function r(i){return e.consume(i),a}function a(i){return sa(i)?n(i):t(i)}}function g7(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||on(e)}function y7(e){return!Na(e)}function b7(e){return!(e===47||LN(e))}function LN(e){return e===43||e===45||e===46||e===95||sa(e)}function OC(e){let t=e.length,n=!1;for(;t--;){const r=e[t][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const mxe={tokenize:_xe,partial:!0};function pxe(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:bxe,continuation:{tokenize:vxe},exit:wxe}},text:{91:{name:"gfmFootnoteCall",tokenize:yxe},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:xxe,resolveTo:gxe}}}}function xxe(e,t,n){const r=this;let a=r.events.length;const i=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o;for(;a--;){const c=r.events[a][1];if(c.type==="labelImage"){o=c;break}if(c.type==="gfmFootnoteCall"||c.type==="labelLink"||c.type==="label"||c.type==="image"||c.type==="link")break}return l;function l(c){if(!o||!o._balanced)return n(c);const u=bo(r.sliceSerialize({start:o.end,end:r.now()}));return u.codePointAt(0)!==94||!i.includes(u.slice(1))?n(c):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(c),e.exit("gfmFootnoteCallLabelMarker"),t(c))}}function gxe(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},a={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};a.end.column++,a.end.offset++,a.end._bufferIndex++;const i={type:"gfmFootnoteCallString",start:Object.assign({},a.end),end:Object.assign({},e[e.length-1][1].start)},o={type:"chunkString",contentType:"string",start:Object.assign({},i.start),end:Object.assign({},i.end)},l=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",a,t],["exit",a,t],["enter",i,t],["enter",o,t],["exit",o,t],["exit",i,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...l),e}function yxe(e,t,n){const r=this,a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i=0,o;return l;function l(h){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),c}function c(h){return h!==94?n(h):(e.enter("gfmFootnoteCallMarker"),e.consume(h),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(h){if(i>999||h===93&&!o||h===null||h===91||on(h))return n(h);if(h===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return a.includes(bo(r.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(h)}return on(h)||(o=!0),i++,e.consume(h),h===92?d:u}function d(h){return h===91||h===92||h===93?(e.consume(h),i++,u):u(h)}}function bxe(e,t,n){const r=this,a=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let i,o=0,l;return c;function c(x){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(x),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(x){return x===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(x),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",d):n(x)}function d(x){if(o>999||x===93&&!l||x===null||x===91||on(x))return n(x);if(x===93){e.exit("chunkString");const g=e.exit("gfmFootnoteDefinitionLabelString");return i=bo(r.sliceSerialize(g)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(x),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return on(x)||(l=!0),o++,e.consume(x),x===92?h:d}function h(x){return x===91||x===92||x===93?(e.consume(x),o++,d):d(x)}function f(x){return x===58?(e.enter("definitionMarker"),e.consume(x),e.exit("definitionMarker"),a.includes(i)||a.push(i),Bt(e,m,"gfmFootnoteDefinitionWhitespace")):n(x)}function m(x){return t(x)}}function vxe(e,t,n){return e.check(dx,t,e.attempt(mxe,t,n))}function wxe(e){e.exit("gfmFootnoteDefinition")}function _xe(e,t,n){const r=this;return Bt(e,a,"gfmFootnoteDefinitionIndent",5);function a(i){const o=r.events[r.events.length-1];return o&&o[1].type==="gfmFootnoteDefinitionIndent"&&o[2].sliceSerialize(o[1],!0).length===4?t(i):n(i)}}function kxe(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:i,resolveAll:a};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function a(o,l){let c=-1;for(;++c<o.length;)if(o[c][0]==="enter"&&o[c][1].type==="strikethroughSequenceTemporary"&&o[c][1]._close){let u=c;for(;u--;)if(o[u][0]==="exit"&&o[u][1].type==="strikethroughSequenceTemporary"&&o[u][1]._open&&o[c][1].end.offset-o[c][1].start.offset===o[u][1].end.offset-o[u][1].start.offset){o[c][1].type="strikethroughSequence",o[u][1].type="strikethroughSequence";const d={type:"strikethrough",start:Object.assign({},o[u][1].start),end:Object.assign({},o[c][1].end)},h={type:"strikethroughText",start:Object.assign({},o[u][1].end),end:Object.assign({},o[c][1].start)},f=[["enter",d,l],["enter",o[u][1],l],["exit",o[u][1],l],["enter",h,l]],m=l.parser.constructs.insideSpan.null;m&&gi(f,f.length,0,h0(m,o.slice(u+1,c),l)),gi(f,f.length,0,[["exit",h,l],["enter",o[c][1],l],["exit",o[c][1],l],["exit",d,l]]),gi(o,u-1,c-u+3,f),c=u+f.length-2;break}}for(c=-1;++c<o.length;)o[c][1].type==="strikethroughSequenceTemporary"&&(o[c][1].type="data");return o}function i(o,l,c){const u=this.previous,d=this.events;let h=0;return f;function f(x){return u===126&&d[d.length-1][1].type!=="characterEscape"?c(x):(o.enter("strikethroughSequenceTemporary"),m(x))}function m(x){const g=qh(u);if(x===126)return h>
vendor: 4,072 bytes, line 788
7881?c(x):(o.consume(x),h++,m);if(h<2&&!n)return c(x);const y=o.exit("strikethroughSequenceTemporary"),b=qh(x);return y._open=!b||b===2&&!!g,y._close=!g||g===2&&!!b,l(x)}}}class jxe{constructor(){this.map=[]}add(t,n,r){Nxe(this,t,n,r)}consume(t){if(this.map.sort(function(i,o){return i[0]-o[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let a=r.pop();for(;a;){for(const i of a)t.push(i);a=r.pop()}this.map.length=0}}function Nxe(e,t,n,r){let a=0;if(!(n===0&&r.length===0)){for(;a<e.map.length;){if(e.map[a][0]===t){e.map[a][1]+=n,e.map[a][2].push(...r);return}a+=1}e.map.push([t,n,r])}}function Sxe(e,t){let n=!1;const r=[];for(;t<e.length;){const a=e[t];if(n){if(a[0]==="enter")a[1].type==="tableContent"&&r.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(a[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const i=r.length-1;r[i]=r[i]==="left"?"center":"right"}}else if(a[1].type==="tableDelimiterRow")break}else a[0]==="enter"&&a[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return r}function Cxe(){return{flow:{null:{name:"table",tokenize:Exe,resolveAll:Axe}}}}function Exe(e,t,n){const r=this;let a=0,i=0,o;return l;function l(C){let T=r.events.length-1;for(;T>-1;){const R=r.events[T][1].type;if(R==="lineEnding"||R==="linePrefix")T--;else break}const S=T>-1?r.events[T][1].type:null,O=S==="tableHead"||S==="tableRow"?j:c;return O===j&&r.parser.lazy[r.now().line]?n(C):O(C)}function c(C){return e.enter("tableHead"),e.enter("tableRow"),u(C)}function u(C){return C===124||(o=!0,i+=1),d(C)}function d(C){return C===null?n(C):ft(C)?i>1?(i=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),m):n(C):Vt(C)?Bt(e,d,"whitespace")(C):(i+=1,o&&(o=!1,a+=1),C===124?(e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),o=!0,d):(e.enter("data"),h(C)))}function h(C){return C===null||C===124||on(C)?(e.exit("data"),d(C)):(e.consume(C),C===92?f:h)}function f(C){return C===92||C===124?(e.consume(C),h):h(C)}function m(C){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(C):(e.enter("tableDelimiterRow"),o=!1,Vt(C)?Bt(e,x,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):x(C))}function x(C){return C===45||C===58?y(C):C===124?(o=!0,e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),g):k(C)}function g(C){return Vt(C)?Bt(e,y,"whitespace")(C):y(C)}function y(C){return C===58?(i+=1,o=!0,e.enter("tableDelimiterMarker"),e.consume(C),e.exit("tableDelimiterMarker"),b):C===45?(i+=1,b(C)):C===null||ft(C)?_(C):k(C)}function b(C){return C===45?(e.enter("tableDelimiterFiller"),v(C)):k(C)}function v(C){return C===45?(e.consume(C),v):C===58?(o=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(C),e.exit("tableDelimiterMarker"),w):(e.exit("tableDelimiterFiller"),w(C))}function w(C){return Vt(C)?Bt(e,_,"whitespace")(C):_(C)}function _(C){return C===124?x(C):C===null||ft(C)?!o||a!==i?k(C):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(C)):k(C)}function k(C){return n(C)}function j(C){return e.enter("tableRow"),N(C)}function N(C){return C===124?(e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),N):C===null||ft(C)?(e.exit("tableRow"),t(C)):Vt(C)?Bt(e,N,"whitespace")(C):(e.enter("data"),E(C))}function E(C){return C===null||C===124||on(C)?(e.exit("data"),N(C)):(e.consume(C),C===92?A:E)}function A(C){return C===92||C===124?(e.consume(C),E):E(C)}}function Axe(e,t){let n=-1,r=!0,a=0,i=[0,0,0,0],o=[0,0,0,0],l=!1,c=0,u,d,h;const f=new jxe;for(;++n<e.length;){const m=e[n],x=m[1];m[0]==="enter"?x.type==="tableHead"?(l=!1,c!==0&&(zI(f,t,c,u,d),d=void 0,c=0),u={type:"table",start:Object.assign({},x.start),end:Object.assign({},x.end)},f.add(n,0,[["enter",u,t]])):x.type==="tableRow"||x.type==="tableDelimiterRow"?(r=!0,h=void 0,i=[0,0,0,0],o=[0,n+1,0,0],l&&(l=!1,d={type:"tableBody",start:Object.assign({},x.start),end:Object.assign({},x.end)}
788,f.add(n,0,[["enter",d,t]])),a=x.type==="tableDelimiterRow"?2:d?3:1):a&&(x.type==="data"||x.type==="tableDelimiterMarker"||x.type==="tableDelimiterFiller")?(r=!1,o[2]===0&&(i[1]!==0&&(o[0]=o[1],h=bg(f,t,i,a,void 0,h),i=[0,0,0,0]),o[2]=n)):x.type==="tableCellDivider"&&(r?r=!1:(i[1]!==0&&(o[0]=o[1],h=bg(f,t,i,a,void 0,h)),i=o,o=[i[1],n,0,0])):x.type==="tableHead"?(l=!0,c=n):x.type==="tableRow"||x.type==="tableDelimiterRow"?(c=n,i[1]!==0?(o[0]=o[1],h=bg(f,t,i,a,n,h)):o[1]!==0&&(h=bg(f,t,o,a,n,h)),a=0):a&&(x.type==="data"||x.type==="tableDelimiterMarker"||x.type==="tableDelimiterFiller")&&(o[3]=n)}for(c!==0&&zI(f,t,c,u,d),f.consume(t.events),n=-1;++n<t.events.length;){const m=t.events[n];m[0]==="enter"&&m[1].type==="table"&&(m[1]._align=Sxe(t.events,n))}return e}function bg(e,t,n,r,a,i){const o=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",l="tableContent";n[0]!==0&&(i.end=Object.assign({},yh(t.events,n[0])),e.add(n[0],0,[["exit",i,t]]));const c=yh(t.events,n[1]);if(i={type:o,start:Object.assign({},c),end:Object.assign({},c)},e.add(n[1],0,[["enter",i,t]]),n[2]!==0){const u=yh(t.events,n[2]),d=yh(t.events,n[3]),h={type:l,start:Object.assign({},u),end:Object.assign({},d)};if(e.add(n[2],0,[["enter",h,t]]),r!==2){const f=t.events[n[2]],m=t.events[n[3]];if(f[1].end=Object.assign({},m[1].end),f[1].type="chunkText",f[1].contentType="text",n[3]>n[2]+1){const x=n[2]+1,g=n[3]-n[2]-1;e.add(x,g,[])}}e.add(n[3]+1,0,[["exit",h,t]])}return a!==void 0&&(i.end=Object.assign({},yh(t.events,a)),e.add(a,0,[["exit",i,t]]),i=void 0),i}function zI(e,t,n,r,a){const i=[],o=yh(t.events,n);a&&(a.end=Object.assign({},o),i.push(["exit",a,t])),r.end=Object.assign({},o),i.push(["exit",r,t]),e.add(n+1,0,i)}function yh(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const Txe={name:"tasklistCheck",tokenize:Ixe};function Oxe(){return{text:{91:Txe}}}function Ixe(e,t,n){const r=this;return a;function a(c){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(c):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),i)}function i(c){return on(c)?(e.enter("taskListCheckValueUnchecked"),e.consume(c),e.exit("taskListCheckValueUnchecked"),o):c===88||c===120?(e.enter("taskListCheckValueChecked"),e.consume(c),e.exit("taskListCheckValueChecked"),o):n(c)}function o(c){return c===93?(e.enter("taskListCheckMarker"),e.consume(c),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),l):n(c)}function l(c){return ft(c)?t(c):Vt(c)?e.check({tokenize:Pxe},t,n)(c):n(c)}}function Pxe(e,t,n){return Bt(e,r,"whitespace");function r(a){return a===null?n(a):t(a)}}function Rxe(e){return OB([axe(),pxe(),kxe(e),Cxe(),Oxe()])}const Dxe={};function px(e){const t=this,n=e||Dxe,r=t.data(),a=r.micromarkExtensions||(r.micromarkExtensions=[]),i=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),o=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);a.push(Rxe(n)),i.push(txe()),o.push(nxe(n))}const v7=p.createContext(null);function w7(e){const t=String(e||"").trim();return!(!t.startsWith("/")||t.startsWith("//")||/^https?:/i.test(t)||/github\.com/i.test(t))}function Mxe(e){return/github\.com/i.test(String(e||""))}function $xe({userId:e,children:t}){const[n,r]=p.useState(!1),[a,i]=p.useState([]),[o,l]=p.useState(0),[c,u]=p.useState(!1),[d,h]=p.useState(!1),f=p.useCallback(()=>r(b=>!b),[]),m=p.useCallback(()=>r(!1),[]),x=p.useCallback(()=>{if(!e){i([]),l(0);return}u(!0),h(!1),Ey.list().then(b=>{i(b.notifications),l(b.unread_count),u(!1)}).catch(()=>{h(!0),u(!1)})},[e]);p.useEffect(()=>{x()},[x]),p.useEffect(()=>{if(!e)return;let b=null;const v=xn.channel(`notifications:${e}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"notifications",filter:`recipient_user_id=eq.${e}`},()=>{b&&clearTimeout(b),b=setTimeout(()=>{x(),b=null},400)}).subscribe();return()=>{b&&clearTimeout(b),xn.removeChannel(v)}},[e,x]);const g=p.useCallback(b=>{let v=!1;i(w=>w.map(_=>_.id===b&&!_.read_at?(v=!0,{..._,read_at:new Date().toISOString()}):_)),v&&(l(w=>Math.max(0,w-1)),Ey.markRead(b).catch(()=>x()))},[x]),y=p.useCallback(()=>
788{if(o===0)return;const b=new Date().toISOString();i(v=>v.map(w=>w.read_at?w:{...w,read_at:b})),l(0),Ey.markAllRead().catch(()=>x())},[o,x]);return s.jsx(v7.Provider,{value:{open:n,toggle:f,close:m,items:a,unreadCount:o,loading:c,errored:d,markRead:g,markAllRead:y},children:t})}function _7(){const e=p.useContext(v7);return e||{open:!1,toggle:()=>{},close:()=>{},items:[],unreadCount:0,loading:!1,errored:!1,markRead:()=>{},markAllRead:()=>{}}}function Lxe(){const{open:e,close:t,items:n,unreadCount:r,loading:a,errored:i,markRead:o,markAllRead:l}=_7(),c=Rt(),[u,d]=p.useState(null),h=u!=null?n.find(g=>g.id===u)??null:null,f=p.useCallback(g=>{g||(d(null),t())},[t]),m=p.useCallback(g=>{o(g.id),d(g.id)},[o]),x=p.useCallback(g=>{w7(g.link_url)&&(d(null),t(),c(g.link_url))},[c,t]);return s.jsx(Cr,{open:e,onOpenChange:f,children:s.jsxs(mr,{side:"right",size:h?"lg":"md",className:"transition-[width,max-width] duration-200",children:[s.jsxs(Er,{className:"flex items-center gap-2 pr-10",children:[h?s.jsxs("button",{type:"button",onClick:()=>d(null),className:"inline-flex items-center gap-1 text-sm text-text-secondary hover:text-text-primary rounded px-1 py-0.5 hover:bg-surface-sunken -ml-1",children:[s.jsx(ff,{className:"w-4 h-4"}),"Back"]}):s.jsxs(s.Fragment,{children:[s.jsx(xr,{className:"flex-1",children:"Notifications"}),r>0&&s.jsxs("button",{type:"button",onClick:l,className:"text-xs text-text-secondary hover:text-text-primary inline-flex items-center gap-1 rounded px-1.5 py-1 hover:bg-surface-sunken",title:"Mark all as read",children:[s.jsx(Ote,{className:"w-3.5 h-3.5"}),"Mark all read"]})]}),s.jsx(Mr,{className:"sr-only",children:"Messages and updates published to your account."})]}),h?s.jsx(Uxe,{row:h,onCta:()=>x(h)}):s.jsx(pr,{children:a&&n.length===0?s.jsx(S1,{title:"Loadingâ¦"}):i?s.jsx(S1,{title:"Couldn't load notifications. Try again."}):n.length===0?s.jsx(S1,{title:"You have no notifications.",subtitle:"We'll let you know
788when we have something new for you."}):s.jsx("ul",{className:"divide-y divide-outline-faint",children:n.map(g=>s.jsx(Fxe,{row:g,onClick:()=>m(g)},g.id))})})]})})}function Fxe({row:e,onClick:t}){const n=!e.read_at,r=e.summary??e.body;return s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:t,className:B("w-full text-left px-4 py-3 min-h-11 flex items-start gap-2.5 hover:bg-surface-sunken",n&&"bg-surface-infoSubtle/40"),children:[s.jsx("span",{className:B("mt-1.5 w-2 h-2 rounded-full shrink-0",n?"bg-intent-info":"bg-transparent"),"aria-hidden":!0}),s.jsxs("span",{className:"flex-1 min-w-0",children:[s.jsxs("span",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:B("text-sm truncate",n?"text-text-primary font-semibold":"text-text-secondary"),children:e.title}),s.jsx("span",{className:"text-xs text-text-tertiary shrink-0",children:zxe(e.created_at)})]}),s.jsx("span",{className:"block text-xs text-text-secondary mt-0.5 line-clamp-2",children:r})]}),s.jsx(fr,{className:"w-4 h-4 text-text-tertiary shrink-0 mt-0.5","aria-hidden":!0})]})})}const Bxe={p:({node:e,...t})=>s.jsx("p",{className:"text-sm text-text-body leading-relaxed my-2.5",...t}),h1:({node:e,...t})=>s.jsx("h1",{className:"text-base font-semibold text-text-primary mt-5 mb-1.5",...t}),h2:({node:e,...t})=>s.jsx("h2",{className:"text-sm font-semibold text-text-primary mt-5 mb-1.5",...t}),h3:({node:e,...t})=>s.jsx("h3",{className:"text-sm font-semibold text-text-secondary mt-4 mb-1",...t}),ul:({node:e,...t})=>s.jsx("ul",{className:"list-disc pl-5 my-2.5 space-y-1.5",...t}),ol:({node:e,...t})=>s.jsx("ol",{className:"list-decimal pl-5 my-2.5 space-y-1.5",...t}),li:({node:e,...t})=>s.jsx("li",{className:"text-sm text-text-body leading-relaxed pl-0.5",...t}),a:({node:e,href:t,children:n,...r})=>Mxe(t)?s.jsx("span",{...r,children:n}):s.jsx("a",{className:"text-intent-info underline underline-offset-2 hover:no-underline",target:"_blank",rel:"noopener noreferrer",...r,href:t,children:n}),strong:({node:e,...t})=>s.jsx("strong",{className:"font-semibold text-text-primary",...t}),em:({node:e,...t})=>s.jsx("em",{className:"italic",...t}),code:({node:e,...t})=>s.jsx("code",{className:"px-1 py-0.5 rounded bg-surface-sunken text-text-primary text-[0.85em]",...t}),hr:({node:e,...t})=>s.jsx("hr",{className:"my-4 border-outline-subtle",...t}),blockquote:({node:e,...t})=>s.jsx("blockquote",{className:"border-l-2 border-outline-subtle pl-3 my-2.5 text-text-secondary",...t})};function Uxe({row:e,onCta:t}){return s.jsx(pr,{children:s.jsxs("div",{className:"px-5 py-4",children:[s.jsx("h2",{className:"text-base font-semibold text-text-primary",children:e.title}),s.jsx("div",{className:"text-xs text-text-tertiary mt-0.5",children:Wxe(e.created_at)}),s.jsx("div",{className:"mt-3 [&>*:first-child]:mt-0",children:s.jsx(mx,{remarkPlugins:[px],components:Bxe,children:e.body})}),w7(e.link_url)&&s.jsxs("button",{type:"button",onClick:t,className:"mt-5 inline-flex items-center gap-1.5 rounded-md px-3 py-2 text-sm font-medium bg-intent-info hover:bg-intent-infoHover text-text-inverse",children:[e.cta_label??"Open",s.jsx(fr,{className:"w-4 h-4"})]})]})})}function S1({title:e,subtitle:t}){return s.jsxs("div",{className:"p-8 text-center",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:e}),t&&s.jsx("div",{className:"text-sm text-text-secondary mt-1",children:t})]})}function zxe(e){const t=new Date(e),n=new Date;return t.toDateString()===n.toDateString()?t.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit"}):t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function Wxe(e){return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}var Kxe=Object.defineProperty,vs=(e,t)=>Kxe(e,"name",{value:t,configurable:!0});function k7(e){const t=e+"CollectionProvider",[n,r]=du(t),[a,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),o=vs(g=>{const{scope:y,children:b}=g,v=p.useRef(null),w=p.useRef(new Map).current;return s.jsx(a,{scope:y,itemMap:w,collectionRef:v,children:b})},"CollectionProvider");o.displayName=t;const l=e+"CollectionSlot",c=op(l),u=p.forwardRef((g,y)=>{const{scope:b,children:v}
788=g,w=i(l,b),_=oa(y,w.collectionRef);return s.jsx(c,{ref:_,children:v})});u.displayName=l;const d=e+"CollectionItemSlot",h="data-radix-collection-item",f=op(d),m=p.forwardRef((g,y)=>{const{scope:b,children:v,...w}=g,_=p.useRef(null),k=oa(y,_),j=i(d,b);return p.useEffect(()=>(j.itemMap.set(_,{ref:_,...w}),()=>void j.itemMap.delete(_))),s.jsx(f,{[h]:"",ref:k,children:v})});m.displayName=d;function x(g){const y=i(e+"CollectionConsumer",g);return p.useCallback(()=>{const v=y.collectionRef.current;if(!v)return[];const w=Array.from(v.querySelectorAll(`[${h}]`));return Array.from(y.itemMap.values()).sort((j,N)=>w.indexOf(j.ref.current)-w.indexOf(N.ref.current))},[y.collectionRef,y.itemMap])}return vs(x,"useCollection"),[{Provider:o,Slot:u,ItemSlot:m},x,r]}vs(k7,"createCollection");var WI=new WeakMap,Hr,hi,C1=(hi=class extends Map{constructor(n){super(n);pT(this,Hr);Yw(this,Hr,[...super.keys()]),WI.set(this,!0)}set(n,r){return WI.get(this)&&(this.has(n)?Ys(this,Hr)[Ys(this,Hr).indexOf(n)]=n:Ys(this,Hr).push(n)),super.set(n,r),this}insert(n,r,a){const i=this.has(r),o=Ys(this,Hr).length,l=IC(n);let c=l>=0?l:o+l;const u=c<0||c>=o?-1:c;if(u===this.size||i&&u===this.size-1||u===-1)return this.set(r,a),this;const d=this.size+(i?0:1);l<0&&c++;const h=[...Ys(this,Hr)];let f,m=!1;for(let x=c;x<d;x++)if(c===x){let g=h[x];h[x]===r&&(g=h[x+1]),i&&this.delete(r),f=this.get(g),this.set(r,a)}else{!m&&h[x-1]===r&&(m=!0);const g=h[m?x:x-1],y=f;f=this.get(g),this.delete(g),this.set(g,y)}return this}with(n,r,a){const i=new hi(this);return i.insert(n,r,a),i}before(n){const r=Ys(this,Hr).indexOf(n)-1;if(!(r<0))return this.entryAt(r)}setBefore(n,r,a){const i=Ys(this,Hr).indexOf(n);return i===-1?this:this.insert(i,r,a)}after(n){let r=Ys(this,Hr).indexOf(n);if(r=r===-1||r===this.size-1?-1:r+1,r!==-1)return this.entryAt(r)}setAfter(n,r,a){const i=Ys(this,Hr).indexOf(n);return i===-1?this:this.insert(i+1,r,a)}first(){return this.entryAt(0)}last(){return this.entryAt(-1)}clear(){return Yw(this,Hr,[]),super.clear()}delete(n){const r=super.delete(n);return r&&Ys(this,Hr).splice(Ys(this,Hr).indexOf(n),1),r}deleteAt(n){const r=this.keyAt(n);return r!==void 0?this.delete(r):!1}at(n){const r=Oy(Ys(this,Hr),n);if(r!==void 0)return this.get(r)}entryAt(n){const r=Oy(Ys(this,Hr),n);if(r!==void 0)return[r,this.get(r)]}indexOf(n){return Ys(this,Hr).indexOf(n)}keyAt(n){return Oy(Ys(this,Hr),n)}from(n,r){const a=this.indexOf(n);if(a===-1)return;let i=a+r;return i<0&&(i=0),i>=this.size&&(i=this.size-1),this.at(i)}keyFrom(n,r){const a=this.indexOf(n);if(a===-1)return;let i=a+r;return i<0&&(i=0),i>=this.size&&(i=this.size-1),this.keyAt(i)}find(n,r){let a=0;for(const i of this){if(Reflect.apply(n,r,[i,a,this]))return i;a++}}findIndex(n,r){let a=0;for(const i of this){if(Reflect.apply(n,r,[i,a,this]))return a;a++}return-1}filter(n,r){const a=[];let i=0;for(const o of this)Reflect.apply(n,r,[o,i,this])&&a.push(o),i++;return new hi(a)}map(n,r){const a=[];let i=0;for(const o of this)a.push([o[0],Reflect.apply(n,r,[o,i,this])]),i++;return new hi(a)}reduce(...n){const[r,a]=n;let i=0,o=a??this.at(0);for(const l of this)i===0&&n.length===1?o=l:o=Reflect.apply(r,this,[o,l,i,this]),i++;return o}reduceRight(...n){const[r,a]=n;let i=a??this.at(-1);for(let o=this.size-1;o>=0;o--){const l=this.at(o);o===this.size-1&&n.length===1?i=l:i=Reflect.apply(r,this,[i,l,o,this])}return i}toSorted(n){const r=[...this.entries()].sort(n);return new hi(r)}toReversed(){const n=new hi;for(let r=this.size-1;r>=0;r--){const a=this.keyAt(r),i=this.get(a);n.set(a,i)}return n}toSpliced(...n){const r=[...this.entries()];return r.splice(...n),new hi(r)}slice(n,r){const a=new hi;let i=this.size-1;if(n===void 0)return a;n<0&&(n=n+this.size),r!==void 0&&r>0&&(i=r-1);for(let o=n;o<=i;o++){const l=this.keyAt(o),c=this.get(l);a.set(l,c)}return a}every(n,r){let a=0;for(const i of this){if(!Reflect.apply(n,r,[i,a,this]))return!1;a++}return!0}some(n,r){let a=0;for(const i of this){if(Reflect.apply(n,r,[i,a,this]))return!0;a++}return!1}},Hr=new WeakMap,vs(hi,"OrderedDict"),hi);function Oy(e,t){if("at"in Array.prototype)return Array.prototype.at.call(e,t);const n=j7(e,t);return n===-1?void 0:e[n]}vs(Oy,"at");function j7(e,t){const n=e.length,r=IC(t),a=r>=0?r:n+r;return a<0||a>=n?-1:a}vs(j7,"toSafeIndex");function IC(e){return e!==e||e===0?0:Math.trunc(e)}vs(IC,"toSafeInteger");function Hxe(e){const t=e+"CollectionProvider",[n,r]=du(t),[a,i]=n(t,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new C1,setItemMap:vs(()=>{},"setItemMap")}),o=vs(({state:w,..._})=>w?s.jsx(c,{..._,state:w}):s.jsx(l,{..._}),"CollectionProvider");o.displayName=t;const l=vs(w=>{const _=y();return s.jsx(c,{...w,state:_})},"CollectionInit");l.displayName=t+"Init";const c=vs(w=>{const{scope:_,children:k,state:j}=w,N=p.useRef(null),[E,A]=p.useState(null),C=oa(N,A),[T,S]=j;return p.useEffect(()=>{if(!E)return;const O=C7(()=>{});return O.observe(E,{childList:!0,subtree:!0}),()=>{O.disconnect()}},[E]),s.jsx(a,{scope:_,itemMap:T,setItemMap:S,collectionRef:C,collectionRefObject:N,collectionElement:E,children:k})},"CollectionProviderImpl");c.displayName=t+"Impl";const u=e+"CollectionSlot",d=op(u),h=p.forwardRef((w,_)=>{const{scope:k,children:j}=w,N=i(u,k),E=oa(_,N.collectionRef);return s.jsx(d,{ref:E,children:j})});h.displayName=u;const f=e+"CollectionItemSlot",m="data-radix-collection-item",x=op(f),g=p.forwardRef((w,_)=>{const{scope:k,children:j,...N}=w,E=p.useRef(null),[A,C]=p.useState(null),T=oa(_,E,C),S=i(f,k),{setItemMap:O}=S,R=p.useRef(N);N7(R.current,N)||(R.current=N);const I=R.current;return p.useEffect(()=>{const $=I;return O(P=>A?P.has(A)?P.set(A,{...$,element:A}).toSorted(FN):(P.set(A,{...$,element:A}),P.toSorted(FN)):P),()=>{O(P=>!A||!P.has(A)?P:(P.delete(A),new C1(P)))}},[A,I,O]),s.jsx(x,{[m]:"",ref:T,children:j})});g.displayName=f;function y(){return p.useState(new C1)}vs(y,"useInitCollection");function b(w){const{itemMap:_}=i(e+"CollectionConsumer",w);return _}return vs(b,"useCollection"),[{Provider:o,Slot:h,ItemSlot:g},{createCollectionScope:r,useCollection:b,useInitCollection:y}]}vs(Hxe,"createCollection");function N7(e,t){if(e===t)return!0;
788if(typeof e!="object"||typeof t!="object"||e==null||t==null)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const a of n)if(!Object.prototype.hasOwnProperty.call(t,a)||e[a]!==t[a])return!1;return!0}vs(N7,"shallowEqual");function S7(e,t){return!!(t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_PRECEDING)}vs(S7,"isElementPreceding");function FN(e,t){return!e[1].element||!t[1].element?0:S7(e[1].element,t[1].element)?-1:1}vs(FN,"sortByDocumentPosition");function C7(e){return new MutationObserver(n=>{for(const r of n)if(r.type==="childList"){e();return}})}vs(C7,"getChildListObserver");var Vxe=Object.defineProperty,qxe=(e,t)=>Vxe(e,"name",{value:t,configurable:!0}),Gxe=p.createContext(void 0);function PC(e){const t=p.useContext(Gxe);return e||t||"ltr"}qxe(PC,"useDirection");var Yxe=Object.defineProperty,RC=(e,t)=>Yxe(e,"name",{value:t,configurable:!0}),E1=!1;function E7(){const[e,t]=p.useState(E1);return p.useEffect(()=>{E1||(E1=!0,t(!0))},[]),e}RC(E7,"useIsHydrated");var A7=o6[" useSyncExternalStore ".trim().toString()];function T7(){return()=>{}}RC(T7,"subscribe");function O7(){return A7(T7,()=>!0,()=>!1)}RC(O7,"useIsHydratedModern");var Zxe=typeof A7=="function"?O7:E7,Xxe=Object.defineProperty,Md=(e,t)=>Xxe(e,"name",{value:t,configurable:!0}),A1="rovingFocusGroup.onEntryFocus",Jxe={bubbles:!1,cancelable:!0},x0="RovingFocusGroup",[BN,I7,Qxe]=k7(x0),[ege,P7]=du(x0,[Qxe]),[tge,nge]=ege(x0),rge=p.forwardRef(Md(function(t,n){return s.jsx(BN.Provider,{scope:t.__scopeRovingFocusGroup,children:s.jsx(BN.Slot,{scope:t.__scopeRovingFocusGroup,children:s.jsx(sge,{...t,ref:n})})})},"RovingFocusGroup")),sge=p.forwardRef(Md(function(t,n){const{__scopeRovingFocusGroup:r,orientation:a,loop:i=!1,dir:o,currentTabStopId:l,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:u,onEntryFocus:d,preventScrollOnEntryFocus:h=!1,...f}=t,m=p.useRef(null),x=oa(n,m),g=PC(o),[y,b]=Jp({prop:l,defaultProp:c??null,onChange:u,caller:x0}),[v,w]=p.useState(!1),_=MY(d),k=I7(r),j=p.useRef(!1),[N,E]=p.useState(0);return p.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(A1,_),()=>A.removeEventListener(A1,_)},[_]),s.jsx(tge,{scope:r,orientation:a,dir:g,loop:i,currentTabStopId:y,onItemFocus:p.useCallback(A=>b(A),[b]),onItemShiftTab:p.useCallback(()=>w(!0),[]),onFocusableItemAdd:p.useCallback(()=>E(A=>A+1),[]),onFocusableItemRemove:p.useCallback(()=>E(A=>A-1),[]),children:s.jsx(ji.div,{tabIndex:v||N===0?-1:0,"data-orientation":a,...f,ref:x,style:{outline:"none",...t.style},onMouseDown:cs(t.onMouseDown,()=>{j.current=!0}),onFocus:cs(t.onFocus,A=>{const C=!j.current;if(A.target===A.currentTarget&&C&&!v){const T=new CustomEvent(A1,Jxe);if(A.currentTarget.dispatchEvent(T),!T.defaultPrevented){const S=k().filter(P=>P.focusable),O=S.find(P=>P.active),R=S.find(P=>P.id===y),$=[O,R,...S].filter(Boolean).map(P=>P.ref.current);DC($,h)}}j.current=!1}),onBlur:cs(t.onBlur,()=>w(!1))})})},"RovingFocusGroupImpl")),age="RovingFocusGroupItem",ige=p.forwardRef(Md(function(t,n){const{__scopeRovingFocusGroup:r,focusable:a=!0,active:i=!1,tabStopId:o,children:l,...c}=t,u=l6(),d=o||u,h=nge(age,r),f=h.currentTabStopId===d,m=I7(r),{onFocusableItemAdd:x,onFocusableItemRemove:g,currentTabStopId:y}=h,b=Zxe();return DY(()=>{if(!(!b||!a))return x(),()=>g()},[b,a,x,g]),p.useEffect(()=>{if(!(b||!a))return x(),()=>g()},[b,a,x,g]),s.jsx(BN.ItemSlot,{scope:r,id:d,focusable:a,active:i,children:s.jsx(ji.span,{tabIndex:f?0:-1,"data-orientation":h.orientation,...c,ref:n,onMouseDown:cs(t.onMouseDown,v=>{a?h.onItemFocus(d):v.preventDefault()}),onFocus:cs(t.onFocus,()=>h.onItemFocus(d)),onKeyDown:cs(t.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){h.onItemShiftTab();return}if(v.target!==v.currentTarget)return;const w=D7(v,h.orientation,h.dir);if(w!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let k=m().filter(j=>j.focusable).map(j=>j.ref.current);if(w==="last")k.reverse();else if(w==="prev"||w==="next"){w==="prev"&&k.reverse();const j=k.indexOf(v.currentTarget);k=h.loop?M7(k,j+1):k.slice(j+1)}setTimeout(()=>DC(k))}}),children:typeof l=="function"?l({isCurrentTabStop:f,hasTabStop:y!=null}):l})})},"RovingFocusGroupItem")),oge={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function R7(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}Md(R7,"getDirectionAwareKey");function D7(e,t,n){const r=R7(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return oge[r]}Md(D7,"getFocusIntent");function DC(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}Md(DC,"focusFirst");function M7(e,t){return e.map((n,r)=>e[(t+r)%e.length])}Md(M7,"wrapArray");var lge=rge,cge=ige,uge=Object.defineProperty,la=(e,t)=>uge(e,"name",{value:t,configurable:!0}),$7="Radio",[dge,L7]=du($7),[hge,g0]=dge($7);function F7(e){const{__scopeRadio:t,checked:n=!1,children:r,disabled:a,form:i,name:o,onCheck:l,required:c,value:u="on",internal_do_not_use_render:d}=e,[h,f]=p.useState(null),[m,x]=p.useState(null),g=p.useRef(!1),[y,b]=p.useReducer(_=>_+1,0),v=h?!!i||!!h.closest("form"):!0,w={checked:n,disabled:a,required:c,name:o,form:i,value:u,control:h,setControl:f,hasConsumerStoppedPropagationRef:g,userInteractionCount:y,onUserInteraction:b,isFormControl:v,bubbleInput:m,setBubbleInput:x,onCheck:la(()=>l==null?void 0:l(),"onCheck")};return s.jsx(hge,{scope:t,...w,children:B7(d)?d(w):r})}la(F7,"RadioProvider");var fge="RadioTrigger",mge=p.forwardRef(la(function({__scopeRadio:t,onClick:n,...r},a){const{checked:i,disabled:o,value:l,setControl:c,onCheck:u,hasConsumerStoppedPropagationRef:d,onUserInteraction:h,isFormControl:f,bubbleInput:m}=g0(fge,t),x=oa(a,c);return s.jsx(ji.button,{type:"button",role:"radio","aria-checked":i,"data-state":MC(i),"data-disabled":o?"":void 0,disabled:o,value:l,...r,ref:x,onClick:cs(n,g=>{i||(h(),u()),m&&f&&(d.current=g.isPropagationStopped(),d.current||g.stopPropagation())})})},"RadioTrigger")),pge="RadioIndicator",xge=p.forwardRef(la(function(t,n){const{__scopeRadio:r,forceMount:a,...i}=t,o=g0(pge,r);return s.jsx(Wv,{present:a||o.checked,children:s.jsx(ji.span,{"data-state":MC(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:n})})},"RadioIndicator")),gge="RadioBubbleInput",yge=p.forwardRef(la(function({__scopeRadio:t,onClick:n,...r},a){const{control:i,checked:o,required:l,disabled:c,name:u,value:d,form:h,bubbleInput:f,setBubbleInput:m,hasConsumerStoppedPropagationRef:x,userInteractionCount:g}=g0(gge,t),y=oa(a,m),b=_2(i),v=p.useRef(!1),w=p.useRef(o),_=p.useRef(g);p.useEffect(()=>{const j=f;if(!j)return;const N=window.HTMLInputElement.prototype,A=Object.getOwnPropertyDescriptor(N,"checked").set,C=g!==_.current;_.current=g;const T=w.current!==o;w.current=o;const S=!(C&&x.current);if(T&&A){v.current=!C;const O=new Event("click",{bubbles:S});A.call(j,o),j.dispatchEvent(O),v.current=!1}},[f,o,x,g]);const k=p.useRef(o);return s.jsx(ji.input,{type:"radio","aria-hidden":!0,defaultChecked:k.current,required:l,disabled:c,name:u,value:d,form:h,...r,tabIndex:-1,ref:y,onClick:cs(n,j=>{v.current&&j.stopPropagation()}),style:{...r.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"RadioBubbleInput"));function B7(e){return typeof e=="function"}la(B7,"isFunction");function MC(e){return e?"checked":"unchecked"}la(MC,"getState");var bge=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],$C="RadioGroup",[vge,prt]=du($C,[P7,L7]),U7=P7(),y0=L7(),[wge,_ge]=vge($C
788),z7=p.forwardRef(la(function(t,n){const{__scopeRadioGroup:r,name:a,form:i,defaultValue:o,value:l,required:c=!1,disabled:u=!1,orientation:d,dir:h,loop:f=!0,onValueChange:m,...x}=t,g=U7(r),y=PC(h),[b,v]=Jp({prop:l,defaultProp:o??null,onChange:m,caller:$C}),[w,_]=p.useState(null),k=oa(n,_),j=p.useRef(b);return p.useEffect(()=>{const N=i?w==null?void 0:w.ownerDocument.getElementById(i):w==null?void 0:w.closest("form");if(N instanceof HTMLFormElement){const E=la(()=>v(j.current),"reset");return N.addEventListener("reset",E),()=>N.removeEventListener("reset",E)}},[w,i,v]),s.jsx(wge,{scope:r,name:a,form:i,required:c,disabled:u,value:b,onValueChange:v,children:s.jsx(lge,{asChild:!0,...g,orientation:d,dir:y,loop:f,children:s.jsx(ji.div,{role:"radiogroup","aria-required":c,"aria-orientation":d,"data-disabled":u?"":void 0,dir:y,...x,ref:k})})})},"RadioGroup")),kge="RadioGroupItemProvider",jge="RadioGroupItemTrigger";function W7(e){const{__scopeRadioGroup:t,value:n,disabled:r,children:a,internal_do_not_use_render:i}=e,o=_ge(kge,t),l=y0(t),c=o.disabled||r;return s.jsx(F7,{...l,checked:o.value===n,disabled:c,required:o.required,name:o.name,form:o.form,value:n,onCheck:()=>o.onValueChange(n),internal_do_not_use_render:i,children:a})}la(W7,"RadioGroupItemProvider");var Nge=p.forwardRef(la(function(t,n){const{__scopeRadioGroup:r,...a}=t,i=U7(r),o=y0(r),{checked:l,disabled:c}=g0(jge,o.__scopeRadio),u=p.useRef(null),d=oa(n,u),h=p.useRef(!1);return p.useEffect(()=>{const f=la(x=>{bge.includes(x.key)&&(h.current=!0)},"handleKeyDown"),m=la(()=>h.current=!1,"handleKeyUp");return document.addEventListener("keydown",f),document.addEventListener("keyup",m),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",m)}},[]),s.jsx(cge,{asChild:!0,...i,focusable:!c,active:l,children:s.jsx(mge,{...o,...a,ref:d,onKeyDown:cs(a.onKeyDown,f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:cs(a.onFocus,()=>{var f;h.current&&((f=u.current)==null||f.click())})})})},"RadioGroupItemTrigger")),K7=p.forwardRef(la(function(t,n){const{__scopeRadioGroup:r,value:a,disabled:i,...o}=t;return s.jsx(W7,{__scopeRadioGroup:r,value:a,disabled:i,internal_do_not_use_render:({isFormControl:l})=>s.jsxs(s.Fragment,{children:[s.jsx(Nge,{...o,ref:n,__scopeRadioGroup:r}),l&&s.jsx(Sge,{__scopeRadioGroup:r})]})})},"RadioGroupItem")),Sge=p.forwardRef(la(function(t,n){const{__scopeRadioGroup:r,...a}=t,i=y0(r);return s.jsx(yge,{...i,...a,ref:n})},"RadioGroupItemBubbleInput")),Cge=p.forwardRef(la(function(t,n){const{__scopeRadioGroup:r,...a}=t,i=y0(r);return s.jsx(xge,{...i,...a,ref:n})},"RadioGroupIndicator"));const Ege=hf("inline-flex items-center rounded-md border bg-surface p-0.5 font-medium",{variants:{variant:{neutral:"border-outline",brand:"border-outline-subtle"},size:{sm:"text-body-lg md:text-body-sm",md:"text-body-lg md:text-body-md"}},defaultVariants:{variant:"brand",size:"sm"}}),Age=hf("inline-flex items-center gap-1.5 rounded-nested transition-colors focus:outline-none focus-visible:shadow-focus disabled:cursor-not-allowed disabled:opacity-50",{variants:{variant:{neutral:"text-text-secondary hover:bg-surface-subtle data-[state=checked]:bg-surface-inverse data-[state=checked]:text-text-inverse",brand:"text-text-secondary hover:bg-surface-subtle data-[state=checked]:bg-surface-brandSubtle data-[state=checked]:text-text-brand"},size:{sm:"min-h-11 px-3 py-2.5 md:min-h-0 md:px-2.5 md:py-1",md:"min-h-11 px-3 py-2.5 md:min-h-0 md:px-3 md:py-1.5"}},defaultVariants:{variant:"brand",size:"sm"}}),H7=p.createContext({variant:"brand",size:"sm"}),Pa=p.forwardRef(({className:e,variant:t,size:n,...r},a)=>{const i=t??"brand",o=n??"sm";return s.jsx(H7.Provider,{value:{variant:i,size:o},children:s.jsx(z7,{ref:a,orientation:"horizontal",className:B(Ege({variant:i,size:o}),e),...r})})});Pa.displayName="SegmentedControl";const Ln=p.forwardRef(({className:e,children:t,...n},r)=>{const{variant:a,size:i}=p.useContext(H7);return s.jsx(K7,{ref:r,className:B(Age({variant:a,size:i}),e),...n,children:t})});Ln.displayName="SegmentedControlItem";const Cp={"/agent":{title:"Chat",purpose:"Your AI workspace for the whole book. Ask about any seller you manage â sales, returns, transactions, rollups â and trigger real actions like syncs, onboarding, or key validation, all in plain language.",solves:"Answering a question about any seller usually means digging through Takealot exports, spreadsheets, and separate tools before you can even start.",helps:"You ask in plain language and get the answer â and the action â in one place, across your whole book, without leaving the conversation.",features:["Scope a conversation to one seller with the Seller picker, or leave it on âNo seller (workspace)â to ask across your entire book","Type any question; the assistant reads live account data and runs the right skill for you","Kick off actions from chat â sync a seller, onboard a new account, validate a Takealot key","Start a fresh chat any time, or reopen a past conversation from the sidebar"],ask:"Which of my sellers need attention this week?"},"/overview":{title:"All Accounts",purpose:"A book-wide dashboard that sums the headline numbers across every store you can see â the portfolio-level read before you drill into any one seller.",solves:"With a book of stores, itâs hard to tell at a glance which accounts are growing, slipping, or bleeding returns.",helps:"One rollup ranks every account on the numbers that matter, so you know
788where to spend your attention before you drill in.",features:["Read the top-line stat cards: 30-day and 90-day sales, 90-day return rate, and how many accounts are in the rollup","Sort the âBy account · last 30 daysâ table by sales, orders, units, or return rate to spot movers","Click any account name to drop straight into that sellerâs Overview","Switch scope from the header to jump to a single store or back to all accounts"],ask:"Give me the portfolio overview."},"/overview/:slug":{title:"Store Overview",purpose:"One storefrontâs at-a-glance health dashboard â roughly two dozen widgets covering sales, ads, returns, stock, and vital signs from a single view.",solves:"A storeâs health is spread across sales, ads, returns, stock, and fees â piecing it together by hand is slow and easy to get wrong.",helps:"Every vital sign sits on one screen, so you can read a storeâs state in seconds and spot whatâs off.",features:["Scan the full widget grid, starting with the sellerâs Vital Signs","Read Sponsored Ads spend, ROAS vs last period, and ads issues â then open Ads for the full tables","Download the whole overview as a PDF from the header","Watch live sync progress while the numbers refresh","Re-scope to another store or the all-accounts rollup from the header picker"],ask:"What stands out in this storeâs numbers this month?"},"/dashboards":{title:"Reports",purpose:"Your library of saved reports. Pin the ones you rely on and reopen them any time â the data refreshes on every open.",solves:"The reports you rely on get rebuilt from scratch every time, or live in scattered files that are always out of date.",helps:"Your go-to reports live in one place and refresh on open, so the version you reach for is always current.",features:["Search reports by title, description, or seller","Read a live headline number on each built-in report before you open it","Star the reports you rely on â including Gadjetâs built-ins â to keep them at the top","Build a new report from scratch with âNew reportâ"]},"/dashboards/:id":{title:"Report",purpose:"The live view of one saved report, rendered against current seller data.",solves:"A report is only useful if it reflects todayâs data and you can get it to whoever needs it.",helps:"Refresh it against live data and hand it over as a PDF in a couple of clicks â no rebuilding.",features:["Pick 7 / 30 / 90 days, this month, or last month without editing the report","Refresh to re-run the report against the latest data","Download the report as a PDF","Duplicate it to build a variant, or edit and delete your own reports","For built-in reports, choose which store to render against"]},"/dashboards/new":{title:"Build a Report",purpose:"A conversational builder â describe the report you want in plain language and the assistant generates and saves it for you.",solves:"Building a custom report normally means SQL, spreadsheets, or waiting on someone who can.",helps:"You describe what you want in plain language and it gets built â then you refine it by chatting, not configuring.",features:["Describe what to show (â30-day units sold by SKU, last monthâ) and watch it get built","Iterate by chatting changes â add a card, change the window, add a section","Start from an example prompt if youâre not sure how to phrase it","Your new report saves automatically and opens as soon as itâs ready"]},"/market-explorer":{title:"Market Explorer",purpose:"Buy-side research on Takealot â size categories and listings in Catalogue, find what shoppers search in Keywords, and stress-test a product idea in Validate before you commit stock.",solves:"Sellers pick products and ads on gut feel, blind to how big a category really is, who already owns the shelf, and which shopper phrases carry real demand.",helps:"You walk in with numbers: category size and crowding, rising phrases mapped to Takealot departments, and a validation pass before you source or advertise.",image:{src:"/help/market-explorer.png",alt:"The Market Explorer results table with the rollup summary above it",caption:"Catalogue rollups summarise a search â size, price spread, top brand, and estimated revenue. Keywords â Browse is the shopper-phrase counterpart."},features:["Shared workbench: query bar, saved rail, results canvas, and a Detail/Shortlist panel on Catalogue, Ke
788ywords, and Validate","Catalogue: pick a scope or lens, Build or Ask on the query bar, refine with chips, click a row for opportunity, wishlist (product-level demand on listings we sync), price history, and add listings to the account shortlist","Keywords: Browse/Search/Expand/Saved live on the query bar; rails sit in the left rail; tick phrases and bulk-add them to the same shortlist","Ranks drills from a department to a shelf and shows the daily pace and estimated revenue on the ranks that were actually measured. Opening a shelf uses one Est Sales lookup","Validate reads the shortlist (one existing playbook run per item) and shows the Launch Decision Brief beside an in-progress step â or start an ad-hoc idea with Validate something else","Folders still save queries; the shortlist saves items (PLIDs and keywords) so ideas travel between tabs without retyping"],ask:"What rising shopper phrases map to Beauty on Takealot?"},"/sops":{title:"SOPs",purpose:"A launcher for your standing operating procedures. Pick a seller, run a procedure, and get back either a downloadable deliverable or an interactive chat run.",solves:"Recurring account work lives in peopleâs heads and gets done inconsistently, or forgotten.",helps:"Every standing procedure is one click from a deliverable or a guided run, so the routine work gets done the same way each time.",features:["Pick a seller in the header, then launch any procedure from the card grid â badges flag the ones worth running now","Build new Takealot listings, resume drafts, and review submissions with a pass-rate health bar under Listings","Re-run or resume past procedure runs from the Runs history","Review and edit filed monthly stock-recon claims under Claims"]},"/ads":{title:"Ads",purpose:"Your Sponsored Ads workspace for one store â see whether ad spend is working, generate banners, and build PLID target lists for competitor PDPs.",solves:"Takealotâs Sponsored Ads reporting is thin: spend and blended ROAS without margin, buybox, stock, or search-query context, and no help choosing who to advertise next to.",helps:"You see spend, success, and waste in one place â including true break-even ROAS, bid health, and queries to harvest or negate â then generate banners and export a target list.",features:["Read headline spend, revenue, blended and direct (same-SKU) ROAS, with a prior-window comparison and 7/14/30/90 day range","See campaigns and advertised products with CTR, CPC, ROAS bands, keep/cap/pause actions, buybox, stock, and margin-adjusted break-even","Upload Keyword Performance and Search Query exports for per-keyword ROAS and harvest/negative lists; campaign-scoped files ask which campaign they belong to","Generate a Sponsored Display banner pack from a SKU, in three sizes and your brand colours","Pick a seed product, review scored competitor PDPs, and export Takealotâs sku_id.tsv targeting file"],ask:"How are this storeâs ads performing?"},"/content":{title:"Content",purpose:"The content-production pipeline. Move one âPillarâ idea through its lifecycle and atomise it into per-channel assets, from backlog to published.",solves:"Content work sprawls across docs, boards, and channels, so ideas stall and the pipeline runs dry without anyone noticing.",helps:"Every idea moves through one visible pipeline â from backlog to published, atomised per channel â so you always know whatâs shipping and whatâs next.",features:["Start on Today â this weekâs pillar, 7Ã7 publish lanes, and the Needs-you-today rail","Header: Monday digest, Review, Film queue, Promote idea â Academy is Film queue, not a tab","Promote from Backlog (light = 4 flagship assets, or a full 25-asset week)","Work the Board â drag pillars across the eight lifecycle stages (WIP 3 is a warning)","Calendar cadence is 1 YouTube / 2 Shorts / 1 blog / 1 email / 7 per social network","Performance is email + blog + Google Ads (GADJET-Search-*); social still Not connected"]},"/content/pillars/:id":{title:"Pillar",purpose:"The detail view for one content Pillar â its metadata, its live data hook, and all the per-channel derivative assets it spawns.",solves:"A single content idea spawns a dozen channel assets, and keeping them and their data straight is a mess of tabs.",helps:"One page holds the whole pillar â its metadata, its live data hook, and every derivative asset with its status and link.",features:["Edit the Pillarâs title, status, target week, and video/blog URLs","Resolve a Market Map hook (category size or crowding) or pin a stat manually","Add and manage derivative assets â
788channel, copy, date, tagged CTA, publish status","Generate / Refine copy, Studio for images (4 options, brand-lock, no Vary/Upscale)","Atomise a light pillar into the daily social week when youâre ready","Paste the live URL, then Mark published â pasting alone does not clear overdue"]},"/content/review":{title:"Review",purpose:"Sign-off on asset copy before it ships. Self-approve is allowed â a second reviewer is optional.",solves:"Copy lands on channel without anyone reading it, or a one-person team is blocked waiting for a reviewer who doesnât exist.",helps:"Comment on a span, request changes, or approve with open threads (youâll get a warning, not a lock).",features:["Queue of assets that have copy and are not yet approved","Inline comments on a selected span of copy","Approve even with open threads â warn, donât disable","Request changes to send the asset back to draft"]},"/content/repurpose":{title:"Repurpose",purpose:"Turn email and blog winners into drafts on a silent channel, and resurface evergreen posts still drawing clicks.",solves:"A post that already worked sits idle while the calendar has a gap on another channel.",helps:"Draft a recut into review in one click, using the owned-channel numbers we already have.",features:["Re-cut candidates from published email/blog with a missing social lane","Evergreen posts older than 90 days still drawing pageviews","Draft it creates a sibling asset on the target channel"]},"/content/film-queue":{title:"Film queue",purpose:"Seller-facing skills that still need an Academy video, with a generated script and shot list.",solves:"The Academy catalogue lags the skill list, so operators donât know what to film next.",helps:"Pick the next unfilmed skill, generate a 60â90s script, mark it filmed, or promote it to a pillar.",features:["Queue of unfilmed seller skills","Generate a talking-head script and shot list","Mark filmed or promote the skill to a content pillar"]},"/content/digest/:week":{title:"Monday digest",purpose:"A reading-width recap of the week: what shipped, reach on owned channels, and a short action list.",solves:"The weekâs content work lives across board, calendar, and email, so Monday starts without a picture.",helps:"Check off this weekâs actions and email the recap to the content team.",features:["Reach, trials, and runway for the selected week","What shipped, channel by channel","Do-this-week checkboxes that write back","Email to team via Loops (no-ops if the template isnât configured)"]},"/calendar":{title:"Calendar",purpose:"A month calendar for one seller that overlays promotions, shipments, payouts, tasks, and system events in one place, with an upcoming agenda alongside.",solves:"Promotions, shipments, payouts, and tasks each live in their own tool, so itâs hard to see whatâs actually happening for a seller this week.",helps:"Everything with a date lands on one calendar, so you can see collisions and whatâs coming, and jump straight to the detail.",features:["Pick a seller and move between months","Toggle event layers on and off by clicking the legend","Switch to weekdays-only view; the preference sticks","Click any day or agenda item for details, then deep-link out to Shipments, Tasks, or a pre-seeded chat"]},"/crm":{title:"CRM",purpose:"The sales pipeline â the master list of companies and leads with follow-up tracking, filtering, and bulk operations.",solves:"Leads and follow-ups scattered across inboxes and spreadsheets mean deals go cold because nobody remembered to chase them.",helps:"Every company, stage, and next action lives in one pipeline you can filter, save, and bulk-manage, so nothing slips.",features:["Add a company or bulk-import by pasting a table from Sheets/Excel","Filter by stage, source, owner, next-action state, revenue, region, and more â then save the filter as a shared view","Work follow-ups under Today, the pipeline under Pipeline (drag cards between stages), or the full list under All companies","Select companies and bulk-set next actions, move stages, assign an owner, or clear actions"]},"/crm/:id":{title:"Company",purpose:"One companyâs full picture â CRM pipeline data fused with live app signals so you can decide the next sales move on a single screen.",solves:"Deciding the next sales move means checking the CRM and the app separately, then guessing how the two connect.",helps:"CRM history and live app signals sit side by side, so you walk into every call knowing exactly where the account stands.",features:["Set the stage, owner, and next-action date; rename the company; refresh live app signals","Read the App Profile: plan, credits, subscription, AM, GMV and sales (30d), chats (7d), connected stores","Log an activity (call, email, WhatsApp, demo, note) with an outcome and follow-up date â then edit or delete it","Add, edit, and delete contacts with click-to-email / call / WhatsApp; inline-edit company details and notes"]},"/earn":{title:"Earn",purpose:"The referral and rewards program. Share your referral link, earn credits and cash for completing activities, and manage your affiliate wallet.",solves:"Sellers whoâd happily refer others or complete quick wins have no easy way to do it, or to see what theyâve earned.",helps:"You share one link, complete simple activities, and watch credits and cash build up â then sweep or withdraw them when youâre ready.",features:["Copy your referral link and track active, pending, and total referrals against the reward ladder","Submit proof for âWays to earnâ activities to unlock credits and Market Explorer searches","Sweep your affiliate balance to chat credit, or withdraw matured cash to your bank","Track submissions and withdrawals with live status pills"]},"/tasks":{title:"Tasks",purpose:"Your task inbox across the whole book â scan, triage, and bulk-manage every to-do, updated in real time.",solves:"Across a whole book, tasks pile up in different places and the important ones get buried under the routine.",helps:"One inbox shows everything due, filterable and bulk-editable, so you can triage the whole book in one sitting.",features:["Create a task, or click any row to edit it in the drawer","Filter by type, seller, or the Overdue toggle, and search by title or seller","Switch scope: Mine, All my book, Team workload, or Closed","Select multiple tasks to reassign, reschedule, set status, or cancel in bulk"]},"/cron-jobs":{title:"Scheduled Tasks",purpose:"The control room for cron-driven work â both AI skill jobs and system capture jobs. Edit schedules, pause or resume, and trigger off-schedule runs.",solves:"Automated jobs run in the background, and when one silently stops or starts failing, you find out too late.",helps:"Every scheduled jobâs schedule, last run, and status is visible in one place, so you can catch a stall and re-run it on the spot.",features:["Read every scheduled job: type, cron schedule (UTC), last run, and status","Filter by All / Active / Paused","Edit a jobâs schedule with a cron expression or a preset, with a live plain-English preview","Pause, resume, or âRun nowâ; expand a row to see its last 10 runs"]},"/sellers/:slug/tasks":{title:"Seller Tasks",purpose:"The task inbox for one seller â every to-do tied to this specific client in one place.",solves:"When you manage a client, their to-dos get mixed in with everyone elseâs and lose their thread.",helps:"This is just this sellerâs list, so you can see exactly whatâs open for them and whatâs been done.",features:["Toggle between Open and Closed tasks","Create a new task, pre-filled with this seller","Click any task to open and edit it","The list live-updates as tasks change"]},"/sellers/:slug/automations":{title:"Automations",purpose:"This sellerâs automation control centre â the Buybox Repricer (competes on price), Pricing Experiments (measured price-up tests on uncontested SKUs), and Agents (unattended Seller Portal procedures).",solves:"Competing on price by hand across a full c
788atalogue is impossible to keep up with â you lose the buybox while you sleep, and you never learn how much room you have to raise price on items you own outright.",helps:"Automations do the watching and adjusting for you, so listings stay competitive around the clock, uncontested SKUs can be tested without babysitting, and portal recipes run on a schedule you set.",features:["Health: how the repricer is performing right now, its capacity, and anything flagged","Activity: every price change the repricer has made, and why","SKUs: enrol listings, tune their floors and tiers, and turn on catalogue-wide Watch","Experiments: raise price on uncontested SKUs the repricer is not managing, then keep or revert","Agents: AM / super-admin only for now â inbound (replen, leadtime-to-draft, confirm, cancel stale drafts), promotions, removal orders, catalogue edits, and the monthly stock-loss claim pack"],ask:"How is my repricer doing this week?"},"/sellers/:slug/automations/repricer/health":{title:"Repricer · Health",purpose:"The at-a-glance state of the Buybox Repricer â how well itâs winning the buybox, how much capacity is left, and any listings that need your attention.",solves:"The repricer moves hundreds of prices on its own, and without one view you canât tell if itâs actually winning or quietly stuck at a floor.",helps:"One screen tells you whether the buybox is being won, where capacity is running out, and exactly which SKUs to fix â so you catch problems before they cost sales.",features:["Read the KPI tiles: enrolled SKUs, buybox win-rate, capacity used, and monthly top-up cost","Track the buybox win-rate trend, plus whatâs being watched or auto-promoted this week","See capacity per tier (Basic, Standard, Boosted, Super Boosted, Watch) and buy more slots","Work the Flagged issues â losing at floor, not buyable, tracking unnecessarily, contested with no slot â and review scheduled pauses"],ask:"How is my repricer doing this week?"},"/sellers/:slug/automations/repricer/activity":{title:"Repricer · Activity",purpose:"The audit trail of what the repricer has actually done â every automated price change over the last 7 days, with the reason behind each one.",solves:"Automated pricing feels like a black box â prices move on their own and youâre left guessing what changed and why.",helps:"You see every move the repricer made and the reason for it, so you can trust the automation and spot any rule thatâs misbehaving.",features:["Read the KPI tiles: number of changes (7d), average change size, and direction (up vs down)","Scan the recent price-changes list â old price to new price for each SKU","See the reason the repricer moved each price","Filter the list down to a single SKU"],ask:"What price changes has the repricer made this week?"},"/sellers/:slug/automations/repricer/skus":{title:"Repricer · SKUs",purpose:"The control table for every listing under the repricer â where you enrol SKUs, set the
788ir floors and tiers, and decide how aggressively each one competes.",solves:"Repricing every product the same way either leaves margin on the table or races your best sellers straight to the floor.",helps:"You tune each SKUâs floor, tier, and aggressiveness on its own â protecting margin on your heroes while competing hard where it counts.",features:["Search and filter the enrolled-SKU table by tier, mode, status, and competition; narrow to enabled-only or at-risk-only","Edit a SKUâs tier, floor, and preferred price, with a built-in profit calculator per row","Select multiple SKUs to bulk-edit, or bulk-enrol from a spreadsheet","Turn on Watch to monitor the whole catalogue and auto-enable repricing when a competitor appears"],ask:"Which of my SKUs are losing the buybox?"},"/sellers/:slug/automations/experiments/run":{title:"Experiments · Run",purpose:"Set up a measured price test on uncontested Takealot listings the repricer is not managing.",solves:"You own the buybox on some SKUs but have no clean way to learn whether the price can go up (or how deep a discount can go) without losing profit.",helps:"Start from this weekâs 5, confirm theyâre uncontested, accept a reasoned test price, then launch. Dispatch moves the live price; you keep or revert with evidence.",features:["Portfolio headroom and a Monday shortlist of the best test candidates","Live PDP check (uncontested, in stock, not on the repricer, not on a live promo). Missing catalogue rows are scanned on demand â the repricer does not have to have seen the SKU first.","Review shows the live PDP price vs the catalogue price, sibling-SKU warnings, and upcoming In Review promotions","Save a draft without changing Takealot prices; managed accounts send the batch to the seller for sign-off","Click a SKU for a 12-week units chart with weekday / week-of-month expected overlay","Reasoning card: contest ceiling, market cluster, implied margin, power preview","Step-and-hold, switchback, or staircase â conservative or aggressive","Price-up or discount-depth. Nothing stays changed unless you say so."],ask:"Which of my SKUs could take a price increase?"},"/sellers/:slug/automations/experiments/live":{title:"Experiments · Live",purpose:"Watch in-flight price tests and abort one if the listing gets contested or volume falls off.",solves:"Once a test price is live you need a heartbeat: buybox held, units vs expected, and a way to stop without waiting for the window.",helps:"Scheduled tests start on the next hourly tick. Running tests show day N/M, current price, buybox-held %, units vs weekday-expected, and an early read.",features:["Buybox-held % and units-so-far vs weekday / week-of-month expected (not a flat average)","Open a row for the expected caption, last PDP check, 12-week history, and Abort & revert","Abort a test from the right-hand drawer to restore the live price immediately"],ask:"Which pricing experiments are running right now?"},"/sellers/:slug/automations/experiments/results":{title:"Experiments · Results",purpose:"Read the verdict on finished price tests and decide whether to keep the new price or revert.",solves:"A test that moved price is useless if you canât see whether volume held, what market drift we subtracted, and then choose keep or revert.",helps:"Each completed experiment shows units, revenue, and gross profit with a confidence interval. Inconclusive tests can be extended or retried; winners can sit on Watch.",features:["Keep-or-revert recommendation with drift explained in English","Click a SKU for 12 weeks of daily units vs weekday / week-of-month expected","Extend an inconclusive window or retry a smaller/bigger step","Park a winner on Watch so a new rival gets an alert"],ask:"Did last weekâs price experiment actually work?"},"/sellers/:slug/automations/agents":{title:"Agents",purpose:"The Seller Portal procedures Gadjet can run as this storeâs agent â inbound shipments, promotions, removal orders, catalogue work, and the monthly stock-loss claim â and when each one should run. Each recipe lists the logins and paths it needs; missing or known-failed dependencies stay flagged until they are fixed. AM and super-admin only until this is proven; sellers cannot see it.",solves:"These jobs used to mean logging into Seller Portal and clicking through them by hand, or waiting for someone to remember.",helps:"You pick which recipes are on and set a schedule, so Gadjet runs them unattended as this storeâs agent.",features:["See every portal procedure available for this store","Turn a recipe on or pause it â only when its dependencies are ready","Flag missing or failed prerequisites (Gadjet agent login, recipe paths that are not yet recorded)","Edit when it runs (daily or weekly cron, UTC)","Visible only to AMs and super-admins while we test"],ask:"When does my bulk replenishment agent run?"},"/sellers/:slug/inventory":{title:"Inventory",purpose:"This sellerâs product catalogue and stock-health hub â physical warehouse items and marketplace listings, with the signals that flag what needs attention.",solves:"Stock problems â running out, dead stock, thin listings, lost buybox â hide across different reports until theyâve already cost you sales.",helps:"Every product and its health signals sit in one filterable view, so you can spot and fix whatâs at risk before it bites.",features:["Search by SKU, title, or barcode; filter by status; export the data","Use quick-filter chips: DC out of stock, warehouse empty, low cover, dead stock, poor conversion, wanted-not-selling (high wishlist, no sales), low quality, losing buybox","Switch views: Statistics, Master Catalogue (physical stock), this storeâs listings (Takealot or Amazon, matching the seller in the nav), or Search visibility (Takealot organic and sponsored ranking vs the previous period)","Click a row to edit price or stock and push the change to that marketplace"],ask:"Which of my SKUs are at risk of stocking out?"},"/sellers/:slug/inventory/scan":{title:"Receive Stock",purpose:"A barcode-scanning receiving station for booking inbound stock into the warehouse.",solves:"Booking inbound stock by typing SKUs into a spreadsheet is slow and error-prone.",helps:"You scan a barcode and the unit is counted in â fast, accurate, and with an undo if you slip.",features:["Scan with your phone camera, a Bluetooth/USB scanner, or by typing the barcode","Each matched scan adds one unit and shows the new on-hand quantity","Resolve an unknown barcode â add it as a new product or attach it to an existing item","Watch the live session log and undo any scan"]},"/sellers/:slug/shipments":{title:"Shipments",purpose:"Tracks this sellerâs inbou
788nd shipments to Takealot DCs and how completely each one was received.",solves:"Takealot doesnât always receive what you sent, and shortfalls go unnoticed unless you reconcile every shipment by hand.",helps:"You see each shipmentâs receive rate, damage, and shortfall at a glance, so you can chase whatâs missing while the claim window is open.",features:["Filter by date range and DC; search by reference or PO number","Quick-filter for shortfalls, in-transit, or damaged units","Read the KPIs: units sent, receive rate, damage rate, shipments with a shortfall","Click a shipment for its detail, including courier status and unloaded date"],ask:"Did all my recent shipments get received in full?"},"/sellers/:slug/sales":{title:"Sales",purpose:"This sellerâs order-level sales ledger, with GMV, margin, and regional insight.",solves:"Raw order data doesnât tell you whatâs really making money or where margin is leaking.",helps:"Orders roll up into GMV, margin, and a regional split, so you can see whatâs selling and whatâs quietly unprofitable.",features:["Filter by date range and region; search by SKU or order number","Quick-filter for multi-unit or high-value orders","Read the KPIs: orders, units, GMV, average order, gross margin, cancelled â plus a regional split","Sort the order table, open any order for detail, and export the filtered view"],ask:"Whatâs selling and whatâs slowing down?"},"/sellers/:slug/transactions":{title:"Transactions",purpose:"What this seller made, what reached the bank, and which products did it â with the Takealot ledger underneath.",solves:"A payout, a sales total, and a fee line are three different numbers, and they get mixed together.",helps:"Earnings shows what the period added to the Takealot balance, then Gadjet and any costs you add. Cash shows the Thursday deposit. Products shows which SKUs contributed.",features:["Earnings bridge from gross sales to Takealot net, then your own costs","Cash: available, held back, and what made up the last payout","Products ranked by contribution after success fee and fulfilment","Add a cost (packaging, freight, ads) without changing the Takealot ledger","The Transactions tab is the line-by-line ledger, with export"],ask:"Explain my most recent payout."},"/sellers/:slug/returns":{title:"Returns",purpose:"Tracks this sellerâs product returns and helps diagnose why customers are sending items back.",solves:"Returns eat into profit, but the reasons hide in individual records so the real pattern never surfaces.",helps:"Returns roll up by reason, SKU, and region with a likely-cause hint, so you can see whatâs driving them and act on the worst offenders.",features:["Filter by date range, reason, and region; search by SKU or order","Quick-filter for open returns or SKUs with a high return rate","Read the KPIs and the top-reasons breakdown â click a reason bar to filter by it","Open any return for detail, including a likely-cause hint, and export","Pickup ready tab â book a courier from the Takealot DC back to the warehouse","Fetch the waybill PDF and live tracking after you book"],ask:"Whatâs driving my returns, and which SKUs are worst?"},"/sellers/:slug/chats":{title:"Seller Chat",purpose:"The AI assistant focused on this one seller â every question and skill defaults to this account.",solves:"Getting an answer about one seller usually means knowing which report to open and how to read it.",helps:"You just ask, and the assistant answers from this sellerâs live data and runs the right skill for you.",features:["Ask anything about this seller; the assistant scopes all its data reads and actions here","Start a new chat, or land back in your most recent one","Use the suggested prompts to get going","Conversations save automatically"],ask:"Give me this weekâs action list for this seller."},"/sellers/:slug/reports":{title:"Documents",purpose:"The reader for a generated report or document â monthly and quarterly rollups, returns deep-dives, sales velocity, payouts, and more.",solves:"The deep-dive reviews a seller needs are time-consuming to produce and easy to let slide.",helps:"Generated reports â monthly, quarterly, returns, payouts â are ready to read and hand over as a PDF whenever you need them.",features:["Read the rendered report, with its type, name, and last-updated date","Download it as a PDF","New reports appear here as the report skills produce them"]},"/settings/profile":{title:"Profile",purpose:"Your personal Gadjet login â your name, avatar, password, and current session. This is about you, not the workspace.",solves:"Personal account details get lost when theyâre mixed in with workspace and billing settings.",helps:"Everything about your own login lives here, separate from the workspace, so itâs quick to find and change.",features:["Upload or remove your profile picture","Edit your name (your email is fixed)","Set how Gadjet talks to you in chat â default, minimal, or detailed â and optional custom instructions","Send yourself a password-reset email","Sign out of this device"]},"/settings/notifications":{title:"Notifications",purpose:"Controls which non-essential emails Gadjet sends you. Billing and security emails always send regardless.",solves:"Useful product email and noise arrive in the same firehose unless you can control what lands.",helps:"One switch decides whether you get non-essential email; the account and security messages you actually need always come through.",features:["Toggle product & account email â tips, summaries, and other non-essential updates"]},"/settings/workspace":{title:"Workspace",purpose:"Your workspaceâs identity, branding, and region, plus a plan-at-a-glance. Owner-editable.",solves:"Branding, region, and plan settings drift out of sync when thereâs no single place that owns them.",helps:"The workspaceâs identity, brand kit, and region live in one place, and they feed the studios and reports automatically.",features:["Upload the workspace logo and rename the workspace","Edit the Brand kit â palette, theme, and fonts that feed the Ads and Image studios","Set the Listing image preset â the shots and prompts used when generating listing images","Set your region (timezone and currency) and see plan, stores used, and members"]},"/settings/workspace/members":{title:"Members",purpose:"Invite teammates and control exactly what each one can see â their role, which stores theyâre scoped to, and which surfaces are visible.",solves:"Giving a teammate access is usually all-or-nothing â you canât easily limit them to the right stores and surfaces.",helps:"You invite by role and control exactly which stores and surfaces each person sees, down to the individual.",features:["Invite a teammate by email as Admin, Member, or Viewer","Change a memberâs role or remove them","Set default surface access per role, hiding whole surfaces from Members or Viewers","Scope a member to specific stores, or override surface access person-by-person"]},"/settings/workspace/billing":{title:"Billing",purpose:"Where you track credit usage, manage your subscription and plan, buy top-ups, and download invoices.",solves:"Credit usage and subscription costs stay opaque until the bill or the empty balance surprises you.",helps:"You can see where credits go, how the plan is pacing, and manage the subscription and top-ups before anything runs out.",features:["Read the monthly-credits meter â remaining, renewal countdown, and pacing","Manage your subscription via the Paystack portal, or change plan","See where this monthâs credits went â by type, skill, and chat","Buy top-up credit packs and download tax-invoice PDFs"]},"/settings/workspace/payouts":{title:"Payouts",purpose:"Stores the bank account Gadjet pays your affiliate cash withdrawals into. Only the last four digits and a secure token are kept â never the full number.",solves:"Affiliate cash canât reach you until thereâs a verified account to pay it into, and bank details shouldnât be scattered around.",helps:"You store one bank account securely here, so withdrawals have somewhere safe to land.",features:["Enter your bank details â account holder, bank, and account number","See the saved account and whether itâs ready for payouts","Replace the bank account when it changes","Jump to Earn to manage your balance and request a withdrawal"]},"/settings/admin":{title:"Admin",purpose:"The super-admin console â cross-tenant operational tools grouped under one roof.",solves:"Cross-tenant operations are spread across separate tools that only some people should ever touch.",helps:"The super-admin controls â users, spend, access, cron, and skills â sit behind one gated console.",features:["Dashboard: the cross-tenant admin overview","Surfaces: live versions and door-only open w
788ork for web, extension, and mobile","Users, AI Spend, and Lockout: manage accounts, watch model spend, and control access","Navigation: set which surfaces each role and account can see","Scheduled tasks and Skills: manage cron jobs and edit the AI skill catalogue"]},"/settings/admin/surfaces":{title:"Surfaces",purpose:"One board for the three client doors â web, Chrome extension, iOS, Android â so versions and door-only work stay visible.",solves:"Web ships on every merge, the extension and store apps ship on a store clock, and open work gets lost in the dump.",helps:"You see what is live on each door, what can only ship through that door, and the next one thing â without copying the whole backlog.",features:["Live versions: web SHA, extension semver, iOS binary, Android (none yet)","Decision row: ships how, only-this-door work, next one thing, blocked on","Ops strip: lag, health, compat floor, last store action, WAU / primary","Shared API / auth row so a breaking /api/extension or /api/pair change is visible before merge"]},"/settings/stores/:slug":{title:"Store",purpose:"One storeâs core configuration and lifecycle status.",solves:"A storeâs core details and on/off state are easy to lose among account-wide settings.",helps:"This storeâs name, identity, and pause/resume live on one page, scoped to just this store.",features:["Edit the storeâs display name","See its legal name, slug, customer owner, account manager, and onboarded date","Pause an active store, or resume a paused one"]},"/settings/stores/:slug/managed":{title:"Managed Account",purpose:"The account-manager cockpit for one managed seller â account facts, the standard-task schedule, team notes, and the portal-credential vault, all in one place.",solves:"Everything an account manager needs about a seller â facts, schedule, notes, logins â usually lives in a dozen different places.",helps:"The whole cockpit for a managed seller is on one screen, so an AM can pick up the account and its context instantly.",features:["See account facts and set the Start of Management date; super-admins reassign the AM from Account manager (that is what the sidebar groups by). Owner is the customer, never a Gadjet AM","Set the standard-tasks grid to auto-create recurring weekly and monthly tasks","Add team notes â seller memories that feed the AI when an AM chats about this seller","Manage the credentials vault â built-in Takealot / Gadjet agent / Amazon / 2 Ship slots wait to be filled; Seller Portal is the human login and Gadjet agent is Portal Actions; reveal is audit-logged and auto-hides after 60 seconds"]},"/settings/stores/:slug/integrations":{title:"Integrations",purpose:"Manage this storeâs connected marketplaces and the API/session keys that keep data flowing.",solves:"When a marketplace key expires or a session goes stale, data quietly stops flowing and you notice only when the numbers look wrong.",helps:"You can see each connectionâs health and rotate or reconnect keys here, keeping the data pipeline alive.",features:["See the Takealot connection and rotate the Marketplace API key","Connect Amazon via SP-API, or check its marketplace and last-sync status","Check the portal session-token health card â captured, expiry, and last error"]},"/settings/stores/:slug/danger":{title:"Danger Zone",purpose:"The sensitive lifecycle actions for a store â converting off a managed retainer, pausing, and offboarding. Super-admin only.",solves:"Sensitive lifecycle actions are risky when theyâre mixed in with everyday settings.",helps:"Pausing, offboarding, and tier changes are gathered in one clearly-marked, gated place, so theyâre deliberate rather than accidental.",features:["Pause syncs (reversible)","Offboard the seller â archive the account and revoke its API key","Convert a managed retainer to a self-serve plan (super-admin)"]}};Cp["/dashboards/:id/edit"]=Cp["/dashboards/new"];const Tge=[[{label:"Health",key:"/sellers/:slug/automations/repricer/health"},{label:"Activity",key:"/sellers/:slug/automations/repricer/activity"},{label:"SKUs",key:"/sellers/:slug/automations/repricer/skus"}],[{label:"Run",key:"/sellers/:slug/automations/experiments/run"},{label:"Live",key:"/sellers/:slug/automations/experiments/live"},{label:"Results",key:"/sellers/:slug/automations/experiments/results"}]];function Oge(e){return Tge.find(t=>t.some(n=>n.key===e))??null}
788function Ige(e){const t=e.replace(/\/+$/,"").split("/").filter(Boolean);let n=null,r=-1;for(const a of Object.keys(Cp)){const i=a.split("/").filter(Boolean);if(i.length>t.length)continue;let o=0,l=!0;for(let c=0;c<i.length;c++)if(i[c].startsWith(":"))o+=1;else if(i[c]===t[c])o+=2;else{l=!1;break}l&&o>r&&(n=a,r=o)}return n?{key:n,help:Cp[n]}:null}function Pge(e,t){const n=e.split("/").filter(Boolean);if(n.length>t.length)return null;let r=0;for(let a=0;a<n.length;a++)if(n[a].startsWith(":"))r+=1;else if(n[a]===t[a])r+=2;else return null;return r}function Rge(e,t){var a;const n=t.replace(/\/+$/,"").split("/").filter(Boolean),r=[];for(const i of e){const o=(a=i.page_help_keys)!=null&&a.length?i.page_help_keys:i.page_help_key?[i.page_help_key]:[];let l=null;for(const c of o){const u=Pge(c,n);u!==null&&(l===null||u>l)&&(l=u)}l!==null&&r.push({v:i,score:l})}return r.sort((i,o)=>o.score-i.score||i.v.sort_order-o.v.sort_order||i.v.title.localeCompare(o.v.title)),r.map(i=>i.v)}function Dge(e){const t=e.match(/^\/(?:sellers|overview|settings\/stores)\/([^/]+)/);return t?t[1]:null}const Qd="text-xs font-semibold uppercase tracking-wider text-text-tertiary";function Mge({image:e}){const[t,n]=p.useState(!1);return t?null:s.jsxs("figure",{className:"mb-6 overflow-hidden rounded-xl border border-outline-subtle bg-surface-subtle",children:[s.jsx("img",{src:e.src,alt:e.alt,loading:"lazy",onError:()=>n(!0),className:"block h-auto w-full"}),e.caption&&s.jsx("figcaption",{className:"border-t border-outline-subtle bg-surface px-3.5 py-2.5 text-xs leading-snug text-text-secondary",children:e.caption})]})}function $ge({video:e}){return s.jsxs("figure",{className:"mb-6 overflow-hidden rounded-xl border border-outline-subtle bg-black",children:[s.jsx("video",{src:e.video_url,poster:e.poster_url??void 0,controls:!0,preload:"none",className:"block aspect-video w-full"}),s.jsxs("figcaption",{className:"flex items-center justify-between gap-2 border-t border-outline-subtle bg-surface px-3.5 py-2.5 text-xs text-text-secondary",children:[s.jsx("span",{className:"min-w-0 truncate font-medium text-text-primary",children:e.title}),s.jsx(st,{to:"/academy",className:"shrink-0 font-medium text-text-brand hover:underline",children:"More in Academy â"})]})]})}function Lge(){const{pathname:e}=Ba(),[t,n]=p.useState(!1),[r,a]=p.useState([]),i=Ige(e),o=(i==null?void 0:i.key)??null,[l,c]=p.useState(o);if(p.useEffect(()=>c(o),[o]),p.useEffect(()=>{if(!t)return;let m=!0;return wp.listCached().then(x=>{m&&a(Rge(x,e))}).catch(()=>m&&a([])),()=>{m=!1}},[t,e]),!i||!o)return null;const u=Oge(o),d=l&&Cp[l]||i.help,h=Dge(e),f=d.ask?`${Zl()}?${new URLSearchParams(h?{prompt:d.ask,seller:h}:{prompt:d.ask}).toString()}`:null;return s.jsxs(Cr,{open:t,onOpenChange:m=>{n(m),m&&c(o)},children:[s.jsx("button",{type:"button",onClick:()=>n(!0),"aria-label":`How this page works: ${d.title}`,title:"How this page works",className:"p-2.5 md:p-1.5 rounded-md text-text-tertiary hover:text-text-body hover:bg-surface-sunken",children:s.jsx(Hte,{className:"w-4 h-4"})}),s.jsxs(mr,{side:"right",size:"lg","aria-describedby":void 0,className:"max-w-[92vw]",children:[s.jsxs(Er,{className:"px-6 pt-5 pb-4",children:[s.jsx("p",{className:Qd,children:"How this page works"}),s.jsx(xr,{className:"mt-1.5 pr-8 text-lg font-bold tracking-tight",children:d.title}),u&&l&&s.jsx(Pa,{value:l,onValueChange:c,variant:"brand",size:"sm","aria-label":"Read help for another tab",className:"mt-3 flex",children:u.map(m=>s.jsx(Ln,{value:m.key,className:"flex-1",children:m.label},m.key))})]}),s.jsxs(pr,{className:"px-6 py-5",children:[s.jsx("p",{className:`${Qd} mb-2`,children:"What this space is for"}),s.jsx("p",{className:"mb-6 text-base leading-relaxed text-text-primary",children:d.purpose}),(d.solves||d.helps)&&s.jsxs("div",{className:"mb-6 grid gap-4",children:[d.solves&&s.jsxs("div",{className:"grid grid-cols-[36px_1fr] items-start gap-3",children:[s.jsx("div",{className:"grid h-9 w-9 place-items-center rounded-lg bg-surface-warningSubtle text-intent-warning",children:s.jsx(yt,{className:"h-4 w-4"})}),s.jsxs("div",{children:[s.jsx("p",{className:`${Qd} mb-1`,children:"The problem it solves"}),s.jsx("p",{className:"text-sm leading-relaxed text-text-secondary",children:d.solves})]})]}),d.helps&&s.jsxs("div",{className:"grid grid-cols-[36px_1fr] items-start gap-3",children:[s.jsx("div",{className:"grid h-9 w-9 place-items-center rounded-lg bg-surface-brandSubtle text-text-brand",children:s.jsx(Ht,{className:"h-4 w-4"})}),s.jsxs("div",{children:[s.jsx("p",{className:`${Qd} mb-1`,children:"How it helps you"}),s.jsx("p",{className:"text-sm leading-relaxed text-text-secondary",children:d.helps})]})]})]}),r.length>1&&s.jsx("p",{className:`${Qd} mb-2`,children:"Videos for this page"}),r.map(m=>s.jsx($ge,{video:m},m.id)),d.image&&s.jsx(Mge,{image:d.image},d.image.src),s.jsx("p",{className:`${Qd} mb-3`,children:"What you can do"}),s.jsx("ul",{className:"grid gap-3",children:d.features.map((m,x)=>s.jsxs("li",{className:"grid grid-cols-[20px_1fr] gap-2.5 text-sm leading-relaxed text-text-secondary",children:[s.jsx("span",{className:"mt-0.5 grid h-[18px] w-[18px] place-items-center rounded-md bg-surface-brandSubtle text-text-brand",children:s.jsx(fn,{className:"h-3 w-3"})}),s.jsx("span",{children:m})]},x))})]}),f&&s.jsx(ml,{className:"justify-stretch",children:s.jsxs(st,{to:f,onClick:()=>n(!1),className:"flex w-full items-center gap-3 rounded-lg border border-outline bg-surface px-3 py-2.5 hover:border-outline-brand",children:[s.jsx("span",{className:"grid h-6 w-6 shrink-0 place-items-center rounded-md bg-intent-brand text-text-inverse",children:s.jsx(Ht,{className:"h-3.5 w-3.5"})}),s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block text-xs font-semibold uppercase tracking-wide text-text-tertiary",children:"Ask in chat"}),s.jsxs("span",{className:"block truncate text-sm font-medium text-text-primary",children:["â",d.ask,"â"]}
788)]}),s.jsx(os,{className:"ml-auto h-4 w-4 shrink-0 text-text-brand"})]})})]})]})}function Fge({items:e,separator:t="âº",className:n}){return s.jsx("nav",{"aria-label":"Breadcrumb",className:B("flex items-center gap-1.5 min-w-0 text-body-sm",n),children:e.map((r,a)=>{const i=typeof r=="string"?r:r.label,o=typeof r=="string"?void 0:r.to,l=a===e.length-1;return s.jsxs(p.Fragment,{children:[a>0&&s.jsx("span",{"aria-hidden":"true",className:"text-outline-subtle shrink-0",children:t}),l||!o?s.jsx("span",{"aria-current":l?"page":void 0,className:B("truncate",l?"text-text-primary font-semibold":"text-text-secondary"),children:i}):s.jsx(st,{to:o,className:"text-text-secondary hover:text-text-primary truncate",children:i})]},a)})})}const LC=p.createContext({host:null,setHost:()=>{}});function Bge({children:e}){const[t,n]=p.useState(null);return s.jsx(LC.Provider,{value:{host:t,setHost:n},children:e})}function Uge({left:e}){const{setHost:t}=p.useContext(LC);return s.jsxs("div",{className:"border-b border-outline-subtle px-4 md:px-6 h-14 flex items-center bg-surface shrink-0 gap-3",children:[e,s.jsx("div",{ref:t,className:"flex-1 min-w-0 flex items-center"})]})}function Pt({crumbs:e,actions:t}){const{host:n}=p.useContext(LC),r=xB(),a=_7(),i=r.newReadyCount>9?"9+":r.newReadyCount>0?String(r.newReadyCount):null,o=a.unreadCount>9?"9+":a.unreadCount>0?String(a.unreadCount):null;if(!n)return null;const l=a.unreadCount===1?"1 unread":`${a.unreadCount} unread`;return Kv.createPortal(s.jsxs(s.Fragment,{children:[s.jsx(Fge,{className:"flex-1",items:e.map(c=>({label:c.label,to:c.to}))}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t,s.jsx(Lge,{}),s.jsxs("button",{type:"button",onClick:a.toggle,"aria-label":o?`Notifications (${l})`:"Notifications",title:"Notifications",className:"relative inline-flex h-11 w-11 md:h-auto md:w-auto items-center justify-center p-2.5 md:p-1.5 rounded-md text-text-tertiary hover:text-text-body hover:bg-surface-sunken",children:[s.jsx(Z6,{className:"w-4 h-4"}),o&&s.jsx("span",{className:"absolute top-1.5 right-1.5 md:-top-0.5 md:-right-0.5 inline-flex items-center justify-center min-w-[16px] h-[16px] px-1 rounded-full bg-intent-info text-text-inverse text-body-xs font-semibold leading-none",children:o})]}),s.jsxs("button",{type:"button",onClick:r.toggle,"aria-label":i?`Open exports (${r.newReadyCount} new)`:"Open exports",title:"Exports",className:"relative inline-flex h-11 w-11 md:h-auto md:w-auto items-center justify-center p-2.5 md:p-1.5 rounded-md text-text-tertiary hover:text-text-body hover:bg-surface-sunken",children:[s.jsx(tF,{className:"w-4 h-4"}),i&&s.jsx("span",{className:"absolute top-1.5 right-1.5 md:-top-0.5 md:-right-0.5 inline-flex items-center justify-center min-w-[16px] h-[16px] px-1 rounded-full bg-intent-info text-text-inverse text-body-xs font-semibold leading-none",children:i})]})]})]}),n)}var zge=Object.defineProperty,yu=(e,t)=>zge(e,"name",{value:t,configurable:!0}),FC="Popover",[V7,xrt]=du(FC,[c6]),BC=c6(),[Wge,Af]=V7(FC),Kge=yu(e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:o=!1}=e,l=BC(t),c=p.useRef(null),[u,d]=p.useState(!1),[h,f]=Jp({prop:r,defaultProp:a??!1,onChange:i,caller:FC});return s.jsx(KY,{...l,children:s.jsx(Wge,{scope:t,contentId:l6(),triggerRef:c,open:h,onOpenChange:f,onOpenToggle:p.useCallback(()=>f(m=>!m),[f]),hasCustomAnchor:u,onCustomAnchorAdd:p.useCallback(()=>d(!0),[]),onCustomAnchorRemove:p.useCallback(()=>d(!1),[]),modal:o,children:n})})},"Popover"),Hge="PopoverTrigger",Vge=p.forwardRef(yu(function(t,n){const{__scopePopover:r,...a}=t,i=Af(Hge,r),o=BC(r),l=oa(n,i.triggerRef),c=s.jsx(ji.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":UC(i.open),...a,ref:l,onClick:cs(t.onClick,i.onOpenToggle)});return i.hasCustomAnchor?c:s.jsx(HY,{asChild:!0,...o,children:c})},"PopoverTrigger")),q7="PopoverPortal",[qge,Gge]=V7(q7,{forceMount:void 0}),Yge=yu(e=>{const{__scopePopover:t,forceMount:n,children:r,container:a}=e,i=Af(q7,t);return s.jsx(qge,{scope:t,forceMount:n,children:s.jsx(Wv,{present:n||i.open,children:s.jsx($Y,{asChild:!0,container:a,children:r})})})},"PopoverPortal"),Ep="PopoverContent",Zge=p.forwardRef(yu(function(t,n){const r=Gge(Ep,t.__scopePopover),{forceMount:a=r.forceMount,...i}=t,o=Af(Ep,t.__scopePopover);return s.jsx(Wv,{present:a||o.open,children:o.modal?s.jsx(Jge,{...i,ref:n}):s.jsx(Qge,{...i,ref:n})})},"PopoverContent")),Xge=op("PopoverContent.RemoveScroll"),Jge=p.forwardRef(yu(function(t,n){const r=Af(Ep,t.__scopePopover),a=p.useRef(null),i=oa(n,a),o=p.useRef(!1);return p.useEffect(()=>{const l=a.current;if(l)return LY(l)},[]),s.jsx(FY,{as:Xge,allowPinchZoom:!0,children:s.jsx(G7,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:cs(t.onCloseAutoFocus,l=>{var c;l.preventDefault(),o.current||(c=r.triggerRef.current)==null||c.focus()}),onPointerDownOutside:cs(t.onPointerDownOutside,l=>{const c=l.detail.originalEvent,u=c.button===0&&c.ctrlKey===!0,d=c.button===2||u;o.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:cs(t.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})},"PopoverContentModal")),Qge=p.forwardRef(yu(function(t,n){const r=Af(Ep,t.__scopePopover),a=p.useRef(!1),i=p.useRef(!1);return s.jsx(G7,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:o=>{var l,c;(l=t.onCloseAutoFocus)==null||l.call(t,o),o.defaultPrevented||(a.current||(c=r.triggerRef.current)==null||c.focus(),o.preventDefault()),a.current=!1,i.current=!1},onInteractOutside:o=>{var u,d;(u=t.onInteractOutside)==null||u.call(t,o),o.defaultPrevented||(a.current=!0,o.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const l=o.target;((d=r.triggerRef.current)==null?void 0:d.contains(l))&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&i.current&&o.preventDefault()}})},"PopoverContentNonModal")),G7=p.forwardRef(yu(function(t,n){const{__scopePopover:r,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:o,disableOutsidePointerEvents:l,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:h,...f}=t,m=Af(Ep,r),x=BC(r);return BY(),s.jsx(UY,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:i,onUnmountAutoFocus:o,children:s.jsx(zY,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:h,onEscapeKeyDown:c,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>m.onOpenChange(!1),deferPointerDownOutside:!0,children:s.jsx(WY,{"data-state":UC(m.open),role:"dialog",id:m.contentId,...x,...f,ref:n,style:{...f.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})},"PopoverContentImpl"));function UC(e){return e?"open":"closed"}yu(UC,"getState");var eye=Kge,tye=Vge,nye=Yge,rye=Zge;const zC=eye,WC=tye,b0=p.forwardRef(({className:e,sideOffset:t=4,align:n="center",...r},a)=>s.jsx(nye,{children:s.jsx(rye,{ref:a,sideOffset:t,align:n,className:B("z-tooltip rounded-md border border-outline-subtle bg-surface shadow-lg p-1 outline-none","data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95","data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95","data-[side=bottom]:slide-in-from-top-1 data-[side=top]:slide-in-from-bottom-1","data-[side=left]:slide-in-from-right-1 data-[side=right]:sli
788de-in-from-left-1",e),...r})}));b0.displayName="PopoverContent";const Tf=zC,Of=WC,$d=p.forwardRef(({className:e,...t},n)=>s.jsx(b0,{ref:n,role:"menu",className:B("min-w-[12rem] p-1",e),...t}));$d.displayName="MenuContent";const Gh=p.forwardRef(({className:e,destructive:t,...n},r)=>s.jsx("button",{ref:r,type:"button",role:"menuitem",className:B("flex min-h-11 w-full items-center gap-2 rounded-sm px-3 py-2.5 text-left text-body-lg text-text-primary transition md:min-h-0 md:px-2.5 md:py-1.5 md:text-body-sm","hover:bg-surface-subtle focus:bg-surface-subtle focus:outline-none","disabled:cursor-not-allowed disabled:opacity-50",t&&"text-text-error hover:bg-surface-errorSubtle focus:bg-surface-errorSubtle",e),...n}));Gh.displayName="MenuItem";const sye=p.forwardRef(({className:e,checked:t,onCheckedChange:n,children:r,onClick:a,...i},o)=>s.jsxs("button",{ref:o,type:"button",role:"menuitemcheckbox","aria-checked":!!t,onClick:l=>{n==null||n(!t),a==null||a(l)},className:B("flex min-h-11 w-full items-center gap-2 rounded-sm px-3 py-2.5 text-left text-body-lg text-text-primary transition md:min-h-0 md:px-2.5 md:py-1.5 md:text-body-sm","hover:bg-surface-subtle focus:bg-surface-subtle focus:outline-none","disabled:cursor-not-allowed disabled:opacity-50",e),...i,children:[s.jsx("span",{className:B("flex h-4 w-4 shrink-0 items-center justify-center rounded border",t?"border-intent-brand bg-intent-brand text-text-inverse":"border-outline bg-surface"),"aria-hidden":!0,children:t?s.jsx(fn,{className:"h-3 w-3",strokeWidth:3}):null}),s.jsx("span",{className:"min-w-0 flex-1",children:r})]}));sye.displayName="MenuCheckboxItem";function aye({className:e}){return s.jsx("div",{role:"separator",className:B("my-1 h-px bg-outline-faint",e)})}function iye({className:e,...t}){return s.jsx("div",{className:B("px-2.5 py-3 text-center text-body-xs text-text-secondary",e),...t})}function oye({sellers:e,value:t,onChange:n,leadingOptions:r=[],placeholder:a="Select sellerâ¦",disabled:i,className:o}){const[l,c]=p.useState(!1),[u,d]=p.useState(""),h=p.useRef(null),f=p.useMemo(()=>[...r,...e.map(b=>({value:b.slug,label:b.display_name??b.slug}))],[r,e]),m=f.find(b=>b.value===t),x=(m==null?void 0:m.label)??"",g=p.useMemo(()=>{const b=u.trim().toLowerCase();return b?f.filter(v=>v.label.toLowerCase().includes(b)||v.value.toLowerCase().includes(b)):f},[f,u]);function y(b){n(b),c(!1),d("")}return s.jsxs(Tf,{open:l,onOpenChange:b=>{c(b),b||d("")},children:[s.jsx(Of,{asChild:!0,children:s.jsxs("button",{type:"button",disabled:i||f.length===0,className:B("flex min-w-[12rem] items-center justify-between gap-2 rounded-md border border-outline bg-surface px-3 py-1.5 text-body-sm shadow-xs transition hover:bg-surface-subtle focus-visible:outline-none focus-visible:shadow-focus disabled:cursor-not-allowed disabled:opacity-50",o),children:[s.jsx("span",{className:B("truncate",x?"text-text-primary":"text-text-secondary"),children:f.length===0?"Loadingâ¦":x||a}),s.jsx(J6,{className:"h-3.5 w-3.5 shrink-0 text-text-tertiary"})]})}),s.jsxs($d,{align:"start",className:"w-[16rem] p-0",onOpenAutoFocus:b=>{var v;b.preventDefault(),(v=h.current)==null||v.focus()},children:[s.jsxs("div",{className:"flex items-center gap-2 border-b border-outline-subtle px-2.5 py-1.5",children:[s.jsx(Fa,{className:"h-3.5 w-3.5 shrink-0 text-text-tertiary"}),s.jsx("input",{ref:h,value:u,onChange:b=>d(b.target.value),onKeyDown:b=>{b.key==="Enter"&&g[0]&&(b.preventDefault(),y(g[0].value))},placeholder:"Search sellersâ¦",className:"w-full bg-transparent text-body-sm text-text-primary placeholder:text-text-tertiary focus:outline-none"})]}),s.jsx("div",{className:"max-h-64 overflow-y-auto p-1",children:g.length===0?s.jsxs(iye,{children:["No sellers match â",u,"â."]}):g.map(b=>{const v=b.value===t;return s.jsxs(Gh,{onClick:()=>y(b.value),className:v?"text-text-primary":"text-text-secondary",children:[s.jsx("span",{className:"truncate",children:b.label}),v?s.jsx(fn,{className:"h-3.5 w-3.5 shrink-0 text-intent-brand"}):null]},b.value)})})]})]})}const Vc="all",KI="__workspace__",lye={allowAll:!0,allowWorkspace:!1,read:e=>{if(e==="/overview")return Vc;const t=/^\/overview\/([^/]+)/.exec(e);return t?decodeURIComponent(t[1]):null},apply:(e,{navigate:t})=>{t(e===Vc?"/overview":`/overview/${e}`)}},cye={allowAll:!1,allowWorkspace:!1,read:e=>{const t=/^\/ads\/([^/]+)/.exec(e);return t?decodeURIComponent(t[1]):null},apply:(e,{navigate:t})=>{t(`/ads/${e}`)}};function Y7(){return{allowAll:!1,allowWorkspace:!1,read:(e,t)=>t.get("seller"),apply:(e,{searchParams:t,setSearchParams:n})=>
788{const r=new URLSearchParams(t);r.set("seller",e),n(r,{replace:!0})}}}const uye=Y7(),dye=Y7();function hye(e){return e==="/overview"||e.startsWith("/overview/")?lye:e==="/ads"||e.startsWith("/ads/")?cye:e==="/sops"?uye:e==="/calendar"?dye:null}const Z7="gadjet:seller-scope",X7=p.createContext(null);function fye(){try{return localStorage.getItem(Z7)||Vc}catch{return Vc}}function mye({sellers:e,children:t}){const[n,r]=p.useState(fye);p.useEffect(()=>{VY(n===Vc?null:n)},[n]);const a=p.useMemo(()=>({sellers:e,stickyScope:n,setStickyScope:i=>{r(i);try{localStorage.setItem(Z7,i)}catch{}}}),[e,n]);return s.jsx(X7.Provider,{value:a,children:t})}function pye(){const e=p.useContext(X7);if(!e)throw new Error("useSellerScope must be used within a SellerScopeProvider");return e}function xye(){const e=Ba(),t=Rt(),[n,r]=ki(),{sellers:a,stickyScope:i,setStickyScope:o}=pye(),l=hye(e.pathname),c=p.useMemo(()=>{if(!l)return[];const x=[];return l.allowAll&&x.push({value:Vc,label:"All accounts"}),l.allowWorkspace&&x.push({value:KI,label:"Workspace (no seller)"}),x},[l]);if(!l)return null;const d=l.read(e.pathname,n)??i,f=d===Vc||d===KI||a.some(x=>x.slug===d)?d:l.allowAll?Vc:"";function m(x){l&&(o(x),l.apply(x,{navigate:t,pathname:e.pathname,searchParams:n,setSearchParams:r}))}return s.jsx(oye,{sellers:a,leadingOptions:c,value:f,onChange:m,className:"min-w-[10rem] max-w-[15rem]"})}const gye=6e4;function yye(e){p.useEffect(()=>{if(!e)return;let t=!1;async function n(){if(!(t||document.hidden))try{await oe("/api/heartbeat",{method:"POST"})}catch{}}n();const r=window.setInterval(n,gye);function a(){document.hidden||n()}return document.addEventListener("visibilitychange",a),()=>{t=!0,window.clearInterval(r),document.removeEventListener("visibilitychange",a)}},[e])}const bye=new Set(["invalid_code","self_referral","already_referred","no_account"]);function vye(e,t){const n=p.useRef(!1);p.useEffect(()=>{if(!e||!t||n.current)return;const r=qY();r&&(n.current=!0,Us.claimReferral(r).then(()=>xT()).catch(a=>{bye.has(a.message)?xT():n.current=!1}))},[e,t])}function wye(e){const t=p.useRef(!1);p.useEffect(()=>{if(!e||t.current)return;const n=GY();n&&(t.current=!0,oe("/api/me/first-touch",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(n)}).then(r=>{r.ok||r.status===409?YY():t.current=!1}).catch(()=>{t.current=!1}))},[e])}const _ye={toast:"font-sans rounded-lg shadow-md text-body-sm border",title:"text-body-sm font-medium",description:"!text-current",closeButton:"!bg-inherit !border-current !text-current hover:!bg-surface/60",actionButton:"!bg-surface-inverse !text-text-inverse",success:"!bg-surface-successSubtle !border-outline-success !text-text-success",error:"!bg-surface-errorSubtle !border-outline-error !text-text-error",info:"!bg-surface-infoSubtle !border-outline-info !text-text-info",warning:"!bg-surface-warningSubtle !border-outline-warning !text-text-warning",loading:"!bg-surface-subtle !border-outline-subtle !text-text-body"},HI="gadjet:sidebar-collapsed";function kye({children:e}){const t=Lt(),n=Ba();if(t.kind!=="ready")return s.jsx(s.Fragment,{children:e});const r=t.me.nav_visibility??null,a=Dle(n.pathname);if(!a||Kc(r,a))return s.jsx(s.Fragment,{children:e});const i=t.me.role==="seller_user",o=[...t.me.allowed_slugs??[]].sort()[0]??null,l=Mle(r,i||t.me.role==="content_creator"&&!!o,o);return l===n.pathname?s.jsx(s.Fragment,{children:e}):s.jsx(Yt,{to:l,replace:!0})}function jye(){var N;const e=u6(),[t,n]=p.useState(null),[r,a]=p.useState({}),[i,o]=p.useState(null),[l,c]=p.useState(!1),[u,d]=p.useState(()=>{try{return localStorage.getItem(HI)==="1"}catch{return!1}});p.useEffect(()=>{try{localStorage.setItem(HI,u?"1":"0")}catch{}},[u]);const h=jn(),f=Ba(),m=((N=/^\/settings\/stores\/([^/]+)/.exec(f.pathname))==null?void 0:N[1])??null,x=h.slug??m,g=Lt();yye(g.kind==="ready"),vye(g.kind==="ready",g.kind==="ready"?g.me.account_id:null),wye(g.kind==="ready");const y=g.kind==="ready"&&g.me.is_demo_mode,b=g.kind==="ready"?`${g.me.id}|${g.me.account_id}|${g.me.is_demo_mode}|${g.me.has_sellers}`:g.kind,w=!(f.pathname.startsWith("/agent")||/^\/sellers\/[^/]+\/chats(\/.*)?$/.test(f.pathname)||/^\/sellers\/[^/]+\/reports(\/.*)?$/.test(f.pathname)),_=zle(f.pathname),[k,j]=p.useState(0);return p.useEffect(()=>{K.sellers().then(n).catch(E=>o(String(E))),K.listSellerBadges().then(a).catch(()=>{})},[b,k]),p.useEffect(()=>{if(g.kind!=="ready")return;let E=null;const A=xn.channel("seller-summary-changes").on("postgres_changes",{event:"*",schema:"public",table:"seller_summary"},()=>{E&&clearTimeout(E),E=setTimeout(()=>{j(C=>C+1),E=null},500)}).subscribe();return()=>{E&&clearTimeout(E),xn.removeChannel(A)}},[g.kind]),p.useEffect(()=>{c(!1)},[f.pathname]),p.useEffect(()=>{if(!l)return;const E=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=E}},[l]),s.jsx(sue,{slug:x,children:s.jsx($xe,{userId:g.kind==="ready"?g.me.id:null,children:s.jsx(Bge,{children:s.jsx(mye,{sellers:t??[],children:s.jsxs(Oce,{children:[s.jsxs("div",{className:"flex flex-col h-full bg-surface",children:[s.jsxs(ece,{children:[s.jsx(nue,{}),s.jsx(Qce,{}),y&&s.jsx(qce,{}),s.jsx(Zce,{}),s.jsx(oB,{detail:"stack"})]}),s.jsxs("div",{className:"flex flex-col md:flex-row flex-1 min-h-0",children:[s.jsx(Hce,{onMenuClick:()=>c(!0)}),l&&s.jsx("button",{type:"button","aria-label":"Close navigation",onClick:()=>c(!1),className:"md:hidden fixed inset-0 z-drawer bg-surface-inverse/30"}),s.jsx(xce,{sellers:t,sellerBadges:r,activeSlug:x,drawerOpen:l,onCloseDrawer:()=>c(!1),collapsed:u}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col overflow-hidden",children:[s.jsx(Uge,{left:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>d(E=>!E),"aria-label":u?"Show sidebar":"Hide sidebar",title:u?"Show sidebar":"Hide sidebar",className:"hidden md:flex p-1.5 rounded-md text-text-secondary hover:text-text-primary hover:bg-surface-sunken",children:u?s.jsx(fre,{className:"w-4 h-4"}):s.jsx(dre,{className:"w-4 h-4"})}),s.jsx(xye,{})]})}),s.jsxs("div",{className:"flex-1 min-w-0 flex overflow-hidden",children:[!w&&s.jsx(Kce,{sellers:t,activeSlug:x,error:i,mobileVisible:_}),s.jsx("main",{className:_?"hidden md:flex flex-1 min-w-0 overflow-hidden flex-col":"flex-1 min-w-0 overflow-hidden flex flex-col",children:s.jsx(Vce,{resetKey:f.pathname,children:s.jsx(kye,{children:s.jsx(ZY,{})})})})]})]})]})]}),s.jsx(aue,{slug:x}),s.jsx(Lxe,{}),s.jsx(Ale,{position:"bottom-right",theme:e,closeButton:!0,toastOptions:{duration:4e3,classNames:_ye},className:"!z-toast"})]})})})})})}const Nye={overview:"Overview",sales:"Sales",returns:"Returns",inventory:"Inventory",shipments:"Shipments"};function J7(e){return e?e.slice(0,10)||e:"â"}function Q7(e){return e==null?"â":ge(e)}function xx({view:e,chrome:t=!0}){const{slug:n=""}=jn(),[r,a]=p.useState(null),[i,o]=p.useState(null),[l,c]=p.useState(!1);async function u(f){c(!0),o(null);try{const m=await K.makroPortalSync(n,f);a(m)}catch(m){o(m instanceof Error?m.message:"Could not read Makro")}finally{c(!1)}}p.useEffect(()=>{let f=!0;return a(null),o(null),K.makroPortal(n).then(m=>{f&&(a(m),m.connected&&m.session==="ok"&&!m.synced_at&&(c(!0),K.makroPortalSync(n,!1).then(x=>{f&&a(x)}).catch(x=>{f&&o(x instanceof Error?x.message:"Could not read Makro")}).finally(()=>{f&&c(!1)})))}).catch(m=>{f&&o(m instanceof Error?m.message:"Could not read Makro")}),()=>{f=!1}},[n]);const d=Nye[e],h=s.jsxs("div",{className:t?"w-full p-4 md:p-6 space-y-4":"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("p",{className:"text-xs text-text-secondary",children:r!=null&&r.synced_at?`Read from the Makro portal ${J7(r.synced_at)}`:"Orders, returns, and listings come from the connected Makro portal."}),s.jsxs(W,{onClick:()=>void u(!0),disabled:l||!(r!=null&&r.connected),intent:"neutral",variant:"outline",size:"sm",children:[l?s.jsx(_e,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):s.jsx(pa,{className:"mr-2 h-3.5 w-3.5"}),l?"Reading Makroâ¦":"Refresh"]})]}),i&&s.jsx(V,{className:"p-3 text-sm text-text-error",children:i}),!r&&!i&&s.jsx("p",{className:"text-sm text-text-secondary",children:"Loading Makroâ¦"}),r&&!r.connected&&s.jsxs(V,{className:"p-4 text-sm text-text-secondary",children:["Connect this store in"," ",s.jsx(st,{className:"text-text-brand",to:`/settings/stores/${n}`,children:"Settings â Integrations"}),". Makroâs seller API cannot read orders, so the portal connection is what fills this page."]}),(r==null?void 0:r.message)&&s.jsx(V,{className:"p-4 text-sm text-text-secondary",children:r.message}),(r==null?void 0:r.connected)&&r.session==="ok"&&s.jsx(Sye,{view:e,snapshot:r})]});return t?s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Sellers",to:"/"},{label:(r==null?void 0:r.display_name)||n,to:`/overview/${n}`},{label:d}]}),s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:h})]}):h}function Sye({view:e,snapshot:t}){if(e==="sales")return s.jsxs(s.Fragment,{children:[t.orders.note&&s.jsx(V,{className:"p-3 text-sm text-text-secondary",children:t.orders.note}),s.jsx(fb,{lines:t.orders.lines,empty:"No Makro orders in the portal yet."})]});if(e==="shipments"){const n=t.orders.lines.filter(r=>r.bucket==="To pack"||r.bucket==="In transit");return s.jsx(fb,{lines:n,empty:"Nothing is waiting to pack or in transit."})}return e==="returns"?s.jsx(Eye,{snapshot:t}):e==="inventory"?s.jsx(Aye,{snapshot:t}):s.jsx(Cye,{snapshot:t})}function Cye({snapshot:e}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[s.jsx(Wl,{label:"Orders",value:de(e.orders.total)}),s.jsx(Wl,{label:"Cancellations",value:de(e.cancellations.total)}),s.jsx(Wl,{label:"Listings",value:de(e.listings.count)}
788),s.jsx(Wl,{label:"Categories",value:de(e.categories.verticals)})]}),s.jsx(fb,{lines:e.orders.lines.slice(0,8),empty:"No Makro orders in the portal yet."}),s.jsx(e9,{snapshot:e})]})}function Eye({snapshot:e}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsx(Wl,{label:"Cancellations",value:de(e.cancellations.total)}),s.jsx(Wl,{label:"Returns",value:e.returns.available?de(e.returns.total):"â"})]}),e.returns.note&&s.jsx(V,{className:"p-3 text-sm text-text-secondary",children:e.returns.note}),s.jsx(fb,{lines:[...e.cancellations.lines,...e.returns.lines],empty:"No cancellations or returns in the portal yet."})]})}function Aye({snapshot:e}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[s.jsx(Wl,{label:"Listings",value:de(e.listings.count)}),s.jsx(Wl,{label:"Pickup",value:e.pickup_location_id||"None yet"}),s.jsx(Wl,{label:"Catalogue verticals",value:de(e.categories.verticals)})]}),Object.keys(e.listings.states).length>0&&s.jsx(V,{className:"p-3 text-xs text-text-secondary",children:Object.entries(e.listings.states).map(([t,n])=>s.jsxs("span",{className:"mr-3",children:[t,": ",de(n)]},t))}),s.jsx(Tye,{lines:e.listings.lines}),s.jsx(e9,{snapshot:e})]})}function e9({snapshot:e}){const{departments:t,verticals:n,names:r}=e.categories;return t?s.jsxs(V,{className:"p-4 text-sm text-text-secondary",children:["Makroâs category catalogue has ",de(t)," departments and ",de(n)," verticals",r.length?`: ${r.slice(0,8).join(", ")}`:"","."]}):null}function Wl({label:e,value:t}){return s.jsxs(V,{className:"p-3",children:[s.jsx("div",{className:"text-xs text-text-tertiary",children:e}),s.jsx("div",{className:"text-lg font-semibold text-text-primary truncate",children:t})]})}function fb({lines:e,empty:t}){return e.length?s.jsx(V,{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full text-sm",children:[s.jsx("thead",{className:"text-left text-xs text-text-tertiary",children:s.jsxs("tr",{children:[s.jsx("th",{className:"px-3 py-2 font-medium",children:"Order"}),s.jsx("th",{className:"px-3 py-2 font-medium",children:"Item"}),s.jsx("th",{className:"px-3 py-2 font-medium",children:"Status"}),s.jsx("th",{className:"px-3 py-2 font-medium",children:"Qty"}),s.jsx("th",{className:"px-3 py-2 font-medium",children:"Amount"}),s.jsx("th",{className:"px-3 py-2 font-medium",children:"Date"})]})}),s.jsx("tbody",{children:e.map((n,r)=>s.jsxs("tr",{className:"border-t border-outline-subtle",children:[s.jsx("td",{className:"px-3 py-2 text-text-primary",children:n.order_id||"â"}),s.jsxs("td",{className:"px-3 py-2",children:[s.jsx("div",{className:"text-text-primary",children:n.title||n.sku||"â"}),n.bucket&&s.jsx("div",{className:"text-xs text-text-tertiary",children:n.bucket})]}),s.jsx("td",{className:"px-3 py-2",children:n.status||"â"}),s.jsx("td",{className:"px-3 py-2",children:n.quantity??"â"}),s.jsx("td",{className:"px-3 py-2",children:Q7(n.amount)}),s.jsx("td",{className:"px-3 py-2",children:J7(n.ordered_at)})]},`${n.order_item_id||n.order_id||"row"}-${r}`))})]})}):s.jsx(V,{className:"p-4 text-sm text-text-secondary",children:t})}function Tye({lines:e}){return e.length?s.jsx(V,{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full text-sm",children:[s.jsx("thead",{className:"text-left text-xs text-text-tertiary",children:s.jsxs("tr",{children:[s.jsx("th",{className:"px-3 py-2 font-medium",children:"SKU"}),s.jsx("th",{className:"px-3 py-2 font-medium",children:"Title"}),s.jsx("th",{className:"px-3 py-2 font-medium",children:"State"}),s.jsx("th",{className:"px-3 py-2 font-medium",children:"Price"}),s.jsx("th",{className:"px-3 py-2 font-medium",children:"Stock"})]})}),s.jsx("tbody",{children:e.map((t,n)=>s.jsxs("tr",{className:"border-t border-outline-subtle",children:[s.jsx("td",{className:"px-3 py-2",children:t.sku||t.product_id||"â"}),s.jsx("td",{className:"px-3 py-2",children:t.title||"â"}),s.jsx("td",{className:"px-3 py-2",children:t.state||"â"}),s.jsx("td",{className:"px-3 py-2",children:Q7(t.price)}),s.jsx("td",{className:"px-3 py-2",children:t.stock??"â"})]},`${t.listing_id||t.sku||"listing"}-${n}`))})]})}):s.jsx(V,{className:"p-4 text-sm text-text-secondary",children:"No Makro listings in the portal yet."})}var Oye=["dangerouslySetInnerHTML","onCopy","onCopyCapture","onCut","onCutCapture","onPaste","onPasteCapture","onCompositionEnd","onCompositionEndCapture","onCompositionStart","onCompositionStartCapture","onCompositionUpdate","onCompositionUpdateCapture","onF
788ocus","onFocusCapture","onBlur","onBlurCapture","onChange","onChangeCapture","onBeforeInput","onBeforeInputCapture","onInput","onInputCapture","onReset","onResetCapture","onSubmit","onSubmitCapture","onInvalid","onInvalidCapture","onLoad","onLoadCapture","onError","onErrorCapture","onKeyDown","onKeyDownCapture","onKeyPress","onKeyPressCapture","onKeyUp","onKeyUpCapture","onAbort","onAbortCapture","onCanPlay","onCanPlayCapture","onCanPlayThrough","onCanPlayThroughCapture","onDurationChange","onDurationChangeCapture","onEmptied","onEmptiedCapture","onEncrypted","onEncryptedCapture","onEnded","onEndedCapture","onLoadedData","onLoadedDataCapture","onLoadedMetadata","onLoadedMetadataCapture","onLoadStart","onLoadStartCapture","onPause","onPauseCapture","onPlay","onPlayCapture","onPlaying","onPlayingCapture","onProgress","onProgressCapture","onRateChange","onRateChangeCapture","onSeeked","onSeekedCapture","onSeeking","onSeekingCapture","onStalled","onStalledCapture","onSuspend","onSuspendCapture","onTimeUpdate","onTimeUpdateCapture","onVolumeChange","onVolumeChangeCapture","onWaiting","onWaitingCapture","onAuxClick","onAuxClickCapture","onClick","onClickCapture","onContextMenu","onContextMenuCapture","onDoubleClick","onDoubleClickCapture","onDrag","onDragCapture","onDragEnd","onDragEndCapture","onDragEnter","onDragEnterCapture","onDragExit","onDragExitCapture","onDragLeave","onDragLeaveCapture","onDragOver","onDragOverCapture","onDragStart","onDragStartCapture","onDrop","onDropCapture","onMouseDown","onMouseDownCapture","onMouseEnter","onMouseLeave","onMouseMove","onMouseMoveCapture","onMouseOut","onMouseOutCapture","onMouseOver","onMouseOverCapture","onMouseUp","onMouseUpCapture","onSelect","onSelectCapture","onTouchCancel","onTouchCancelCapture","onTouchEnd","onTouchEndCapture","onTouchMove","onTouchMoveCapture","onTouchStart","onTouchStartCapture","onPointerDown","onPointerDownCapture","onPointerMove","onPointerMoveCapture","onPointerUp","onPointerUpCapture","onPointerCancel","onPointerCancelCapture","onPointerEnter","onPointerEnterCapture","onPointerLeave","onPointerLeaveCapture","onPointerOver","onPointerOverCapture","onPointerOut","onPointerOutCapture","onGotPointerCapture","onGotPointerCaptureCapture","onLostPointerCapture","onLostPointerCaptureCapture","onScroll","onScrollCapture","onWheel","onWheelCapture","onAnimationStart","onAnimationStartCapture","onAnimationEnd","onAnimationEndCapture","onAnimationIteration","onAnimationIterationCapture","onTransitionEnd","onTransitionEndCapture"];function KC(e){if(typeof e!="string")return!1;var t=Oye;return t.includes(e)}var Iye=["aria-activedescendant","aria-atomic","aria-autocomplete","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colspan","aria-controls","aria-current","aria-describedby","aria-details","aria-disabled","aria-errormessage","aria-expanded","aria-flowto","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext","className","color","height","id","lang","max","media","method","min","name","style","target","width","role","tabIndex","accentHeight","accumulate","additive","alignmentBaseline","allowReorder","alphabetic","amplitude","arabicForm","ascent","attributeName","attributeType","autoReverse","azimuth","baseFrequency","baselineShift","baseProfile","bbox","begin","bias","by","calcMode","capHeight","clip","clipPath","clipPathUnits","clipRule","colorInterpolation","colorInterpolationFilters","colorProfile","colorRendering","contentScriptType","contentStyleType","cursor","cx","cy","d","decelerate","descent","diffuseConstant","direction","display","divisor","dominantBaseline","dur","dx","dy","edgeMode","elevation","enableBackground","end","exponent","externalResourcesRequired","fill","fillOpacity","fillRule","filter","filterRes","filterUnits","floodColor","floodOpacity","focusable","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","format","from","fx","fy","g1","g2","glyphName","glyphOrientationHorizontal","glyphOrientationVertical","glyphRef","gradientTransform","gradientUnits","hanging","horizAdvX","horizOriginX","href","ideographic","imageRendering","in2","in","intercept","k1","k2","k3","k4","k","kernelMatrix","kernelUnitLength","kerning","keyPoints","keySplines","keyTimes","lengthAdjust","letterSpacing","lightingColor","limitingConeAngle","local","markerEnd","markerHeight","markerMid","markerStart","markerUnits","markerWidth","mask","maskContentUnits","maskUnits","mathematical","mode","numOctaves","offset","opacity","operator","order","orient","orientation","origin","overflow","overlinePosition","overlineThickness","paintOrder","panose1","pathLength","patternContentUnits","patternTransform","patternUnits","pointerEvents","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","r","radius","refX","refY","renderingIntent","repeatCount","repeatDur","requiredExtensions","requiredFeatures","restart","result","rotate","rx","ry","seed","shapeRendering","slope","spacing","specularConstant","specularExponent","speed","spreadMethod","startOffset","stdDeviation","stemh","stemv","stitchTiles","stopColor","stopOpacity","strikethroughPosition","strikethroughThickness","string","stroke","strokeDasharray","strokeDashoffset","strokeLinecap","strokeLinejoin","strokeMiterlimit","strokeOpacity","strokeWidth","surfaceScale","systemLanguage","tableValues","targetX","targetY","textAnchor","textDecoration","textLength","textRendering","to","transform","u1","u2","underlinePosition","underlineThickness","unicode","unicodeBidi","unicodeRange","unitsPerEm","vAlphabetic","values","vectorEffect","version","vertAdvY","vertOriginX","vertOriginY","vHanging","vIdeographic","viewTarget","visibility","vMathematical","widths","wordSpacing","writingMode","x1","x2","x","xChannelSelector","xHeight","xlinkActuate","xlinkArcrole","xlinkHref","xlinkRole","xlinkShow","xlinkTitle","xlinkType","xmlBase","xmlLang","xmlns","xmlnsXlink","xmlSpace","y1","y2","y","yChannelSelector","z","zoomAndPan","ref","key","angle"],Pye=new Set(Iye);function t9(e){return typeof e!="string"?!1:Pye.has(e)}function n9(e){return typeof e=="string"&&e.startsWith("data-")}function Ra(e){if(typeof e!="object"||e===null)return{};var t={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t9(n)||n9(n))&&(t[n]=e[n]);return t}function _d(e){if(e==null)return null;if(p.isValidElement(e)&&typeof e.props=="object"&&e.props!==null){var t=e.props;return Ra(t)}return typeof e=="object"&&!Array.isArray(e)?Ra(e):null}function ha(e){var t={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t9(n)||n9(n)||KC(n))&&(t[n]=e[n]);return t}function Rye(e){return e==null?null:p.isValidElement(e)?ha(e.props):typeof e=="object"&&!Array.isArray(e)?ha(e):null}var Dye=["children","width","height","viewBox","className","style","title","desc"];function UN(){return UN=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},UN.apply(null,arguments)}function Mye(e,t){if(e==null)return{};var n,r,a=$ye(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function $ye(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var HC=p.forwardRef((e,t)=>
788{var n=e.children,r=e.width,a=e.height,i=e.viewBox,o=e.className,l=e.style,c=e.title,u=e.desc,d=Mye(e,Dye),h=i||{width:r,height:a,x:0,y:0},f=un("recharts-surface",o);return p.createElement("svg",UN({},ha(d),{className:f,width:r,height:a,style:l,viewBox:"".concat(h.x," ").concat(h.y," ").concat(h.width," ").concat(h.height),ref:t}),p.createElement("title",null,c),p.createElement("desc",null,u),n)}),Lye=["children","className"];function zN(){return zN=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},zN.apply(null,arguments)}function Fye(e,t){if(e==null)return{};var n,r,a=Bye(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function Bye(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var rr=p.forwardRef((e,t)=>{var n=e.children,r=e.className,a=Fye(e,Lye),i=un("recharts-layer",r);return p.createElement("g",zN({className:i},ha(a),{ref:t}),n)}),T1={},O1={},VI;function Uye(){return VI||(VI=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n){return n==="__proto__"}e.isUnsafeProperty=t})(O1)),O1}var I1={},qI;function r9(){return qI||(qI=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n){switch(typeof n){case"number":case"symbol":return!1;case"string":return n.includes(".")||n.includes("[")||n.includes("]")}}e.isDeepKey=t})(I1)),I1}var P1={},GI;function VC(){return GI||(GI=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n){var r;return typeof n=="string"||typeof n=="symbol"?n:Object.is((r=n==null?void 0:n.valueOf)==null?void 0:r.call(n),-0)?"-0":String(n)}e.toKey=t})(P1)),P1}var R1={},D1={},YI;function zye(){return YI||(YI=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n){if(n==null)return"";if(typeof n=="string")return n;if(Array.isArray(n))return n.map(t).join(",");const r=String(n);return r==="0"&&Object.is(Number(n),-0)?"-0":r}e.toString=t})(D1)),D1}var ZI;function qC(){return ZI||(ZI=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=zye(),n=VC();function r(a){if(Array.isArray(a))return a.map(n.toKey);if(typeof a=="symbol")return[a];a=t.toString(a);const i=[],o=a.length;if(o===0)return i;let l=0,c="",u="",d=!1;for(a.charCodeAt(0)===46&&(i.push(""),l++);l<o;){const h=a[l];u?h==="\\"&&l+1<o?(l++,c+=a[l]):h===u?u="":c+=h:d?h==='"'||h==="'"?u=h:h==="]"?(d=!1,i.push(c),c=""):c+=h:h==="["?(d=!0,c&&(i.push(c),c="")):h==="."?c&&(i.push(c),c=""):c+=h,l++}return c&&i.push(c),i}e.toPath=r})(R1)),R1}var XI;function GC(){return XI||(XI=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=Uye(),n=r9(),r=VC(),a=qC();function i(l,c,u){if(l==null)return u;switch(typeof c){case"string":{if(t.isUnsafeProperty(c))return u;const d=l[c];return d===void 0?n.isDeepKey(c)?i(l,a.toPath(c),u):u:d}case"number":case"symbol":{typeof c=="number"&&(c=r.toKey(c));const d=l[c];return d===void 0?u:d}default:{if(Array.isArray(c))return o(l,c,u);if(Object.is(c==null?void 0:c.valueOf(),-0)?c="-0":c=String(c),t.isUnsafeProperty(c))return u;const d=l[c];return d===void 0?u:d}}}function o(l,c,u){if(c.length===0)return u;let d=l;for(let h=0;h<c.length;h++){if(d==null||t.isUnsafeProperty(c[h]))return u;d=d[c[h]]}return d===void 0?u:d}e.get=i})(T1)),T1}var M1,JI;function Wye(){return JI||(JI=1,M1=GC().get),M1}var Kye=Wye();const kd=hl(Kye);var Hye=4;function Kl(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Hye,n=10**t,r=Math.round(e*n)/n;return Object.is(r,-0)?0:r}function Ms(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return e.reduce((a,i,o)=>{var l=n[o-1];return typeof l=="string"?a+l+i:l!==void 0?a+Kl(l)+i:a+i},"")}var ws=e=>e===0?0:e>0?1:-1,No=e=>typeof e=="number"&&e!=+e,jd=e=>typeof e=="string"&&e.length>1&&e.indexOf("%")===e.length-1,rt=e=>(typeof e=="number"||e instanceof Number)&&!No(e),aa=e=>rt(e)||typeof e=="string",Vye=0,Ap=e=>{var t=++Vye;return"".concat(e||"").concat(t)},ca=function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!rt(t)&&typeof t!="string")return r;var i;if(jd(t)){if(n==null)return r;var o=t.indexOf("%");i=n*parseFloat(t.slice(0,o))/100}else i=+t;return No(i)&&(i=r),a&&n!=null&&i>n&&(i=n),i},s9=e=>{if(!Array.isArray(e))return!1;for(var t=e.length,n={},r=0;r<t;r++)if(!n[String(e[r])])n[String(e[r])]=!0;else return!0;return!1};
788function qn(e,t,n){return rt(e)&&rt(t)?Kl(e+n*(t-e)):t}function a9(e,t,n){if(!(!e||!e.length))return e.find(r=>r&&(typeof t=="function"?t(r):kd(r,t))===n)}var sr=e=>e===null||typeof e>"u",gx=e=>sr(e)?e:"".concat(e.charAt(0).toUpperCase()).concat(e.slice(1));function Ea(e){return e!=null}function bu(){}function YC(e){if(e)return{x:e.x,y:e.y,upperWidth:"upperWidth"in e?e.upperWidth:e.width,lowerWidth:"lowerWidth"in e?e.lowerWidth:e.width,width:e.width,height:e.height}}function QI(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function $o(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?QI(Object(n),!0).forEach(function(r){qye(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):QI(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function qye(e,t,n){return(t=Gye(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Gye(e){var t=Yye(e,"string");return typeof t=="symbol"?t:t+""}function Yye(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var i9=e=>{var t=e.viewBox,n=e.position,r=e.offset,a=r===void 0?0:r,i=e.parentViewBox,o=e.clamp,l=YC(t),c=l.x,u=l.y,d=l.height,h=l.upperWidth,f=l.lowerWidth,m=c,x=c+(h-f)/2,g=(m+x)/2,y=(h+f)/2,b=m+h/2,v=d>=0?1:-1,w=v*a,_=v>0?"end":"start",k=v>0?"start":"end",j=h>=0?1:-1,N=j*a,E=j>0?"end":"start",A=j>0?"start":"end",C=i;if(n==="top"){var T={x:m+h/2,y:u-w,horizontalAnchor:"middle",verticalAnchor:_};return o&&C&&(T.height=Math.max(u-C.y,0),T.width=h),T}if(n==="bottom"){var S={x:x+f/2,y:u+d+w,horizontalAnchor:"middle",verticalAnchor:k};return o&&C&&(S.height=Math.max(C.y+C.height-(u+d),0),S.width=f),S}if(n==="left"){var O={x:g-N,y:u+d/2,horizontalAnchor:E,verticalAnchor:"middle"};return o&&C&&(O.width=Math.max(O.x-C.x,0),O.height=d),O}if(n==="right"){var R={x:g+y+N,y:u+d/2,horizontalAnchor:A,verticalAnchor:"middle"};return o&&C&&(R.width=Math.max(C.x+C.width-R.x,0),R.height=d),R}var I=o&&C?{width:y,height:d}:{};return n==="insideLeft"?$o({x:g+N,y:u+d/2,horizontalAnchor:A,verticalAnchor:"middle"},I):n==="insideRight"?$o({x:g+y-N,y:u+d/2,horizontalAnchor:E,verticalAnchor:"middle"},I):n==="insideTop"?$o({x:m+h/2,y:u+w,horizontalAnchor:"middle",verticalAnchor:k},I):n==="insideBottom"?$o({x:x+f/2,y:u+d-w,horizontalAnchor:"middle",verticalAnchor:_},I):n==="insideTopLeft"?$o({x:m+N,y:u+w,horizontalAnchor:A,verticalAnchor:k},I):n==="insideTopRight"?$o({x:m+h-N,y:u+w,horizontalAnchor:E,verticalAnchor:k},I):n==="insideBottomLeft"?$o({x:x+N,y:u+d-w,horizontalAnchor:A,verticalAnchor:_},I):n==="insideBottomRight"?$o({x:x+f-N,y:u+d-w,horizontalAnchor:E,verticalAnchor:_},I):n&&typeof n=="object"&&(rt(n.x)||jd(n.x))&&(rt(n.y)||jd(n.y))?$o({x:c+ca(n.x,y),y:u+ca(n.y,d),horizontalAnchor:"end",verticalAnchor:"end"},I):$o({x:b,y:u+d/2,horizontalAnchor:"middle",verticalAnchor:"middle"},I)},Zye=["top","left","right","bottom"];function ZC(e){return e==null?!1:typeof e=="object"?!0:Zye.includes(e)}var o9=p.createContext(null),Xye=()=>p.useContext(o9);function Vn(e){return function(){return e}}const l9=Math.cos,mb=Math.sin,To=Math.sqrt,pb=Math.PI,v0=2*pb,WN=Math.PI,KN=2*WN,Hu=1e-6,Jye=KN-Hu;function c9(e){this._+=e[0];for(let t=1,n=e.length;t<n;++t)this._+=arguments[t]+e[t]}function Qye(e){let t=Math.floor(e);if(!(t>=0))throw new Error(`invalid digits: ${e}`);if(t>15)return c9;const n=10**t;return function(r){this._+=r[0];for(let a=1,i=r.length;a<i;++a)this._+=Math.round(arguments[a]*n)/n+r[a]}}class ebe{constructor(t){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=t==null?c9:Qye(t)}moveTo(t,n){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`)}lineTo(t,n){this._append`L${this._x1=+t},${this._y1=+n}`}quadraticCurveTo(t,n,r,a){this._append`Q${+t},${+n},${this._x1=+r},${this._y1=+a}`}bezierCurveTo(t,n,r,a,i,o){this._append`C${+t},${+n},${+r},${+a},${this._x1=+i},${this._y1=+o}`}
vendor: 4,573 bytes, line 788
788arcTo(t,n,r,a,i){if(t=+t,n=+n,r=+r,a=+a,i=+i,i<0)throw new Error(`negative radius: ${i}`);let o=this._x1,l=this._y1,c=r-t,u=a-n,d=o-t,h=l-n,f=d*d+h*h;if(this._x1===null)this._append`M${this._x1=t},${this._y1=n}`;else if(f>Hu)if(!(Math.abs(h*c-u*d)>Hu)||!i)this._append`L${this._x1=t},${this._y1=n}`;else{let m=r-o,x=a-l,g=c*c+u*u,y=m*m+x*x,b=Math.sqrt(g),v=Math.sqrt(f),w=i*Math.tan((WN-Math.acos((g+f-y)/(2*b*v)))/2),_=w/v,k=w/b;Math.abs(_-1)>Hu&&this._append`L${t+_*d},${n+_*h}`,this._append`A${i},${i},0,0,${+(h*m>d*x)},${this._x1=t+k*c},${this._y1=n+k*u}`}}arc(t,n,r,a,i,o){if(t=+t,n=+n,r=+r,o=!!o,r<0)throw new Error(`negative radius: ${r}`);let l=r*Math.cos(a),c=r*Math.sin(a),u=t+l,d=n+c,h=1^o,f=o?a-i:i-a;this._x1===null?this._append`M${u},${d}`:(Math.abs(this._x1-u)>Hu||Math.abs(this._y1-d)>Hu)&&this._append`L${u},${d}`,r&&(f<0&&(f=f%KN+KN),f>Jye?this._append`A${r},${r},0,1,${h},${t-l},${n-c}A${r},${r},0,1,${h},${this._x1=u},${this._y1=d}`:f>Hu&&this._append`A${r},${r},0,${+(f>=WN)},${h},${this._x1=t+r*Math.cos(i)},${this._y1=n+r*Math.sin(i)}`)}rect(t,n,r,a){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}h${r=+r}v${+a}h${-r}Z`}toString(){return this._}}function XC(e){let t=3;return e.digits=function(n){if(!arguments.length)return t;if(n==null)t=null;else{const r=Math.floor(n);if(!(r>=0))throw new RangeError(`invalid digits: ${n}`);t=r}return e},()=>new ebe(t)}function JC(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function u9(e){this._context=e}u9.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t);break}}};function w0(e){return new u9(e)}function d9(e){return e[0]}function h9(e){return e[1]}function f9(e,t){var n=Vn(!0),r=null,a=w0,i=null,o=XC(l);e=typeof e=="function"?e:e===void 0?d9:Vn(e),t=typeof t=="function"?t:t===void 0?h9:Vn(t);function l(c){var u,d=(c=JC(c)).length,h,f=!1,m;for(r==null&&(i=a(m=o())),u=0;u<=d;++u)!(u<d&&n(h=c[u],u,c))===f&&((f=!f)?i.lineStart():i.lineEnd()),f&&i.point(+e(h,u,c),+t(h,u,c));if(m)return i=null,m+""||null}return l.x=function(c){return arguments.length?(e=typeof c=="function"?c:Vn(+c),l):e},l.y=function(c){return arguments.length?(t=typeof c=="function"?c:Vn(+c),l):t},l.defined=function(c){return arguments.length?(n=typeof c=="function"?c:Vn(!!c),l):n},l.curve=function(c){return arguments.length?(a=c,r!=null&&(i=a(r)),l):a},l.context=function(c){return arguments.length?(c==null?r=i=null:i=a(r=c),l):r},l}function vg(e,t,n){var r=null,a=Vn(!0),i=null,o=w0,l=null,c=XC(u);e=typeof e=="function"?e:e===void 0?d9:Vn(+e),t=typeof t=="function"?t:Vn(t===void 0?0:+t),n=typeof n=="function"?n:n===void 0?h9:Vn(+n);function u(h){var f,m,x,g=(h=JC(h)).length,y,b=!1,v,w=new Array(g),_=new Array(g);for(i==null&&(l=o(v=c())),f=0;f<=g;++f){if(!(f<g&&a(y=h[f],f,h))===b)if(b=!b)m=f,l.areaStart(),l.lineStart();else{for(l.lineEnd(),l.lineStart(),x=f-1;x>=m;--x)l.point(w[x],_[x]);l.lineEnd(),l.areaEnd()}b&&(w[f]=+e(y,f,h),_[f]=+t(y,f,h),l.point(r?+r(y,f,h):w[f],n?+n(y,f,h):_[f]))}if(v)return l=null,v+""||null}function d(){return f9().defined(a).curve(o).context(i)}return u.x=function(h){return arguments.length?(e=typeof h=="function"?h:Vn(+h),r=null,u):e},u.x0=function(h){return arguments.length?(e=typeof h=="function"?h:Vn(+h),u):e},u.x1=function(h){return arguments.length?(r=h==null?null:typeof h=="function"?h:Vn(+h),u):r},u.y=function(h){return arguments.length?(t=typeof h=="function"?h:Vn(+h),n=null,u):t},u.y0=function(h){return arguments.length?(t=typeof h=="function"?h:Vn(+h),u):t},u.y1=function(h){return arguments.length?(n=h==null?null:typeof h=="function"?h:Vn(+h),u):n},u.lineX0=u.lineY0=function(){return d().x(e).y(t)},u.lineY1=function(){return d().x(e).y(n)},u.lineX1=function(){return d().x(r).y(t)},u.defined=function(h){return arguments.length?(a=typeof h=="function"?h:Vn(!!h),u):a},u.curve=function(h){return arguments.length?(o=h,i!=null&&(l=o(i)),u):o},u.context=function(h){return arguments.length?(h==null?i=l=null:l=o(i=h),u):i},u}class m9{constructor(t,n){this._context=t,this._x=n}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}
788point(t,n){switch(t=+t,n=+n,this._point){case 0:{this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,n,t,n):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+n)/2,t,this._y0,t,n);break}}this._x0=t,this._y0=n}}function tbe(e){return new m9(e,!0)}function nbe(e){return new m9(e,!1)}const QC={draw(e,t){const n=To(t/pb);e.moveTo(n,0),e.arc(0,0,n,0,v0)}},rbe={draw(e,t){const n=To(t/5)/2;e.moveTo(-3*n,-n),e.lineTo(-n,-n),e.lineTo(-n,-3*n),e.lineTo(n,-3*n),e.lineTo(n,-n),e.lineTo(3*n,-n),e.lineTo(3*n,n),e.lineTo(n,n),e.lineTo(n,3*n),e.lineTo(-n,3*n),e.lineTo(-n,n),e.lineTo(-3*n,n),e.closePath()}},p9=To(1/3),sbe=p9*2,abe={draw(e,t){const n=To(t/sbe),r=n*p9;e.moveTo(0,-n),e.lineTo(r,0),e.lineTo(0,n),e.lineTo(-r,0),e.closePath()}},ibe={draw(e,t){const n=To(t),r=-n/2;e.rect(r,r,n,n)}},obe=.8908130915292852,x9=mb(pb/10)/mb(7*pb/10),lbe=mb(v0/10)*x9,cbe=-l9(v0/10)*x9,ube={draw(e,t){const n=To(t*obe),r=lbe*n,a=cbe*n;e.moveTo(0,-n),e.lineTo(r,a);for(let i=1;i<5;++i){const o=v0*i/5,l=l9(o),c=mb(o);e.lineTo(c*n,-l*n),e.lineTo(l*r-c*a,c*r+l*a)}e.closePath()}},$1=To(3),dbe={draw(e,t){const n=-To(t/($1*3));e.moveTo(0,n*2),e.lineTo(-$1*n,-n),e.lineTo($1*n,-n),e.closePath()}},Ai=-.5,Ti=To(3)/2,HN=1/To(12),hbe=(HN/2+1)*3,fbe={draw(e,t){const n=To(t/hbe),r=n/2,a=n*HN,i=r,o=n*HN+n,l=-i,c=o;e.moveTo(r,a),e.lineTo(i,o),e.lineTo(l,c),e.lineTo(Ai*r-Ti*a,Ti*r+Ai*a),e.lineTo(Ai*i-Ti*o,Ti*i+Ai*
vendor: 6,913 bytes, line 788
788o),e.lineTo(Ai*l-Ti*c,Ti*l+Ai*c),e.lineTo(Ai*r+Ti*a,Ai*a-Ti*r),e.lineTo(Ai*i+Ti*o,Ai*o-Ti*i),e.lineTo(Ai*l+Ti*c,Ai*c-Ti*l),e.closePath()}};function mbe(e,t){let n=null,r=XC(a);e=typeof e=="function"?e:Vn(e||QC),t=typeof t=="function"?t:Vn(t===void 0?64:+t);function a(){let i;if(n||(n=i=r()),e.apply(this,arguments).draw(n,+t.apply(this,arguments)),i)return n=null,i+""||null}return a.type=function(i){return arguments.length?(e=typeof i=="function"?i:Vn(i),a):e},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:Vn(+i),a):t},a.context=function(i){return arguments.length?(n=i??null,a):n},a}function xb(){}function gb(e,t,n){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+n)/6)}function g9(e){this._context=e}g9.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:gb(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:gb(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function pbe(e){return new g9(e)}function y9(e){this._context=e}y9.prototype={areaStart:xb,areaEnd:xb,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:gb(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function xbe(e){return new y9(e)}function b9(e){this._context=e}b9.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+e)/6,r=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:gb(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function gbe(e){return new b9(e)}function v9(e){this._context=e}v9.prototype={areaStart:xb,areaEnd:xb,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(e,t){e=+e,t=+t,this._point?this._context.lineTo(e,t):(this._point=1,this._context.moveTo(e,t))}};function ybe(e){return new v9(e)}function eP(e){return e<0?-1:1}function tP(e,t,n){var r=e._x1-e._x0,a=t-e._x1,i=(e._y1-e._y0)/(r||a<0&&-0),o=(n-e._y1)/(a||r<0&&-0),l=(i*a+o*r)/(r+a);return(eP(i)+eP(o))*Math.min(Math.abs(i),Math.abs(o),.5*Math.abs(l))||0}function nP(e,t){var n=e._x1-e._x0;return n?(3*(e._y1-e._y0)/n-t)/2:t}function L1(e,t,n){var r=e._x0,a=e._y0,i=e._x1,o=e._y1,l=(i-r)/3;e._context.bezierCurveTo(r+l,a+l*t,i-l,o-l*n,i,o)}function yb(e){this._context=e}yb.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:L1(this,this._t0,nP(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var n=NaN;if(e=+e,t=+t,!(e===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,L1(this,nP(this,n=tP(this,e,t)),n);break;default:L1(this,this._t0,n=tP(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=n}}};function w9(e){this._context=new _9(e)}(w9.prototype=Object.create(yb.prototype)).point=function(e,t){yb.prototype.point.call(this,t,e)};function _9(e){this._context=e}_9.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,n,r,a,i){this._context.bezierCurveTo(t,e,r,n,i,a)}};function bbe(e){return new yb(e)}function vbe(e){return new w9(e)}function k9(e){this._context=e}k9.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var e=this._x,t=this._y,n=e.length;if(n)if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),n===2)this._context.lineTo(e[1],t[1]);else for(var r=rP(e),a=rP(t),i=0,o=1;o<n;++i,++o)this._context.bezierCurveTo(r[0][i],a[0][i],r[1][i],a[1][i],e[o],t[o]);(this._line||this._line!==0&&n===1)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(e,t){this._x.push(+e),this._y.push(+t)}};function rP(e){var t,n=e.length-1,r,a=new Array(n),i=new Array(n),o=new Array(n);for(a[0]=0,i[0]=2,o[0]=e[0]+2*e[1],t=1;t<n-1;++t)a[t]=1,i[t]=4,o[t]=4*e[t]+2*e[t+1];for(a[n-1]=2,i[n-1]=7,o[n-1]=8*e[n-1]+e[n],t=1;t<n;++t)r=a[t]/i[t-1],i[t]-=r,o[t]-=r*o[t-1];for(a[n-1]=o[n-1]/i[n-1],t=n-2;t>=0;--t)a[t]=(o[t]-a[t+1])/i[t];for(i[n-1]=(e[n]+a[n-1])/2,t=0;t<n-1;++t)i[t]=2*e[t+1]-a[t+1];return[a,i]}function wbe(e){return new k9(e)}function _0(e,t){this._context=e,this._t=t}_0.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&this._point===2&&this._context.lineTo(this._x,this._y),(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;
788default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var n=this._x*(1-this._t)+e*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}break}}this._x=e,this._y=t}};function _be(e){return new _0(e,.5)}function kbe(e){return new _0(e,0)}function jbe(e){return new _0(e,1)}function Nd(e,t){if((o=e.length)>1)for(var n=1,r,a,i=e[t[0]],o,l=i.length;n<o;++n)for(a=i,i=e[t[n]],r=0;r<l;++r)i[r][1]+=i[r][0]=isNaN(a[r][1])?a[r][0]:a[r][1]}function VN(e){for(var t=e.length,n=new Array(t);--t>=0;)n[t]=t;return n}function Nbe(e,t){return e[t]}function Sbe(e){const t=[];return t.key=e,t}function Cbe(){var e=Vn([]),t=VN,n=Nd,r=Nbe;function a(i){var o=Array.from(e.apply(this,arguments),Sbe),l,c=o.length,u=-1,d;for(const h of i)for(l=0,++u;l<c;++l)(o[l][u]=[0,+r(h,o[l].key,u,i)]).data=h;for(l=0,d=JC(t(o));l<c;++l)o[d[l]].index=l;return n(o,d),o}return a.keys=function(i){return arguments.length?(e=typeof i=="function"?i:Vn(Array.from(i)),a):e},a.value=function(i){return arguments.length?(r=typeof i=="function"?i:Vn(+i),a):r},a.order=function(i){return arguments.length?(t=i==null?VN:typeof i=="function"?i:Vn(Array.from(i)),a):t},a.offset=function(i){return arguments.length?(n=i??Nd,a):n},a}function Ebe(e,t){if((r=e.length)>0){for(var n,r,a=0,i=e[0].length,o;a<i;++a){for(o=n=0;n<r;++n)o+=e[n][a][1]||0;if(o)for(n=0;n<r;++n)e[n][a][1]/=o}Nd(e,t)}}function Abe(e,t){if((a=e.length)>0){for(var n=0,r=e[t[0]],a,i=r.length;n<i;++n){for(var o=0,l=0;o<a;++o)l+=e[o][n][1]||0;r[n][1]+=r[n][0]=-l/2}Nd(e,t)}}function Tbe(e,t){if(!(!((o=e.length)>0)||!((i=(a=e[t[0]]).length)>0))){for(var n=0,r=1,a,i,o;r<i;++r){for(var l=0,c=0,u=0;l<o;++l){for(var d=e[t[l]],h=d[r][1]||0,f=d[r-1][1]||0,m=(h-f)/2,x=0;x<l;++x){var g=e[t[x]],y=g[r][1]||0,b=g[r-1][1]||0;m+=y-b}c+=h,u+=m*h}a[r-1][1]+=a[r-1][0]=n,c&&(n-=u/c)}a[r-1][1]+=a[r-1][0]=n,Nd(e,t)}}var Obe=["type","size","sizeType"];function qN(){return qN=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},qN.apply(null,arguments)}function sP(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function aP(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?sP(Object(n),!0).forEach(function(r){Ibe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):sP(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Ibe(e,t,n){return(t=Pbe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Pbe(e){var t=Rbe(e,"string");return typeof t=="symbol"?t:t+""}function Rbe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Dbe(e,t){if(e==null)return{};var n,r,a=Mbe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function Mbe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var j9={symbolCircle:QC,symbolCross:rbe,symbolDiamond:abe,symbolSquare:ibe,symbolStar:ube,symbolTriangle:dbe,symbolWye:fbe},$be=Math.PI/180,Lbe=e=>{var t="symbol".concat(gx(e));return j9[t]||QC},Fbe=(e,t,n)=>{if(t==="area")return e;switch(n){case"cross":return 5*e*e/9;case"diamond":return .5*e*e/Math.sqrt(3);case"square":return e*e;case"star":{var r=18*$be;return 1.25*e*e*(Math.tan(r)-Math.tan(r*2)*Math.tan(r)**2)}case"triangle":return Math.sqrt(3)*e*e/4;case"wye":return(21-10*Math.sqrt(3))*e*e/8;default:return Math.PI*e*e/4}},Bbe=(e,t)=>
788{j9["symbol".concat(gx(e))]=t},N9=e=>{var t=e.type,n=t===void 0?"circle":t,r=e.size,a=r===void 0?64:r,i=e.sizeType,o=i===void 0?"area":i,l=Dbe(e,Obe),c=aP(aP({},l),{},{type:n,size:a,sizeType:o}),u="circle";typeof n=="string"&&(u=n);var d=()=>{var g=Lbe(u),y=mbe().type(g).size(Fbe(a,o,u)),b=y();if(b!==null)return b},h=c.className,f=c.cx,m=c.cy,x=ha(c);return rt(f)&&rt(m)&&rt(a)?p.createElement("path",qN({},x,{className:un("recharts-symbols",h),transform:"translate(".concat(f,", ").concat(m,")"),d:d()})):null};N9.registerSymbol=Bbe;var S9=e=>"radius"in e&&"startAngle"in e&&"endAngle"in e,eE=(e,t)=>{if(!e||typeof e=="function"||typeof e=="boolean")return null;var n=e;if(p.isValidElement(e)&&(n=e.props),typeof n!="object"&&typeof n!="function")return null;var r={};return Object.keys(n).forEach(a=>{KC(a)&&typeof n[a]=="function"&&(r[a]=(i=>n[a](n,i)))}),r},Ube=(e,t,n)=>r=>(e(t,n,r),null),yx=(e,t,n)=>{if(e===null||typeof e!="object"&&typeof e!="function")return null;var r=null;return Object.keys(e).forEach(a=>{var i=e[a];KC(a)&&typeof i=="function"&&(r||(r={}),r[a]=Ube(i,t,n))}),r};function iP(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function zbe(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?iP(Object(n),!0).forEach(function(r){Wbe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):iP(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Wbe(e,t,n){return(t=Kbe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Kbe(e){var t=Hbe(e,"string");return typeof t=="symbol"?t:t+""}function Hbe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function $r(e,t){var n=zbe({},e),r=t,a=Object.keys(t),i=a.reduce((o,l)=>(o[l]===void 0&&r[l]!==void 0&&(o[l]=r[l]),o),n);return i}function bb(){return bb=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},bb.apply(null,arguments)}function oP(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function C9(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?oP(Object(n),!0).forEach(function(r){Vbe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):oP(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Vbe(e,t,n){return(t=qbe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function qbe(e){var t=Gbe(e,"string");return typeof t=="symbol"?t:t+""}function Gbe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Ri=32,Ybe={align:"center",iconSize:14,inactiveColor:"#ccc",layout:"horizontal",verticalAlign:"middle",labelStyle:{}};function Zbe(e){if(typeof e=="object"&&e!==null&&"strokeDasharray"in e)return String(e.strokeDasharray)}function Xbe(e){var t=e.data,n=e.iconType,r=e.inactiveColor,a=Ri/2,i=Ri/6,o=Ri/3,l=t.inactive?r:t.color,c=n??t.type;if(c==="none")return null;if(c==="plainline")return p.createElement("line",{strokeWidth:4,fill:"none",stroke:l,strokeDasharray:Zbe(t.payload),x1:0,y1:a,x2:Ri,y2:a,className:"recharts-legend-icon"});if(c==="line")return p.createElement("path",{strokeWidth:4,fill:"none",stroke:l,d:"M0,".concat(a,"h").concat(o,` 789 A`).concat(i,",").concat(i,",0,1,1,").concat(2*o,",").concat(a,` 790 H`).concat(Ri,"M").concat(2*o,",").concat(a,` 791 A`).concat(i,",").concat(i,",0,1,1,").concat(o,",").concat(a),className:"recharts-legend-icon"});if(c==="rect")return p.createElement("path",{stroke:"none",fill:l,d:"M0,".concat(Ri/8,"h").concat(Ri,"v").concat(Ri*3/4,"h").concat(-Ri,"z"),className:"recharts-legend-icon"});if(p.isValidElement(t.legendIcon)){var u=C9({},t);return delete u.legendIcon,p.cloneElement(t.legendIcon,u)}return p.createElement(N9,{fill:l,cx:a,cy:a,size:Ri,sizeType:"diameter",type:c})}function Jbe(e){var t=e.payload,n=e.iconSize,r=e.layout,a=e.formatter,i=e.inactiveColor,o=e.iconType,l=e.labelStyle,c={x:0,y:0,width:Ri,height:Ri},u={display:r==="horizontal"?"inline-block":"block",marginRight:10,whiteSpace:"nowrap"},d={display:"inline-block",verticalAlign:"middle",marginRight:4};return t.map((h,f)=>{var m,x,g=h.formatter||a,y=un({"recharts-legend-item":!0,["legend-item-".concat(f)]:!0,inactive:h.inactive});if(h.type==="none")return null;var b=typeof l=="object"?C9({},l):{};b.color=h.inactive?i:b.color||h.color,(m=b.whiteSpace)!==null&&m!==void 0||(b.whiteSpace="normal"),(x=b.overflowWrap)!==null&&x!==void 0||(b.overflowWrap="break-word");var v=g?g(h.value,h,f):h.value;
791return p.createElement("li",bb({className:y,style:u,key:"legend-item-".concat(f)},yx(e,h,f)),p.createElement(HC,{width:n,height:n,viewBox:c,style:d,"aria-label":h.value==null?"legend icon":"".concat(h.value," legend icon")},p.createElement(Xbe,{data:h,iconType:o,inactiveColor:i})),p.createElement("span",{className:"recharts-legend-item-text",style:b},v))})}var Qbe=e=>{var t=$r(e,Ybe),n=t.payload,r=t.layout,a=t.align;if(!n||!n.length)return null;var i={padding:0,margin:0,textAlign:r==="horizontal"?a:"left"};return p.createElement("ul",{className:"recharts-default-legend",style:i},p.createElement(Jbe,bb({},t,{payload:n})))},F1={},B1={},lP;function eve(){return lP||(lP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n,r){const a=new Map;for(let i=0;i<n.length;i++){const o=n[i],l=r(o,i,n);a.has(l)||a.set(l,o)}return Array.from(a.values())}e.uniqBy=t})(B1)),B1}var U1={},cP;function tve(){return cP||(cP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n,r){return function(...a){return n.apply(this,a.slice(0,r))}}e.ary=t})(U1)),U1}var z1={},uP;function E9(){return uP||(uP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n){return n}e.identity=t})(z1)),z1}var W1={},K1={},H1={},dP;function nve(){return dP||(dP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n){return Number.isSafeInteger(n)&&n>=0}e.isLength=t})(H1)),H1}var hP;function A9(){return hP||(hP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=nve();function n(r){return r!=null&&typeof r!="function"&&t.isLength(r.length)}e.isArrayLike=n})(K1)),K1}var V1={},fP;function rve(){return fP||(fP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n){return typeof n=="object"&&n!==null}e.isObjectLike=t})(V1)),V1}var mP;function sve(){return mP||(mP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=A9(),n=rve();function r(a){return n.isObjectLike(a)&&t.isArrayLike(a)}e.isArrayLikeObject=r})(W1)),W1}var q1={},G1={},pP;function ave(){return pP||(pP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=GC();function n(r){return function(a){return t.get(a,r)}}e.property=n})(G1)),G1}var Y1={},Z1={},X1={},J1={},xP;function T9(){return xP||(xP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n){return n!==null&&(typeof n=="object"||typeof n=="function")}e.isObject=t})(J1)),J1}var Q1={},gP;function O9(){return gP||(gP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n){return n==null||typeof n!="object"&&typeof n!="function"}e.isPrimitive=t})(Q1)),Q1}var e_={},yP;function tE(){return yP||(yP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n,r){return n===r||Number.isNaN(n)&&Number.isNaN(r)}e.isEqualsSameValueZero=t})(e_)),e_}var bP;function ive(){return bP||(bP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=T9(),n=O9(),r=tE();function a(d,h,f){return typeof f!="function"?a(d,h,()=>{}):i(d,h,function m(x,g,y,b,v,w){const _=f(x,g,y,b,v,w);return _!==void 0?!!_:i(x,g,m,w)},new Map)}function i(d,h,f,m){if(h===d)return!0;switch(typeof h){case"object":return o(d,h,f,m);case"function":return Object.keys(h).length>0?i(d,{...h},f,m):r.isEqualsSameValueZero(d,h);default:return t.isObject(d)?typeof h=="string"?h==="":!0:r.isEqualsSameValueZero(d,h)}}function o(d,h,f,m){if(h==null)return!0;if(Array.isArray(h))return c(d,h,f,m);if(h instanceof Map)return l(d,h,f,m);if(h instanceof Set)return u(d,h,f,m);const x=Object.keys(h);if(d==null||n.isPrimitive(d))return x.length===0;if(x.length===0)return!0;if(m!=null&&m.has(h))return m.get(h)===d;m==null||m.set(h,d);try{for(let g=0;g<x.length;g++){const y=x[g];if(!n.isPrimitive(d)&&!(y in d)||h[y]===void 0&&d[y]!==void 0||h[y]===null&&d[y]!==null||!f(d[y],h[y],y,d,h,m))return!1}return!0}finally{m==null||m.delete(h)}}function l(d,h,f,m){if(h.size===0)return!0;
791if(!(d instanceof Map))return!1;for(const[x,g]of h.entries()){const y=d.get(x);if(f(y,g,x,d,h,m)===!1)return!1}return!0}function c(d,h,f,m){if(h.length===0)return!0;if(!Array.isArray(d))return!1;const x=new Set;for(let g=0;g<h.length;g++){const y=h[g];let b=!1;for(let v=0;v<d.length;v++){if(x.has(v))continue;const w=d[v];let _=!1;if(f(w,y,g,d,h,m)&&(_=!0),_){x.add(v),b=!0;break}}if(!b)return!1}return!0}function u(d,h,f,m){return h.size===0?!0:d instanceof Set?c([...d],[...h],f,m):!1}e.isMatchWith=a,e.isSetMatch=u})(X1)),X1}var vP;function I9(){return vP||(vP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=ive();function n(r,a){return t.isMatchWith(r,a,()=>{})}e.isMatch=n})(Z1)),Z1}var t_={},n_={},r_={},wP;function P9(){return wP||(wP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n){return Object.getOwnPropertySymbols(n).filter(r=>Object.prototype.propertyIsEnumerable.call(n,r))}e.getSymbols=t})(r_)),r_}var s_={},_P;function k0(){return _P||(_P=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n){return n==null?n===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(n)}e.getTag=t})(s_)),s_}var a_={},kP;function nE(){return kP||(kP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t="[object RegExp]",n="[object String]",r="[object Number]",a="[object Boolean]",i="[object Arguments]",o="[object Symbol]",l="[object Date]",c="[object Map]",u="[object Set]",d="[object Array]",h="[object Function]",f="[object ArrayBuffer]",m="[object Object]",x="[object Error]",g="[object DataView]",y="[object Uint8Array]",b="[object Uint8ClampedArray]",v="[object Uint16Array]",w="[object Uint32Array]",_="[object BigUint64Array]",k="[object Int8Array]",j="[object Int16Array]",N="[object Int32Array]",E="[object BigInt64Array]",A="[object Float32Array]",C="[object Float64Array]";e.argumentsTag=i,e.arrayBufferTag=f,e.arrayTag=d,e.bigInt64ArrayTag=E,e.bigUint64ArrayTag=_,e.booleanTag=a,e.dataViewTag=g,e.dateTag=l,e.errorTag=x,e.float32ArrayTag=A,e.float64ArrayTag=C,e.functionTag=h,e.int16ArrayTag=j,e.int32ArrayTag=N,e.int8ArrayTag=k,e.mapTag=c,e.numberTag=r,e.objectTag=m,e.regexpTag=t,e.setTag=u,e.stringTag=n,e.symbolTag=o,e.uint16ArrayTag=v,e.uint32ArrayTag=w,e.uint8ArrayTag=y,e.uint8ClampedArrayTag=b})(a_)),a_}var i_={},o_={},jP;function ove(){return jP||(jP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=typeof globalThis=="object"&&globalThis||typeof window=="object"&&window||typeof self=="object"&&self||typeof gT=="object"&&gT||(function(){return this})()||Function("return this")();e.globalThis=t})(o_)),o_}var NP;function R9(){return NP||(NP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=ove();function n(r){return typeof t.globalThis.Buffer<"u"&&t.globalThis.Buffer.isBuffer(r)}e.isBuffer=n})(i_)),i_}var l_={},SP;function lve(){return SP||(SP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n){return ArrayBuffer.isView(n)&&!(n instanceof DataView)}e.isTypedArray=t})(l_)),l_}var CP;function D9(){return CP||(CP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=P9(),n=k0(),r=nE(),a=R9(),i=O9(),o=lve();function l(h,f){return c(h,void 0,h,new Map,f)}function c(h,f,m,x=new Map,g=void 0){const y=g==null?void 0:g(h,f,m,x);if(y!==void 0)return y;if(i.isPrimitive(h))return h;if(x.has(h))return x.get(h);if(Array.isArray(h)){const b=new Array(h.length);x.set(h,b);for(let v=0;v<h.length;v++)b[v]=c(h[v],v,m,x,g);return Object.hasOwn(h,"index")&&(b.index=h.index),Object.hasOwn(h,"input")&&(b.input=h.input),b}if(h instanceof Date)return new Date(h.getTime());if(h instanceof RegExp){const b=new RegExp(h.source,h.flags);return b.lastIndex=h.lastIndex,b}if(h instanceof Map){const b=new Map;x.set(h,b);for(const[v,w]of h)b.set(v,c(w,v,m,x,g));return b}if(h instanceof Set){const b=new Set;x.set(h,b);for(const v of h)b.add(c(v,void 0,m,x,g));return b}if(a.isBuffer(h))return h.subarray();if(o.isTypedArray(h)){const b=new(Object.getPrototypeOf(h)).constructor(h.length);x.set(h,b);for(let v=0;v<h.length;v++)b[v]=c(h[v],v,m,x,g);return b}if(h instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&h instanceof SharedArrayBuffer)return h.slice(0);
791if(h instanceof DataView){const b=new DataView(h.buffer.slice(0),h.byteOffset,h.byteLength);return x.set(h,b),u(b,h,m,x,g),b}if(typeof File<"u"&&h instanceof File){const b=new File([h],h.name,{type:h.type});return x.set(h,b),u(b,h,m,x,g),b}if(typeof Blob<"u"&&h instanceof Blob){const b=new Blob([h],{type:h.type});return x.set(h,b),u(b,h,m,x,g),b}if(h instanceof Error){const b=structuredClone(h);return x.set(h,b),b.message=h.message,b.name=h.name,b.stack=h.stack,b.cause=h.cause,b.constructor=h.constructor,u(b,h,m,x,g),b}if(h instanceof Boolean){const b=new Boolean(h.valueOf());return x.set(h,b),u(b,h,m,x,g),b}if(h instanceof Number){const b=new Number(h.valueOf());return x.set(h,b),u(b,h,m,x,g),b}if(h instanceof String){const b=new String(h.valueOf());return x.set(h,b),u(b,h,m,x,g),b}if(typeof h=="object"&&d(h)){const b=Object.create(Object.getPrototypeOf(h));return x.set(h,b),u(b,h,m,x,g),b}return h}function u(h,f,m=h,x,g){const y=[...Object.keys(f),...t.getSymbols(f)];for(let b=0;b<y.length;b++){const v=y[b],w=Object.getOwnPropertyDescriptor(h,v);(w==null||w.writable)&&(h[v]=c(f[v],v,m,x,g))}}function d(h){switch(n.getTag(h)){case r.argumentsTag:case r.arrayTag:case r.arrayBufferTag:case r.dataViewTag:case r.booleanTag:case r.dateTag:case r.float32ArrayTag:case r.float64ArrayTag:case r.int8ArrayTag:case r.int16ArrayTag:case r.int32ArrayTag:case r.mapTag:case r.numberTag:case r.objectTag:case r.regexpTag:case r.setTag:case r.stringTag:case r.symbolTag:case r.uint8ArrayTag:case r.uint8ClampedArrayTag:case r.uint16ArrayTag:case r.uint32ArrayTag:return!0;default:return!1}}e.cloneDeepWith=l,e.cloneDeepWithImpl=c,e.copyProperties=u})(n_)),n_}var EP;function cve(){return EP||(EP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=D9();function n(r){return t.cloneDeepWithImpl(r,void 0,r,new Map,void 0)}e.cloneDeep=n})(t_)),t_}var AP;function uve(){return AP||(AP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=I9(),n=cve();function r(a){return a=n.cloneDeep(a),i=>t.isMatch(i,a)}e.matches=r})(Y1)),Y1}var c_={},u_={},d_={},TP;function dve(){return TP||(TP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=D9(),n=k0(),r=nE();function a(i,o){return t.cloneDeepWith(i,(l,c,u,d)=>{const h=o==null?void 0:o(l,c,u,d);if(h!==void 0)return h;if(typeof i=="object"){if(n.getTag(i)===r.objectTag&&typeof i.constructor!="function"){const f={};return d.set(i,f),t.copyProperties(f,i,u,d),f}switch(Object.prototype.toString.call(i)){case r.numberTag:case r.stringTag:case r.booleanTag:{const f=new i.constructor(i==null?void 0:i.valueOf());return t.copyProperties(f,i),f}case r.argumentsTag:{const f={};return t.copyProperties(f,i),f.length=i.length,f[Symbol.iterator]=i[Symbol.iterator],f}default:return}}})}e.cloneDeepWith=a})(d_)),d_}var OP;function hve(){return OP||(OP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=dve();function n(r){return t.cloneDeepWith(r)}e.cloneDeep=n})(u_)),u_}var h_={},f_={},IP;function M9(){return IP||(IP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=/^(?:0|[1-9]\d*)$/;function n(r,a=Number.MAX_SAFE_INTEGER){switch(typeof r){case"number":return Number.isInteger(r)&&r>=0&&r<a;case"symbol":return!1;case"string":return t.test(r)}}e.isIndex=n})(f_)),f_}var m_={},PP;function fve(){return PP||(PP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=k0();function n(r){return r!==null&&typeof r=="object"&&t.getTag(r)==="[object Arguments]"}e.isArguments=n})(m_)),m_}var RP;function mve(){return RP||(RP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=r9(),n=M9(),r=fve(),a=qC();function i(o,l){let c;if(Array.isArray(l)?c=l:typeof l=="string"&&t.isDeepKey(l)&&(o==null?void 0:o[l])==null?c=a.toPath(l):c=[l],c.length===0)return!1;let u=o;for(let d=0;d<c.length;d++){const h=c[d];if((u==null||!Object.hasOwn(u,h))&&!((Array.isArray(u)||r.isArguments(u))&&n.isIndex(h)&&h<u.length))return!1;u=u[h]}return!0}e.has=i})(h_)),h_}var DP;function pve(){return DP||(DP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=I9(),n=VC(),r=hve(),a=GC(),i=mve();function o(l,c){switch(typeof l){case"object":{Object.is(l==null?void 0:l.valueOf(),-0)&&(l="-0");break}case"number":{l=n.toKey(l);break}}return c=r.cloneDeep(c),function(u){const d=a.get(u,l);return d===void 0?i.has(u,l):c===void 0?d===void 0:t.isMatch(d,c)}}e.matchesProperty=o})(c_)),c_}var MP;function xve(){return MP||(MP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=E9(),n=ave(),r=uve(),a=pve();function i(o){if(o==null)return t.identity;switch(typeof o){case"function":return o;case"object":return Array.isArray(o)&&o.length===2?a.matchesProperty(o[0],o[1]):r.matches(o);case"string":case"symbol":case"number":return n.property(o)}}e.iteratee=i})(q1)),q1}var $P;function gve(){return $P||($P=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=eve(),n=tve(),r=E9(),a=sve(),i=xve();function o(l,c=r.identity){return a.isArrayLikeObject(l)?t.uniqBy(Array.from(l),n.ary(i.iteratee(c),1)):[]}e.uniqBy=o})(F1)),F1}var p_,LP;function yve(){return LP||(LP=1,p_=gve().uniqBy),p_}var bve=yve();const FP=hl(bve);function $9(e,t,n){return t===!0?FP(e,n):typeof t=="function"?FP(e,t):e}var x_={exports:{}},g_={},y_={exports:{}},b_={};
791/** 792 * @license React 793 * use-sync-external-store-shim.production.js 794 * 795 * Copyright (c) Meta Platforms, Inc. and affiliates. 796 * 797 * This source code is licensed under the MIT license found in the 798 * LICENSE file in the root directory of this source tree. 799 */var BP;function vve(){if(BP)return b_;BP=1;var e=k2();function t(h,f){return h===f&&(h!==0||1/h===1/f)||h!==h&&f!==f}var n=typeof Object.is=="function"?Object.is:t,r=e.useState,a=e.useEffect,i=e.useLayoutEffect,o=e.useDebugValue;function l(h,f){var m=f(),x=r({inst:{value:m,getSnapshot:f}}),g=x[0].inst,y=x[1];return i(function(){g.value=m,g.getSnapshot=f,c(g)&&y({inst:g})},[h,m,f]),a(function(){return c(g)&&y({inst:g}),h(function(){c(g)&&y({inst:g})})},[h]),o(m),m}function c(h){var f=h.getSnapshot;h=h.value;try{var m=f();return!n(h,m)}catch{return!0}}function u(h,f){return f()}var d=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?u:l;return b_.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:d,b_}var UP;function wve(){return UP||(UP=1,y_.exports=vve()),y_.exports}/** 800 * @license React 801 * use-sync-external-store-shim/with-selector.production.js 802 * 803 * Copyright (c) Meta Platforms, Inc. and affiliates. 804 * 805 * This source code is licensed under the MIT license found in the 806 * LICENSE file in the root directory of this source tree. 807 */var zP;function _ve(){if(zP)return g_;zP=1;var e=k2(),t=wve();function n(u,d){return u===d&&(u!==0||1/u===1/d)||u!==u&&d!==d}var r=typeof Object.is=="function"?Object.is:n,a=t.useSyncExternalStore,i=e.useRef,o=e.useEffect,l=e.useMemo,c=e.useDebugValue;return g_.useSyncExternalStoreWithSelector=function(u,d,h,f,m){var x=i(null);if(x.current===null){var g={hasValue:!1,value:null};x.current=g}else g=x.current;x=l(function(){function b(j){if(!v){if(v=!0,w=j,j=f(j),m!==void 0&&g.hasValue){var N=g.value;if(m(N,j))return _=N}return _=j}if(N=_,r(w,j))return N;var E=f(j);return m!==void 0&&m(N,E)?(w=j,N):(w=j,_=E)}var v=!1,w,_,k=h===void 0?null:h;return[function(){return b(d())},k===null?void 0:function(){return b(k())}]},[d,h,f,m]);var y=a(u,x[0],x[1]);return o(function(){g.hasValue=!0,g.value=y},[y]),c(y),y},g_}var WP;function kve(){return WP||(WP=1,x_.exports=_ve()),x_.exports}var jve=kve(),rE=p.createContext(null),Nve=e=>e,Nn=()=>{var e=p.useContext(rE);return e?e.store.dispatch:Nve},Iy=()=>{},Sve=()=>Iy,Cve=(e,t)=>e===t;function ot(e){var t=p.useContext(rE),n=p.useMemo(()=>t?r=>{if(r!=null)return e(r)}:Iy,[t,e]);return jve.useSyncExternalStoreWithSelector(t?t.subscription.addNestedSub:Sve,t?t.store.getState:Iy,t?t.store.getState:Iy,n,Cve)}function Eve(e,t=`expected a function, instead received ${typeof e}`){if(typeof e!="function")throw new TypeError(t)}function Ave(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(n=>typeof n=="function")){const n=e.map(r=>typeof r=="function"?`function ${r.name||"unnamed"}()`:typeof r).join(", ");throw new TypeError(`${t}[${n}]`)}}var KP=e=>Array.isArray(e)?e:[e];function Tve(e){const t=Array.isArray(e[0])?e[0]:e;return Ave(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}function Ove(e,t){const n=[],{length:r}=e;for(let a=0;a<r;a++)n.push(e[a].apply(null,t));return n}var Ive=class{constructor(e){this.value=e}deref(){return this.value}},Pve=()=>typeof WeakRef>"u"?Ive:WeakRef,L9=Pve(),Rve=0,HP=1;function wg(){return{s:Rve,v:void 0,o:null,p:null}}function Dve(e){return e instanceof L9?e.deref():e}function F9(e,t={}){let n=wg();const{resultEqualityCheck:r}=t;let a,i=0;function o(){let l=n;const{length:c}=arguments;for(let h=0,f=c;h<f;h++){const m=arguments[h];if(typeof m=="function"||typeof m=="object"&&m!==null){let x=l.o;x===null&&(l.o=x=new WeakMap);const g=x.get(m);g===void 0?(l=wg(),x.set(m,l)):l=g}else{let x=l.p;x===null&&(l.p=x=new Map);const g=x.get(m);g===void 0?(l=wg(),x.set(m,l)):l=g}}const u=l;let d;if(l.s===HP)d=l.v;else if(d=e.apply(null,arguments),i++,r){const h=Dve(a);h!=null&&r(h,d)&&(d=h,i!==0&&i--),a=typeof d=="object"&&d!==null||typeof d=="function"?new L9(d):d}return u.s=HP,u.v=d,d}return o.clearCache=()=>{n=wg(),o.resetResultsCount()},o.resultsCount=()=>i,o.resetResultsCount=()=>{i=0},o}function Mve(e,...t){const n=typeof e=="function"?{memoize:e,memoizeOptions:t}:e,r=(...a)=>{let i=0,o=0,l,c={},u=a.pop();typeof u=="object"&&(c=u,u=a.pop()),Eve(u,`createSelector expects an output function after the inputs, but received: [${typeof u}]`);const d={...n,...c},{memoize:h,memoizeOptions:f=[],argsMemoize:m=F9,argsMemoizeOptions:x=[]}=d,g=KP(f),y=KP(x),b=Tve(a),v=h(function(){return i++,u.apply(null,arguments)},...g),w=m(function(){o++;const k=Ove(b,arguments);return l=v.apply(null,k),l},...y);
807return Object.assign(w,{resultFunc:u,memoizedResultFunc:v,dependencies:b,dependencyRecomputations:()=>o,resetDependencyRecomputations:()=>{o=0},lastResult:()=>l,recomputations:()=>i,resetRecomputations:()=>{i=0},memoize:h,argsMemoize:m})};return Object.assign(r,{withTypes:()=>r}),r}var be=Mve(F9),v_={},w_={},__={},VP;function $ve(){return VP||(VP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(r){return typeof r=="symbol"?1:r===null?2:r===void 0?3:r!==r?4:0}const n=(r,a,i)=>{if(r!==a){const o=t(r),l=t(a);if(o===l&&o===0){if(r<a)return i==="desc"?1:-1;if(r>a)return i==="desc"?-1:1}return i==="desc"?l-o:o-l}return 0};e.compareValues=n})(__)),__}var k_={},j_={},qP;function B9(){return qP||(qP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n){return typeof n=="symbol"||n instanceof Symbol}e.isSymbol=t})(j_)),j_}var GP;function Lve(){return GP||(GP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=B9(),n=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,r=/^\w*$/;function a(i,o){return Array.isArray(i)?!1:typeof i=="number"||typeof i=="boolean"||i==null||t.isSymbol(i)?!0:typeof i=="string"&&(r.test(i)||!n.test(i))||o!=null&&Object.hasOwn(o,i)}e.isKey=a})(k_)),k_}var YP;function Fve(){return YP||(YP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=$ve(),n=Lve(),r=qC();function a(i,o,l,c){if(i==null)return[];l=c?void 0:l,Array.isArray(i)||(i=Object.values(i)),Array.isArray(o)||(o=o==null?[null]:[o]),o.length===0&&(o=[null]),Array.isArray(l)||(l=l==null?[]:[l]),l=l.map(m=>String(m));const u=(m,x)=>{let g=m;for(let y=0;y<x.length&&g!=null;++y)g=g[x[y]];return g},d=(m,x)=>x==null||m==null?x:typeof m=="object"&&"key"in m?Object.hasOwn(x,m.key)?x[m.key]:u(x,m.path):typeof m=="function"?m(x):Array.isArray(m)?u(x,m):typeof x=="object"?x[m]:x,h=o.map(m=>(Array.isArray(m)&&m.length===1&&(m=m[0]),m==null||typeof m=="function"||Array.isArray(m)||n.isKey(m)?m:{key:m,path:r.toPath(m)}));return i.map(m=>({original:m,criteria:h.map(x=>d(x,m))})).slice().sort((m,x)=>{for(let g=0;g<h.length;g++){const y=t.compareValues(m.criteria[g],x.criteria[g],l[g]);if(y!==0)return y}return 0}).map(m=>m.original)}e.orderBy=a})(w_)),w_}var N_={},ZP;function Bve(){return ZP||(ZP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n,r=1){const a=[],i=Math.floor(r),o=(l,c)=>{for(let u=0;u<l.length;u++){const d=l[u];Array.isArray(d)&&c<i?o(d,c+1):a.push(d)}};return o(n,0),a}e.flatten=t})(N_)),N_}var S_={},XP;function U9(){return XP||(XP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=M9(),n=A9(),r=T9(),a=tE();function i(o,l,c){return r.isObject(c)&&(typeof l=="number"&&n.isArrayLike(c)&&t.isIndex(l)&&l<c.length||typeof l=="string"&&l in c)?a.isEqualsSameValueZero(c[l],o):!1}e.isIterateeCall=i})(S_)),S_}var JP;function Uve(){return JP||(JP=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=Fve(),n=Bve(),r=U9();function a(i,...o){const l=o.length;return l>1&&r.isIterateeCall(i,o[0],o[1])?o=[]:l>2&&r.isIterateeCall(o[0],o[1],o[2])&&(o=[o[0]]),t.orderBy(i,n.flatten(o),["asc"])}e.sortBy=a})(v_)),v_}var C_,QP;function zve(){return QP||(QP=1,C_=Uve().sortBy),C_}var Wve=zve();const j0=hl(Wve);var z9=e=>e.legend.settings,Kve=e=>e.legend.size,Hve=e=>e.legend.payload,Vve=be([Hve,z9],(e,t)=>{var n=t.itemSorter,r=e.flat(1);return n?j0(r,n):r});function qve(){return ot(Vve)}function Gve(e,t){return Jve(e)||Xve(e,t)||Zve(e,t)||Yve()}function Yve(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 808In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Zve(e,t){if(e){if(typeof e=="string")return eR(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?eR(e,t):void 0}}function eR(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Xve(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}
808finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function Jve(e){if(Array.isArray(e))return e}var _g=1;function tR(e,t){return Math.abs(e.height-t.height)>_g||Math.abs(e.left-t.left)>_g||Math.abs(e.top-t.top)>_g||Math.abs(e.width-t.width)>_g}function nR(e){var t=e.getBoundingClientRect();return{height:t.height,left:t.left,top:t.top,width:t.width}}function W9(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=p.useState({height:0,left:0,top:0,width:0}),n=Gve(t,2),r=n[0],a=n[1],i=p.useRef(null),o=p.useRef(r);o.current=r;var l=p.useCallback(c=>{if(i.current!=null&&(i.current.disconnect(),i.current=null),c!=null){var u=nR(c);if(tR(u,o.current)&&a(u),typeof ResizeObserver<"u"){var d=new ResizeObserver(()=>{var h=nR(c);tR(h,o.current)&&a(h)});d.observe(c),i.current=d}}},[...e]);return p.useEffect(()=>()=>{var c;(c=i.current)===null||c===void 0||c.disconnect()},[]),[r,l]}function Ds(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var Qve=typeof Symbol=="function"&&Symbol.observable||"@@observable",rR=Qve,E_=()=>Math.random().toString(36).substring(7).split("").join("."),e0e={INIT:`@@redux/INIT${E_()}`,REPLACE:`@@redux/REPLACE${E_()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${E_()}`},vb=e0e;function sE(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function K9(e,t,n){if(typeof e!="function")throw new Error(Ds(2));if(typeof t=="function"&&typeof n=="function"||typeof n=="function"&&typeof arguments[3]=="function")throw new Error(Ds(0));if(typeof t=="function"&&typeof n>"u"&&(n=t,t=void 0),typeof n<"u"){if(typeof n!="function")throw new Error(Ds(1));return n(K9)(e,t)}let r=e,a=t,i=new Map,o=i,l=0,c=!1;function u(){o===i&&(o=new Map,i.forEach((y,b)=>{o.set(b,y)}))}function d(){if(c)throw new Error(Ds(3));return a}function h(y){if(typeof y!="function")throw new Error(Ds(4));if(c)throw new Error(Ds(5));let b=!0;u();const v=l++;return o.set(v,y),function(){if(b){if(c)throw new Error(Ds(6));b=!1,u(),o.delete(v),i=null}}}function f(y){if(!sE(y))throw new Error(Ds(7));if(typeof y.type>"u")throw new Error(Ds(8));if(typeof y.type!="string")throw new Error(Ds(17));if(c)throw new Error(Ds(9));try{c=!0,a=r(a,y)}finally{c=!1}return(i=o).forEach(v=>{v()}),y}function m(y){if(typeof y!="function")throw new Error(Ds(10));r=y,f({type:vb.REPLACE})}function x(){const y=h;return{subscribe(b){if(typeof b!="object"||b===null)throw new Error(Ds(11));function v(){const _=b;_.next&&_.next(d())}return v(),{unsubscribe:y(v)}},[rR](){return this}}}return f({type:vb.INIT}),{dispatch:f,subscribe:h,getState:d,replaceReducer:m,[rR]:x}}function t0e(e){Object.keys(e).forEach(t=>{const n=e[t];if(typeof n(void 0,{type:vb.INIT})>"u")throw new Error(Ds(12));if(typeof n(void 0,{type:vb.PROBE_UNKNOWN_ACTION()})>"u")throw new Error(Ds(13))})}function H9(e){const t=Object.keys(e),n={};for(let i=0;i<t.length;i++){const o=t[i];typeof e[o]=="function"&&(n[o]=e[o])}const r=Object.keys(n);let a;try{t0e(n)}catch(i){a=i}return function(o={},l){if(a)throw a;let c=!1;const u={};for(let d=0;d<r.length;d++){const h=r[d],f=n[h],m=o[h],x=f(m,l);if(typeof x>"u")throw l&&l.type,new Error(Ds(14));u[h]=x,c=c||x!==m}return c=c||r.length!==Object.keys(o).length,c?u:o}}function wb(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,n)=>(...r)=>t(n(...r)))}function n0e(...e){return t=>(n,r)=>{const a=t(n,r);let i=()=>{throw new Error(Ds(15))};const o={getState:a.getState,dispatch:(c,...u)=>i(c,...u)},l=e.map(c=>c(o));return i=wb(...l)(a.dispatch),{...a,dispatch:i}}}function V9(e){return sE(e)&&"type"in e&&typeof e.type=="string"}var q9=Symbol.for("immer-nothing"),sR=Symbol.for("immer-draftable"),fa=Symbol.for("immer-state");function po(e,...t){throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var xi=Object,Yh=xi.getPrototypeOf,_b="constructor",N0="prototype",GN="configurable",kb="enumerable",Py="writable",Tp="value",ic=e=>!!e&&!!e[fa];function Gi(e){var t;return e?G9(e)||C0(e)||!!e[sR]||!!((t=e[_b])!=null&&t[sR])||E0(e)||A0(e):!1}var r0e=xi[N0][_b].toString(),aR=new WeakMap;function G9(e){if(!e||!aE(e))return!1;const t=Yh(e);if(t===null||t===xi[N0])return!0;const n=xi.hasOwnProperty.call(t,_b)&&t[_b];if(n===Object)return!0;
808if(!bh(n))return!1;let r=aR.get(n);return r===void 0&&(r=Function.toString.call(n),aR.set(n,r)),r===r0e}function S0(e,t,n=!0){bx(e)===0?(n?Reflect.ownKeys(e):xi.keys(e)).forEach(a=>{t(a,e[a],e)}):e.forEach((r,a)=>t(a,r,e))}function bx(e){const t=e[fa];return t?t.type_:C0(e)?1:E0(e)?2:A0(e)?3:0}var A_=(e,t,n=bx(e))=>n===2?e.has(t):xi[N0].hasOwnProperty.call(e,t),YN=(e,t,n=bx(e))=>n===2?e.get(t):e[t],jb=(e,t,n,r=bx(e))=>{r===2?e.set(t,n):r===3?e.add(n):e[t]=n};function s0e(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}var C0=Array.isArray,E0=e=>e instanceof Map,A0=e=>e instanceof Set,aE=e=>typeof e=="object",bh=e=>typeof e=="function",T_=e=>typeof e=="boolean";function a0e(e){const t=+e;return Number.isInteger(t)&&String(t)===e}var Dl=e=>e.copy_||e.base_,iE=e=>e.modified_?e.copy_:e.base_;function ZN(e,t){if(E0(e))return new Map(e);if(A0(e))return new Set(e);if(C0(e))return Array[N0].slice.call(e);const n=G9(e);if(t===!0||t==="class_only"&&!n){const r=xi.getOwnPropertyDescriptors(e);delete r[fa];let a=Reflect.ownKeys(r);for(let i=0;i<a.length;i++){const o=a[i],l=r[o];l[Py]===!1&&(l[Py]=!0,l[GN]=!0),(l.get||l.set)&&(r[o]={[GN]:!0,[Py]:!0,[kb]:l[kb],[Tp]:e[o]})}return xi.create(Yh(e),r)}else{const r=Yh(e);if(r!==null&&n)return{...e};const a=xi.create(r);return xi.assign(a,e)}}function oE(e,t=!1){return T0(e)||ic(e)||!Gi(e)||(bx(e)>1&&xi.defineProperties(e,{set:kg,add:kg,clear:kg,delete:kg}),xi.freeze(e),t&&S0(e,(n,r)=>{oE(r,!0)},!1)),e}function i0e(){po(2)}var kg={[Tp]:i0e};function T0(e){return e===null||!aE(e)?!0:xi.isFrozen(e)}var Nb="MapSet",XN="Patches",iR="ArrayMethods",Y9={};function Sd(e){const t=Y9[e];return t||po(0,e),t}var oR=e=>!!Y9[e],Op,Z9=()=>Op,o0e=(e,t)=>({drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:oR(Nb)?Sd(Nb):void 0,arrayMethodsPlugin_:oR(iR)?Sd(iR):void 0});function lR(e,t){t&&(e.patchPlugin_=Sd(XN),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function JN(e){QN(e),e.drafts_.forEach(l0e),e.drafts_=null}function QN(e){e===Op&&(Op=e.parent_)}var cR=e=>Op=o0e(Op,e);function l0e(e){const t=e[fa];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function uR(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];if(e!==void 0&&e!==n){n[fa].modified_&&(JN(t),po(4)),Gi(e)&&(e=dR(t,e));const{patchPlugin_:a}=t;a&&a.generateReplacementPatches_(n[fa].base_,e,t)}else e=dR(t,n);return c0e(t,e,!0),JN(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==q9?e:void 0}function dR(e,t){if(T0(t))return t;const n=t[fa];if(!n)return Sb(t,e.handledSet_,e);if(!O0(n,e))return t;if(!n.modified_)return n.base_;if(!n.finalized_){const{callbacks_:r}=n;if(r)for(;r.length>0;)r.pop()(e);Q9(n,e)}return n.copy_}function c0e(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&oE(t,n)}function X9(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var O0=(e,t)=>e.scope_===t,u0e=[];function J9(e,t,n,r){const a=Dl(e),i=e.type_;if(r!==void 0&&YN(a,r,i)===t){jb(a,r,n,i);return}if(!e.draftLocations_){const l=e.draftLocations_=new Map;S0(a,(c,u)=>{if(ic(u)){const d=l.get(u)||[];d.push(c),l.set(u,d)}})}const o=e.draftLocations_.get(t)??u0e;for(const l of o)jb(a,l,n,i)}function d0e(e,t,n){e.callbacks_.push(function(a){var l;const i=t;if(!i||!O0(i,a))return;(l=a.mapSetPlugin_)==null||l.fixSetContents(i);const o=iE(i);J9(e,i.draft_??i,o,n),Q9(i,a)})}function Q9(e,t){var r;if(e.modified_&&!e.finalized_&&(e.type_===3||e.type_===1&&e.allIndicesReassigned_||(((r=e.assigned_)==null?void 0:r.size)??0)>0)){const{patchPlugin_:a}=t;if(a){const i=a.getPath(e);i&&a.generatePatches_(e,i,t)}X9(e)}}function h0e(e,t,n){const{scope_:r}=e;if(ic(n)){const a=n[fa];O0(a,r)&&a.callbacks_.push(function(){Ry(e);const o=iE(a);J9(e,n,o,t)})}else Gi(n)&&e.callbacks_.push(function(){const i=Dl(e);e.type_===3?i.has(n)&&Sb(n,r.handledSet_,r):YN(i,t,e.type_)===n&&r.drafts_.length>1&&(e.assigned_.get(t)??!1)===!0&&e.copy_&&Sb(YN(e.copy_,t,e.type_),r.handledSet_,r)})}function Sb(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||ic(e)||t.has(e)||!Gi(e)||T0(e)||(t.add(e),S0(e,(r,a)=>{if(ic(a)){const i=a[fa];if(O0(i,n)){const o=iE(i);jb(e,r,o,e.type_),X9(i)}}else Gi(a)&&Sb(a,t,n)})),e}function f0e(e,t){const n=C0(e),r={type_:n?1:0,scope_:t?t.scope_:Z9(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let a=r,i=Cb;n&&(a=[r],i=Ip);const{revoke:o,proxy:l}=Proxy.revocable(a,i);return r.draft_=l,r.revoke_=o,[l,r]}var Cb={get(e,t){if(t===fa)return e;let n=e.scope_.arrayMethodsPlugin_;const r=e.type_===1&&typeof t=="string";if(r&&n!=null&&n.isArrayOperationMethod(t))return n.createMethodInterceptor(e,t);const a=Dl(e);if(!A_(a,t,e.type_))return p0e(e,a,t);const i=a[t];if(e.finalized_||!Gi(i)||r&&e.operationMethod&&(n!=null&&n.isMutatingArrayMethod(e.operationMethod))&&a0e(t))return i;if(i===O_(e.base_,t)||m0e(e,t,i)){Ry(e);const o=e.type_===1?+t:t,l=tS(e.scope_,i,e,o);return e.copy_[o]=l}return i},has(e,t){return t in Dl(e)},ownKeys(e){return Reflect.ownKeys(Dl(e))},set(e,t,n){const r=eU(Dl(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const a=O_(Dl(e),t),i=a==null?void 0:a[fa];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_.set(t,!1),!0;if(s0e(n,a)&&(n!==void 0||A_(e.base_,t,e.type_)))return!0;Ry(e),eS(e)}return e.copy_[t]===n&&(n!==void 0||A_(e.copy_,t,e.type_))||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_.set(t,!0),h0e(e,t,n)),!0},deleteProperty(e,t){return Ry(e),O_(e.base_,t)!==void 0||t in e.base_?(e.assigned_.set(t,!1),eS(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Dl(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{[Py]:!0,[GN]:e.type_!==1||t!=="length",[kb]:r[kb],[Tp]:n[t]}},defineProperty(){po(11)},getPrototypeOf(e){return Yh(e.base_)},setPrototypeOf(){po(12)}},Ip={};for(let e in Cb){let t=Cb[e];Ip[e]=function(){const n=arguments;return n[0]=n[0][0],t.apply(this,n)}}Ip.deleteProperty=function(e,t){return Ip.set.call(this,e,t,void 0)};
808Ip.set=function(e,t,n){return Cb.set.call(this,e[0],t,n,e[0])};function O_(e,t){const n=e[fa];return(n?Dl(n):e)[t]}function m0e(e,t,n){var r;return e.type_!==1||!e.allIndicesReassigned_||(r=e.assigned_)!=null&&r.get(t)||!Gi(n)||n[fa]?!1:e.baseRefs_.has(n)}function p0e(e,t,n){var a;const r=eU(t,n);return r?Tp in r?r[Tp]:(a=r.get)==null?void 0:a.call(e.draft_):void 0}function eU(e,t){if(!(t in e))return;let n=Yh(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=Yh(n)}}function eS(e){e.modified_||(e.modified_=!0,e.parent_&&eS(e.parent_))}function Ry(e){e.copy_||(e.assigned_=new Map,e.copy_=ZN(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var x0e=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(t,n,r)=>{if(bh(t)&&!bh(n)){const i=n;n=t;const o=this;return function(c=i,...u){return o.produce(c,d=>n.call(this,d,...u))}}bh(n)||po(6),r!==void 0&&!bh(r)&&po(7);let a;if(Gi(t)){const i=cR(this),o=tS(i,t,void 0);let l=!0;try{a=n(o),l=!1}finally{l?JN(i):QN(i)}return lR(i,r),uR(a,i)}else if(!t||!aE(t)){if(a=n(t),a===void 0&&(a=t),a===q9&&(a=void 0),this.autoFreeze_&&oE(a,!0),r){const i=[],o=[];Sd(XN).generateReplacementPatches_(t,a,{patches_:i,inversePatches_:o}),r(i,o)}return a}else po(1,t)},this.produceWithPatches=(t,n)=>{if(bh(t))return(o,...l)=>this.produceWithPatches(o,c=>t(c,...l));let r,a;return[this.produce(t,n,(o,l)=>{r=o,a=l}),r,a]},T_(e==null?void 0:e.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),T_(e==null?void 0:e.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),T_(e==null?void 0:e.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){Gi(e)||po(8),ic(e)&&(e=zi(e));const t=cR(this),n=tS(t,e,void 0);return n[fa].isManual_=!0,QN(t),n}finishDraft(e,t){const n=e&&e[fa];(!n||!n.isManual_)&&po(9);const{scope_:r}=n;return lR(r,t),uR(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const a=t[n];if(a.path.length===0&&a.op==="replace"){e=a.value;break}}n>-1&&(t=t.slice(n+1));const r=Sd(XN).applyPatches_;return ic(e)?r(e,t):this.produce(e,a=>r(a,t))}};function tS(e,t,n,r){const[a,i]=E0(t)?Sd(Nb).proxyMap_(t,n):A0(t)?Sd(Nb).proxySet_(t,n):f0e(t,n);return((n==null?void 0:n.scope_)??Z9()).drafts_.push(a),i.callbacks_=(n==null?void 0:n.callbacks_)??[],i.key_=r,n&&r!==void 0?d0e(n,i,r):i.callbacks_.push(function(c){var d;(d=c.mapSetPlugin_)==null||d.fixSetContents(i);const{patchPlugin_:u}=c;i.modified_&&u&&u.generatePatches_(i,[],c)}),a}function zi(e){return ic(e)||po(10,e),tU(e)}function tU(e){if(!Gi(e)||T0(e))return e;const t=e[fa];let n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=ZN(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=ZN(e,!0);return S0(n,(a,i)=>{jb(n,a,tU(i))},r),t&&(t.finalized_=!1),n}var g0e=new x0e,nU=g0e.produce,pn=e=>e;function rU(e){return({dispatch:n,getState:r})=>a=>i=>typeof i=="function"?i(n,r,e):a(i)}var y0e=rU(),b0e=rU,v0e=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(arguments.length!==0)return typeof arguments[0]=="object"?wb:wb.apply(null,arguments)};function wi(e,t){function n(...r){if(t){let a=t(...r);if(!a)throw new Error(yi(0));return{type:e,payload:a.payload,..."meta"in a&&{meta:a.meta},..."error"in a&&{error:a.error}}}return{type:e,payload:r[0]}}return n.toString=()=>`${e}`,n.type=e,n.match=r=>V9(r)&&r.type===e,n}var sU=class Lm extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,Lm.prototype)}static get[Symbol.species](){return Lm}concat(...t){return super.concat.apply(this,t)}prepend(...t){return t.length===1&&Array.isArray(t[0])?new Lm(...t[0].concat(this)):new Lm(...t.concat(this))}};function hR(e){return Gi(e)?nU(e,()=>{}):e}function jg(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}function w0e(e){return typeof e=="boolean"}var _0e=()=>function(t){const{thunk:n=!0,immutableCheck:r=!0,serializableCheck:a=!0,actionCreatorCheck:i=!0}=t??{};let o=new sU;return n&&(w0e(n)?o.push(y0e):o.push(b0e(n.extraArgument))),o},aU="RTK_autoBatch",er=()=>e=>({payload:e,meta:{[aU]:!0}}),fR=e=>t=>{setTimeout(t,e)},k0e=(e,t)=>n=>{let r=!1;const a=()=>{r||(r=!0,cancelAnimationFrame(i),clearTimeout(o),n())},i=e(a),o=setTimeout(a,t)},iU=(e={type:"raf"})=>t=>(...n)=>{const r=t(...n);let a=!0,i=!1,o=!1;const l=new Set,c=e.type==="tick"?queueMicrotask:e.type==="raf"?typeof window<"u"&&window.requestAnimationFrame?k0e(window.requestAnimationFrame,100):fR(10):e.type==="callback"?e.queueNotification:fR(e.timeout),u=()=>{o=!1,i&&(i=!1,l.forEach(d=>d()))};return Object.assign({},r,{subscribe(d){const h=()=>a&&d(),f=r.subscribe(h);return l.add(d),()=>{f(),l.delete(d)}},dispatch(d){var h;try{return a=!((h=d==null?void 0:d.meta)!=null&&h[aU]),i=!a,i&&(o||(o=!0,c(u))),r.dispatch(d)}finally{a=!0}}})},j0e=e=>function(n){const{autoBatch:r=!0}=n??{};let a=new sU(e);return r&&a.push(iU(typeof r=="object"?r:void 0)),a};function N0e(e){const t=_0e(),{reducer:n=void 0,middleware:r,devTools:a=!0,preloadedState:i=void 0,enhancers:o=void 0}=e||{};let l;if(typeof n=="function")l=n;else if(sE(n))l=H9(n);else throw new Error(yi(1));let c;typeof r=="function"?c=r(t):c=t();let u=wb;a&&(u=v0e({trace:!1,...typeof a=="object"&&a}));const d=n0e(...c),h=j0e(d);
808let f=typeof o=="function"?o(h):h();const m=u(...f);return K9(l,i,m)}function oU(e){const t={},n=[];let r;const a={addCase(i,o){const l=typeof i=="string"?i:i.type;if(!l)throw new Error(yi(28));if(l in t)throw new Error(yi(29));return t[l]=o,a},addAsyncThunk(i,o){return o.pending&&(t[i.pending.type]=o.pending),o.rejected&&(t[i.rejected.type]=o.rejected),o.fulfilled&&(t[i.fulfilled.type]=o.fulfilled),o.settled&&n.push({matcher:i.settled,reducer:o.settled}),a},addMatcher(i,o){return n.push({matcher:i,reducer:o}),a},addDefaultCase(i){return r=i,a}};return e(a),[t,n,r]}function S0e(e){return typeof e=="function"}function C0e(e,t){let[n,r,a]=oU(t),i;if(S0e(e))i=()=>hR(e());else{const l=hR(e);i=()=>l}function o(l=i(),c){let u=[n[c.type],...r.filter(({matcher:d})=>d(c)).map(({reducer:d})=>d)];return u.filter(d=>!!d).length===0&&(u=[a]),u.reduce((d,h)=>{if(h)if(ic(d)){const m=h(d,c);return m===void 0?d:m}else{if(Gi(d))return nU(d,f=>h(f,c));{const f=h(d,c);if(f===void 0){if(d===null)return d;throw Error("A case reducer on a non-draftable value must not return undefined")}return f}}return d},l)}return o.getInitialState=i,o}var E0e="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW",A0e=(e=21)=>{let t="",n=e;for(;n--;)t+=E0e[Math.random()*64|0];return t},T0e=Symbol.for("rtk-slice-createasyncthunk");function O0e(e,t){return`${e}/${t}`}function I0e({creators:e}={}){var n;const t=(n=e==null?void 0:e.asyncThunk)==null?void 0:n[T0e];return function(a){const{name:i,reducerPath:o=i}=a;if(!i)throw new Error(yi(11));const l=(typeof a.reducers=="function"?a.reducers(R0e()):a.reducers)||{},c=Object.keys(l),u={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},d={addCase(_,k){const j=typeof _=="string"?_:_.type;if(!j)throw new Error(yi(12));if(j in u.sliceCaseReducersByType)throw new Error(yi(13));return u.sliceCaseReducersByType[j]=k,d},addMatcher(_,k){return u.sliceMatchers.push({matcher:_,reducer:k}),d},exposeAction(_,k){return u.actionCreators[_]=k,d},exposeCaseReducer(_,k){return u.sliceCaseReducersByName[_]=k,d}};c.forEach(_=>{const k=l[_],j={reducerName:_,type:O0e(i,_),createNotation:typeof a.reducers=="function"};M0e(k)?L0e(j,k,d,t):D0e(j,k,d)});function h(){const[_={},k=[],j=void 0]=typeof a.extraReducers=="function"?oU(a.extraReducers):[a.extraReducers],N={..._,...u.sliceCaseReducersByType};return C0e(a.initialState,E=>{for(let A in N)E.addCase(A,N[A]);for(let A of u.sliceMatchers)E.addMatcher(A.matcher,A.reducer);for(let A of k)E.addMatcher(A.matcher,A.reducer);j&&E.addDefaultCase(j)})}const f=_=>_,m=new Map,x=new WeakMap;let g;function y(_,k){return g||(g=h()),g(_,k)}function b(){return g||(g=h()),g.getInitialState()}function v(_,k=!1){function j(E){let A=E[_];return typeof A>"u"&&k&&(A=jg(x,j,b)),A}function N(E=f){const A=jg(m,k,()=>new WeakMap);return jg(A,E,()=>{const C={};for(const[T,S]of Object.entries(a.selectors??{}))C[T]=P0e(S,E,()=>jg(x,E,b),k);return C})}return{reducerPath:_,getSelectors:N,get selectors(){return N(j)},selectSlice:j}}const w={name:i,reducer:y,actions:u.actionCreators,caseReducers:u.sliceCaseReducersByName,getInitialState:b,...v(o),injectInto(_,{reducerPath:k,...j}={}){const N=k??o;return _.inject({reducerPath:N,reducer:y},j),{...w,...v(N,!0)}}};return w}}function P0e(e,t,n,r){function a(i,...o){let l=t(i);return typeof l>"u"&&r&&(l=n()),e(l,...o)}return a.unwrapped=e,a}var ga=I0e();function R0e(){function e(t,n){return{_reducerDefinitionType:"asyncThunk",payloadCreator:t,...n}}return e.withTypes=()=>e,{reducer(t){return Object.assign({[t.name](...n){return t(...n)}}[t.name],{_reducerDefinitionType:"reducer"})},preparedReducer(t,n){return{_reducerDefinitionType:"reducerWithPrepare",prepare:t,reducer:n}},asyncThunk:e}}function D0e({type:e,reducerName:t,createNotation:n},r,a){let i,o;if("reducer"in r){if(n&&!$0e(r))throw new Error(yi(17));i=r.reducer,o=r.prepare}else i=r;a.addCase(e,i).exposeCaseReducer(t,i).exposeAction(t,o?wi(e,o):wi(e))}function M0e(e){return e._reducerDefinitionType==="asyncThunk"}function $0e(e){return e._reducerDefinitionType==="reducerWithPrepare"}function L0e({type:e,reducerName:t},n,r,a){if(!a)throw new Error(yi(18));const{payloadCreator:i,fulfilled:o,pending:l,rejected:c,settled:u,options:d}=n,h=a(e,i,d);r.exposeAction(t,h),o&&r.addCase(h.fulfilled,o),l&&r.addCase(h.pending,l),c&&r.addCase(h.rejected,c),u&&r.addMatcher(h.settled,u),r.exposeCaseReducer(t,{fulfilled:o||Ng,pending:l||Ng,rejected:c||Ng,settled:u||Ng})}function Ng(){}var F0e="task",lU="listener",cU="completed",lE="cancelled",B0e=`task-${lE}`,U0e=`task-${cU}`,nS=`${lU}-${lE}`,z0e=`${lU}-${cU}`,I0=class{constructor(e){_c(this,"code");_c(this,"name","TaskAbortError");_c(this,"message");
808this.code=e,this.message=`${F0e} ${lE} (reason: ${e})`}},cE=(e,t)=>{if(typeof e!="function")throw new TypeError(yi(32))},Eb=()=>{},uU=(e,t=Eb)=>(e.catch(t),e),dU=(e,t)=>(e.addEventListener("abort",t,{once:!0}),()=>e.removeEventListener("abort",t)),dd=e=>{if(e.aborted)throw new I0(e.reason)};function hU(e,t){let n=Eb;return new Promise((r,a)=>{const i=()=>a(new I0(e.reason));if(e.aborted){i();return}n=dU(e,i),t.finally(()=>n()).then(r,a)}).finally(()=>{n=Eb})}var W0e=async(e,t)=>{try{return await Promise.resolve(),{status:"ok",value:await e()}}catch(n){return{status:n instanceof I0?"cancelled":"rejected",error:n}}finally{t==null||t()}},Ab=e=>t=>uU(hU(e,t).then(n=>(dd(e),n))),fU=e=>{const t=Ab(e);return n=>t(new Promise(r=>setTimeout(r,n)))},{assign:$h}=Object,mR={},P0="listenerMiddleware",K0e=(e,t)=>{const n=r=>dU(e,()=>r.abort(e.reason));return(r,a)=>{cE(r);const i=new AbortController;n(i);const o=W0e(async()=>{dd(e),dd(i.signal);const l=await r({pause:Ab(i.signal),delay:fU(i.signal),signal:i.signal});return dd(i.signal),l},()=>i.abort(U0e));return a!=null&&a.autoJoin&&t.push(o.catch(Eb)),{result:Ab(e)(o),cancel(){i.abort(B0e)}}}},H0e=(e,t)=>{const n=async(r,a)=>{dd(t);let i=()=>{};const l=[new Promise((c,u)=>{let d=e({predicate:r,effect:(h,f)=>{f.unsubscribe(),c([h,f.getState(),f.getOriginalState()])}});i=()=>{d(),u()}})];a!=null&&l.push(new Promise(c=>setTimeout(c,a,null)));try{const c=await hU(t,Promise.race(l));return dd(t),c}finally{i()}};return((r,a)=>uU(n(r,a)))},mU=e=>{let{type:t,actionCreator:n,matcher:r,predicate:a,effect:i}=e;if(t)a=wi(t).match;else if(n)t=n.type,a=n.match;else if(r)a=r;else if(!a)throw new Error(yi(21));return cE(i),{predicate:a,type:t,effect:i}},pU=$h(e=>{const{type:t,predicate:n,effect:r}=mU(e);return{id:A0e(),effect:r,type:t,predicate:n,pending:new Set,unsubscribe:()=>{throw new Error(yi(22))}}},{withTypes:()=>pU}),pR=(e,t)=>{const{type:n,effect:r,predicate:a}=mU(t);return Array.from(e.values()).find(i=>(typeof n=="string"?i.type===n:i.predicate===a)&&i.effect===r)},rS=e=>{e.pending.forEach(t=>{t.abort(nS)})},V0e=(e,t)=>()=>{for(const n of t.keys())rS(n);e.clear()},xR=(e,t,n)=>{try{e(t,n)}catch(r){setTimeout(()=>{throw r},0)}},xU=$h(wi(`${P0}/add`),{withTypes:()=>xU}),q0e=wi(`${P0}/removeAll`),gU=$h(wi(`${P0}/remove`),{withTypes:()=>gU}),G0e=(...e)=>{console.error(`${P0}/error`,...e)},vx=(e={})=>{const t=new Map,n=new Map,r=m=>{const x=n.get(m)??0;n.set(m,x+1)},a=m=>{const x=n.get(m)??1;x===1?n.delete(m):n.set(m,x-1)},{extra:i,onError:o=G0e}=e;cE(o);const l=m=>(m.unsubscribe=()=>t.delete(m.id),t.set(m.id,m),x=>{m.unsubscribe(),x!=null&&x.cancelActive&&rS(m)}),c=(m=>{const x=pR(t,m)??pU(m);return l(x)});$h(c,{withTypes:()=>c});const u=m=>{const x=pR(t,m);return x&&(x.unsubscribe(),m.cancelActive&&rS(x)),!!x};$h(u,{withTypes:()=>u});const d=async(m,x,g,y)=>{const b=new AbortController,v=H0e(c,b.signal),w=[];try{m.pending.add(b),r(m),await Promise.resolve(m.effect(x,$h({},g,{getOriginalState:y,condition:(_,k)=>v(_,k).then(Boolean),take:v,delay:fU(b.signal),pause:Ab(b.signal),extra:i,signal:b.signal,fork:K0e(b.signal,w),unsubscribe:m.unsubscribe,subscribe:()=>{t.set(m.id,m)},cancelActiveListeners:()=>{m.pending.forEach((_,k,j)=>{_!==b&&(_.abort(nS),j.delete(_))})},cancel:()=>{b.abort(nS),m.pending.delete(b)},throwIfCancelled:()=>{dd(b.signal)}})))}catch(_){_ instanceof I0||xR(o,_,{raisedBy:"effect"})}finally{await Promise.all(w),b.abort(z0e),a(m),m.pending.delete(b)}},h=V0e(t,n);return{middleware:m=>x=>g=>{if(!V9(g))return x(g);if(xU.match(g))return c(g.payload);if(q0e.match(g)){h();return}if(gU.match(g))return u(g.payload);let y=m.getState();const b=()=>{if(y===mR)throw new Error(yi(23));return y};let v;try{if(v=x(g),t.size>0){const w=m.getState(),_=Array.from(t.values());for(const k of _){let j=!1;try{j=k.predicate(g,w,y)}catch(N){j=!1,xR(o,N,{raisedBy:"predicate"})}j&&d(k,g,m,b)}}}finally{y=mR}return v},startListening:c,stopListening:u,clearListeners:h}};function yi(e){return`Minified Redux Toolkit error #${e}; visit https://redux-toolkit.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var Y0e={layoutType:"horizontal",width:0,height:0,margin:{top:5,right:5,bottom:5,left:5},scale:1},yU=ga({name:"chartLayout",initialState:Y0e,reducers:{setLayout(e,t){e.layoutType=t.payload},setChartSize(e,t){e.width=t.payload.width,e.height=t.payload.height},setMargin(e,t){var n,r,a,i;e.margin.top=(n=t.payload.top)!==null&&n!==void 0?n:0,e.margin.right=(r=t.payload.right)!==null&&r!==void 0?r:0,e.margin.bottom=(a=t.payload.bottom)!==null&&a!==void 0?a:0,e.margin.left
808=(i=t.payload.left)!==null&&i!==void 0?i:0},setScale(e,t){e.scale=t.payload}}}),R0=yU.actions,Z0e=R0.setMargin,X0e=R0.setLayout,J0e=R0.setChartSize,Q0e=R0.setScale,ewe=yU.reducer;function bU(e,t,n){return Array.isArray(e)&&e&&t+n!==0?e.slice(t,n+1):e}function Mt(e){return Number.isFinite(e)}function ol(e){return typeof e=="number"&&e>0&&Number.isFinite(e)}function gR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Ga(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?gR(Object(n),!0).forEach(function(r){twe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):gR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function twe(e,t,n){return(t=nwe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function nwe(e){var t=rwe(e,"string");return typeof t=="symbol"?t:t+""}function rwe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function hn(e,t,n){return sr(e)||sr(t)?n:aa(t)?kd(e,t,n):typeof t=="function"?t(e):n}var swe=(e,t,n)=>{if(t&&n){var r=n.width,a=n.height,i=t.align,o=t.verticalAlign,l=t.layout,c=t.position,u=t.offset,d=u===void 0?0:u;if(c!=null){if(ZC(c)){if(c==="top"&&rt(e.top))return Ga(Ga({},e),{},{top:e.top+(a||0)+d});if(c==="bottom"&&rt(e.bottom))return Ga(Ga({},e),{},{bottom:e.bottom+(a||0)+d});if(c==="left"&&rt(e.left))return Ga(Ga({},e),{},{left:e.left+(r||0)+d});if(c==="right"&&rt(e.right))return Ga(Ga({},e),{},{right:e.right+(r||0)+d})}return e}if((l==="vertical"||l==="horizontal"&&o==="middle")&&i!=="center"&&rt(e[i]))return Ga(Ga({},e),{},{[i]:e[i]+(r||0)});if((l==="horizontal"||l==="vertical"&&i==="center")&&o!=="middle"&&rt(e[o]))return Ga(Ga({},e),{},{[o]:e[o]+(a||0)})}return e},Oo=(e,t)=>e==="horizontal"&&t==="xAxis"||e==="vertical"&&t==="yAxis"||e==="centric"&&t==="angleAxis"||e==="radial"&&t==="radiusAxis",vU=(e,t,n,r)=>{if(r)return e.map(l=>l.coordinate);var a,i,o=e.map(l=>(l.coordinate===t&&(a=!0),l.coordinate===n&&(i=!0),l.coordinate));return a||o.push(t),i||o.push(n),o},wU=(e,t,n)=>{if(!e)return null;var r=e.duplicateDomain,a=e.type,i=e.range,o=e.scale,l=e.realScaleType,c=e.isCategorical,u=e.categoricalDomain,d=e.tickCount,h=e.ticks,f=e.niceTicks,m=e.axisType;if(!o)return null;var x=l==="scaleBand"&&o.bandwidth?o.bandwidth()/2:2,g=a==="category"&&o.bandwidth?o.bandwidth()/x:0;if(g=m==="angleAxis"&&i&&i.length>=2?ws(i[0]-i[1])*2*g:g,h||f){var y=(h||f||[]).map((b,v)=>{var w=r?r.indexOf(b):b,_=o.map(w);return Mt(_)?{coordinate:_+g,value:b,offset:g,index:v}:null}).filter(Ea);return y}return c&&u?u.map((b,v)=>{var w=o.map(b);return Mt(w)?{coordinate:w+g,value:b,index:v,offset:g}:null}).filter(Ea):o.ticks&&d!=null?o.ticks(d).map((b,v)=>{var w=o.map(b);return Mt(w)?{coordinate:w+g,value:b,index:v,offset:g}:null}).filter(Ea):o.domain().map((b,v)=>{var w=o.map(b);return Mt(w)?{coordinate:w+g,value:r?r[b]:b,index:v,offset:g}:null}).filter(Ea)},awe=(e,t)=>{if(!t||t.length!==2||!rt(t[0])||!rt(t[1]))return e;var n=Math.min(t[0],t[1]),r=Math.max(t[0],t[1]),a=[e[0],e[1]];return(!rt(e[0])||e[0]<n)&&(a[0]=n),(!rt(e[1])||e[1]>r)&&(a[1]=r),a[0]>r&&(a[0]=r),a[1]<n&&(a[1]=n),a},iwe=e=>{var t,n=e.length;if(!(n<=0)){var r=(t=e[0])===null||t===void 0?void 0:t.length;if(!(r==null||r<=0))for(var a=0;a<r;++a)for(var i=0,o=0,l=0;l<n;++l){var c=e[l],u=c==null?void 0:c[a];if(u!=null){var d=u[1],h=u[0],f=No(d)?h:d;f>=0?(u[0]=i,i+=f,u[1]=i):(u[0]=o,o+=f,u[1]=o)}}}},owe=e=>{var t,n=e.length;if(!(n<=0)){var r=(t=e[0])===null||t===void 0?void 0:t.length;if(!(r==null||r<=0))for(var a=0;a<r;++a)for(var i=0,o=0;o<n;++o){var l=e[o],c=l==null?void 0:l[a];if(c!=null){var u=No(c[1])?c[0]:c[1];u>=0?(c[0]=i,i+=u,c[1]=i):(c[0]=0,c[1]=0)}}}},lwe={sign:iwe,expand:Ebe,none:Nd,silhouette:Abe,wiggle:Tbe,positive:owe},cwe=(e,t,n)=>{var r,a=(r=lwe[n])!==null&&r!==void 0?r:Nd,i=Cbe().keys(t).value((l,c)=>Number(hn(l,c,0))).order(VN).offset(a),o=i(e);return o.forEach((l,c)=>{l.forEach((u,d)=>
808{var h=hn(e[d],t[c],0);Array.isArray(h)&&h.length===2&&rt(h[0])&&rt(h[1])&&(u[0]=h[0],u[1]=h[1])})}),o};function _U(e){return e==null?void 0:String(e)}function Tb(e){var t=e.axis,n=e.ticks,r=e.bandSize,a=e.entry,i=e.index,o=e.dataKey;if(t.type==="category"){if(!t.allowDuplicatedCategory&&t.dataKey&&!sr(a[t.dataKey])){var l=a9(n,"value",a[t.dataKey]);if(l)return l.coordinate+r/2}return n!=null&&n[i]?n[i].coordinate+r/2:null}var c=hn(a,sr(o)?t.dataKey:o),u=t.scale.map(c);return rt(u)?u:null}var yR=e=>{var t=e.axis,n=e.ticks,r=e.offset,a=e.bandSize,i=e.entry,o=e.index;if(t.type==="category")return n[o]?n[o].coordinate+r:null;var l=hn(i,t.dataKey,t.scale.domain()[o]);if(sr(l))return null;var c=t.scale.map(l);return rt(c)?c-a/2+r:null},uwe=e=>{var t=e.numericAxis,n=t.scale.domain();if(t.type==="number"){var r=Math.min(n[0],n[1]),a=Math.max(n[0],n[1]);return r<=0&&a>=0?0:a<0?a:r}return n[0]},dwe=e=>{var t=e.flat(2).filter(rt);return[Math.min(...t),Math.max(...t)]},hwe=e=>[e[0]===1/0?0:e[0],e[1]===-1/0?0:e[1]],fwe=(e,t,n)=>{if(!(e==null||Object.keys(e).length===0))return hwe(Object.keys(e).reduce((r,a)=>{var i=e[a];if(!i)return r;var o=i.stackedData,l=o.reduce((c,u)=>{var d=bU(u,t,n),h=dwe(d);return!Mt(h[0])||!Mt(h[1])?c:[Math.min(c[0],h[0]),Math.max(c[1],h[1])]},[1/0,-1/0]);return[Math.min(l[0],r[0]),Math.max(l[1],r[1])]},[1/0,-1/0]))},bR=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,vR=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,su=(e,t,n)=>{if(e&&e.scale&&e.scale.bandwidth){var r=e.scale.bandwidth();if(!n||r>0)return r}if(e&&t&&t.length>=2){for(var a=j0(t,g=>g.coordinate),i=[],o=0,l=1,c=a.length;l<c;l++){var u,d,h=(((u=a[l])===null||u===void 0?void 0:u.coordinate)||0)-(((d=a[l-1])===null||d===void 0?void 0:d.coordinate)||0);i.push(h),o=Math.max(h,o)}var f=o*1e-4,m=1/0;for(var x of i)x>f&&(m=Math.min(x,m));return m===1/0?0:m}return n?void 0:0};function wR(e){var t=e.tooltipEntrySettings,n=e.dataKey,r=e.payload,a=e.value,i=e.name;return Ga(Ga({},t),{},{dataKey:n,payload:r,value:a,name:i})}function vu(e,t){if(e!=null)return String(e);if(typeof t=="string")return t}var mwe=(e,t)=>{if(t==="horizontal")return e.relativeX;if(t==="vertical")return e.relativeY},pwe=(e,t)=>t==="centric"?e.angle:e.radius,xl=e=>e.layout.width,gl=e=>e.layout.height,xwe=e=>e.layout.scale,uE=e=>e.layout.margin,D0=be(e=>e.cartesianAxis.xAxis,e=>Object.values(e)),M0=be(e=>e.cartesianAxis.yAxis,e=>Object.values(e)),kU="data-recharts-item-index",jU="data-recharts-item-id",wx=60,dE=30;function _R(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Sg(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?_R(Object(n),!0).forEach(function(r){gwe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_R(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function gwe(e,t,n){return(t=ywe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ywe(e){var t=bwe(e,"string");return typeof t=="symbol"?t:t+""}function bwe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var vwe=e=>e.brush.height;function wwe(e){var t=M0(e);return t.reduce((n,r)=>{if(r.orientation==="left"&&!r.mirror&&!r.hide){var a=typeof r.width=="number"?r.width:wx;return n+a}return n},0)}function _we(e){var t=M0(e);return t.reduce((n,r)=>{if(r.orientation==="right"&&!r.mirror&&!r.hide){var a=typeof r.width=="number"?r.width:wx;return n+a}return n},0)}function kwe(e){var t=D0(e);return t.reduce((n,r)=>{if(r.orientation==="top"&&!r.mirror&&!r.hide){var a=typeof r.height=="number"?r.height:dE;return n+a}return n},0)}function jwe(e){var t=D0(e);return t.reduce((n,r)=>{if(r.orientation==="bottom"&&!r.mirror&&!r.hide){var a=typeof r.height=="number"?r.height:dE;return n+a}return n},0)}
808var ds=be([xl,gl,uE,vwe,wwe,_we,kwe,jwe,z9,Kve],(e,t,n,r,a,i,o,l,c,u)=>{var d={left:(n.left||0)+a,right:(n.right||0)+i},h={top:(n.top||0)+o,bottom:(n.bottom||0)+l},f=Sg(Sg({},h),d),m=f.bottom;f.bottom+=r,f=swe(f,c,u);var x=e-f.left-f.right,g=t-f.top-f.bottom;return Sg(Sg({brushBottom:m},f),{},{width:Math.max(x,0),height:Math.max(g,0)})}),NU=be(ds,e=>({x:e.left,y:e.top,width:e.width,height:e.height})),hE=be(xl,gl,(e,t)=>({x:0,y:0,width:e,height:t})),Nwe=p.createContext(null),Jr=()=>p.useContext(Nwe)!=null,$0=e=>e.brush,L0=be([$0,ds,uE],(e,t,n)=>({height:e.height,x:rt(e.x)?e.x:t.left,y:rt(e.y)?e.y:t.top+t.height+t.brushBottom-((n==null?void 0:n.bottom)||0),width:rt(e.width)?e.width:t.width})),I_={},P_={},R_={},kR;function Swe(){return kR||(kR=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n,r,{signal:a,edges:i}={}){let o,l=null;const c=i!=null&&i.includes("leading"),u=i==null||i.includes("trailing"),d=()=>{l!==null&&(n.apply(o,l),o=void 0,l=null)},h=()=>{u&&d(),g()};let f=null;const m=()=>{f!=null&&clearTimeout(f),f=setTimeout(()=>{f=null,h()},r)},x=()=>{f!==null&&(clearTimeout(f),f=null)},g=()=>{x(),o=void 0,l=null},y=()=>{d()},b=function(...v){if(a!=null&&a.aborted)return;o=this,l=v;const w=f==null;m(),c&&w&&d()};return b.schedule=m,b.cancel=g,b.flush=y,a==null||a.addEventListener("abort",g,{once:!0}),b}e.debounce=t})(R_)),R_}var jR;function Cwe(){return jR||(jR=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=Swe();function n(r,a=0,i={}){typeof i!="object"&&(i={});const{leading:o=!1,trailing:l=!0,maxWait:c}=i,u=Array(2);o&&(u[0]="leading"),l&&(u[1]="trailing");let d,h=null;const f=t.debounce(function(...g){d=r.apply(this,g),h=null},a,{edges:u}),m=function(...g){return c!=null&&(h===null&&(h=Date.now()),Date.now()-h>=c)?(d=r.apply(this,g),h=Date.now(),f.cancel(),f.schedule(),d):(f.apply(this,g),d)},x=()=>(f.flush(),d);return m.cancel=f.cancel,m.flush=x,m}e.debounce=n})(P_)),P_}var NR;function Ewe(){return NR||(NR=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=Cwe();function n(r,a=0,i={}){const{leading:o=!0,trailing:l=!0}=i;return t.debounce(r,a,{leading:o,maxWait:a,trailing:l})}e.throttle=n})(I_)),I_}var D_,SR;function Awe(){return SR||(SR=1,D_=Ewe().throttle),D_}var Twe=Awe();const Owe=hl(Twe);var Ob=function(t,n){for(var r=arguments.length,a=new Array(r>2?r-2:0),i=2;i<r;i++)a[i-2]=arguments[i];if(typeof console<"u"&&console.warn&&(n===void 0&&console.warn("LogUtils requires an error message argument"),!t))if(n===void 0)console.warn("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var o=0;console.warn(n.replace(/%s/g,()=>a[o++]))}},Xo={width:"100%",height:"100%",debounce:0,minWidth:0,initialDimension:{width:-1,height:-1}},SU=(e,t,n)=>{var r=n.width,a=r===void 0?Xo.width:r,i=n.height,o=i===void 0?Xo.height:i,l=n.aspect,c=n.maxHeight,u=jd(a)?e:Number(a),d=jd(o)?t:Number(o);return l&&l>0&&(u?d=u/l:d&&(u=d*l),c&&d!=null&&d>c&&(d=c)),{calculatedWidth:u,calculatedHeight:d}},Iwe={width:0,height:0,overflow:"visible"},Pwe={width:0,overflowX:"visible"},Rwe={height:0,overflowY:"visible"},Dwe={},Mwe=e=>{var t=e.width,n=e.height,r=jd(t),a=jd(n);return r&&a?Iwe:r?Pwe:a?Rwe:Dwe};function $we(e){var t=e.width,n=e.height,r=e.aspect,a=t,i=n;return a===void 0&&i===void 0?(a=Xo.width,i=Xo.height):a===void 0?a=r&&r>0?void 0:Xo.width:i===void 0&&(i=r&&r>0?void 0:Xo.height),{width:a,height:i}}var Lwe=["aspect","initialDimension","width","height","minWidth","minHeight","maxHeight","children","debounce","id","className","onResize","style"];function Ib(){return Ib=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Ib.apply(null,arguments)}function CR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function ER(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
808t%2?CR(Object(n),!0).forEach(function(r){Fwe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):CR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Fwe(e,t,n){return(t=Bwe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Bwe(e){var t=Uwe(e,"string");return typeof t=="symbol"?t:t+""}function Uwe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function zwe(e,t){return Vwe(e)||Hwe(e,t)||Kwe(e,t)||Wwe()}function Wwe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 809In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Kwe(e,t){if(e){if(typeof e=="string")return AR(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?AR(e,t):void 0}}function AR(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Hwe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function Vwe(e){if(Array.isArray(e))return e}function qwe(e,t){if(e==null)return{};var n,r,a=Gwe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function Gwe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var CU=p.createContext(Xo.initialDimension);function Ywe(e){return ol(e.width)&&ol(e.height)}function EU(e){var t=e.children,n=e.width,r=e.height,a=p.useMemo(()=>({width:n,height:r}),[n,r]);return Ywe(a)?p.createElement(CU.Provider,{value:a},t):null}var fE=()=>p.useContext(CU),Zwe=p.forwardRef((e,t)=>{var n=e.aspect,r=e.initialDimension,a=r===void 0?Xo.initialDimension:r,i=e.width,o=e.height,l=e.minWidth,c=l===void 0?Xo.minWidth:l,u=e.minHeight,d=e.maxHeight,h=e.children,f=e.debounce,m=f===void 0?Xo.debounce:f,x=e.id,g=e.className,y=e.onResize,b=e.style,v=b===void 0?{}:b,w=qwe(e,Lwe),_=p.useRef(null),k=p.useRef();k.current=y,p.useImperativeHandle(t,()=>_.current);var j=p.useState({containerWidth:a.width,containerHeight:a.height}),N=zwe(j,2),E=N[0],A=N[1],C=p.useCallback(($,P)=>{A(F=>{var Z=Math.round($),D=Math.round(P);return F.containerWidth===Z&&F.containerHeight===D?F:{containerWidth:Z,containerHeight:D}})},[]);p.useEffect(()=>{if(_.current==null||typeof ResizeObserver>"u")return bu;var $=H=>{var Y,M=H[0];if(M!=null){var z=M.contentRect,G=z.width,te=z.height;C(G,te),(Y=k.current)===null||Y===void 0||Y.call(k,G,te)}};m>0&&($=Owe($,m,{trailing:!0,leading:!1}));var P=new ResizeObserver($),F=_.current.getBoundingClientRect(),Z=F.width,D=F.height;return C(Z,D),P.observe(_.current),()=>{P.disconnect()}},[C,m]);var T=E.containerWidth,S=E.containerHeight;Ob(!n||n>0,"The aspect(%s) must be greater than zero.",n);var O=SU(T,S,{width:i,height:o,aspect:n,maxHeight:d}),R=O.calculatedWidth,I=O.calculatedHeight;return Ob(T<0||S<0||R!=null&&R>0||I!=null&&I>0,`The width(%s) and height(%s) of chart should be greater than 0, 810 please check the style of container, or the props width(%s) and height(%s), 811 or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the 812 height and width.`,R,I,i,o,c,u,n),p.createElement("div",Ib({id:x?"".concat(x):void 0,className:un("recharts-responsive-container",g),style:ER(ER({},v),{},{width:i,height:o,minWidth:c,minHeight:u,maxHeight:d}),ref:_},w),p.createElement("div",{style:Mwe({width:i,height:o})},p.createElement(EU,{width:R,height:I},h)))}),li=p.forwardRef((e,t)=>
812{var n=fE();if(ol(n.width)&&ol(n.height))return e.children;var r=$we({width:e.width,height:e.height,aspect:e.aspect}),a=r.width,i=r.height,o=SU(void 0,void 0,{width:a,height:i,aspect:e.aspect,maxHeight:e.maxHeight}),l=o.calculatedWidth,c=o.calculatedHeight;return rt(l)&&rt(c)?p.createElement(EU,{width:l,height:c},e.children):p.createElement(Zwe,Ib({},e,{width:a,height:i,ref:t}))}),_x=()=>{var e,t=Jr(),n=ot(NU),r=ot(L0),a=(e=ot($0))===null||e===void 0?void 0:e.padding;return!t||!r||!a?n:{width:r.width-a.left-a.right,height:r.height-a.top-a.bottom,x:a.left,y:a.top}},Xwe={top:0,bottom:0,left:0,right:0,width:0,height:0,brushBottom:0},AU=()=>{var e;return(e=ot(ds))!==null&&e!==void 0?e:Xwe},mE=()=>ot(xl),pE=()=>ot(gl),Jwe=()=>ot(e=>e.layout.margin),sn=e=>e.layout.layoutType,wu=()=>ot(sn),xE=()=>{var e=wu();if(e==="horizontal"||e==="vertical")return e},gE=e=>{var t=e.layout.layoutType;if(t==="centric"||t==="radial")return t},Qwe=()=>ot(gE),e1e=()=>{var e=wu();return e!==void 0},kx=e=>{var t=Nn(),n=Jr(),r=e.width,a=e.height,i=fE(),o=r,l=a;return i&&(o=i.width>0?i.width:r,l=i.height>0?i.height:a),p.useEffect(()=>{!n&&ol(o)&&ol(l)&&t(J0e({width:o,height:l}))},[t,n,o,l]),null},t1e={settings:{layout:"horizontal",align:"center",verticalAlign:"bottom",itemSorter:"value",position:void 0,offset:0},size:{width:0,height:0},payload:[]},TU=ga({name:"legend",initialState:t1e,reducers:{setLegendSize(e,t){e.size.width=t.payload.width,e.size.height=t.payload.height},setLegendSettings(e,t){e.settings.align=t.payload.align,e.settings.layout=t.payload.layout,e.settings.verticalAlign=t.payload.verticalAlign,e.settings.itemSorter=t.payload.itemSorter,e.settings.position=t.payload.position,e.settings.offset=t.payload.offset},addLegendPayload:{reducer(e,t){e.payload.push(pn(t.payload))},prepare:er()},replaceLegendPayload:{reducer(e,t){var n=t.payload,r=n.prev,a=n.next,i=zi(e).payload.indexOf(pn(r));i>-1&&(e.payload[i]=pn(a))},prepare:er()},removeLegendPayload:{reducer(e,t){var n=zi(e).payload.indexOf(pn(t.payload));n>-1&&e.payload.splice(n,1)},prepare:er()}}}),jx=TU.actions,TR=jx.setLegendSize,n1e=jx.setLegendSettings,OU=jx.addLegendPayload,IU=jx.replaceLegendPayload,PU=jx.removeLegendPayload,r1e=TU.reducer,M_={exports:{}},$_={};/** 813 * @license React 814 * use-sync-external-store-with-selector.production.js 815 * 816 * Copyright (c) Meta Platforms, Inc. and affiliates. 817 * 818 * This source code is licensed under the MIT license found in the 819 * LICENSE file in the root directory of this source tree. 820 */var OR;function s1e(){if(OR)return $_;OR=1;var e=k2();function t(c,u){return c===u&&(c!==0||1/c===1/u)||c!==c&&u!==u}var n=typeof Object.is=="function"?Object.is:t,r=e.useSyncExternalStore,a=e.useRef,i=e.useEffect,o=e.useMemo,l=e.useDebugValue;return $_.useSyncExternalStoreWithSelector=function(c,u,d,h,f){var m=a(null);if(m.current===null){var x={hasValue:!1,value:null};m.current=x}else x=m.current;m=o(function(){function y(k){if(!b){if(b=!0,v=k,k=h(k),f!==void 0&&x.hasValue){var j=x.value;if(f(j,k))return w=j}return w=k}if(j=w,n(v,k))return j;var N=h(k);return f!==void 0&&f(j,N)?(v=k,j):(v=k,w=N)}var b=!1,v,w,_=d===void 0?null:d;return[function(){return y(u())},_===null?void 0:function(){return y(_())}]},[u,d,h,f]);var g=r(c,m[0],m[1]);return i(function(){x.hasValue=!0,x.value=g},[g]),l(g),g},$_}var IR;function a1e(){return IR||(IR=1,M_.exports=s1e()),M_.exports}a1e();function i1e(e){e()}function o1e(){let e=null,t=null;return{clear(){e=null,t=null},notify(){i1e(()=>{let n=e;for(;n;)n.callback(),n=n.next})},get(){const n=[];let r=e;for(;r;)n.push(r),r=r.next;return n},subscribe(n){let r=!0;const a=t={callback:n,next:null,prev:t};return a.prev?a.prev.next=a:e=a,function(){!r||e===null||(r=!1,a.next?a.next.prev=a.prev:t=a.prev,a.prev?a.prev.next=a.next:e=a.next)}}}}var PR={notify(){},get:()=>[]};function l1e(e,t){let n,r=PR,a=0,i=!1;function o(g){d();const y=r.subscribe(g);let b=!1;return()=>{b||(b=!0,y(),h())}}function l(){r.notify()}function c(){x.onStateChange&&x.onStateChange()}function u(){return i}function d(){a++,n||(n=e.subscribe(c),r=o1e())}function h(){a--,n&&a===0&&(n(),n=void 0,r.clear(),r=PR)}function f(){i||(i=!0,d())}function m(){i&&(i=!1,h())}const x={addNestedSub:o,notifyNestedSubs:l,handleChangeWrapper:c,isSubscribed:u,trySubscribe:f,tryUnsubscribe:m,getListeners:()=>r};return x}var c1e=()=>typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",u1e=c1e(),d1e=()=>typeof navigator<"u"&&navigator.product==="ReactNative",h1e=d1e(),f1e=()=>u1e||h1e?p.useLayoutEffect:p.useEffect,m1e=f1e();function RR(e,t){return e===t?e!==0||t!==0||1/e===1/t:e!==e&&t!==t}function p1e(e,t){if(RR(e,t))return!0;
820if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let a=0;a<n.length;a++)if(!Object.prototype.hasOwnProperty.call(t,n[a])||!RR(e[n[a]],t[n[a]]))return!1;return!0}var L_=Symbol.for("react-redux-context"),F_=typeof globalThis<"u"?globalThis:{};function x1e(){if(!p.createContext)return{};const e=F_[L_]??(F_[L_]=new Map);let t=e.get(p.createContext);return t||(t=p.createContext(null),e.set(p.createContext,t)),t}var g1e=x1e();function y1e(e){const{children:t,context:n,serverState:r,store:a}=e,i=p.useMemo(()=>{const c=l1e(a);return{store:a,subscription:c,getServerState:r?()=>r:void 0}},[a,r]),o=p.useMemo(()=>a.getState(),[a]);m1e(()=>{const{subscription:c}=i;return c.onStateChange=c.notifyNestedSubs,c.trySubscribe(),o!==a.getState()&&c.notifyNestedSubs(),()=>{c.tryUnsubscribe(),c.onStateChange=void 0}},[i,o]);const l=n||g1e;return p.createElement(l.Provider,{value:i},t)}var b1e=y1e,v1e=new Set(["axisLine","tickLine","activeBar","activeDot","activeLabel","activeShape","allowEscapeViewBox","background","cursor","dot","label","line","margin","padding","position","shape","style","tick","wrapperStyle","radius","throttledEvents"]);function w1e(e,t){return e==null&&t==null?!0:typeof e=="number"&&typeof t=="number"?e===t||e!==e&&t!==t:e===t}function Ld(e,t){var n=new Set([...Object.keys(e),...Object.keys(t)]);for(var r of n)if(v1e.has(r)){if(e[r]==null&&t[r]==null)continue;if(!p1e(e[r],t[r]))return!1}else if(!w1e(e[r],t[r]))return!1;return!0}var _1e=be([xl,gl,uE],(e,t,n)=>({x:n.left||0,y:n.top||0,width:Math.max(e-(n.left||0)-(n.right||0),0),height:Math.max(t-(n.top||0)-(n.bottom||0),0)}));function k1e(e,t){var n;if(e==="start"&&t==="start")return"";var r={start:"0",middle:"-50%",end:"-100%"},a={start:"0",middle:"-50%",end:"-100%"},i=e==="inherit"?"0":r[e],o=(n=a[t])!==null&&n!==void 0?n:"0";return"translate(".concat(i,", ").concat(o,")")}var j1e=["contextPayload"];function sS(){return sS=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},sS.apply(null,arguments)}function N1e(e,t){return A1e(e)||E1e(e,t)||C1e(e,t)||S1e()}function S1e(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 821In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function C1e(e,t){if(e){if(typeof e=="string")return DR(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?DR(e,t):void 0}}function DR(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function E1e(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function A1e(e){if(Array.isArray(e))return e}function MR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Zh(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?MR(Object(n),!0).forEach(function(r){T1e(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):MR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function T1e(e,t,n){return(t=O1e(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function O1e(e){var t=I1e(e,"string");return typeof t=="symbol"?t:t+""}function I1e(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function P1e(e,t){if(e==null)return{};var n,r,a=R1e(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function R1e(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function D1e(e){return e.value}function M1e(e){var t=e.contextPayload,n=P1e(e,j1e),r=$9(t,e.payloadUniqBy,D1e),a=Zh(Zh({},n),{},{payload:r});return p.isValidElement(e.content)?p.cloneElement(e.content,a):typeof e.content=="function"?p.createElement(e.content,a):p.createElement(Qbe,a)}function $1e(e){return e==="left"||e==="right"||e==="insideLeft"||e==="insideRight"?"vertical":"horizontal"}function L1e(e,t){return t==null?null:ZC(t)?_1e(e):NU(e)}function F1e(e,t,n){return e==="top"?{top:n.height+t}:e==="bottom"?{top:-n.height-t}:e==="left"?{left:n.width+t}:e==="right"?{left:-n.width-t}:{}}function B1e(e,t,n,r,a,i){var o=t.layout,l=t.align,c=t.verticalAlign,u,d;return(!e||(e.left===void 0||e.left===null)&&(e.right===void 0||e.right===null))&&(l==="center"&&o==="vertical"?u={left:((r||0)-i.width)/2}:u=l==="right"?{right:n&&n.right||0}:{left:n&&n.left||0}),(!e||(e.top===void 0||e.top===null)&&(e.bottom===void 0||e.bottom===null))&&(c==="middle"?d={top:((a||0)-i.height)/2}:d=c==="bottom"?{bottom:n&&n.bottom||0}:{top:n&&n.top||0}),Zh(Zh({},u),d)}function U1e(e){var t=e.align,n=e.layout,r=e.verticalAlign,a=e.itemSorter,i=e.position,o=e.offset,l=Nn();return p.useLayoutEffect(()=>{l(n1e({align:t,layout:n,verticalAlign:r,itemSorter:a,position:i,offset:o}))},[l,t,n,r,a,i,o]),null}
821function z1e(e){var t=e.width,n=e.height,r=Nn();return p.useLayoutEffect(()=>{r(TR({width:t,height:n}))},[r,t,n]),p.useLayoutEffect(()=>()=>{r(TR({width:0,height:0}))},[r]),null}function W1e(e,t,n,r){return e==="vertical"&&t!=null?{height:t}:e==="horizontal"?{width:n||r}:null}var K1e={align:"center",iconSize:14,inactiveColor:"#ccc",itemSorter:"value",labelStyle:{},layout:"auto",verticalAlign:"bottom",offset:0};function H1e(e){var t,n,r,a,i,o,l,c,u=$r(e,K1e),d=e.layout&&e.layout!=="auto"?e.layout:$1e(u.position),h=qve(),f=Xye(),m=Jwe(),x=ot(D=>L1e(D,u.position)),g=u.width,y=u.height,b=u.wrapperStyle,v=u.portal,w=v==null&&(u.position==null||ZC(u.position)),_=W9([h]),k=N1e(_,2),j=k[0],N=k[1],E=mE(),A=pE();if(E==null||A==null||u.position!=null&&x==null)return null;var C=E-((m==null?void 0:m.left)||0)-((m==null?void 0:m.right)||0),T=W1e(d,y,g,C),S=u.position==null?null:i9({viewBox:x??{x:0,y:0,width:E,height:A},position:u.position,offset:(t=u.offset)!==null&&t!==void 0?t:0}),O=F1e(u.position,(n=u.offset)!==null&&n!==void 0?n:0,j),R=d==="vertical"?((r=x==null?void 0:x.width)!==null&&r!==void 0?r:0)/2:(a=x==null?void 0:x.width)!==null&&a!==void 0?a:0,I=d==="horizontal"?((i=x==null?void 0:x.height)!==null&&i!==void 0?i:0)/2:(o=x==null?void 0:x.height)!==null&&o!==void 0?o:0,$=S?{width:"max-content",height:"max-content",maxWidth:R,maxHeight:I,overflowY:"auto",top:S.y+((l=O.top)!==null&&l!==void 0?l:0),left:S.x+((c=O.left)!==null&&c!==void 0?c:0),transform:k1e(S.horizontalAnchor,S.verticalAnchor)}:B1e(b,u,m,E,A,j),P=v?b:Zh(Zh({position:"absolute",width:(T==null?void 0:T.width)||g||"auto",height:(T==null?void 0:T.height)||y||"auto"},$),b),F=v??f;if(F==null||h==null)return null;var Z=p.createElement("div",{className:"recharts-legend-wrapper",style:P,ref:N},p.createElement(U1e,{layout:d,align:u.align,verticalAlign:u.verticalAlign,itemSorter:u.itemSorter,position:u.position,offset:u.offset}),w&&p.createElement(z1e,j),p.createElement(M1e,sS({},u,{layout:d},T,{margin:m,chartWidth:E,chartHeight:A,contextPayload:h})));return Kv.createPortal(Z,F)}var yE=p.memo(H1e,Ld);yE.displayName="Legend";function aS(){return aS=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},aS.apply(null,arguments)}function $R(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function im(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?$R(Object(n),!0).forEach(function(r){V1e(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$R(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function V1e(e,t,n){return(t=q1e(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function q1e(e){var t=G1e(e,"string");return typeof t=="symbol"?t:t+""}function G1e(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Y1e(e,t){return Q1e(e)||J1e(e,t)||X1e(e,t)||Z1e()}function Z1e(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 822In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function X1e(e,t){if(e){if(typeof e=="string")return LR(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?LR(e,t):void 0}}function LR(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function J1e(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}
822finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function Q1e(e){if(Array.isArray(e))return e}function e_e(e){return Array.isArray(e)&&aa(e[0])&&aa(e[1])?e.join(" ~ "):e}var eh={separator:" : ",contentStyle:{margin:0,padding:10,backgroundColor:"#fff",border:"1px solid #ccc",whiteSpace:"nowrap"},itemStyle:{display:"block",paddingTop:4,paddingBottom:4,color:"#000"},labelStyle:{},accessibilityLayer:!1};function t_e(e,t){return t==null?e:j0(e,t)}var n_e=e=>{var t=e.separator,n=t===void 0?eh.separator:t,r=e.contentStyle,a=e.itemStyle,i=e.labelStyle,o=i===void 0?eh.labelStyle:i,l=e.payload,c=e.formatter,u=e.itemSorter,d=e.wrapperClassName,h=e.labelClassName,f=e.label,m=e.labelFormatter,x=e.accessibilityLayer,g=x===void 0?eh.accessibilityLayer:x,y=()=>{if(l&&l.length){var E={padding:0,margin:0},A=t_e(l,u),C=A.map((T,S)=>{if(!T||T.type==="none")return null;var O=T.formatter||c||e_e,R=T.value,I=T.name,$=R,P=I;if(O){var F=O(R,I,T,S,l);if(Array.isArray(F)){var Z=Y1e(F,2);$=Z[0],P=Z[1]}else if(F!=null)$=F;else return null}var D=im(im({},eh.itemStyle),{},{color:T.color||eh.itemStyle.color},a);return p.createElement("li",{className:"recharts-tooltip-item",key:"tooltip-item-".concat(S),style:D},aa(P)?p.createElement("span",{className:"recharts-tooltip-item-name"},P):null,aa(P)?p.createElement("span",{className:"recharts-tooltip-item-separator"},n):null,p.createElement("span",{className:"recharts-tooltip-item-value"},$),p.createElement("span",{className:"recharts-tooltip-item-unit"},T.unit||""))});return p.createElement("ul",{className:"recharts-tooltip-item-list",style:E},C)}return null},b=im(im({},eh.contentStyle),r),v=im({margin:0},o),w=!sr(f),_=w?f:"",k=un("recharts-default-tooltip",d),j=un("recharts-tooltip-label",h);w&&m&&l!==void 0&&l!==null&&(_=m(f,l));var N=g?{role:"status","aria-live":"assertive"}:{};return p.createElement("div",aS({className:k,style:b},N),p.createElement("p",{className:j,style:v},p.isValidElement(_)?_:"".concat(_)),y())},om="recharts-tooltip-wrapper",r_e={visibility:"hidden"};function s_e(e){var t=e.coordinate,n=e.translateX,r=e.translateY;return un(om,{["".concat(om,"-right")]:rt(n)&&t&&rt(t.x)&&n>=t.x,["".concat(om,"-left")]:rt(n)&&t&&rt(t.x)&&n<t.x,["".concat(om,"-bottom")]:rt(r)&&t&&rt(t.y)&&r>=t.y,["".concat(om,"-top")]:rt(r)&&t&&rt(t.y)&&r<t.y})}function FR(e){var t=e.allowEscapeViewBox,n=e.coordinate,r=e.key,a=e.offset,i=e.position,o=e.reverseDirection,l=e.tooltipDimension,c=e.viewBox,u=e.viewBoxDimension;if(i&&rt(i[r]))return i[r];var d=n[r]-l-(a>0?a:0),h=n[r]+a;if(t[r])return o[r]?d:h;var f=c[r];if(f==null)return 0;if(o[r]){var m=d,x=f;return m<x?Math.max(h,f):Math.max(d,f)}if(u==null)return 0;var g=h+l,y=f+u;return g>y?Math.max(d,f):Math.max(h,f)}function a_e(e){var t=e.translateX,n=e.translateY,r=e.useTranslate3d;return{transform:r?"translate3d(".concat(t,"px, ").concat(n,"px, 0)"):"translate(".concat(t,"px, ").concat(n,"px)")}}function i_e(e){var t=e.allowEscapeViewBox,n=e.coordinate,r=e.offsetTop,a=e.offsetLeft,i=e.position,o=e.reverseDirection,l=e.tooltipBox,c=e.useTranslate3d,u=e.viewBox,d,h,f;return l&&l.height>0&&l.width>0&&n?(h=FR({allowEscapeViewBox:t,coordinate:n,key:"x",offset:a,position:i,reverseDirection:o,tooltipDimension:l.width,viewBox:u,viewBoxDimension:u.width}),f=FR({allowEscapeViewBox:t,coordinate:n,key:"y",offset:r,position:i,reverseDirection:o,tooltipDimension:l.height,viewBox:u,viewBoxDimension:u.height}),d=a_e({translateX:h,translateY:f,useTranslate3d:c})):d=r_e,{cssProperties:d,cssClasses:s_e({translateX:h,translateY:f,coordinate:n})}}var o_e=()=>!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout),Nx={isSsr:o_e()};function l_e(e,t){return h_e(e)||d_e(e,t)||u_e(e,t)||c_e()}function c_e(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 823In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function u_e(e,t){if(e){if(typeof e=="string")return BR(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?BR(e,t):void 0}}function BR(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}
823function d_e(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function h_e(e){if(Array.isArray(e))return e}function RU(){var e=p.useState(()=>Nx.isSsr||!window.matchMedia?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches),t=l_e(e,2),n=t[0],r=t[1];return p.useEffect(()=>{if(window.matchMedia){var a=window.matchMedia("(prefers-reduced-motion: reduce)"),i=()=>{r(a.matches)};return a.addEventListener("change",i),()=>{a.removeEventListener("change",i)}}},[]),n}function UR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function th(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?UR(Object(n),!0).forEach(function(r){f_e(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):UR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function f_e(e,t,n){return(t=m_e(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function m_e(e){var t=p_e(e,"string");return typeof t=="symbol"?t:t+""}function p_e(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function x_e(e,t){return v_e(e)||b_e(e,t)||y_e(e,t)||g_e()}function g_e(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 824In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function y_e(e,t){if(e){if(typeof e=="string")return zR(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?zR(e,t):void 0}}function zR(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function b_e(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function v_e(e){if(Array.isArray(e))return e}function w_e(e){if(!(e.prefersReducedMotion&&e.isAnimationActive==="auto")&&e.isAnimationActive&&e.active){var t=typeof e.animationEasing=="string"?e.animationEasing:"ease";return"transform ".concat(e.animationDuration,"ms ").concat(t)}}function __e(e){var t,n,r,a,i,o,l=RU(),c=p.useState(()=>({dismissed:!1,dismissedAtCoordinate:{x:0,y:0}})),u=x_e(c,2),d=u[0],h=u[1];p.useEffect(()=>{var b=v=>{if(v.key==="Escape"){var w,_,k,j;h({dismissed:!0,dismissedAtCoordinate:{x:(w=(_=e.coordinate)===null||_===void 0?void 0:_.x)!==null&&w!==void 0?w:0,y:(k=(j=e.coordinate)===null||j===void 0?void 0:j.y)!==null&&k!==void 0?k:0}})}};return document.addEventListener("keydown",b),()=>{document.removeEventListener("keydown",b)}},[(t=e.coordinate)===null||t===void 0?void 0:t.x,(n=e.coordinate)===null||n===void 0?void 0:n.y]),d.dismissed&&(((r=(a=e.coordinate)===null||a===void 0?void 0:a.x)!==null&&r!==void 0?r:0)!==d.dismissedAtCoordinate.x||((i=(o=e.coordinate)===null||o===void 0?void 0:o.y)!==null&&i!==void 0?i:0)!==d.dismissedAtCoordinate.y)&&h(th(th({},d),{},{dismissed:!1}));var f=i_e({allowEscapeViewBox:e.allowEscapeViewBox,coordinate:e.coordinate,offsetLeft:typeof e.offset=="number"?e.offset:e.offset.x,offsetTop:typeof e.offset=="number"?e.offset:e.offset.y,position:e.position,reverseDirection:e.reverseDirection,tooltipBox:e.lastBoundingBox,useTranslate3d:e.useTranslate3d,viewBox:e.viewBox}
824),m=f.cssClasses,x=f.cssProperties,g=e.hasPortalFromProps?{}:th(th({transition:w_e({prefersReducedMotion:l,isAnimationActive:e.isAnimationActive,active:e.active,animationDuration:e.animationDuration,animationEasing:e.animationEasing})},x),{},{pointerEvents:"none",position:"absolute",top:0,left:0}),y=th(th({},g),{},{visibility:!d.dismissed&&e.active&&e.hasPayload?"visible":"hidden"},e.wrapperStyle);return p.createElement("div",{xmlns:"http://www.w3.org/1999/xhtml",tabIndex:-1,className:m,style:y,ref:e.innerRef},e.children)}var k_e=p.memo(__e),DU=()=>{var e;return(e=ot(t=>t.rootProps.accessibilityLayer))!==null&&e!==void 0?e:!0};function iS(){return iS=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},iS.apply(null,arguments)}function WR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function KR(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?WR(Object(n),!0).forEach(function(r){j_e(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):WR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function j_e(e,t,n){return(t=N_e(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function N_e(e){var t=S_e(e,"string");return typeof t=="symbol"?t:t+""}function S_e(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var HR={curveBasisClosed:xbe,curveBasisOpen:gbe,curveBasis:pbe,curveBumpX:tbe,curveBumpY:nbe,curveLinearClosed:ybe,curveLinear:w0,curveMonotoneX:bbe,curveMonotoneY:vbe,curveNatural:wbe,curveStep:_be,curveStepAfter:jbe,curveStepBefore:kbe},Pb=e=>Mt(e.x)&&Mt(e.y),VR=e=>e.base!=null&&Pb(e.base)&&Pb(e),lm=e=>e.x,cm=e=>e.y,C_e=(e,t)=>{if(typeof e=="function")return e;var n="curve".concat(gx(e));if((n==="curveMonotone"||n==="curveBump")&&t){var r=HR["".concat(n).concat(t==="vertical"?"Y":"X")];if(r)return r}return HR[n]||w0},qR={connectNulls:!1,type:"linear"},E_e=e=>{var t=e.type,n=t===void 0?qR.type:t,r=e.points,a=r===void 0?[]:r,i=e.baseLine,o=e.layout,l=e.connectNulls,c=l===void 0?qR.connectNulls:l,u=C_e(n,o),d=c?a.filter(Pb):a;if(Array.isArray(i)){var h,f=a.map((b,v)=>KR(KR({},b),{},{base:i[v]}));o==="vertical"?h=vg().y(cm).x1(lm).x0(b=>b.base.x):h=vg().x(lm).y1(cm).y0(b=>b.base.y);var m=h.defined(VR).curve(u),x=c?f.filter(VR):f;return m(x)}var g;o==="vertical"&&rt(i)?g=vg().y(cm).x1(lm).x0(i):rt(i)?g=vg().x(lm).y1(cm).y0(i):g=f9().x(lm).y(cm);var y=g.defined(Pb).curve(u);return y(d)},Lh=e=>{var t=e.className,n=e.points,r=e.path,a=e.pathRef,i=wu();if((!n||!n.length)&&!r)return null;var o={type:e.type,points:e.points,baseLine:e.baseLine,layout:e.layout||i,connectNulls:e.connectNulls},l=n&&n.length?E_e(o):r;return p.createElement("path",iS({},Ra(e),eE(e),{className:un("recharts-curve",t),d:l===null?void 0:l,ref:a}))},A_e=["x","y","top","left","width","height","className"];function oS(){return oS=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},oS.apply(null,arguments)}function GR(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function T_e(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?GR(Object(n),!0).forEach(function(r){O_e(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):GR(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function O_e(e,t,n){return(t=I_e(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function I_e(e){var t=P_e(e,"string");return typeof t=="symbol"?t:t+""}function P_e(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}
824function R_e(e,t){if(e==null)return{};var n,r,a=D_e(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function D_e(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var M_e=(e,t,n,r,a,i)=>"M".concat(e,",").concat(a,"v").concat(r,"M").concat(i,",").concat(t,"h").concat(n),$_e=e=>{var t=e.x,n=t===void 0?0:t,r=e.y,a=r===void 0?0:r,i=e.top,o=i===void 0?0:i,l=e.left,c=l===void 0?0:l,u=e.width,d=u===void 0?0:u,h=e.height,f=h===void 0?0:h,m=e.className,x=R_e(e,A_e),g=T_e({x:n,y:a,top:o,left:c,width:d,height:f},x);return!rt(n)||!rt(a)||!rt(d)||!rt(f)||!rt(o)||!rt(c)?null:p.createElement("path",oS({},ha(g),{className:un("recharts-cross",m),d:M_e(n,a,d,f,o,c)}))};function L_e(e,t,n,r){var a=r/2;return{stroke:"none",fill:"#ccc",x:e==="horizontal"?t.x-a:n.left+.5,y:e==="horizontal"?n.top+.5:t.y-a,width:e==="horizontal"?r:n.width-1,height:e==="horizontal"?n.height-1:r}}var Rb=1e-4,MU=(e,t)=>[0,3*e,3*t-6*e,3*e-3*t+1],$U=(e,t)=>e.map((n,r)=>n*t**r).reduce((n,r)=>n+r),YR=(e,t)=>n=>{var r=MU(e,t);return $U(r,n)},F_e=(e,t)=>n=>{var r=MU(e,t),a=[...r.map((i,o)=>i*o).slice(1),0];return $U(a,n)},B_e=e=>{var t,n=e.split("(");if(n.length!==2||n[0]!=="cubic-bezier")return null;var r=(t=n[1])===null||t===void 0||(t=t.split(")")[0])===null||t===void 0?void 0:t.split(",");if(r==null||r.length!==4)return null;var a=r.map(i=>parseFloat(i));return[a[0],a[1],a[2],a[3]]},U_e=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];if(n.length===1)switch(n[0]){case"linear":return[0,0,1,1];case"ease":return[.25,.1,.25,1];case"ease-in":return[.42,0,1,1];case"ease-out":return[.42,0,.58,1];case"ease-in-out":return[0,0,.58,1];default:{var a=B_e(n[0]);if(a)return a}}return n.length===4?n:[0,0,1,1]},z_e=(e,t,n,r)=>{var a=YR(e,n),i=YR(t,r),o=F_e(e,n),l=u=>u>1?1:u<0?0:u,c=u=>{for(var d=u>1?1:u,h=d,f=0;f<8;++f){var m=a(h)-d,x=o(h);if(Math.abs(m-d)<Rb||x<Rb)return i(h);h=l(h-m/x)}return i(h)};return c.isStepper=!1,c},ZR=function(){return z_e(...U_e(...arguments))},W_e=function(){for(var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=t.stiff,r=n===void 0?100:n,a=t.damping,i=a===void 0?8:a,o=t.dt,l=o===void 0?16.67:o,c=1,u=[0],d=0,h=0,f=1e4,m=0;m<f;){var x=-(d-c)*r,g=h*i;if(h+=(x-g)*l/1e3,d+=h*l/1e3,u.push(d),Math.abs(d-c)<Rb&&Math.abs(h)<Rb)break;m++}u[u.length-1]=c;var y=u.length-1;return b=>{var v,w,_;if(b<=0)return 0;if(b>=1)return c;var k=b*y,j=Math.floor(k),N=k-j;return((v=u[j])!==null&&v!==void 0?v:0)+(((w=u[j+1])!==null&&w!==void 0?w:0)-((_=u[j])!==null&&_!==void 0?_:0))*N}},K_e=e=>{if(typeof e=="string")switch(e){case"ease":case"ease-in-out":case"ease-out":case"ease-in":case"linear":return ZR(e);case"spring":return W_e();default:if(e.split("(")[0]==="cubic-bezier")return ZR(e)}return typeof e=="function"?e:null},H_e=(e,t,n)=>{var r,a=i=>{var o=t.tick(i);if(t.getState()==="active"){if(n(t.getInterpolated()),t.getProgress()===1){t.complete(),r=void 0;return}r=e.setTimeout(a,o);return}r=e.setTimeout(a,o)};return r=e.setTimeout(a,0),()=>{var i;return(i=r)===null||i===void 0?void 0:i()}},LU=p.createContext(H_e);LU.Provider;function V_e(e){var t=p.useContext(LU);return p.useMemo(()=>e??t,[e,t])}function q_e(e,t,n){return(t=G_e(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function G_e(e){var t=Y_e(e,"string");return typeof t=="symbol"?t:t+""}function Y_e(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var XR="init",JR="pending",QR="active",Z_e="completed";function B_(e){return Math.max(0,e)}class X_e{getAnimationStartedTime(){return this.animationStartedTime}getBeginStartedTime(){return this.beginStartedTime}constructor(t){var n;q_e(this,"state",XR),this.animationId=t.animationId,this.onAnimationEnd=t.onAnimationEnd,this.animationDuration=B_(t.animationDuration),this.animationBegin=B_(t.animationBegin),this.progress=0,this.from=t.from,this.to=t.to,this.easing=t.easing,(n=t.onAnimationStart)===null||n===void 0||n.call(t)}getState(){return this.state}getEasing(){return this.easing}getAnimationDuration(){return this.animationDuration}tick(t){if(this.getState()===XR)return this.state=JR,this.beginStartedTime=t,this.animationBegin;if(this.getState()===JR){if(this.beginStartedTime==null)throw new Error;var n=t-this.beginStartedTime;return n>=this.animationBegin?(this.state=QR,this.animationStartedTime=t,this.nextAnimationUpdate(0)):B_(this.animationBegin-n)}if(this.getState()===QR){if(this.animationStartedTime==null)throw new Error;var r=t-this.animationStartedTime;return this.setProgress(r/this.animationDuration),this.nextAnimationUpdate(r)}return 0}setProgress(t){this.progress=Math.min(1,Math.max(0,t))}getProgress(){return this.progress}complete(){if(this.progress=1,this.state==="active"){var t;(t=this.onAnimationEnd)===null||t===void 0||t.call(this)}this.state=Z_e}getFrom(){return this.from}getTo(){return this.to}getAnimationId(){return this.animationId}getAnimationBegin(){return this.animationBegin}}class J_e extends X_e{nextAnimationUpdate(){return 0}getInterpolated(){return this.easing(qn(this.getFrom(),this.getTo(),this.getProgress()))}}class Q_e{setTimeout(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=performance.now(),a=null,i=o=>{o-r>=n?t(o):a=requestAnimationFrame(i)};return a=requestAnimationFrame(i),()=>{a!=null&&cancelAnimationFrame(a)}}}function eke(e,t){return ske(e)||rke(e,t)||nke(e,t)||tke()}
824function tke(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 825In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function nke(e,t){if(e){if(typeof e=="string")return e4(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?e4(e,t):void 0}}function e4(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function rke(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function ske(e){if(Array.isArray(e))return e}var ake={begin:0,duration:1e3,easing:"ease",isActive:!0,canBegin:!0,onAnimationEnd:()=>{},onAnimationStart:()=>{}},t4=0,U_=1;function FU(e){var t=$r(e,ake),n=t.animationId,r=t.isActive,a=t.canBegin,i=t.duration,o=t.easing,l=t.begin,c=t.onAnimationEnd,u=t.onAnimationStart,d=t.children,h=RU(),f=r==="auto"?!Nx.isSsr&&!h:r,m=V_e(t.animationController),x=p.useState(f?t4:U_),g=eke(x,2),y=g[0],b=g[1];return p.useEffect(()=>{f||b(U_)},[f]),p.useEffect(()=>{var v=K_e(o);if(!f||!a||v==null)return bu;var w=new Q_e,_=new J_e({animationId:n,easing:v,animationDuration:i,animationBegin:l,onAnimationStart:u,onAnimationEnd:c,from:t4,to:U_});return m(w,_,b)},[m,n,f,a,i,o,l,u,c]),d(Number(y))}function BU(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"animation-",n=p.useRef(Ap(t)),r=p.useRef(e);return r.current!==e&&(n.current=Ap(t),r.current=e),n.current}var ike=e=>e.replace(/([A-Z])/g,t=>"-".concat(t.toLowerCase())),oke=(e,t,n)=>e.map(r=>"".concat(ike(r)," ").concat(t,"ms ").concat(n)).join(","),lke=["radius"],cke=["radius"],n4,r4,s4,a4,i4,o4,l4,c4,u4,d4;function h4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function f4(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?h4(Object(n),!0).forEach(function(r){uke(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):h4(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function uke(e,t,n){return(t=dke(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function dke(e){var t=hke(e,"string");return typeof t=="symbol"?t:t+""}function hke(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Db(){return Db=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Db.apply(null,arguments)}function m4(e,t){if(e==null)return{};var n,r,a=fke(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function fke(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function mke(e,t){return yke(e)||gke(e,t)||xke(e,t)||pke()}function pke(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 826In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function xke(e,t){if(e){if(typeof e=="string")return p4(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?p4(e,t):void 0}}function p4(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function gke(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}
826finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function yke(e){if(Array.isArray(e))return e}function Lo(e,t){return t||(t=e.slice(0)),Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}var x4=(e,t,n,r,a)=>{var i=Kl(n),o=Kl(r),l=Math.min(Math.abs(i)/2,Math.abs(o)/2),c=o>=0?1:-1,u=i>=0?1:-1,d=o>=0&&i>=0||o<0&&i<0?1:0,h;if(l>0&&Array.isArray(a)){for(var f=[0,0,0,0],m=0,x=4;m<x;m++){var g,y=(g=a[m])!==null&&g!==void 0?g:0;f[m]=y>l?l:y}h=Ms(n4||(n4=Lo(["M",",",""])),e,t+c*f[0]),f[0]>0&&(h+=Ms(r4||(r4=Lo(["A ",",",",0,0,",",",",",""])),f[0],f[0],d,e+u*f[0],t)),h+=Ms(s4||(s4=Lo(["L ",",",""])),e+n-u*f[1],t),f[1]>0&&(h+=Ms(a4||(a4=Lo(["A ",",",",0,0,",`, 827 `,",",""])),f[1],f[1],d,e+n,t+c*f[1])),h+=Ms(i4||(i4=Lo(["L ",",",""])),e+n,t+r-c*f[2]),f[2]>0&&(h+=Ms(o4||(o4=Lo(["A ",",",",0,0,",`, 828 `,",",""])),f[2],f[2],d,e+n-u*f[2],t+r)),h+=Ms(l4||(l4=Lo(["L ",",",""])),e+u*f[3],t+r),f[3]>0&&(h+=Ms(c4||(c4=Lo(["A ",",",",0,0,",`, 829 `,",",""])),f[3],f[3],d,e,t+r-c*f[3])),h+="Z"}else if(l>0&&a===+a&&a>0){var b=Math.min(l,a);h=Ms(u4||(u4=Lo(["M ",",",` 830 A `,",",",0,0,",",",",",` 831 L `,",",` 832 A `,",",",0,0,",",",",",` 833 L `,",",` 834 A `,",",",0,0,",",",",",` 835 L `,",",` 836 A `,",",",0,0,",",",","," Z"])),e,t+c*b,b,b,d,e+u*b,t,e+n-u*b,t,b,b,d,e+n,t+c*b,e+n,t+r-c*b,b,b,d,e+n-u*b,t+r,e+u*b,t+r,b,b,d,e,t+r-c*b)}else h=Ms(d4||(d4=Lo(["M ",","," h "," v "," h "," Z"])),e,t,n,r,-n);return h},g4={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},bE=e=>{var t=$r(e,g4),n=p.useRef(null),r=p.useState(-1),a=mke(r,2),i=a[0],o=a[1];p.useEffect(()=>{if(n.current&&n.current.getTotalLength)try{var F=n.current.getTotalLength();F&&o(F)}catch{}},[]);var l=t.x,c=t.y,u=t.width,d=t.height,h=t.radius,f=t.className,m=t.animationEasing,x=t.animationDuration,g=t.animationBegin,y=t.isAnimationActive,b=t.isUpdateAnimationActive,v=p.useRef(u),w=p.useRef(d),_=p.useRef(l),k=p.useRef(c),j=p.useMemo(()=>({x:l,y:c,width:u,height:d,radius:h}),[l,c,u,d,h]),N=BU(j,"rectangle-");if(l!==+l||c!==+c||u!==+u||d!==+d||u===0||d===0)return null;var E=un("recharts-rectangle",f);if(!b){var A=ha(t);A.radius;var C=m4(A,lke);return p.createElement("path",Db({},C,{x:Kl(l),y:Kl(c),width:Kl(u),height:Kl(d),radius:typeof h=="number"?h:void 0,className:E,d:x4(l,c,u,d,h)}))}var T=v.current,S=w.current,O=_.current,R=k.current,I="0px ".concat(i===-1?1:i,"px"),$="".concat(i,"px ").concat(i,"px"),P=oke(["strokeDasharray"],x,typeof m=="string"?m:g4.animationEasing);return p.createElement(FU,{animationId:N,key:N,canBegin:i>0,duration:x,easing:m,isActive:b,begin:g},F=>{var Z=qn(T,u,F),D=qn(S,d,F),H=qn(O,l,F),Y=qn(R,c,F);n.current&&(v.current=Z,w.current=D,_.current=H,k.current=Y);var M;y?F>0?M={transition:P,strokeDasharray:$}:M={strokeDasharray:I}:M={strokeDasharray:$};var z=ha(t);z.radius;var G=m4(z,cke);return p.createElement("path",Db({},G,{radius:typeof h=="number"?h:void 0,className:E,d:x4(H,Y,Z,D,h),ref:n,style:f4(f4({},M),t.style)}))})};function y4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function b4(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?y4(Object(n),!0).forEach(function(r){bke(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):y4(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function bke(e,t,n){return(t=vke(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function vke(e){var t=wke(e,"string");return typeof t=="symbol"?t:t+""}function wke(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Mb=Math.PI/180,_ke=e=>e*180/Math.PI,Zr=(e,t,n,r)=>({x:e+Math.cos(-Mb*r)*n,y:t+Math.sin(-Mb*r)*n}),UU=function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(r.left||0)-(r.right||0)),Math.abs(n-(r.top||0)-(r.bottom||0)))/2},kke=(e,t)=>{var n=e.x,r=e.y,a=t.x,i=t.y;return Math.sqrt((n-a)**2+(r-i)**2)},jke=(e,t)=>{var n=e.x,r=e.y,a=t.cx,i=t.cy,o=kke({x:n,y:r},{x:a,y:i});if(o<=0)return{radius:o,angle:0};var l=(n-a)/o,c=Math.acos(l);return r>i&&(c=2*Math.PI-c),{radius:o,angle:_ke(c),angleInRadian:c}},Nke=e=>{var t=e.startAngle,n=e.endAngle,r=Math.floor(t/360),a=Math.floor(n/360),i=Math.min(r,a);return{startAngle:t-i*360,endAngle:n-i*360}},Ske=(e,t)=>{var n=t.startAngle,r=t.endAngle,a=Math.floor(n/360),i=Math.floor(r/360),o=Math.min(a,i);return e+o*360},Cke=(e,t)=>{var n=e.relativeX,r=e.relativeY,a=jke({x:n,y:r},t),i=a.radius,o=a.angle,l=t.innerRadius,c=t.outerRadius;if(i<l||i>c||i===0)return null;
836var u=Nke(t),d=u.startAngle,h=u.endAngle,f=o,m;if(d<=h){for(;f>h;)f-=360;for(;f<d;)f+=360;m=f>=d&&f<=h}else{for(;f>d;)f-=360;for(;f<h;)f+=360;m=f>=h&&f<=d}return m?b4(b4({},t),{},{radius:i,angle:Ske(f,t)}):null};function zU(e){var t=e.cx,n=e.cy,r=e.radius,a=e.startAngle,i=e.endAngle,o=Zr(t,n,r,a),l=Zr(t,n,r,i);return{points:[o,l],cx:t,cy:n,radius:r,startAngle:a,endAngle:i}}var v4,w4,_4,k4,j4,N4,S4;function lS(){return lS=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},lS.apply(null,arguments)}function Qu(e,t){return t||(t=e.slice(0)),Object.freeze(Object.defineProperties(e,{raw:{value:Object.freeze(t)}}))}var Eke=(e,t)=>{var n=ws(t-e),r=Math.min(Math.abs(t-e),359.999);return n*r},Cg=e=>{var t=e.cx,n=e.cy,r=e.radius,a=e.angle,i=e.sign,o=e.isExternal,l=e.cornerRadius,c=e.cornerIsExternal,u=l*(o?1:-1)+r,d=Math.asin(l/u)/Mb,h=c?a:a+i*d,f=Zr(t,n,u,h),m=Zr(t,n,r,h),x=c?a-i*d:a,g=Zr(t,n,u*Math.cos(d*Mb),x);return{center:f,circleTangency:m,lineTangency:g,theta:d}},WU=e=>{var t=e.cx,n=e.cy,r=e.innerRadius,a=e.outerRadius,i=e.startAngle,o=e.endAngle,l=Eke(i,o),c=i+l,u=Zr(t,n,a,i),d=Zr(t,n,a,c),h=Ms(v4||(v4=Qu(["M ",",",` 837 A `,",",`,0, 838 `,",",`, 839 `,",",` 840 `])),u.x,u.y,a,a,+(Math.abs(l)>180),+(i>c),d.x,d.y);if(r>0){var f=Zr(t,n,r,i),m=Zr(t,n,r,c);h+=Ms(w4||(w4=Qu(["L ",",",` 841 A `,",",`,0, 842 `,",",`, 843 `,","," Z"])),m.x,m.y,r,r,+(Math.abs(l)>180),+(i<=c),f.x,f.y)}else h+=Ms(_4||(_4=Qu(["L ",","," Z"])),t,n);return h},Ake=e=>{var t=e.cx,n=e.cy,r=e.innerRadius,a=e.outerRadius,i=e.cornerRadius,o=e.forceCornerRadius,l=e.cornerIsExternal,c=e.startAngle,u=e.endAngle,d=ws(u-c),h=Cg({cx:t,cy:n,radius:a,angle:c,sign:d,cornerRadius:i,cornerIsExternal:l}),f=h.circleTangency,m=h.lineTangency,x=h.theta,g=Cg({cx:t,cy:n,radius:a,angle:u,sign:-d,cornerRadius:i,cornerIsExternal:l}),y=g.circleTangency,b=g.lineTangency,v=g.theta,w=l?Math.abs(c-u):Math.abs(c-u)-x-v;if(w<0)return o?Ms(k4||(k4=Qu(["M ",",",` 844 a`,",",",0,0,1,",`,0 845 a`,",",",0,0,1,",`,0 846 `])),m.x,m.y,i,i,i*2,i,i,-i*2):WU({cx:t,cy:n,innerRadius:r,outerRadius:a,startAngle:c,endAngle:u});var _=Ms(j4||(j4=Qu(["M ",",",` 847 A`,",",",0,0,",",",",",` 848 A`,",",",0,",",",",",",",` 849 A`,",",",0,0,",",",",",` 850 `])),m.x,m.y,i,i,+(d<0),f.x,f.y,a,a,+(w>180),+(d<0),y.x,y.y,i,i,+(d<0),b.x,b.y);if(r>0){var k=Cg({cx:t,cy:n,radius:r,angle:c,sign:d,isExternal:!0,cornerRadius:i,cornerIsExternal:l}),j=k.circleTangency,N=k.lineTangency,E=k.theta,A=Cg({cx:t,cy:n,radius:r,angle:u,sign:-d,isExternal:!0,cornerRadius:i,cornerIsExternal:l}),C=A.circleTangency,T=A.lineTangency,S=A.theta,O=l?Math.abs(c-u):Math.abs(c-u)-E-S;if(O<0&&i===0)return"".concat(_,"L").concat(t,",").concat(n,"Z");_+=Ms(N4||(N4=Qu(["L",",",` 851 A`,",",",0,0,",",",",",` 852 A`,",",",0,",",",",",",",` 853 A`,",",",0,0,",",",",","Z"])),T.x,T.y,i,i,+(d<0),C.x,C.y,r,r,+(O>180),+(d>0),j.x,j.y,i,i,+(d<0),N.x,N.y)}else _+=Ms(S4||(S4=Qu(["L",",","Z"])),t,n);return _},Tke={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},KU=e=>{var t=$r(e,Tke),n=t.cx,r=t.cy,a=t.innerRadius,i=t.outerRadius,o=t.cornerRadius,l=t.forceCornerRadius,c=t.cornerIsExternal,u=t.startAngle,d=t.endAngle,h=t.className;if(i<a||u===d)return null;var f=un("recharts-sector",h),m=i-a,x=ca(o,m,0,!0),g;return x>0&&Math.abs(u-d)<360?g=Ake({cx:n,cy:r,innerRadius:a,outerRadius:i,cornerRadius:Math.min(x,m/2),forceCornerRadius:l,cornerIsExternal:c,startAngle:u,endAngle:d}):g=WU({cx:n,cy:r,innerRadius:a,outerRadius:i,startAngle:u,endAngle:d}),p.createElement("path",lS({},ha(t),{className:f,d:g}))};function Oke(e,t,n){if(e==="horizontal")return[{x:t.x,y:n.top},{x:t.x,y:n.top+n.height}];if(e==="vertical")return[{x:n.left,y:t.y},{x:n.left+n.width,y:t.y}];if(S9(t)){if(e==="centric"){var r=t.cx,a=t.cy,i=t.innerRadius,o=t.outerRadius,l=t.angle,c=Zr(r,a,i,l),u=Zr(r,a,o,l);return[{x:c.x,y:c.y},{x:u.x,y:u.y}]}return zU(t)}}var z_={},W_={},K_={},C4;function Ike(){return C4||(C4=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=B9();function n(r){return t.isSymbol(r)?NaN:Number(r)}e.toNumber=n})(K_)),K_}var E4;function Pke(){return E4||(E4=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=Ike();function n(r){return r?(r=t.toNumber(r),r===1/0||r===-1/0?(r<0?-1:1)*Number.MAX_VALUE:r===r?r:0):r===0?r:0}e.toFinite=n})(W_)),W_}var A4;function Rke(){return A4||(A4=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=U9(),n=Pke();function r(a,i,o){o&&typeof o!="number"&&t.isIterateeCall(a,i,o)&&(i=o=void 0),a=n.toFinite(a),i===void 0?(i=a,a=0):i=n.toFinite(i),o=o===void 0?a<i?1:-1:n.toFinite(o);const l=Math.max(Math.ceil((i-a)/(o||1)),0),c=new Array(l);for(let u=0;u<l;u++)c[u]=a,a+=o;return c}e.range=r})(z_)),z_}var H_,T4;function Dke(){return T4||(T4=1,H_=Rke().range),H_}var Mke=Dke();const HU=hl(Mke);var Io=e=>e.chartData,Sx=be([Io],e=>{var t=e.chartData!=null?e.chartData.length-1:0;return{chartData:e.chartData,computedData:e.computedData,dataEndIndex:t,dataStartIndex:0}}),Cx=(e,t,n,r)=>r?Sx(e):Io(e),VU=(e,t,n)=>n?Sx(e):Io(e),$ke=be([Cx],e=>{var t=e.chartData,n=e.dataStartIndex,r=e.dataEndIndex;return t!=null?t.slice(n,r+1):[]}),Lke=be([Sx],e=>{var t=e.chartData,n=e.dataStartIndex,r=e.dataEndIndex;return t!=null?t.slice(n,r+1):[]}),Fke=be([Io],e=>{var t=e.chartData,n=e.dataStartIndex,r=e.dataEndIndex;return t!=null?t.slice(n,r+1):[]});function vE(e,t){return Wke(e)||zke(e,t)||Uke(e,t)||Bke()}
853function Bke(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 854In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Uke(e,t){if(e){if(typeof e=="string")return O4(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?O4(e,t):void 0}}function O4(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function zke(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function Wke(e){if(Array.isArray(e))return e}function tl(e){if(Array.isArray(e)&&e.length===2){var t=vE(e,2),n=t[0],r=t[1];if(Mt(n)&&Mt(r))return!0}return!1}function I4(e,t,n){return n?e:[Math.min(e[0],t[0]),Math.max(e[1],t[1])]}function qU(e,t){if(t&&typeof e!="function"&&Array.isArray(e)&&e.length===2){var n=vE(e,2),r=n[0],a=n[1],i,o;if(Mt(r))i=r;else if(typeof r=="function")return;if(Mt(a))o=a;else if(typeof a=="function")return;var l=[i,o];if(tl(l))return l}}function Kke(e,t,n){if(!(!n&&t==null)){if(typeof e=="function"&&t!=null)try{var r=e(t,n);if(tl(r))return I4(r,t,n)}catch{}if(Array.isArray(e)&&e.length===2){var a=vE(e,2),i=a[0],o=a[1],l,c;if(i==="auto")t!=null&&(l=Math.min(...t));else if(rt(i))l=i;else if(typeof i=="function")try{t!=null&&(l=i(t==null?void 0:t[0]))}catch{}else if(typeof i=="string"&&bR.test(i)){var u=bR.exec(i);if(u==null||u[1]==null||t==null)l=void 0;else{var d=+u[1];l=t[0]-d}}else l=t==null?void 0:t[0];if(o==="auto")t!=null&&(c=Math.max(...t));else if(rt(o))c=o;else if(typeof o=="function")try{t!=null&&(c=o(t==null?void 0:t[1]))}catch{}else if(typeof o=="string"&&vR.test(o)){var h=vR.exec(o);if(h==null||h[1]==null||t==null)c=void 0;else{var f=+h[1];c=t[1]+f}}else c=t==null?void 0:t[1];var m=[l,c];if(tl(m))return t==null?m:I4(m,t,n)}}}var If=1e9,Hke={precision:20,rounding:4,toExpNeg:-7,toExpPos:21,LN10:"2.302585092994045684017991454684364207601101488628772976033327900967572609677352480235997205089598298341967784042286"},_E,ur=!0,Yi="[DecimalError] ",hd=Yi+"Invalid argument: ",wE=Yi+"Exponent out of range: ",Pf=Math.floor,Vu=Math.pow,Vke=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,pi,bs=1e7,tr=7,GU=9007199254740991,$b=Pf(GU/tr),pt={};pt.absoluteValue=pt.abs=function(){var e=new this.constructor(this);return e.s&&(e.s=1),e};pt.comparedTo=pt.cmp=function(e){var t,n,r,a,i=this;if(e=new i.constructor(e),i.s!==e.s)return i.s||-e.s;if(i.e!==e.e)return i.e>e.e^i.s<0?1:-1;for(r=i.d.length,a=e.d.length,t=0,n=r<a?r:a;t<n;++t)if(i.d[t]!==e.d[t])return i.d[t]>e.d[t]^i.s<0?1:-1;return r===a?0:r>a^i.s<0?1:-1};pt.decimalPlaces=pt.dp=function(){var e=this,t=e.d.length-1,n=(t-e.e)*tr;if(t=e.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n};pt.dividedBy=pt.div=function(e){return Xl(this,new this.constructor(e))};pt.dividedToIntegerBy=pt.idiv=function(e){var t=this,n=t.constructor;return Un(Xl(t,new n(e),0,1),n.precision)};pt.equals=pt.eq=function(e){return!this.cmp(e)};pt.exponent=function(){return Xr(this)};pt.greaterThan=pt.gt=function(e){return this.cmp(e)>0};pt.greaterThanOrEqualTo=pt.gte=function(e){return this.cmp(e)>=0};pt.isInteger=pt.isint=function(){return this.e>this.d.length-2};pt.isNegative=pt.isneg=function(){return this.s<0};pt.isPositive=pt.ispos=function(){return this.s>0};pt.isZero=function(){return this.s===0};pt.lessThan=pt.lt=function(e){return this.cmp(e)<0};pt.lessThanOrEqualTo=pt.lte=function(e){return this.cmp(e)<1};pt.logarithm=pt.log=function(e){var t,n=this,r=n.constructor,a=r.precision,i=a+5;if(e===void 0)e=new r(10);else if(e=new r(e),e.s<1||e.eq(pi))throw Error(Yi+"NaN");if(n.s<1)throw Error(Yi+(n.s?"NaN":"-Infinity"));return n.eq(pi)?new r(0):(ur=!1,t=Xl(Pp(n,i),Pp(e,i),i),ur=!0,Un(t,a))};pt.minus=pt.sub=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?XU(t,e):YU(t,(e.s=-e.s,e))};pt.modulo=pt.mod=function(e){var t,n=this,r=n.constructor,a=r.precision;if(e=new r(e),!e.s)throw Error(Yi+"NaN");return n.s?(ur=!1,t=Xl(n,e,0,1).times(e),ur=!0,n.minus(t)):Un(new r(n),a)};pt.naturalExponential=pt.exp=function(){return ZU(this)};pt.naturalLogarithm=pt.ln=function(){return Pp(this)};pt.negated=pt.neg=function(){var e=new this.constructor(this);return e.s=-e.s||0,e};pt.plus=pt.add=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?YU(t,e):XU(t,(e.s=-e.s,e))};pt.precision=pt.sd=function(e){var t,n,r,a=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(hd+e);if(t=Xr(a)+1,r=a.d.length-1,n=r*tr+1,r=a.d[r],r){for(;r%10==0;r/=10)n--;for(r=a.d[0];r>=10;r/=10)n++}return e&&t>n?t:n};pt.squareRoot=pt.sqrt=function(){var e,t,n,r,a,i,o,l=this,c=l.constructor;if(l.s<1){if(!l.s)return new c(0);throw Error(Yi+"NaN")}for(e=Xr(l),ur=!1,a=Math.sqrt(+l),a==0||a==1/0?(t=Jo(l.d),(t.length+e)%2==0&&(t+="0"),a=Math.sqrt(t),e=Pf((e+1)/2)-(e<0||e%2),a==1/0?t="5e"+e:(t=a.toExponential(),t=t.slice(0,t.indexOf("e")+1)+e),r=new c(t)):r=new c(a.toString()),n=c.precision,a=o=n+3;;)if(i=r,r=i.plus(Xl(l,i,o+2)).times(.5),Jo(i.d).slice(0,o)===(t=Jo(r.d)).slice(0,o)){if
vendor: 10,173 bytes, line 854
854(t=t.slice(o-3,o+1),a==o&&t=="4999"){if(Un(i,n+1,0),i.times(i).eq(l)){r=i;break}}else if(t!="9999")break;o+=4}return ur=!0,Un(r,n)};pt.times=pt.mul=function(e){var t,n,r,a,i,o,l,c,u,d=this,h=d.constructor,f=d.d,m=(e=new h(e)).d;if(!d.s||!e.s)return new h(0);for(e.s*=d.s,n=d.e+e.e,c=f.length,u=m.length,c<u&&(i=f,f=m,m=i,o=c,c=u,u=o),i=[],o=c+u,r=o;r--;)i.push(0);for(r=u;--r>=0;){for(t=0,a=c+r;a>r;)l=i[a]+m[r]*f[a-r-1]+t,i[a--]=l%bs|0,t=l/bs|0;i[a]=(i[a]+t)%bs|0}for(;!i[--o];)i.pop();return t?++n:i.shift(),e.d=i,e.e=n,ur?Un(e,h.precision):e};pt.toDecimalPlaces=pt.todp=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(ll(e,0,If),t===void 0?t=r.rounding:ll(t,0,8),Un(n,e+Xr(n)+1,t))};pt.toExponential=function(e,t){var n,r=this,a=r.constructor;return e===void 0?n=Cd(r,!0):(ll(e,0,If),t===void 0?t=a.rounding:ll(t,0,8),r=Un(new a(r),e+1,t),n=Cd(r,!0,e+1)),n};pt.toFixed=function(e,t){var n,r,a=this,i=a.constructor;return e===void 0?Cd(a):(ll(e,0,If),t===void 0?t=i.rounding:ll(t,0,8),r=Un(new i(a),e+Xr(a)+1,t),n=Cd(r.abs(),!1,e+Xr(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};pt.toInteger=pt.toint=function(){var e=this,t=e.constructor;return Un(new t(e),Xr(e)+1,t.rounding)};pt.toNumber=function(){return+this};pt.toPower=pt.pow=function(e){var t,n,r,a,i,o,l=this,c=l.constructor,u=12,d=+(e=new c(e));if(!e.s)return new c(pi);if(l=new c(l),!l.s){if(e.s<1)throw Error(Yi+"Infinity");return l}if(l.eq(pi))return l;if(r=c.precision,e.eq(pi))return Un(l,r);if(t=e.e,n=e.d.length-1,o=t>=n,i=l.s,o){if((n=d<0?-d:d)<=GU){for(a=new c(pi),t=Math.ceil(r/tr+4),ur=!1;n%2&&(a=a.times(l),R4(a.d,t)),n=Pf(n/2),n!==0;)l=l.times(l),R4(l.d,t);return ur=!0,e.s<0?new c(pi).div(a):Un(a,r)}}else if(i<0)throw Error(Yi+"NaN");return i=i<0&&e.d[Math.max(t,n)]&1?-1:1,l.s=1,ur=!1,a=e.times(Pp(l,r+u)),ur=!0,a=ZU(a),a.s=i,a};pt.toPrecision=function(e,t){var n,r,a=this,i=a.constructor;return e===void 0?(n=Xr(a),r=Cd(a,n<=i.toExpNeg||n>=i.toExpPos)):(ll(e,1,If),t===void 0?t=i.rounding:ll(t,0,8),a=Un(new i(a),e,t),n=Xr(a),r=Cd(a,e<=n||n<=i.toExpNeg,e)),r};pt.toSignificantDigits=pt.tosd=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(ll(e,1,If),t===void 0?t=r.rounding:ll(t,0,8)),Un(new r(n),e,t)};pt.toString=pt.valueOf=pt.val=pt.toJSON=pt[Symbol.for("nodejs.util.inspect.custom")]=function(){var e=this,t=Xr(e),n=e.constructor;return Cd(e,t<=n.toExpNeg||t>=n.toExpPos)};function YU(e,t){var n,r,a,i,o,l,c,u,d=e.constructor,h=d.precision;if(!e.s||!t.s)return t.s||(t=new d(e)),ur?Un(t,h):t;if(c=e.d,u=t.d,o=e.e,a=t.e,c=c.slice(),i=o-a,i){for(i<0?(r=c,i=-i,l=u.length):(r=u,a=o,l=c.length),o=Math.ceil(h/tr),l=o>l?o+1:l+1,i>l&&(i=l,r.length=1),r.reverse();i--;)r.push(0);r.reverse()}for(l=c.length,i=u.length,l-i<0&&(i=l,r=u,u=c,c=r),n=0;i;)n=(c[--i]=c[i]+u[i]+n)/bs|0,c[i]%=bs;for(n&&(c.unshift(n),++a),l=c.length;c[--l]==0;)c.pop();return t.d=c,t.e=a,ur?Un(t,h):t}function ll(e,t,n){if(e!==~~e||e<t||e>n)throw Error(hd+e)}function Jo(e){var t,n,r,a=e.length-1,i="",o=e[0];if(a>0){for(i+=o,t=1;t<a;t++)r=e[t]+"",n=tr-r.length,n&&(i+=Ic(n)),i+=r;o=e[t],r=o+"",n=tr-r.length,n&&(i+=Ic(n))}else if(o===0)return"0";for(;o%10===0;)o/=10;return i+o}var Xl=(function(){function e(r,a){var i,o=0,l=r.length;for(r=r.slice();l--;)i=r[l]*a+o,r[l]=i%bs|0,o=i/bs|0;return o&&r.unshift(o),r}function t(r,a,i,o){var l,c;if(i!=o)c=i>o?1:-1;else for(l=c=0;l<i;l++)if(r[l]!=a[l]){c=r[l]>a[l]?1:-1;break}return c}function n(r,a,i){for(var o=0;i--;)r[i]-=o,o=r[i]<a[i]?1:0,r[i]=o*bs+r[i]-a[i];for(;!r[0]&&r.length>1;)r.shift()}return function(r,a,i,o){var l,c,u,d,h,f,m,x,g,y,b,v,w,_,k,j,N,E,A=r.constructor,C=r.s==a.s?1:-1,T=r.d,S=a.d;if(!r.s)return new A(r);if(!a.s)throw Error(Yi+"Division by zero");for(c=r.e-a.e,N=S.length,k=T.length,m=new A(C),x=m.d=[],u=0;S[u]==(T[u]||0);)++u;if(S[u]>(T[u]||0)&&--c,i==null?v=i=A.precision:o?v=i+(Xr(r)-Xr(a))+1:v=i,v<0)return new A(0);if(v=v/tr+2|0,u=0,N==1)for(d=0,S=S[0],v++;(u<k||d)&&v--;u++)w=d*bs+(T[u]||0),x[u]=w/S|0,d=w%S|0;else{for(d=bs/(S[0]+1)|0,d>1&&(S=e(S,d),T=e(T,d),N=S.length,k=T.length),_=N,g=T.slice(0,N),y=g.length;y<N;)g[y++]=0;E=S.slice(),E.unshift(0),j=S[0],S[1]>=bs/2&&++j;do d=0,l=t(S,g,N,y),l<0?(b=g[0],N!=y&&(b=b*bs+(g[1]||0)),d=b/j|0,d>1?(d>=bs&&(d=bs-1),h=e(S,d),f=h.length,y=g.length,l=t(h,g,f,y),l==1&&(d--,n(h,N<f?E:S,f))):(d==0&&(l=d=1),h=S.slice()),f=h.length,f<y&&h.unshift(0),n(g,h,y),l==-1&&(y=g.length,l=t(S,g,N,y),l<1&&(d++,n(g,N<y?E:S,y))),y=g.length):l===0&&(d++,g=[0]),x[u++]=d,l&&g[0]?g[y++]=T[_]||0:(g=[T[_]],y=1);while((_++<k||g[0]!==void 0)&&v--)}return x[0]||x.shift(),m.e=c,Un(m,o?i+Xr(m)+1:i)}})();function ZU(e,t){var n,r,a,i,o,l,c=0,u=0,d=e.constructor,h=d.precision;if(Xr(e)>16)throw Error(wE+Xr(e));if(!e.s)return new d(pi);for(ur=!1,l=h,o=new d(.03125);e.abs().gte(.1);)e=e.times(o),u+=5;for(r=Math.log(Vu(2,u))/Math.LN10*2+5|0,l+=r,n=a=i=new d(pi),d.precision=l;;){if(a=Un(a.times(e),l),n=n.times(++c),o=i.plus(Xl(a,n,l)),Jo(o.d).slice(0,l)===Jo(i.d).slice(0,l)){for(;u--;)i=Un(i.times(i),l);return d.precision=h,t==null?(ur=!0,Un(i,h)):i}i=o}}function Xr(e){for(var t=e.e*tr,n=e.d[0];n>=10;n/=10)t++;return t}function V_(e,t,n){if(t>e.LN10.sd())throw ur=!0,n&&(e.precision=n),Error(Yi+"LN10 precision limit exceeded");return Un(new e(e.LN10),t)}function Ic(e){for(var t="";e--;)t+="0";return t}function Pp(e,t){var n,r,a,i,o,l,c,u,d,h=1,f=10,m=e,x=m.d,g=m.constructor,y=g.precision;if(m.s<1)throw Error(Yi+(m.s?"NaN":"-Infinity"));if(m.eq(pi))return new g(0);if(t==null?(ur=!1,u=y):u=t,m.eq(10))return t==null&&(ur=!0),V_(g,u);if(u+=f,g.precision=u,n=Jo(x),r=n.charAt(0),i=Xr(m),Math.abs(i)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)m=m.times(e),n=Jo(m.d),r=n.charAt(0),h++;i=Xr(m),r>1?(m=new g("0."+n),i++):m=new g(r+"."+n.slice(1))}else return c=V_(g,u+2,y).times(i+""),m=Pp(new g(r+"."+n.slice(1)),u-f).plus(c),g.precision=y,t==null?(ur=!0,Un(m,y)):m;for(l=o=m=Xl(m.minus(pi),m.plus(pi),u),d=Un(m.times(m),u),a=3;;){if(o=Un(o.times(d),u),c=l.plus(Xl(o,new g(a),u)),Jo(c.d).slice(0,u)===Jo(l.d).slice(0,u))return l=l.times(2),i!==0&&(l=l.plus(V_(g,u+2,y).times(i+""))),l=Xl(l,new g(h),u),g.precision=y,t==null?(ur=!0,Un(l,y)):l;l=c,a+=2}}function P4(e,t){var n,r,a;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;)++r;for(a=t.length;t.charCodeAt(a-1)===48;)--a;if(t=t.slice(r,a),t){if(a-=r,n=n-r-1,e.e=Pf(n/tr),e.d=[],r=(n+1)%tr,n<0&&(r+=tr),r<a){for(r&&e.d.push(+t.slice(0,r)),a-=tr;r<a;)e.d.push(+t.slice(r,r+=tr));t=t.slice(r),r=tr-t.length}else r-=a;for(;r--;)t+="0";if(e.d.push(+t),ur&&(e.e>$b||e.e<-$b))throw Error(wE+n)}else e.s=0,e.e=0,e.d=[0];return e}function Un(e,t,n){var r,a,i,o,l,c,u,d,h=e.d;for(o=1,i=h[0];i>=10;i/=10)o++;if(r=t-o,r<0)r+=tr,a=t,u=h[d=0];else{if(d=Math.ceil((r+1)/tr),i=h.length,d>=i)return e;for(u=i=h[d],o=1;i>=10;i/=10)o++;r%=tr,a=r-tr+o}if(n!==void 0&&(i=Vu(10,o-a-1),l=u/i%10|0,c=t<0||h[d+1]!==void 0||u%i,c=n<4?(l||c)&&(n==0||n==(e.s<0?3:2)):l>5||l==5&&(n==4||c||n==6&&(r>0?a>0?u/Vu(10,o-a):0:h[d-1])%10&1||n==(e.s<0?8:7))),t<1||!h[0])return c?(i=Xr(e),h.length=1,t=t-i-1,h[0]=Vu(10,(tr-t%tr)%tr),e.e=Pf(-t/tr)||0):(h.length=1,h[0]=e.e=e.s=0),e;if(r==0?(h.length=d,i=1,d--):(h.length=d+1,i=Vu(10,tr-r),h[d]=a>0?(u/Vu(10,o-a)%Vu(10,a)|0)*i:0),c)for(;;)if(d==0){(h[0]+=i)==bs&&(h[0]=1,++e.e);break}else{if(h[d]+=i,h[d]!=bs)break;h[d--]=0,i=1}for(r=h.length;h[--r]===0;)h.pop();if(ur&&(e.e>$b||e.e<-$b))throw Error(wE+Xr(e));return e}function XU(e,t){var n,r,a,i,o,l,c,u,d,h,f=e.constructor,m=f.precision;if(!e.s||!t.s)return t.s?t.s=-t.s:t=new f(e),ur?Un(t,m):t;if(c=e.d,h=t.d,r=t.e,u=e.e,c=c.slice(),o=u-r,o){for(d=o<0,d?(n=c,o=-o,l=h.length):(n=h,r=u,l=c.length),a=Math.max(Math.ceil(m/tr),l)+2,o>a&&(o=a,n.length=1),n.reverse(),a=o;a--;)n.push(0);n.reverse()}else{for(a=c.length,l=h.length,d=a<l,d&&(l=a),a=0;a<l;a++)if(c[a]!=h[a]){d=c[a]<h[a];break}o=0}for(d&&(n=c,c=h,h=n,t.s=-t.s),l=c.length,a=h.length-l;a>0;--a)c[l++]=0;for(a=h.length;a>o;){if(c[--a]<h[a]){for(i=a;i&&c[--i]===0;)c[i]=bs-1;--c[i],c[a]+=bs}c[a]-=h[a]}for(;c[--l]===0;)c.pop();for(;c[0]===0;c.shift())--r;return c[0]?(t.d=c,t.e=r,ur?Un(t,m):t):new f(0)}function Cd(e,t,n){var r,a=Xr(e),i=Jo(e.d),o=i.length;return t?(n&&(r=n-o)>0?i=i.charAt(0)+"."+i.slice(1)+Ic(r):o>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+Ic(-a-1)+i,n&&(r=n-o)>0&&(i+=Ic(r))):a>=o?(i+=Ic(a+1-o),n&&(r=n-a-1)>0&&(i=i+"."+Ic(r))):((r=a+1)<o&&(i=i.slice(0,r)+"."+i.slice(r)),n&&(r=n-o)>0&&(a+1===o&&(i+="."),i+=Ic(r))),e.s<0?"-"+i:i}function R4(e,t){if(e.length>t)return e.length=t,!0}function JU(e){var t,n,r;function a(i){var o=this;if(!(o instanceof a))return new a(i);if(o.constructor=a,i instanceof a){o.s=i.s,o.e=i.e,o.d=(i=i.d)?i.slice():i;return}if(typeof i=="number"){if(i*0!==0)throw Error(hd+i);if(i>0)o.s=1;else if(i<0)i=-i,o.s=-1;else{o.s=0,o.e=0,o.d=[0];return}if(i===~~i&&i<1e7){o.e=0,o.d=[i];return}return P4(o,i.toString())}else if(typeof i!="string")throw Error(hd+i);if(i.charCodeAt(0)===45?(i=i.slice(1),o.s=-1):o.s=1,Vke.test(i))P4(o,i);else throw Error(hd+i)}if(a.prototype=pt,a.ROUND_UP=0,a.ROUND_DOWN=1,a.ROUND_CEIL=2,a.ROUND_FLOOR=3,a.ROUND_HALF_UP=4,a.ROUND_HALF_DOWN=5,a.ROUND_HALF_EVEN=6,a.ROUND_HALF_CEIL=7,a.ROUND_HALF_FLOOR=8,a.clone=JU,a.config=a.set=qke,e===void 0&&(e={}),e)for(r=["precision","rounding","toExpNeg","toExpPos","LN10"],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return a.config(e),a}function qke(e){if(!e||typeof e!="object")throw Error(Yi+"Object expected");var t,n,r,a=["precision",1,If,"rounding",0,8,"toExpNeg",-1/0,0,"toExpPos",0,1/0];for(t=0;t<a.length;t+=3)if((r=e[n=a[t]])!==void 0)if(Pf(r)===r&&r>=a[t+1]&&r<=a[t+2])this[n]=r;else throw Error(hd+n+": "+r);if((r=e[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(hd+n+": "+r);return this}var _E=JU(Hke);pi=new _E(1);const rn=_E;function QU(e){var t;return e===0?t=1:t=Math.floor(new rn(e).abs().log(10).toNumber())+1,t}function ez(e,t,n){for(var r=new rn(e),a=0,i=[];r.lt(t)&&a<1e5;)i.push(r.toNumber()),r=r.add(n),a++;return i}function Rp(e,t){return Xke(e)||Zke(e,t)||Yke(e,t)||Gke()}
854function Gke(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 855In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Yke(e,t){if(e){if(typeof e=="string")return D4(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?D4(e,t):void 0}}function D4(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Zke(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function Xke(e){if(Array.isArray(e))return e}var tz=e=>{var t=Rp(e,2),n=t[0],r=t[1],a=n,i=r;return n>r&&(a=r,i=n),[a,i]},kE=(e,t,n)=>{if(e.lte(0))return new rn(0);var r=QU(e.toNumber()),a=new rn(10).pow(r),i=e.div(a),o=r!==1?.05:.1,l=new rn(Math.ceil(i.div(o).toNumber())).add(n).mul(o),c=l.mul(a);return t?new rn(c.toNumber()):new rn(Math.ceil(c.toNumber()))},nz=(e,t,n)=>{var r;if(e.lte(0))return new rn(0);var a=[1,2,2.5,5],i=e.toNumber(),o=Math.floor(new rn(i).abs().log(10).toNumber()),l=new rn(10).pow(o),c=e.div(l).toNumber(),u=a.findIndex(m=>m>=c-1e-10);if(u===-1&&(l=l.mul(10),u=0),u+=n,u>=a.length){var d=Math.floor(u/a.length);u%=a.length,l=l.mul(new rn(10).pow(d))}var h=(r=a[u])!==null&&r!==void 0?r:1,f=new rn(h).mul(l);return t?f:new rn(Math.ceil(f.toNumber()))},Jke=(e,t,n)=>{var r=new rn(1),a=new rn(e);if(!a.isint()&&n){var i=Math.abs(e);i<1?(r=new rn(10).pow(QU(e)-1),a=new rn(Math.floor(a.div(r).toNumber())).mul(r)):i>1&&(a=new rn(Math.floor(e)))}else e===0?a=new rn(Math.floor((t-1)/2)):n||(a=new rn(Math.floor(e)));for(var o=Math.floor((t-1)/2),l=[],c=0;c<t;c++)l.push(a.add(new rn(c-o).mul(r)).toNumber());return l},rz=function(t,n,r,a){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0,o=arguments.length>5&&arguments[5]!==void 0?arguments[5]:kE;if(!Number.isFinite((n-t)/(r-1)))return{step:new rn(0),tickMin:new rn(0),tickMax:new rn(0)};var l=o(new rn(n).sub(t).div(r-1),a,i),c;t<=0&&n>=0?c=new rn(0):(c=new rn(t).add(n).div(2),c=c.sub(new rn(c).mod(l)));var u=Math.ceil(c.sub(t).div(l).toNumber()),d=Math.ceil(new rn(n).sub(c).div(l).toNumber()),h=u+d+1;return h>r?rz(t,n,r,a,i+1,o):(h<r&&(d=n>0?d+(r-h):d,u=n>0?u:u+(r-h)),{step:l,tickMin:c.sub(new rn(u).mul(l)),tickMax:c.add(new rn(d).mul(l))})},M4=function(t){var n=Rp(t,2),r=n[0],a=n[1],i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"auto",c=Math.max(i,2),u=tz([r,a]),d=Rp(u,2),h=d[0],f=d[1];if(h===-1/0||f===1/0){var m=f===1/0?[h,...Array(i-1).fill(1/0)]:[...Array(i-1).fill(-1/0),f];return r>a?m.reverse():m}if(h===f)return Jke(h,i,o);var x=l==="snap125"?nz:kE,g=rz(h,f,c,o,0,x),y=g.step,b=g.tickMin,v=g.tickMax,w=ez(b,v.add(new rn(.1).mul(y)),y);return r>a?w.reverse():w},$4=function(t,n){var r=Rp(t,2),a=r[0],i=r[1],o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=arguments.length>3&&arguments[3]!==void 0?arguments[3]:"auto",c=tz([a,i]),u=Rp(c,2),d=u[0],h=u[1];if(d===-1/0||h===1/0)return[a,i];if(d===h)return[d];var f=l==="snap125"?nz:kE,m=Math.max(n,2),x=f(new rn(h).sub(d).div(m-1),o,0),g=[...ez(new rn(d),new rn(h),x),h];if(o===!1){g=g.map(b=>Math.round(b));var y=g.length-1;y>0&&g[y]===g[y-1]&&(g=g.slice(0,y))}return a>i?g.reverse():g},sz=e=>e.rootProps.maxBarSize,Qke=e=>e.rootProps.barGap,az=e=>e.rootProps.barCategoryGap,eje=e=>e.rootProps.barSize,Ex=e=>e.rootProps.stackOffset,iz=e=>e.rootProps.reverseStackOrder,jE=e=>e.options.chartName,NE=e=>e.rootProps.syncId,oz=e=>e.rootProps.syncMethod,SE=e=>e.options.eventEmitter,tje=e=>e.rootProps.baseValue,_r={grid:-100,barBackground:-50,area:100,cursorRectangle:200,bar:300,line:400,axis:500,scatter:600,activeBar:1e3,cursorLine:1100,activeDot:1200,label:2e3},Pu={allowDecimals:!1,allowDataOverflow:!1,angleAxisId:0,reversed:!1,scale:"auto",tick:!0,type:"auto"},Fo={allowDataOverflow:!1,allowDecimals:!1,allowDuplicatedCategory:!0,includeHidden:!1,radiusAxisId:0,reversed:!1,scale:"auto",tick:!0,tickCount:5,type:"auto"},F0=(e,t)=>{if(!(!e||!t))return e!=null&&e.reversed?[t[1],t[0]]:t};function B0(e,t,n){if(n!=="auto")return n;if(e!=null)return Oo(e,t)?"category":"number"}function L4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}
855function Lb(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?L4(Object(n),!0).forEach(function(r){nje(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):L4(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function nje(e,t,n){return(t=rje(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function rje(e){var t=sje(e,"string");return typeof t=="symbol"?t:t+""}function sje(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var F4={allowDataOverflow:Pu.allowDataOverflow,allowDecimals:Pu.allowDecimals,allowDuplicatedCategory:!1,dataKey:void 0,domain:void 0,id:Pu.angleAxisId,includeHidden:!1,name:void 0,reversed:Pu.reversed,scale:Pu.scale,tick:Pu.tick,tickCount:void 0,ticks:void 0,type:Pu.type,unit:void 0,niceTicks:"auto"},B4={allowDataOverflow:Fo.allowDataOverflow,allowDecimals:Fo.allowDecimals,allowDuplicatedCategory:Fo.allowDuplicatedCategory,dataKey:void 0,domain:void 0,id:Fo.radiusAxisId,includeHidden:Fo.includeHidden,name:void 0,reversed:Fo.reversed,scale:Fo.scale,tick:Fo.tick,tickCount:Fo.tickCount,ticks:void 0,type:Fo.type,unit:void 0,niceTicks:"auto"},aje=(e,t)=>{if(t!=null)return e.polarAxis.angleAxis[t]},CE=be([aje,gE],(e,t)=>{var n;if(e!=null)return e;var r=(n=B0(t,"angleAxis",F4.type))!==null&&n!==void 0?n:"category";return Lb(Lb({},F4),{},{type:r})}),ije=(e,t)=>e.polarAxis.radiusAxis[t],EE=be([ije,gE],(e,t)=>{var n;if(e!=null)return e;var r=(n=B0(t,"radiusAxis",B4.type))!==null&&n!==void 0?n:"category";return Lb(Lb({},B4),{},{type:r})}),U0=e=>e.polarOptions,AE=be([xl,gl,ds],UU),lz=be([U0,AE],(e,t)=>{if(e!=null)return ca(e.innerRadius,t,0)}),cz=be([U0,AE],(e,t)=>{if(e!=null)return ca(e.outerRadius,t,t*.8)}),oje=e=>{if(e==null)return[0,0];var t=e.startAngle,n=e.endAngle;return[t,n]},uz=be([U0],oje);be([CE,uz],F0);var dz=be([AE,lz,cz],(e,t,n)=>{if(!(e==null||t==null||n==null))return[t,n]});be([EE,dz],F0);var hz=be([sn,U0,lz,cz,xl,gl],(e,t,n,r,a,i)=>{if(!(e!=="centric"&&e!=="radial"||t==null||n==null||r==null)){var o=t.cx,l=t.cy,c=t.startAngle,u=t.endAngle;return{cx:ca(o,a,a/2),cy:ca(l,i,i/2),innerRadius:n,outerRadius:r,startAngle:c,endAngle:u,clockWise:!1}}}),Ar=(e,t)=>t,Ax=(e,t,n)=>n;function z0(e){return e==null?void 0:e.id}function fz(e,t,n){var r=t.chartData,a=r===void 0?[]:r,i=n.allowDuplicatedCategory,o=n.dataKey,l=new Map;return e.forEach(c=>{var u,d=(u=c.data)!==null&&u!==void 0?u:a;if(!(d==null||d.length===0)){var h=z0(c);d.forEach((f,m)=>{var x=o==null||i?m:String(hn(f,o,null)),g=hn(f,c.dataKey,0),y;l.has(x)?y=l.get(x):y={},Object.assign(y,{[h]:g}),l.set(x,y)})}}),Array.from(l.values())}function W0(e){return"stackId"in e&&e.stackId!=null&&e.dataKey!=null}var Tx=(e,t)=>e===t?!0:e==null||t==null?!1:e[0]===t[0]&&e[1]===t[1];function K0(e,t){return Array.isArray(e)&&Array.isArray(t)&&e.length===0&&t.length===0?!0:e===t}function lje(e,t){if(e.length===t.length){for(var n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}return!1}var Ss=e=>{var t=sn(e);return t==="horizontal"?"xAxis":t==="vertical"?"yAxis":t==="centric"?"angleAxis":"radiusAxis"},Rf=e=>e.tooltip.settings.axisId;function TE(e){if(e!=null){var t=e.ticks,n=e.bandwidth,r=e.range(),a=[Math.min(...r),Math.max(...r)];return{domain:()=>e.domain(),range:(function(i){function o(){return i.apply(this,arguments)}return o.toString=function(){return i.toString()},o})(()=>a),rangeMin:()=>a[0],rangeMax:()=>a[1],isInRange(i){var o=a[0],l=a[1];return o<=l?i>=o&&i<=l:i>=l&&i<=o},bandwidth:n?()=>n.call(e):void 0,ticks:t?i=>t.call(e,i):void 0,map:(i,o)=>{var l=e(i);if(l!=null){if(e.bandwidth&&o!==null&&o!==void 0&&o.position){var c=e.bandwidth();switch(o.position){case"middle":l+=c/2;break;case"end":l+=c;break}}return l}}}}}var mz=(e,t)=>{if(t!=null)switch(e){case"linear":{if(!tl(t)){for(var n,r,a=0;a<t.length;a++){var i=t[a];Mt(i)&&((n===void 0||i<n)&&(n=i),(r===void 0||i>r)&&(r=i))}return n!==void 0&&r!==void 0?[n,r]:void 0}return t}default:return t}};function qc(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function cje(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function OE(e){let t,n,r;e.length!==2?(t=qc,n=(l,c)=>qc(e(l),c),r=(l,c)=>e(l)-c):(t=e===qc||e===cje?e:uje,n=e,r=e);function a(l,c,u=0,d=l.length){if(u<d){if(t(c,c)!==0)return d;do{const h=u+d>>>1;n(l[h],c)<0?u=h+1:d=h}while(u<d)}return u}function i(l,c,u=0,d=l.length){if(u<d){if(t(c,c)!==0)return d;do{const h=u+d>>>1;n(l[h],c)<=0?u=h+1:d=h}while(u<d)}return u}function o(l,c,u=0,d=l.length){const h=a(l,c,u,d-1);return h>u&&r(l[h-1],c)>-r(l[h],c)?h-1:h}return{left:a,center:o,right:i}}function uje(){return 0}function pz(e){return e===null?NaN:+e}function*dje(e,t){for(let n of e)n!=null&&(n=+n)>=n&&(yield n)}const hje=OE(qc),Ox=hje.right;OE(pz).center;class U4 extends Map{constructor(t,n=pje){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),t!=null)for(const[r,a]of t)this.set(r,a)}get(t){return super.get(z4(this,t))}has(t){return super.has(z4(this,t))}set(t,n){return super.set(fje(this,t),n)}delete(t){return super.delete(mje(this,t))}}function z4({_intern:e,_key:t},n){const r=t(n);return e.has(r)?e.get(r):n}function fje({_intern:e,_key:t},n){const r=t(n);return e.has(r)?e.get(r):(e.set(r,n),n)}function mje({_intern:e,_key:t},n){const r=t(n);return e.has(r)&&(n=e.get(r),e.delete(r)),n}function pje(e){return e!==null&&typeof e=="object"?e.valueOf():e}function xje(e=qc){if(e===qc)return xz;if(typeof e!="function")throw new TypeError("compare is not a function");return(t,n)=>{const r=e(t,n);return r||r===0?r:(e(n,n)===0)-(e(t,t)===0)}}function xz(e,t){return(e==null||!(e>=e))-(t==null||!(t>=t))||(e<t?-1:e>t?1:0)}const gje=Math.sqrt(50),yje=Math.sqrt(10),bje=Math.sqrt(2);function Fb(e,t,n){const r=(t-e)/Math.max(0,n),a=Math.floor(Math.log10(r)),i=r/Math.pow(10,a),o=i>=gje?10:i>=yje?5:i>=bje?2:1;let l,c,u;return a<0?(u=Math.pow(10,-a)/o,l=Math.round(e*u),c=Math.round(t*u),l/u<e&&++l,c/u>t&&--c,u=-u):(u=Math.pow(10,a)*o,l=Math.round(e/u),c=Math.round(t/u),l*u<e&&++l,c*u>t&&--c),c<l&&.5<=n&&n<2?Fb(e,t,n*2):[l,c,u]}function cS(e,t,n){if(t=+t,e=+e,n=+n,!(n>0))return[];if(e===t)return[e];
855const r=t<e,[a,i,o]=r?Fb(t,e,n):Fb(e,t,n);if(!(i>=a))return[];const l=i-a+1,c=new Array(l);if(r)if(o<0)for(let u=0;u<l;++u)c[u]=(i-u)/-o;else for(let u=0;u<l;++u)c[u]=(i-u)*o;else if(o<0)for(let u=0;u<l;++u)c[u]=(a+u)/-o;else for(let u=0;u<l;++u)c[u]=(a+u)*o;return c}function uS(e,t,n){return t=+t,e=+e,n=+n,Fb(e,t,n)[2]}function dS(e,t,n){t=+t,e=+e,n=+n;const r=t<e,a=r?uS(t,e,n):uS(e,t,n);return(r?-1:1)*(a<0?1/-a:a)}function W4(e,t){let n;for(const r of e)r!=null&&(n<r||n===void 0&&r>=r)&&(n=r);return n}function K4(e,t){let n;for(const r of e)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function gz(e,t,n=0,r=1/0,a){if(t=Math.floor(t),n=Math.floor(Math.max(0,n)),r=Math.floor(Math.min(e.length-1,r)),!(n<=t&&t<=r))return e;for(a=a===void 0?xz:xje(a);r>n;){if(r-n>600){const c=r-n+1,u=t-n+1,d=Math.log(c),h=.5*Math.exp(2*d/3),f=.5*Math.sqrt(d*h*(c-h)/c)*(u-c/2<0?-1:1),m=Math.max(n,Math.floor(t-u*h/c+f)),x=Math.min(r,Math.floor(t+(c-u)*h/c+f));gz(e,t,m,x,a)}const i=e[t];let o=n,l=r;for(um(e,n,t),a(e[r],i)>0&&um(e,n,r);o<l;){for(um(e,o,l),++o,--l;a(e[o],i)<0;)++o;for(;a(e[l],i)>0;)--l}a(e[n],i)===0?um(e,n,l):(++l,um(e,l,r)),l<=t&&(n=l+1),t<=l&&(r=l-1)}return e}function um(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function vje(e,t,n){if(e=Float64Array.from(dje(e)),!(!(r=e.length)||isNaN(t=+t))){if(t<=0||r<2)return K4(e);if(t>=1)return W4(e);var r,a=(r-1)*t,i=Math.floor(a),o=W4(gz(e,i).subarray(0,i+1)),l=K4(e.subarray(i+1));return o+(l-o)*(a-i)}}function wje(e,t,n=pz){if(!(!(r=e.length)||isNaN(t=+t))){if(t<=0||r<2)return+n(e[0],0,e);if(t>=1)return+n(e[r-1],r-1,e);var r,a=(r-1)*t,i=Math.floor(a),o=+n(e[i],i,e),l=+n(e[i+1],i+1,e);return o+(l-o)*(a-i)}}function _je(e,t,n){e=+e,t=+t,n=(a=arguments.length)<2?(t=e,e=0,1):a<3?1:+n;for(var r=-1,a=Math.max(0,Math.ceil((t-e)/n))|0,i=new Array(a);++r<a;)i[r]=e+r*n;return i}function eo(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e);break}return this}function gc(e,t){switch(arguments.length){case 0:break;case 1:{typeof e=="function"?this.interpolator(e):this.range(e);break}default:{this.domain(e),typeof t=="function"?this.interpolator(t):this.range(t);break}}return this}const hS=Symbol("implicit");function IE(){var e=new U4,t=[],n=[],r=hS;function a(i){let o=e.get(i);if(o===void 0){if(r!==hS)return r;e.set(i,o=t.push(i)-1)}return n[o%n.length]}return a.domain=function(i){if(!arguments.length)return t.slice();t=[],e=new U4;for(const o of i)e.has(o)||e.set(o,t.push(o)-1);return a},a.range=function(i){return arguments.length?(n=Array.from(i),a):n.slice()},a.unknown=function(i){return arguments.length?(r=i,a):r},a.copy=function(){return IE(t,n).unknown(r)},eo.apply(a,arguments),a}function PE(){var e=IE().unknown(void 0),t=e.domain,n=e.range,r=0,a=1,i,o,l=!1,c=0,u=0,d=.5;delete e.unknown;function h(){var f=t().length,m=a<r,x=m?a:r,g=m?r:a;i=(g-x)/Math.max(1,f-c+u*2),l&&(i=Math.floor(i)),x+=(g-x-i*(f-c))*d,o=i*(1-c),l&&(x=Math.round(x),o=Math.round(o));var y=_je(f).map(function(b){return x+i*b});return n(m?y.reverse():y)}return e.domain=function(f){return arguments.length?(t(f),h()):t()},e.range=function(f){return arguments.length?([r,a]=f,r=+r,a=+a,h()):[r,a]},e.rangeRound=function(f){return[r,a]=f,r=+r,a=+a,l=!0,h()},e.bandwidth=function(){return o},e.step=function(){return i},e.round=function(f){return arguments.length?(l=!!f,h()):l},e.padding=function(f){return arguments.length?(c=Math.min(1,u=+f),h()):c},e.paddingInner=function(f){return arguments.length?(c=Math.min(1,f),h()):c},e.paddingOuter=function(f){return arguments.length?(u=+f,h()):u},e.align=function(f){return arguments.length?(d=Math.max(0,Math.min(1,f)),h()):d},e.copy=function(){return PE(t(),[r,a]).round(l).paddingInner(c).paddingOuter(u).align(d)},eo.apply(h(),arguments)}function yz(e){var t=e.copy;return e.padding=e.paddingOuter,delete e.paddingInner,delete e.paddingOuter,e.copy=function(){return yz(t())},e}function kje(){return yz(PE.apply(null,arguments).paddingInner(1))}function RE(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function bz(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Ix(){}var Dp=.7,Bb=1/Dp,Fh="\\s*([+-]?\\d+)\\s*",Mp="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",nl="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",jje=/^#([0-9a-f]{3,8})$/,Nje=new RegExp(`^rgb\\(${Fh},${Fh},${Fh}\\)$`),Sje=new RegExp(`^rgb\\(${nl},${nl},${nl}\\)$`),Cje=new RegExp(`^rgba\\(${Fh},${Fh},${Fh},${Mp}\\)$`),Eje=new RegExp(`^rgba\\(${nl},${nl},${nl},${Mp}\\)$`),Aje=new RegExp(`^hsl\\(${Mp},${nl},${nl}\\)$`),Tje=new RegExp(`^hsla\\(${Mp},${nl},${nl},${Mp}\\)$`),H4={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};RE(Ix,$p,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:V4,formatHex:V4,formatHex8:Oje,formatHsl:Ije,formatRgb:q4,toString:q4});function V4(){return this.rgb().formatHex()}function Oje(){return this.rgb().formatHex8()}function Ije(){return vz(this).formatHsl()}function q4(){return this.rgb().formatRgb()}function $p(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=jje.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?G4(t):n===3?new Qa(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?Eg(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Eg(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=Nje.exec(e))?new Qa(t[1],t[2],t[3],1):(t=Sje.exec(e))?new Qa(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Cje.exec(e))?Eg(t[1],t[2],t[3],t[4]):(t=Eje.exec(e))?Eg(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Aje.exec(e))?X4(t[1],t[2]/100,t[3]/100,1):(t=Tje.exec(e))?X4(t[1],t[2]/100,t[3]/100,t[4]):H4.hasOwnProperty(e)?G4(H4[e]):e==="transparent"?new Qa(NaN,NaN,NaN,0):null}function G4(e){return new Qa(e>>16&255,e>>8&255,e&255,1)}function Eg(e,t,n,r){return r<=0&&(e=t=n=NaN),new Qa(e,t,n,r)}function Pje(e){return e instanceof Ix||(e=$p(e)),e?(e=e.rgb(),new Qa(e.r,e.g,e.b,e.opacity)):new Qa}function fS(e,t,n,r){return arguments.length===1?Pje(e):new Qa(e,t,n,r??1)}function Qa(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}
vendor: 6,655 bytes, line 855
855RE(Qa,fS,bz(Ix,{brighter(e){return e=e==null?Bb:Math.pow(Bb,e),new Qa(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Dp:Math.pow(Dp,e),new Qa(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Qa(fd(this.r),fd(this.g),fd(this.b),Ub(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Y4,formatHex:Y4,formatHex8:Rje,formatRgb:Z4,toString:Z4}));function Y4(){return`#${ed(this.r)}${ed(this.g)}${ed(this.b)}`}function Rje(){return`#${ed(this.r)}${ed(this.g)}${ed(this.b)}${ed((isNaN(this.opacity)?1:this.opacity)*255)}`}function Z4(){const e=Ub(this.opacity);return`${e===1?"rgb(":"rgba("}${fd(this.r)}, ${fd(this.g)}, ${fd(this.b)}${e===1?")":`, ${e})`}`}function Ub(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function fd(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function ed(e){return e=fd(e),(e<16?"0":"")+e.toString(16)}function X4(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new xo(e,t,n,r)}function vz(e){if(e instanceof xo)return new xo(e.h,e.s,e.l,e.opacity);if(e instanceof Ix||(e=$p(e)),!e)return new xo;if(e instanceof xo)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,a=Math.min(t,n,r),i=Math.max(t,n,r),o=NaN,l=i-a,c=(i+a)/2;return l?(t===i?o=(n-r)/l+(n<r)*6:n===i?o=(r-t)/l+2:o=(t-n)/l+4,l/=c<.5?i+a:2-i-a,o*=60):l=c>0&&c<1?0:o,new xo(o,l,c,e.opacity)}function Dje(e,t,n,r){return arguments.length===1?vz(e):new xo(e,t,n,r??1)}function xo(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}RE(xo,Dje,bz(Ix,{brighter(e){return e=e==null?Bb:Math.pow(Bb,e),new xo(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Dp:Math.pow(Dp,e),new xo(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,a=2*n-r;return new Qa(q_(e>=240?e-240:e+120,a,r),q_(e,a,r),q_(e<120?e+240:e-120,a,r),this.opacity)},clamp(){return new xo(J4(this.h),Ag(this.s),Ag(this.l),Ub(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=Ub(this.opacity);return`${e===1?"hsl(":"hsla("}${J4(this.h)}, ${Ag(this.s)*100}%, ${Ag(this.l)*100}%${e===1?")":`, ${e})`}`}}));function J4(e){return e=(e||0)%360,e<0?e+360:e}function Ag(e){return Math.max(0,Math.min(1,e||0))}function q_(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const DE=e=>()=>e;function Mje(e,t){return function(n){return e+n*t}}function $je(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function Lje(e){return(e=+e)==1?wz:function(t,n){return n-t?$je(t,n,e):DE(isNaN(t)?n:t)}}function wz(e,t){var n=t-e;return n?Mje(e,n):DE(isNaN(e)?t:e)}const Q4=(function e(t){var n=Lje(t);function r(a,i){var o=n((a=fS(a)).r,(i=fS(i)).r),l=n(a.g,i.g),c=n(a.b,i.b),u=wz(a.opacity,i.opacity);return function(d){return a.r=o(d),a.g=l(d),a.b=c(d),a.opacity=u(d),a+""}}return r.gamma=e,r})(1);function Fje(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),a;return function(i){for(a=0;a<n;++a)r[a]=e[a]*(1-i)+t[a]*i;return r}}function Bje(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Uje(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,a=new Array(r),i=new Array(n),o;for(o=0;o<r;++o)a[o]=Df(e[o],t[o]);for(;o<n;++o)i[o]=t[o];return function(l){for(o=0;o<r;++o)i[o]=a[o](l);return i}}function zje(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function zb(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function Wje(e,t){var n={},r={},a;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(a in t)a in e?n[a]=Df(e[a],t[a]):r[a]=t[a];return function(i){for(a in n)r[a]=n[a](i);return r}}var mS=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,G_=new RegExp(mS.source,"g");function Kje(e){return function(){return e}}function Hje(e){return function(t){return e(t)+""}}function Vje(e,t){var n=mS.lastIndex=G_.lastIndex=0,r,a,i,o=-1,l=[],c=[];for(e=e+"",t=t+"";(r=mS.exec(e))&&(a=G_.exec(t));)(i=a.index)>n&&(i=t.slice(n,i),l[o]?l[o]+=i:l[++o]=i),(r=r[0])===(a=a[0])?l[o]?l[o]+=a:l[++o]=a:(l[++o]=null,c.push({i:o,x:zb(r,a)})),n=G_.lastIndex;return n<t.length&&(i=t.slice(n),l[o]?l[o]+=i:l[++o]=i),l.length<2?c[0]?Hje(c[0].x):Kje(t):(t=c.length,function(u){for(var d=0,h;d<t;++d)l[(h=c[d]).i]=h.x(u);return l.join("")})}function Df(e,t){var n=typeof t,r;return t==null||n==="boolean"?DE(t):(n==="number"?zb:n==="string"?(r=$p(t))?(t=r,Q4):Vje:t instanceof $p?Q4:t instanceof Date?zje:Bje(t)?Fje:Array.isArray(t)?Uje:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?Wje:zb)(e,t)}function ME(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}function qje(e,t){t===void 0&&(t=e,e=Df);for(var n=0,r=t.length-1,a=t[0],i=new Array(r<0?0:r);n<r;)i[n]=e(a,a=t[++n]);return function(o){var l=Math.max(0,Math.min(r-1,Math.floor(o*=r)));return i[l](o-l)}}function Gje(e){return function(){return e}}function Wb(e){return+e}var e5=[0,1];function Aa(e){return e}function pS(e,t){return(t-=e=+e)?function(n){return(n-e)/t}:Gje(isNaN(t)?NaN:.5)}function Yje(e,t){var n;return e>t&&(n=e,e=t,t=n),function(r){return Math.max(e,Math.min(t,r))}}function Zje(e,t,n){var r=e[0],a=e[1],i=t[0],o=t[1];return a<r?(r=pS(a,r),i=n(o,i)):(r=pS(r,a),i=n(i,o)),function(l){return i(r(l))}}function Xje(e,t,n){var r=Math.min(e.length,t.length)-1,a=new Array(r),i=new Array(r),o=-1;for(e[r]<e[0]&&(e=e.slice().reverse(),t=t.slice().reverse());++o<r;)a[o]=pS(e[o],e[o+1]),i[o]=n(t[o],t[o+1]);return function(l){var c=Ox(e,l,1,r)-1;return i[c](a[c](l))}}function Px(e,t){return t.domain(e.domain()).range(e.range()).interpolate(e.interpolate()).clamp(e.clamp()).unknown(e.unknown())}function H0(){var e=e5,t=e5,n=Df,r,a,i,o=Aa,l,c,u;function d(){var f=Math.min(e.length,t.length);return o!==Aa&&(o=Yje(e[0],e[f-1])),l=f>2?Xje:Zje,c=u=null,h}function h(f){return f==null||isNaN(f=+f)?i:(c||(c=l(e.map(r),t,n)))(r(o(f)))}return h.invert=function(f){return o(a((u||(u=l(t,e.map(r),zb)))(f)))},h.domain=function(f){return arguments.length?(e=Array.from(f,Wb),d()):e.slice()},h.range=function(f){return arguments.length?(t=Array.from(f),d()):t.slice()},h.rangeRound=function(f){return t=Array.from(f),n=ME,d()},h.clamp=function(f){return arguments.length?(o=f?!0:Aa,d()):o!==Aa},h.interpolate=function(f){return arguments.length?(n=f,d()):n},h.unknown=function(f){return arguments.length?(i=f,h):i},function(f,m){return r=f,a=m,d()}}function $E(){return H0()(Aa,Aa)}
vendor: 4,597 bytes, line 855
855function Jje(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function Kb(e,t){if(!isFinite(e)||e===0)return null;var n=(e=t?e.toExponential(t-1):e.toExponential()).indexOf("e"),r=e.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+e.slice(n+1)]}function Xh(e){return e=Kb(Math.abs(e)),e?e[1]:NaN}function Qje(e,t){return function(n,r){for(var a=n.length,i=[],o=0,l=e[0],c=0;a>0&&l>0&&(c+l+1>r&&(l=Math.max(1,r-c)),i.push(n.substring(a-=l,a+l)),!((c+=l+1)>r));)l=e[o=(o+1)%e.length];return i.reverse().join(t)}}function eNe(e){return function(t){return t.replace(/[0-9]/g,function(n){return e[+n]})}}var tNe=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Lp(e){if(!(t=tNe.exec(e)))throw new Error("invalid format: "+e);var t;return new LE({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}Lp.prototype=LE.prototype;function LE(e){this.fill=e.fill===void 0?" ":e.fill+"",this.align=e.align===void 0?">":e.align+"",this.sign=e.sign===void 0?"-":e.sign+"",this.symbol=e.symbol===void 0?"":e.symbol+"",this.zero=!!e.zero,this.width=e.width===void 0?void 0:+e.width,this.comma=!!e.comma,this.precision=e.precision===void 0?void 0:+e.precision,this.trim=!!e.trim,this.type=e.type===void 0?"":e.type+""}LE.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function nNe(e){e:for(var t=e.length,n=1,r=-1,a;n<t;++n)switch(e[n]){case".":r=a=n;break;case"0":r===0&&(r=n),a=n;break;default:if(!+e[n])break e;r>0&&(r=0);break}return r>0?e.slice(0,r)+e.slice(a+1):e}var Hb;function rNe(e,t){var n=Kb(e,t);if(!n)return Hb=void 0,e.toPrecision(t);var r=n[0],a=n[1],i=a-(Hb=Math.max(-8,Math.min(8,Math.floor(a/3)))*3)+1,o=r.length;return i===o?r:i>o?r+new Array(i-o+1).join("0"):i>0?r.slice(0,i)+"."+r.slice(i):"0."+new Array(1-i).join("0")+Kb(e,Math.max(0,t+i-1))[0]}function t5(e,t){var n=Kb(e,t);if(!n)return e+"";var r=n[0],a=n[1];return a<0?"0."+new Array(-a).join("0")+r:r.length>a+1?r.slice(0,a+1)+"."+r.slice(a+1):r+new Array(a-r.length+2).join("0")}const n5={"%":(e,t)=>(e*100).toFixed(t),b:e=>Math.round(e).toString(2),c:e=>e+"",d:Jje,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:e=>Math.round(e).toString(8),p:(e,t)=>t5(e*100,t),r:t5,s:rNe,X:e=>Math.round(e).toString(16).toUpperCase(),x:e=>Math.round(e).toString(16)};function r5(e){return e}var s5=Array.prototype.map,a5=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function sNe(e){var t=e.grouping===void 0||e.thousands===void 0?r5:Qje(s5.call(e.grouping,Number),e.thousands+""),n=e.currency===void 0?"":e.currency[0]+"",r=e.currency===void 0?"":e.currency[1]+"",a=e.decimal===void 0?".":e.decimal+"",i=e.numerals===void 0?r5:eNe(s5.call(e.numerals,String)),o=e.percent===void 0?"%":e.percent+"",l=e.minus===void 0?"â":e.minus+"",c=e.nan===void 0?"NaN":e.nan+"";function u(h,f){h=Lp(h);var m=h.fill,x=h.align,g=h.sign,y=h.symbol,b=h.zero,v=h.width,w=h.comma,_=h.precision,k=h.trim,j=h.type;j==="n"?(w=!0,j="g"):n5[j]||(_===void 0&&(_=12),k=!0,j="g"),(b||m==="0"&&x==="=")&&(b=!0,m="0",x="=");var N=(f&&f.prefix!==void 0?f.prefix:"")+(y==="$"?n:y==="#"&&/[boxX]/.test(j)?"0"+j.toLowerCase():""),E=(y==="$"?r:/[%p]/.test(j)?o:"")+(f&&f.suffix!==void 0?f.suffix:""),A=n5[j],C=/[defgprs%]/.test(j);_=_===void 0?6:/[gprs]/.test(j)?Math.max(1,Math.min(21,_)):Math.max(0,Math.min(20,_));function T(S){var O=N,R=E,I,$,P;if(j==="c")R=A(S)+R,S="";else{S=+S;var F=S<0||1/S<0;if(S=isNaN(S)?c:A(Math.abs(S),_),k&&(S=nNe(S)),F&&+S==0&&g!=="+"&&(F=!1),O=(F?g==="("?g:l:g==="-"||g==="("?"":g)+O,R=(j==="s"&&!isNaN(S)&&Hb!==void 0?a5[8+Hb/3]:"")+R+(F&&g==="("?")":""),C){for(I=-1,$=S.length;++I<$;)if(P=S.charCodeAt(I),48>P||P>57){R=(P===46?a+S.slice(I+1):S.slice(I))+R,S=S.slice(0,I);break}}}w&&!b&&(S=t(S,1/0));var Z=O.length+S.length+R.length,D=Z<v?new Array(v-Z+1).join(m):"";switch(w&&b&&(S=t(D+S,D.length?v-R.length:1/0),D=""),x){case"<":S=O+S+R+D;break;case"=":S=O+D+S+R;break;case"^":S=D.slice(0,Z=D.length>>1)+O+S+R+D.slice(Z);break;default:S=D+O+S+R;break}return i(S)}return T.toString=function(){return h+""},T}function d(h,f){var m=Math.max(-8,Math.min(8,Math.floor(Xh(f)/3)))*3,x=Math.pow(10,-m),g=u((h=Lp(h),h.type="f",h),{suffix:a5[8+m/3]});return function(y){return g(x*y)}}return{format:u,formatPrefix:d}}var Tg,FE,_z;
855aNe({thousands:",",grouping:[3],currency:["$",""]});function aNe(e){return Tg=sNe(e),FE=Tg.format,_z=Tg.formatPrefix,Tg}function iNe(e){return Math.max(0,-Xh(Math.abs(e)))}function oNe(e,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Xh(t)/3)))*3-Xh(Math.abs(e)))}function lNe(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,Xh(t)-Xh(e))+1}function kz(e,t,n,r){var a=dS(e,t,n),i;switch(r=Lp(r??",f"),r.type){case"s":{var o=Math.max(Math.abs(e),Math.abs(t));return r.precision==null&&!isNaN(i=oNe(a,o))&&(r.precision=i),_z(r,o)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(i=lNe(a,Math.max(Math.abs(e),Math.abs(t))))&&(r.precision=i-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(i=iNe(a))&&(r.precision=i-(r.type==="%")*2);break}}return FE(r)}function _u(e){var t=e.domain;return e.ticks=function(n){var r=t();return cS(r[0],r[r.length-1],n??10)},e.tickFormat=function(n,r){var a=t();return kz(a[0],a[a.length-1],n??10,r)},e.nice=function(n){n==null&&(n=10);var r=t(),a=0,i=r.length-1,o=r[a],l=r[i],c,u,d=10;for(l<o&&(u=o,o=l,l=u,u=a,a=i,i=u);d-- >0;){if(u=uS(o,l,n),u===c)return r[a]=o,r[i]=l,t(r);if(u>0)o=Math.floor(o/u)*u,l=Math.ceil(l/u)*u;else if(u<0)o=Math.ceil(o*u)/u,l=Math.floor(l*u)/u;else break;c=u}return e},e}function jz(){var e=$E();return e.copy=function(){return Px(e,jz())},eo.apply(e,arguments),_u(e)}function Nz(e){var t;function n(r){return r==null||isNaN(r=+r)?t:r}return n.invert=n,n.domain=n.range=function(r){return arguments.length?(e=Array.from(r,Wb),n):e.slice()},n.unknown=function(r){return arguments.length?(t=r,n):t},n.copy=function(){return Nz(e).unknown(t)},e=arguments.length?Array.from(e,Wb):[0,1],_u(n)}function Sz(e,t){e=e.slice();var n=0,r=e.length-1,a=e[n],i=e[r],o;return i<a&&(o=n,n=r,r=o,o=a,a=i,i=o),e[n]=t.floor(a),e[r]=t.ceil(i),e}function i5(e){return Math.log(e)}function o5(e){return Math.exp(e)}function cNe(e){return-Math.log(-e)}function uNe(e){return-Math.exp(-e)}function dNe(e){return isFinite(e)?+("1e"+e):e<0?0:e}function hNe(e){return e===10?dNe:e===Math.E?Math.exp:t=>Math.pow(e,t)}function fNe(e){return e===Math.E?Math.log:e===10&&Math.log10||e===2&&Math.log2||(e=Math.log(e),t=>Math.log(t)/e)}function l5(e){return(t,n)=>-e(-t,n)}function BE(e){const t=e(i5,o5),n=t.domain;let r=10,a,i;function o(){return a=fNe(r),i=hNe(r),n()[0]<0?(a=l5(a),i=l5(i),e(cNe,uNe)):e(i5,o5),t}return t.base=function(l){return arguments.length?(r=+l,o()):r},t.domain=function(l){return arguments.length?(n(l),o()):n()},t.ticks=l=>{const c=n();let u=c[0],d=c[c.length-1];const h=d<u;h&&([u,d]=[d,u]);let f=a(u),m=a(d),x,g;const y=l==null?10:+l;let b=[];if(!(r%1)&&m-f<y){if(f=Math.floor(f),m=Math.ceil(m),u>0){for(;f<=m;++f)for(x=1;x<r;++x)if(g=f<0?x/i(-f):x*i(f),!(g<u)){if(g>d)break;b.push(g)}}else for(;f<=m;++f)for(x=r-1;x>=1;--x)if(g=f>0?x/i(-f):x*i(f),!(g<u)){if(g>d)break;b.push(g)}b.length*2<y&&(b=cS(u,d,y))}else b=cS(f,m,Math.min(m-f,y)).map(i);return h?b.reverse():b},t.tickFormat=(l,c)=>{if(l==null&&(l=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=Lp(c)).precision==null&&(c.trim=!0),c=FE(c)),l===1/0)return c;const u=Math.max(1,r*l/t.ticks().length);return d=>{let h=d/i(Math.round(a(d)));return h*r<r-.5&&(h*=r),h<=u?c(d):""}},t.nice=()=>n(Sz(n(),{floor:l=>i(Math.floor(a(l))),ceil:l=>i(Math.ceil(a(l)))})),t}function Cz(){const e=BE(H0()).domain([1,10]);return e.copy=()=>Px(e,Cz()).base(e.base()),eo.apply(e,arguments),e}function c5(e){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/e))}}function u5(e){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*e}}function UE(e){var t=1,n=e(c5(t),u5(t));return n.constant=function(r){return arguments.length?e(c5(t=+r),u5(t)):t},_u(n)}function Ez(){var e=UE(H0());return e.copy=function(){return Px(e,Ez()).constant(e.constant())},eo.apply(e,arguments)}function d5(e){return function(t){return t<0?-Math.pow(-t,e):Math.pow(t,e)}}function mNe(e){return e<0?-Math.sqrt(-e):Math.sqrt(e)}function pNe(e){return e<0?-e*e:e*e}function zE(e){var t=e(Aa,Aa),n=1;function r(){return n===1?e(Aa,Aa):n===.5?e(mNe,pNe):e(d5(n),d5(1/n))}return t.exponent=function(a){return arguments.length?(n=+a,r()):n},_u(t)}function WE(){var e=zE(H0());return e.copy=function(){return Px(e,WE()).exponent(e.exponent())},eo.apply(e,arguments),e}function xNe(){return WE.apply(null,arguments).exponent(.5)}function h5(e){return Math.sign(e)*e*e}function gNe(e){return Math.sign(e)*Math.sqrt(Math.abs(e))}function Az(){var e=$E(),t=[0,1],n=!1,r;function a(i){var o=gNe(e(i));return isNaN(o)?r:n?Math.round(o):o}return a.invert=function(i){return e.invert(h5(i))},a.domain=function(i){return arguments.length?(e.domain(i),a):e.domain()},a.range=function(i){return arguments.length?(e.range((t=Array.from(i,Wb)).map(h5)),a):t.slice()}
855,a.rangeRound=function(i){return a.range(i).round(!0)},a.round=function(i){return arguments.length?(n=!!i,a):n},a.clamp=function(i){return arguments.length?(e.clamp(i),a):e.clamp()},a.unknown=function(i){return arguments.length?(r=i,a):r},a.copy=function(){return Az(e.domain(),t).round(n).clamp(e.clamp()).unknown(r)},eo.apply(a,arguments),_u(a)}function Tz(){var e=[],t=[],n=[],r;function a(){var o=0,l=Math.max(1,t.length);for(n=new Array(l-1);++o<l;)n[o-1]=wje(e,o/l);return i}function i(o){return o==null||isNaN(o=+o)?r:t[Ox(n,o)]}return i.invertExtent=function(o){var l=t.indexOf(o);return l<0?[NaN,NaN]:[l>0?n[l-1]:e[0],l<n.length?n[l]:e[e.length-1]]},i.domain=function(o){if(!arguments.length)return e.slice();e=[];for(let l of o)l!=null&&!isNaN(l=+l)&&e.push(l);return e.sort(qc),a()},i.range=function(o){return arguments.length?(t=Array.from(o),a()):t.slice()},i.unknown=function(o){return arguments.length?(r=o,i):r},i.quantiles=function(){return n.slice()},i.copy=function(){return Tz().domain(e).range(t).unknown(r)},eo.apply(i,arguments)}function Oz(){var e=0,t=1,n=1,r=[.5],a=[0,1],i;function o(c){return c!=null&&c<=c?a[Ox(r,c,0,n)]:i}function l(){var c=-1;for(r=new Array(n);++c<n;)r[c]=((c+1)*t-(c-n)*e)/(n+1);return o}return o.domain=function(c){return arguments.length?([e,t]=c,e=+e,t=+t,l()):[e,t]},o.range=function(c){return arguments.length?(n=(a=Array.from(c)).length-1,l()):a.slice()},o.invertExtent=function(c){var u=a.indexOf(c);return u<0?[NaN,NaN]:u<1?[e,r[0]]:u>=n?[r[n-1],t]:[r[u-1],r[u]]},o.unknown=function(c){return arguments.length&&(i=c),o},o.thresholds=function(){return r.slice()},o.copy=function(){return Oz().domain([e,t]).range(a).unknown(i)},eo.apply(_u(o),arguments)}function Iz(){var e=[.5],t=[0,1],n,r=1;function a(i){return i!=null&&i<=i?t[Ox(e,i,0,r)]:n}return a.domain=function(i){return arguments.length?(e=Array.from(i),r=Math.min(e.length,t.length-1),a):e.slice()},a.range=function(i){return arguments.length?(t=Array.from(i),r=Math.min(e.length,t.length-1),a):t.slice()},a.invertExtent=function(i){var o=t.indexOf(i);return[e[o-1],e[o]]},a.unknown=function(i){return arguments.length?(n=i,a):n},a.copy=function(){return Iz().domain(e).range(t).unknown(n)},eo.apply(a,arguments)}const Y_=new Date,Z_=new Date;function hs(e,t,n,r){function a(i){return e(i=arguments.length===0?new Date:new Date(+i)),i}return a.floor=i=>(e(i=new Date(+i)),i),a.ceil=i=>(e(i=new Date(i-1)),t(i,1),e(i),i),a.round=i=>{const o=a(i),l=a.ceil(i);return i-o<l-i?o:l},a.offset=(i,o)=>(t(i=new Date(+i),o==null?1:Math.floor(o)),i),a.range=(i,o,l)=>{const c=[];if(i=a.ceil(i),l=l==null?1:Math.floor(l),!(i<o)||!(l>0))return c;let u;do c.push(u=new Date(+i)),t(i,l),e(i);while(u<i&&i<o);return c},a.filter=i=>hs(o=>{if(o>=o)for(;e(o),!i(o);)o.setTime(o-1)},(o,l)=>{if(o>=o)if(l<0)for(;++l<=0;)for(;t(o,-1),!i(o););else for(;--l>=0;)for(;t(o,1),!i(o););}),n&&(a.count=(i,o)=>(Y_.setTime(+i),Z_.setTime(+o),e(Y_),e(Z_),Math.floor(n(Y_,Z_))),a.every=i=>(i=Math.floor(i),!isFinite(i)||!(i>0)?null:i>1?a.filter(r?o=>r(o)%i===0:o=>a.count(0,o)%i===0):a)),a}const Vb=hs(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>t-e);Vb.every=e=>(e=Math.floor(e),!isFinite(e)||!(e>0)?null:e>1?hs(t=>{t.setTime(Math.floor(t/e)*e)},(t,n)=>{t.setTime(+t+n*e)},(t,n)=>(n-t)/e):Vb);Vb.range;const Hl=1e3,Wi=Hl*60,Vl=Wi*60,oc=Vl*24,KE=oc*7,f5=oc*30,X_=oc*365,td=hs(e=>{e.setTime(e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*Hl)},(e,t)=>(t-e)/Hl,e=>e.getUTCSeconds());td.range;const HE=hs(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*Hl)},(e,t)=>{e.setTime(+e+t*Wi)},(e,t)=>(t-e)/Wi,e=>e.getMinutes());HE.range;const VE=hs(e=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*Wi)},(e,t)=>(t-e)/Wi,e=>e.getUTCMinutes());VE.range;const qE=hs(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*Hl-e.getMinutes()*Wi)},(e,t)=>{e.setTime(+e+t*Vl)},(e,t)=>(t-e)/Vl,e=>e.getHours());qE.range;const GE=hs(e=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*Vl)},(e,t)=>(t-e)/Vl,e=>e.getUTCHours());GE.range;const Rx=hs(e=>e.setHours(0,0,0,0),(e,t)=>e.setDate(e.getDate()+t),(e,t)=>(t-e-(t.getTimezoneOffset()-e.getTimezoneOffset())*Wi)/oc,e=>e.getDate()-1);Rx.range;const V0=hs(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/oc,e=>e.getUTCDate()-1);V0.range;const Pz=hs(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/oc,e=>Math.floor(e/oc));Pz.range;function Fd(e){return hs(t=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(t,n)=>{t.setDate(t.getDate()+n*7)},(t,n)=>(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*Wi)/KE)}
vendor: 2,768 bytes, line 855
855const q0=Fd(0),qb=Fd(1),yNe=Fd(2),bNe=Fd(3),Jh=Fd(4),vNe=Fd(5),wNe=Fd(6);q0.range;qb.range;yNe.range;bNe.range;Jh.range;vNe.range;wNe.range;function Bd(e){return hs(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCDate(t.getUTCDate()+n*7)},(t,n)=>(n-t)/KE)}const G0=Bd(0),Gb=Bd(1),_Ne=Bd(2),kNe=Bd(3),Qh=Bd(4),jNe=Bd(5),NNe=Bd(6);G0.range;Gb.range;_Ne.range;kNe.range;Qh.range;jNe.range;NNe.range;const YE=hs(e=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12,e=>e.getMonth());YE.range;const ZE=hs(e=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12,e=>e.getUTCMonth());ZE.range;const lc=hs(e=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>t.getFullYear()-e.getFullYear(),e=>e.getFullYear());lc.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:hs(t=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,n)=>{t.setFullYear(t.getFullYear()+n*e)});lc.range;const cc=hs(e=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>t.getUTCFullYear()-e.getUTCFullYear(),e=>e.getUTCFullYear());cc.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:hs(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n*e)});cc.range;function Rz(e,t,n,r,a,i){const o=[[td,1,Hl],[td,5,5*Hl],[td,15,15*Hl],[td,30,30*Hl],[i,1,Wi],[i,5,5*Wi],[i,15,15*Wi],[i,30,30*Wi],[a,1,Vl],[a,3,3*Vl],[a,6,6*Vl],[a,12,12*Vl],[r,1,oc],[r,2,2*oc],[n,1,KE],[t,1,f5],[t,3,3*f5],[e,1,X_]];function l(u,d,h){const f=d<u;f&&([u,d]=[d,u]);const m=h&&typeof h.range=="function"?h:c(u,d,h),x=m?m.range(u,+d+1):[];return f?x.reverse():x}function c(u,d,h){const f=Math.abs(d-u)/h,m=OE(([,,y])=>y).right(o,f);if(m===o.length)return e.every(dS(u/X_,d/X_,h));if(m===0)return Vb.every(Math.max(dS(u,d,h),1));const[x,g]=o[f/o[m-1][2]<o[m][2]/f?m-1:m];return x.every(g)}return[l,c]}const[SNe,CNe]=Rz(cc,ZE,G0,Pz,GE,VE),[ENe,ANe]=Rz(lc,YE,q0,Rx,qE,HE);function J_(e){if(0<=e.y&&e.y<100){var t=new Date(-1,e.m,e.d,e.H,e.M,e.S,e.L);return t.setFullYear(e.y),t}return new Date(e.y,e.m,e.d,e.H,e.M,e.S,e.L)}function Q_(e){if(0<=e.y&&e.y<100){var t=new Date(Date.UTC(-1,e.m,e.d,e.H,e.M,e.S,e.L));return t.setUTCFullYear(e.y),t}return new Date(Date.UTC(e.y,e.m,e.d,e.H,e.M,e.S,e.L))}function dm(e,t,n){return{y:e,m:t,d:n,H:0,M:0,S:0,L:0}}function TNe(e){var t=e.dateTime,n=e.date,r=e.time,a=e.periods,i=e.days,o=e.shortDays,l=e.months,c=e.shortMonths,u=hm(a),d=fm(a),h=
vendor: 8,448 bytes, line 855
855hm(i),f=fm(i),m=hm(o),x=fm(o),g=hm(l),y=fm(l),b=hm(c),v=fm(c),w={a:P,A:F,b:Z,B:D,c:null,d:b5,e:b5,f:QNe,g:cSe,G:dSe,H:ZNe,I:XNe,j:JNe,L:Dz,m:eSe,M:tSe,p:H,q:Y,Q:_5,s:k5,S:nSe,u:rSe,U:sSe,V:aSe,w:iSe,W:oSe,x:null,X:null,y:lSe,Y:uSe,Z:hSe,"%":w5},_={a:M,A:z,b:G,B:te,c:null,d:v5,e:v5,f:xSe,g:SSe,G:ESe,H:fSe,I:mSe,j:pSe,L:$z,m:gSe,M:ySe,p:re,q:L,Q:_5,s:k5,S:bSe,u:vSe,U:wSe,V:_Se,w:kSe,W:jSe,x:null,X:null,y:NSe,Y:CSe,Z:ASe,"%":w5},k={a:C,A:T,b:S,B:O,c:R,d:g5,e:g5,f:VNe,g:x5,G:p5,H:y5,I:y5,j:zNe,L:HNe,m:UNe,M:WNe,p:A,q:BNe,Q:GNe,s:YNe,S:KNe,u:DNe,U:MNe,V:$Ne,w:RNe,W:LNe,x:I,X:$,y:x5,Y:p5,Z:FNe,"%":qNe};w.x=j(n,w),w.X=j(r,w),w.c=j(t,w),_.x=j(n,_),_.X=j(r,_),_.c=j(t,_);function j(q,me){return function(ee){var ne=[],X=-1,he=0,ae=q.length,je,$e,J;for(ee instanceof Date||(ee=new Date(+ee));++X<ae;)q.charCodeAt(X)===37&&(ne.push(q.slice(he,X)),($e=m5[je=q.charAt(++X)])!=null?je=q.charAt(++X):$e=je==="e"?" ":"0",(J=me[je])&&(je=J(ee,$e)),ne.push(je),he=X+1);return ne.push(q.slice(he,X)),ne.join("")}}function N(q,me){return function(ee){var ne=dm(1900,void 0,1),X=E(ne,q,ee+="",0),he,ae;if(X!=ee.length)return null;if("Q"in ne)return new Date(ne.Q);if("s"in ne)return new Date(ne.s*1e3+("L"in ne?ne.L:0));if(me&&!("Z"in ne)&&(ne.Z=0),"p"in ne&&(ne.H=ne.H%12+ne.p*12),ne.m===void 0&&(ne.m="q"in ne?ne.q:0),"V"in ne){if(ne.V<1||ne.V>53)return null;"w"in ne||(ne.w=1),"Z"in ne?(he=Q_(dm(ne.y,0,1)),ae=he.getUTCDay(),he=ae>4||ae===0?Gb.ceil(he):Gb(he),he=V0.offset(he,(ne.V-1)*7),ne.y=he.getUTCFullYear(),ne.m=he.getUTCMonth(),ne.d=he.getUTCDate()+(ne.w+6)%7):(he=J_(dm(ne.y,0,1)),ae=he.getDay(),he=ae>4||ae===0?qb.ceil(he):qb(he),he=Rx.offset(he,(ne.V-1)*7),ne.y=he.getFullYear(),ne.m=he.getMonth(),ne.d=he.getDate()+(ne.w+6)%7)}else("W"in ne||"U"in ne)&&("w"in ne||(ne.w="u"in ne?ne.u%7:"W"in ne?1:0),ae="Z"in ne?Q_(dm(ne.y,0,1)).getUTCDay():J_(dm(ne.y,0,1)).getDay(),ne.m=0,ne.d="W"in ne?(ne.w+6)%7+ne.W*7-(ae+5)%7:ne.w+ne.U*7-(ae+6)%7);return"Z"in ne?(ne.H+=ne.Z/100|0,ne.M+=ne.Z%100,Q_(ne)):J_(ne)}}function E(q,me,ee,ne){for(var X=0,he=me.length,ae=ee.length,je,$e;X<he;){if(ne>=ae)return-1;if(je=me.charCodeAt(X++),je===37){if(je=me.charAt(X++),$e=k[je in m5?me.charAt(X++):je],!$e||(ne=$e(q,ee,ne))<0)return-1}else if(je!=ee.charCodeAt(ne++))return-1}return ne}function A(q,me,ee){var ne=u.exec(me.slice(ee));return ne?(q.p=d.get(ne[0].toLowerCase()),ee+ne[0].length):-1}function C(q,me,ee){var ne=m.exec(me.slice(ee));return ne?(q.w=x.get(ne[0].toLowerCase()),ee+ne[0].length):-1}function T(q,me,ee){var ne=h.exec(me.slice(ee));return ne?(q.w=f.get(ne[0].toLowerCase()),ee+ne[0].length):-1}function S(q,me,ee){var ne=b.exec(me.slice(ee));return ne?(q.m=v.get(ne[0].toLowerCase()),ee+ne[0].length):-1}function O(q,me,ee){var ne=g.exec(me.slice(ee));return ne?(q.m=y.get(ne[0].toLowerCase()),ee+ne[0].length):-1}function R(q,me,ee){return E(q,t,me,ee)}function I(q,me,ee){return E(q,n,me,ee)}function $(q,me,ee){return E(q,r,me,ee)}function P(q){return o[q.getDay()]}function F(q){return i[q.getDay()]}function Z(q){return c[q.getMonth()]}function D(q){return l[q.getMonth()]}function H(q){return a[+(q.getHours()>=12)]}function Y(q){return 1+~~(q.getMonth()/3)}function M(q){return o[q.getUTCDay()]}function z(q){return i[q.getUTCDay()]}function G(q){return c[q.getUTCMonth()]}function te(q){return l[q.getUTCMonth()]}function re(q){return a[+(q.getUTCHours()>=12)]}function L(q){return 1+~~(q.getUTCMonth()/3)}return{format:function(q){var me=j(q+="",w);return me.toString=function(){return q},me},parse:function(q){var me=N(q+="",!1);return me.toString=function(){return q},me},utcFormat:function(q){var me=j(q+="",_);return me.toString=function(){return q},me},utcParse:function(q){var me=N(q+="",!0);return me.toString=function(){return q},me}}}var m5={"-":"",_:" ",0:"0"},Cs=/^\s*\d+/,ONe=/^%/,INe=/[\\^$*+?|[\]().{}]/g;function gn(e,t,n){var r=e<0?"-":"",a=(r?-e:e)+"",i=a.length;return r+(i<n?new Array(n-i+1).join(t)+a:a)}function PNe(e){return e.replace(INe,"\\$&")}function hm(e){return new RegExp("^(?:"+e.map(PNe).join("|")+")","i")}function fm(e){return new Map(e.map((t,n)=>[t.toLowerCase(),n]))}function RNe(e,t,n){var r=Cs.exec(t.slice(n,n+1));return r?(e.w=+r[0],n+r[0].length):-1}function DNe(e,t,n){var r=Cs.exec(t.slice(n,n+1));return r?(e.u=+r[0],n+r[0].length):-1}function MNe(e,t,n){var r=Cs.exec(t.slice(n,n+2));return r?(e.U=+r[0],n+r[0].length):-1}function $Ne(e,t,n){var r=Cs.exec(t.slice(n,n+2));return r?(e.V=+r[0],n+r[0].length):-1}function LNe(e,t,n){var r=Cs.exec(t.slice(n,n+2));return r?(e.W=+r[0],n+r[0].length):-1}function p5(e,t,n){var r=Cs.exec(t.slice(n,n+4));return r?(e.y=+r[0],n+r[0].length):-1}function x5(e,t,n){var r=Cs.exec(t.slice(n,n+2));return r?(e.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function FNe(e,t,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(n,n+6));return r?(e.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function BNe(e,t,n){var r=Cs.exec(t.slice(n,n+1));return r?(e.q=r[0]*3-3,n+r[0].length):-1}function UNe(e,t,n){var r=Cs.exec(t.slice(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function g5(e,t,n){var r=Cs.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function zNe(e,t,n){var r=Cs.exec(t.slice(n,n+3));return r?(e.m=0,e.d=+r[0],n+r[0].length):-1}function y5(e,t,n){var r=Cs.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function WNe(e,t,n){var r=Cs.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function KNe(e,t,n){var r=Cs.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function HNe(e,t,n){var r=Cs.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function VNe(e,t,n){var r=Cs.exec(t.slice(n,n+6));return r?(e.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function qNe(e,t,n){var r=ONe.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function GNe(e,t,n){var r=Cs.exec(t.slice(n));return r?(e.Q=+r[0],n+r[0].length):-1}function YNe(e,t,n){var r=Cs.exec(t.slice(n));return r?(e.s=+r[0],n+r[0].length):-1}function b5(e,t){return gn(e.getDate(),t,2)}function ZNe(e,t){return gn(e.getHours(),t,2)}function XNe(e,t){return gn(e.getHours()%12||12,t,2)}function JNe(e,t){return gn(1+Rx.count(lc(e),e),t,3)}function Dz(e,t){return gn(e.getMilliseconds(),t,3)}function QNe(e,t){return Dz(e,t)+"000"}function eSe(e,t){return gn(e.getMonth()+1,t,2)}function tSe(e,t){return gn(e.getMinutes(),t,2)}function nSe(e,t){return gn(e.getSeconds(),t,2)}function rSe(e){var t=e.getDay();return t===0?7:t}function sSe(e,t){return gn(q0.count(lc(e)-1,e),t,2)}function Mz(e){var t=e.getDay();return t>=4||t===0?Jh(e):Jh.ceil(e)}function aSe(e,t){return e=Mz(e),gn(Jh.count(lc(e),e)+(lc(e).getDay()===4),t,2)}function iSe(e){return e.getDay()}function oSe(e,t){return gn(qb.count(lc(e)-1,e),t,2)}function lSe(e,t){return gn(e.getFullYear()%100,t,2)}function cSe(e,t){return e=Mz(e),gn(e.getFullYear()%100,t,2)}function uSe(e,t){return gn(e.getFullYear()%1e4,t,4)}function dSe(e,t){var n=e.getDay();return e=n>=4||n===0?Jh(e):Jh.ceil(e),gn(e.getFullYear()%1e4,t,4)}function hSe(e){var t=e.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+gn(t/60|0,"0",2)+gn(t%60,"0",2)}function v5(e,t){return gn(e.getUTCDate(),t,2)}function fSe(e,t){return gn(e.getUTCHours(),t,2)}function mSe(e,t){return gn(e.getUTCHours()%12||12,t,2)}function pSe(e,t){return gn(1+V0.count(cc(e),e),t,3)}function $z(e,t){return gn(e.getUTCMilliseconds(),t,3)}function xSe(e,t){return $z(e,t)+"000"}function gSe(e,t){return gn(e.getUTCMonth()+1,t,2)}function ySe(e,t){return gn(e.getUTCMinutes(),t,2)}function bSe(e,t){return gn(e.getUTCSeconds(),t,2)}function vSe(e){var t=e.getUTCDay();return t===0?7:t}function wSe(e,t){return gn(G0.count(cc(e)-1,e),t,2)}function Lz(e){var t=e.getUTCDay();return t>=4||t===0?Qh(e):Qh.ceil(e)}function _Se(e,t){return e=Lz(e),gn(Qh.count(cc(e),e)+(cc(e).getUTCDay()===4),t,2)}function kSe(e){return e.getUTCDay()}function jSe(e,t){return gn(Gb.count(cc(e)-1,e),t,2)}function NSe(e,t){return gn(e.getUTCFullYear()%100,t,2)}function SSe(e,t){return e=Lz(e),gn(e.getUTCFullYear()%100,t,2)}function CSe(e,t){return gn(e.getUTCFullYear()%1e4,t,4)}function ESe(e,t){var n=e.getUTCDay();return e=n>=4||n===0?Qh(e):Qh.ceil(e),gn(e.getUTCFullYear()%1e4,t,4)}function ASe(){return"+0000"}function w5(){return"%"}function _5(e){return+e}function k5(e){return Math.floor(+e/1e3)}var nh,Fz,Bz;TSe({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Frid
855ay","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function TSe(e){return nh=TNe(e),Fz=nh.format,nh.parse,Bz=nh.utcFormat,nh.utcParse,nh}function OSe(e){return new Date(e)}function ISe(e){return e instanceof Date?+e:+new Date(+e)}function XE(e,t,n,r,a,i,o,l,c,u){var d=$E(),h=d.invert,f=d.domain,m=u(".%L"),x=u(":%S"),g=u("%I:%M"),y=u("%I %p"),b=u("%a %d"),v=u("%b %d"),w=u("%B"),_=u("%Y");function k(j){return(c(j)<j?m:l(j)<j?x:o(j)<j?g:i(j)<j?y:r(j)<j?a(j)<j?b:v:n(j)<j?w:_)(j)}return d.invert=function(j){return new Date(h(j))},d.domain=function(j){return arguments.length?f(Array.from(j,ISe)):f().map(OSe)},d.ticks=function(j){var N=f();return e(N[0],N[N.length-1],j??10)},d.tickFormat=function(j,N){return N==null?k:u(N)},d.nice=function(j){var N=f();return(!j||typeof j.range!="function")&&(j=t(N[0],N[N.length-1],j??10)),j?f(Sz(N,j)):d},d.copy=function(){return Px(d,XE(e,t,n,r,a,i,o,l,c,u))},d}function PSe(){return eo.apply(XE(ENe,ANe,lc,YE,q0,Rx,qE,HE,td,Fz).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)}function RSe(){return eo.apply(XE(SNe,CNe,cc,ZE,G0,V0,GE,VE,td,Bz).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)}function Y0(){var e=0,t=1,n,r,a,i,o=Aa,l=!1,c;function u(h){return h==null||isNaN(h=+h)?c:o(a===0?.5:(h=(i(h)-n)*a,l?Math.max(0,Math.min(1,h)):h))}u.domain=function(h){return arguments.length?([e,t]=h,n=i(e=+e),r=i(t=+t),a=n===r?0:1/(r-n),u):[e,t]},u.clamp=function(h){return arguments.length?(l=!!h,u):l},u.interpolator=function(h){return arguments.length?(o=h,u):o};function d(h){return function(f){var m,x;return arguments.length?([m,x]=f,o=h(m,x),u):[o(0),o(1)]}}return u.range=d(Df),u.rangeRound=d(ME),u.unknown=function(h){return arguments.length?(c=h,u):c},function(h){return i=h,n=h(e),r=h(t),a=n===r?0:1/(r-n),u}}function ku(e,t){return t.domain(e.domain()).interpolator(e.interpolator()).clamp(e.clamp()).unknown(e.unknown())}function Uz(){var e=_u(Y0()(Aa));return e.copy=function(){return ku(e,Uz())},gc.apply(e,arguments)}function zz(){var e=BE(Y0()).domain([1,10]);return e.copy=function(){return ku(e,zz()).base(e.base())},gc.apply(e,arguments)}function Wz(){var e=UE(Y0());return e.copy=function(){return ku(e,Wz()).constant(e.constant())},gc.apply(e,arguments)}function JE(){var e=zE(Y0());return e.copy=function(){return ku(e,JE()).exponent(e.exponent())},gc.apply(e,arguments)}function DSe(){return JE.apply(null,arguments).exponent(.5)}function Kz(){var e=[],t=Aa;function n(r){if(r!=null&&!isNaN(r=+r))return t((Ox(e,r,1)-1)/(e.length-1))}return n.domain=function(r){if(!arguments.length)return e.slice();e=[];for(let a of r)a!=null&&!isNaN(a=+a)&&e.push(a);return e.sort(qc),n},n.interpolator=function(r){return arguments.length?(t=r,n):t},n.range=function(){return e.map((r,a)=>t(a/(e.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,i)=>vje(e,i/r))},n.copy=function(){return Kz(t).domain(e)},gc.apply(n,arguments)}function Z0(){var e=0,t=.5,n=1,r=1,a,i,o,l,c,u=Aa,d,h=!1,f;function m(g){return isNaN(g=+g)?f:(g=.5+((g=+d(g))-i)*(r*g<r*i?l:c),u(h?Math.max(0,Math.min(1,g)):g))}m.domain=function(g){return arguments.length?([e,t,n]=g,a=d(e=+e),i=d(t=+t),o=d(n=+n),l=a===i?0:.5/(i-a),c=i===o?0:.5/(o-i),r=i<a?-1:1,m):[e,t,n]},m.clamp=function(g){return arguments.length?(h=!!g,m):h},m.interpolator=function(g){return arguments.length?(u=g,m):u};function x(g){return function(y){var b,v,w;return arguments.length?([b,v,w]=y,u=qje(g,[b,v,w]),m):[u(0),u(.5),u(1)]}}return m.range=x(Df),m.rangeRound=x(ME),m.unknown=function(g){return arguments.length?(f=g,m):f},function(g){return d=g,a=g(e),i=g(t),o=g(n),l=a===i?0:.5/(i-a),c=i===o?0:.5/(o-i),r=i<a?-1:1,m}}function Hz(){var e=_u(Z0()(Aa));return e.copy=function(){return ku(e,Hz())},gc.apply(e,arguments)}function Vz(){var e=BE(Z0()).domain([.1,1,10]);return e.copy=function(){return ku(e,Vz()).base(e.base())},gc.apply(e,arguments)}function qz(){var e=UE(Z0());return e.copy=function(){return ku(e,qz()).constant(e.constant())},gc.apply(e,arguments)}function QE(){var e=zE(Z0());return e.copy=function(){return ku(e,QE()).exponent(e.exponent())},gc.apply(e,arguments)}function MSe(){return QE.apply(null,arguments).exponent(.5)}const Gz=Object.freeze(Object.defineProperty({__proto__:null,scaleBand:PE,scaleDiverging:Hz,scaleDivergingLog:Vz,scaleDivergingPow:QE,scaleDivergingSqrt:MSe,scaleDivergingSymlog:qz,scaleIdentity:Nz,scaleImplicit:hS,scaleLinear:jz,scaleLog:Cz,scaleOrdinal:IE,scalePoint:kje,scalePow:WE,scaleQuantile:Tz,scaleQuantize:Oz,scaleRadial:Az,scaleSequential:Uz,scaleSequentialLog:zz,scaleSequentialPow:JE,scaleSequentialQuantile:Kz,scaleSequentialSqrt:DSe,scaleSequentialSymlog:Wz,scaleSqrt:xNe,scaleSymlog:Ez,scaleThreshold:Iz,scaleTime:PSe,scaleUtc:RSe,tickFormat:kz},Symbol.toStringTag,{value:"Module"}));function $Se(e){var t=Gz;if(e in t&&typeof t[e]=="function")return t[e]();var n="scale".concat(gx(e));if(n in t&&typeof t[n]=="function")return t[n]()}
855function j5(e,t,n){if(typeof e=="function")return e.copy().domain(t).range(n);if(e!=null){var r=$Se(e);if(r!=null)return r.domain(t).range(n),r}}function eA(e,t,n,r){if(!(n==null||r==null))return typeof e.scale=="function"?j5(e.scale,n,r):j5(t,n,r)}function LSe(e){return"scale".concat(gx(e))}function FSe(e){return LSe(e)in Gz}var Yz=(e,t,n)=>{if(e!=null){var r=e.scale,a=e.type;if(r==="auto")return a==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!t)?"point":a==="category"?"band":"linear";if(typeof r=="string")return FSe(r)?r:"point"}};function BSe(e,t){for(var n=0,r=e.length,a=e[0]<e[e.length-1];n<r;){var i=Math.floor((n+r)/2);(a?e[i]<t:e[i]>t)?n=i+1:r=i}return n}function Zz(e,t){if(e){var n=t??e.domain(),r=n.map(i=>{var o;return(o=e(i))!==null&&o!==void 0?o:0}),a=e.range();if(!(n.length===0||a.length<2))return i=>{var o,l,c=BSe(r,i);if(c<=0)return n[0];if(c>=n.length)return n[n.length-1];var u=(o=r[c-1])!==null&&o!==void 0?o:0,d=(l=r[c])!==null&&l!==void 0?l:0;return Math.abs(i-u)<=Math.abs(i-d)?n[c-1]:n[c]}}}function USe(e){if(e!=null)return"invert"in e&&typeof e.invert=="function"?e.invert.bind(e):Zz(e,void 0)}function N5(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Yb(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?N5(Object(n),!0).forEach(function(r){zSe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):N5(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function zSe(e,t,n){return(t=WSe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function WSe(e){var t=KSe(e,"string");return typeof t=="symbol"?t:t+""}function KSe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Xz(e,t){return GSe(e)||qSe(e,t)||VSe(e,t)||HSe()}function HSe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 856In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function VSe(e,t){if(e){if(typeof e=="string")return S5(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?S5(e,t):void 0}}function S5(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function qSe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function GSe(e){if(Array.isArray(e))return e}var xS=[0,"auto"],Qr={allowDataOverflow:!1,allowDecimals:!0,allowDuplicatedCategory:!0,angle:0,dataKey:void 0,domain:void 0,height:30,hide:!0,id:0,includeHidden:!1,interval:"preserveEnd",minTickGap:5,mirror:!1,name:void 0,orientation:"bottom",padding:{left:0,right:0},reversed:!1,scale:"auto",tick:!0,tickCount:5,tickFormatter:void 0,ticks:void 0,type:"category",unit:void 0,niceTicks:"auto"},Jz=(e,t)=>e.cartesianAxis.xAxis[t],yl=(e,t)=>{var n=Jz(e,t);return n??Qr},es={allowDataOverflow:!1,allowDecimals:!0,allowDuplicatedCategory:!0,angle:0,dataKey:void 0,domain:xS,hide:!0,id:0,includeHidden:!1,interval:"preserveEnd",minTickGap:5,mirror:!1,name:void 0,orientation:"left",padding:{top:0,bottom:0},reversed:!1,scale:"auto",tick:!0,tickCount:5,tickFormatter:void 0,ticks:void 0,type:"number",unit:void 0,niceTicks:"auto",width:wx},Qz=(e,t)=>
856e.cartesianAxis.yAxis[t],bl=(e,t)=>{var n=Qz(e,t);return n??es},YSe={domain:[0,"auto"],includeHidden:!1,reversed:!1,allowDataOverflow:!1,allowDuplicatedCategory:!1,dataKey:void 0,id:0,name:"",range:[64,64],scale:"auto",type:"number",unit:""},tA=(e,t)=>{var n=e.cartesianAxis.zAxis[t];return n??YSe},Tr=(e,t,n)=>{switch(t){case"xAxis":return yl(e,n);case"yAxis":return bl(e,n);case"zAxis":return tA(e,n);case"angleAxis":return CE(e,n);case"radiusAxis":return EE(e,n);default:throw new Error("Unexpected axis type: ".concat(t))}},ZSe=(e,t,n)=>{switch(t){case"xAxis":return yl(e,n);case"yAxis":return bl(e,n);default:throw new Error("Unexpected axis type: ".concat(t))}},Mf=(e,t,n)=>{switch(t){case"xAxis":return yl(e,n);case"yAxis":return bl(e,n);case"angleAxis":return CE(e,n);case"radiusAxis":return EE(e,n);default:throw new Error("Unexpected axis type: ".concat(t))}},eW=e=>e.graphicalItems.cartesianItems.some(t=>t.type==="bar")||e.graphicalItems.polarItems.some(t=>t.type==="radialBar");function nA(e,t){return n=>{switch(e){case"xAxis":return"xAxisId"in n&&n.xAxisId===t;case"yAxis":return"yAxisId"in n&&n.yAxisId===t;case"zAxis":return"zAxisId"in n&&n.zAxisId===t;case"angleAxis":return"angleAxisId"in n&&n.angleAxisId===t;case"radiusAxis":return"radiusAxisId"in n&&n.radiusAxisId===t;default:return!1}}}var Dx=e=>e.graphicalItems.cartesianItems,XSe=be([Ar,Ax],nA),rA=(e,t,n)=>e.filter(n).filter(r=>(t==null?void 0:t.includeHidden)===!0?!0:!r.hide),$f=be([Dx,Tr,XSe],rA,{memoizeOptions:{resultEqualityCheck:K0}}),tW=be([$f],e=>e.filter(t=>t.type==="area"||t.type==="bar").filter(W0)),nW=e=>e.filter(t=>!("stackId"in t)||t.stackId===void 0),JSe=be([$f],nW),sA=e=>e.map(t=>t.data).filter(Boolean).flat(1),QSe=be([$f],e=>e.some(t=>!t.data)),rW=be([$f],sA,{memoizeOptions:{resultEqualityCheck:K0}}),aA=(e,t)=>{var n=t.chartData,r=n===void 0?[]:n,a=t.dataStartIndex,i=t.dataEndIndex;return e.length>0?e:r.slice(a,i+1)},iA=be([rW,Cx],aA),sW=(e,t,n)=>(t==null?void 0:t.dataKey)!=null?e.map(r=>({value:hn(r,t.dataKey)})):n.length>0?n.map(r=>r.dataKey).flatMap(r=>e.map(a=>({value:hn(a,r)}))):e.map(r=>({value:r})),aW=(e,t,n,r,a,i)=>{var o=r.chartData,l=o===void 0?[]:o,c=r.dataStartIndex,u=r.dataEndIndex,d=sW(e,t,n);if(a&&(t==null?void 0:t.dataKey)!=null&&i.length>0){var h=l.slice(c,u+1),f=h.map(m=>({value:hn(m,t.dataKey)})).filter(m=>m.value!=null);return[...f,...d]}return d},Mx=be([iA,Tr,$f,Cx,QSe,rW],aW);function Bh(e){if(aa(e)||e instanceof Date){var t=Number(e);if(Mt(t))return t}}function C5(e){if(Array.isArray(e)){var t=[Bh(e[0]),Bh(e[1])];return tl(t)?t:void 0}var n=Bh(e);if(n!=null)return[n,n]}function So(e){return e.map(Bh).filter(Ea)}function e2e(e,t){var n=Bh(e),r=Bh(t);return n==null&&r==null?0:n==null?-1:r==null?1:n-r}var t2e=be([Mx],e=>e==null?void 0:e.map(t=>t.value).sort(e2e));function iW(e,t){switch(e){case"xAxis":return t.direction==="x";case"yAxis":return t.direction==="y";default:return!1}}function n2e(e,t,n){if(!n)return[];if(!n.length)return[];var r;if(typeof t=="number"&&!No(t))r=t;else if(Array.isArray(t)){var a=So(t);a.length>0&&(r=Math.max(...a))}return r==null?[]:So(n.flatMap(i=>{var o=hn(e,i.dataKey),l,c;if(Array.isArray(o)){var u=Xz(o,2);l=u[0],c=u[1]}else l=c=o;if(!(!Mt(l)||!Mt(c)))return[r-l,r+c]}))}var fs=e=>{var t=Ss(e),n=Rf(e);return Mf(e,t,n)},ef=be([fs],e=>e==null?void 0:e.dataKey),r2e=be([tW,Cx,fs],fz),oW=(e,t,n,r)=>{var a={},i=t.reduce((o,l)=>{if(l.stackId==null)return o;var c=o[l.stackId];return c==null&&(c=[]),c.push(l),o[l.stackId]=c,o},a);return Object.fromEntries(Object.entries(i).map(o=>{var l=Xz(o,2),c=l[0],u=l[1],d=r?[...u].reverse():u,h=d.map(z0);return[c,{stackedData:cwe(e,h,n),graphicalItems:d}]}))},Zb=be([r2e,tW,Ex,iz],oW),lW=(e,t,n,r)=>{var a=t.dataStartIndex,i=t.dataEndIndex;if(r==null&&n!=="zAxis")return fwe(e,a,i)},s2e=be([Tr],e=>e.allowDataOverflow),oA=e=>{var t;if(e==null||!("domain"in e))return xS;if(e.domain!=null)return e.domain;if("ticks"in e&&e.ticks!=null){if(e.type==="number"){var n=So(e.ticks);return[Math.min(...n),Math.max(...n)]}if(e.type==="category")return e.ticks.map(String)}return(t=e==null?void 0:e.domain)!==null&&t!==void 0?t:xS},lA=be([Tr],oA),cA=be([lA,s2e],qU),a2e=be([Zb,Io,Ar,cA],lW,{memoizeOptions:{resultEqualityCheck:Tx}}),X0=e=>
856e.errorBars,i2e=(e,t,n)=>e.flatMap(r=>t[r.id]).filter(Boolean).filter(r=>iW(n,r)),Xb=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];var a=n.filter(Boolean);if(a.length!==0){var i=a.flat(),o=Math.min(...i),l=Math.max(...i);return[o,l]}},uA=function(t,n,r,a,i){var o=arguments.length>5&&arguments[5]!==void 0?arguments[5]:[],l,c;if(r.length>0&&r.forEach(u=>{var d,h=u.data!=null?[...u.data]:o,f=(d=a[u.id])===null||d===void 0?void 0:d.filter(m=>iW(i,m));h.forEach(m=>{var x,g=hn(m,(x=n.dataKey)!==null&&x!==void 0?x:u.dataKey),y=n2e(m,g,f);if(y.length>=2){var b=Math.min(...y),v=Math.max(...y);(l==null||b<l)&&(l=b),(c==null||v>c)&&(c=v)}var w=C5(g);w!=null&&(l=l==null?w[0]:Math.min(l,w[0]),c=c==null?w[1]:Math.max(c,w[1]))})}),(n==null?void 0:n.dataKey)!=null&&r.length===0&&t.forEach(u=>{var d=C5(hn(u,n.dataKey));d!=null&&(l=l==null?d[0]:Math.min(l,d[0]),c=c==null?d[1]:Math.max(c,d[1]))}),Mt(l)&&Mt(c))return[l,c]},o2e=be([iA,Tr,JSe,X0,Ar,$ke],uA,{memoizeOptions:{resultEqualityCheck:Tx}});function l2e(e){var t=e.value;if(aa(t)||t instanceof Date)return t}var c2e=(e,t,n)=>{var r=e.map(l2e).filter(a=>a!=null);return n&&(t.dataKey==null||t.allowDuplicatedCategory&&s9(r))?HU(0,e.length):t.allowDuplicatedCategory?r:Array.from(new Set(r))},cW=e=>e.referenceElements.dots,Lf=(e,t,n)=>e.filter(r=>r.ifOverflow==="extendDomain").filter(r=>t==="xAxis"?r.xAxisId===n:r.yAxisId===n),u2e=be([cW,Ar,Ax],Lf),uW=e=>e.referenceElements.areas,d2e=be([uW,Ar,Ax],Lf),dW=e=>e.referenceElements.lines,h2e=be([dW,Ar,Ax],Lf),hW=(e,t)=>
856{if(e!=null){var n=So(e.map(r=>t==="xAxis"?r.x:r.y));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},f2e=be(u2e,Ar,hW),fW=(e,t)=>{if(e!=null){var n=So(e.flatMap(r=>[t==="xAxis"?r.x1:r.y1,t==="xAxis"?r.x2:r.y2]));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},m2e=be([d2e,Ar],fW);function p2e(e){var t;if(e.x!=null)return So([e.x]);var n=(t=e.segment)===null||t===void 0?void 0:t.map(r=>r.x);return n==null||n.length===0?[]:So(n)}function x2e(e){var t;if(e.y!=null)return So([e.y]);var n=(t=e.segment)===null||t===void 0?void 0:t.map(r=>r.y);return n==null||n.length===0?[]:So(n)}var mW=(e,t)=>{if(e!=null){var n=e.flatMap(r=>t==="xAxis"?p2e(r):x2e(r));if(n.length!==0)return[Math.min(...n),Math.max(...n)]}},g2e=be([h2e,Ar],mW),y2e=be(f2e,g2e,m2e,(e,t,n)=>Xb(e,n,t)),dA=(e,t,n,r,a,i,o,l,c)=>{if(n!=null)return n;var u=o==="vertical"&&l==="xAxis"||o==="horizontal"&&l==="yAxis",d=u?Xb(r,i,a):Xb(i,a),h=Kke(t,d,e.allowDataOverflow);return h??(e.allowDataOverflow&&d==null&&c!=null?c:h)},b2e=e=>{if(!(e==null||e.type!=="number"||!("ticks"in e)||e.ticks==null)){var t=So(e.ticks);if(t.length!==0)return[Math.min(...t),Math.max(...t)]}},v2e=be([Tr],b2e,{memoizeOptions:{resultEqualityCheck:Tx}}),w2e=be([Tr,lA,cA,a2e,o2e,y2e,sn,Ar,v2e],dA,{memoizeOptions:{resultEqualityCheck:Tx}}),_2e=[0,1],hA=(e,t,n,r,a,i,o)=>{if(!((e==null||n==null||n.length===0)&&o===void 0)){var l=e.dataKey,c=e.type,u=Oo(t,i);if(u&&l==null){var d;return HU(0,(d=n==null?void 0:n.length)!==null&&d!==void 0?d:0)}return c==="category"?c2e(r,e,u):a==="expand"&&!u?_2e:o}},fA=be([Tr,sn,iA,Mx,Ex,Ar,w2e],hA),ju=be([Tr,eW,jE],Yz),mA=(e,t,n)=>{var r=t.niceTicks;if(r!=="none"){var a=oA(t),i=Array.isArray(a)&&(a[0]==="auto"||a[1]==="auto");if((r==="snap125"||r==="adaptive")&&t!=null&&t.tickCount&&tl(e)){if(i)return M4(e,t.tickCount,t.allowDecimals,r);if(t.type==="number")return $4(e,t.tickCount,t.allowDecimals,r)}if(r==="auto"&&n==="linear"&&t!=null&&t.tickCount){if(i&&tl(e))return M4(e,t.tickCount,t.allowDecimals,"adaptive");if(t.type==="number"&&tl(e))return $4(e,t.tickCount,t.allowDecimals,"adaptive")}}},pA=be([fA,Mf,ju],mA),xA=(e,t,n,r)=>{if(r!=="angleAxis"&&(e==null?void 0:e.type)==="number"&&tl(t)&&Array.isArray(n)&&n.length>0){var a,i,o=t[0],l=(a=n[0])!==null&&a!==void 0?a:0,c=t[1],u=(i=n[n.length-1])!==null&&i!==void 0?i:0;return[Math.min(o,l),Math.max(c,u)]}return t},k2e=be([Tr,fA,pA,Ar],xA),j2e=be(Mx,Tr,(e,t)=>{if(!(!t||t.type!=="number")){var n=1/0,r=Array.from(So(e.map(h=>h.value))).sort((h,f)=>h-f),a=r[0],i=r[r.length-1];if(a==null||i==null)return 1/0;var o=i-a;if(o===0)return 1/0;for(var l=0;l<r.length-1;l++){var c=r[l],u=r[l+1];if(!(c==null||u==null)){var d=u-c;n=Math.min(n,d)}}return n/o}}),pW=be(j2e,sn,az,ds,(e,t,n,r,a)=>a,(e,t,n,r,a)=>{if(!Mt(e))return 0;var i=t==="vertical"?r.height:r.width;if(a==="gap")return e*i/2;if(a==="no-gap"){var o=ca(n,e*i),l=e*i/2;return l-o-(l-o)/i*o}return 0}),N2e=(e,t,n)=>{var r=yl(e,t);return r==null||typeof r.padding!="string"?0:pW(e,"xAxis",t,n,r.padding)},S2e=(e,t,n)=>{var r=bl(e,t);return r==null||typeof r.padding!="string"?0:pW(e,"yAxis",t,n,r.padding)},C2e=be(yl,N2e,(e,t)=>{var n,r;if(e==null)return{left:0,right:0};var a=e.padding;return typeof a=="string"?{left:t,right:t}:{left:((n=a.left)!==null&&n!==void 0?n:0)+t,right:((r=a.right)!==null&&r!==void 0?r:0)+t}}),E2e=be(bl,S2e,(e,t)=>{var n,r;if(e==null)return{top:0,bottom:0};var a=e.padding;return typeof a=="string"?{top:t,bottom:t}:{top:((n=a.top)!==null&&n!==void 0?n:0)+t,bottom:((r=a.bottom)!==null&&r!==void 0?r:0)+t}}),xW=be([ds,C2e,L0,$0,(e,t,n)=>n],(e,t,n,r,a)=>{var i=r.padding;return a?[i.left,n.width-i.right]:[e.left+t.left,e.left+e.width-t.right]}),gW=be([ds,sn,E2e,L0,$0,(e,t,n)=>n],(e,t,n,r,a,i)=>{var o=a.padding;return i?[r.height-o.bottom,o.top]:t==="horizontal"?[e.top+e.height-n.bottom,e.top+n.top]:[e.top+n.top,e.top+e.height-n.bottom]}),$x=(e,t,n,r)=>{var a;switch(t){case"xAxis":return xW(e,n,r);case"yAxis":return gW(e,n,r);case"zAxis":return(a=tA(e,n))===null||a===void 0?void 0:a.range;case"angleAxis":return uz(e);case"radiusAxis":return dz(e,n);default:return}},yW=be([Tr,$x],F0),A2e=be([ju,k2e],mz),gA=be([Tr,ju,A2e,yW],eA),bW=(e,t,n,r)=>{if(!(n==null||n.dataKey==null)){var a=n.type,i=n.scale,o=Oo(e,r);if(o&&(a==="number"||i!=="auto"))return t.map(l=>l.value)}},yA=be([sn,Mx,Mf,Ar],bW),au=be([gA],TE);be([gA],USe);be([gA,t2e],Zz);be([$f,X0,Ar],i2e);function vW(e,t){return e.id<t.id?-1:e.id>t.id?1:0}var J0=(e,t)=>t,Q0=(e,t,n)=>n,T2e=be(D0,J0,Q0,(e,t,n)=>e.filter(r=>r.orientation===t).filter(r=>r.mirror===n).sort(vW)),O2e=be(M0,J0,Q0,(e,t,n)=>e.filter(r=>r.orientation===t).filter(r=>r.mirror===n).sort(vW)),wW=(e,t)=>
856{var n=typeof t.height=="number"?t.height:dE;return{width:e.width,height:n}},I2e=(e,t)=>{var n=typeof t.width=="number"?t.width:wx;return{width:n,height:e.height}},_W=be(ds,yl,wW),P2e=(e,t,n)=>{switch(t){case"top":return e.top;case"bottom":return n-e.bottom;default:return 0}},R2e=(e,t,n)=>{switch(t){case"left":return e.left;case"right":return n-e.right;default:return 0}},D2e=be(gl,ds,T2e,J0,Q0,(e,t,n,r,a)=>{var i={},o;return n.forEach(l=>{var c=wW(t,l);o==null&&(o=P2e(t,r,e));var u=r==="top"&&!a||r==="bottom"&&a;i[l.id]=o-Number(u)*c.height,o+=(u?-1:1)*c.height}),i}),M2e=be(xl,ds,O2e,J0,Q0,(e,t,n,r,a)=>{var i={},o;return n.forEach(l=>{var c=I2e(t,l);o==null&&(o=R2e(t,r,e));var u=r==="left"&&!a||r==="right"&&a;i[l.id]=o-Number(u)*c.width,o+=(u?-1:1)*c.width}),i}),$2e=(e,t)=>{var n=yl(e,t);if(n!=null)return D2e(e,n.orientation,n.mirror)},L2e=be([ds,yl,$2e,(e,t)=>t],(e,t,n,r)=>{if(t!=null){var a=n==null?void 0:n[r];return a==null?{x:e.left,y:0}:{x:e.left,y:a}}}),F2e=(e,t)=>{var n=bl(e,t);if(n!=null)return M2e(e,n.orientation,n.mirror)},B2e=be([ds,bl,F2e,(e,t)=>t],(e,t,n,r)=>{if(t!=null){var a=n==null?void 0:n[r];return a==null?{x:0,y:e.top}:{x:a,y:e.top}}}),kW=be(ds,bl,(e,t)=>{var n=typeof t.width=="number"?t.width:wx;return{width:n,height:e.height}}),E5=(e,t,n)=>{switch(t){case"xAxis":return _W(e,n).width;case"yAxis":return kW(e,n).height;default:return}},jW=(e,t,n,r)=>{if(n!=null){var a=n.allowDuplicatedCategory,i=n.type,o=n.dataKey,l=Oo(e,r),c=t.map(d=>d.value),u=c.filter(d=>d!=null);if(o&&l&&i==="category"&&a&&s9(u))return c}},bA=be([sn,Mx,Tr,Ar],jW),A5=be([sn,ZSe,ju,au,bA,yA,$x,pA,Ar],(e,t,n,r,a,i,o,l,c)=>{if(t!=null){var u=Oo(e,c);return{angle:t.angle,interval:t.interval,minTickGap:t.minTickGap,orientation:t.orientation,tick:t.tick,tickCount:t.tickCount,tickFormatter:t.tickFormatter,ticks:t.ticks,type:t.type,unit:t.unit,axisType:c,categoricalDomain:i,duplicateDomain:a,isCategorical:u,niceTicks:l,range:o,realScaleType:n,scale:r}}}),U2e=(e,t,n,r,a,i,o,l,c)=>{if(!(t==null||r==null)){var u=Oo(e,c),d=t.type,h=t.ticks,f=t.tickCount,m=n==="scaleBand"&&typeof r.bandwidth=="function"?r.bandwidth()/2:2,x=d==="category"&&r.bandwidth?r.bandwidth()/m:0;x=c==="angleAxis"&&i!=null&&i.length>=2?ws(i[0]-i[1])*2*x:x;var g=h||a;return g?g.map((y,b)=>{var v=o?o.indexOf(y):y,w=r.map(v);return Mt(w)?{index:b,coordinate:w+x,value:y,offset:x}:null}).filter(Ea):u&&l?l.map((y,b)=>{var v=r.map(y);return Mt(v)?{coordinate:v+x,value:y,index:b,offset:x}:null}).filter(Ea):r.ticks?r.ticks(f).map((y,b)=>{var v=r.map(y);return Mt(v)?{coordinate:v+x,value:y,index:b,offset:x}:null}).filter(Ea):r.domain().map((y,b)=>{var v=r.map(y);return Mt(v)?{coordinate:v+x,value:o?o[y]:y,index:b,offset:x}:null}).filter(Ea)}},NW=be([sn,Mf,ju,au,pA,$x,bA,yA,Ar],U2e),z2e=(e,t,n,r,a,i,o)=>{if(!(t==null||n==null||r==null||r[0]===r[1])){var l=Oo(e,o),c=t.tickCount,u=0;return u=o==="angleAxis"&&(r==null?void 0:r.length)>=2?ws(r[0]-r[1])*2*u:u,l&&i?i.map((d,h)=>{var f=n.map(d);return Mt(f)?{coordinate:f+u,value:d,index:h,offset:u}:null}).filter(Ea):n.ticks?n.ticks(c).map((d,h)=>{var f=n.map(d);return Mt(f)?{coordinate:f+u,value:d,index:h,offset:u}:null}).filter(Ea):n.domain().map((d,h)=>{var f=n.map(d);return Mt(f)?{coordinate:f+u,value:a?a[d]:d,index:h,offset:u}:null}).filter(Ea)}},cl=be([sn,Mf,au,$x,bA,yA,Ar],z2e),ul=be(Tr,au,(e,t)=>{if(!(e==null||t==null))return Yb(Yb({},e),{},{scale:t})}),W2e=be([Tr,ju,fA,yW],eA),K2e=be([W2e],TE);be((e,t,n)=>tA(e,n),K2e,(e,t)=>{if(!(e==null||t==null))return Yb(Yb({},e),{},{scale:t})});var H2e=be([sn,D0,M0],(e,t,n)=>{switch(e){case"horizontal":return t.some(r=>r.reversed)?"right-to-left":"left-to-right";case"vertical":return n.some(r=>r.reversed)?"bottom-to-top":"top-to-bottom";case"centric":case"radial":return"left-to-right";default:return}}),V2e=(e,t,n)=>{var r;return(r=e.renderedTicks[t])===null||r===void 0?void 0:r[n]};be([V2e],e=>{if(!(!e||e.length===0))return t=>{var n,r=1/0,a=e[0];for(var i of e){var o=Math.abs(i.coordinate-t);o<r&&(r=o,a=i)}return(n=a)===null||n===void 0?void 0:n.value}});var SW=e=>e.options.defaultTooltipEventType,CW=e=>e.options.validateTooltipEventTypes;function EW(e,t,n){if(e==null)return t;var r=e?"axis":"item";return n==null?t:n.includes(r)?r:t}function Lx(e,t){var n=SW(e),r=CW(e);return EW(t,n,r)}function q2e(e){return ot(t=>Lx(t,e))}var AW=(e,t)=>{var n,r=Number(t);if(!(No(r)||t==null))return r>=0?e==null||(n=e[r])===null||n===void 0?void 0:n.value:void 0},G2e=e=>e.tooltip.settings,Lc={active:!1,index:null,dataKey:void 0,graphicalItemId:void 0,coordinate:void 0},Y2e={itemInteraction:{click:Lc,hover:Lc},axisInteraction:{click:Lc,hover:Lc},keyboardInteraction:Lc,syncInteraction:{active:!1,index:null,dataKey:void 0,label:void 0,coordinate:void 0,sourceViewBox:void 0,graphicalItemId:void 0},tooltipItemPayloads:[],settings:{shared:void 0,trigger:"hover",axisId:0,active:!1,defaultIndex:void 0}},TW=ga({name:"tooltip",initialState:Y2e,reducers:{addTooltipEntrySettings:{reducer(e,t){e.tooltipItemPayloads.push(pn(t.payload))},prepare:er()},replaceTooltipEntrySettings:{reducer(e,t){var n=t.payload,r=n.prev,a=n.next,i=zi(e).tooltipItemPayloads.indexOf(pn(r));i>-1&&(e.tooltipItemPayloads[i]=pn(a))},prepare:er()},removeTooltipEntrySettings:{reducer(e,t){var n=zi(e).tooltipItemPayloads.indexOf(pn(t.payload));n>-1&&e.tooltipItemPayloads.splice(n,1)},prepare:er()},setTooltipSettingsState(e,t){e.settings=t.payload},setActiveMouseOverItemIndex(e,t){e.syncInteraction.active=!1,e.syncInteraction.sourceViewBox=void 0,e.keyboardInteraction.active=!1,e.itemInteraction.hover.active=!0,e.itemInteraction.hover.index=t.payload.activeIndex,e.itemInteraction.hover.dataKey=t.payload.activeDataKey,e.itemInteraction.hover.graphicalItemId=t.payload.activeGraphicalItemId,e.itemInteraction.hover.coordinate=t.payload.activeCoordinate},mouseLeaveChart(e){e.itemInteraction.hover.active=!1,e.axisInteraction.hover.active=!1},mouseLeaveItem(e){e.itemInteraction.hover.active=!1},setActiveClickItemIndex(e,t){e.syncInteraction.active=!1,e.syncInteraction.sourceViewBox=void 0,e.itemInteraction.click.active=!0,e.keyboardInteraction.active=!1,e.itemInteraction.click.index=t.payload.activeIndex,e.itemInteraction.click.dataKey=t.payload.activeDataKey,e.itemInteraction.click.graphicalItemId=t.payload.activeGraphicalItemId,e.itemInteraction.click.coordinate=t.payload.activeCoordinate},setMouseOverAxisIndex(e,t){e.syncInteraction.active=!1,e.syncInteraction.sourceViewBox=void 0,e.axisInteraction.hover.active=!0,e.keyboardInteraction.active=!1,e.axisInteraction.hover.index=t.payload.activeIndex,e.axisInteraction.hover.dataKey=t.payload.activeDataKey,e.axisInteraction.hover.coordinate=t.payload.activeCoordinate},setMouseClickAxisIndex(e,t){e.syncInteraction.active=!1,e.syncInteraction.sourceViewBox=void 0,e.keyboardInteraction.active=!1,e.axisInteraction.click.active=!0,e.axisInteraction.click.index=t.payload.activeIndex,e.axisInteraction.click.dataKey=t.payload.activeDataKey,e.axisInteraction.click.coordinate=t.payload.activeCoordinate},setSyncInteraction(e,t){e.syncInteraction=t.payload},setKeyboardInteraction(e,t){e.keyboardInteraction.active=t.payload.active,e.keyboardInteraction.index=t.payload.activeIndex,e.keyboardInteraction.coordinate=t.payload.activeCoordinate}}}),to=TW.actions,Z2e=to.addTooltipEntrySettings,X2e=to.replaceTooltipEntrySettings,J2e=to.removeTooltipEntrySettings,Q2e=to.setTooltipSettingsState,OW=to.setActiveMouseOverItemIndex,eCe=to.mouseLeaveItem,IW=to.mouseLeaveChart,tCe=to.setActiveClickItemIndex,PW=to.setMouseOverAxisIndex,nCe=to.setMouseClickAxisIndex,Fm=to.setSyncInteraction,Jb=to.setKeyboardInteraction,rCe=TW.reducer;function T5(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Og(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
856t%2?T5(Object(n),!0).forEach(function(r){sCe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):T5(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function sCe(e,t,n){return(t=aCe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function aCe(e){var t=iCe(e,"string");return typeof t=="symbol"?t:t+""}function iCe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function oCe(e,t,n){return t==="axis"?n==="click"?e.axisInteraction.click:e.axisInteraction.hover:n==="click"?e.itemInteraction.click:e.itemInteraction.hover}function lCe(e){return e.index!=null}var RW=(e,t,n,r)=>{if(t==null)return Lc;var a=oCe(e,t,n);if(a==null)return Lc;if(a.active)return a;if(e.keyboardInteraction.active)return e.keyboardInteraction;if(e.syncInteraction.active&&e.syncInteraction.index!=null)return e.syncInteraction;var i=e.settings.active===!0;if(lCe(a)){if(i)return Og(Og({},a),{},{active:!0})}else if(r!=null)return{active:!0,coordinate:void 0,dataKey:void 0,index:r,graphicalItemId:void 0};return Og(Og({},Lc),{},{coordinate:a.coordinate})};function cCe(e){if(typeof e=="number")return Number.isFinite(e)?e:void 0;if(e instanceof Date){var t=e.valueOf();return Number.isFinite(t)?t:void 0}var n=Number(e);return Number.isFinite(n)?n:void 0}function uCe(e,t){var n=cCe(e),r=t[0],a=t[1];if(n===void 0)return!1;var i=Math.min(r,a),o=Math.max(r,a);return n>=i&&n<=o}function dCe(e,t,n){if(n==null||t==null)return!0;var r=hn(e,t);return r==null||!tl(n)?!0:uCe(r,n)}var ep=(e,t,n,r)=>{var a=e==null?void 0:e.index;if(a==null)return null;var i=Number(a);if(!Mt(i))return a;var o=0,l=1/0;t.length>0&&(l=t.length-1);var c=Math.max(o,Math.min(i,l)),u=t[c];return u==null||dCe(u,n,r)?String(c):null},DW=(e,t,n,r,a,i,o)=>{if(i!=null){var l=o[0],c=l==null?void 0:l.getPosition(i);if(c!=null)return c;var u=a==null?void 0:a[Number(i)];if(u)switch(n){case"horizontal":return{x:u.coordinate,y:(r.top+t)/2};default:return{x:(r.left+e)/2,y:u.coordinate}}}},MW=(e,t,n,r)=>{if(t==="axis")return e.tooltipItemPayloads;if(e.tooltipItemPayloads.length===0)return[];var a;if(n==="hover"?a=e.itemInteraction.hover.graphicalItemId:a=e.itemInteraction.click.graphicalItemId,e.syncInteraction.active&&a==null)return e.tooltipItemPayloads;if(a==null&&(r!=null||e.keyboardInteraction.active)){var i=e.tooltipItemPayloads[0];return i!=null?[i]:[]}return e.tooltipItemPayloads.filter(o=>{var l;return((l=o.settings)===null||l===void 0?void 0:l.graphicalItemId)===a})},$W=e=>e.options.tooltipPayloadSearcher,Ff=e=>e.tooltip;function O5(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function I5(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?O5(Object(n),!0).forEach(function(r){hCe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):O5(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function hCe(e,t,n){return(t=fCe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function fCe(e){var t=mCe(e,"string");return typeof t=="symbol"?t:t+""}function mCe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function pCe(e){if(typeof e=="string"||typeof e=="number")return e}function xCe(e){if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e}function gCe(e){if(typeof e=="string"||typeof e=="number")return e;if(typeof e=="function")return t=>e(t)}function P5(e){if(typeof e=="string")return e}function yCe(e){if(!(e==null||typeof e!="object")){var t="name"in e?pCe(e.name):void 0,n="unit"in e?xCe(e.unit):void 0,r="dataKey"in e?gCe(e.dataKey):void 0,a="payload"in e?e.payload:void 0,i="color"in e?P5(e.color):void 0,o="fill"in e?P5(e.fill):void 0;return{name:t,unit:n,dataKey:r,payload:a,color:i,fill:o}}}function bCe(e,t){return e??t}var LW=(e,t,n,r,a,i,o)=>
856{if(!(t==null||i==null)){var l=n.chartData,c=n.computedData,u=n.dataStartIndex,d=n.dataEndIndex,h=[];return e.reduce((f,m)=>{var x,g=m.dataDefinedOnItem,y=m.settings,b=bCe(g,l),v=Array.isArray(b)?bU(b,u,d):b,w=(x=y==null?void 0:y.dataKey)!==null&&x!==void 0?x:r,_=y==null?void 0:y.nameKey,k;if(r&&Array.isArray(v)&&!Array.isArray(v[0])&&o==="axis"?(k=a9(v,r,a),k==null&&(k=i(v,t,c,_))):k=i(v,t,c,_),Array.isArray(k))k.forEach(N=>{var E,A,C=yCe(N),T=C==null?void 0:C.name,S=C==null?void 0:C.dataKey,O=C==null?void 0:C.payload,R=I5(I5({},y),{},{name:T,unit:C==null?void 0:C.unit,color:(E=C==null?void 0:C.color)!==null&&E!==void 0?E:y==null?void 0:y.color,fill:(A=C==null?void 0:C.fill)!==null&&A!==void 0?A:y==null?void 0:y.fill});f.push(wR({tooltipEntrySettings:R,dataKey:S,payload:O,value:hn(O,S),name:T==null?void 0:String(T)}))});else{var j;f.push(wR({tooltipEntrySettings:y,dataKey:w,payload:k,value:hn(k,w),name:(j=hn(k,_))!==null&&j!==void 0?j:y==null?void 0:y.name}))}return f},h)}},vA=be([fs,eW,jE],Yz),vCe=be([e=>e.graphicalItems.cartesianItems,e=>e.graphicalItems.polarItems],(e,t)=>[...e,...t]),wCe=be([Ss,Rf],nA),Ud=be([vCe,fs,wCe],rA,{memoizeOptions:{resultEqualityCheck:K0}}),_Ce=be([Ud],e=>e.filter(W0)),FW=be([Ud],sA,{memoizeOptions:{resultEqualityCheck:K0}}),kCe=be([Ud],e=>e.some(t=>!t.data)),Ed=be([FW,Io],aA),jCe=be([_Ce,Io,fs],fz),wA=be([Ed,fs,Ud,Io,kCe,FW],aW),BW=be([fs],oA),NCe=be([fs],e=>e.allowDataOverflow),UW=be([BW,NCe],qU),SCe=be([Ud],e=>e.filter(W0)),CCe=be([jCe,SCe,Ex,iz],oW),ECe=be([CCe,Io,Ss,UW],lW),ACe=be([Ud],nW),TCe=be([Ed,fs,ACe,X0,Ss,Fke],uA,{memoizeOptions:{resultEqualityCheck:Tx}}),OCe=be([cW,Ss,Rf],Lf),ICe=be([OCe,Ss],hW),PCe=be([uW,Ss,Rf],Lf),RCe=be([PCe,Ss],fW),DCe=be([dW,Ss,Rf],Lf),MCe=be([DCe,Ss],mW),$Ce=be([ICe,MCe,RCe],Xb),LCe=be([fs,BW,UW,ECe,TCe,$Ce,sn,Ss],dA),tf=be([fs,sn,Ed,wA,Ex,Ss,LCe],hA),FCe=be([tf,fs,vA],mA),BCe=be([fs,tf,FCe,Ss],xA),zW=e=>{var t=Ss(e),n=Rf(e),r=!1;return $x(e,t,n,r)},WW=be([fs,zW],F0),UCe=be([fs,vA,BCe,WW],eA),KW=be([UCe],TE),zCe=be([sn,wA,fs,Ss],jW),WCe=be([sn,wA,fs,Ss],bW),KCe=(e,t,n,r,a,i,o,l)=>{if(t){var c=t.type,u=Oo(e,l);if(r){var d=n==="scaleBand"&&r.bandwidth?r.bandwidth()/2:2,h=c==="category"&&r.bandwidth?r.bandwidth()/d:0;return h=l==="angleAxis"&&a!=null&&(a==null?void 0:a.length)>=2?ws(a[0]-a[1])*2*h:h,u&&o?o.map((f,m)=>{var x=r.map(f);return Mt(x)?{coordinate:x+h,value:f,index:m,offset:h}:null}).filter(Ea):r.domain().map((f,m)=>{var x=r.map(f);return Mt(x)?{coordinate:x+h,value:i?i[f]:f,index:m,offset:h}:null}).filter(Ea)}}},yc=be([sn,fs,vA,KW,zW,zCe,WCe,Ss],KCe),_A=be([SW,CW,G2e],(e,t,n)=>EW(n.shared,e,t)),HW=e=>e.tooltip.settings.trigger,kA=e=>e.tooltip.settings.defaultIndex,Fx=be([Ff,_A,HW,kA],RW),iu=be([Fx,Ed,ef,tf],ep),VW=be([yc,iu],AW),jA=be([Fx],e=>{if(e)return e.dataKey}),qW=be([Fx],e=>{if(e)return e.graphicalItemId}),GW=be([Ff,_A,HW,kA],MW),HCe=be([xl,gl,sn,ds,yc,kA,GW],DW),VCe=be([Fx,HCe],(e,t)=>e!=null&&e.coordinate?e.coordinate:t),qCe=be([Fx],e=>{var t;return(t=e==null?void 0:e.active)!==null&&t!==void 0?t:!1}),GCe=be([GW,iu,Io,ef,VW,$W,_A],LW),YCe=be([GCe],e=>{if(e!=null){var t=e.map(n=>n.payload).filter(n=>n!=null);return Array.from(new Set(t))}});function R5(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function D5(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?R5(Object(n),!0).forEach(function(r){ZCe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):R5(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function ZCe(e,t,n){return(t=XCe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function XCe(e){var t=JCe(e,"string");return typeof t=="symbol"?t:t+""}function JCe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var QCe=()=>ot(fs),eEe=()=>{var e=QCe(),t=ot(yc),n=ot(KW);return su(!e||!n?void 0:D5(D5({},e),{},{scale:n}),t)};function M5(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function rh(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
856t%2?M5(Object(n),!0).forEach(function(r){tEe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):M5(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function tEe(e,t,n){return(t=nEe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function nEe(e){var t=rEe(e,"string");return typeof t=="symbol"?t:t+""}function rEe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var sEe=(e,t,n,r)=>{var a=t.find(i=>i&&i.index===n);if(a){if(e==="horizontal")return{x:a.coordinate,y:r.relativeY};if(e==="vertical")return{x:r.relativeX,y:a.coordinate}}return{x:0,y:0}},aEe=(e,t,n,r)=>{var a=t.find(u=>u&&u.index===n);if(a){if(e==="centric"){var i=a.coordinate,o=r.radius;return rh(rh(rh({},r),Zr(r.c
856x,r.cy,o,i)),{},{angle:i,radius:o})}var l=a.coordinate,c=r.angle;return rh(rh(rh({},r),Zr(r.cx,r.cy,l,c)),{},{angle:c,radius:l})}return{angle:0,clockWise:!1,cx:0,cy:0,endAngle:0,innerRadius:0,outerRadius:0,radius:0,startAngle:0,x:0,y:0}};function iEe(e,t){var n=e.relativeX,r=e.relativeY;return n>=t.left&&n<=t.left+t.width&&r>=t.top&&r<=t.top+t.height}var YW=(e,t,n,r,a)=>{var i,o=(i=t==null?void 0:t.length)!==null&&i!==void 0?i:0;if(o<=1||e==null)return 0;if(r==="angleAxis"&&a!=null&&Math.abs(Math.abs(a[1]-a[0])-360)<=1e-6)for(var l=a[1]-a[0],c=(I,$,P)=>[e,e+l,e-l].some(F=>(P?F>=I:F>I)&&F<=$),u=0;u<o;u++){var d,h,f,m,x,g=u>0?(d=n[u-1])===null||d===void 0?void 0:d.coordinate:(h=n[o-1])===null||h===void 0?void 0:h.coordinate,y=(f=n[u])===null||f===void 0?void 0:f.coordinate,b=u>=o-1?(m=n[0])===null||m===void 0?void 0:m.coordinate:(x=n[u+1])===null||x===void 0?void 0:x.coordinate,v=void 0;if(!(g==null||y==null||b==null))if(ws(y-g)!==ws(b-y)){var w=[];if(ws(b-y)===ws(a[1]-a[0])){v=b;var _=y+a[1]-a[0];w[0]=Math.min(_,(_+g)/2),w[1]=Math.max(_,(_+g)/2)}else{v=g;var k=b+a[1]-a[0];w[0]=Math.min(y,(k+y)/2),w[1]=Math.max(y,(k+y)/2)}var j=[Math.min(y,(v+y)/2),Math.max(y,(v+y)/2)];if(c(j[0],j[1],!1)||c(w[0],w[1],!0)){var N;return(N=n[u])===null||N===void 0?void 0:N.index}}else{var E=Math.min(g,b),A=Math.max(g,b);if(c((E+y)/2,(A+y)/2,!1)){var C;return(C=n[u])===null||C===void 0?void 0:C.index}}}else if(t)for(var T=0;T<o;T++){var S=t[T];if(S!=null){var O=t[T+1],R=t[T-1];if(T===0&&O!=null&&e<=(S.coordinate+O.coordinate)/2||T===o-1&&R!=null&&e>(S.coordinate+R.coordinate)/2||T>0&&T<o-1&&R!=null&&O!=null&&e>(S.coordinate+R.coordinate)/2&&e<=(S.coordinate+O.coordinate)/2)return S.index}}return-1},ZW=()=>ot(jE),NA=(e,t)=>t,XW=(e,t,n)=>n,SA=(e,t,n,r)=>r,oEe=be(yc,e=>j0(e,t=>t.coordinate)),CA=be([Ff,NA,XW,SA],RW),EA=be([CA,Ed,ef,tf],ep),lEe=(e,t,n)=>{if(t!=null){var r=Ff(e);return t==="axis"?n==="hover"?r.axisInteraction.hover.dataKey:r.axisInteraction.click.dataKey:n==="hover"?r.itemInteraction.hover.dataKey:r.itemInteraction.click.dataKey}},JW=be([Ff,NA,XW,SA],MW),Qb=be([xl,gl,sn,ds,yc,SA,JW],DW),cEe=be([CA,Qb],(e,t)=>{var n;return(n=e.coordinate)!==null&&n!==void 0?n:t}),QW=be([yc,EA],AW),uEe=be([JW,EA,Io,ef,QW,$W,NA],LW),dEe=be([CA,EA],(e,t)=>({isActive:e.active&&t!=null,activeIndex:t})),hEe=(e,t,n,r,a,i,o)=>{if(!(!e||!n||!r||!a)&&iEe(e,o)){var l=mwe(e,t),c=YW(l,i,a,n,r),u=sEe(t,a,c,e);return{activeIndex:String(c),activeCoordinate:u}}},fEe=(e,t,n,r,a,i,o)=>{if(!(!e||!r||!a||!i||!n)){var l=Cke(e,n);if(l){var c=pwe(l,t),u=YW(c,o,i,r,a),d=aEe(t,i,u,l);return{activeIndex:String(u),activeCoordinate:d}}}},mEe=(e,t,n,r,a,i,o,l)=>{if(!(!e||!t||!r||!a||!i))return t==="horizontal"||t==="vertical"?hEe(e,t,r,a,i,o,l):fEe(e,t,n,r,a,i,o)},pEe=be(e=>e.zIndex.zIndexMap,(e,t)=>t,(e,t,n)=>n,(e,t,n)=>{if(t!=null){var r=e[t];if(r!=null)return n?r.panoramaElement:r.element}}),xEe=be(e=>e.zIndex.zIndexMap,e=>{var t=Object.keys(e).map(r=>parseInt(r,10)).concat(Object.values(_r)),n=Array.from(new Set(t));return n.sort((r,a)=>r-a)},{memoizeOptions:{resultEqualityCheck:lje}});function $5(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function L5(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?$5(Object(n),!0).forEach(function(r){gEe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$5(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function gEe(e,t,n){return(t=yEe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function yEe(e){var t=bEe(e,"string");return typeof t=="symbol"?t:t+""}function bEe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var vEe={},wEe={zIndexMap:Object.values(_r).reduce((e,t)=>
856L5(L5({},e),{},{[t]:{element:void 0,panoramaElement:void 0,consumers:0}}),vEe)},_Ee=new Set(Object.values(_r));function kEe(e){return _Ee.has(e)}var eK=ga({name:"zIndex",initialState:wEe,reducers:{registerZIndexPortal:{reducer:(e,t)=>{var n=t.payload.zIndex;e.zIndexMap[n]?e.zIndexMap[n].consumers+=1:e.zIndexMap[n]={consumers:1,element:void 0,panoramaElement:void 0}},prepare:er()},unregisterZIndexPortal:{reducer:(e,t)=>{var n=t.payload.zIndex;e.zIndexMap[n]&&(e.zIndexMap[n].consumers-=1,e.zIndexMap[n].consumers<=0&&!kEe(n)&&delete e.zIndexMap[n])},prepare:er()},registerZIndexPortalElement:{reducer:(e,t)=>{var n=t.payload,r=n.zIndex,a=n.element,i=n.isPanorama;e.zIndexMap[r]?i?e.zIndexMap[r].panoramaElement=pn(a):e.zIndexMap[r].element=pn(a):e.zIndexMap[r]={consumers:0,element:i?void 0:pn(a),panoramaElement:i?pn(a):void 0}},prepare:er()},unregisterZIndexPortalElement:{reducer:(e,t)=>{var n=t.payload.zIndex;e.zIndexMap[n]&&(t.payload.isPanorama?e.zIndexMap[n].panoramaElement=void 0:e.zIndexMap[n].element=void 0)},prepare:er()}}}),ew=eK.actions,jEe=ew.registerZIndexPortal,ek=ew.unregisterZIndexPortal,NEe=ew.registerZIndexPortalElement,SEe=ew.unregisterZIndexPortalElement,CEe=eK.reducer;function Ks(e){var t=e.zIndex,n=e.children,r=e1e(),a=r&&t!==void 0&&t!==0,i=Jr(),o=p.useRef(void 0),l=p.useRef(new Set),c=Nn(),u=ot(h=>pEe(h,t,i));if(p.useLayoutEffect(()=>{if(!a){var h=l.current;h.forEach(m=>{c(ek({zIndex:m}))}),h.clear(),o.current=void 0;return}if(l.current.has(t)||(c(jEe({zIndex:t})),l.current.add(t)),u){o.current=u;var f=l.current;f.forEach(m=>{m!==t&&(c(ek({zIndex:m})),f.delete(m))})}},[c,t,a,u]),p.useLayoutEffect(()=>{var h=l.current;return()=>{h.forEach(f=>{c(ek({zIndex:f}))}),h.clear()}},[c]),!a)return n;var d=u??o.current;return d?Kv.createPortal(n,d):null}function gS(){return gS=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},gS.apply(null,arguments)}function F5(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Ig(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?F5(Object(n),!0).forEach(function(r){EEe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):F5(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function EEe(e,t,n){return(t=AEe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function AEe(e){var t=TEe(e,"string");return typeof t=="symbol"?t:t+""}function TEe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function OEe(e){var t=e.cursor,n=e.cursorComp,r=e.cursorProps;return p.isValidElement(t)?p.cloneElement(t,r):p.createElement(n,r)}function IEe(e){var t,n=e.coordinate,r=e.payload,a=e.index,i=e.offset,o=e.tooltipAxisBandSize,l=e.layout,c=e.cursor,u=e.tooltipEventType,d=e.chartName,h=n,f=r,m=a;if(!c||!h||d!=="ScatterChart"&&u!=="axis")return null;var x,g,y;if(d==="ScatterChart")x=h,g=$_e,y=_r.cursorLine;else if(d==="BarChart")x=L_e(l,h,i,o),g=bE,y=_r.cursorRectangle;else if(l==="radial"&&S9(h)){var b=zU(h),v=b.cx,w=b.cy,_=b.radius,k=b.startAngle,j=b.endAngle;x={cx:v,cy:w,startAngle:k,endAngle:j,innerRadius:_,outerRadius:_},g=KU,y=_r.cursorLine}else x={points:Oke(l,h,i)},g=Lh,y=_r.cursorLine;var N=typeof c=="object"&&"className"in c?c.className:void 0,E=Ig(Ig(Ig(Ig({stroke:"#ccc",pointerEvents:"none"},i),x),_d(c)),{},{payload:f,payloadIndex:m,className:un("recharts-tooltip-cursor",N)});return p.createElement(Ks,{zIndex:(t=e.zIndex)!==null&&t!==void 0?t:y},p.createElement(OEe,{cursor:c,cursorComp:g,cursorProps:E}))}function PEe(e){var t=eEe(),n=AU(),r=wu(),a=ZW();return t==null||n==null||r==null||a==null?null:p.createElement(IEe,gS({}
856,e,{offset:n,layout:r,tooltipAxisBandSize:t,chartName:a}))}var tK=p.createContext(null),REe=()=>p.useContext(tK),tk={exports:{}},B5;function DEe(){return B5||(B5=1,(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function a(c,u,d){this.fn=c,this.context=u,this.once=d||!1}function i(c,u,d,h,f){if(typeof d!="function")throw new TypeError("The listener must be a function");var m=new a(d,h||c,f),x=n?n+u:u;return c._events[x]?c._events[x].fn?c._events[x]=[c._events[x],m]:c._events[x].push(m):(c._events[x]=m,c._eventsCount++),c}function o(c,u){--c._eventsCount===0?c._events=new r:delete c._events[u]}function l(){this._events=new r,this._eventsCount=0}l.prototype.eventNames=function(){var u=[],d,h;if(this._eventsCount===0)return u;for(h in d=this._events)t.call(d,h)&&u.push(n?h.slice(1):h);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(d)):u},l.prototype.listeners=function(u){var d=n?n+u:u,h=this._events[d];if(!h)return[];if(h.fn)return[h.fn];for(var f=0,m=h.length,x=new Array(m);f<m;f++)x[f]=h[f].fn;return x},l.prototype.listenerCount=function(u){var d=n?n+u:u,h=this._events[d];return h?h.fn?1:h.length:0},l.prototype.emit=function(u,d,h,f,m,x){var g=n?n+u:u;if(!this._events[g])return!1;var y=this._events[g],b=arguments.length,v,w;if(y.fn){switch(y.once&&this.removeListener(u,y.fn,void 0,!0),b){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,d),!0;case 3:return y.fn.call(y.context,d,h),!0;case 4:return y.fn.call(y.context,d,h,f),!0;case 5:return y.fn.call(y.context,d,h,f,m),!0;case 6:return y.fn.call(y.context,d,h,f,m,x),!0}for(w=1,v=new Array(b-1);w<b;w++)v[w-1]=arguments[w];y.fn.apply(y.context,v)}else{var _=y.length,k;for(w=0;w<_;w++)switch(y[w].once&&this.removeListener(u,y[w].fn,void 0,!0),b){case 1:y[w].fn.call(y[w].context);break;case 2:y[w].fn.call(y[w].context,d);break;case 3:y[w].fn.call(y[w].context,d,h);break;case 4:y[w].fn.call(y[w].context,d,h,f);break;default:if(!v)for(k=1,v=new Array(b-1);k<b;k++)v[k-1]=arguments[k];y[w].fn.apply(y[w].context,v)}}return!0},l.prototype.on=function(u,d,h){return i(this,u,d,h,!1)},l.prototype.once=function(u,d,h){return i(this,u,d,h,!0)},l.prototype.removeListener=function(u,d,h,f){var m=n?n+u:u;if(!this._events[m])return this;if(!d)return o(this,m),this;var x=this._events[m];if(x.fn)x.fn===d&&(!f||x.once)&&(!h||x.context===h)&&o(this,m);else{for(var g=0,y=[],b=x.length;g<b;g++)(x[g].fn!==d||f&&!x[g].once||h&&x[g].context!==h)&&y.push(x[g]);y.length?this._events[m]=y.length===1?y[0]:y:o(this,m)}return this},l.prototype.removeAllListeners=function(u){var d;return u?(d=n?n+u:u,this._events[d]&&o(this,d)):(this._events=new r,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=n,l.EventEmitter=l,e.exports=l})(tk)),tk.exports}var MEe=DEe();const $Ee=hl(MEe);var Fp=new $Ee,yS="recharts.syncEvent.tooltip",U5="recharts.syncEvent.brush",Bx=(e,t)=>{if(t&&Array.isArray(e)){var n=Number.parseInt(t,10);if(!No(n))return e[n]}},LEe={chartName:"",tooltipPayloadSearcher:()=>{},eventEmitter:void 0,defaultTooltipEventType:"axis"},nK=ga({name:"options",initialState:LEe,reducers:{createEventEmitter:e=>{e.eventEmitter==null&&(e.eventEmitter=Symbol("rechartsEventEmitter"))}}}),FEe=nK.reducer,BEe=nK.actions.createEventEmitter;function UEe(e){return e.tooltip.syncInteraction}var zEe={chartData:void 0,computedData:void 0,dataStartIndex:0,dataEndIndex:0},rK=ga({name:"chartData",initialState:zEe,reducers:{setChartData(e,t){if(e.chartData=pn(t.payload),t.payload==null){e.dataStartIndex=0,e.dataEndIndex=0;return}t.payload.length>0&&e.dataEndIndex!==t.payload.length-1&&(e.dataEndIndex=t.payload.length-1)},setComputedData(e,t){e.computedData=t.payload},setDataStartEndIndexes(e,t){var n=t.payload,r=n.startIndex,a=n.endIndex;r!=null&&(e.dataStartIndex=r),a!=null&&(e.dataEndIndex=a)}}}),AA=rK.actions,z5=AA.setChartData,WEe=AA.setDataStartEndIndexes;AA.setComputedData;var KEe=rK.reducer,HEe=["x","y"];function W5(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function sh(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
856t%2?W5(Object(n),!0).forEach(function(r){VEe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):W5(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function VEe(e,t,n){return(t=qEe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function qEe(e){var t=GEe(e,"string");return typeof t=="symbol"?t:t+""}function GEe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function YEe(e,t){if(e==null)return{};var n,r,a=ZEe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function ZEe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function XEe(){var e=ot(NE),t=ot(SE),n=Nn(),r=ot(oz),a=ot(yc),i=wu(),o=_x(),l=ot(c=>c.rootProps.className);p.useEffect(()=>{if(e==null)return bu;var c=(u,d,h)=>{if(t!==h&&e===u){if(d.payload.active===!1){n(Fm({active:!1,coordinate:void 0,dataKey:void 0,index:null,label:void 0,sourceViewBox:void 0,graphicalItemId:void 0}));return}if(r==="index"){var f;if(o&&d!==null&&d!==void 0&&(f=d.payload)!==null&&f!==void 0&&f.coordinate&&d.payload.sourceViewBox){var m=d.payload.coordinate,x=m.x,g=m.y,y=YEe(m,HEe),b=d.payload.sourceViewBox,v=b.x,w=b.y,_=b.width,k=b.height,j=sh(sh({},y),{},{x:o.x+(_?(x-v)/_:0)*o.width,y:o.y+(k?(g-w)/k:0)*o.height});n(sh(sh({},d),{},{payload:sh(sh({},d.payload),{},{coordinate:j})}))}else n(d);return}if(a!=null){var N;if(typeof r=="function"){var E={activeTooltipIndex:d.payload.index==null?void 0:Number(d.payload.index),isTooltipActive:d.payload.active,activeIndex:d.payload.index==null?void 0:Number(d.payload.index),activeLabel:d.payload.label,activeDataKey:d.payload.dataKey,activeCoordinate:d.payload.coordinate},A=r(a,E);N=a[A]}else r==="value"&&(N=a.find(P=>String(P.value)===d.payload.label));var C=d.payload.coordinate;if(C==null||o==null){n(Fm({active:!1,coordinate:void 0,dataKey:void 0,index:null,label:void 0,sourceViewBox:void 0,graphicalItemId:void 0}));return}if(N==null){n(Fm({active:!1,coordinate:void 0,dataKey:void 0,index:null,label:void 0,sourceViewBox:d.payload.sourceViewBox,graphicalItemId:void 0}));return}var T=C.x,S=C.y,O=Math.min(T,o.x+o.width),R=Math.min(S,o.y+o.height),I={x:i==="horizontal"?N.coordinate:O,y:i==="horizontal"?R:N.coordinate},$=Fm({active:d.payload.active,coordinate:I,dataKey:d.payload.dataKey,index:String(N.index),label:d.payload.label,sourceViewBox:d.payload.sourceViewBox,graphicalItemId:d.payload.graphicalItemId});n($)}}};return Fp.on(yS,c),()=>{Fp.off(yS,c)}},[l,n,t,e,r,a,i,o])}function JEe(){var e=ot(NE),t=ot(SE),n=Nn();p.useEffect(()=>{if(e==null)return bu;var r=(a,i,o)=>{t!==o&&e===a&&n(WEe(i))};return Fp.on(U5,r),()=>{Fp.off(U5,r)}},[n,t,e])}function QEe(){var e=Nn();p.useEffect(()=>{e(BEe())},[e]),XEe(),JEe()}function eAe(e,t,n,r,a,i){var o=ot(x=>lEe(x,e,t)),l=ot(qW),c=ot(SE),u=ot(NE),d=ot(oz),h=ot(UEe),f=(h==null?void 0:h.sourceViewBox)!=null,m=_x();p.useEffect(()=>{if(!f&&u!=null&&c!=null){var x=Fm({active:i,coordinate:n,dataKey:o,index:a,label:typeof r=="number"?String(r):r,sourceViewBox:m,graphicalItemId:l});Fp.emit(yS,u,x,c)}},[f,n,o,l,a,r,c,u,d,i,m])}function K5(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function H5(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?K5(Object(n),!0).forEach(function(r){tAe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):K5(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function tAe(e,t,n){return(t=nAe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function nAe(e){var t=rAe(e,"string");return typeof t=="symbol"?t:t+""}function rAe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function sAe(e,t){return lAe(e)||oAe(e,t)||iAe(e,t)||aAe()}
856function aAe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 857In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function iAe(e,t){if(e){if(typeof e=="string")return V5(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?V5(e,t):void 0}}function V5(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function oAe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function lAe(e){if(Array.isArray(e))return e}function cAe(e){return e.dataKey}function uAe(e,t){return p.isValidElement(e)?p.cloneElement(e,t):typeof e=="function"?p.createElement(e,t):p.createElement(n_e,t)}var q5=[],dAe={allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",axisId:0,contentStyle:{},cursor:!0,filterNull:!0,includeHidden:!1,isAnimationActive:"auto",itemSorter:"name",itemStyle:{},labelStyle:{},offset:10,reverseDirection:{x:!1,y:!1},separator:" : ",trigger:"hover",useTranslate3d:!1,wrapperStyle:{}};function Da(e){var t,n,r=$r(e,dAe),a=r.active,i=r.allowEscapeViewBox,o=r.animationDuration,l=r.animationEasing,c=r.content,u=r.filterNull,d=r.isAnimationActive,h=r.offset,f=r.payloadUniqBy,m=r.position,x=r.reverseDirection,g=r.useTranslate3d,y=r.wrapperStyle,b=r.cursor,v=r.shared,w=r.trigger,_=r.defaultIndex,k=r.portal,j=r.axisId,N=Nn(),E=typeof _=="number"?String(_):_;p.useEffect(()=>{N(Q2e({shared:v,trigger:w,axisId:j,active:a,defaultIndex:E}))},[N,v,w,j,a,E]);var A=_x(),C=DU(),T=q2e(v),S=(t=ot(ee=>dEe(ee,T,w,E)))!==null&&t!==void 0?t:{},O=S.activeIndex,R=S.isActive,I=ot(ee=>uEe(ee,T,w,E)),$=ot(ee=>QW(ee,T,w,E)),P=ot(ee=>cEe(ee,T,w,E)),F=I,Z=REe(),D=(n=a??R)!==null&&n!==void 0?n:!1,H=W9([F,D]),Y=sAe(H,2),M=Y[0],z=Y[1],G=T==="axis"?$:void 0;eAe(T,w,P,G,O,D);var te=k??Z;if(te==null||A==null||T==null)return null;var re=F??q5;D||(re=q5),u&&re.length&&(re=$9(re.filter(ee=>ee.value!=null&&(ee.hide!==!0||r.includeHidden)),f,cAe));var L=re.length>0,q=H5(H5({},r),{},{payload:re,label:G,active:D,activeIndex:O,coordinate:P,accessibilityLayer:C}),me=p.createElement(k_e,{allowEscapeViewBox:i,animationDuration:o,animationEasing:l,isAnimationActive:d,active:D,coordinate:P,hasPayload:L,offset:h,position:m,reverseDirection:x,useTranslate3d:g,viewBox:A,wrapperStyle:y,lastBoundingBox:M,innerRef:z,hasPortalFromProps:!!k},uAe(c,q));return p.createElement(p.Fragment,null,Kv.createPortal(me,te),D&&p.createElement(PEe,{cursor:b,tooltipEventType:T,coordinate:P,payload:re,index:O}))}var zd=e=>null;zd.displayName="Cell";function hAe(e,t,n){return(t=fAe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function fAe(e){var t=mAe(e,"string");return typeof t=="symbol"?t:t+""}function mAe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}class pAe{constructor(t){hAe(this,"cache",new Map),this.maxSize=t}get(t){var n=this.cache.get(t);return n!==void 0&&(this.cache.delete(t),this.cache.set(t,n)),n}set(t,n){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxSize){var r=this.cache.keys().next().value;r!=null&&this.cache.delete(r)}this.cache.set(t,n)}clear(){this.cache.clear()}size(){return this.cache.size}}function G5(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function xAe(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
857t%2?G5(Object(n),!0).forEach(function(r){gAe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):G5(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function gAe(e,t,n){return(t=yAe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function yAe(e){var t=bAe(e,"string");return typeof t=="symbol"?t:t+""}function bAe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var vAe={cacheSize:2e3,enableCache:!0},sK=xAe({},vAe),Y5=new pAe(sK.cacheSize),wAe={position:"absolute",top:"-20000px",left:0,padding:0,margin:0,border:"none",whiteSpace:"pre"},Z5="recharts_measurement_span";function _Ae(e,t){var n=t.fontSize||"",r=t.fontFamily||"",a=t.fontWeight||"",i=t.fontStyle||"",o=t.letterSpacing||"",l=t.textTransform||"";return"".concat(e,"|").concat(n,"|").concat(r,"|").concat(a,"|").concat(i,"|").concat(o,"|").concat(l)}var X5=(e,t)=>{try{var n=document.getElementById(Z5);n||(n=document.createElement("span"),n.setAttribute("id",Z5),n.setAttribute("aria-hidden","true"),document.body.appendChild(n)),Object.assign(n.style,wAe,t),n.textContent="".concat(e);var r=n.getBoundingClientRect();return{width:r.width,height:r.height}}catch{return{width:0,height:0}}},tp=function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||Nx.isSsr)return{width:0,height:0};if(!sK.enableCache)return X5(t,n);var r=_Ae(t,n),a=Y5.get(r);if(a)return a;var i=X5(t,n);return Y5.set(r,i),i},aK;function ev(e,t){return SAe(e)||NAe(e,t)||jAe(e,t)||kAe()}function kAe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 858In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function jAe(e,t){if(e){if(typeof e=="string")return J5(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?J5(e,t):void 0}}function J5(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function NAe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function SAe(e){if(Array.isArray(e))return e}function CAe(e,t,n){return(t=EAe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function EAe(e){var t=AAe(e,"string");return typeof t=="symbol"?t:t+""}function AAe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Q5=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([*/])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,eD=/(-?\d+(?:\.\d+)?[a-zA-Z%]*)([+-])(-?\d+(?:\.\d+)?[a-zA-Z%]*)/,TAe=/^(px|cm|vh|vw|em|rem|%|mm|in|pt|pc|ex|ch|vmin|vmax|Q)$/,OAe=/(-?\d+(?:\.\d+)?)([a-zA-Z%]+)?/,IAe={cm:96/2.54,mm:96/25.4,pt:96/72,pc:96/6,in:96,Q:96/(2.54*40),px:1},PAe=["cm","mm","pt","pc","in","Q","px"];function RAe(e){return PAe.includes(e)}var Sh="NaN";function DAe(e,t){return e*IAe[t]}class $s{static parse(t){var n,r=(n=OAe.exec(t))!==null&&n!==void 0?n:[],a=ev(r,3),i=a[1],o=a[2];return i==null?$s.NaN:new $s(parseFloat(i),o??"")}constructor(t,n){this.num=t,this.unit=n,this.num=t,this.unit=n,No(t)&&(this.unit=""),n!==""&&!TAe.test(n)&&(this.num=NaN,this.unit=""),RAe(n)&&(this.num=DAe(t,n),this.unit="px")}add(t){return this.unit!==t.unit?new $s(NaN,""):new $s(this.num+t.num,this.unit)}subtract(t){return this.unit!==t.unit?new $s(NaN,""):new $s(this.num-t.num,this.unit)}multiply(t){return this.unit!==""&&t.unit!==""&&this.unit!==t.unit?new $s(NaN,""):new $s(this.num*t.num,this.unit||t.unit)}divide(t){return this.unit!==""&&t.unit!==""&&this.unit!==t.unit?new $s(NaN,""):new $s(this.num/t.num,this.unit||t.unit)}toString(){return"".concat(this.num).concat(this.unit)}isNaN(){return No(this.num)}}aK=$s;CAe($s,"NaN",new aK(NaN,""));function iK(e){if(e==null||e.includes(Sh))return Sh;for(var t=e;t.includes("*")||t.includes("/");
858){var n,r=(n=Q5.exec(t))!==null&&n!==void 0?n:[],a=ev(r,4),i=a[1],o=a[2],l=a[3],c=$s.parse(i??""),u=$s.parse(l??""),d=o==="*"?c.multiply(u):c.divide(u);if(d.isNaN())return Sh;t=t.replace(Q5,d.toString())}for(;t.includes("+")||/.-\d+(?:\.\d+)?/.test(t);){var h,f=(h=eD.exec(t))!==null&&h!==void 0?h:[],m=ev(f,4),x=m[1],g=m[2],y=m[3],b=$s.parse(x??""),v=$s.parse(y??""),w=g==="+"?b.add(v):b.subtract(v);if(w.isNaN())return Sh;t=t.replace(eD,w.toString())}return t}var tD=/\(([^()]*)\)/;function MAe(e){for(var t=e,n;(n=tD.exec(t))!=null;){var r=n,a=ev(r,2),i=a[1];t=t.replace(tD,iK(i))}return t}function $Ae(e){var t=e.replace(/\s+/g,"");return t=MAe(t),t=iK(t),t}function LAe(e){try{return $Ae(e)}catch{return Sh}}function nk(e){var t=LAe(e.slice(5,-1));return t===Sh?"":t}var FAe=["x","y","lineHeight","capHeight","fill","scaleToFit","textAnchor","verticalAnchor"],BAe=["dx","dy","angle","className","breakAll"];function bS(){return bS=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},bS.apply(null,arguments)}function nD(e,t){if(e==null)return{};var n,r,a=UAe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function UAe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function rD(e,t){return HAe(e)||KAe(e,t)||WAe(e,t)||zAe()}function zAe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 859In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function WAe(e,t){if(e){if(typeof e=="string")return sD(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?sD(e,t):void 0}}function sD(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function KAe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function HAe(e){if(Array.isArray(e))return e}var oK=/[ \f\n\r\t\v\u2028\u2029]+/,lK=e=>{var t=e.children,n=e.breakAll,r=e.style;try{var a=[];sr(t)||(n?a=t.toString().split(""):a=t.toString().split(oK));
859var i=a.map(l=>({word:l,width:tp(l,r).width})),o=n?0:tp(" ",r).width;return{wordsWithComputedWidth:i,spaceWidth:o}}catch{return null}};function cK(e){return e==="start"||e==="middle"||e==="end"||e==="inherit"}function VAe(e){return sr(e)||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}var uK=(e,t,n,r)=>e.reduce((a,i)=>{var o=i.word,l=i.width,c=a[a.length-1];if(c&&l!=null&&(t==null||r||c.width+l+n<Number(t)))c.words.push(o),c.width+=l+n;else{var u={words:[o],width:l};a.push(u)}return a},[]),dK=e=>e.reduce((t,n)=>t.width>n.width?t:n),qAe="â¦",aD=(e,t,n,r,a,i,o,l)=>{var c=e.slice(0,t),u=lK({breakAll:n,style:r,children:c+qAe});if(!u)return[!1,[]];var d=uK(u.wordsWithComputedWidth,i,o,l),h=d.length>a||dK(d).width>Number(i);return[h,d]},GAe=(e,t,n,r,a)=>{var i=e.maxLines,o=e.children,l=e.style,c=e.breakAll,u=rt(i),d=String(o),h=uK(t,r,n,a);if(!u||a)return h;var f=h.length>i||dK(h).width>Number(r);if(!f)return h;for(var m=0,x=d.length-1,g=0,y;m<=x&&g<=d.length-1;){var b=Math.floor((m+x)/2),v=b-1,w=aD(d,v,c,l,i,r,n,a),_=rD(w,2),k=_[0],j=_[1],N=aD(d,b,c,l,i,r,n,a),E=rD(N,1),A=E[0];if(!k&&!A&&(m=b+1),k&&A&&(x=b-1),!k&&A){y=j;break}g++}return y||h},iD=e=>{var t=sr(e)?[]:e.toString().split(oK);return[{words:t,width:void 0}]},YAe=e=>{var t=e.width,n=e.scaleToFit,r=e.children,a=e.style,i=e.breakAll,o=e.maxLines;if((t||n)&&!Nx.isSsr){var l,c,u=lK({breakAll:i,children:r,style:a});if(u){var d=u.wordsWithComputedWidth,h=u.spaceWidth;l=d,c=h}else return iD(r);return GAe({breakAll:i,children:r,maxLines:o,style:a},l,c,t,!!n)}return iD(r)},hK="#808080",ZAe={angle:0,breakAll:!1,capHeight:"0.71em",fill:hK,lineHeight:"1em",scaleToFit:!1,textAnchor:"start",verticalAnchor:"end",x:0,y:0},tw=p.forwardRef((e,t)=>{var n=$r(e,ZAe),r=n.x,a=n.y,i=n.lineHeight,o=n.capHeight,l=n.fill,c=n.scaleToFit,u=n.textAnchor,d=n.verticalAnchor,h=nD(n,FAe),f=p.useMemo(()=>YAe({breakAll:h.breakAll,children:h.children,maxLines:h.maxLines,scaleToFit:c,style:h.style,width:h.width}),[h.breakAll,h.children,h.maxLines,c,h.style,h.width]),m=h.dx,x=h.dy,g=h.angle,y=h.className,b=h.breakAll,v=nD(h,BAe);if(!aa(r)||!aa(a)||f.length===0)return null;var w=Number(r)+(rt(m)?m:0),_=Number(a)+(rt(x)?x:0);if(!Mt(w)||!Mt(_))return null;var k;switch(d){case"start":k=nk("calc(".concat(o,")"));break;case"middle":k=nk("calc(".concat((f.length-1)/2," * -").concat(i," + (").concat(o," / 2))"));break;default:k=nk("calc(".concat(f.length-1," * -").concat(i,")"));break}var j=[],N=f[0];if(c&&N!=null){var E=N.width,A=h.width;j.push("scale(".concat(rt(A)&&rt(E)?A/E:1,")"))}return g&&j.push("rotate(".concat(g,", ").concat(w,", ").concat(_,")")),j.length&&(v.transform=j.join(" ")),p.createElement("text",bS({},ha(v),{ref:t,x:w,y:_,className:un("recharts-text",y),textAnchor:u,fill:l.includes("url")?hK:l}),f.map((C,T)=>{var S=C.words.join(b?"":" ");return p.createElement("tspan",{x:w,dy:T===0?k:i,key:"".concat(S,"-").concat(T)},S)}))});tw.displayName="Text";var XAe=["labelRef"],JAe=["content"];function oD(e,t){if(e==null)return{};var n,r,a=QAe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function QAe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function lD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function qu(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?lD(Object(n),!0).forEach(function(r){e3e(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):lD(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function e3e(e,t,n){return(t=t3e(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function t3e(e){var t=n3e(e,"string");return typeof t=="symbol"?t:t+""}function n3e(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Fl(){return Fl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Fl.apply(null,arguments)}var fK=p.createContext(null),TA=e=>{var t=e.x,n=e.y,r=e.upperWidth,a=e.lowerWidth,i=e.width,o=e.height,l=e.children,c=p.useMemo(()=>({x:t,y:n,upperWidth:r,lowerWidth:a,width:i,height:o}),[t,n,r,a,i,o]);return p.createElement(fK.Provider,{value:c},l)},mK=()=>{var e=p.useContext(fK),t=_x();return e||(t?YC(t):void 0)},pK=p.createContext(null),r3e=e=>{var t=e.cx,n=e.cy,r=e.innerRadius,a=e.outerRadius,i=e.startAngle,o=e.endAngle,l=e.clockWise,c=e.children,u=p.useMemo(()=>({cx:t,cy:n,innerRadius:r,outerRadius:a,startAngle:i,endAngle:o,clockWise:l}),[t,n,r,a,i,o,l]);return p.createElement(pK.Provider,{value:u},c)},s3e=()=>{var e=p.useContext(pK),t=ot(hz);return e||t},a3e=e=>{var t=e.value,n=e.formatter,r=sr(e.children)?t:e.children;return typeof n=="function"?n(r):r},nw=e=>e!=null&&typeof e=="function",i3e=(e,t)=>
859{var n=ws(t-e),r=Math.min(Math.abs(t-e),360);return n*r},o3e=(e,t,n,r,a)=>{var i=e.offset,o=e.className,l=a.cx,c=a.cy,u=a.innerRadius,d=a.outerRadius,h=a.startAngle,f=a.endAngle,m=a.clockWise,x=(u+d)/2,g=i3e(h,f),y=g>=0?1:-1,b,v;switch(t){case"insideStart":b=h+y*i,v=m;break;case"insideEnd":b=f-y*i,v=!m;break;case"end":b=f+y*i,v=m;break;default:throw new Error("Unsupported position ".concat(t))}v=g<=0?v:!v;var w=Zr(l,c,x,b),_=Zr(l,c,x,b+(v?1:-1)*359),k="M".concat(w.x,",").concat(w.y,` 860 A`).concat(x,",").concat(x,",0,1,").concat(v?0:1,`, 861 `).concat(_.x,",").concat(_.y),j=sr(e.id)?Ap("recharts-radial-line-"):e.id;return p.createElement("text",Fl({},r,{dominantBaseline:"central",className:un("recharts-radial-bar-label",o)}),p.createElement("defs",null,p.createElement("path",{id:j,d:k})),p.createElement("textPath",{xlinkHref:"#".concat(j)},n))},l3e=(e,t,n)=>{var r=e.cx,a=e.cy,i=e.innerRadius,o=e.outerRadius,l=e.startAngle,c=e.endAngle,u=(l+c)/2;if(n==="outside"){var d=Zr(r,a,o+t,u),h=d.x,f=d.y;return{x:h,y:f,textAnchor:h>=r?"start":"end",verticalAnchor:"middle"}}if(n==="center")return{x:r,y:a,textAnchor:"middle",verticalAnchor:"middle"};if(n==="centerTop")return{x:r,y:a,textAnchor:"middle",verticalAnchor:"start"};if(n==="centerBottom")return{x:r,y:a,textAnchor:"middle",verticalAnchor:"end"};var m=(i+o)/2,x=Zr(r,a,m,u),g=x.x,y=x.y;return{x:g,y,textAnchor:"middle",verticalAnchor:"middle"}},vh=e=>e!=null&&"cx"in e&&rt(e.cx),c3e={angle:0,offset:5,zIndex:_r.label,position:"middle",textBreakAll:!1};function u3e(e){if(!vh(e))return e;var t=e.cx,n=e.cy,r=e.outerRadius,a=r*2;return{x:t-r,y:n-r,width:a,upperWidth:a,lowerWidth:a,height:a}}function Pc(e){var t,n,r=$r(e,c3e),a=r.viewBox,i=r.parentViewBox,o=r.position,l=r.value,c=r.children,u=r.content,d=r.className,h=d===void 0?"":d,f=r.textBreakAll,m=r.labelRef,x=s3e(),g=mK(),y=o==="center"?g:x??g,b,v,w;a==null?b=y:vh(a)?b=a:b=YC(a);var _=u3e(b);if(!b||sr(l)&&sr(c)&&!p.isValidElement(u)&&typeof u!="function")return null;var k=vh(b)&&(o==="insideStart"||o==="insideEnd"||o==="end");if(vh(b))k||(w=l3e(b,r.offset,r.position));else if(_){var j=i9({viewBox:_,position:o,offset:r.offset,parentViewBox:vh(i)?void 0:i,clamp:!0});w=qu(qu({x:j.x,y:j.y,textAnchor:j.horizontalAnchor,verticalAnchor:j.verticalAnchor},j.width!==void 0?{width:j.width}:{}),j.height!==void 0?{height:j.height}:{})}var N=qu(qu(qu(qu({},((t=w)===null||t===void 0?void 0:t.x)!==void 0?{x:w.x}:{}),((n=w)===null||n===void 0?void 0:n.y)!==void 0?{y:w.y}:{}),r),{},{viewBox:b});if(p.isValidElement(u)){N.labelRef;var E=oD(N,XAe);return p.cloneElement(u,E)}if(typeof u=="function"){N.content;var A=oD(N,JAe);if(v=p.createElement(u,A),p.isValidElement(v))return v}else v=a3e(r);var C=ha(r);return k&&vh(b)?o3e(r,o,v,C,b):w==null?null:p.createElement(Ks,{zIndex:r.zIndex},p.createElement(tw,Fl({ref:m,className:un("recharts-label",h)},C,w,{textAnchor:cK(C.textAnchor)?C.textAnchor:w.textAnchor,breakAll:f}),v))}Pc.displayName="Label";var d3e=(e,t,n)=>{if(!e)return null;var r={viewBox:t,labelRef:n};return e===!0?p.createElement(Pc,Fl({key:"label-implicit"},r)):aa(e)?p.createElement(Pc,Fl({key:"label-implicit",value:e},r)):p.isValidElement(e)?e.type===Pc?p.cloneElement(e,qu({key:"label-implicit"},r)):p.createElement(Pc,Fl({key:"label-implicit",content:e},r)):nw(e)?p.createElement(Pc,Fl({key:"label-implicit",content:e},r)):e&&typeof e=="object"?p.createElement(Pc,Fl({},e,{key:"label-implicit"},r)):null};function OA(e){var t=e.label,n=e.labelRef,r=mK();return d3e(t,r,n)||null}var h3e=["valueAccessor"],f3e=["dataKey","clockWise","id","textBreakAll","zIndex"];function tv(){return tv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},tv.apply(null,arguments)}function cD(e,t){if(e==null)return{};var n,r,a=m3e(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function m3e(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var p3e=e=>{var t=Array.isArray(e.value)?e.value[e.value.length-1]:e.value;if(VAe(t))return t},xK=p.createContext(void 0),IA=xK.Provider,gK=p.createContext(void 0),x3e=gK.Provider;function g3e(){return p.useContext(xK)}function y3e(){return p.useContext(gK)}function Dy(e){var t=e.valueAccessor,n=t===void 0?p3e:t,r=cD(e,h3e),a=r.dataKey;r.clockWise;var i=r.id,o=r.textBreakAll,l=r.zIndex,c=cD(r,f3e),u=g3e(),d=y3e(),h=u||d;return!h||!h.length?null:p.createElement(Ks,{zIndex:l??_r.label},p.createElement(rr,{className:"recharts-label-list"},h.map((f,m)=>{var x,g=sr(a)?n(f,m):hn(f.payload,a),y=sr(i)?{}:{id:"".concat(i,"-").concat(m)};return p.createElement(Pc,tv({key:"label-".concat(m)},ha(f),c,y,{fill:(x=r.fill)!==null&&x!==void 0?x:f.fill,parentViewBox:f.parentViewBox,value:g,textBreakAll:o,viewBox:f.viewBox,index:m,zIndex:0}))})))}Dy.displayName="LabelList";function rw(e){var t=e.label;return t?t===!0?p.createElement(Dy,{key:"labelList-implicit"}):p.isValidElement(t)||nw(t)?p.createElement(Dy,{key:"labelList-implicit",content:t}):typeof t=="object"?p.createElement(Dy,tv({key:"labelList-implicit"},t,{type:String(t.type)})):null:null}function vS(){return vS=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},vS.apply(null,arguments)}var yK=e=>{var t=e.cx,n=e.cy,r=e.r,a=e.className,i=un("recharts-dot",a);return rt(t)&&rt(n)&&rt(r)?p.createElement("circle",vS({},Ra(e),eE(e),{className:i,cx:t,cy:n,r})):null},bK=e=>e.graphicalItems.polarItems,b3e=be([Ar,Ax],nA),sw=be([bK,Tr,b3e],rA),v3e=be([sw],sA),aw=be([v3e,Sx],aA),w3e=be([aw,Tr,sw],sW);be([aw,Tr,sw],(e,t,n)=>n.length>0?e.flatMap(r=>n.flatMap(a=>{var i,o=hn(r,(i=t.dataKey)!==null&&i!==void 0?i:a.dataKey);return{value:o,errorDomain:[]}}
861)).filter(Boolean):(t==null?void 0:t.dataKey)!=null?e.map(r=>({value:hn(r,t.dataKey),errorDomain:[]})):e.map(r=>({value:r,errorDomain:[]})));var uD=()=>{},_3e=be([aw,Tr,sw,X0,Ar,Lke],uA),k3e=be([Tr,lA,cA,uD,_3e,uD,sn,Ar],dA),vK=be([Tr,sn,aw,w3e,Ex,Ar,k3e],hA),j3e=be([vK,Mf,ju],mA),N3e=be([Tr,vK,j3e,Ar],xA);be([ju,N3e],mz);var S3e={radiusAxis:{},angleAxis:{}},wK=ga({name:"polarAxis",initialState:S3e,reducers:{addRadiusAxis(e,t){e.radiusAxis[t.payload.id]=pn(t.payload)},removeRadiusAxis(e,t){delete e.radiusAxis[t.payload.id]},addAngleAxis(e,t){e.angleAxis[t.payload.id]=pn(t.payload)},removeAngleAxis(e,t){delete e.angleAxis[t.payload.id]}}}),iw=wK.actions;iw.addRadiusAxis;iw.removeRadiusAxis;iw.addAngleAxis;iw.removeAngleAxis;var C3e=wK.reducer;function _K(e){return e&&typeof e=="object"&&"className"in e&&typeof e.className=="string"?e.className:""}function dD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function hD(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?dD(Object(n),!0).forEach(function(r){E3e(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):dD(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function E3e(e,t,n){return(t=A3e(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function A3e(e){var t=T3e(e,"string");return typeof t=="symbol"?t:t+""}function T3e(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var O3e=(e,t)=>t,PA=be([bK,O3e],(e,t)=>e.filter(n=>n.type==="pie").find(n=>n.id===t)),I3e=[],RA=(e,t,n)=>(n==null?void 0:n.length)===0?I3e:n,kK=be([Sx,PA,RA],(e,t,n)=>{var r=e.chartData;if(t!=null){var a;if((t==null?void 0:t.data)!=null&&t.data.length>0?a=t.data:a=r,(!a||!a.length)&&n!=null&&(a=n.map(i=>hD(hD({},t.presentationProps),i.props))),a!=null)return a}}),P3e=be([kK,PA,RA],(e,t,n)=>{if(!(e==null||t==null))return e.map((r,a)=>{var i,o=hn(r,t.nameKey,t.name),l;return n!=null&&(i=n[a])!==null&&i!==void 0&&(i=i.props)!==null&&i!==void 0&&i.fill?l=n[a].props.fill:typeof r=="object"&&r!=null&&"fill"in r?l=r.fill:l=t.fill,{value:vu(o,t.dataKey),dataKey:t.dataKey,color:l,payload:r,type:t.legendType}})}),R3e=be([kK,PA,RA,ds],(e,t,n,r)=>{if(!(t==null||e==null))return HTe({offset:r,pieSettings:t,displayedData:e,cells:n})}),rk={exports:{}},Rn={};/** 862 * @license React 863 * react-is.production.js 864 * 865 * Copyright (c) Meta Platforms, Inc. and affiliates. 866 * 867 * This source code is licensed under the MIT license found in the 868 * LICENSE file in the root directory of this source tree. 869 */var fD;function D3e(){if(fD)return Rn;fD=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),i=Symbol.for("react.consumer"),o=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),u=Symbol.for("react.suspense_list"),d=Symbol.for("react.memo"),h=Symbol.for("react.lazy"),f=Symbol.for("react.view_transition"),m=Symbol.for("react.client.reference");function x(g){if(typeof g=="object"&&g!==null){var y=g.$$typeof;switch(y){case e:switch(g=g.type,g){case n:case a:case r:case c:case u:case f:return g;default:switch(g=g&&g.$$typeof,g){case o:case l:case h:case d:return g;case i:return g;default:return y}}case t:return y}}}return Rn.ContextConsumer=i,Rn.ContextProvider=o,Rn.Element=e,Rn.ForwardRef=l,Rn.Fragment=n,Rn.Lazy=h,Rn.Memo=d,Rn.Portal=t,Rn.Profiler=a,Rn.StrictMode=r,Rn.Suspense=c,Rn.SuspenseList=u,Rn.isContextConsumer=function(g){return x(g)===i},Rn.isContextProvider=function(g){return x(g)===o},Rn.isElement=function(g){return typeof g=="object"&&g!==null&&g.$$typeof===e},Rn.isForwardRef=function(g){return x(g)===l},Rn.isFragment=function(g){return x(g)===n},Rn.isLazy=function(g){return x(g)===h},Rn.isMemo=function(g){return x(g)===d},Rn.isPortal=function(g){return x(g)===t},Rn.isProfiler=function(g){return x(g)===a},Rn.isStrictMode=function(g){return x(g)===r},Rn.isSuspense=function(g){return x(g)===c},Rn.isSuspenseList=function(g){return x(g)===u},Rn.isValidElementType=function(g){return typeof g=="string"||typeof g=="function"||g===n||g===a||g===r||g===c||g===u||typeof g=="object"&&g!==null&&(g.$$typeof===h||g.$$typeof===d||g.$$typeof===o||g.$$typeof===i||g.$$typeof===l||g.$$typeof===m||g.getModuleId!==void 0)},Rn.typeOf=x,Rn}var mD;function M3e(){return mD||(mD=1,rk.exports=D3e()),rk.exports}var $3e=M3e(),pD=e=>typeof e=="string"?e:e?e.displayName||e.name||"Component":"",xD=null,sk=null,jK=e=>{if(e===xD&&Array.isArray(sk))return sk;var t=[];
869return p.Children.forEach(e,n=>{sr(n)||($3e.isFragment(n)?t=t.concat(jK(n.props.children)):t.push(n))}),sk=t,xD=e,t};function DA(e,t){var n=[],r=[];return Array.isArray(t)?r=t.map(a=>pD(a)):r=[pD(t)],jK(e).forEach(a=>{var i=kd(a,"type.displayName")||kd(a,"type.name");i&&r.indexOf(i)!==-1&&n.push(a)}),n}var MA=e=>e&&typeof e=="object"&&"clipDot"in e?!!e.clipDot:!0;function gD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function yD(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?gD(Object(n),!0).forEach(function(r){L3e(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):gD(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function L3e(e,t,n){return(t=F3e(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function F3e(e){var t=B3e(e,"string");return typeof t=="symbol"?t:t+""}function B3e(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function NK(e,t){return yD(yD({},t),e)}function U3e(e){return p.isValidElement(e)?e.props:e}function z3e(e,t){return p.cloneElement(e,NK(U3e(e),t))}function W3e(e){if("index"in e){var t=e.index;return typeof t=="number"||typeof t=="string"?t:void 0}}function K3e(e){return"isActive"in e&&e.isActive===!0}function ow(e){var t=e.option,n=e.DefaultShape,r=e.shapeProps,a=e.activeClassName,i=a===void 0?"recharts-active-shape":a,o=e.inActiveClassName,l=o===void 0?"recharts-shape":o,c=W3e(r),u;return p.isValidElement(t)?u=z3e(t,r):t===n?u=p.createElement(n,r):typeof t=="function"?u=t(r,c):typeof t=="object"?u=p.createElement(n,NK(t,r)):u=p.createElement(n,r),K3e(r)?p.createElement(rr,{className:i},u):p.createElement(rr,{className:l},u)}
869var $A=(e,t,n)=>{var r=Nn();return(a,i)=>o=>{e==null||e(a,i,o),r(OW({activeIndex:String(i),activeDataKey:t,activeCoordinate:a.tooltipPosition,activeGraphicalItemId:n}))}},LA=e=>{var t=Nn();return(n,r)=>a=>{e==null||e(n,r,a),t(eCe())}},FA=(e,t,n)=>{var r=Nn();return(a,i)=>o=>{e==null||e(a,i,o),r(tCe({activeIndex:String(i),activeDataKey:t,activeCoordinate:a.tooltipPosition,activeGraphicalItemId:n}))}};function lw(e){var t=e.tooltipEntrySettings,n=Nn(),r=Jr(),a=p.useRef(null);return p.useLayoutEffect(()=>{r||(a.current===null?n(Z2e(t)):a.current!==t&&n(X2e({prev:a.current,next:t})),a.current=t)},[t,n,r]),p.useLayoutEffect(()=>()=>{a.current&&(n(J2e(a.current)),a.current=null)},[n]),null}function BA(e){var t=e.legendPayload,n=Nn(),r=Jr(),a=p.useRef(null);return p.useLayoutEffect(()=>{r||(a.current===null?n(OU(t)):a.current!==t&&n(IU({prev:a.current,next:t})),a.current=t)},[n,r,t]),p.useLayoutEffect(()=>()=>{a.current&&(n(PU(a.current)),a.current=null)},[n]),null}function H3e(e){var t=e.legendPayload,n=Nn(),r=ot(sn),a=p.useRef(null);return p.useLayoutEffect(()=>{r!=="centric"&&r!=="radial"||(a.current===null?n(OU(t)):a.current!==t&&n(IU({prev:a.current,next:t})),a.current=t)},[n,r,t]),p.useLayoutEffect(()=>()=>{a.current&&(n(PU(a.current)),a.current=null)},[n]),null}function V3e(e,t){return Z3e(e)||Y3e(e,t)||G3e(e,t)||q3e()}function q3e(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 870In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function G3e(e,t){if(e){if(typeof e=="string")return bD(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?bD(e,t):void 0}}function bD(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Y3e(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function Z3e(e){if(Array.isArray(e))return e}var cw="index",UA="append";function zA(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[],r=[];for(var a of n)r.push({status:"removed",prev:a});for(var i=0;i<t.length;i++){var o=e[i],l=t[i];o!=null?r.push({status:"matched",prev:o,next:l}):r.push({status:"added",next:l})}return r}function X3e(e,t){var n=e.length/t.length,r=t.map((a,i)=>e[Math.floor(i*n)]);return zA(r,t)}function J3e(e,t){var n=t.map((r,a)=>e[a]);return zA(n,t)}function Q3e(e,t){for(var n=new Map,r=0;r<e.length;r++){var a=e[r];if(a!=null){var i=t(a,r);i!=null&&!n.has(i)&&n.set(i,a)}}return n}function eTe(e,t,n){var r=Q3e(e,n),a=new Set,i=t.map((h,f)=>{var m=n(h,f);if(m!=null){var x=r.get(m);if(x!==void 0)return a.add(m),x}}),o=[];for(var l of r){var c=V3e(l,2),u=c[0],d=c[1];a.has(u)||o.push(d)}return zA(i,t,o)}function wS(e,t,n){return t==null?null:e==null?t.map(r=>({status:"added",next:r})):n===cw?X3e(e,t):n===UA?J3e(e,t):eTe(e,t,n)}function SK(e,t){var n=p.useRef(e),r=p.useRef(t.current),a=p.useRef(!0);n.current!==e&&(n.current=e,r.current=t.current,a.current=!1);var i=p.useCallback(function(o,l){var c=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(l===0){a.current=!0;return}l===1&&(r.current=o),l>0&&a.current&&c&&(t.current=o)},[t]);return{startValue:r.current,syncStepValue:i}}function tTe(e,t){return aTe(e)||sTe(e,t)||rTe(e,t)||nTe()}function nTe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 871In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function rTe(e,t){if(e){if(typeof e=="string")return vD(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?vD(e,t):void 0}}function vD(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function sTe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}
871finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function aTe(e){if(Array.isArray(e))return e}function uw(e,t){var n=p.useState(!1),r=tTe(n,2),a=r[0],i=r[1],o=p.useCallback(()=>{typeof e=="function"&&e(),i(!0)},[e]),l=p.useCallback(()=>{typeof t=="function"&&t(),i(!1)},[t]);return{isAnimating:a,handleAnimationStart:o,handleAnimationEnd:l}}function dw(e){var t,n=e.animationInput,r=e.animationIdPrefix,a=e.items,i=e.previousItemsRef,o=e.isAnimationActive,l=e.animationBegin,c=e.animationDuration,u=e.animationEasing,d=e.onAnimationStart,h=e.onAnimationEnd,f=e.animationInterpolateFn,m=e.animationMatchBy,x=e.shouldUpdatePreviousRef,g=e.children,y=e.layout,b=BU(n,r),v=SK(b,i),w=(t=v.startValue)!==null&&t!==void 0?t:null,_=wS(w,a,m??cw);return p.createElement(FU,{animationId:b,begin:l,duration:c,isActive:o,easing:u,onAnimationEnd:h,onAnimationStart:d,key:b},k=>{var j=w==null,N=a==null?a:f(_,k,y),E=x?x(k):k>0;return v.syncStepValue(N,k,E),N==null?null:g(N,k,j)})}var ak;function iTe(e,t){return uTe(e)||cTe(e,t)||lTe(e,t)||oTe()}function oTe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 872In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function lTe(e,t){if(e){if(typeof e=="string")return wD(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?wD(e,t):void 0}}function wD(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function cTe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function uTe(e){if(Array.isArray(e))return e}var dTe=()=>{var e=p.useState(()=>Ap("uid-")),t=iTe(e,1),n=t[0];return n},CK=(ak=o6.useId)!==null&&ak!==void 0?ak:dTe;function hTe(e,t){var n=CK();return t||(e?"".concat(e,"-").concat(n):n)}var fTe=p.createContext(void 0),hw=e=>{var t=e.id,n=e.type,r=e.children,a=hTe("recharts-".concat(n),t);return p.createElement(fTe.Provider,{value:a},r(a))},mTe={cartesianItems:[],polarItems:[]},EK=ga({name:"graphicalItems",initialState:mTe,reducers:{addCartesianGraphicalItem:{reducer(e,t){e.cartesianItems.push(pn(t.payload))},prepare:er()},replaceCartesianGraphicalItem:{reducer(e,t){var n=t.payload,r=n.prev,a=n.next,i=zi(e).cartesianItems.indexOf(pn(r));i>-1&&(e.cartesianItems[i]=pn(a))},prepare:er()},removeCartesianGraphicalItem:{reducer(e,t){var n=zi(e).cartesianItems.indexOf(pn(t.payload));n>-1&&e.cartesianItems.splice(n,1)},prepare:er()},addPolarGraphicalItem:{reducer(e,t){e.polarItems.push(pn(t.payload))},prepare:er()},removePolarGraphicalItem:{reducer(e,t){var n=zi(e).polarItems.indexOf(pn(t.payload));n>-1&&e.polarItems.splice(n,1)},prepare:er()},replacePolarGraphicalItem:{reducer(e,t){var n=t.payload,r=n.prev,a=n.next,i=zi(e).polarItems.indexOf(pn(r));i>-1&&(e.polarItems[i]=pn(a))},prepare:er()}}}),Bf=EK.actions,pTe=Bf.addCartesianGraphicalItem,xTe=Bf.replaceCartesianGraphicalItem,gTe=Bf.removeCartesianGraphicalItem,yTe=Bf.addPolarGraphicalItem,bTe=Bf.removePolarGraphicalItem,vTe=Bf.replacePolarGraphicalItem,wTe=EK.reducer,_Te=e=>{var t=Nn(),n=p.useRef(null);return p.useLayoutEffect(()=>{n.current===null?t(pTe(e)):n.current!==e&&t(xTe({prev:n.current,next:e})),n.current=e},[t,e]),p.useLayoutEffect(()=>()=>{n.current&&(t(gTe(n.current)),n.current=null)},[t]),null},WA=p.memo(_Te),kTe=e=>{var t=Nn(),n=p.useRef(null);return p.useLayoutEffect(()=>{n.current===null?t(yTe(e)):n.current!==e&&t(vTe({prev:n.current,next:e})),n.current=e},[t,e]),p.useLayoutEffect(()=>()=>{n.current&&(t(bTe(n.current)),n.current=null)},[t]),null},jTe=p.memo(kTe),NTe=["key"],STe=["onMouseEnter","onClick","onMouseLeave"],CTe=["id"],ETe=["id"];function Ad(){return Ad=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Ad.apply(null,arguments)}function fw(e,t){if(e==null)return{};var n,r,a=ATe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function ATe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function _D(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function lr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
872t%2?_D(Object(n),!0).forEach(function(r){TTe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_D(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function TTe(e,t,n){return(t=OTe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function OTe(e){var t=ITe(e,"string");return typeof t=="symbol"?t:t+""}function ITe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var AK=KU;function PTe(e){var t=p.useMemo(()=>DA(e.children,zd),[e.children]),n=ot(r=>P3e(r,e.id,t));return n==null?null:p.createElement(H3e,{legendPayload:n})}function RTe(e){if(!(e==null||typeof e=="boolean"||typeof e=="function")){if(p.isValidElement(e)){var t,n=(t=e.props)===null||t===void 0?void 0:t.fill;return typeof n=="string"?n:void 0}var r=e.fill;return typeof r=="string"?r:void 0}}var DTe=p.memo(e=>{var t=e.dataKey,n=e.nameKey,r=e.sectors,a=e.stroke,i=e.strokeWidth,o=e.fill,l=e.name,c=e.hide,u=e.tooltipType,d=e.formatter,h=e.id,f=e.activeShape,m=RTe(f),x=r.map(y=>{var b=y.tooltipPayload;return m==null||b==null?b:b.map(v=>lr(lr({},v),{},{color:m,fill:m}))}),g={dataDefinedOnItem:x,getPosition:y=>{var b;return(b=r[Number(y)])===null||b===void 0?void 0:b.tooltipPosition},settings:{stroke:a,strokeWidth:i,fill:o,dataKey:t,nameKey:n,name:vu(l,t),hide:c,type:u,color:o,unit:"",formatter:d,graphicalItemId:h}};return p.createElement(lw,{tooltipEntrySettings:g})}),MTe=(e,t)=>e>t?"start":e<t?"end":"middle",$Te=(e,t,n)=>ca(typeof t=="function"?t(e):t,n,n*.8),LTe=(e,t,n)=>{var r=t.top,a=t.left,i=t.width,o=t.height,l=UU(i,o),c=a+ca(e.cx,i,i/2),u=r+ca(e.cy,o,o/2),d=ca(e.innerRadius,l,0),h=$Te(n,e.outerRadius,l),f=e.maxRadius||Math.sqrt(i*i+o*o)/2;return{cx:c,cy:u,innerRadius:d,outerRadius:h,maxRadius:f}},FTe=(e,t)=>{var n=ws(t-e),r=Math.min(Math.abs(t-e),360);return n*r},BTe=(e,t)=>{if(p.isValidElement(e))return p.cloneElement(e,t);if(typeof e=="function")return e(t);var n=un("recharts-pie-label-line",typeof e!="boolean"?e.className:"");t.key;var r=fw(t,NTe);return p.createElement(Lh,Ad({},r,{type:"linear",className:n}))},UTe=(e,t,n)=>{if(p.isValidElement(e))return p.cloneElement(e,t);var r=n;if(typeof e=="function"&&(r=e(t),p.isValidElement(r)))return r;var a=un("recharts-pie-label-text",_K(e));return p.createElement(tw,Ad({},t,{alignmentBaseline:"middle",className:a}),r)};function zTe(e){var t=e.sectors,n=e.props,r=e.showLabels,a=n.label,i=n.labelLine,o=n.dataKey;if(!r||!a||!t)return null;var l=Ra(n),c=_d(a),u=_d(i),d=typeof a=="object"&&"offsetRadius"in a&&typeof a.offsetRadius=="number"&&a.offsetRadius||20,h=t.map((f,m)=>{var x=(f.startAngle+f.endAngle)/2,g=Zr(f.cx,f.cy,f.outerRadius+d,x),y=lr(lr(lr(lr({},l),f),{},{stroke:"none"},c),{},{index:m,textAnchor:MTe(g.x,f.cx)},g),b=lr(lr(lr(lr({},l),f),{},{fill:"none",stroke:f.fill},u),{},{index:m,points:[Zr(f.cx,f.cy,f.outerRadius,x),g],key:"line"});return p.createElement(Ks,{zIndex:_r.label,key:"label-".concat(f.startAngle,"-").concat(f.endAngle,"-").concat(f.midAngle,"-").concat(m)},p.createElement(rr,null,i&&BTe(i,b),UTe(a,y,hn(f,o))))});return p.createElement(rr,{className:"recharts-pie-labels"},h)}function WTe(e){var t=e.sectors,n=e.props,r=e.showLabels,a=n.label;return typeof a=="object"&&a!=null&&"position"in a?p.createElement(rw,{label:a}):p.createElement(zTe,{sectors:t,props:n,showLabels:r})}function KTe(e){var t=e.sectors,n=e.activeShape,r=e.inactiveShape,a=e.allOtherPieProps,i=e.shape,o=e.id,l=e.animationElapsedTime,c=e.isAnimating,u=e.isEntrance,d=ot(iu),h=ot(jA),f=ot(qW),m=a.onMouseEnter,x=a.onClick,g=a.onMouseLeave,y=fw(a,STe),b=$A(m,a.dataKey,o),v=LA(g),w=FA(x,a.dataKey,o);return t==null||t.length===0?null:p.createElement(p.Fragment,null,t.map((_,k)=>{if((_==null?void 0:_.startAngle)===0&&(_==null?void 0:_.endAngle)===0&&t.length!==1)return null;var j=f==null||f===o,N=String(k)===d&&(h==null||a.dataKey===h)&&j,E=d?r:null,A=n&&N?n:E,C=lr(lr({},_),{},{stroke:_.stroke,tabIndex:-1,index:k,isActive:N,animationElapsedTime:l,isAnimating:c,isEntrance:u,[kU]:k,[jU]:o});return p.createElement(rr,Ad({key:"sector-".concat(_==null?void 0:_.startAngle,"-").concat(_==null?void 0:_.endAngle,"-").concat(_.midAngle,"-").concat(k),tabIndex:-1,
872className:"recharts-pie-sector"},yx(y,_,k),{onMouseEnter:b(_,k),onMouseLeave:v(_,k),onClick:w(_,k)}),p.createElement(ow,{option:A??i,DefaultShape:AK,shapeProps:C}))}))}function HTe(e){var t,n=e.pieSettings,r=e.displayedData,a=e.cells,i=e.offset,o=n.cornerRadius,l=n.startAngle,c=n.endAngle,u=n.dataKey,d=n.nameKey,h=n.tooltipType,f=Math.abs(n.minAngle),m=FTe(l,c),x=Math.abs(m),g=r.length<=1?0:(t=n.paddingAngle)!==null&&t!==void 0?t:0,y=r.filter(E=>hn(E,u,0)!==0).length,b=(x>=360?y:y-1)*g,v=r.reduce((E,A)=>{var C=hn(A,u,0);return E+(rt(C)?C:0)},0),w=f>0&&v>0&&r.some(E=>{var A=hn(E,u,0),C=(rt(A)?A:0)/v;return A!==0&&C*x<f}),_=w?f:0,k=x-y*_-b,j;if(v>0){var N;j=r.map((E,A)=>{var C=hn(E,u,0),T=hn(E,d,A),S=LTe(n,i,E),O=(rt(C)?C:0)/v,R,I=lr(lr({},E),a&&a[A]&&a[A].props),$=I!=null&&"fill"in I&&typeof I.fill=="string"?I.fill:n.fill;A?R=N.endAngle+ws(m)*g*(C!==0?1:0):R=l;var P=R+ws(m)*((C!==0?_:0)+O*k),F=(R+P)/2,Z=(S.innerRadius+S.outerRadius)/2,D=[{name:T,value:C,payload:I,dataKey:u,type:h,color:$,fill:$,graphicalItemId:n.id}],H=Zr(S.cx,S.cy,Z,F);return N=lr(lr(lr(lr({},n.presentationProps),{},{percent:O,cornerRadius:typeof o=="string"?parseFloat(o):o,name:T,tooltipPayload:D,midAngle:F,middleRadius:Z,tooltipPosition:H},I),S),{},{value:C,dataKey:u,startAngle:R,endAngle:P,payload:I,paddingAngle:C!==0?ws(m)*g:0}),N})}return j}function VTe(e){var t=e.showLabels,n=e.sectors,r=e.children,a=p.useMemo(()=>!t||!n?[]:n.map(i=>({value:i.value,payload:i.payload,clockWise:!1,parentViewBox:void 0,viewBox:{cx:i.cx,cy:i.cy,innerRadius:i.innerRadius,outerRadius:i.outerRadius,startAngle:i.startAngle,endAngle:i.endAngle,clockWise:!1},fill:i.fill})),[n,t]);return p.createElement(x3e,{value:t?a:void 0},r)}var qTe=(e,t)=>{if(e==null)return[];var n=[],r=e.find(i=>i.status!=="removed"),a=r?r.next.startAngle:0;return e.forEach((i,o)=>{if(i.status!=="removed"){var l=o>0?kd(i.next,"paddingAngle",0):0;if(i.status==="matched"){var c=qn(i.prev.endAngle-i.prev.startAngle,i.next.endAngle-i.next.startAngle,t),u=lr(lr({},i.next),{},{startAngle:a+l,endAngle:a+c+l});n.push(u),a=u.endAngle}else{var d=qn(0,i.next.endAngle-i.next.startAngle,t),h=lr(lr({},i.next),{},{startAngle:a+l,endAngle:a+d+l});n.push(h),a=h.endAngle}}}),n};function GTe(e){var t,n,r,a,i=e.props,o=e.previousSectorsRef,l=e.id,c=i.sectors,u=i.activeShape,d=i.inactiveShape,h=i.animationInterpolateFn,f=uw(i.onAnimationStart,i.onAnimationEnd),m=f.isAnimating,x=f.handleAnimationStart,g=f.handleAnimationEnd,y=Qwe();if(y==null)return null;var b=c[0];return p.createElement(VTe,{showLabels:!m,sectors:c},p.createElement(dw,{animationInput:i,animationIdPrefix:"recharts-pie-",items:c,previousItemsRef:o,isAnimationActive:i.isAnimationActive,animationBegin:i.animationBegin,animationDuration:i.animationDuration,animationEasing:i.animationEasing,onAnimationStart:x,onAnimationEnd:g,animationInterpolateFn:h,animationMatchBy:i.animationMatchBy,layout:y},(v,w,_)=>p.createElement(rr,null,p.createElement(KTe,{sectors:v,activeShape:u,inactiveShape:d,allOtherPieProps:i,shape:i.shape,id:l,animationElapsedTime:w,isAnimating:m||w<1,isEntrance:_}))),p.createElement(WTe,{showLabels:!m,sectors:c,props:i}),p.createElement(r3e,{cx:(t=b==null?void 0:b.cx)!==null&&t!==void 0?t:0,cy:(n=b==null?void 0:b.cy)!==null&&n!==void 0?n:0,innerRadius:(r=b==null?void 0:b.innerRadius)!==null&&r!==void 0?r:0,outerRadius:(a=b==null?void 0:b.outerRadius)!==null&&a!==void 0?a:0,startAngle:i.startAngle,endAngle:i.endAngle,clockWise:!1},i.children))}var YTe={animationBegin:400,animationDuration:1500,animationEasing:"ease",animationInterpolateFn:qTe,animationMatchBy:UA,cx:"50%",cy:"50%",dataKey:"value",endAngle:360,fill:"#808080",hide:!1,innerRadius:0,isAnimationActive:"auto",label:!1,labelLine:!0,legendType:"rect",minAngle:0,nameKey:"name",outerRadius:"80%",paddingAngle:0,rootTabIndex:0,shape:AK,startAngle:0,stroke:"#fff",zIndex:_r.area};function ZTe(e){var t=e.id,n=fw(e,CTe),r=e.hide,a=e.className,i=e.rootTabIndex,o=p.useMemo(()=>DA(e.children,zd),[e.children]),l=ot(d=>R3e(d,t,o)),c=p.useRef(null),u=un("recharts-pie",a);return r||l==null?(c.current=null,p.createElement(rr,{tabIndex:i,className:u})):p.createElement(Ks,{zIndex:e.zIndex},p.createElement(DTe,{dataKey:e.dataKey,nameKey:e.nameKey,sectors:l,stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,name:e.name,hide:e.hide,tooltipType:e.tooltipType,formatter:e.formatter,id:t,activeShape:e.activeShape}),p.createElement(rr,{tabIndex:i,className:u},p.createElement(GTe,{props:lr(lr({},n),{},{sectors:l}),previousSectorsRef:c,id:t})))}function XTe(e){var t=$r(e,YTe),n=t.id,r=fw(t,ETe),a=Ra(r);return p.createElement(hw,{id:n,type:"pie"},i=>p.createElement(p.Fragment,null,p.createElement(jTe,{type:"pie",id:i,data:r.data,dataKey:r.dataKey,hide:r.hide,angleAxisId:0,radiusAxisId:0,name:r.name,nameKey:r.nameKey,tooltipType:r.tooltipType,legendType:r.legendType,fill:r.fill,cx:r.cx,cy:r.cy,startAngle:r.startAngle,endAngle:r.endAngle,paddingAngle:r.paddingAngle,minAngle:r.minAngle,innerRadius:r.innerRadius,outerRadius:r.outerRadius,cornerRadius:r.cornerRadius,presentationProps:a,maxRadius:t.maxRadius}),p.createElement(PTe,Ad({},r,{id:i})),p.createElement(ZTe,Ad({},r,{id:i}))))}var TK=XTe;TK.displayName="Pie";var JTe=["points"];function kD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function ik(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
872t%2?kD(Object(n),!0).forEach(function(r){QTe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):kD(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function QTe(e,t,n){return(t=eOe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function eOe(e){var t=tOe(e,"string");return typeof t=="symbol"?t:t+""}function tOe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function nv(){return nv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},nv.apply(null,arguments)}function nOe(e,t){if(e==null)return{};var n,r,a=rOe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function rOe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function sOe(e){var t=e.option,n=e.dotProps,r=e.className;if(p.isValidElement(t))return p.cloneElement(t,n);if(typeof t=="function")return t(n);var a=un(r,typeof t!="boolean"?t.className:""),i=n??{};i.points;var o=nOe(i,JTe);return p.createElement(yK,nv({},o,{className:a}))}function aOe(e,t){return e==null?!1:t?!0:e.length===1}function OK(e){var t=e.points,n=e.dot,r=e.className,a=e.dotClassName,i=e.dataKey,o=e.baseProps,l=e.needClip,c=e.clipPathId,u=e.zIndex,d=u===void 0?_r.scatter:u;if(!aOe(t,n))return null;var h=MA(n),f=Rye(n),m=t.map((g,y)=>{var b,v,w=ik(ik(ik({r:3},o),f),{},{index:y,cx:(b=g.x)!==null&&b!==void 0?b:void 0,cy:(v=g.y)!==null&&v!==void 0?v:void 0,dataKey:i,value:g.value,payload:g.payload,points:t});return p.createElement(sOe,{key:"dot-".concat(y),option:n,dotProps:w,className:a})}),x={};return l&&c!=null&&(x.clipPath="url(#clipPath-".concat(h?"":"dots-").concat(c,")")),p.createElement(Ks,{zIndex:d},p.createElement(rr,nv({className:r},x),m))}function jD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Pg(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?jD(Object(n),!0).forEach(function(r){iOe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):jD(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function iOe(e,t,n){return(t=oOe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function oOe(e){var t=lOe(e,"string");return typeof t=="symbol"?t:t+""}function lOe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var IK=0,cOe={xAxis:{},yAxis:{},zAxis:{}},PK=ga({name:"cartesianAxis",initialState:cOe,reducers:{addXAxis:{reducer(e,t){e.xAxis[t.payload.id]=pn(t.payload)},prepare:er()},replaceXAxis:{reducer(e,t){var n=t.payload,r=n.prev,a=n.next;e.xAxis[r.id]!==void 0&&(r.id!==a.id&&delete e.xAxis[r.id],e.xAxis[a.id]=pn(a))},prepare:er()},removeXAxis:{reducer(e,t){delete e.xAxis[t.payload.id]},prepare:er()},addYAxis:{reducer(e,t){e.yAxis[t.payload.id]=pn(t.payload)},prepare:er()},replaceYAxis:{reducer(e,t){var n=t.payload,r=n.prev,a=n.next;e.yAxis[r.id]!==void 0&&(r.id!==a.id&&delete e.yAxis[r.id],e.yAxis[a.id]=pn(a))},prepare:er()},removeYAxis:{reducer(e,t){delete e.yAxis[t.payload.id]},prepare:er()},addZAxis:{reducer(e,t){e.zAxis[t.payload.id]=pn(t.payload)},prepare:er()},replaceZAxis:{reducer(e,t){var n=t.payload,r=n.prev,a=n.next;e.zAxis[r.id]!==void 0&&(r.id!==a.id&&delete e.zAxis[r.id],e.zAxis[a.id]=pn(a))},prepare:er()},removeZAxis:{reducer(e,t){delete e.zAxis[t.payload.id]},prepare:er()},updateYAxisWidth(e,t){var n=t.payload,r=n.id,a=n.width,i=e.yAxis[r];if(i){var o,l=i.widthHistory||[];if(l.length===3&&l[0]===l[2]&&a===l[1]&&a!==i.width&&Math.abs(a-((o=l[0])!==null&&o!==void 0?o:0))<=1)return;var c=[...l,a].slice(-3);e.yAxis[r]=Pg(Pg({},i),{},{width:a,widthHistory:c})}},updateXAxisHeight(e,t){var n=t.payload,r=n.id,a=n.height,i=e.xAxis[r];if(i){var o,l=i.heightHistory||[];if(l.length===3&&l[0]===l[2]&&a===l[1]&&a!==i.height&&Math.abs(a-((o=l[0])!==null&&o!==void 0?o:0))<=1)return;var c=[...l,a].slice(-3);e.xAxis[r]=Pg(Pg({},i),{},{height:a,heightHistory:c})}}}}),Po=PK.actions,uOe=Po.addXAxis,dOe=Po.replaceXAxis,hOe=Po.removeXAxis,fOe=Po.addYAxis,mOe=Po.replaceYAxis,pOe=Po.removeYAxis;Po.addZAxis;Po.replaceZAxis;Po.removeZAxis;var xOe=Po.updateYAxisWidth,gOe=Po.updateXAxisHeight,yOe=PK.reducer,bOe=be([ds],e=>({top:e.top,bottom:e.bottom,left:e.left,right:e.right})),vOe=be([bOe,xl,gl],(e,t,n)=>{if(!(!e||t==null||n==null))return{x:e.left,y:e.top,width:Math.max(0,t-e.left-e.right),height:Math.max(0,n-e.top-e.bottom)}}),mw=()=>ot(vOe),wOe=()=>ot(YCe);function ND(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function ok(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
872t%2?ND(Object(n),!0).forEach(function(r){_Oe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ND(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function _Oe(e,t,n){return(t=kOe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function kOe(e){var t=jOe(e,"string");return typeof t=="symbol"?t:t+""}function jOe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var NOe=e=>{var t=e.point,n=e.childIndex,r=e.mainColor,a=e.activeDot,i=e.dataKey,o=e.clipPath;if(a===!1||t.x==null||t.y==null)return null;var l={index:n,dataKey:i,cx:t.x,cy:t.y,r:4,fill:r??"none",strokeWidth:2,stroke:"#fff",payload:t.payload,value:t.value},c=ok(ok(ok({},l),_d(a)),eE(a)),u;return p.isValidElement(a)?u=p.cloneElement(a,c):typeof a=="function"?u=a(c):u=p.createElement(yK,c),p.createElement(rr,{className:"recharts-active-dot",clipPath:o},u)};function _S(e){var t=e.points,n=e.mainColor,r=e.activeDot,a=e.itemDataKey,i=e.clipPath,o=e.zIndex,l=o===void 0?_r.activeDot:o,c=ot(iu),u=wOe();if(t==null||u==null)return null;var d=t.find(h=>u.includes(h.payload));return sr(d)?null:p.createElement(Ks,{zIndex:l},p.createElement(NOe,{point:d,childIndex:Number(c),mainColor:n,dataKey:a,activeDot:r,clipPath:i}))}function SOe(e,t){return TOe(e)||AOe(e,t)||EOe(e,t)||COe()}function COe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 873In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function EOe(e,t){if(e){if(typeof e=="string")return SD(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?SD(e,t):void 0}}function SD(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function AOe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function TOe(e){if(Array.isArray(e))return e}var CD=(e,t,n)=>{var r=n??e;if(!sr(r))return ca(r,t,0)},OOe=(e,t,n)=>{var r={},a=e.filter(W0),i=e.filter(u=>u.stackId==null),o=a.reduce((u,d)=>{var h=u[d.stackId];return h==null&&(h=[]),h.push(d),u[d.stackId]=h,u},r),l=Object.entries(o).map(u=>{var d,h=SOe(u,2),f=h[0],m=h[1],x=m.map(y=>y.dataKey),g=CD(t,n,(d=m[0])===null||d===void 0?void 0:d.barSize);return{stackId:f,dataKeys:x,barSize:g}}),c=i.map(u=>{var d=[u.dataKey].filter(f=>f!=null),h=CD(t,n,u.barSize);return{stackId:void 0,dataKeys:d,barSize:h}});return[...l,...c]};function ED(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Rg(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?ED(Object(n),!0).forEach(function(r){IOe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ED(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function IOe(e,t,n){return(t=POe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function POe(e){var t=ROe(e,"string");return typeof t=="symbol"?t:t+""}function ROe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function DOe(e,t,n,r,a){var i,o=r.length;if(!(o<1)){var l=ca(e,n,0,!0),c,u=[];
873if(Mt((i=r[0])===null||i===void 0?void 0:i.barSize)){var d=!1,h=n/o,f=r.reduce((v,w)=>v+(w.barSize||0),0);f+=(o-1)*l,f>=n&&(f-=(o-1)*l,l=0),f>=n&&h>0&&(d=!0,h*=.9,f=o*h);var m=Math.round((n-f)/2),x={offset:m-l,size:0};c=r.reduce((v,w)=>{var _,k={stackId:w.stackId,dataKeys:w.dataKeys,position:{offset:x.offset+x.size+l,size:d?h:(_=w.barSize)!==null&&_!==void 0?_:0}},j=[...v,k];return x=k.position,j},u)}else{var g=ca(t,n,0,!0);n-2*g-(o-1)*l<=0&&(l=0);var y=(n-2*g-(o-1)*l)/o;y>1&&(y=Math.round(y));var b=Mt(a)?Math.min(y,a):y;c=r.reduce((v,w,_)=>[...v,{stackId:w.stackId,dataKeys:w.dataKeys,position:{offset:g+o*(y-b)/2+(b+l)*_,size:b}}],u)}return c}}var MOe=(e,t,n,r,a,i,o)=>{var l=sr(o)?t:o,c=DOe(n,r,a!==i?a:i,e,l);return a!==i&&c!=null&&(c=c.map(u=>Rg(Rg({},u),{},{position:Rg(Rg({},u.position),{},{offset:u.position.offset-a/2})}))),c},$Oe=(e,t)=>{var n=z0(t);if(!(!e||n==null||t==null)){var r=t.stackId;if(r!=null){var a=e[r];if(a){var i=a.stackedData;if(i)return i.find(o=>o.key===n)}}}},LOe=(e,t)=>{if(!(e==null||t==null)){var n=e.find(r=>r.stackId===t.stackId&&t.dataKey!=null&&r.dataKeys.includes(t.dataKey));if(n!=null)return n.position}};function FOe(e,t){return e&&typeof e=="object"&&"zIndex"in e&&typeof e.zIndex=="number"&&Mt(e.zIndex)?e.zIndex:t}var RK=e=>{var t=e.chartData,n=Nn(),r=Jr();return p.useEffect(()=>r?()=>{}:(n(z5(t)),()=>{n(z5(void 0))}),[t,n,r]),null},AD={x:0,y:0,width:0,height:0,padding:{top:0,right:0,bottom:0,left:0}},DK=ga({name:"brush",initialState:AD,reducers:{setBrushSettings(e,t){return t.payload==null?AD:t.payload}}});DK.actions.setBrushSettings;var BOe=DK.reducer,MK=(e,t)=>{var n=e.x,r=e.y,a=t.x,i=t.y;return{x:Math.min(n,a),y:Math.min(r,i),width:Math.abs(a-n),height:Math.abs(i-r)}},UOe=e=>{var t=e.x1,n=e.y1,r=e.x2,a=e.y2;return MK({x:t,y:n},{x:r,y:a})};function zOe(e){return(e%180+180)%180}var WOe=function(t){var n=t.width,r=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=zOe(a),o=i*Math.PI/180,l=Math.atan(r/n),c=o>l&&o<Math.PI-l?r/Math.sin(o):n/Math.cos(o);return Math.abs(c)},KOe={dots:[],areas:[],lines:[]},$K=ga({name:"referenceElements",initialState:KOe,reducers:{addDot:(e,t)=>{e.dots.push(t.payload)},removeDot:(e,t)=>{var n=zi(e).dots.findIndex(r=>r===t.payload);n!==-1&&e.dots.splice(n,1)},addArea:(e,t)=>{e.areas.push(t.payload)},removeArea:(e,t)=>{var n=zi(e).areas.findIndex(r=>r===t.payload);n!==-1&&e.areas.splice(n,1)},addLine:(e,t)=>{e.lines.push(pn(t.payload))},removeLine:(e,t)=>{var n=zi(e).lines.findIndex(r=>r===t.payload);n!==-1&&e.lines.splice(n,1)}}}),Uf=$K.actions;Uf.addDot;Uf.removeDot;var HOe=Uf.addArea,VOe=Uf.removeArea,qOe=Uf.addLine,GOe=Uf.removeLine,YOe=$K.reducer;function ZOe(e,t){return eIe(e)||QOe(e,t)||JOe(e,t)||XOe()}function XOe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 874In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function JOe(e,t){if(e){if(typeof e=="string")return TD(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?TD(e,t):void 0}}function TD(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function QOe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function eIe(e){if(Array.isArray(e))return e}var LK=p.createContext(void 0),tIe=e=>{var t=e.children,n=p.useState("".concat(Ap("recharts"),"-clip")),r=ZOe(n,1),a=r[0],i=mw();if(i==null)return null;var o=i.x,l=i.y,c=i.width,u=i.height;return p.createElement(LK.Provider,{value:a},p.createElement("defs",null,p.createElement("clipPath",{id:a},p.createElement("rect",{x:o,y:l,height:u,width:c}))),t)},FK=()=>p.useContext(LK);class BK{constructor(t){var n=t.x,r=t.y;this.xAxisScale=n,this.yAxisScale=r}
874map(t,n){var r,a,i=n.position;return{x:(r=this.xAxisScale.map(t.x,{position:i}))!==null&&r!==void 0?r:0,y:(a=this.yAxisScale.map(t.y,{position:i}))!==null&&a!==void 0?a:0}}mapWithFallback(t,n){var r,a,i=n.position,o=n.fallback,l,c;return o==="rangeMin"?l=this.yAxisScale.rangeMin():o==="rangeMax"?l=this.yAxisScale.rangeMax():l=0,o==="rangeMin"?c=this.xAxisScale.rangeMin():o==="rangeMax"?c=this.xAxisScale.rangeMax():c=0,{x:(r=this.xAxisScale.map(t.x,{position:i}))!==null&&r!==void 0?r:c,y:(a=this.yAxisScale.map(t.y,{position:i}))!==null&&a!==void 0?a:l}}isInRange(t){var n=t.x,r=t.y,a=n==null||this.xAxisScale.isInRange(n),i=r==null||this.yAxisScale.isInRange(r);return a&&i}}function OD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function ID(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?OD(Object(n),!0).forEach(function(r){nIe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):OD(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function nIe(e,t,n){return(t=rIe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function rIe(e){var t=sIe(e,"string");return typeof t=="symbol"?t:t+""}function sIe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function rv(){return rv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},rv.apply(null,arguments)}var aIe=(e,t)=>{var n;if(p.isValidElement(e))n=p.cloneElement(e,t);else if(typeof e=="function")n=e(t);else{if(!Mt(t.x1)||!Mt(t.y1)||!Mt(t.x2)||!Mt(t.y2))return null;n=p.createElement("line",rv({},t,{className:"recharts-reference-line-line"}))}return n},iIe=(e,t,n,r,a,i)=>{var o=i.x,l=i.width,c=a.map(e,{position:n});if(!Mt(c)||t==="discard"&&!a.isInRange(c))return null;var u=[{x:o+l,y:c},{x:o,y:c}];return r==="left"?u.reverse():u},oIe=(e,t,n,r,a,i)=>{var o=i.y,l=i.height,c=a.map(e,{position:n});if(!Mt(c)||t==="discard"&&!a.isInRange(c))return null;var u=[{x:c,y:o+l},{x:c,y:o}];return r==="top"?u.reverse():u},lIe=(e,t,n,r)=>{var a=[r.mapWithFallback(e[0],{position:n,fallback:"rangeMin"}),r.mapWithFallback(e[1],{position:n,fallback:"rangeMax"})];return t==="discard"&&a.some(i=>!r.isInRange(i))?null:a},cIe=(e,t,n,r,a,i,o)=>{var l=o.x,c=o.y,u=o.segment,d=o.ifOverflow,h=aa(l),f=aa(c);return f?iIe(c,d,r,i,t,n):h?oIe(l,d,r,a,e,n):u!=null&&u.length===2?lIe(u,d,r,new BK({x:e,y:t})):null};function uIe(e){var t=Nn();return p.useEffect(()=>(t(qOe(e)),()=>{t(GOe(e))})),null}function dIe(e){var t=e.xAxisId,n=e.yAxisId,r=e.shape,a=e.className,i=e.ifOverflow,o=Jr(),l=FK(),c=ot(N=>yl(N,t)),u=ot(N=>bl(N,n)),d=ot(N=>au(N,"xAxis",t,o)),h=ot(N=>au(N,"yAxis",n,o)),f=_x();if(!l||!f||c==null||u==null||d==null||h==null)return null;var m=cIe(d,h,f,e.position,c.orientation,u.orientation,e);if(!m)return null;var x=m[0],g=m[1];if(x==null||g==null)return null;var y=x.x,b=x.y,v=g.x,w=g.y,_=i==="hidden"?"url(#".concat(l,")"):void 0,k=ID(ID({clipPath:_},ha(e)),{},{x1:y,y1:b,x2:v,y2:w}),j=UOe({x1:y,y1:b,x2:v,y2:w});return p.createElement(Ks,{zIndex:e.zIndex},p.createElement(rr,{className:un("recharts-reference-line",a)},aIe(r,k),p.createElement(TA,rv({},j,{lowerWidth:j.width,upperWidth:j.width}),p.createElement(OA,{label:e.label}),e.children)))}var hIe={ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",label:!1,stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle",zIndex:_r.line};function UK(e){var t=$r(e,hIe);return p.createElement(p.Fragment,null,p.createElement(uIe,{yAxisId:t.yAxisId,xAxisId:t.xAxisId,ifOverflow:t.ifOverflow,x:t.x,y:t.y,segment:t.segment}),p.createElement(dIe,t))}UK.displayName="ReferenceLine";function PD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function RD(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
874t%2?PD(Object(n),!0).forEach(function(r){fIe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):PD(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function fIe(e,t,n){return(t=mIe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function mIe(e){var t=pIe(e,"string");return typeof t=="symbol"?t:t+""}function pIe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function sv(){return sv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},sv.apply(null,arguments)}var xIe=(e,t,n,r,a,i,o)=>{var l,c,u,d,h=o.x1,f=o.x2,m=o.y1,x=o.y2;if(a==null||i==null)return null;var g=new BK({x:a,y:i}),y={x:e?(l=a.map(h,{position:"start"}))!==null&&l!==void 0?l:null:a.rangeMin(),y:n?(c=i.map(m,{position:"start"}))!==null&&c!==void 0?c:null:i.rangeMin()},b={x:t?(u=a.map(f,{position:"end"}))!==null&&u!==void 0?u:null:a.rangeMax(),y:r?(d=i.map(x,{position:"end"}))!==null&&d!==void 0?d:null:i.rangeMax()};return o.ifOverflow==="discard"&&(!g.isInRange(y)||!g.isInRange(b))?null:MK(y,b)},gIe=(e,t)=>{var n;return p.isValidElement(e)?n=p.cloneElement(e,t):typeof e=="function"?n=e(t):n=p.createElement(bE,sv({},t,{className:"recharts-reference-area-rect"})),n};function yIe(e){var t=Nn();return p.useEffect(()=>(t(HOe(e)),()=>{t(VOe(e))})),null}function bIe(e){var t=e.x1,n=e.x2,r=e.y1,a=e.y2,i=e.className,o=e.shape,l=e.xAxisId,c=e.yAxisId,u=FK(),d=Jr(),h=ot(_=>au(_,"xAxis",l,d)),f=ot(_=>au(_,"yAxis",c,d));if(h==null||f==null)return null;var m=aa(t),x=aa(n),g=aa(r),y=aa(a);if(!m&&!x&&!g&&!y&&!o)return null;var b=xIe(m,x,g,y,h,f,e);if(!b&&!o)return null;var v=e.ifOverflow==="hidden",w=v?"url(#".concat(u,")"):void 0;return p.createElement(Ks,{zIndex:e.zIndex},p.createElement(rr,{className:un("recharts-reference-area",i)},gIe(o,RD(RD({clipPath:w},ha(e)),b)),b!=null&&p.createElement(TA,sv({},b,{lowerWidth:b.width,upperWidth:b.width}),p.createElement(OA,{label:e.label}),e.children)))}var vIe={ifOverflow:"discard",xAxisId:0,yAxisId:0,radius:0,fill:"#ccc",label:!1,fillOpacity:.5,stroke:"none",strokeWidth:1,zIndex:_r.area};function zK(e){var t=$r(e,vIe);return p.createElement(p.Fragment,null,p.createElement(yIe,{yAxisId:t.yAxisId,xAxisId:t.xAxisId,ifOverflow:t.ifOverflow,x1:t.x1,x2:t.x2,y1:t.y1,y2:t.y2}),p.createElement(bIe,t))}zK.displayName="ReferenceArea";var lk={},ck={},uk={},DD;function wIe(){return DD||(DD=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(n){if(!n||typeof n!="object")return!1;const r=Object.getPrototypeOf(n);return r===null||r===Object.prototype||Object.getPrototypeOf(r)===null?Object.prototype.toString.call(n)==="[object Object]":!1}e.isPlainObject=t})(uk)),uk}var MD;function _Ie(){return MD||(MD=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=R9(),n=wIe(),r=P9(),a=k0(),i=nE(),o=tE();function l(d,h,f){return c(d,h,void 0,void 0,void 0,void 0,f)}function c(d,h,f,m,x,g,y){const b=y(d,h,f,m,x,g);if(b!==void 0)return b;if(typeof d==typeof h)switch(typeof d){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return d===h;case"number":return d===h||Object.is(d,h);case"function":return d===h;case"object":return u(d,h,g,y)}return u(d,h,g,y)}function u(d,h,f,m){if(Object.is(d,h))return!0;let x=a.getTag(d),g=a.getTag(h);if(x===i.argumentsTag&&(x=i.objectTag),g===i.argumentsTag&&(g=i.objectTag),x!==g)return!1;switch(x){case i.stringTag:return d.toString()===h.toString();case i.numberTag:{const v=d.valueOf(),w=h.valueOf();return o.isEqualsSameValueZero(v,w)}case i.booleanTag:case i.dateTag:case i.symbolTag:return Object.is(d.valueOf(),h.valueOf());case i.regexpTag:return d.source===h.source&&d.flags===h.flags;case i.functionTag:return d===h}f=f??new Map;const y=f.get(d),b=f.get(h);if(y!=null&&b!=null)return y===h;f.set(d,h),f.set(h,d);try{switch(x){case i.mapTag:{if(d.size!==h.size)return!1;for(const[v,w]of d.entries())if(!h.has(v)||!c(w,h.get(v),v,d,h,f,m))return!1;return!0}case i.setTag:{if(d.size!==h.size)return!1;const v=Array.from(d.values()),w=Array.from(h.values());for(let _=0;_<v.length;_++){const k=v[_],j=w.findIndex(N=>c(k,N,void 0,d,h,f,m));if(j===-1)return!1;w.splice(j,1)}return!0}case i.arrayTag:case i.uint8ArrayTag:case i.uint8ClampedArrayTag:case i.uint16ArrayTag:case i.uint32ArrayTag:case i.bigUint64ArrayTag:case i.int8ArrayTag:case i.int16ArrayTag:case i.int32ArrayTag:case i.bigInt64ArrayTag:case i.float32ArrayTag:case i.float64ArrayTag:{if(t.isBuffer(d)!==t.isBuffer(h)||d.length!==h.length)return!1;for(let v=0;v<d.length;v++)if(!c(d[v],h[v],v,d,h,f,m))return!1;return!0}case i.arrayBufferTag:return d.byteLength!==h.byteLength?!1:u(new Uint8Array(d),new Uint8Array(h),f,m);case i.dataViewTag:return d.byteLength!==h.byteLength||d.byteOffset!==h.byteOffset?!1:u(new Uint8Array(d),new Uint8Array(h),f,m);case i.errorTag:return d.name===h.name&&d.message===h.message;
874case i.objectTag:{if(!(u(d.constructor,h.constructor,f,m)||n.isPlainObject(d)&&n.isPlainObject(h)))return!1;const w=[...Object.keys(d),...r.getSymbols(d)],_=[...Object.keys(h),...r.getSymbols(h)];if(w.length!==_.length)return!1;for(let k=0;k<w.length;k++){const j=w[k],N=d[j];if(!Object.hasOwn(h,j))return!1;const E=h[j];if(!c(N,E,j,d,h,f,m))return!1}return!0}default:return!1}}finally{f.delete(d),f.delete(h)}}e.isEqualWith=l})(ck)),ck}var dk={},$D;function kIe(){return $D||($D=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});function t(){}e.noop=t})(dk)),dk}var LD;function jIe(){return LD||(LD=1,(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"});const t=_Ie(),n=kIe();function r(a,i){return t.isEqualWith(a,i,n.noop)}e.isEqual=r})(lk)),lk}var hk,FD;function NIe(){return FD||(FD=1,hk=jIe().isEqual),hk}var SIe=NIe();const CIe=hl(SIe);function WK(e,t){if(t<1)return[];if(t===1)return e;for(var n=[],r=0;r<e.length;r+=t){var a=e[r];a!==void 0&&n.push(a)}return n}function EIe(e,t,n){var r={width:e.width+t.width,height:e.height+t.height};return WOe(r,n)}function AIe(e,t,n){var r=n==="width",a=e.x,i=e.y,o=e.width,l=e.height;return t===1?{start:r?a:i,end:r?a+o:i+l}:{start:r?a+o:i+l,end:r?a:i}}function Bp(e,t,n,r,a){if(e*t<e*r||e*t>e*a)return!1;var i=n();return e*(t-e*i/2-r)>=0&&e*(t+e*i/2-a)<=0}function TIe(e,t){return WK(e,t+1)}function OIe(e,t,n,r,a){for(var i=(r||[]).slice(),o=t.start,l=t.end,c=0,u=1,d=o,h=function(){var x=r==null?void 0:r[c];if(x===void 0)return{v:WK(r,u)};var g=c,y,b=()=>(y===void 0&&(y=n(x,g)),y),v=x.coordinate,w=c===0||Bp(e,v,b,d,l);w||(c=0,d=o,u+=1),w&&(d=v+e*(b()/2+a),c+=u)},f;u<=i.length;)if(f=h(),f)return f.v;return[]}function IIe(e,t,n,r,a){var i=(r||[]).slice(),o=i.length;if(o===0)return[];for(var l=t.start,c=t.end,u=1;u<=o;u++){for(var d=(o-1)%u,h=l,f=!0,m=function(){var _=r[g];if(_==null)return 0;var k=g,j,N=()=>(j===void 0&&(j=n(_,k)),j),E=_.coordinate,A=g===d||Bp(e,E,N,h,c);if(!A)return f=!1,1;A&&(h=E+e*(N()/2+a))},x,g=d;g<o&&(x=m(),!(x!==0&&x===1));g+=u);if(f){for(var y=[],b=d;b<o;b+=u){var v=r[b];v!=null&&y.push(v)}return y}}return[]}function BD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Qs(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?BD(Object(n),!0).forEach(function(r){PIe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):BD(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function PIe(e,t,n){return(t=RIe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function RIe(e){var t=DIe(e,"string");return typeof t=="symbol"?t:t+""}function DIe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function MIe(e,t,n,r,a){for(var i=(r||[]).slice(),o=i.length,l=t.start,c=t.end,u=function(f){var m=i[f];if(m==null)return 1;var x=m,g,y=()=>(g===void 0&&(g=n(m,f)),g);if(f===o-1){var b=e*(x.coordinate+e*y()/2-c);i[f]=x=Qs(Qs({},x),{},{tickCoord:b>0?x.coordinate-b*e:x.coordinate})}else i[f]=x=Qs(Qs({},x),{},{tickCoord:x.coordinate});if(x.tickCoord!=null){var v=Bp(e,x.tickCoord,y,l,c);v&&(c=x.tickCoord-e*(y()/2+a),i[f]=Qs(Qs({},x),{},{isShow:!0}))}},d=o-1;d>=0;d--)u(d);return i}function $Ie(e,t,n,r,a,i){var o=(r||[]).slice(),l=o.length,c=t.start,u=t.end;if(i){var d=r[l-1];if(d!=null){var h=n(d,l-1),f=e*(d.coordinate+e*h/2-u);if(o[l-1]=d=Qs(Qs({},d),{},{tickCoord:f>0?d.coordinate-f*e:d.coordinate}),d.tickCoord!=null){var m=Bp(e,d.tickCoord,()=>h,c,u);m&&(u=d.tickCoord-e*(h/2+a),o[l-1]=Qs(Qs({},d),{},{isShow:!0}))}}}for(var x=i?l-1:l,g=function(v){var w=o[v];if(w==null)return 1;var _=w,k,j=()=>(k===void 0&&(k=n(w,v)),k);if(v===0){var N=e*(_.coordinate-e*j()/2-c);o[v]=_=Qs(Qs({},_),{},{tickCoord:N<0?_.coordinate-N*e:_.coordinate})}else o[v]=_=Qs(Qs({},_),{},{tickCoord:_.coordinate});if(_.tickCoord!=null){var E=Bp(e,_.tickCoord,j,c,u);E&&(c=_.tickCoord+e*(j()/2+a),o[v]=Qs(Qs({},_),{},{isShow:!0}
874))}},y=0;y<x;y++)g(y);return o}function KA(e,t,n){var r=e.tick,a=e.ticks,i=e.viewBox,o=e.minTickGap,l=e.orientation,c=e.interval,u=e.tickFormatter,d=e.unit,h=e.angle;if(!a||!a.length||!r)return[];if(rt(c)||Nx.isSsr){var f;return(f=TIe(a,rt(c)?c:0))!==null&&f!==void 0?f:[]}var m=[],x=l==="top"||l==="bottom"?"width":"height",g=d&&x==="width"?tp(d,{fontSize:t,letterSpacing:n}):{width:0,height:0},y=(k,j)=>{var N=typeof u=="function"?u(k.value,j):k.value;return x==="width"?EIe(tp(N,{fontSize:t,letterSpacing:n}),g,h):tp(N,{fontSize:t,letterSpacing:n})[x]},b=a[0],v=a[1],w=a.length>=2&&b!=null&&v!=null?ws(v.coordinate-b.coordinate):1,_=AIe(i,w,x);return c==="equidistantPreserveStart"?OIe(w,_,y,a,o):c==="equidistantPreserveEnd"?IIe(w,_,y,a,o):(c==="preserveStart"||c==="preserveStartEnd"?m=$Ie(w,_,y,a,o,c==="preserveStartEnd"):m=MIe(w,_,y,a,o),m.filter(k=>k.isShow))}var LIe=e=>{var t=e.ticks,n=e.label,r=e.labelGapWithTick,a=r,i=e.tickSize,o=i===void 0?0:i,l=e.tickMargin,c=l===void 0?0:l,u=0;if(t){Array.from(t).forEach(m=>{if(m){var x=m.getBoundingClientRect();x.width>u&&(u=x.width)}});var d=n?n.getBoundingClientRect().width:0,h=o+c,f=u+h+d+(n?a:0);return Math.round(f)}return 0},FIe=e=>{var t=e.ticks,n=e.label,r=e.labelGapWithTick,a=r,i=e.tickSize,o=i===void 0?0:i,l=e.tickMargin,c=l===void 0?0:l,u=0;if(t){Array.from(t).forEach(m=>{if(m){var x=m.getBoundingClientRect();x.height>u&&(u=x.height)}});var d=n?n.getBoundingClientRect().height:0,h=o+c,f=u+h+d+(n?a:0);return Math.round(f)}return 0},BIe={xAxis:{},yAxis:{}},KK=ga({name:"renderedTicks",initialState:BIe,reducers:{setRenderedTicks:(e,t)=>{var n=t.payload,r=n.axisType,a=n.axisId,i=n.ticks;e[r][a]=pn(i)},removeRenderedTicks:(e,t)=>{var n=t.payload,r=n.axisType,a=n.axisId;delete e[r][a]}}}),HK=KK.actions,UIe=HK.setRenderedTicks,zIe=HK.removeRenderedTicks,WIe=KK.reducer,KIe=["axisLine","width","height","className","hide","ticks","axisType","axisId"];function UD(e,t){return GIe(e)||qIe(e,t)||VIe(e,t)||HIe()}function HIe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 875In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function VIe(e,t){if(e){if(typeof e=="string")return zD(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?zD(e,t):void 0}}function zD(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function qIe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function GIe(e){if(Array.isArray(e))return e}function YIe(e,t){if(e==null)return{};var n,r,a=ZIe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function ZIe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function Td(){return Td=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Td.apply(null,arguments)}function WD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Pr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?WD(Object(n),!0).forEach(function(r){XIe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):WD(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function XIe(e,t,n){return(t=JIe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function JIe(e){var t=QIe(e,"string");return typeof t=="symbol"?t:t+""}function QIe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var Jl={x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine
875:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd",zIndex:_r.axis};function ePe(e){var t=e.x,n=e.y,r=e.width,a=e.height,i=e.orientation,o=e.mirror,l=e.axisLine,c=e.otherSvgProps;if(!l)return null;var u=Pr(Pr(Pr({},c),Ra(l)),{},{fill:"none"});if(i==="top"||i==="bottom"){var d=+(i==="top"&&!o||i==="bottom"&&o);u=Pr(Pr({},u),{},{x1:t,y1:n+d*a,x2:t+r,y2:n+d*a})}else{var h=+(i==="left"&&!o||i==="right"&&o);u=Pr(Pr({},u),{},{x1:t+h*r,y1:n,x2:t+h*r,y2:n+a})}return p.createElement("line",Td({},u,{className:un("recharts-cartesian-axis-line",kd(l,"className"))}))}function tPe(e,t,n,r,a,i,o,l,c){var u,d,h,f,m,x,g=l?-1:1,y=e.tickSize||o,b=rt(e.tickCoord)?e.tickCoord:e.coordinate;switch(i){case"top":u=d=e.coordinate,f=n+ +!l*a,h=f-g*y,x=h-g*c,m=b;break;case"left":h=f=e.coordinate,d=t+ +!l*r,u=d-g*y,m=u-g*c,x=b;break;case"right":h=f=e.coordinate,d=t+ +l*r,u=d+g*y,m=u+g*c,x=b;break;default:u=d=e.coordinate,f=n+ +l*a,h=f+g*y,x=h+g*c,m=b;break}return{line:{x1:u,y1:h,x2:d,y2:f},tick:{x:m,y:x}}}function nPe(e,t){switch(e){case"left":return t?"start":"end";case"right":return t?"end":"start";default:return"middle"}}function rPe(e,t){switch(e){case"left":case"right":return"middle";case"top":return t?"start":"end";default:return t?"end":"start"}}function sPe(e){var t=e.option,n=e.tickProps,r=e.value,a,i=un(n.className,"recharts-cartesian-axis-tick-value");if(p.isValidElement(t))a=p.cloneElement(t,Pr(Pr({},n),{},{className:i}));else if(typeof t=="function")a=t(Pr(Pr({},n),{},{className:i}));else{var o="recharts-cartesian-axis-tick-value";typeof t!="boolean"&&(o=un(o,_K(t))),a=p.createElement(tw,Td({},n,{className:o}),r)}return a}function aPe(e){var t=e.ticks,n=e.axisType,r=e.axisId,a=Nn(),i=p.useRef(null);return p.useEffect(()=>{if(!(r==null||n==null)){var o=t.map(c=>({value:c.value,coordinate:c.coordinate,offset:c.offset,index:c.index})),l=i.current;l!=null&&l.axisId===r&&l.axisType===n&&CIe(l.ticks,o)||(i.current={ticks:o,axisId:r,axisType:n},a(UIe({ticks:o,axisId:r,axisType:n})))}},[a,t,r,n]),p.useEffect(()=>r==null||n==null?bu:()=>{a(zIe({axisId:r,axisType:n}))},[a,r,n]),null}var iPe=p.forwardRef((e,t)=>{var n=e.ticks,r=n===void 0?[]:n,a=e.tick,i=e.tickLine,o=e.stroke,l=e.tickFormatter,c=e.unit,u=e.padding,d=e.tickTextProps,h=e.orientation,f=e.mirror,m=e.x,x=e.y,g=e.width,y=e.height,b=e.tickSize,v=e.tickMargin,w=e.fontSize,_=e.letterSpacing,k=e.getTicksConfig,j=e.events,N=e.axisType,E=e.axisId,A=KA(Pr(Pr({},k),{},{ticks:r}),w,_),C=Ra(k),T=_d(a),S=cK(C.textAnchor)?C.textAnchor:nPe(h,f),O=rPe(h,f),R={};typeof i=="object"&&(R=i);var I=Pr(Pr({},C),{},{fill:"none"},R),$=A.map(Z=>Pr({entry:Z},tPe(Z,m,x,g,y,h,b,f,v))),P=$.map(Z=>{var D=Z.entry,H=Z.line;return p.createElement(rr,{className:"recharts-cartesian-axis-tick",key:"tick-".concat(D.value,"-").concat(D.coordinate,"-").concat(D.tickCoord)},i&&p.createElement("line",Td({},I,H,{className:un("recharts-cartesian-axis-tick-line",kd(i,"className"))})))}),F=$.map((Z,D)=>{var H,Y,M=Z.entry,z=Z.tick,G=Pr(Pr(Pr(Pr({verticalAnchor:O},C),{},{textAnchor:S,stroke:"none",fill:o},z),{},{index:D,payload:M,visibleTicksCount:A.length,tickFormatter:l,padding:u},d),{},{angle:(H=(Y=d==null?void 0:d.angle)!==null&&Y!==void 0?Y:C.angle)!==null&&H!==void 0?H:0}),te=Pr(Pr({},G),T);return p.createElement(rr,Td({className:"recharts-cartesian-axis-tick-label",key:"tick-label-".concat(M.value,"-").concat(M.coordinate,"-").concat(M.tickCoord)},yx(j,M,D)),a&&p.createElement(sPe,{option:a,tickProps:te,value:"".concat(typeof l=="function"?l(M.value,D):M.value).concat(c||"")}))});return p.createElement("g",{className:"recharts-cartesian-axis-ticks recharts-".concat(N,"-ticks")},p.createElement(aPe,{ticks:A,axisId:E,axisType:N}),F.length>0&&p.createElement(Ks,{zIndex:_r.label},p.createElement("g",{className:"recharts-cartesian-axis-tick-labels recharts-".concat(N,"-tick-labels"),ref:t},F)),P.length>0&&p.createElement("g",{className:"recharts-cartesian-axis-tick-lines recharts-".concat(N,"-tick-lines")},P))}),oPe=p.forwardRef((e,t)=>{var n=e.axisLine,r=e.width,a=e.height,i=e.className,o=e.hide,l=e.ticks,c=e.axisType,u=e.axisId,d=YIe(e,KIe),h=p.useState(""),f=UD(h,2),m=f[0],x=f[1],g=p.use
875State(""),y=UD(g,2),b=y[0],v=y[1],w=p.useRef(null);p.useImperativeHandle(t,()=>({getCalculatedWidth:()=>{var k;return LIe({ticks:w.current,label:(k=e.labelRef)===null||k===void 0?void 0:k.current,labelGapWithTick:5,tickSize:e.tickSize,tickMargin:e.tickMargin})},getCalculatedHeight:()=>{var k;return FIe({ticks:w.current,label:(k=e.labelRef)===null||k===void 0?void 0:k.current,labelGapWithTick:5,tickSize:e.tickSize,tickMargin:e.tickMargin})}}));var _=p.useCallback(k=>{if(k){var j=k.getElementsByClassName("recharts-cartesian-axis-tick-value");w.current=j;var N=j[0];if(N){var E=window.getComputedStyle(N),A=E.fontSize,C=E.letterSpacing;(A!==m||C!==b)&&(x(A),v(C))}}},[m,b]);return o||r!=null&&r<=0||a!=null&&a<=0?null:p.createElement(Ks,{zIndex:e.zIndex},p.createElement(rr,{className:un("recharts-cartesian-axis",i)},p.createElement(ePe,{x:e.x,y:e.y,width:r,height:a,orientation:e.orientation,mirror:e.mirror,axisLine:n,otherSvgProps:Ra(e)}),p.createElement(iPe,{ref:_,axisType:c,events:d,fontSize:m,getTicksConfig:e,height:e.height,letterSpacing:b,mirror:e.mirror,orientation:e.orientation,padding:e.padding,stroke:e.stroke,tick:e.tick,tickFormatter:e.tickFormatter,tickLine:e.tickLine,tickMargin:e.tickMargin,tickSize:e.tickSize,tickTextProps:e.tickTextProps,ticks:l,unit:e.unit,width:e.width,x:e.x,y:e.y,axisId:u}),p.createElement(TA,{x:e.x,y:e.y,width:e.width,height:e.height,lowerWidth:e.width,upperWidth:e.width},p.createElement(OA,{label:e.label,labelRef:e.labelRef}),e.children)))}),HA=p.forwardRef((e,t)=>{var n=$r(e,Jl);return p.createElement(oPe,Td({},n,{ref:t}))});HA.displayName="CartesianAxis";var lPe={grid:{stroke:"#ccc",fill:"none"}},VK=p.createContext(lPe);VK.Provider;var cPe=()=>p.useContext(VK),uPe=["x1","y1","x2","y2","key"],dPe=["offset"],hPe=["xAxisId","yAxisId"],fPe=["xAxisId","yAxisId"];function KD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function na(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?KD(Object(n),!0).forEach(function(r){mPe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):KD(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function mPe(e,t,n){return(t=pPe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function pPe(e){var t=xPe(e,"string");return typeof t=="symbol"?t:t+""}function xPe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function nd(){return nd=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},nd.apply(null,arguments)}function av(e,t){if(e==null)return{};var n,r,a=gPe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function gPe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var yPe=e=>{var t=e.fill;if(!t||t==="none")return null;var n=e.fillOpacity,r=e.x,a=e.y,i=e.width,o=e.height,l=e.ry;return p.createElement("rect",{x:r,y:a,ry:l,width:i,height:o,stroke:"none",fill:t,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function qK(e){var t=e.option,n=e.lineItemProps,r;if(p.isValidElement(t))r=p.cloneElement(t,n);else if(typeof t=="function")r=t(n);else{var a,i=n.x1,o=n.y1,l=n.x2,c=n.y2,u=n.key,d=av(n,uPe),h=(a=Ra(d))!==null&&a!==void 0?a:{};h.offset;var f=av(h,dPe),m=Array.isArray(f.strokeDasharray)?f.strokeDasharray.join(","):f.strokeDasharray;r=p.createElement("line",nd({},f,{strokeDasharray:m,x1:i,y1:o,x2:l,y2:c,fill:"none",key:u}))}return r}function bPe(e){var t=e.x,n=e.width,r=e.horizontal,a=r===void 0?!0:r,i=e.horizontalPoints;if(!a||!i||!i.length)return null;e.xAxisId,e.yAxisId;var o=av(e,hPe),l=i.map((c,u)=>{var d=na(na({},o),{},{x1:t,y1:c,x2:t+n,y2:c,key:"line-".concat(u),index:u});return p.createElement(qK,{key:"line-".concat(u),option:a,lineItemProps:d})});return p.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function vPe(e){var t=e.y,n=e.height,r=e.vertical,a=r===void 0?!0:r,i=e.verticalPoints;if(!a||!i||!i.length)return null;e.xAxisId,e.yAxisId;var o=av(e,fPe),l=i.map((c,u)=>{var d=na(na({},o),{},{x1:c,y1:t,x2:c,y2:t+n,key:"line-".concat(u),index:u});return p.createElement(qK,{option:a,lineItemProps:d,key:"line-".concat(u)})});return p.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function wPe(e){var t=e.horizontalFill,n=e.fillOpacity,r=e.x,a=e.
875y,i=e.width,o=e.height,l=e.horizontalPoints,c=e.horizontal,u=c===void 0?!0:c;if(!u||!t||!t.length||l==null)return null;var d=l.map(f=>Math.round(f+a-a)).sort((f,m)=>f-m);a!==d[0]&&d.unshift(0);var h=d.map((f,m)=>{var x=d[m+1],g=x==null,y=g?a+o-f:x-f;if(y<=0)return null;var b=m%t.length;return p.createElement("rect",{key:"react-".concat(m),y:f,x:r,height:y,width:i,stroke:"none",fill:t[b],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return p.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},h)}function _Pe(e){var t=e.vertical,n=t===void 0?!0:t,r=e.verticalFill,a=e.fillOpacity,i=e.x,o=e.y,l=e.width,c=e.height,u=e.verticalPoints;if(!n||!r||!r.length)return null;var d=u.map(f=>Math.round(f+i-i)).sort((f,m)=>f-m);i!==d[0]&&d.unshift(0);var h=d.map((f,m)=>{var x=d[m+1],g=x==null,y=g?i+l-f:x-f;if(y<=0)return null;var b=m%r.length;return p.createElement("rect",{key:"react-".concat(m),x:f,y:o,width:y,height:c,stroke:"none",fill:r[b],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return p.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},h)}var kPe=(e,t)=>{var n=e.xAxis,r=e.width,a=e.height,i=e.offset;return vU(KA(na(na(na({},Jl),n),{},{ticks:wU(n),viewBox:{x:0,y:0,width:r,height:a}})),i.left,i.left+i.width,t)},jPe=(e,t)=>{var n=e.yAxis,r=e.width,a=e.height,i=e.offset;return vU(KA(na(na(na({},Jl),n),{},{ticks:wU(n),viewBox:{x:0,y:0,width:r,height:a}})),i.top,i.top+i.height,t)},NPe={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],verticalFill:[],horizontalFill:[],xAxisId:0,yAxisId:0,syncWithTicks:!1,zIndex:_r.grid};function Ma(e){var t,n,r,a,i,o,l=mE(),c=pE(),u=AU(),d=na(na({},$r(e,NPe)),{},{x:rt(e.x)?e.x:u.left,y:rt(e.y)?e.y:u.top,width:rt(e.width)?e.width:u.width,height:rt(e.height)?e.height:u.height}),h=d.xAxisId,f=d.yAxisId,m=d.x,x=d.y,g=d.width,y=d.height,b=d.syncWithTicks,v=d.horizontalValues,w=d.verticalValues,_=Jr(),k=ot(P=>A5(P,"xAxis",h,_)),j=ot(P=>A5(P,"yAxis",f,_)),N=cPe(),E={stroke:(t=d.stroke)!==null&&t!==void 0?t:N.grid.stroke,strokeWidth:(n=d.strokeWidth)!==null&&n!==void 0?n:N.grid.strokeWidth,strokeOpacity:(r=d.strokeOpacity)!==null&&r!==void 0?r:N.grid.strokeOpacity,strokeDasharray:(a=d.strokeDasharray)!==null&&a!==void 0?a:N.grid.strokeDasharray};if(!ol(g)||!ol(y)||!rt(m)||!rt(x))return null;var A=d.verticalCoordinatesGenerator||kPe,C=d.horizontalCoordinatesGenerator||jPe,T=d.horizontalPoints,S=d.verticalPoints;if((!T||!T.length)&&typeof C=="function"){var O=v&&v.length,R=C({yAxis:j?na(na({},j),{},{ticks:O?v:j.ticks}):void 0,width:l??g,height:c??y,offset:u},O?!0:b);Ob(Array.isArray(R),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(typeof R,"]")),Array.isArray(R)&&(T=R)}if((!S||!S.length)&&typeof A=="function"){var I=w&&w.length,$=A({xAxis:k?na(na({},k),{},{ticks:I?w:k.ticks}):void 0,width:l??g,height:c??y,offset:u},I?!0:b);Ob(Array.isArray($),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(typeof $,"]")),Array.isArray($)&&(S=$)}return p.createElement(Ks,{zIndex:d.zIndex},p.createElement("g",{className:"recharts-cartesian-grid"},p.createElement(yPe,{fill:(i=d.fill)!==null&&i!==void 0?i:N.grid.fill,fillOpacity:(o=d.fillOpacity)!==null&&o!==void 0?o:N.grid.fillOpacity,x:d.x,y:d.y,width:d.width,height:d.height,ry:d.ry}),p.createElement(wPe,nd({},d,{horizontalPoints:T})),p.createElement(_Pe,nd({},d,{verticalPoints:S})),p.createElement(bPe,nd({},d,E,{offset:u,horizontalPoints:T,xAxis:k,yAxis:j})),p.createElement(vPe,nd({},d,E,{offset:u,verticalPoints:S,xAxis:k,yAxis:j}))))}Ma.displayName="CartesianGrid";var SPe=["animationElapsedTime","isAnimating","isEntrance","visibleLength","strokeDasharray","connectNulls"];function kS(){return kS=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},kS.apply(null,arguments)}function CPe(e,t){if(e==null)return{};var n,r,a=EPe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function EPe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function APe(e){try{return e&&e.getTotalLength&&e.getTotalLength()||0}catch{return 0}}function GK(e,t){return"".concat(t,"px ").concat(e,"px")}function TPe(e){return e.length%2!==0?[...e,...e]:e}function OPe(e,t){for(var n=[],r=0;r<t;++r)n.push(...e);return n}function IPe(e,t,n){var r=TPe(n),a=r.reduce((m,x)=>m+x,0);if(!a)return GK(t,e);for(var i=Math.floor(e/a),o=e%a,l=[],c=0,u=0;c<r.length;u+=(d=r[c])!==null&&d!==void 0?d:0,++c){var d,h=r[c];if(h!=null&&u+h>o){l=[...r.slice(0,c),o-u];break}}var f=l.length%2===0?[0,t]:[t];return[...OPe(r,i),...l,...f].map(m=>"".concat(m,"px")).join(", ")}function PPe(e,t,n){if(e){var r="".concat(e).split(/[,\s]+/gim).map(a=>parseFloat(a));return IPe(n,t,r)}return GK(t,n)}function RPe(e){e.animationElapsedTime,e.isAnimating,e.isEntrance;var t=e.visibleLength,n=e.strokeDasharray,r=e.connectNulls,a=CPe(e,SPe),i=r??!1,o;if(t!=null){var l,c=a.pathRef,u=APe((l=c==null?void 0:c.current)!==null&&l!==void 0?l:null);o=PPe(n,u,t)}else n!=null&&(o=String(n));return p.createElement(Lh,kS({},a,{connectNulls:i,strokeDasharray:o}))}function DPe(e){var t=p.useRef(0),n=p.useRef(0),r=p.useRef(!1),a=p.useRef(e);return a.current!==e&&(t.current=n.current,a.current=e),p.useCallback((i,o)=>
875{if(r.current)return null;var l=Math.min(Kl(t.current+i*o),o);return i>0&&o>0&&(n.current=Math.max(n.current,l),l>=o)?(r.current=!0,null):l},[])}var MPe={},YK=ga({name:"errorBars",initialState:MPe,reducers:{addErrorBar:(e,t)=>{var n=t.payload,r=n.itemId,a=n.errorBar;e[r]||(e[r]=[]),e[r].push(a)},replaceErrorBar:(e,t)=>{var n=t.payload,r=n.itemId,a=n.prev,i=n.next;e[r]&&(e[r]=e[r].map(o=>o.dataKey===a.dataKey&&o.direction===a.direction?i:o))},removeErrorBar:(e,t)=>{var n=t.payload,r=n.itemId,a=n.errorBar;e[r]&&(e[r]=e[r].filter(i=>i.dataKey!==a.dataKey||i.direction!==a.direction))}}}),VA=YK.actions;VA.addErrorBar;VA.replaceErrorBar;VA.removeErrorBar;var $Pe=YK.reducer,LPe=["children"];function FPe(e,t){if(e==null)return{};var n,r,a=BPe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function BPe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var UPe={data:[],xAxisId:"xAxis-0",yAxisId:"yAxis-0",dataPointFormatter:()=>({x:0,y:0,value:0}),errorBarOffset:0},zPe=p.createContext(UPe);function ZK(e){var t=e.children,n=FPe(e,LPe);return p.createElement(zPe.Provider,{value:n},t)}function pw(e,t){var n,r,a=ot(u=>yl(u,e)),i=ot(u=>bl(u,t)),o=(n=a==null?void 0:a.allowDataOverflow)!==null&&n!==void 0?n:Qr.allowDataOverflow,l=(r=i==null?void 0:i.allowDataOverflow)!==null&&r!==void 0?r:es.allowDataOverflow,c=o||l;return{needClip:c,needClipX:o,needClipY:l}}function qA(e){var t=e.xAxisId,n=e.yAxisId,r=e.clipPathId,a=mw(),i=pw(t,n),o=i.needClipX,l=i.needClipY,c=i.needClip,u=ot(w=>xW(w,t,!1)),d=ot(w=>gW(w,n,!1));if(!c||!a)return null;var h=a.x,f=a.y,m=a.width,x=a.height,g=o&&u?Math.min(u[0],u[1]):h-m/2,y=l&&d?Math.min(d[0],d[1]):f-x/2,b=o&&u?Math.abs(u[1]-u[0]):m*2,v=l&&d?Math.abs(d[1]-d[0]):x*2;return p.createElement("clipPath",{id:"clipPath-".concat(r)},p.createElement("rect",{x:g,y,width:b,height:v}))}var XK=(e,t,n,r)=>ul(e,"xAxis",t,r),JK=(e,t,n,r)=>cl(e,"xAxis",t,r),QK=(e,t,n,r)=>ul(e,"yAxis",n,r),eH=(e,t,n,r)=>cl(e,"yAxis",n,r),WPe=be([sn,XK,QK,JK,eH],(e,t,n,r,a)=>Oo(e,"xAxis")?su(t,r,!1):su(n,a,!1)),KPe=(e,t,n,r,a)=>a;function HPe(e){return e.type==="line"}var VPe=be([Dx,KPe],(e,t)=>e.filter(HPe).find(n=>n.id===t)),qPe=be([sn,XK,QK,JK,eH,VPe,WPe,Cx],(e,t,n,r,a,i,o,l)=>{var c=l.chartData,u=l.dataStartIndex,d=l.dataEndIndex;if(!(i==null||t==null||n==null||r==null||a==null||r.length===0||a.length===0||o==null||e!=="horizontal"&&e!=="vertical")){var h=i.dataKey,f=i.data,m;if(f!=null&&f.length>0?m=f:m=c==null?void 0:c.slice(u,d+1),m!=null)return mRe({layout:e,xAxis:t,yAxis:n,xAxisTicks:r,yAxisTicks:a,dataKey:h,bandSize:o,displayedData:m})}});function tH(e){var t=_d(e),n=3,r=2;if(t!=null){var a=t.r,i=t.strokeWidth,o=Number(a),l=Number(i);return(Number.isNaN(o)||o<0)&&(o=n),(Number.isNaN(l)||l<0)&&(l=r),{r:o,strokeWidth:l}}return{r:n,strokeWidth:r}}var GPe=["id"],YPe=["type","layout","connectNulls","needClip","shape","strokeDasharray"],ZPe=["activeDot","animateNewValues","animationBegin","animationDuration","animationEasing","connectNulls","dot","hide","isAnimationActive","label","legendType","xAxisId","yAxisId","id"];function iv(){return iv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},iv.apply(null,arguments)}function GA(e,t){if(e==null)return{};var n,r,a=XPe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function XPe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function HD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function Go(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
875t%2?HD(Object(n),!0).forEach(function(r){JPe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):HD(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function JPe(e,t,n){return(t=QPe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function QPe(e){var t=eRe(e,"string");return typeof t=="symbol"?t:t+""}function eRe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function tRe(e){try{return e&&e.getTotalLength&&e.getTotalLength()||0}catch{return 0}}function nRe(e){var t=0,n=0;for(var r of e)r.status==="matched"&&r.prev.x!=null&&r.next.x!=null&&(t+=r.next.x-r.prev.x,n++);return n>0?t/n:0}var rRe=(e,t)=>{if(e==null)return[];if(t===1)return e.flatMap(l=>l.status==="removed"?[]:[l.next]);var n=nRe(e),r=[];for(var a of e)if(a.status==="matched")r.push(Go(Go({},a.next),{},{x:qn(a.prev.x,a.next.x,t),y:qn(a.prev.y,a.next.y,t)}));else if(a.status==="added")if(a.next.x!=null){var i=a.next.x-n;r.push(Go(Go({},a.next),{},{x:qn(i,a.next.x,t),y:a.next.y}))}else r.push(a.next);else if(a.status==="removed"&&a.prev.x!=null){var o=a.prev.x+n;r.push(Go(Go({},a.prev),{},{x:qn(a.prev.x,o,t),y:a.prev.y}))}return r},YA={activeDot:!0,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",animationInterpolateFn:rRe,animationMatchBy:cw,connectNulls:!1,dot:!0,fill:"#fff",hide:!1,isAnimationActive:"auto",label:!1,legendType:"line",shape:RPe,stroke:"#3182bd",strokeWidth:1,xAxisId:0,yAxisId:0,zIndex:_r.line,type:"linear"},sRe=e=>{var t=e.dataKey,n=e.name,r=e.stroke,a=e.legendType,i=e.hide;return[{inactive:i,dataKey:t,type:a,color:r,value:vu(n,t),payload:e}]},aRe=p.memo(e=>{var t=e.dataKey,n=e.data,r=e.stroke,a=e.strokeWidth,i=e.fill,o=e.name,l=e.hide,c=e.unit,u=e.formatter,d=e.tooltipType,h=e.id,f={dataDefinedOnItem:n,getPosition:bu,settings:{stroke:r,strokeWidth:a,fill:i,dataKey:t,nameKey:void 0,name:vu(o,t),hide:l,type:d,color:r,unit:c,formatter:u,graphicalItemId:h}};return p.createElement(lw,{tooltipEntrySettings:f})});function iRe(e){var t=e.clipPathId,n=e.points,r=e.props,a=r.dot,i=r.dataKey,o=r.needClip;r.id;var l=GA(r,GPe),c=Ra(l);return p.createElement(OK,{points:n,dot:a,className:"recharts-line-dots",dotClassName:"recharts-line-dot",dataKey:i,baseProps:c,needClip:o,clipPathId:t})}function oRe(e){var t=e.showLabels,n=e.children,r=e.points,a=p.useMemo(()=>r==null?void 0:r.map(i=>{var o,l,c={x:(o=i.x)!==null&&o!==void 0?o:0,y:(l=i.y)!==null&&l!==void 0?l:0,width:0,lowerWidth:0,upperWidth:0,height:0};return Go(Go({},c),{},{value:i.value,payload:i.payload,viewBox:c,parentViewBox:void 0,fill:void 0})}),[r]);return p.createElement(IA,{value:t?a:void 0},n)}function lRe(e){var t=e.clipPathId,n=e.pathRef,r=e.points,a=e.props,i=e.animationElapsedTime,o=e.isAnimating,l=e.isEntrance,c=e.visibleLength,u=a.type,d=a.layout,h=a.connectNulls,f=a.needClip,m=a.shape,x=a.strokeDasharray,g=GA(a,YPe),y=Go(Go({},ha(g)),{},{fill:"none",className:"recharts-line-curve",clipPath:f?"url(#clipPath-".concat(t,")"):void 0,points:r,type:u,layout:d,connectNulls:h,strokeDasharray:x??a.strokeDasharray,pathRef:n,animationElapsedTime:i,isAnimating:o,isEntrance:a.animateNewValues?l:!1,visibleLength:c});return p.createElement(p.Fragment,null,(r==null?void 0:r.length)>1&&p.createElement(ow,{option:m,DefaultShape:YA.shape,shapeProps:y}),p.createElement(iRe,{points:r,clipPathId:t,props:a}))}function cRe(e){var t=e.clipPathId,n=e.props,r=e.pathRef,a=e.previousPointsRef,i=n.points,o=n.isAnimationActive,l=n.animationBegin,c=n.animationDuration,u=n.animationEasing,d=n.animationMatchBy,h=n.animationInterpolateFn,f=n.layout,m=tRe(r.current),x=uw(n.onAnimationStart,n.onAnimationEnd),g=x.isAnimating,y=x.handleAnimationStart,b=x.handleAnimationEnd,v=!g,w=DPe(i),_=p.useCallback(k=>k>0&&m>0,[m]);return p.createElement(oRe,{points:i,showLabels:v},n.children,p.createElement(dw,{animationInput:i,animationIdPrefix:"recharts-line-",items:i,previousItemsRef:a,isAnimationActive:o,animationBegin:l,animationDuration:c,animationEasing:u,onAnimationStart:y,onAnimationEnd:b,animationInterpolateFn:h,animationMatchBy:d,shouldUpdatePreviousRef:_,layout:f},(k,j,N)=>
875{var E=g||j<1,A=E?w(j,m):null;return p.createElement(lRe,{props:n,points:k,clipPathId:t,pathRef:r,animationElapsedTime:j,isAnimating:E,isEntrance:N,visibleLength:A})}),p.createElement(rw,{label:n.label}))}function uRe(e){var t=e.clipPathId,n=e.props,r=p.useRef(null),a=p.useRef(null);return p.createElement(cRe,{props:n,clipPathId:t,previousPointsRef:r,pathRef:a})}var dRe=(e,t)=>{var n,r;return{x:(n=e.x)!==null&&n!==void 0?n:void 0,y:(r=e.y)!==null&&r!==void 0?r:void 0,value:e.value,errorVal:hn(e.payload,t)}};class hRe extends p.Component{render(){var t=this.props,n=t.hide,r=t.dot,a=t.points,i=t.className,o=t.xAxisId,l=t.yAxisId,c=t.top,u=t.left,d=t.width,h=t.height,f=t.id,m=t.needClip,x=t.zIndex;if(n)return null;var g=un("recharts-line",i),y=f,b=tH(r),v=b.r,w=b.strokeWidth,_=MA(r),k=v*2+w,j=m?"url(#clipPath-".concat(_?"":"dots-").concat(y,")"):void 0;return p.createElement(Ks,{zIndex:x},p.createElement(rr,{className:g},m&&p.createElement("defs",null,p.createElement(qA,{clipPathId:y,xAxisId:o,yAxisId:l}),!_&&p.createElement("clipPath",{id:"clipPath-dots-".concat(y)},p.createElement("rect",{x:u-k/2,y:c-k/2,width:d+k,height:h+k}))),p.createElement(ZK,{xAxisId:o,yAxisId:l,data:a,dataPointFormatter:dRe,errorBarOffset:0},p.createElement(uRe,{props:this.props,clipPathId:y}))),p.createElement(_S,{activeDot:this.props.activeDot,points:a,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:j}))}}function fRe(e){var t=$r(e,YA),n=t.activeDot,r=t.animateNewValues,a=t.animationBegin,i=t.animationDuration,o=t.animationEasing,l=t.connectNulls,c=t.dot,u=t.hide,d=t.isAnimationActive,h=t.label,f=t.legendType,m=t.xAxisId,x=t.yAxisId,g=t.id,y=GA(t,ZPe),b=pw(m,x),v=b.needClip,w=mw(),_=wu(),k=Jr(),j=ot(T=>qPe(T,m,x,k,g));if(_!=="horizontal"&&_!=="vertical"||j==null||w==null)return null;var N=w.height,E=w.width,A=w.x,C=w.y;return p.createElement(hRe,iv({},y,{id:g,connectNulls:l,dot:c,activeDot:n,animateNewValues:r,animationBegin:a,animationDuration:i,animationEasing:o,isAnimationActive:d,hide:u,label:h,legendType:f,xAxisId:m,yAxisId:x,points:j,layout:_,height:N,width:E,left:A,top:C,needClip:v}))}function mRe(e){var t=e.layout,n=e.xAxis,r=e.yAxis,a=e.xAxisTicks,i=e.yAxisTicks,o=e.dataKey,l=e.bandSize,c=e.displayedData;return c.map((u,d)=>{var h=hn(u,o);if(t==="horizontal"){var f=Tb({axis:n,ticks:a,bandSize:l,entry:u,index:d}),m=sr(h)?null:r.scale.map(h);return{x:f,y:m??null,value:h,payload:u}}var x=sr(h)?null:n.scale.map(h),g=Tb({axis:r,ticks:i,bandSize:l,entry:u,index:d});return x==null||g==null?null:{x,y:g,value:h,payload:u}}).filter(Boolean)}function pRe(e){var t=$r(e,YA),n=Jr();return p.createElement(hw,{id:t.id,type:"line"},r=>p.createElement(p.Fragment,null,p.createElement(BA,{legendPayload:sRe(t)}),p.createElement(aRe,{dataKey:t.dataKey,data:t.data,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,unit:t.unit,formatter:t.formatter,tooltipType:t.tooltipType,id:r}),p.createElement(WA,{type:"line",id:r,data:t.data,xAxisId:t.xAxisId,yAxisId:t.yAxisId,zAxisId:0,dataKey:t.dataKey,hide:t.hide,isPanorama:n}),p.createElement(fRe,iv({},t,{id:r}))))}var Vi=p.memo(pRe,Ld);Vi.displayName="Line";function vl(e,t){var n,r;return(n=(r=e.graphicalItems.cartesianItems.find(a=>a.id===t))===null||r===void 0?void 0:r.xAxisId)!==null&&n!==void 0?n:IK}function wl(e,t){var n,r;return(n=(r=e.graphicalItems.cartesianItems.find(a=>a.id===t))===null||r===void 0?void 0:r.yAxisId)!==null&&n!==void 0?n:IK}var nH=(e,t,n)=>ul(e,"xAxis",vl(e,t),n),rH=(e,t,n)=>cl(e,"xAxis",vl(e,t),n),sH=(e,t,n)=>ul(e,"yAxis",wl(e,t),n),aH=(e,t,n)=>cl(e,"yAxis",wl(e,t),n),xRe=be([sn,nH,sH,rH,aH],(e,t,n,r,a)=>Oo(e,"xAxis")?su(t,r,!1):su(n,a,!1)),gRe=(e,t)=>t,ZA=be([Dx,gRe],(e,t)=>e.filter(n=>n.type==="area").find(n=>n.id===t)),iH=e=>{var t=sn(e),n=Oo(t,"xAxis");return n?"yAxis":"xAxis"},yRe=(e,t)=>{var n=iH(e);return n==="yAxis"?wl(e,t):vl(e,t)},oH=(e,t,n)=>Zb(e,iH(e),yRe(e,t),n),bRe=be([ZA,oH],(e,t)=>{var n;if(!(e==null||t==null)){var r=e.stackId,a=z0(e);if(!(r==null||a==null)){var i=(n=t[r])===null||n===void 0?void 0:n.stackedData,o=i==null?void 0:i.find(l=>l.key===a);if(o!=null)return o.map(l=>[l[0],l[1]])}}}),vRe=be([ZA,oH],(e,t)=>{if(!(e==null||e.stackId==null||t==null)){var n=t[e.stackId];if(n!=null)return n.graphicalItems.map(r=>r.dataKey).filter(Ea)}}),wRe=be([sn,nH,sH,rH,aH,bRe,VU,xRe,ZA,tje,vRe],(e,t,n,r,a,i,o,l,c,u,d)=>{var h=o.chartData,f=o.dataStartIndex,m=o.dataEndIndex;if(!(c==null||e!=="horizontal"&&e!=="vertical"||t==null||n==null||r==null||a==null||r.length===0||a.length===0||l==null)){var x=c.data,g;if(x&&x.length>0?g=x:g=h==null?void 0:h.slice(f,m+1),g!=null)return qRe({layout:e,xAxis:t,yAxis:n,xAxisTicks:r,yAxisTicks:a,dataStartIndex:f,areaSettings:c,stackedData:i,displayedData:g,chartBaseValue:u,bandSize:l,stackDataKeys:d})}}),_Re=["animationElapsedTime","isAnimating","isEntrance","layout","isRange","stroke","connectNulls"],kRe=["id","baseLine"];function np(){return np=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},np.apply(null,arguments)}function VD(e,t){if(e==null)return{};var n,r,a=jRe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function jRe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function NRe(e){var t,n,r=e.alpha,a=e.baseLine,i=e.points,o=e.strokeWidth,l=(t=i[0])===null||t===void 0?void 0:t.x,c=(n=i[i.length-1])===null||n===void 0?void 0:n.x;if(!Mt(l)||!Mt(c))return null;var u=r*Math.abs(l-c),d=Math.max(...i.map(h=>h.y||0));return rt(a)?d=Math.max(a,d):a&&Array.isArray(a)&&a.length&&(d=Math.max(...a.map(h=>h.y||0),d)),rt(d)?p.createElement("rect",{x:l<c?l:l-u,y:0,width:u,height:Math.floor(d+(o?parseInt("".concat(o),10):1))}):null}function SRe(e){var t,n,r=e.alpha,a=e.baseLine,i=e.points,o=e.strokeWidth,l=(t=i[0])===null||t===void 0?void 0:t.y,c=(n=i[i.length-1])===null||n===void 0?void 0:n.y;if(!Mt(l)||!Mt(c))return null;var u=r*Math.abs(l-c),d=Math.max(...i.map(h=>h.x||0));return rt(a)?d=Math.max(a,d):a&&Array.isArray(a)&&a.length&&(d=Math.max(...a.map(h=>h.x||0),d)),rt(d)?p.createElement("rect",{x:0,y:l<c?l:l-u,width:d+(o?parseInt("".concat(o),10):1),height:Math.floor(u)}):null}function CRe(e){var t=e.alpha,n=e.layout,r=e.points,a=e.baseLine,i=e.strokeWidth;return n==="vertical"?p.createElement(SRe,{alpha:t,points:r,baseLine:a,strokeWidth:i}):p.createElement(NRe,{alpha:t,points:r,baseLine:a,strokeWidth:i})}function ERe(e){var t=e.animationElapsedTime,n=t===void 0?1:t,r=e.isAnimating,a=r===void 0?!1:r,i=e.isEntrance,o=i===void 0?!1:i,l=e.layout,c=e.isRange,u=e.stroke,d=e.connectNulls,h=VD(e,_Re),f=l==="vertical"?"vertical":"horizontal",m=d??!1,x=CK(),g=h.id,y=h.baseLine,b=VD(h,kRe),v=Ra(b),w=p.createElement(Lh,np({},h,{id:g,baseLine:y,connectNulls:m,stroke:"none",className:"recharts-area-area",layout:f})),_=u!=="none"&&p.createElement(Lh,np({},v,{className:"recharts-area-curve",layout:f,type:h.type,connectNulls:m,fill:"none",stroke:u,points:h.points})),k=u!=="none"&&c&&Array.isArray(y)&&p.createElement(Lh,np({},v,{className:"recharts-area-curve",layout:f,type:h.type,connectNulls:m,fill:"none",stroke:u,points:y}));if(o&&(a||n<1)){var j;return p.createElement(rr,null,p.createElement("defs",null,p.createElement("clipPath",{id:x},p.createElement(CRe,{alpha:n,points:(j=h.points)!==null&&j!==void 0?j:[],baseLine:y,layout:f,strokeWidth:h.strokeWidth}))),p.createElement(rr,{clipPath:"url(#".concat(x,")")},w,_,k))}return p.createElement(p.Fragment,null,w,_,k)}var ARe=["id"],TRe=["activeDot","animationBegin","animationDuration","animationEasing","connectNulls","dot","fill","fillOpacity","hide","isAnimationActive","legendType","stroke","xAxisId","yAxisId"];function ov(){return ov=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},ov.apply(null,arguments)}function lH(e,t){if(e==null)return{};var n,r,a=ORe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function ORe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function qD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function nf(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
875t%2?qD(Object(n),!0).forEach(function(r){IRe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):qD(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function IRe(e,t,n){return(t=PRe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function PRe(e){var t=RRe(e,"string");return typeof t=="symbol"?t:t+""}function RRe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var DRe=(e,t)=>e==null?[]:t===1?e.flatMap(n=>n.status==="removed"?[]:[n.next]):e.flatMap(n=>n.status==="matched"?[nf(nf({},n.next),{},{x:qn(n.prev.x,n.next.x,t),y:qn(n.prev.y,n.next.y,t)})]:n.status==="added"?[n.next]:[]),cH={activeDot:!0,animationBegin:0,animationDuration:1500,animationEasing:"ease",animationMatchBy:cw,animationInterpolateFn:DRe,connectNulls:!1,dot:!1,fill:"#3182bd",fillOpacity:.6,hide:!1,isAnimationActive:"auto",legendType:"line",stroke:"#3182bd",strokeWidth:1,type:"linear",label:!1,shape:ERe,xAxisId:0,yAxisId:0,zIndex:_r.area};function lv(e,t){return e&&e!=="none"?e:t}var MRe=e=>{var t=e.dataKey,n=e.name,r=e.stroke,a=e.fill,i=e.legendType,o=e.hide;return[{inactive:o,dataKey:t,type:i,color:lv(r,a),value:vu(n,t),payload:e}]},$Re=p.memo(e=>{var t=e.dataKey,n=e.data,r=e.stroke,a=e.strokeWidth,i=e.fill,o=e.name,l=e.hide,c=e.unit,u=e.formatter,d=e.tooltipType,h=e.id,f={dataDefinedOnItem:n,getPosition:bu,settings:{stroke:r,strokeWidth:a,fill:i,dataKey:t,nameKey:void 0,name:vu(o,t),hide:l,type:d,color:lv(r,i),unit:c,formatter:u,graphicalItemId:h}};return p.createElement(lw,{tooltipEntrySettings:f})});function LRe(e){var t=e.clipPathId,n=e.points,r=e.props,a=r.needClip,i=r.dot,o=r.dataKey,l=Ra(r);return p.createElement(OK,{points:n,dot:i,className:"recharts-area-dots",dotClassName:"recharts-area-dot",dataKey:o,baseProps:l,needClip:a,clipPathId:t})}function FRe(e){var t=e.showLabels,n=e.children,r=e.points,a=r.map(i=>{var o,l,c={x:(o=i.x)!==null&&o!==void 0?o:0,y:(l=i.y)!==null&&l!==void 0?l:0,width:0,lowerWidth:0,upperWidth:0,height:0};return nf(nf({},c),{},{value:i.value,payload:i.payload,parentViewBox:void 0,viewBox:c,fill:void 0})});return p.createElement(IA,{value:t?a:void 0},n)}function BRe(e){var t=e.points,n=e.baseLine,r=e.needClip,a=e.clipPathId,i=e.props,o=e.animationElapsedTime,l=e.isAnimating,c=e.isEntrance,u=i.layout,d=i.type,h=i.stroke,f=i.connectNulls,m=i.isRange,x=i.shape,g=i.id,y=lH(i,ARe),b=ha(y),v=nf(nf({},b),{},{id:g,points:t,connectNulls:f,type:d,baseLine:n,layout:u,stroke:h,isRange:m,animationElapsedTime:o,isAnimating:l,isEntrance:c});return p.createElement(p.Fragment,null,(t==null?void 0:t.length)>1&&p.createElement(rr,{clipPath:r?"url(#clipPath-".concat(a,")"):void 0},p.createElement(ow,{option:x,DefaultShape:cH.shape,shapeProps:v})),p.createElement(LRe,{points:t,props:y,clipPathId:a}))}function URe(e,t,n){if(rt(e)){var r=rt(t)?t:void 0;return qn(r,e,n)}if(sr(e)||No(e)){var a=rt(t)?t:void 0;return qn(a,0,n)}return e}function zRe(e){var t=e.needClip,n=e.clipPathId,r=e.props,a=e.previousPointsRef,i=e.previousBaselineRef,o=r.points,l=r.baseLine,c=r.isAnimationActive,u=r.animationBegin,d=r.animationDuration,h=r.animationEasing,f=r.animationMatchBy,m=r.animationInterpolateFn,x=p.useMemo(()=>({points:o,baseLine:l}),[o,l]),g=SK(x,i),y=xE(),b=uw(r.onAnimationStart,r.onAnimationEnd),v=b.isAnimating,w=b.handleAnimationStart,_=b.handleAnimationEnd,k=g.startValue;if(y==null)return null;var j;return Array.isArray(l)&&Array.isArray(k)?j=wS(k,l,f):Array.isArray(l)?j=wS(null,l,f):j=null,p.createElement(dw,{animationInput:x,animationIdPrefix:"recharts-area-",items:o,previousItemsRef:a,isAnimationActive:c,animationBegin:u,animationDuration:d,animationEasing:h,onAnimationStart:w,onAnimationEnd:_,animationInterpolateFn:m,animationMatchBy:f,layout:y},(N,E,A)=>{var C;return E===1?C=l:Array.isArray(l)?C=m(j,E,y):C=A?l:URe(l,k,E),g.syncStepValue(C,E),p.createElement(FRe,{showLabels:!v,points:o},r.children,p.createElement(BRe,{points:N,baseLine:C,needClip:t,clipPathId:n,props:r,animationElapsedTime:E,isAnimating:v||E<1,isEntrance:A}),p.createElement(rw,{label:r.label}))})}function WRe(e){var t=e.needClip,n=e.clipPathId,r=e.props,a=p.useRef(null),i=p.useRef();return p.createElement(zRe,{needClip:t,clipPathId:n,props:r,previousPointsRef:a,previousBaselineRef:i})}class KRe extends p.PureComponent{render(){var t=this.props,n=t.hide,r=t.dot,a=t.points,i=t.className,o=t.top,l=t.left,c=t.needClip,u=t.xAxisId,d=t.yAxisId,h=t.width,f=t.height,m=t.id,x=t.baseLine,g=t.zIndex;if(n)return null;var y=un("recharts-area",i),b=m,v=tH(r),w=v.r,_=v.strokeWidth,k=MA(r),j=w*2+_,N=c?"url(#clipPath-".concat(k?""
875:"dots-").concat(b,")"):void 0;return p.createElement(Ks,{zIndex:g},p.createElement(rr,{className:y},c&&p.createElement("defs",null,p.createElement(qA,{clipPathId:b,xAxisId:u,yAxisId:d}),!k&&p.createElement("clipPath",{id:"clipPath-dots-".concat(b)},p.createElement("rect",{x:l-j/2,y:o-j/2,width:h+j,height:f+j}))),p.createElement(WRe,{needClip:c,clipPathId:b,props:this.props})),p.createElement(_S,{points:a,mainColor:lv(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:N}),this.props.isRange&&Array.isArray(x)&&p.createElement(_S,{points:x,mainColor:lv(this.props.stroke,this.props.fill),itemDataKey:this.props.dataKey,activeDot:this.props.activeDot,clipPath:N}))}}function HRe(e){var t,n=e.activeDot,r=e.animationBegin,a=e.animationDuration,i=e.animationEasing,o=e.connectNulls,l=e.dot,c=e.fill,u=e.fillOpacity,d=e.hide,h=e.isAnimationActive,f=e.legendType,m=e.stroke,x=e.xAxisId,g=e.yAxisId,y=lH(e,TRe),b=wu(),v=ZW(),w=pw(x,g),_=w.needClip,k=Jr(),j=(t=ot(I=>wRe(I,e.id,k)))!==null&&t!==void 0?t:{},N=j.points,E=j.isRange,A=j.baseLine,C=mw();if(b!=="horizontal"&&b!=="vertical"||C==null||v!=="AreaChart"&&v!=="ComposedChart")return null;var T=C.height,S=C.width,O=C.x,R=C.y;return!N||!N.length?null:p.createElement(KRe,ov({},y,{activeDot:n,animationBegin:r,animationDuration:a,animationEasing:i,baseLine:A,connectNulls:o,dot:l,fill:c,fillOpacity:u,height:T,hide:d,layout:b,isAnimationActive:h,isRange:E,legendType:f,needClip:_,points:N,stroke:m,width:S,left:O,top:R,xAxisId:x,yAxisId:g}))}var VRe=(e,t,n,r,a)=>{var i=n??t;if(rt(i))return i;var o=e==="horizontal"?a:r,l=o.scale.domain();if(o.type==="number"){var c=Math.max(l[0],l[1]),u=Math.min(l[0],l[1]);return i==="dataMin"?u:i==="dataMax"||c<0?c:Math.max(Math.min(l[0],l[1]),0)}return i==="dataMin"?l[0]:i==="dataMax"?l[1]:l[0]};function qRe(e){var t=e.areaSettings,n=t.connectNulls,r=t.baseValue,a=t.dataKey,i=e.stackedData,o=e.layout,l=e.chartBaseValue,c=e.xAxis,u=e.yAxis,d=e.displayedData,h=e.dataStartIndex,f=e.xAxisTicks,m=e.yAxisTicks,x=e.bandSize,g=e.stackDataKeys,y=i&&i.length,b=VRe(o,l,r,c,u),v=o==="horizontal",w=!1,_=d.map((j,N)=>{var E,A,C,T;if(y)T=i[h+N];else{var S=hn(j,a);Array.isArray(S)?(T=S,w=!0):T=[b,S]}var O=(E=(A=T)===null||A===void 0?void 0:A[1])!==null&&E!==void 0?E:null,R=hn(j,a),I=y&&R==null&&g!=null&&g.length>0&&g.every(F=>
875hn(j,F)==null),$=O==null||y&&!n&&R==null||I;if(v){var P;return{x:Tb({axis:c,ticks:f,bandSize:x,entry:j,index:N}),y:$?null:(P=u.scale.map(O))!==null&&P!==void 0?P:null,value:T,payload:j}}return{x:$?null:(C=c.scale.map(O))!==null&&C!==void 0?C:null,y:Tb({axis:u,ticks:m,bandSize:x,entry:j,index:N}),value:T,payload:j}}),k;return y||w?k=_.map(j=>{var N,E=Array.isArray(j.value)?j.value[0]:null;if(v){var A;return{x:j.x,y:E!=null&&j.y!=null&&(A=u.scale.map(E))!==null&&A!==void 0?A:null,payload:j.payload}}return{x:E!=null&&(N=c.scale.map(E))!==null&&N!==void 0?N:null,y:j.y,payload:j.payload}}):k=v?u.scale.map(b):c.scale.map(b),{points:_,baseLine:k??0,isRange:w}}function GRe(e){var t=$r(e,cH),n=Jr();return p.createElement(hw,{id:t.id,type:"area"},r=>p.createElement(p.Fragment,null,p.createElement(BA,{legendPayload:MRe(t)}),p.createElement($Re,{dataKey:t.dataKey,data:t.data,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,unit:t.unit,formatter:t.formatter,tooltipType:t.tooltipType,id:r}),p.createElement(WA,{type:"area",id:r,data:t.data,dataKey:t.dataKey,xAxisId:t.xAxisId,yAxisId:t.yAxisId,zAxisId:0,stackId:_U(t.stackId),hide:t.hide,barSize:void 0,baseValue:t.baseValue,isPanorama:n,connectNulls:t.connectNulls}),p.createElement(HRe,ov({},t,{id:r}))))}var xw=p.memo(GRe,Ld);xw.displayName="Area";var YRe="Invariant failed";function ZRe(e,t){throw new Error(YRe)}var XRe=["option"];function JRe(e,t){if(e==null)return{};var n,r,a=QRe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function QRe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var XA=bE;function JA(e){var t=e.option,n=JRe(e,XRe);return p.createElement(ow,{option:t,DefaultShape:XA,shapeProps:n,activeClassName:"recharts-active-bar",inActiveClassName:"recharts-inactive-bar"})}var e4e=function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return(r,a)=>{if(rt(t))return t;var i=rt(r)||sr(r);return i?t(r,a):(i||ZRe(),n)}},t4e=(e,t,n)=>n,n4e=(e,t)=>t,Ux=be([Dx,n4e],(e,t)=>e.filter(n=>n.type==="bar").find(n=>n.id===t)),r4e=be([Ux],e=>e==null?void 0:e.maxBarSize),s4e=(e,t,n,r)=>r,a4e=be([sn,Dx,vl,wl,t4e],(e,t,n,r,a)=>t.filter(i=>e==="horizontal"?i.xAxisId===n:i.yAxisId===r).filter(i=>i.isPanorama===a).filter(i=>i.hide===!1).filter(i=>i.type==="bar")),i4e=(e,t,n)=>{var r=sn(e),a=vl(e,t),i=wl(e,t);if(!(a==null||i==null))return r==="horizontal"?Zb(e,"yAxis",i,n):Zb(e,"xAxis",a,n)},o4e=(e,t)=>{var n=sn(e),r=vl(e,t),a=wl(e,t);if(!(r==null||a==null))return n==="horizontal"?E5(e,"xAxis",r):E5(e,"yAxis",a)},l4e=be([a4e,eje,o4e],OOe),c4e=(e,t,n)=>{var r,a,i=Ux(e,t);if(i==null)return 0;var o=vl(e,t),l=wl(e,t);if(o==null||l==null)return 0;var c=sn(e),u=sz(e),d=i.maxBarSize,h=sr(d)?u:d,f,m;return c==="horizontal"?(f=ul(e,"xAxis",o,n),m=cl(e,"xAxis",o,n)):(f=ul(e,"yAxis",l,n),m=cl(e,"yAxis",l,n)),(r=(a=su(f,m,!0))!==null&&a!==void 0?a:h)!==null&&r!==void 0?r:0},uH=(e,t,n)=>{var r=sn(e),a=vl(e,t),i=wl(e,t);if(!(a==null||i==null)){var o,l;return r==="horizontal"?(o=ul(e,"xAxis",a,n),l=cl(e,"xAxis",a,n)):(o=ul(e,"yAxis",i,n),l=cl(e,"yAxis",i,n)),su(o,l)}},u4e=be([l4e,sz,Qke,az,c4e,uH,r4e],MOe),d4e=(e,t,n)=>{var r=vl(e,t);if(r!=null)return ul(e,"xAxis",r,n)},h4e=(e,t,n)=>{var r=wl(e,t);if(r!=null)return ul(e,"yAxis",r,n)},f4e=(e,t,n)=>{var r=vl(e,t);if(r!=null)return cl(e,"xAxis",r,n)},m4e=(e,t,n)=>{var r=wl(e,t);if(r!=null)return cl(e,"yAxis",r,n)},p4e=be([u4e,Ux],LOe),x4e=be([i4e,Ux],$Oe),g4e=be([ds,hE,d4e,h4e,f4e,m4e,p4e,sn,VU,uH,x4e,Ux,s4e],(e,t,n,r,a,i,o,l,c,u,d,h,f)=>{var m=c.chartData,x=c.dataStartIndex,g=c.dataEndIndex;if(!(h==null||o==null||t==null||l!=="horizontal"&&l!=="vertical"||n==null||r==null||a==null||i==null||u==null)){var y=h.data,b;if(y!=null&&y.length>0?b=y:b=m==null?void 0:m.slice(x,g+1),b!=null)return Z4e({layout:l,barSettings:h,pos:o,parentViewBox:t,bandSize:u,xAxis:n,yAxis:r,xAxisTicks:a,yAxisTicks:i,stackedData:d,displayedData:b,offset:e,cells:f,dataStartIndex:x})}}),y4e=["index"];function jS(){return jS=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},jS.apply(null,arguments)}function b4e(e,t){if(e==null)return{};var n,r,a=v4e(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function v4e(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var dH=p.createContext(void 0),w4e=e=>{var t=p.useContext(dH);if(t!=null)return t.stackId;if(e!=null)return _U(e)},_4e=(e,t)=>
875"recharts-bar-stack-clip-path-".concat(e,"-").concat(t),k4e=e=>{var t=p.useContext(dH);if(t!=null){var n=t.stackId;return"url(#".concat(_4e(n,e),")")}},hH=e=>{var t=e.index,n=b4e(e,y4e),r=k4e(t);return p.createElement(rr,jS({className:"recharts-bar-stack-layer",clipPath:r},n))},j4e=["onMouseEnter","onMouseLeave","onClick"],N4e=["value","background","tooltipPosition"],S4e=["id"],C4e=["onMouseEnter","onClick","onMouseLeave"];function GD(e,t){return O4e(e)||T4e(e,t)||A4e(e,t)||E4e()}function E4e(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 876In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function A4e(e,t){if(e){if(typeof e=="string")return YD(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?YD(e,t):void 0}}function YD(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function T4e(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function O4e(e){if(Array.isArray(e))return e}function ou(){return ou=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},ou.apply(null,arguments)}function ZD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function rs(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?ZD(Object(n),!0).forEach(function(r){I4e(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ZD(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function I4e(e,t,n){return(t=P4e(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function P4e(e){var t=R4e(e,"string");return typeof t=="symbol"?t:t+""}function R4e(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function cv(e,t){if(e==null)return{};var n,r,a=D4e(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function D4e(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var M4e=e=>{var t=e.dataKey,n=e.name,r=e.fill,a=e.legendType,i=e.hide;return[{inactive:i,dataKey:t,type:a,color:r,value:vu(n,t),payload:e}]},$4e=p.memo(e=>{var t=e.dataKey,n=e.stroke,r=e.strokeWidth,a=e.fill,i=e.name,o=e.hide,l=e.unit,c=e.formatter,u=e.tooltipType,d=e.id,h={dataDefinedOnItem:void 0,getPosition:bu,settings:{stroke:n,strokeWidth:r,fill:a,dataKey:t,nameKey:void 0,name:vu(i,t),hide:o,type:u,color:a,unit:l,formatter:c,graphicalItemId:d}};return p.createElement(lw,{tooltipEntrySettings:h})});function L4e(e){var t=ot(iu),n=e.data,r=e.dataKey,a=e.background,i=e.allOtherBarProps,o=i.onMouseEnter,l=i.onMouseLeave,c=i.onClick,u=cv(i,j4e),d=$A(o,r,i.id),h=LA(l),f=FA(c,r,i.id);if(!a||n==null)return null;var m=_d(a);return p.createElement(Ks,{zIndex:FOe(a,_r.barBackground)},n.map((x,g)=>{x.value;var y=x.background;x.tooltipPosition;var b=cv(x,N4e);if(!y)return null;var v=d(x,x.originalDataIndex),w=h(x,x.originalDataIndex),_=f(x,x.originalDataIndex),k=rs(rs(rs(rs(rs({option:a,isActive:String(x.originalDataIndex)===t},b),{},{fill:"#eee"},y),m),yx(u,x,g)),{},{onMouseEnter:v,onMouseLeave:w,onClick:_,dataKey:r,index:g,className:"recharts-bar-background-rectangle"});return p.createElement(JA,ou({key:"background-bar-".concat(g)},k))}))}function F4e(e){var t=e.showLabels,n=e.children,r=e.rects,a=r==null?void 0:r.map(i=>{var o={x:i.x,y:i.y,width:i.width,lowerWidth:i.width,upperWidth:i.width,height:i.height};return rs(rs({},o),{},{value:i.value,payload:i.payload,parentViewBox:i.parentViewBox,viewBox:o,fill:i.fill})});return p.createElement(IA,{value:t?a:void 0},n)}function B4e(e){var t=e.shape,n=e.activeBar,r=e.baseProps,a=e.entry,i=e.index,o=e.dataKey,l=ot(iu),c=ot(jA),u=n&&String(a.originalDataIndex)===l&&(c==null||o===c),d=l!=null&&(String(a.originalDataIndex)!==l||c!=null&&o!==c),h=p.useState(!1),f=GD(h,2),m=f[0],x=f[1],g=p.use
876State(!1),y=GD(g,2),b=y[0],v=y[1];p.useEffect(()=>{var E;return u?(x(!0),E=requestAnimationFrame(()=>{v(!0)})):(v(!1),d&&x(!1)),()=>{cancelAnimationFrame(E)}},[u,d]);var w=p.useCallback(()=>{u||x(!1)},[u]),_=u&&b,k=u||m,j;u?n===!0?j=t:j=n:j=t;var N=p.createElement(JA,ou({},r,{name:String(r.name)},a,{isActive:_,option:j,index:i,dataKey:o,animationElapsedTime:e.animationElapsedTime,isAnimating:e.isAnimating,isEntrance:e.isEntrance,onTransitionEnd:w}));return k?p.createElement(Ks,{zIndex:_r.activeBar},p.createElement(hH,{index:a.originalDataIndex},N)):N}function U4e(e){var t=e.shape,n=e.baseProps,r=e.entry,a=e.index,i=e.dataKey;return p.createElement(JA,ou({},n,{name:String(n.name)},r,{isActive:!1,option:t,index:a,dataKey:i,animationElapsedTime:e.animationElapsedTime,isAnimating:e.isAnimating,isEntrance:e.isEntrance}))}function z4e(e){var t,n=e.data,r=e.props,a=e.animationElapsedTime,i=e.isAnimating,o=e.isEntrance,l=(t=Ra(r))!==null&&t!==void 0?t:{},c=l.id,u=cv(l,S4e),d=r.shape,h=r.dataKey,f=r.activeBar,m=r.onMouseEnter,x=r.onClick,g=r.onMouseLeave,y=cv(r,C4e),b=$A(m,h,c),v=LA(g),w=FA(x,h,c);return n?p.createElement(p.Fragment,null,n.map((_,k)=>p.createElement(hH,ou({index:_.originalDataIndex,key:"rectangle-".concat(_==null?void 0:_.x,"-").concat(_==null?void 0:_.y,"-").concat(_==null?void 0:_.value,"-").concat(k),className:"recharts-bar-rectangle"},yx(y,_,k),{onMouseEnter:b(_,_.originalDataIndex),onMouseLeave:v(_,_.originalDataIndex),onClick:w(_,_.originalDataIndex)}),f?p.createElement(B4e,{shape:d,activeBar:f,baseProps:u,entry:_,index:k,dataKey:h,animationElapsedTime:a,isAnimating:i,isEntrance:o}):p.createElement(U4e,{shape:d,baseProps:u,entry:_,index:k,dataKey:h,animationElapsedTime:a,isAnimating:i,isEntrance:o})))):null}var W4e=(e,t,n)=>e==null?[]:t===1?e.flatMap(r=>r.status==="removed"?[]:[r.next]):e.flatMap(r=>{if(r.status==="removed")return n==="horizontal"?[rs(rs({},r.prev),{},{height:qn(r.prev.height,0,t),y:qn(r.prev.y,r.prev.y+r.prev.height,t)})]:[rs(rs({},r.prev),{},{width:qn(r.prev.width,0,t)})];if(r.status==="matched")return[rs(rs({},r.next),{},{x:qn(r.prev.x,r.next.x,t),y:qn(r.prev.y,r.next.y,t),width:qn(r.prev.width,r.next.width,t),height:qn(r.prev.height,r.next.height,t)})];var a=r.next;return n==="horizontal"?[rs(rs({},a),{},{height:qn(0,a.height,t),y:qn(a.stackedBarStart,a.y,t)})]:[rs(rs({},a),{},{width:qn(0,a.width,t),x:qn(a.stackedBarStart,a.x,t)})]});function K4e(e){var t=e.props,n=e.previousRectanglesRef,r=t.data,a=t.isAnimationActive,i=t.animationBegin,o=t.animationDuration,l=t.animationEasing,c=t.animationInterpolateFn,u=t.layout,d=uw(t.onAnimationStart,t.onAnimationEnd),h=d.isAnimating,f=d.handleAnimationStart,m=d.handleAnimationEnd;return p.createElement(F4e,{showLabels:!h,rects:r},p.createElement(dw,{animationInput:r,animationIdPrefix:"recharts-bar-",items:r,previousItemsRef:n,isAnimationActive:a,animationBegin:i,animationDuration:o,animationEasing:l,onAnimationStart:f,onAnimationEnd:m,animationInterpolateFn:c,animationMatchBy:t.animationMatchBy,layout:u},(x,g,y)=>p.createElement(rr,null,p.createElement(z4e,{props:t,data:x,animationElapsedTime:g,isAnimating:h||g<1,isEntrance:y}))),p.createElement(rw,{label:t.label}),t.children)}function H4e(e){var t=p.useRef(null);return p.createElement(K4e,{previousRectanglesRef:t,props:e})}var fH=0,V4e=(e,t)=>{var n=Array.isArray(e.value)?e.value[1]:e.value;return{x:e.x,y:e.y,value:n,errorVal:hn(e,t)}};class q4e extends p.PureComponent{render(){var t=this.props,n=t.hide,r=t.data,a=t.dataKey,i=t.className,o=t.xAxisId,l=t.yAxisId,c=t.needClip,u=t.background,d=t.id;if(n||r==null)return null;var h=un("recharts-bar",i),f=d;return p.createElement(rr,{className:h,id:d},c&&p.createElement("defs",null,p.createElement(qA,{clipPathId:f,xAxisId:o,yAxisId:l})),p.createElement(rr,{className:"recharts-bar-rectangles",clipPath:c?"url(#clipPath-".concat(f,")"):void 0},p.createElement(L4e,{data:r,dataKey:a,background:u,allOtherBarProps:this.props}),p.createElement(H4e,this.props)))}}var G4e={activeBar:!1,animationBegin:0,animationDuration:400,animationEasing:"ease",animationInterpolateFn:W4e,animationMatchBy:UA,background:!1,hide:!1,isAnimationActive:"auto",label:!1,legendT
876ype:"rect",minPointSize:fH,shape:XA,xAxisId:0,yAxisId:0,zIndex:_r.bar};function Y4e(e){var t=e.xAxisId,n=e.yAxisId,r=e.hide,a=e.legendType,i=e.minPointSize,o=e.activeBar,l=e.animationBegin,c=e.animationDuration,u=e.animationEasing,d=e.isAnimationActive,h=pw(t,n),f=h.needClip,m=wu(),x=Jr(),g=DA(e.children,zd),y=ot(w=>g4e(w,e.id,x,g));if(m!=="vertical"&&m!=="horizontal")return null;var b,v=y==null?void 0:y[0];return v==null||v.height==null||v.width==null?b=0:b=m==="vertical"?v.height/2:v.width/2,p.createElement(ZK,{xAxisId:t,yAxisId:n,data:y,dataPointFormatter:V4e,errorBarOffset:b},p.createElement(q4e,ou({},e,{layout:m,needClip:f,data:y,xAxisId:t,yAxisId:n,hide:r,legendType:a,minPointSize:i,activeBar:o,animationBegin:l,animationDuration:c,animationEasing:u,isAnimationActive:d})))}function Z4e(e){var t=e.layout,n=e.barSettings,r=n.dataKey,a=n.minPointSize,i=n.hasCustomShape,o=e.pos,l=e.bandSize,c=e.xAxis,u=e.yAxis,d=e.xAxisTicks,h=e.yAxisTicks,f=e.stackedData,m=e.displayedData,x=e.offset,g=e.cells,y=e.parentViewBox,b=e.dataStartIndex,v=t==="horizontal"?u:c,w=f?v.scale.domain():null,_=uwe({numericAxis:v}),k=v.scale.map(_);return m.map((j,N)=>{var E,A,C,T,S,O;if(f){var R=f[N+b];if(R==null)return null;E=awe(R,w)}else E=hn(j,r),Array.isArray(E)||(E=[_,E]);var I=e4e(a,fH)(E[1],N);if(t==="horizontal"){var $,P=u.scale.map(E[0]),F=u.scale.map(E[1]);if(P==null||F==null)return null;A=yR({axis:c,ticks:d,bandSize:l,offset:o.offset,entry:j,index:N}),C=($=F??P)!==null&&$!==void 0?$:void 0,T=o.size;var Z=P-F;if(S=No(Z)?0:Z,O={x:A,y:x.top,width:T,height:x.height},Math.abs(I)>0&&Math.abs(S)<Math.abs(I)){var D=ws(S||I)*(Math.abs(I)-Math.abs(S));C-=D,S+=D}}else{var H=c.scale.map(E[0]),Y=c.scale.map(E[1]);if(H==null||Y==null)return null;if(A=H,C=yR({axis:u,ticks:h,bandSize:l,offset:o.offset,entry:j,index:N}),T=Y-H,S=o.size,O={x:x.left,y:C,width:x.width,height:S},Math.abs(I)>0&&Math.abs(T)<Math.abs(I)){var M=ws(T||I)*(Math.abs(I)-Math.abs(T));T+=M}}if(A==null||C==null||T==null||S==null||!i&&(T===0||S===0))return null;var z=rs(rs({},j),{},{stackedBarStart:k,x:A,y:C,width:T,height:S,value:f?E:E[1],payload:j,background:O,tooltipPosition:{x:A+T/2,y:C+S/2},parentViewBox:y,originalDataIndex:N},g&&g[N]&&g[N].props);return z}).filter(Boolean)}function X4e(e){var t=$r(e,G4e),n=w4e(t.stackId),r=Jr();return p.createElement(hw,{id:t.id,type:"bar"},a=>p.createElement(p.Fragment,null,p.createElement(BA,{legendPayload:M4e(t)}),p.createElement($4e,{dataKey:t.dataKey,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,unit:t.unit,formatter:t.formatter,tooltipType:t.tooltipType,id:a}),p.createElement(WA,{type:"bar",id:a,data:void 0,xAxisId:t.xAxisId,yAxisId:t.yAxisId,zAxisId:0,dataKey:t.dataKey,stackId:n,hide:t.hide,barSize:t.barSize,minPointSize:t.minPointSize,maxBarSize:t.maxBarSize,isPanorama:r,hasCustomShape:t.shape!=null&&t.shape!==XA}),p.createElement(Ks,{zIndex:t.zIndex},p.createElement(Y4e,ou({},t,{id:a})))))}var vo=p.memo(X4e,Ld);vo.displayName="Bar";var J4e=["domain","range"],Q4e=["domain","range"];function XD(e,t){if(e==null)return{};var n,r,a=e5e(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function e5e(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function JD(e,t){return e===t?!0:Array.isArray(e)&&e.length===2&&Array.isArray(t)&&t.length===2?e[0]===t[0]&&e[1]===t[1]:!1}function mH(e,t){if(e===t)return!0;var n=e.domain,r=e.range,a=XD(e,J4e),i=t.domain,o=t.range,l=XD(t,Q4e);return!JD(n,i)||!JD(r,o)?!1:Ld(a,l)}var t5e=["type"],n5e=["dangerouslySetInnerHTML","ticks","scale"],r5e=["id","scale"];function NS(){return NS=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},NS.apply(null,arguments)}function QD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function eM(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
876t%2?QD(Object(n),!0).forEach(function(r){s5e(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):QD(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function s5e(e,t,n){return(t=a5e(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a5e(e){var t=i5e(e,"string");return typeof t=="symbol"?t:t+""}function i5e(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function SS(e,t){if(e==null)return{};var n,r,a=o5e(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function o5e(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function l5e(e){var t=Nn(),n=p.useRef(null),r=xE(),a=e.type,i=SS(e,t5e),o=B0(r,"xAxis",a),l=p.useMemo(()=>{if(o!=null)return eM(eM({},i),{},{type:o})},[i,o]);return p.useLayoutEffect(()=>{l!=null&&(n.current===null?t(uOe(l)):n.current!==l&&t(dOe({prev:n.current,next:l})),n.current=l)},[l,t]),p.useLayoutEffect(()=>()=>{n.current&&(t(hOe(n.current)),n.current=null)},[t]),null}var c5e=e=>{var t=e.xAxisId,n=e.className,r=e.height,a=e.label,i=p.useRef(null),o=p.useRef(null),l=ot(hE),c=Jr(),u=Nn(),d="xAxis",h=ot(b=>NW(b,d,t,c)),f=ot(b=>_W(b,t)),m=ot(b=>L2e(b,t)),x=ot(b=>Jz(b,t));if(p.useLayoutEffect(()=>{if(!(r!=="auto"||!f||nw(a)||p.isValidElement(a)||x==null)){var b=i.current;if(b){var v=b.getCalculatedHeight();Math.round(f.height)!==Math.round(v)&&u(gOe({id:t,height:v}))}}},[h,f,u,a,t,r,x]),f==null||m==null||x==null)return null;e.dangerouslySetInnerHTML,e.ticks,e.scale;var g=SS(e,n5e);x.id,x.scale;var y=SS(x,r5e);return p.createElement(HA,NS({}
876,g,y,{ref:i,labelRef:o,x:m.x,y:m.y,width:f.width,height:f.height,className:un("recharts-".concat(d," ").concat(d),n),viewBox:l,ticks:h,axisType:d,axisId:t}))},u5e={allowDataOverflow:Qr.allowDataOverflow,allowDecimals:Qr.allowDecimals,allowDuplicatedCategory:Qr.allowDuplicatedCategory,angle:Qr.angle,axisLine:Jl.axisLine,height:Qr.height,hide:!1,includeHidden:Qr.includeHidden,interval:Qr.interval,label:!1,minTickGap:Qr.minTickGap,mirror:Qr.mirror,orientation:Qr.orientation,padding:Qr.padding,reversed:Qr.reversed,scale:Qr.scale,tick:Qr.tick,tickCount:Qr.tickCount,tickLine:Jl.tickLine,tickSize:Jl.tickSize,type:Qr.type,niceTicks:Qr.niceTicks,xAxisId:0},d5e=e=>{var t=$r(e,u5e);return p.createElement(p.Fragment,null,p.createElement(l5e,{allowDataOverflow:t.allowDataOverflow,allowDecimals:t.allowDecimals,allowDuplicatedCategory:t.allowDuplicatedCategory,angle:t.angle,dataKey:t.dataKey,domain:t.domain,height:t.height,hide:t.hide,id:t.xAxisId,includeHidden:t.includeHidden,interval:t.interval,minTickGap:t.minTickGap,mirror:t.mirror,name:t.name,orientation:t.orientation,padding:t.padding,reversed:t.reversed,scale:t.scale,tick:t.tick,tickCount:t.tickCount,tickFormatter:t.tickFormatter,ticks:t.ticks,type:t.type,unit:t.unit,niceTicks:t.niceTicks}),p.createElement(c5e,t))},$a=p.memo(d5e,mH);$a.displayName="XAxis";var h5e=["type"],f5e=["dangerouslySetInnerHTML","ticks","scale"],m5e=["id","scale"];function CS(){return CS=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},CS.apply(null,arguments)}function tM(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function nM(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?tM(Object(n),!0).forEach(function(r){p5e(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):tM(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function p5e(e,t,n){return(t=x5e(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function x5e(e){var t=g5e(e,"string");return typeof t=="symbol"?t:t+""}function g5e(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function ES(e,t){if(e==null)return{};var n,r,a=y5e(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function y5e(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function b5e(e){var t=Nn(),n=p.useRef(null),r=xE(),a=e.type,i=ES(e,h5e),o=B0(r,"yAxis",a),l=p.useMemo(()=>{if(o!=null)return nM(nM({},i),{},{type:o})},[o,i]);return p.useLayoutEffect(()=>{l!=null&&(n.current===null?t(fOe(l)):n.current!==l&&t(mOe({prev:n.current,next:l})),n.current=l)},[l,t]),p.useLayoutEffect(()=>()=>{n.current&&(t(pOe(n.current)),n.current=null)},[t]),null}function v5e(e){var t=e.yAxisId,n=e.className,r=e.width,a=e.label,i=p.useRef(null),o=p.useRef(null),l=ot(hE),c=Jr(),u=Nn(),d="yAxis",h=ot(b=>kW(b,t)),f=ot(b=>B2e(b,t)),m=ot(b=>NW(b,d,t,c)),x=ot(b=>Qz(b,t));if(p.useLayoutEffect(()=>{if(!(r!=="auto"||!h||nw(a)||p.isValidElement(a)||x==null)){var b=i.current;if(b){var v=b.getCalculatedWidth();Math.round(h.width)!==Math.round(v)&&u(xOe({id:t,width:v}))}}},[m,h,u,a,t,r,x]),h==null||f==null||x==null)return null;e.dangerouslySetInnerHTML,e.ticks,e.scale;var g=ES(e,f5e);x.id,x.scale;var y=ES(x,m5e);return p.createElement(HA,CS({},g,y,{ref:i,labelRef:o,x:f.x,y:f.y,tickTextProps:r==="auto"?{width:void 0}:{width:r},width:h.width,height:h.height,className:un("recharts-".concat(d," ").concat(d),n),viewBox:l,ticks:m,axisType:d,axisId:t}))}var w5e={allowDataOverflow:es.allowDataOverflow,allowDecimals:es.allowDecimals,allowDuplicatedCategory:es.allowDuplicatedCategory,angle:es.angle,axisLine
876:Jl.axisLine,hide:!1,includeHidden:es.includeHidden,interval:es.interval,label:!1,minTickGap:es.minTickGap,mirror:es.mirror,orientation:es.orientation,padding:es.padding,reversed:es.reversed,scale:es.scale,tick:es.tick,tickCount:es.tickCount,tickLine:Jl.tickLine,tickSize:Jl.tickSize,type:es.type,niceTicks:es.niceTicks,width:es.width,yAxisId:0},_5e=e=>{var t=$r(e,w5e);return p.createElement(p.Fragment,null,p.createElement(b5e,{interval:t.interval,id:t.yAxisId,scale:t.scale,type:t.type,domain:t.domain,allowDataOverflow:t.allowDataOverflow,dataKey:t.dataKey,allowDuplicatedCategory:t.allowDuplicatedCategory,allowDecimals:t.allowDecimals,tickCount:t.tickCount,padding:t.padding,includeHidden:t.includeHidden,reversed:t.reversed,ticks:t.ticks,width:t.width,orientation:t.orientation,mirror:t.mirror,hide:t.hide,unit:t.unit,name:t.name,angle:t.angle,minTickGap:t.minTickGap,tick:t.tick,tickFormatter:t.tickFormatter,niceTicks:t.niceTicks}),p.createElement(v5e,t))},zr=p.memo(_5e,mH);zr.displayName="YAxis";var k5e=(e,t)=>t,QA=be([k5e,sn,hz,Ss,WW,yc,oEe,ds],mEe);function j5e(e){return"getBBox"in e.currentTarget&&typeof e.currentTarget.getBBox=="function"}function e3(e){var t=e.currentTarget.getBoundingClientRect(),n,r;if(j5e(e)){var a=e.currentTarget.getBBox();n=a.width>0?t.width/a.width:1,r=a.height>0?t.height/a.height:1}else{var i=e.currentTarget;n=i.offsetWidth>0?t.width/i.offsetWidth:1,r=i.offsetHeight>0?t.height/i.offsetHeight:1}var o=(l,c)=>({relativeX:Math.round((l-t.left)/n),relativeY:Math.round((c-t.top)/r)});return"touches"in e?Array.from(e.touches).map(l=>o(l.clientX,l.clientY)):o(e.clientX,e.clientY)}var pH=wi("mouseClick"),xH=vx();xH.startListening({actionCreator:pH,effect:(e,t)=>{var n=e.payload,r=QA(t.getState(),e3(n));(r==null?void 0:r.activeIndex)!=null&&t.dispatch(nCe({activeIndex:r.activeIndex,activeDataKey:void 0,activeCoordinate:r.activeCoordinate}))}});var AS=wi("mouseMove"),gH=vx(),ah=null,Ru=null,fk=null;gH.startListening({actionCreator:AS,effect:(e,t)=>{var n=e.payload,r=t.getState(),a=r.eventSettings,i=a.throttleDelay,o=a.throttledEvents,l=o==="all"||(o==null?void 0:o.includes("mousemove"));ah!==null&&(cancelAnimationFrame(ah),ah=null),Ru!==null&&(typeof i!="number"||!l)&&(clearTimeout(Ru),Ru=null),fk=e3(n);var c=()=>{var u=t.getState(),d=Lx(u,u.tooltip.settings.shared);if(!fk){ah=null,Ru=null;return}if(d==="axis"){var h=QA(u,fk);(h==null?void 0:h.activeIndex)!=null?t.dispatch(PW({activeIndex:h.activeIndex,activeDataKey:void 0,activeCoordinate:h.activeCoordinate})):t.dispatch(IW())}ah=null,Ru=null};if(!l){c();return}i==="raf"?ah=requestAnimationFrame(c):typeof i=="number"&&Ru===null&&(Ru=setTimeout(c,i))}});function N5e(e,t){return t instanceof HTMLElement?"HTMLElement <".concat(t.tagName,' class="').concat(t.className,'">'):t===window?"global.window":e==="children"&&typeof t=="object"&&t!==null?"<<CHILDREN>>":t}var rM={accessibilityLayer:!0,barCategoryGap:"10%",barGap:4,barSize:void 0,className:void 0,maxBarSize:void 0,stackOffset:"none",syncId:void 0,syncMethod:"index",baseValue:void 0,reverseStackOrder:!1},yH=ga({name:"rootProps",initialState:rM,reducers:{updateOptions:(e,t)=>{var n;e.accessibilityLayer=t.payload.accessibilityLayer,e.barCategoryGap=t.payload.barCategoryGap,e.barGap=(n=t.payload.barGap)!==null&&n!==void 0?n:rM.barGap,e.barSize=t.payload.barSize,e.maxBarSize=t.payload.maxBarSize,e.stackOffset=t.payload.stackOffset,e.syncId=t.payload.syncId,e.syncMethod=t.payload.syncMethod,e.className=t.payload.className,e.baseValue=t.payload.baseValue,e.reverseStackOrder=t.payload.reverseStackOrder}}}),S5e=yH.reducer,C5e=yH.actions.updateOptions,E5e=null,A5e={updatePolarOptions:(e,t)=>e===null?t.payload:(e.startAngle=t.payload.startAngle,e.endAngle=t.payload.endAngle,e.cx=t.payload.cx,e.cy=t.payload.cy,e.innerRadius=t.payload.innerRadius,e.outerRadius=t.payload.outerRadius,e)},bH=ga({name:"polarOptions",initialState:E5e,reducers:A5e}),T5e=bH.actions.updatePolarOptions,O5e=bH.reducer,vH=wi("keyDown"),wH=wi("focus"),_H=wi("blur"),gw=vx(),ih=null,Du=null,Dg=null;gw.startListening({actionCreator:vH,effect:(e,t)=>{Dg=e.payload,ih!==null&&(cancelAnimationFrame(ih),ih=null);var n=t.getState(),r=n.eventSettings,a=r.throttleDelay,i=r.throttledEvents,o=i==="all"||i.includes("keydown");
876Du!==null&&(typeof a!="number"||!o)&&(clearTimeout(Du),Du=null);var l=()=>{try{var c=t.getState(),u=c.rootProps.accessibilityLayer!==!1;if(!u)return;var d=c.tooltip.keyboardInteraction,h=Dg;if(h!=="ArrowRight"&&h!=="ArrowLeft"&&h!=="Enter")return;var f=ep(d,Ed(c),ef(c),tf(c)),m=f==null?-1:Number(f),x=!Number.isFinite(m)||m<0,g=yc(c),y=Ed(c),b=Lx(c,c.tooltip.settings.shared);if(h==="Enter"){if(x)return;var v=Qb(c,b,"hover",String(d.index));t.dispatch(Jb({active:!d.active,activeIndex:d.index,activeCoordinate:v}));return}var w=H2e(c),_=w==="left-to-right"?1:-1,k=h==="ArrowRight"?1:-1,j;if(x){var N=ef(c),E=tf(c),A=k*_,C=I=>({active:!1,index:String(I),dataKey:void 0,graphicalItemId:void 0,coordinate:void 0});if(j=-1,A>0){for(var T=0;T<y.length;T++)if(ep(C(T),y,N,E)!=null){j=T;break}}else for(var S=y.length-1;S>=0;S--)if(ep(C(S),y,N,E)!=null){j=S;break}if(j<0)return}else{j=m+k*_;var O=(g==null?void 0:g.length)||y.length;if(O===0||j>=O||j<0)return}var R=Qb(c,b,"hover",String(j));t.dispatch(Jb({active:!0,activeIndex:j.toString(),activeCoordinate:R}))}finally{ih=null,Du=null}};if(!o){l();return}a==="raf"?ih=requestAnimationFrame(l):typeof a=="number"&&Du===null&&(l(),Dg=null,Du=setTimeout(()=>{Dg?l():(Du=null,ih=null)},a))}});gw.startListening({actionCreator:wH,effect:(e,t)=>{var n=t.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var a=n.tooltip.keyboardInteraction;if(!a.active&&a.index==null){var i="0",o=Lx(n,n.tooltip.settings.shared),l=Qb(n,o,"hover",String(i));t.dispatch(Jb({active:!0,activeIndex:i,activeCoordinate:l}))}}}});gw.startListening({actionCreator:_H,effect:(e,t)=>{var n=t.getState(),r=n.rootProps.accessibilityLayer!==!1;if(r){var a=n.tooltip.keyboardInteraction;a.active&&t.dispatch(Jb({active:!1,activeIndex:a.index,activeCoordinate:a.coordinate}))}}});function kH(e){e.persist();var t=e.currentTarget;return new Proxy(e,{get:(n,r)=>{if(r==="currentTarget")return t;var a=Reflect.get(n,r);return typeof a=="function"?a.bind(n):a}})}var Pi=wi("externalEvent"),jH=vx(),Mg=new Map,mm=new Map,mk=new Map;jH.startListening({actionCreator:Pi,effect:(e,t)=>{var n=e.payload,r=n.handler,a=n.reactEvent;if(r!=null){var i=a.type,o=kH(a);mk.set(i,{handler:r,reactEvent:o});var l=Mg.get(i);l!==void 0&&(cancelAnimationFrame(l),Mg.delete(i));var c=t.getState(),u=c.eventSettings,d=u.throttleDelay,h=u.throttledEvents,f=h,m=f==="all"||(f==null?void 0:f.includes(i)),x=mm.get(i);x!==void 0&&(typeof d!="number"||!m)&&(clearTimeout(x),mm.delete(i));var g=()=>{var v=mk.get(i);try{if(!v)return;var w=v.handler,_=v.reactEvent,k=t.getState(),j={activeCoordinate:VCe(k),activeDataKey:jA(k),activeIndex:iu(k),activeLabel:VW(k),activeTooltipIndex:iu(k),isTooltipActive:qCe(k)};w&&w(j,_)}finally{Mg.delete(i),mm.delete(i),mk.delete(i)}};if(!m){g();return}if(d==="raf"){var y=requestAnimationFrame(g);Mg.set(i,y)}else if(typeof d=="number"){if(!mm.has(i)){g();var b=setTimeout(g,d);mm.set(i,b)}}else g()}}});var I5e=be([Ff],e=>e.tooltipItemPayloads),P5e=be([I5e,(e,t)=>t,(e,t,n)=>n],(e,t,n)=>{if(t!=null){var r=e.find(i=>i.settings.graphicalItemId===n);if(r!=null){var a=r.getPosition;if(a!=null)return a(t)}}}),NH=wi("touchMove"),SH=vx(),Mu=null,jc=null,sM=null,pm=null;SH.startListening({actionCreator:NH,effect:(e,t)=>{var n=e.payload;if(!(n.touches==null||n.touches.length===0)){pm=kH(n);var r=t.getState(),a=r.eventSettings,i=a.throttleDelay,o=a.throttledEvents,l=o==="all"||o.includes("touchmove");Mu!==null&&(cancelAnimationFrame(Mu),Mu=null),jc!==null&&(typeof i!="number"||!l)&&(clearTimeout(jc),jc=null),sM=Array.from(n.touches).map(u=>e3({clientX:u.clientX,clientY:u.clientY,currentTarget:n.currentTarget}));var c=()=>{if(pm!=null){var u=t.getState(),d=Lx(u,u.tooltip.settings.shared);if(d==="axis"){var h,f=(h=sM)===null||h===void 0?void 0:h[0];if(f==null){Mu=null,jc=null;return}var m=QA(u,f);(m==null?void 0:m.activeIndex)!=null&&t.dispatch(PW({activeIndex:m.activeIndex,activeDataKey:void 0,activeCoordinate:m.activeCoordinate}))}else if(d==="item"){var x,g=pm.touches[0];if(document.elementFromPoint==null||g==null)return;var y=document.elementFromPoint(g.clientX,g.clientY);if(!y||!y.getAttribute)return;var b=y.getAttribute(kU),v=(x=y.getAttribute(jU))!==null&&x!==void 0?x:void 0,w=Ud(u).find(j=>j.id===v);if(b==null||w==null||v==null)return;var _=w.dataKey,k=P5e(u,b,v);t.dispatch(OW({activeDataKey:_,activeIndex:b,activeCoordinate:k,activeGraphicalItemId:v}))}Mu=null,jc=null}};if(!l){c();return}i==="raf"?Mu=requestAnimationFrame(c):typeof i=="number"&&jc===null&&(c(),pm=null,jc=setTimeout(()=>{pm?c():(jc=null,Mu=null)},i))}}});var t3={throttleDelay:"raf",throttledEvents:["mousemove","touchmove","pointermove","scroll","wheel"]},CH=ga({name:"eventSettings",initialState:t3,reducers:{setEventSettings:(e,t)=>{t.payload.throttleDelay!=null&&(e.throttleDelay=t.payload.throttleDelay),t.payload.throttledEvents!=null&&(e.throttledEvents=pn(t.payload.throttledEvents))}}}),R5e=CH.actions.setEventSettings,D5e=CH.reducer,M5e=H9({brush:BOe,cartesianAxis:yOe,chartData:KEe,errorBars:$Pe,eventSettings:D5e,graphicalItems:wTe,layout:ewe,legend:r1e,options:FEe,polarAxis:C3e,polarOptions:O5e,referenceElements:YOe,renderedTicks:WIe,rootProps:S5e,tooltip:rCe,zIndex:CEe}),$5e=function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"Chart";return N0e({reducer:M5e,preloadedState:t,middleware:r=>{var a;return r({serializableCheck:!1,immutableCheck:!["commonjs","es6","production"].includes((a="es6")!==null&&a!==void 0?a:"")}).concat([xH.middleware,gH.middleware,gw.middleware,jH.middleware,SH.middleware])},enhancers:r=>{var a=r;return typeof r=="function"&&(a=r()),a.concat(iU({type:"raf"}))},devTools:{serialize:{replacer:N5e},name:"recharts-".concat(n)}})};function EH(e){var t=e.preloadedState,n=e.children,r=e.reduxStoreName,a=Jr(),i=p.useRef(null);if(a)return n;i.current==null&&(i.current=$5e(t,r));var o=rE;return p.createElement(b1e,{context:o,store:i.current},n)}function L5e(e){var t=e.layout,n=e.margin,r=Nn(),a=Jr();return p.useEffect(()=>{a||(r(X0e(t)),r(Z0e(n)))},[r,a,t,n]),null}var AH=p.memo(L5e,Ld);function TH(e){var t=Nn();return p.useEffect(()=>{t(C5e(e))},[t,e]),null}var F5e=e=>{var t=Nn();return p.useEffect(()=>{t(R5e(e))},[t,e]),null},OH=p.memo(F5e,Ld);function aM(e){var t=e.zIndex,n=e.isPanorama,r=p.useRef(null),a=Nn();return p.useLayoutEffect(()=>(r.current&&a(NEe({zIndex:t,element:r.current,isPanorama:n})),()=>{a(SEe({zIndex:t,isPanorama:n}))}),[a,t,n]),p.createElement("g",{tabIndex:-1,ref:r,className:"recharts-zIndex-layer_".concat(t)})}function iM(e){var t=e.children,n=e.isPanorama,r=ot(xEe);if(!r||r.length===0)return t;var a=r.filter(o=>o<0),i=r.filter(o=>o>0);return p.createElement(p.Fragment,null,a.map(o=>p.createElement(aM,{key:o,zIndex:o,isPanorama:n})),t,i.map(o=>p.createElement(aM,{key:o,zIndex:o,isPanorama:n})))}var B5e=["children"];function U5e(e,t){if(e==null)return{};var n,r,a=z5e(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function z5e(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function uv(){return uv=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},uv.apply(null,arguments)}var W5e={width:"100%",height:"100%",display:"block"},K5e=p.forwardRef((e,t)=>
876{var n=mE(),r=pE(),a=DU();if(!ol(n)||!ol(r))return null;var i=e.children,o=e.otherAttributes,l=e.title,c=e.desc,u,d;return o!=null&&(typeof o.tabIndex=="number"?u=o.tabIndex:u=a?0:void 0,typeof o.role=="string"?d=o.role:d=a?"application":void 0),p.createElement(HC,uv({},o,{title:l,desc:c,role:d,tabIndex:u,width:n,height:r,style:W5e,ref:t}),i)}),H5e=e=>{var t=e.children,n=ot(L0);if(!n)return null;var r=n.width,a=n.height,i=n.y,o=n.x;return p.createElement(HC,{width:r,height:a,x:o,y:i},t)},oM=p.forwardRef((e,t)=>{var n=e.children,r=U5e(e,B5e),a=Jr();return a?p.createElement(H5e,null,p.createElement(iM,{isPanorama:!0},n)):p.createElement(K5e,uv({ref:t},r),p.createElement(iM,{isPanorama:!1},n))});function V5e(e,t){return Z5e(e)||Y5e(e,t)||G5e(e,t)||q5e()}function q5e(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 877In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function G5e(e,t){if(e){if(typeof e=="string")return lM(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?lM(e,t):void 0}}function lM(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Y5e(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function Z5e(e){if(Array.isArray(e))return e}function X5e(){var e=Nn(),t=p.useState(null),n=V5e(t,2),r=n[0],a=n[1],i=ot(xwe);return p.useEffect(()=>{if(r!=null){var o=r.getBoundingClientRect(),l=o.width/r.offsetWidth;Mt(l)&&l!==i&&e(Q0e(l))}},[r,e,i]),a}function cM(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function J5e(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?cM(Object(n),!0).forEach(function(r){Q5e(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):cM(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Q5e(e,t,n){return(t=eDe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function eDe(e){var t=tDe(e,"string");return typeof t=="symbol"?t:t+""}function tDe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Gc(){return Gc=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Gc.apply(null,arguments)}function dv(e,t){return aDe(e)||sDe(e,t)||rDe(e,t)||nDe()}function nDe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. 878In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function rDe(e,t){if(e){if(typeof e=="string")return uM(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?uM(e,t):void 0}}function uM(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function sDe(e,t){var n=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(n!=null){var r,a,i,o,l=[],c=!0,u=!1;try{if(i=(n=n.call(e)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(l.push(r.value),l.length!==t);c=!0);}catch(d){u=!0,a=d}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(u)throw a}}return l}}function aDe(e){if(Array.isArray(e))return e}var iDe=()=>(QEe(),null);function hv(e){if(typeof e=="number")return e;if(typeof e=="string"){var t=parseFloat(e);
878if(!Number.isNaN(t))return t}return 0}var oDe=p.forwardRef((e,t)=>{var n,r,a=p.useRef(null),i=p.useState({containerWidth:hv((n=e.style)===null||n===void 0?void 0:n.width),containerHeight:hv((r=e.style)===null||r===void 0?void 0:r.height)}),o=dv(i,2),l=o[0],c=o[1],u=p.useCallback((h,f)=>{c(m=>{var x=Math.round(h),g=Math.round(f);return m.containerWidth===x&&m.containerHeight===g?m:{containerWidth:x,containerHeight:g}})},[]),d=p.useCallback(h=>{if(typeof t=="function"&&t(h),a.current!=null&&(a.current.disconnect(),a.current=null),h!=null&&typeof ResizeObserver<"u"){var f=h.getBoundingClientRect(),m=f.width,x=f.height;u(m,x);var g=b=>{var v=b[0];if(v!=null){var w=v.contentRect,_=w.width,k=w.height;u(_,k)}},y=new ResizeObserver(g);y.observe(h),a.current=y}},[t,u]);return p.useEffect(()=>()=>{var h=a.current;h!=null&&h.disconnect()},[u]),p.createElement(p.Fragment,null,p.createElement(kx,{width:l.containerWidth,height:l.containerHeight}),p.createElement("div",Gc({ref:d},e)))}),lDe=p.forwardRef((e,t)=>{var n=e.width,r=e.height,a=p.useState({containerWidth:hv(n),containerHeight:hv(r)}),i=dv(a,2),o=i[0],l=i[1],c=p.useCallback((d,h)=>{l(f=>{var m=Math.round(d),x=Math.round(h);return f.containerWidth===m&&f.containerHeight===x?f:{containerWidth:m,containerHeight:x}})},[]),u=p.useCallback(d=>{if(typeof t=="function"&&t(d),d!=null){var h=d.getBoundingClientRect(),f=h.width,m=h.height;c(f,m)}},[t,c]);return p.createElement(p.Fragment,null,p.createElement(kx,{width:o.containerWidth,height:o.containerHeight}),p.createElement("div",Gc({ref:u},e)))}),cDe=p.forwardRef((e,t)=>{var n=e.width,r=e.height;return p.createElement(p.Fragment,null,p.createElement(kx,{width:n,height:r}),p.createElement("div",Gc({ref:t},e)))}),uDe=p.forwardRef((e,t)=>{var n=e.width,r=e.height;return typeof n=="string"||typeof r=="string"?p.createElement(lDe,Gc({},e,{ref:t})):typeof n=="number"&&typeof r=="number"?p.createElement(cDe,Gc({},e,{width:n,height:r,ref:t})):p.createElement(p.Fragment,null,p.createElement(kx,{width:n,height:r}),p.createElement("div",Gc({ref:t},e)))});function dDe(e){return e?oDe:uDe}var hDe=p.forwardRef((e,t)=>{var n=e.children,r=e.className,a=e.height,i=e.onClick,o=e.onContextMenu,l=e.onDoubleClick,c=e.onMouseDown,u=e.onMouseEnter,d=e.onMouseLeave,h=e.onMouseMove,f=e.onMouseUp,m=e.onTouchEnd,x=e.onTouchMove,g=e.onTouchStart,y=e.style,b=e.width,v=e.responsive,w=e.dispatchTouchEvents,_=w===void 0?!0:w,k=p.useRef(null),j=Nn(),N=p.useState(null),E=dv(N,2),A=E[0],C=E[1],T=p.useState(null),S=dv(T,2),O=S[0],R=S[1],I=X5e(),$=fE(),P=($==null?void 0:$.width)>0?$.width:b,F=($==null?void 0:$.height)>0?$.height:a,Z=p.useCallback(ae=>{I(ae),typeof t=="function"&&t(ae),C(ae),R(ae),ae!=null&&(k.current=ae)},[I,t,C,R]),D=p.useCallback(ae=>{j(pH(ae)),j(Pi({handler:i,reactEvent:ae}))},[j,i]),H=p.useCallback(ae=>{j(AS(ae)),j(Pi({handler:u,reactEvent:ae}))},[j,u]),Y=p.useCallback(ae=>{j(IW()),j(Pi({handler:d,reactEvent:ae}))},[j,d]),M=p.useCallback(ae=>{j(AS(ae)),j(Pi({handler:h,reactEvent:ae}))},[j,h]),z=p.useCallback(()=>{j(wH())},[j]),G=p.useCallback(()=>{j(_H())},[j]),te=p.useCallback(ae=>{j(vH(ae.key))},[j]),re=p.useCallback(ae=>{j(Pi({handler:o,reactEvent:ae}))},[j,o]),L=p.useCallback(ae=>{j(Pi({handler:l,reactEvent:ae}))},[j,l]),q=p.useCallback(ae=>{j(Pi({handler:c,reactEvent:ae}))},[j,c]),me=p.useCallback(ae=>{j(Pi({handler:f,reactEvent:ae}))},[j,f]),ee=p.useCallback(ae=>{j(Pi({handler:g,reactEvent:ae}))},[j,g]),ne=p.useCallback(ae=>{_&&j(NH(ae)),j(Pi({handler:x,reactEvent:ae}))},[j,_,x]),X=p.useCallback(ae=>{j(Pi({handler:m,reactEvent:ae}))},[j,m]),he=dDe(v);return p.createElement(tK.Provider,{value:A},p.createElement(o9.Provider,{value:O},p.createElement(he,{width:P??(y==null?void 0:y.width),height:F??(y==null?void 0:y.height),className:un("recharts-wrapper",r),style:J5e({position:"relative",cursor:"default",width:P,height:F},y),onClick:D,onContextMenu:re,onDoubleClick:L,onFocus:z,onBlur:G,onKeyDown:te,onMouseDown:q,onMouseEnter:H,onMouseLeave:Y,onMouseMove:M,onMouseUp:me,onTouchEnd:X,onTouchMove:ne,onTouchStart:ee,ref:Z},p.createElement(iDe,null),n)))}),fDe=["width","height","responsive","children","className","style","compact","title","desc"];function mDe(e,t){if(e==null)return{};var n,r,a=pDe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function pDe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var IH=p.forwardRef((e,t)=>
878{var n=e.width,r=e.height,a=e.responsive,i=e.children,o=e.className,l=e.style,c=e.compact,u=e.title,d=e.desc,h=mDe(e,fDe),f=Ra(h);return c?p.createElement(p.Fragment,null,p.createElement(kx,{width:n,height:r}),p.createElement(oM,{otherAttributes:f,title:u,desc:d},i)):p.createElement(hDe,{className:o,style:l,width:n,height:r,responsive:a??!1,onClick:e.onClick,onMouseLeave:e.onMouseLeave,onMouseEnter:e.onMouseEnter,onMouseMove:e.onMouseMove,onMouseDown:e.onMouseDown,onMouseUp:e.onMouseUp,onContextMenu:e.onContextMenu,onDoubleClick:e.onDoubleClick,onTouchStart:e.onTouchStart,onTouchMove:e.onTouchMove,onTouchEnd:e.onTouchEnd},p.createElement(oM,{otherAttributes:f,title:u,desc:d,ref:t},p.createElement(tIe,null,i)))});function TS(){return TS=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},TS.apply(null,arguments)}function dM(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function xDe(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?dM(Object(n),!0).forEach(function(r){gDe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):dM(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function gDe(e,t,n){return(t=yDe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function yDe(e){var t=bDe(e,"string");return typeof t=="symbol"?t:t+""}function bDe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var vDe={top:5,right:5,bottom:5,left:5},wDe=xDe({accessibilityLayer:!0,barCategoryGap:"10%",barGap:4,layout:"horizontal",margin:vDe,responsive:!1,reverseStackOrder:!1,stackOffset:"none",syncMethod:"index"},t3),yw=p.forwardRef(function(t,n){var r,a=$r(t.categoricalChartProps,wDe),i=t.chartName,o=t.defaultTooltipEventType,l=t.validateTooltipEventTypes,c=t.tooltipPayloadSearcher,u=t.categoricalChartProps,d={chartName:i,defaultTooltipEventType:o,validateTooltipEventTypes:l,tooltipPayloadSearcher:c,eventEmitter:void 0};return p.createElement(EH,{preloadedState:{options:d},reduxStoreName:(r=u.id)!==null&&r!==void 0?r:i},p.createElement(RK,{chartData:u.data}),p.createElement(AH,{layout:a.layout,margin:a.margin}),p.createElement(OH,{throttleDelay:a.throttleDelay,throttledEvents:a.throttledEvents}),p.createElement(TH,{baseValue:a.baseValue,accessibilityLayer:a.accessibilityLayer,barCategoryGap:a.barCategoryGap,maxBarSize:a.maxBarSize,stackOffset:a.stackOffset,barGap:a.barGap,barSize:a.barSize,syncId:a.syncId,syncMethod:a.syncMethod,className:a.className,reverseStackOrder:a.reverseStackOrder}),p.createElement(IH,TS({},a,{ref:n})))}),_De=["axis"],PH=p.forwardRef((e,t)=>p.createElement(yw,{chartName:"LineChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:_De,tooltipPayloadSearcher:Bx,categoricalChartProps:e,ref:t})),kDe=["axis","item"],zx=p.forwardRef((e,t)=>p.createElement(yw,{chartName:"BarChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:kDe,tooltipPayloadSearcher:Bx,categoricalChartProps:e,ref:t}));function jDe(e){var t=Nn();return p.useEffect(()=>{t(T5e(e))},[t,e]),null}var NDe=["layout"];function OS(){return OS=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},OS.apply(null,arguments)}function SDe(e,t){if(e==null)return{};var n,r,a=CDe(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function CDe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function hM(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function EDe(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};
878t%2?hM(Object(n),!0).forEach(function(r){ADe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):hM(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function ADe(e,t,n){return(t=TDe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function TDe(e){var t=ODe(e,"string");return typeof t=="symbol"?t:t+""}function ODe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var IDe={top:5,right:5,bottom:5,left:5},RH=EDe({accessibilityLayer:!0,stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:IDe,reverseStackOrder:!1,syncMethod:"index",layout:"radial",responsive:!1,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"},t3),PDe=p.forwardRef(function(t,n){var r,a=$r(t.categoricalChartProps,RH),i=a.layout,o=SDe(a,NDe),l=t.chartName,c=t.defaultTooltipEventType,u=t.validateTooltipEventTypes,d=t.tooltipPayloadSearcher,h={chartName:l,defaultTooltipEventType:c,validateTooltipEventTypes:u,tooltipPayloadSearcher:d,eventEmitter:void 0};return p.createElement(EH,{preloadedState:{options:h},reduxStoreName:(r=a.id)!==null&&r!==void 0?r:l},p.createElement(RK,{chartData:a.data}),p.createElement(AH,{layout:i,margin:a.margin}),p.createElement(OH,{throttleDelay:a.throttleDelay,throttledEvents:a.throttledEvents}),p.createElement(TH,{baseValue:void 0,accessibilityLayer:a.accessibilityLayer,barCategoryGap:a.barCategoryGap,maxBarSize:a.maxBarSize,stackOffset:a.stackOffset,barGap:a.barGap,barSize:a.barSize,syncId:a.syncId,syncMethod:a.syncMethod,className:a.className,reverseStackOrder:a.reverseStackOrder}),p.createElement(jDe,{cx:a.cx,cy:a.cy,startAngle:a.startAngle,endAngle:a.endAngle,innerRadius:a.innerRadius,outerRadius:a.outerRadius}),p.createElement(IH,OS({},o,{ref:n})))});function fM(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(e,a).enumerable})),n.push.apply(n,r)}return n}function mM(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?fM(Object(n),!0).forEach(function(r){RDe(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):fM(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function RDe(e,t,n){return(t=DDe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function DDe(e){var t=MDe(e,"string");return typeof t=="symbol"?t:t+""}function MDe(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}var $De=["item"],LDe=mM(mM({},RH),{},{layout:"centric",startAngle:0,endAngle:360}),FDe=p.forwardRef((e,t)=>{var n=$r(e,LDe);return p.createElement(PDe,{chartName:"PieChart",defaultTooltipEventType:"item",validateTooltipEventTypes:$De,tooltipPayloadSearcher:Bx,categoricalChartProps:n,ref:t})}),BDe=["axis"],DH=p.forwardRef((e,t)=>p.createElement(yw,{chartName:"AreaChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:BDe,tooltipPayloadSearcher:Bx,categoricalChartProps:e,ref:t})),UDe=["axis"],Wx=p.forwardRef((e,t)=>
878p.createElement(yw,{chartName:"ComposedChart",defaultTooltipEventType:"axis",validateTooltipEventTypes:UDe,tooltipPayloadSearcher:Bx,categoricalChartProps:e,ref:t}));const zDe=hf("animate-pulse",{variants:{variant:{text:"inline-block h-3 w-16 rounded bg-outline-subtle align-middle",block:"h-14 rounded-lg border border-outline-subtle bg-surface-subtle",row:"h-4 w-full rounded bg-outline-subtle"}},defaultVariants:{variant:"text"}}),Ta=p.forwardRef(({className:e,variant:t="text",...n},r)=>{const a=t==="text"?"span":"div";return s.jsx(a,{ref:r,className:B(zDe({variant:t}),e),...n})});Ta.displayName="Skeleton";const Ue={purple:"#7239EA",green:"#10b981",blue:"#2563eb",amber:"#f59e0b",red:"#ef4444",teal:"#059669",violet:"#a78bfa",slate:"#667085"},et={soft:"#D1C8F9",mid:"#BAA7F6",strong:"#A282F2",deep:"#8554ED",primary:"#7239EA",dark:"#6832B4",track:"rgb(var(--color-surface-sunken))",neutral:"rgb(var(--color-outline))",ink:"rgb(var(--color-text-primary))",success:"#17B26A",warning:"#FDB022",danger:"#F04438",dangerSoft:"#F97066"},kr="rgb(var(--color-text-tertiary))",bw="rgb(var(--color-outline-subtle))",Co="rgb(var(--color-outline-faint))",Nu="rgb(var(--color-surface-subtle))",vw="rgb(var(--color-text-secondary))";function n3({pct:e,color:t=et.primary,label:n,value:r}){return s.jsxs("div",{className:"mb-2.5 last:mb-0",children:[s.jsxs("div",{className:"mb-1.5 flex items-baseline justify-between gap-2",children:[s.jsx("span",{className:"truncate text-body-xs text-text-secondary",children:n}),s.jsx("span",{className:"shrink-0 text-body-xs font-semibold tabular-nums text-text-primary",children:r})]}),s.jsx("div",{className:"h-1.5 overflow-hidden rounded-full",style:{background:et.track},children:s.jsx("div",{className:"h-full rounded-full",style:{width:`${Math.max(0,Math.min(100,e))}%`,background:t}})})]})}function MH({pct:e,color:t=et.primary}){return s.jsx("div",{className:"h-2 overflow-hidden rounded-full",style:{background:et.track},children:s.jsx("div",{className:"h-full rounded-full",style:{width:`${Math.max(0,Math.min(100,e))}%`,background:t}})})}function Kx({segments:e,height:t=10}){const n=e.reduce((r,a)=>r+a.value,0)||1;return s.jsx("div",{className:"flex w-full overflow-hidden rounded-full",style:{height:t,background:et.track},children:e.map((r,a)=>s.jsx("div",{style:{width:`${r.value/n*100}%`,background:r.color},title:r.label},a))})}function IS({color:e,children:t,className:n}){return s.jsxs("span",{className:`inline-flex items-center gap-1.5 text-body-xs text-text-secondary ${n??""}`,children:[s.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{background:e}}),t]})}const Ch={soft:et.soft,mid:et.mid,strong:et.strong,deep:et.deep,primary:et.primary,dark:et.dark,success:et.success,warning:et.warning,danger:et.danger,neutral:et.neutral};function PS(e){return typeof e=="number"?e:e.value}function WDe(e){return typeof e=="number"?void 0:e.label}function KDe(e,t,n){return n?Ch[n]:e>=t?Ch.primary:e>=.65?Ch.strong:Ch.soft}function r3({data:e,height:t=140,gap:n=4,axis:r,highlight:a=.85,tone:i,className:o}){const l=Math.max(...e.map(PS),1);return s.jsxs("div",{className:o,children:[s.jsx("div",{className:"flex items-end",style:{height:t,gap:n},children:e.map((c,u)=>{const d=PS(c),h=WDe(c),f=d/l;return s.jsx("div",{title:h?`${h}: ${d}`:String(d),className:"flex-1 min-w-[2px] rounded-t-[3px]",style:{height:`${Math.max(2,f*100)}%`,background:KDe(f,a,i)}},u)})}),r&&s.jsxs("div",{className:"mt-2 flex justify-between text-body-xs text-text-tertiary",children:[s.jsx("span",{children:r[0]}),s.jsx("span",{children:r[1]})]})]})}function s3({data:e,height:t=140,tone:n="primary",area:r=!0,axis:a,stroke:i,className:o}){const l=e.map(PS),c=Math.max(...l,1),u=Math.min(...l,0),d=c-u||1,h=100,f=100,m=(y,b)=>[l.length===1?0:b/(l.length-1)*h,f-(y-u)/d*f],x=l.map((y,b)=>m(y,b).map(v=>v.toFixed(2)).join(",")).join(" "),g=i??Ch[n];return s.jsxs("div",{className:o,children:[s.jsxs("svg",{viewBox:`0 0 ${h} ${f}`,preserveAspectRatio:"none",className:"block w-full",style:{height:t},children:[[0,50,100].map(y=>s.jsx("line",{x1:"0",y1:y,x2:h,y2:y,stroke:et.track,strokeWidth:"0.5",vectorEffect:"non-scaling-stroke"}
878,y)),r&&s.jsx("polygon",{points:`0,${f} ${x} ${h},${f}`,fill:g,opacity:.12}),s.jsx("polyline",{points:x,fill:"none",stroke:g,strokeWidth:"2",vectorEffect:"non-scaling-stroke",strokeLinecap:"round",strokeLinejoin:"round"})]}),a&&s.jsxs("div",{className:"mt-2 flex justify-between text-body-xs text-text-tertiary",children:[s.jsx("span",{children:a[0]}),s.jsx("span",{children:a[1]})]})]})}const pM=["primary","strong","soft","deep","dark","mid"];function HDe({data:e,size:t=132,thickness:n=16,centerLabel:r,centerValue:a,legend:i=!0,className:o}){const l=e.slice(0,6),c=l.reduce((m,x)=>m+x.value,0)||1,u=(t-n)/2,d=2*Math.PI*u;let h=0;const f=l.map((m,x)=>{const g=m.value/c*d,y={...m,len:g,offset:h,color:Ch[m.tone??pM[x%pM.length]]};return h+=g,y});return s.jsxs("div",{className:B("flex items-center gap-5",o),children:[s.jsxs("div",{className:"relative shrink-0",style:{width:t,height:t},children:[s.jsxs("svg",{width:t,height:t,className:"block",style:{transform:"rotate(-90deg)"},children:[s.jsx("circle",{cx:t/2,cy:t/2,r:u,fill:"none",stroke:et.track,strokeWidth:n}),f.map((m,x)=>s.jsx("circle",{cx:t/2,cy:t/2,r:u,fill:"none",stroke:m.color,strokeWidth:n,strokeDasharray:`${m.len} ${d-m.len}`,strokeDashoffset:-m.offset},x))]}),(a||r)&&s.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-center",children:[s.jsx("div",{className:"text-headline-md tabular-nums text-text-primary",children:a}),r&&s.jsx("div",{className:"text-body-xs uppercase tracking-wider text-text-tertiary",children:r})]})]}),i&&s.jsx("div",{className:"flex min-w-0 flex-col gap-[7px]",children:f.map((m,x)=>s.jsxs("div",{className:"flex items-center gap-2 text-body-sm",children:[s.jsx("span",{className:"h-2 w-2 shrink-0 rounded-xs",style:{background:m.color}}),s.jsx("span",{className:"min-w-0 flex-1 whitespace-nowrap text-text-body",children:m.label}),s.jsxs("span",{className:"tabular-nums font-medium text-text-primary",children:[Math.round(m.value/c*100),"%"]})]},x))})]})}const VDe={submitted:"Booked",booked:"Booked",booking:"Bookingâ¦","collection-assigned":"Collection booked","collection-unassigned":"Collection booked","collection-rejected":"Collection booked","collection-exception":"Collection issue","collection-failed-attempt":"Collection missed",collected:"Collected","awaiting-dropoff":"Awaiting drop-off","at-hub":"In transit","on-hold":"On hold","on-hold-internal":"In transit","returned-to-hub":"Returned to hub",manifested:"In transit","ready-for-dispatch":"In transit","in-transit":"In transit","at-destination-hub":"Near destination","delivery-assigned":"Out for delivery","delivery-unassigned":"Out for delivery","delivery-rejected":"Out for delivery","out-for-delivery":"Out for delivery","delivery-exception":"Delivery issue","delivery-failed-attempt":"Delivery missed","ready-for-pickup":"Ready for pickup",delivered:"Delivered","returned-to-sender":"Returned",undeliverable:"Undeliverable",cancelled:"Cancelled",failed:"Booking failed","floor-check":"At hub"};function rf(e){if(!e)return null;const t=String(e).toLowerCase();return VDe[t]??String(e).replace(/-/g," ")}const xM=[7,14,30];function a3(e){return`/market-explorer?tab=keywords&mode=search&q=${encodeURIComponent(e)}`}function qDe(e){return`/market-explorer?tab=keywords&mode=expand&q=${encodeURIComponent(e)}`}function Ql(e){return e==null||Number.isNaN(e)?"â":Number.isInteger(e)?String(e):e.toFixed(1)}function fv(e){return e==null?"â":`#${e}`}function GDe(e){if(e==null||Number.isNaN(e)||e===0)return null;const t=e>0?"+":"",n=Number.isInteger(e)?String(e):e.toFixed(1);return`${t}${n}`}function RS(e){switch(e){case"improved":return"Improved rank";case"declined":return"Declined rank";case"newly_visible":return"Newly visible";case"lost_coverage":return"Lost coverage";default:return"Unchanged"}}function sf({delta:e,className:t}){const n=GDe(e);if(n==null)return s.jsx("span",{className:"text-text-tertiary",children:"â"});const r=(e??0)>0,a=(e??0)<0;return s.jsxs("span",{className:B("inline-flex items-center gap-0.5 tabular-nums text-xs font-medium",r&&"text-text-success",a&&"text-text-error",!r&&!a&&"text-text-tertiary",t),children:[r?s.jsx(d6,{className:"h-3 w-3"}):a?s.jsx(XY,{className:"h-3 w-3"}):s.jsx(Hv,{className:"h-3 w-3"}),n]})}function DS({score:e,delta:t}){return s.jsxs("span",{className:"inline-flex flex-col items-end leading-tight",children:[s.jsx("span",{className:"tabular-nums text-text-primary",children:Ql(e)}),s.jsx(sf,{delta:t})]})}const YDe={normal:"bg-intent-brand",caution:"bg-intent-warning",alarm:"bg-intent-errorHover"};function ZDe(e){const t=(e==null?void 0:e.summary.declining_organic)??0,n=(e==null?void 0:e.summary.gaining_organic)??0;return t>=3&&t>n*2?"alarm":t>0&&t>=n?"caution":"normal"}function XDe({slug:e,data:t,className:n}){const r=`/sellers/${e}/inventory?tab=search-visibility`,a=ZDe(t),i=(t==null?void 0:t.summary.products_with_organic)??0,o=(t==null?void 0:t.summary.declining_organic)??0,l=(t==null?void 0:t.summary.gaining_organic)??0,c=[...((t==null?void 0:t.losers)??[]).map(u=>({...u,kind:"down"})),...((t==null?void 0:t.gainers)??[]).map(u=>({...u,kind:"up"}))].slice(0,6);return s.jsxs(V,{padding:"none",className:B("flex flex-col break-inside-avoid p-[18px]",n),children:[s.jsxs("div",{className:"mb-3.5 flex items-center gap-2",children:[s.jsx("span",{className:B("h-1.5 w-1.5 shrink-0 rounded-full",YDe[a])}),s.jsx("span",{className:"text-body-sm font-semibold text-text-primary",children:"Search visibility"}),s.jsx("span",{className:"ml-auto min-w-0 truncate text-body-xs text-text-tertiary",children:"7 days"})]}),s.jsx("div",{className:"flex flex-1 flex-col",children:t===void 0?s.jsxs("div",{className:"space-y-2",role:"status","aria-label":"Loading search ranks",children:[s.jsx(Ta,{variant:"text",className:"h-7 w-24"}),s.jsx(Ta,{variant:"row",className:"w-2/3"}),s.jsx(Ta,{variant:"row",className:"w-1/2"})]}):!t||i===0?s.jsx("div",{className:"py-2 text-body-xs text-text-secondary",children:"No keyword history yet. Nightly rank capture fills scores for tracked search terms."}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-1.5",children:[s.jsx("span",{className:"text-[26px] font-bold leading-8 tabular-nums text-text-primary",children:de(o)}),s.jsx("span",{className:"text-body-xs text-text-secondary",children:"losing"}),s.jsx("span",{className:"text-body-xs text-text-tertiary",children:"·"}),s.jsx("span",{className:"text-[26px] font-bold leading-8 tabular-nums text-text-primary",children:de(l)}),s.jsx("span",{className:"text-body-xs text-text-secondary",children:"gaining"})]}),s.jsxs("div",{className:"mt-0.5 text-body-xs text-text-secondary",children:[de(i)," listing",i===1?"":"s"," with search history"]})]}),c.length>0&&s.jsx("div",{className:"mt-3.5 space-y-2",children:c.map(u=>s.jsxs("div",{className:"flex items-baseline justify-between gap-3 text-body-xs",children:[s.jsx("span",{className:"min-w-0 truncate text-text-primary",children:u.title||u.sku}),s.jsxs("span",{className:"inline-flex shrink-0 items-baseline gap-1.5 tabular-nums",children:[s.jsx("span",{className:"font-semibold text-text-primary",children:Ql(u.score)}),s.jsx(sf,{delta:u.delta})]})]},`${u.kind}-${u.sku}`))})]})}),s.jsxs(st,{to:r,className:"mt-3.5 inline-flex items-center gap-1.5 self-start text-body-xs font-semibold text-text-brand hover:text-text-brand print:hidden",children:[s.jsx(Si,{className:"h-3 w-3"})," Open search visibility"]})]})}function JDe(e){if(!(e!=null&&e.reviews))return"â";
878const t=e.reviews.count.toLocaleString(),n=e.reviews.delta_7d;if(n==null||n===0)return t;const r=n>0?"+":"â";return`${t} · ${r}${Math.abs(n).toLocaleString()} this week`}function QDe(e){const n=((e==null?void 0:e.product_peers)??[]).map(i=>i.display_name).filter(i=>!!i);if(n.length===0)return null;const r=n.slice(0,3),a=n.length-r.length;return a>0?`${r.join(", ")} +${a}`:r.join(", ")}function eMe(e,t){const n=e==null?void 0:e.revenue_per_review,r=QDe(e);return[{label:"Marketplace rank",value:e!=null&&e.rank?`#${e.rank.position.toLocaleString()}`:"â"},{label:"Reviews",value:JDe(e)},{label:"Seller score",value:(e==null?void 0:e.score)!=null?e.score.toFixed(2):"â"},{label:"Your sales per review",value:(n==null?void 0:n.own)!=null?ge(n.own):"â"},{label:"Stores like yours",value:(n==null?void 0:n.band_p25)!=null&&n.band_p75!=null?`${ge(n.band_p25)} â ${ge(n.band_p75)}`:"â"},...r?[{label:"Also on your products",value:r}]:[],{label:"Page views (30d)",value:t?de(t.page_views):"â"},{label:"Conversion (30d)",value:(t==null?void 0:t.avg_conversion_pct)!=null?`${t.avg_conversion_pct.toFixed(2)}%`:"â"}]}function xm({title:e,children:t}){return s.jsxs("section",{className:"flex flex-col gap-3.5",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("h3",{className:"text-body-md font-semibold text-text-primary",children:e}),s.jsx("div",{className:"h-px flex-1 bg-outline-subtle"})]}),s.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5",children:t})]})}function Kr({className:e,tall:t=!1}){return s.jsxs(V,{padding:"none",className:`flex flex-col break-inside-avoid p-[18px] ${e??""}`,children:[s.jsxs("div",{className:"mb-3.5 flex items-center gap-2",children:[s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-outline-subtle"}),s.jsx(Ta,{variant:"text",className:"w-28"})]}),s.jsx(Ta,{variant:"text",className:"h-7 w-24"}),s.jsx(Ta,{variant:"row",className:"mt-3 w-3/4"}),t&&s.jsx(Ta,{variant:"block",className:"mt-4 h-24 border-0"})]})}function tMe(){return s.jsxs(V,{padding:"none",className:"p-3.5",children:[s.jsx(Ta,{variant:"text",className:"w-20"}),s.jsx(Ta,{variant:"text",className:"mt-2 h-6 w-16"}),s.jsx(Ta,{variant:"row",className:"mt-2 w-12"})]})}function gM({rollup:e=!1,amazon:t=!1,variant:n="full"}){const r=n==="rest"?"Loading more overview widgets":"Loading dashboard";return s.jsxs("div",{className:"space-y-7",role:"status","aria-live":"polite","aria-busy":"true","aria-label":r,children:[s.jsxs("span",{className:"sr-only",children:[r,"â¦"]}),n==="full"&&s.jsxs(s.Fragment,{children:[!e&&s.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6",children:Array.from({length:t?5:6},(a,i)=>s.jsx(tMe,{},i))}),s.jsxs(xm,{title:"Sales & money",children:[s.jsx(Kr,{}),s.jsx(Kr,{}),s.jsx(Kr,{}),s.jsx(Kr,{}),s.jsx(Kr,{className:"col-span-full",tall:!0}),s.jsx(Kr,{className:"col-span-full",tall:!0})]})]}),!e&&!t&&s.jsxs(xm,{title:"Ads",children:[s.jsx(Kr,{className:"sm:col-span-2"}),s.jsx(Kr,{}),s.jsx(Kr,{})]}),s.jsxs(xm,{title:"Progress",children:[s.jsx(Kr,{className:"col-span-full"}),s.jsx(Kr,{className:"sm:col-span-2",tall:!0}),s.jsx(Kr,{className:"sm:col-span-2",tall:!0})]}),s.jsxs(xm,{title:t?"Inventory":"Buybox & inventory",children:[!t&&s.jsx(Kr,{}),!t&&s.jsx(Kr,{}),s.jsx(Kr,{}),s.jsx(Kr,{}),s.jsx(Kr,{})]}),s.jsxs(xm,{title:"Returns",children:[s.jsx(Kr,{className:"sm:col-span-2"}),s.jsx(Kr,{}),s.jsx(Kr,{})]})]})}function nMe({sellerName:e,offers:t,revenue90d:n,units90d:r}){return s.jsx(V,{padding:"lg",children:s.jsxs("div",{className:"flex flex-col items-center gap-4 py-6 text-center",children:[s.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-surface-brandSubtle",children:s.jsx(Si,{className:"h-6 w-6 text-text-brand"})}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-body-lg font-semibold text-text-primary",children:[e," is connected"]}),s.jsx("div",{className:"mx-auto mt-1.5 max-w-md text-body-sm text-text-secondary",children:"Takealot has no offers and no sales on this store yet, so there is nothing to chart. This overview is up to date. It fills in on its own once listings and orders exist."})]}),s.jsxs("div",{className:"grid w-full max-w-lg grid-cols-3 gap-3",children:[s.jsx(pk,{label:"Offers",value:de(t)}),s.jsx(pk,{label:"Revenue (90 days)",value:ge(n)}),s.jsx(pk,{label:"Units (90 days)",value:de(r)})]})]})})}function pk({label:e,value:t}){return s.jsxs("div",{className:"rounded-md border border-outline-subtle bg-surface px-3 py-3",children:[s.jsx("div",{className:"text-body-xs text-text-tertiary",children:e}),s.jsx("div",{className:"mt-1 text-body-lg font-semibold tabular-nums text-text-primary",children:t})]})}const rMe="__overviewPrintReady";function sMe(){typeof window<"u"&&(window[rMe]=!0)}function aMe(e){return Object.keys(e).length>=20}function iMe(e,t,n){const[r,a]=p.useState(null),[i,o]=p.useState(!1),[l,c]=p.useState(null),[u,d]=p.useState(null),[h,f]=p.useState(void 0),[m,x]=p.useState(void 0);return p.useEffect(()=>{let g=!1,y=!1,b=!1;a(null),o(!1),c(null),d(null),f(t||n?null:void 0),x(t||n?null:void 0),Wc()||K.overviewTelemetry(e,"view");const v=k=>{g||(y=!0,a(k),o(!0))},w=(k,j=0)=>
878{if(g||y)return;if(((k==null?void 0:k.status)===429||(k==null?void 0:k.code)==="rate_limit_exceeded")&&j===0){window.setTimeout(()=>{g||y||K.overviewScoreboard(e).then(v).catch(E=>w(E,1))},1500);return}b?o(!0):c(String((k==null?void 0:k.message)??k))};Wc()||K.overviewScoreboard(e,{wave:"priority"}).then(k=>{if(!(g||y)){if(aMe(k)){v(k);return}b=!0,a(k)}}).catch(()=>{}),K.overviewScoreboard(e).then(v).catch(w);const _=(k,j,N=0)=>{k().then(E=>{g||j(E)}).catch(E=>{if(((E==null?void 0:E.status)===429||(E==null?void 0:E.code)==="rate_limit_exceeded")&&N===0){window.setTimeout(()=>{g||_(k,j,1)},1500);return}g||j(null)})};return!t&&!n&&(_(()=>K.overviewStorefrontHealth(e),d),_(()=>K.overviewAdsSnapshot(e),f),_(()=>K.searchVisibilityOverview(e),x)),()=>{g=!0}},[e,t,n]),p.useEffect(()=>{Wc()&&(r!==null||l!==null)&&sMe()},[r,l]),{data:r,complete:i,error:l,health:u,ads:h,visibility:m}}const Es=p.createContext({ask:()=>{},sellerName:"",slug:"",actionsEnabled:!0,amazon:!1});function oMe(e){return!!(e&&/^amazon/i.test(e))}function $H({slug:e,sellerName:t=e,rollup:n=!1,marketplace:r=null}){var w,_,k,j,N,E,A,C,T;const a=oMe(r),{data:i,complete:o,error:l,health:c,ads:u,visibility:d}=iMe(e,n,a),h=jf(),f=Wc()?()=>{}:S=>h(S,e);if(l)return s.jsxs(V,{padding:"md",className:"text-body-sm text-text-error",children:["Couldn't load the dashboard: ",l]});if(!i)return Wc()?s.jsxs("div",{className:"flex items-center gap-2 text-body-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Loading dashboardâ¦"]}):s.jsx(gM,{rollup:n,amazon:a});const m=(w=i.kpi)==null?void 0:w.periods.find(S=>S.key==="90d"),x=!m||m.units===0&&m.revenue===0,g=!((_=i.catalogue)!=null&&_.buyability)||i.catalogue.buyability.total===0;if(o&&!n&&x&&g)return s.jsx(nMe,{sellerName:t,offers:((j=(k=i.catalogue)==null?void 0:k.buyability)==null?void 0:j.total)??0,revenue90d:(m==null?void 0:m.revenue)??0,units90d:(m==null?void 0:m.units)??0});const y=!!((E=(N=i.progress)==null?void 0:N.comparisons)!=null&&E.length||(C=(A=i.progress)==null?void 0:A.series)!=null&&C.some(S=>S.buyable!=null||S.excellent_pct!=null||S.return_rate_30d!=null)),b=!!(i.courier&&(i.courier.open_count>0||i.courier.delivered_30d>0||i.courier.recent.length)),v=!!((T=i.catalogue)!=null&&T.quality&&i.catalogue.quality.total>0);return s.jsx(Es.Provider,{value:{ask:f,sellerName:t,slug:e,actionsEnabled:!n,amazon:a},children:s.jsxs("div",{className:"space-y-7",children:[!n&&s.jsx(dMe,{data:i}),s.jsxs(Ml,{title:"Sales & money",children:[s.jsx(gMe,{balance:i.balance,progress:i.progress}),s.jsx(yMe,{data:i}),s.jsx(bMe,{profit:i.profit}),s.jsx(vMe,{ob:i.orders_by_hour}),s.jsx(wMe,{kpi:i.kpi,className:"col-span-full"}),s.jsx(kMe,{daily:i.daily_sales,className:"col-span-full"})]}),o?s.jsxs(s.Fragment,{children:[!n&&!a&&s.jsx(hMe,{slug:e,ads:u}),(!a||y)&&s.jsxs(Ml,{title:"Progress",children:[s.jsx(SMe,{progress:i.progress,className:"col-span-full"}),s.jsx(CMe,{progress:i.progress,className:"sm:col-span-2"}),s.jsx(EMe,{progress:i.progress,className:"sm:col-span-2"})]}),s.jsxs(Ml,{title:a?"Inventory":"Buybox & inventory",children:[!a&&s.jsx(AMe,{repricer:i.repricer}),!a&&s.jsx(TMe,{repricer:i.repricer}),s.jsx(OMe,{inventory:i.inventory}),s.jsx(PMe,{progress:i.progress,inventory:i.inventory}),s.jsx(RMe,{inventory:i.inventory})]}),s.jsxs(Ml,{title:"Returns",children:[s.jsx(DMe,{returns:i.returns,kpi:i.kpi,progress:i.progress,className:"sm:col-span-2"}),s.jsx(MMe,{returns:i.returns}),s.jsx($Me,{dmg:i.damage_in_transit}),(!a||b)&&s.jsx(XMe,{courier:i.courier})]}),s.jsxs(Ml,{title:a?"Catalogue & products":"Catalogue, storefront & products",children:[!n&&!a&&s.jsx(LMe,{health:c,engagement:i.engagement}),s.jsx(FMe,{catalogue:i.catalogue,progress:i.progress}),(!a||v)&&s.jsx(BMe,{catalogue:i.catalogue,progress:i.progress}),!a&&s.jsx(UMe,{cl:i.conversion_leaks}),!n&&!a&&s.jsx(XDe,{slug:e,data:d}),s.jsx(zMe,{tp:i.top_products,className:"sm:col-span-2"}),s.jsx(WMe,{wa:i.warehouse_alerts,className:"sm:col-span-2"}),s.jsx(KMe,{alerts:i.alerts,className:"sm:col-span-2"})]}),s.jsxs(Ml,{title:"Momentum, cash & logistics",children:[s.jsx(HMe,{movers:i.movers,className:"sm:col-span-2"}),s.jsx(VMe,{fs:i.fee_shift}),s.jsx(qMe,{cf:i.cash_flow}),s.jsx(GMe,{dts:i.days_to_stockout}),s.jsx(YMe,{os:i.overstock}),s.jsx(ZMe,{inb:i.inbound,className:"sm:col-span-2"})]})]}):s.jsx(gM,{variant:"rest",rollup:n,amazon:a})]})})}function Ml({title:e,children:t}){return s.jsxs("section",{className:"flex flex-col gap-3.5",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("h3",{className:"text-body-md font-semibold text-text-primary",children:e}),s.jsx("div",{className:"h-px flex-1 bg-outline-subtle"})]}),s.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-5",children:t})]})}const lMe={normal:"bg-intent-brand",caution:"bg-intent-warning",alarm:"bg-intent-errorHover"};function xt({title:e,meta:t,tone:n="normal",children:r,className:a,action:i}){const{ask:o,actionsEnabled:l}=p.useContext(Es);return s.jsxs(V,{padding:"none",className:B("flex flex-col break-inside-avoid p-[18px]",a),children:[s.jsxs("div",{className:"mb-3.5 flex items-center gap-2",children:[s.jsx("span",{className:B("h-1.5 w-1.5 shrink-0 rounded-full",lMe[n])}),s.jsx("span",{className:"text-body-sm font-semibold text-text-primary",children:e}),t&&s.jsx("span",{className:"ml-auto min-w-0 truncate text-body-xs text-text-tertiary",children:t})]}),s.jsx("div",{className:"flex flex-1 flex-col",children:r}),l&&i&&(i.href?s.jsxs(st,{to:i.href,className:"mt-3.5 inline-flex items-center gap-1.5 self-start text-body-xs font-semibold text-text-brand hover:text-text-brand print:hidden",children:[s.jsx(Si,{className:"h-3 w-3"})," ",i.label]}):i.prompt?s.jsxs("button",{type:"button",onClick:()=>o(i.prompt),className:"mt-3.5 inline-flex items-center gap-1.5 self-start text-body-xs font-semibold text-text-brand hover:text-text-brand print:hidden",children:[s.jsx(Rd,{className:"h-3 w-3"})," ",i.label]}):null)]})}function qt({children:e="No data yet"}){return s.jsx("div",{className:"py-2 text-body-xs text-text-secondary",children:e})}function ci({value:e,caption:t,inlineCaption:n,tone:r}){return s.jsxs("div",{children:[s.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-1.5",children:[s.jsx("span",{className:B("text-[26px] font-bold leading-8 tabular-nums text-text-primary",r),children:e}),n&&t&&s.jsx("span",{className:"text-body-xs text-text-secondary",children:t})]}),!n&&t&&s.jsx("div",{className:"mt-0.5 text-body-xs text-text-secondary",children:t})]})}function ua({label:e,value:t,valueClass:n}){return s.jsxs("div",{className:"flex items-baseline justify-between gap-3 text-body-xs",children:[s.jsx("span",{className:"min-w-0 truncate text-text-secondary",children:e}),s.jsx("span",{className:B("shrink-0 font-semibold tabular-nums text-text-primary",n),children:t})]})}function mv(e,t){return e==null?void 0:e.periods.find(n=>n.key===t)}const cMe=60,uMe=-40;function md({pct:e,suffix:t,invert:n}){if(e==null)return null;const r=e>=0,a=n?!r:r,i=e>=cMe||e<=uMe;
878return s.jsxs("span",{title:i?"Unusual vs your prior period":void 0,className:["inline-flex items-center gap-[3px] text-body-xs font-semibold",a?"text-text-success":"text-text-error",i?`rounded px-1 ${a?"bg-surface-successSubtle":"bg-surface-errorSubtle"}`:""].join(" "),children:[r?s.jsx(Xi,{className:"h-3 w-3"}):s.jsx(ax,{className:"h-3 w-3"}),r?"+":"",e.toFixed(1),"%",t?` ${t}`:"",i&&s.jsx("span",{className:"ml-0.5 font-bold",children:"!"})]})}function dMe({data:e}){var h,f,m;const{amazon:t}=p.useContext(Es),n=mv(e.kpi,"today"),r=mv(e.kpi,"30d"),a=r&&r.units>0?r.returns/r.units*100:null,i=e.alerts?[e.alerts.returns_over_5pct,e.alerts.sales_no_stock,e.alerts.fee_drag_skus,e.alerts.catalog_stale?1:0]:null,o=i?i.reduce((x,g)=>x+g,0):null,l=i?i.filter(x=>x>0).length:0,c=((h=e.repricer)==null?void 0:h.buybox_pct)??null,u=(f=FH(e.progress,"return_rate_30d"))==null?void 0:f.delta_pct,d=[{label:"Today's revenue",value:n?ge(n.revenue):"â",foot:s.jsx(md,{pct:(n==null?void 0:n.revenue_delta_pct)??null})},{label:"In-flight orders",value:e.in_flight?de(e.in_flight.line_items):"â",foot:s.jsx("span",{className:"text-text-tertiary",children:"line items"})},...t?[]:[{label:"Buybox rate",value:c!=null?`${c.toFixed(1)}%`:"â",foot:c!=null?s.jsx("div",{className:"h-1 overflow-hidden rounded-full",style:{background:et.track},children:s.jsx("div",{className:"h-full rounded-full",style:{width:`${Math.min(100,c)}%`,background:et.primary}})}):null}],{label:"Needs attention",value:o!=null?de(o):"â",valueClass:o?"text-text-error":void 0,foot:s.jsxs("span",{className:"text-text-tertiary",children:["across ",l," check",l===1?"":"s"]})},{label:"Return rate (30d)",value:a!=null?`${a.toFixed(1)}%`:"â",foot:u!=null&&Math.abs(u)>=.05?s.jsx(zf,{progress:e.progress,metricKey:"return_rate_30d"}):s.jsx("span",{className:"text-text-tertiary",children:r?`${de(r.returns)} units`:""})},{label:"Net margin (30d)",value:((m=e.profit)==null?void 0:m.margin_pct)!=null?`${e.profit.margin_pct.toFixed(1)}%`:"â",foot:s.jsx("span",{className:"text-text-tertiary",children:"after fees"})}];return s.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6",children:d.map(x=>s.jsxs(V,{padding:"none",className:"p-3.5",children:[s.jsx("div",{className:"truncate text-body-xs text-text-secondary",children:x.label}),s.jsx("div",{className:B("mt-1.5 text-[22px] font-bold leading-7 tabular-nums text-text-primary",x.valueClass),children:x.value}),s.jsx("div",{className:"mt-0.5 text-body-xs",children:x.foot})]},x.label))})}function MS(e){const t=typeof e=="string"?Number(e):typeof e=="number"?e:0;return Number.isFinite(t)?t:0}function pv(e){if(e==null||e==="")return null;const t=typeof e=="string"?Number(e):typeof e=="number"?e:NaN;return Number.isFinite(t)?t:null}function xk(e){return MS(e)/100}function yM(e){const t=pv(e);return t!=null&&t>0?`${t.toFixed(1)}Ã`:"â"}function gk(e,t){const n=pv(e),r=pv(t);return n==null||r==null||r===0?null:(n-r)/Math.abs(r)*100}function hMe({slug:e,ads:t}){return t===null?null:t===void 0?s.jsx(Ml,{title:"Ads",children:s.jsx(xt,{title:"Sponsored Ads",meta:"last 30 days",className:"sm:col-span-2",children:s.jsxs("div",{className:"space-y-2",role:"status","aria-label":"Loading ads",children:[s.jsx(Ta,{variant:"text",className:"h-7 w-24"}),s.jsx(Ta,{variant:"row",className:"w-2/3"}),s.jsx(Ta,{variant:"block",className:"h-16 border-0"})]})})}):t.data_present?s.jsxs(Ml,{title:"Ads",children:[s.jsx(fMe,{slug:e,ads:t,className:"sm:col-span-2"}),s.jsx(mMe,{slug:e,ads:t}),s.jsx(pMe,{ads:t})]}):s.jsx(Ml,{title:"Ads",children:s.jsx(xt,{title:"Sponsored Ads",meta:"last 30 days",className:"sm:col-span-2",children:s.jsxs(qt,{children:["No ad spend in the last ",t.window_days," days."," ",s.jsx(st,{to:`/ads/${e}`,className:"font-semibold text-text-brand hover:text-text-brand print:hidden",children:"Open Ads"})," ","to upload a portal export or connect Osmos."]})})})}function fMe({slug:e,ads:t,className:n}){const r=t.totals,a=t.prior,i=(t.series??[]).map(c=>xk(c.spend_cents)),o=pv(r.roas),l=[{label:"Ad spend",value:ge(xk(r.spend_cents)),foot:s.jsx(md,{pct:gk(r.spend_cents,a==null?void 0:a.spend_cents),invert:!0})},{label:"Ad revenue",value:ge(xk(r.revenue_cents)),foot:s.jsx(md,{pct:gk(r.revenue_cents,a==null?void 0:a.revenue_cents)})},{label:"Blended ROAS",value:yM(r.roas),valueClass:o!=null&&o<2?"text-text-error":o!=null&&o>=3?"text-text-success":void 0,foot:r.direct_roas?s.jsxs("span",{className:"text-text-tertiary",children:["direct ",yM(r.direct_roas)]}):s.jsx(md,{pct:gk(r.roas,a==null?void 0:a.roas)})},{label:"Orders",value:de(MS(r.orders)),foot:s.jsxs("span",{className:"text-text-tertiary",children:[de(MS(r.clicks))," clicks"]})}];return s.jsxs(xt,{title:"Sponsored Ads",meta:`${t.window_days}d vs prior`,className:n,children:[s.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-3",children:l.map(c=>s.jsxs("div",{children:[s.jsx("div",{className:"truncate text-body-xs text-text-secondary",children:c.label}),s.jsx("div",{className:B("mt-0.5 text-[22px] font-bold leading-7 tabular-nums text-text-primary",c.valueClass),children:c.value}),s.jsx("div",{className:"mt-0.5 text-body-xs",children:c.foot})]},c.label))}),i.length>=2&&s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-tertiary",children:["Spend · ",t.window_days,"d"]}),s.jsx(s3,{data:i,height:40,area:!1})]}),s.jsx(st,{to:`/ads/${e}`,className:"mt-3 inline-block text-body-xs font-semibold text-text-brand hover:text-text-brand print:hidden",children:"Open Ads"})]})}function mMe({slug:e,ads:t}){const{sellerName:n}=p.useContext(Es),r=t.alerts??[],a=t.reallocation,o=r.some(l=>l.severity==="high")?"alarm":r.length?"caution":"normal";return s.jsx(xt,{title:"Ad issues",meta:r.length?`${r.length} this window`:"All clear",tone:o,action:r.length?{label:"What's wasting ad spend?",prompt:`Based on ${n}'s ads alerts, what should I pause, cap, or fix this week? Open Ads â Performance for the tables.`}:void 0,children:r.length===0&&!a?s.jsxs(qt,{children:["No ads alerts in the last ",t.window_days," days."]}):s.jsxs("div",{className:"space-y-2.5",children:[r.map((l,c)=>s.jsxs("div",{className:"text-body-xs",children:[s.jsx("div",{className:l.severity==="high"?"font-semibold text-text-error":"font-semibold text-text-primary",children:l.title}),l.detail?s.jsx("div",{className:"mt-0.5 text-text-secondary",children:l.detail}):null]},`${l.kind}-${c}`)),a!=null&&a.rationale?s.jsx("div",{className:"text-body-xs text-text-secondary",children:a.rationale}):null,s.jsx(st,{to:`/ads/${e}`,className:"inline-block text-body-xs font-semibold text-text-brand hover:text-text-brand print:hidden",children:"See campaigns and products"})]})})}function pMe({ads:e}){const t=e.budget,n=e.wallet;if(!t&&!n)return null;
878const r=n==null?void 0:n.runway_days,a=r!=null&&r<7||!!(t!=null&&t.hitting_cap);return s.jsx(xt,{title:"Ads wallet",meta:n!=null&&n.snapshot_date?`as of ${n.snapshot_date}`:"Data Insights",tone:a?"caution":"normal",children:s.jsxs("div",{className:"space-y-2.5",children:[(n==null?void 0:n.remaining_balance)!=null&&s.jsx(s.Fragment,{children:s.jsx(ci,{value:ge(n.remaining_balance),caption:r!=null?`~${r} day${r===1?"":"s"} of runway`:"wallet remaining"})}),t&&s.jsx(ua,{label:t.hitting_cap?"Hitting daily cap":"Daily budget",value:ge(t.daily_budget),valueClass:t.hitting_cap?"text-text-warning":void 0}),t&&s.jsx(ua,{label:"Spent vs expected",value:`${ge(t.actual_spend)} / ${ge(t.expected_spend)}`})]})})}function yk(e){return e==null||Number.isNaN(e)?"â":new Intl.NumberFormat("en-ZA",{style:"currency",currency:"ZAR",minimumFractionDigits:2,maximumFractionDigits:2}).format(e)}function zs(e){const[,t,n]=e.split("-").map(Number);return`${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][(t||1)-1]} ${n}`}function LH(e){return e!=null&&e.comparisons.length?e.comparisons.find(t=>t.key==="30d")??e.comparisons[0]:null}function FH(e,t){var n;return((n=LH(e))==null?void 0:n.metrics.find(r=>r.key===t))??null}function xMe(e,t){const n=[];for(const r of(e==null?void 0:e.series)??[]){const a=r[t];typeof a=="number"&&Number.isFinite(a)&&n.push(a)}return n}function zf({progress:e,metricKey:t}){const n=LH(e),r=FH(e,t);return!n||!r||r.delta_pct==null||Math.abs(r.delta_pct)<.05?null:s.jsx(md,{pct:r.delta_pct,invert:r.invert,suffix:`vs ${zs(n.prior_date)}`})}function ww({progress:e,metricKey:t,color:n=et.primary}){const r=xMe(e,t);if(r.length<2)return null;const a=e.series;return s.jsx("div",{className:"mt-auto pt-4",children:s.jsx(s3,{data:r,height:48,area:!1,stroke:n,axis:[zs(a[0].day),zs(a[a.length-1].day)]})})}function gMe({balance:e,progress:t}){const{amazon:n}=p.useContext(Es);if(!e)return s.jsx(xt,{title:"Balance",meta:"Current payout cycle",children:s.jsx(qt,{})});const r=e.live?"Live":e.as_of?`As of ${zs(e.as_of)}`:void 0,a=(e.available>0||e.held_back>0)&&!n;return s.jsxs(xt,{title:"Balance",meta:r,action:{label:"Explain my payout",prompt:n?"Explain my current Amazon settlement balance â what this open payout group is and when it typically deposits.":"Explain my current Takealot balance â how much is available vs held back this payout cycle, and why."},children:[s.jsx(ci,{value:yk(e.current),caption:n?"Open settlement · accruing to next payout":"Total balance · current payout cycle"}),s.jsx("div",{className:"mt-1",children:s.jsx(zf,{progress:t,metricKey:"balance"})}),a&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mt-3.5",children:s.jsx(Kx,{height:8,segments:[{value:e.available,color:et.primary,label:"Available"},{value:e.held_back,color:et.soft,label:"Held back"}]})}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx(ua,{label:s.jsxs(s.Fragment,{children:["Available ",e.available_pct!=null&&s.jsxs("span",{className:"text-text-tertiary",children:["· ",e.available_pct.toFixed(1),"%"]})]}),value:yk(e.available)}),s.jsx(ua,{label:s.jsxs(s.Fragment,{children:["Held back ",e.held_back_pct!=null&&s.jsxs("span",{className:"text-text-tertiary",children:["· ",e.held_back_pct.toFixed(1),"%"]})]}),value:yk(e.held_back)})]})]}),s.jsx(ww,{progress:t,metricKey:"balance"})]})}function yMe({data:e}){var a;const t=mv(e.kpi,"today"),n=((a=e.revenue_spark)==null?void 0:a.days)??[],r=n.map(i=>i.revenue);return s.jsxs(xt,{title:"Revenue today",meta:"14d",children:[s.jsx(ci,{value:t?ge(t.revenue):"â"}),s.jsx("div",{className:"mt-1",children:s.jsx(md,{pct:(t==null?void 0:t.revenue_delta_pct)??null,suffix:"vs yesterday"})}),r.length>=2?s.jsx("div",{className:"mt-auto pt-4",children:s.jsx(s3,{data:r,area:!1,axis:[zs(n[0].day),zs(n[n.length-1].day)]})}):s.jsx(qt,{})]})}const BH=50;function bMe({profit:e}){const{slug:t}=p.useContext(Es);if(!e)return s.jsx(xt,{title:"Net of fees (30d)",children:s.jsx(qt,{})});const n=e.coverage_pct,r=n!=null&&n>=BH&&e.net_profit_covered!=null,a=e.margin_pct;return s.jsxs(xt,{title:"Net of fees (30d)",action:r?void 0:{label:"Add product costs",href:`/sellers/${t}/inventory?tab=catalogue&upload=cogs`},children:[s.jsx(ci,{value:ge(e.net_of_fees),caption:a!=null?`${a.toFixed(1)}% margin after marketplace fees`:"After marketplace fees"}),a!=null&&s.jsx("div",{className:"mt-3.5",children:s.jsx(Kx,{height:8,segments:[{value:Math.max(0,a),color:et.primary,label:"Kept"},{value:Math.max(0,100-a),color:bw,label:"Fees"}]})}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx(ua,{label:"Income",value:ge(e.income)}),s.jsx(ua,{label:"Fees",value:`â${ge(e.fees)}`})]}),s.jsx("div",{className:"mt-3 text-body-xs text-text-secondary",children:r?s.jsxs(s.Fragment,{children:["True profit on costed lines (",n.toFixed(0),"% of GMV): ",s.jsx("span",{className:"font-semibold text-text-primary",children:ge(e.net_profit_c
878overed)})]}):n&&n>0?`${n.toFixed(0)}% of sales have a cost set. Add costs to see true profit after COGS.`:"No product costs set yet. Add costs to see true profit after COGS."})]})}function vMe({ob:e}){if(!e)return s.jsx(xt,{title:"Orders today",meta:"By hour",children:s.jsx(qt,{})});const t=new Map(e.hours.map(i=>[i.hour,i.orders])),r=Array.from({length:16},(i,o)=>o+6).map(i=>t.get(i)??0),a=e.hours.reduce((i,o)=>o.orders>0&&(!i||o.orders>i.orders)?o:i,null);return s.jsxs(xt,{title:"Orders today",meta:"06:00â21:00",children:[s.jsx(ci,{value:de(e.total_orders),caption:`${de(e.total_units)} units${a?` · peak ${String(a.hour).padStart(2,"0")}:00`:""}`}),s.jsx("div",{className:"mt-auto pt-4",children:s.jsx(r3,{data:r,height:64,gap:3,axis:["06:00","21:00"]})})]})}function bM({pct:e}){if(e==null)return null;const t=e>=0;return s.jsxs("span",{className:`ml-1 text-body-xs font-medium tabular-nums ${t?"text-text-success":"text-text-error"}`,children:[t?"+":"â",Math.abs(e).toFixed(1),"%"]})}function wMe({kpi:e,className:t}){const n="Units · Returns · Revenue · Hanging · GP";if(!e)return s.jsx(xt,{title:"Performance",meta:n,className:t,children:s.jsx(qt,{})});const r=e.live?`${n} · units and revenue live from Takealot`:n,a=e.periods,i="border-t border-outline-faint py-[7px]";return s.jsx(xt,{title:"Performance",meta:r,className:t,children:s.jsx("div",{className:"-mx-[18px] overflow-x-auto px-[18px]",children:s.jsxs("table",{className:"w-full min-w-[560px] border-collapse text-body-sm tabular-nums",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"text-body-xs text-text-tertiary",children:[s.jsx("th",{className:"pb-2 text-left font-medium"}),a.map(o=>s.jsx("th",{className:"pb-2 text-right font-medium",children:o.label},o.key))]})}),s.jsxs("tbody",{children:[s.jsxs("tr",{className:"text-right",children:[s.jsx("td",{className:B(i,"text-left text-text-secondary"),children:"Units"}),a.map(o=>s.jsxs("td",{className:B(i,"font-semibold text-text-primary"),children:[de(o.units),s.jsx(bM,{pct:o.units_delta_pct})]},o.key))]}),s.jsxs("tr",{className:"text-right",children:[s.jsx("td",{className:B(i,"text-left text-text-secondary"),children:"Returns"}),a.map(o=>s.jsx("td",{className:B(i,"text-text-primary"),children:de(o.returns)},o.key))]}),s.jsxs("tr",{className:"text-right",children:[s.jsx("td",{className:B(i,"text-left text-text-secondary"),children:"Revenue"}),a.map(o=>s.jsxs("td",{className:B(i,"font-semibold text-text-primary"),children:[ge(o.revenue),s.jsx(bM,{pct:o.revenue_delta_pct})]},o.key))]}),s.jsxs("tr",{className:"text-right",children:[s.jsx("td",{className:B(i,"text-left text-text-secondary"),children:"Hanging"}),a.map(o=>s.jsx("td",{className:B(i,"text-text-secondary"),children:o.hanging!=null?ge(o.hanging):"â"},o.key))]}),s.jsxs("tr",{className:"text-right",children:[s.jsx("td",{className:B(i,"text-left text-text-secondary"),children:"GP"}),a.map(o=>s.jsx("td",{className:B(i,"text-text-secondary"),children:o.gp!=null?ge(o.gp):"â"},o.key))]})]})]})})})}function _Me(){const e=[{label:"Orders",color:et.primary},{label:"Units",color:et.mid},{label:"Returns",color:et.dangerSoft}];return s.jsxs("span",{className:"inline-flex items-center gap-3.5 text-body-xs text-text-secondary",children:[e.map(t=>s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx("span",{className:"h-2 w-2 rounded-[2px]",style:{background:t.color}}),t.label]},t.label)),s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx("span",{className:"h-0.5 w-2.5",style:{background:et.ink}}),"Revenue"]})]})}function kMe({daily:e,className:t}){const n=(e==null?void 0:e.days)??[];return n.some(a=>a.orders||a.units||a.returns||a.revenue)?s.jsx(xt,{title:"Daily sales",meta:s.jsx(_Me,{}),className:t,action:{label:"Explain the trend",prompt:"Walk me through my last 30 days of daily sales â orders, units, returns and revenue. Call out the notable spikes, dips and any return-rate concerns."},children:s.jsx("div",{style:{height:230},children:s.jsx(li,{width:"100%",height:"100%",children:s.jsxs(Wx,{data:n,margin:{top:6,right:4,bottom:0,left:0},children:[s.jsx(Ma,{stroke:Co,vertical:!1}),s.jsx($a,{dataKey:"day",tickFormatter:zs,tick:{fontSize:10,fill:kr}
878,tickLine:!1,axisLine:{stroke:bw},interval:"preserveStartEnd",minTickGap:20}),s.jsx(zr,{yAxisId:"count",allowDecimals:!1,tick:{fontSize:10,fill:kr},tickLine:!1,axisLine:!1,width:30}),s.jsx(zr,{yAxisId:"rev",orientation:"right",tick:{fontSize:10,fill:kr},tickLine:!1,axisLine:!1,width:46,tickFormatter:a=>ge(Number(a),{compact:!0})}),s.jsx(Da,{cursor:{fill:Nu},content:({active:a,payload:i})=>{if(!a||!(i!=null&&i.length))return null;const o=i[0].payload;return s.jsxs("div",{className:"rounded-md border border-outline-subtle bg-surface px-2.5 py-1.5 text-body-xs shadow-sm",children:[s.jsx("div",{className:"mb-1 font-semibold text-text-primary",children:zs(o.day)}),s.jsxs("div",{className:"space-y-0.5 tabular-nums",children:[s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("span",{style:{color:et.primary},children:"Orders"}),s.jsx("span",{className:"text-text-primary",children:o.orders})]}),s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("span",{style:{color:et.strong},children:"Units"}),s.jsx("span",{className:"text-text-primary",children:o.units})]}),s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("span",{style:{color:et.danger},children:"Returns"}),s.jsx("span",{className:"text-text-primary",children:o.returns})]}),s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("span",{className:"text-text-secondary",children:"Revenue"}),s.jsx("span",{className:"text-text-primary",children:ge(o.revenue)})]})]})]})}}),s.jsx(vo,{yAxisId:"count",dataKey:"orders",name:"Orders",fill:et.primary,radius:[3,3,0,0],isAnimationActive:!1}),s.jsx(vo,{yAxisId:"count",dataKey:"units",name:"Units",fill:et.mid,radius:[3,3,0,0],isAnimationActive:!1}),s.jsx(vo,{yAxisId:"count",dataKey:"returns",name:"Returns",fill:et.dangerSoft,radius:[2,2,0,0],isAnimationActive:!1}),s.jsx(Vi,{yAxisId:"rev",type:"monotone",dataKey:"revenue",name:"Revenue",stroke:et.ink,strokeWidth:1.5,dot:!1,isAnimationActive:!1})]})})})}):s.jsx(xt,{title:"Daily sales",meta:"Last 30 days",className:t,children:s.jsx(qt,{})})}const jMe=["return_rate_30d","buyable","excellent_pct","stock_cover_days","conversion_30d_pct","views_30d"];function NMe(e,t){return t==null?"â":e==="percent"?`${t.toFixed(1)}%`:e==="zar"?ge(t,{compact:!0}):e==="days"?`${Math.round(t)}d`:de(Math.round(t))}function SMe({progress:e,className:t}){if(!e||e.days_captured<2)return s.jsx(xt,{title:"Progress vs last period",meta:"Nightly snapshot",className:t,children:s.jsx(qt,{children:"Trends fill in after a few nightly snapshots. Sales trends above already use live history."})});const n=e.comparisons.find(a=>a.key==="30d")??e.comparisons[0];if(!n)return s.jsx(xt,{title:"Progress vs last period",meta:`${e.days_captured} nights`,className:t,children:s.jsx(qt,{children:"Need two snapshots to compare."})});const r=jMe.map(a=>n.metrics.find(i=>i.key===a)).filter(a=>a!=null);return s.jsx(xt,{title:"Progress vs last period",meta:`${n.label.replace(/^vs /,"")} · as of ${zs(e.as_of??"")}`,className:t,action:{label:"What should I do with this?",prompt:"Using my nightly seller snapshots, walk me through how catalogue health (buyable offers, excellent listings), return rate, stock cover, conversion and page views have changed over 7, 30 and 90 days. Call out what improved, what slipped, and the two actions that would move the numbers most."},children:s.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-6",children:r.map(a=>s.jsxs("div",{children:[s.jsx("div",{className:"truncate text-body-xs text-text-secondary",children:a.label}),s.jsx("div",{className:"mt-1 text-[22px] font-bold leading-7 tabular-nums text-text-primary",children:NMe(a.kind,a.current)}),s.jsx("div",{className:"mt-0.5",children:s.jsx(md,{pct:a.delta_pct,invert:a.invert,suffix:`vs ${zs(n.prior_date)}`})})]},a.key))})})}function CMe({progress:e,className:t}){const n=(e==null?void 0:e.series)??[];return n.some(a=>a.buyable!=null||a.excellent_pct!=null)?s.jsx(xt,{title:"Catalogue over time",meta:`${e.days_captured} nights`,className:t,children:s.jsx("div",{style:{height:180},children:s.jsx(li,{width:"100%",height:"100%",children:s.jsxs(Wx,{data:n,margin:{top:6,right:4,bottom:0,left:0},children:[s.jsx(Ma,{stroke:Co,vertical:!1}),s.jsx($a,{dataKey:"day",tickFormatter:zs,tick:{fontSize:10,fill:kr}
878,tickLine:!1,axisLine:{stroke:bw},interval:"preserveStartEnd",minTickGap:24}),s.jsx(zr,{yAxisId:"count",allowDecimals:!1,tick:{fontSize:10,fill:kr},tickLine:!1,axisLine:!1,width:36}),s.jsx(zr,{yAxisId:"pct",orientation:"right",domain:[0,100],tick:{fontSize:10,fill:kr},tickLine:!1,axisLine:!1,width:32,tickFormatter:a=>`${a}%`}),s.jsx(Da,{cursor:{fill:Nu},content:({active:a,payload:i})=>{if(!a||!(i!=null&&i.length))return null;const o=i[0].payload;return s.jsxs("div",{className:"rounded-md border border-outline-subtle bg-surface px-2.5 py-1.5 text-body-xs shadow-sm",children:[s.jsx("div",{className:"mb-1 font-semibold text-text-primary",children:zs(o.day)}),s.jsxs("div",{className:"space-y-0.5 tabular-nums",children:[s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("span",{style:{color:et.primary},children:"Buyable"}),s.jsx("span",{children:o.buyable??"â"})]}),s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("span",{style:{color:et.ink},children:"Excellent"}),s.jsx("span",{children:o.excellent_pct!=null?`${o.excellent_pct.toFixed(1)}%`:"â"})]})]})]})}}),s.jsx(Vi,{yAxisId:"count",type:"monotone",dataKey:"buyable",name:"Buyable",stroke:et.primary,strokeWidth:1.5,dot:!1,isAnimationActive:!1}),s.jsx(Vi,{yAxisId:"pct",type:"monotone",dataKey:"excellent_pct",name:"Excellent %",stroke:et.ink,strokeWidth:1.5,dot:!1,isAnimationActive:!1})]})})})}):s.jsx(xt,{title:"Catalogue over time",meta:"Nightly snapshot",className:t,children:s.jsx(qt,{})})}function EMe({progress:e,className:t}){const n=(e==null?void 0:e.series)??[];return n.some(a=>a.return_rate_30d!=null||a.conversion_30d_pct!=null||a.stock_cover_days!=null)?s.jsx(xt,{title:"Health over time",meta:"Return rate · conversion · cover",className:t,children:s.jsx("div",{style:{height:180},children:s.jsx(li,{width:"100%",height:"100%",children:s.jsxs(Wx,{data:n,margin:{top:6,right:4,bottom:0,left:0},children:[s.jsx(Ma,{stroke:Co,vertical:!1}),s.jsx($a,{dataKey:"day",tickFormatter:zs,tick:{fontSize:10,fill:kr},tickLine:!1,axisLine:{stroke:bw},interval:"preserveStartEnd",minTickGap:24}),s.jsx(zr,{yAxisId:"pct",tick:{fontSize:10,fill:kr},tickLine:!1,axisLine:!1,width:32,tickFormatter:a=>`${a}%`}),s.jsx(zr,{yAxisId:"days",orientation:"right",tick:{fontSize:10,fill:kr},tickLine:!1,axisLine:!1,width:28}),s.jsx(Da,{cursor:{fill:Nu},content:({active:a,payload:i})=>{if(!a||!(i!=null&&i.length))return null;const o=i[0].payload;return s.jsxs("div",{className:"rounded-md border border-outline-subtle bg-surface px-2.5 py-1.5 text-body-xs shadow-sm",children:[s.jsx("div",{className:"mb-1 font-semibold text-text-primary",children:zs(o.day)}),s.jsxs("div",{className:"space-y-0.5 tabular-nums",children:[s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("span",{style:{color:et.danger},children:"Return rate"}),s.jsx("span",{children:o.return_rate_30d!=null?`${o.return_rate_30d.toFixed(1)}%`:"â"})]}),s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("span",{style:{color:et.primary},children:"Conversion"}),s.jsx("span",{children:o.conversion_30d_pct!=null?`${o.conversion_30d_pct.toFixed(1)}%`:"â"})]}),s.jsxs("div",{className:"flex justify-between gap-4",children:[s.jsx("span",{className:"text-text-secondary",children:"Stock cover"}),s.jsx("span",{children:o.stock_cover_days!=null?`${Math.round(o.stock_cover_days)}d`:"â"})]})]})]})}}),s.jsx(Vi,{yAxisId:"pct",type:"monotone",dataKey:"return_rate_30d",name:"Return rate",stroke:et.danger,strokeWidth:1.5,dot:!1,isAnimationActive:!1}),s.jsx(Vi,{yAxisId:"pct",type:"monotone",dataKey:"conversion_30d_pct",name:"Conversion",stroke:et.primary,strokeWidth:1.5,dot:!1,isAnimationActive:!1}),s.jsx(Vi,{yAxisId:"days",type:"monotone",dataKey:"stock_cover_days",name:"Stock cover",stroke:et.ink,strokeWidth:1.5,dot:!1,isAnimationActive:!1})]})})})}):s.jsx(xt,{title:"Health over time",meta:"Nightly snapshot",className:t,children:s.jsx(qt,{})})}function AMe({repricer:e}){if(!e)return s.jsx(xt,{title:"Buybox ownership",children:s.jsx(qt,{})});const t=e.reason_mix,n=e.buybox_pct,r=e.buybox_known,a=n==null?null:r!=null?`of ${de(r)} confirmed listing${r===1?"":"s"}`:"of confirmed listings";return s.jsxs(xt,{title:"Buybox ownership",children:[n==null?s.jsx(qt,{children:"No confirmed buybox reads yet"}):s.jsxs(s.Fragment,{children:[s.jsx(ci,{value:`${n.toFixed(1)}%`,caption:a,inlineCaption:!0}
878),s.jsx("div",{className:"mt-3.5",children:s.jsx(MH,{pct:n})})]}),s.jsxs("div",{className:"mt-3 text-body-xs text-text-secondary",children:[de(e.changes_today)," price change",e.changes_today===1?"":"s"," today"]}),s.jsxs("div",{className:"mt-3 space-y-[7px]",children:[s.jsx(ua,{label:"Compete price",value:de(t.compete_price)}),s.jsx(ua,{label:"Hit min bid",value:de(t.hit_min_bid)}),s.jsx(ua,{label:"Reset to preferred",value:de(t.reset_to_preferred)})]})]})}function TMe({repricer:e}){const{sellerName:t}=p.useContext(Es);if(!e)return s.jsx(xt,{title:"Wasted re-pricers",tone:"alarm",children:s.jsx(qt,{})});const n=e.wasted,r=e.enabled_subs||1;return s.jsxs(xt,{title:"Wasted re-pricers",tone:"alarm",action:n>0?{label:"Fix wasted re-pricers",prompt:`${t} has ${n} re-pricer(s) running on non-buyable SKUs. Show me which ones and how to free up the slots.`}:void 0,children:[s.jsx(ci,{value:de(n),caption:`of ${de(e.enabled_subs)} enabled subs`,inlineCaption:!0}),s.jsx("div",{className:"mt-0.5 text-body-xs text-text-secondary",children:"Active rule on a non-buyable SKU"}),s.jsx("div",{className:"mt-3.5",children:s.jsx(MH,{pct:n/r*100,color:et.danger})})]})}const My={JHB:"Johannesburg",CPT:"Cape Town",DBN:"Durban",FBA:"FBA",FBM:"Merchant fulfilled"};function OMe({inventory:e}){if(!e)return s.jsx(xt,{title:"Inventory coverage",meta:"By location",children:s.jsx(qt,{})});const t=e.health,n=Math.min(...e.dcs.map(r=>r.coverage_pct??0));return s.jsxs(xt,{title:"Inventory coverage",meta:"By location",children:[e.dcs.length?e.dcs.map(r=>{const a=r.coverage_pct??0;return s.jsx(n3,{pct:a,color:e.dcs.length>1&&a===n?et.mid:et.primary,label:My[r.region]??r.region,value:r.coverage_pct!=null?`${Math.round(r.coverage_pct)}%`:"â"},r.region)}):s.jsx(qt,{}),t&&s.jsxs("div",{className:"mt-3.5 flex justify-between border-t border-outline-faint pt-3 text-body-xs text-text-secondary",children:[s.jsxs("span",{children:["Well ",s.jsx("span",{className:"font-semibold text-text-primary",children:de(t.well)})]}),s.jsxs("span",{children:["At risk ",s.jsx("span",{className:"font-semibold text-text-warning",children:de(t.at_risk)})]}),s.jsxs("span",{children:["Critical ",s.jsx("span",{className:"font-semibold text-text-error",children:de(t.critical)})]})]})]})}function IMe({days:e,takealot:t,warehouse:n,showTakealot:r=!0,height:a=48}){const i=Math.min(n.length,e.length,r?t.length:n.length);if(i<2)return null;const o=t.slice(-i),l=n.slice(-i),c=Math.max(...r?o:[],...l,1),u=Math.min(...r?o:[],...l,0),d=c-u||1,h=100,f=100,m=x=>x.map((g,y)=>{const b=i===1?0:y/(i-1)*h,v=f-(g-u)/d*f;return`${b.toFixed(2)},${v.toFixed(2)}`}).join(" ");return s.jsxs("div",{className:"mt-auto pt-4",children:[s.jsxs("svg",{viewBox:`0 0 ${h} ${f}`,preserveAspectRatio:"none",className:"block w-full",style:{height:a},children:[[0,50,100].map(x=>s.jsx("line",{x1:"0",y1:x,x2:h,y2:x,stroke:et.track,strokeWidth:"0.5",vectorEffect:"non-scaling-stroke"},x)),r&&s.jsx("polyline",{points:m(o),fill:"none",stroke:et.primary,strokeWidth:"2",vectorEffect:"non-scaling-stroke",strokeLinecap:"round",strokeLinejoin:"round"}),s.jsx("polyline",{points:m(l),fill:"none",stroke:et.mid,strokeWidth:"2",vectorEffect:"non-scaling-stroke",strokeLinecap:"round",strokeLinejoin:"round"})]}),s.jsxs("div",{className:"mt-2 flex justify-between text-body-xs text-text-tertiary",children:[s.jsx("span",{children:zs(e[e.length-i].day)}),s.jsx("span",{children:zs(e[e.length-1].day)})]}),s.jsxs("div",{className:"mt-1.5 flex gap-3 text-body-xs text-text-secondary",children:[r&&s.jsx(IS,{color:et.primary,children:"Takealot"}),s.jsx(IS,{color:et.mid,children:"Warehouse"})]})]})}function PMe({progress:e,inventory:t}){const{slug:n,amazon:r}=p.useContext(Es),a=(e==null?void 0:e.series)??[],i=(e==null?void 0:e.current_stock)??(a.length?a[a.length-1]:null),o=i==null?void 0:i.stock_value_fba,l=i==null?void 0:i.stock_value_fbm,c=r&&(t!=null&&t.stock_value)&&t.stock_value.total>0?t.stock_value:r&&((o??0)>0||(l??0)>0)?{fba:o??0,fbm:l??0,total:(o??0)+(l??0)}:null;if((!i||i.stock_value==null)&&!c)return s.jsx(xt,{title:"Stock value",meta:"On-hand now",children:s.jsx(qt,{})});const u=(i==null?void 0:i.stock_cost_coverage_pct)??null,d=u!=null&&u>=BH,h=(c==null?void 0:c.total)??(i==null?void 0:i.stock_value)??0,f=(i==null?void 0:i.stock_cost)??null,m=!!(e!=null&&e.current_stock)||!!c,x=a.some(w=>typeof w.stock_value_takealot=="number"&&w.stock_value_takealot>0),g=c?[...c.fba>0?[{key:"fba",label:"FBA",selling:c.fba,cost:null}]:[],...c.fbm>0?[{key:"fbm",label:"Merchant fulfilled",selling:c.fbm,cost:null}]:[],{key:"total",label:"Total",selling:h,cost:f,total:!0}]:[{key:"takealot",label:"Takealot",selling:(i==null?void 0:i.stock_value_takealot)??null,cost:(i==null?void 0:i.stock_cost_takealot)??null,deltaKey:x?"stock_value_takealot":void 0},{key:"jhb",label:My.JHB,selling:(i==null?void 0:i.stock_value_jhb)??null,cost:(i==null?void 0:i.stock_cost_jhb)??null,indent:!0},{key:"cpt",label:My.CPT,selling:(i==null?void 0:i.stock_value_cpt)??null,cost:(i==null?void 0:i.stock_cost_cpt)??null,indent:!0},{key:"dbn",label:My.DBN,selling:(i==null?void 0:i.stock_value_dbn)??null,cost:(i==null?void 0:i.stock_cost_dbn)??null,indent:!0},{key:"warehouse",label:"Warehouse",selling:(i==null?void 0:i.stock_value_warehouse)??null,cost:(i==null?void 0:i.stock_cost_warehouse)??null,deltaKey:"stock_value_warehouse"},{key:"total",label:"Total",selling:h,cost:f,total:!0,deltaKey:"stock_value"}].filter(w=>w.total||w.selling!=null&&w.selling>0||w.cost!=null&&w.cost>0),y=[],b=[],v=[];for(const w of a){const _=w.stock_value_takealot,k=w.stock_value_warehouse;typeof _!="number"&&typeof k!="number"||(y.push(typeof _=="number"&&Number.isFinite(_)?_:0),b.push(typeof k=="number"&&Number.isFinite(k)?k:0),v.push(w))}return s.jsxs(xt,{title:"Stock value",meta:m?"On-hand now":e!=null&&e.as_of?`As of ${zs(e.as_of)}`:"Nightly snapshot",className:"sm:col-span-2",action:h>0&&!d?{label:"Add product costs",href:`/sellers/${n}/inventory?tab=catalogue&upload=cogs`}:void 0,children:[s.jsx("div",{className:"text-body-xs text-text-secondary",children:"Selling incl. VAT · Cost excl. VAT · on-hand now"}),s.jsxs("div",{className:"mt-3 grid grid-cols-[minmax(0,1fr)_auto_auto] gap-x-4 gap-y-1.5 text-body-xs",children:[s.jsx("div",{}),s.jsx("div",{className:"text-right font-semibold text-text-tertiary",children:"Selling"}),s.jsx("div",{className:"text-right font-semibold text-text-tertiary",children:"Cost"}),g.map(w=>s.jsxs("div",{className:"contents",children:[s.jsx("div",{className:B(w.total?"border-t border-outline-faint pt-1.5 font-semibold text-text-primary":"text-text-secondary",w.indent&&"pl-3 text-text-tertiary"),children:w.label}),s.jsxs("div",{className:B("text-right tabular-nums whitespace-nowrap",w.total?"border-t border-outline-faint pt-1.5 font-semibold text-text-primary":"font-semibold text-text-primary"),children:[s.jsx("div",{children:ge(w.selling)}),w.deltaKey&&s.jsx("div",{className:"font-normal",children:s.jsx(zf,{progress:e,metricKey:w.deltaKey})})]}),s.jsx("div",{className:B("text-right tabular-nums whitespace-nowrap",w.total?"border-t border-outline-faint pt-1.5 font-semibold text-text-primary":"font-semibold text-text-primary"),children:ge(w.cost)})]},w.key))]}),s.jsx("div",{className:"mt-3 text-body-xs text-text-secondary",children:h<=0?"N
878o on-hand stock.":d?`Cost covers ${u.toFixed(0)}% of selling value. Uncosted SKUs are omitted from cost.`:u&&u>0?`Cost covers ${u.toFixed(0)}% of selling value â add costs to make this number complete.`:"No product costs set yet. Cost stays blank until unit costs are added."}),s.jsx(IMe,{days:v,takealot:y,warehouse:b,showTakealot:x})]})}function RMe({inventory:e}){const t=e==null?void 0:e.bands;if(!t)return s.jsx(xt,{title:"SOH distribution",children:s.jsx(qt,{})});const n=[{label:"Zero stock",n:t.zero,c:et.danger},{label:"1â10 units",n:t.b1_10,c:et.mid},{label:"11â50 units",n:t.b11_50,c:et.deep},{label:"50+ units",n:t.b50_plus,c:et.dark}];return s.jsxs(xt,{title:"SOH distribution",meta:`${de(t.total)} SKUs`,children:[s.jsx(Kx,{segments:n.map(r=>({value:r.n,color:r.c,label:r.label}))}),s.jsx("div",{className:"mt-3 space-y-2",children:n.map(r=>s.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[s.jsx(IS,{color:r.c,children:r.label}),s.jsx("span",{className:"shrink-0 text-body-xs font-semibold tabular-nums text-text-primary",children:de(r.n)})]},r.label))})]})}function DMe({returns:e,kpi:t,progress:n,className:r}){const{sellerName:a}=p.useContext(Es);if(!e)return s.jsx(xt,{title:"Returns",meta:"Last 30 days",tone:"caution",className:r,children:s.jsx(qt,{})});const i=mv(t,"30d"),o=i&&i.units>0?i.returns/i.units*100:null,l=e.reason_mix.slice(0,4),c=e.units||1,u=[et.primary,et.deep,et.strong,et.soft];return s.jsxs(xt,{title:"Returns",meta:"Last 30 days",tone:"caution",className:r,action:e.units>0?{label:"Deep-dive returns",prompt:`Do a return-reason deep-dive for ${a} over the last 30 days and tell me what to fix.`}:void 0,children:[s.jsxs("div",{className:"flex flex-col gap-6 sm:flex-row",children:[s.jsxs("div",{className:"sm:w-[180px] sm:shrink-0",children:[s.jsx(ci,{value:de(e.units),caption:`units returned${o!=null?` · ${o.toFixed(1)}% rate`:""}`}),s.jsx("div",{className:"mt-1",children:s.jsx(zf,{progress:n,metricKey:"return_rate_30d"})}),s.jsxs("div",{className:"mt-3 text-body-xl font-bold tabular-nums text-text-error",children:["â",ge(e.value_lost)]}),s.jsx("div",{className:"mt-0.5 text-body-xs text-text-secondary",children:"value lost"})]}),s.jsx("div",{className:"min-w-0 flex-1",children:l.length?l.map((d,h)=>s.jsx(n3,{pct:d.units/c*100,color:u[h%u.length],label:d.reason,value:`${de(d.units)} · ${Math.round(d.units/c*100)}%`},d.reason)):s.jsx(qt,{children:"No returns in window"})})]}),s.jsx(ww,{progress:n,metricKey:"return_rate_30d",color:et.danger})]})}function MMe({returns:e}){if(!e||!e.status_mix.length)return s.jsx(xt,{title:"Return status",meta:"Last 30 days",tone:"caution",children:s.jsx(qt,{})});const t=e.status_mix.reduce((r,a)=>r+a.lines,0)||1,n=r=>/sellable/i.test(r)?et.success:/removal|write/i.test(r)?et.warning:/incorrect/i.test(r)?et.danger:et.neutral;return s.jsx(xt,{title:"Return status",meta:"Where returns landed",tone:"caution",children:e.status_mix.slice(0,5).map(r=>s.jsx(n3,{pct:r.lines/t*100,color:n(r.outcome),label:r.outcome,value:`${de(r.lines)} · ${Math.round(r.lines/t*100)}%`},r.outcome))})}function $Me({dmg:e}){const{sellerName:t}=p.useContext(Es);return e?s.jsxs(xt,{title:"Damage in transit",meta:"Last 90 days",tone:"alarm",action:e.damaged_units>0?{label:"Review packaging",prompt:`${t}'s damage-in-transit returns look elevated. Review packaging and show me the worst SKUs.`}:void 0,children:[s.jsx(ci,{value:e.damage_rate_pct!=null?`${e.damage_rate_pct.toFixed(1)}%`:"â",caption:`${de(e.damaged_units)} of ${de(e.total_units)} returned`}),e.top_skus.length>0&&s.jsx("div",{className:"mt-3.5 space-y-2",children:e.top_skus.map(n=>s.jsx(ua,{label:n.sku,value:de(n.damaged)},n.sku))})]}):s.jsx(xt,{title:"Damage in transit",meta:"Last 90 days",tone:"alarm",children:s.jsx(qt,{})})}function LMe({health:e,engagement:t}){const n=eMe(e,t);return s.jsx(xt,{title:"Vital signs",meta:"Storefront health",children:s.jsx("div",{className:"space-y-2.5",children:n.map(r=>s.jsx(ua,{label:r.label,value:r.value},r.label))})})}function FMe({catalogue:e,progress:t}){const{amazon:n}=p.useContext(Es),r=e==null?void 0:e.buyability;if(!r)return s.jsx(xt,{title:"Buyability funnel",children:s.jsx(qt,{})});const a=[{value:r.buyable,color:et.primary,label:"Buyable"},{value:r.not_buyable,color:et.mid,label:"Not buyable"},{value:r.off_by_seller,color:et.neutral,label:"Off (seller)"},{value:r.off_by_takealot,color:et.danger,label:n?"Off (Amazon)":"Off (Takealot)"}];return s.jsxs(xt,{title:"Buyability funnel",meta:`${de(r.total)} offers`,children:[s.jsx(ci,{value:de(r.buyable),caption:"buyable right now",inlineCaption:!0}
878),s.jsx("div",{className:"mt-1",children:s.jsx(zf,{progress:t,metricKey:"buyable"})}),s.jsx("div",{className:"mt-3.5",children:s.jsx(Kx,{segments:a})}),s.jsx("div",{className:"mt-3 space-y-2",children:a.map(i=>s.jsx(ua,{label:i.label,value:de(i.value)},i.label))}),s.jsx(ww,{progress:t,metricKey:"buyable"})]})}function BMe({catalogue:e,progress:t}){const n=e==null?void 0:e.quality;if(!n)return s.jsx(xt,{title:"Listing quality",children:s.jsx(qt,{})});const r=[{value:n.excellent,color:et.primary,label:"Excellent"},{value:n.moderate,color:et.mid,label:"Moderate"},{value:n.poor,color:et.danger,label:"Poor"}];return s.jsxs(xt,{title:"Listing quality",meta:`${de(n.total)} offers`,children:[s.jsx(zf,{progress:t,metricKey:"excellent_pct"}),s.jsx("div",{className:"mt-3.5",children:s.jsx(Kx,{segments:r})}),s.jsx("div",{className:"mt-3 space-y-2",children:r.map(a=>s.jsx(ua,{label:a.label,value:de(a.value)},a.label))}),s.jsx(ww,{progress:t,metricKey:"excellent_pct"})]})}function UMe({cl:e}){const{sellerName:t}=p.useContext(Es);return!e||!e.skus.length?s.jsx(xt,{title:"Conversion leaks",meta:"High views, low CR",tone:"caution",children:s.jsx(qt,{children:"No leaks detected"})}):s.jsx(xt,{title:"Conversion leaks",meta:"High views, low CR",tone:"caution",action:{label:"Audit conversion leaks",prompt:`Run a conversion-leak audit for ${t} â the high-traffic, low-converting SKUs and what's losing the sale. Only recommend listing or price changes the seller can actually make; do not present missing Brand on an unbranded product, low reviews, customer cancellations, or DC stock cover as fixes.`},children:s.jsx("div",{className:"space-y-2",children:e.skus.slice(0,6).map(n=>s.jsxs("div",{className:"flex items-baseline justify-between gap-3 text-body-xs",children:[s.jsx("span",{className:"min-w-0 truncate text-text-primary",children:n.title}),s.jsxs("span",{className:"shrink-0 tabular-nums text-text-secondary",children:[de(n.views)," · ",n.conversion_pct!=null?`${n.conversion_pct.toFixed(1)}%`:"â"]})]},n.sku))})})}function zMe({tp:e,className:t}){if(!e||!e.products.length)return s.jsx(xt,{title:"Top products",meta:"By 30-day sales",className:t,children:s.jsx(qt,{})});const n=Math.max(...e.products.map(r=>r.revenue),1);return s.jsx(xt,{title:"Top products",meta:"By 30-day sales",className:t,children:s.jsx("div",{className:"space-y-3",children:e.products.map(r=>s.jsxs("div",{children:[s.jsxs("div",{className:"mb-1.5 flex items-baseline justify-between gap-3 text-body-xs",children:[s.jsxs("span",{className:"min-w-0 truncate text-text-primary",children:[r.title," ",r.buyable?s.jsxs("span",{className:"text-text-tertiary",children:["· ",de(r.units)," units"]}):s.jsx("span",{className:"text-text-error",children:"· not buyable"})]}),s.jsx("span",{className:"shrink-0 font-semibold tabular-nums text-text-primary",children:ge(r.revenue)})]}),s.jsx("div",{className:"h-1.5 overflow-hidden rounded-full",style:{background:et.track},children:s.jsx("div",{className:"h-full rounded-full",style:{width:`${r.revenue/n*100}%`,background:r.buyable?et.primary:et.mid}})})]},r.sku))})})}function WMe({wa:e,className:t}){const{sellerName:n}=p.useContext(Es);return!e||!e.skus.length?s.jsx(xt,{title:"Warehouse alerts",meta:"Zero stock, still selling",tone:"alarm",className:t,children:s.jsx(qt,{children:"No stockouts on selling SKUs"})}):s.jsx(xt,{title:"Warehouse alerts",meta:"Zero stock, still selling",tone:"alarm",className:t,action:{label:"Plan a restock",prompt:`${n} has ${e.skus.length} active SKU(s) out of stock at Takealot but still selling (e.g. ${e.skus.slice(0,3).map(r=>r.title).join(", ")}). Give me a replen plan and what we're losing.`},children:s.jsx("div",{children:e.skus.map(r=>s.jsxs("div",{className:"flex items-baseline justify-between gap-3 border-t border-outline-faint py-2 text-body-xs",children:[s.jsxs("span",{className:"min-w-0 truncate text-text-primary",children:[r.title," ",s.jsx("span",{className:"text-text-tertiary",children:r.sku})]}),s.jsxs("span",{className:"shrink-0 tabular-nums",children:[s.jsxs("span",{className:"font-semibold text-text-error",children:["SOH ",r.soh]}),s.jsxs("span",{className:"text-text-secondary",children:[" · ",de(r.units_30d)," sold/30d"]})]})]},r.sku))})})}function KMe({alerts:e,className:t}){const{sellerName:n}=p.useContext(Es);if(!e)return s.jsx(xt,{title:"Needs attention",tone:"alarm",className:t,children:s.jsx(qt,{})});const r=[{label:"SKUs with returns over 5%",n:e.returns_over_5pct,suffix:""},{label:"Selling but out of stock",n:e.sales_no_stock,suffix:""},{label:"Storage fee-drag SKUs",n:e.fee_drag_skus,suffix:""},{label:"Catalogue stale",n:e.catalog_stale?e.stale_days??1:0,suffix:e.catalog_stale?" days":""}],a=r.every(i=>!i.n);return s.jsx(xt,{title:"Needs attention",meta:"What to fix",tone:"alarm",className:t,action:a?void 0:{label:"What should I focus on?",prompt:`Based on ${n}'s current alerts, what should ${n} focus on this week?`},children:a?s.jsx(qt,{children:"All clear"}):s.jsx("div",{className:"space-y-2.5",children:r.filter(i=>i.n>0).map(i=>s.jsx(ua,{label:i.label,value:`${de(i.n)}${i.suffix}`},i.label))})})}function HMe({movers:e,className:t}){var a,i;const{sellerName:n}=p.useContext(Es);if(!e)return s.jsx(xt,{title:"Movers",meta:"7d vs prior 7d",className:t,children:s.jsx(qt,{})});const r=({title:o,rows:l,up:c})=>s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`mb-2.5 text-body-xs font-semibold ${c?"text-text-success":"text-text-error"}`,children:o}),l.length?s.jsx("div",{className:"space-y-2",children:l.map(u=>s.jsxs("div",{className:"flex items-baseline justify-between gap-3 text-body-xs",children:[s.jsx("span",{className:"min-w-0 truncate text-text-primary",children:u.title}),s.jsxs("span",{className:`shrink-0 text-body-xs font-semibold tabular-nums ${c?"text-text-success":"text-text-error"}`,children:[c?"+":"â",ge(Math.abs(u.delta))]})]},u.sku))}):s.jsx(qt,{})]});return s.jsx(xt,{title:"Movers",meta:"7d vs prior 7d",className:t,action:(((a=e.fallers[0])==null?void 0:a.delta)??0)<0?{label:"Investigate the fallers",prompt:`Some of ${n}'s SKUs are sliding week-on-week (e.g. ${(i=e.fallers[0])==null?void 0:i.title}). What's driving it and what should I do?`}:void 0,children:s.jsxs("div",{className:"flex flex-col gap-6 sm:flex-row",children:[s.jsx(r,{title:"Risers",rows:e.risers,up:!0}),s.jsx(r,{title:"Fallers",rows:e.fallers,up:!1})]})})}
878function VMe({fs:e}){if(!e)return s.jsx(xt,{title:"Fee shift",meta:"30d vs prior 30d",tone:"caution",children:s.jsx(qt,{})});const t=e.fee_pct_delta_pp,n=t!=null&&t>0;return s.jsxs(xt,{title:"Fee shift",meta:"30d vs prior 30d",tone:"caution",children:[s.jsx(ci,{value:e.fee_pct_current!=null?`${e.fee_pct_current.toFixed(1)}%`:"â",caption:"of GMV goes to fees"}),t!=null&&s.jsxs("div",{className:`mt-3 inline-flex items-center gap-[3px] text-body-xs font-semibold ${n?"text-text-error":"text-text-success"}`,children:[n?s.jsx(Xi,{className:"h-3 w-3"}):s.jsx(ax,{className:"h-3 w-3"}),n?"+":"â",Math.abs(t).toFixed(2),"pp vs prior 30d"]})]})}function qMe({cf:e}){var n,r,a,i;if(!e)return s.jsx(xt,{title:"Cash flow",meta:"Weekly net",children:s.jsx(qt,{})});const t=[...e.weeks].sort((o,l)=>l.weeks_ago-o.weeks_ago);return s.jsxs(xt,{title:"Cash flow",meta:"Weekly net",children:[s.jsx(ci,{value:ge(e.projected_next),caption:"Sales-derived projection"}),s.jsx("div",{className:"mt-auto pt-4",children:s.jsx(r3,{height:56,gap:3,data:t.map(o=>o.net),axis:[((n=t[0])==null?void 0:n.weeks_ago)===0?"now":`â${(r=t[0])==null?void 0:r.weeks_ago}w`,((a=t[t.length-1])==null?void 0:a.weeks_ago)===0?"now":`â${(i=t[t.length-1])==null?void 0:i.weeks_ago}w`]})})]})}function GMe({dts:e}){const{sellerName:t}=p.useContext(Es);if(!e||!e.skus.length)return s.jsx(xt,{title:"Days to stockout",meta:"Soonest first",tone:"alarm",children:s.jsx(qt,{})});const n=r=>r==null?"text-text-body":r<=7?"text-text-error":r<=14?"text-text-warning":"text-text-body";return s.jsx(xt,{title:"Days to stockout",meta:"Soonest first",tone:"alarm",action:{label:"Plan a replen",prompt:`${t} has SKUs about to stock out (e.g. ${e.skus.slice(0,3).map(r=>r.title).join(", ")}). Give me a replenishment plan with quantities.`},children:s.jsx("div",{className:"space-y-2",children:e.skus.slice(0,6).map(r=>s.jsx(ua,{label:r.title,value:r.days==null?"â":`${r.days}d`,valueClass:n(r.days)},r.sku))})})}function YMe({os:e}){const{sellerName:t}=p.useContext(Es);return!e||!e.skus.length?s.jsx(xt,{title:"Overstock / dead stock",meta:">90d cover",children:s.jsx(qt,{children:"No overstock"})}):s.jsx(xt,{title:"Overstock / dead stock",meta:">90d cover",action:{label:"Plan a flush",prompt:`Where is ${t} overstocked? Show the dead stock and a flush plan.`},children:s.jsx("div",{className:"space-y-2",children:e.skus.slice(0,6).map(n=>s.jsx(ua,{label:n.title,value:s.jsxs("span",{className:"font-normal text-text-secondary",children:[n.days_cover==null?"â":`${n.days_cover}d`," · SOH ",de(n.soh)]})},n.sku))})})}function ZMe({inb:e,className:t}){if(!e)return s.jsx(xt,{title:"Inbound shipments",meta:"60d receive rate",className:t,children:s.jsx(qt,{})});const n=e.channel==="fba";return s.jsxs(xt,{title:n?"FBA inbound":"Inbound shipments",meta:n?"in transit vs fulfillable":"60d receive rate",className:t,children:[s.jsx(ci,{value:n?de(e.inbound_units??0):e.receive_rate_pct!=null?`${e.receive_rate_pct.toFixed(0)}%`:"â",caption:n?"units inbound to FBA":"received",inlineCaption:!0}),s.jsx("div",{className:"mt-0.5 text-body-xs text-text-secondary",children:n?`${de(e.fulfillable_units??e.received)} fulfillable · ${de(e.inbound_units??0)} in transit`:`${de(e.received)} of ${de(e.sent)} units`}),s.jsx("div",{className:"mt-3",children:e.recent.length?e.recent.map((r,a)=>s.jsxs("div",{className:"flex items-baseline justify-between gap-3 border-t border-outline-faint py-2 text-body-xs",children:[s.jsx("span",{className:"min-w-0 truncate text-text-secondary",children:r.reference??"â"}),s.jsx("span",{className:B("shrink-0",/received/i.test(r.state??"")?"text-text-success":"text-text-secondary"),children:r.state??"â"})]},`${r.reference}-${a}`)):s.jsx(qt,{children:"No recent shipments"})})]})}function XMe({courier:e}){const{sellerName:t}=p.useContext(Es);return e?s.jsxs(xt,{title:"Courier collections",meta:"Gadjet booked",action:e.open_count>0?{label:"Track these collections",prompt:`Fetch the waybill and live tracking for open courier collections on ${t}.`}:void 0,children:[s.jsx(ci,{value:de(e.open_count),caption:e.open_returns>0?`in transit · ${e.open_returns} DC return${e.open_returns===1?"":"s"}`:"in transit"}),s.jsxs("div",{className:"mt-0.5 text-body-xs text-text-secondary",children:[de(e.delivered_30d)," delivered in 30d"]}
878),s.jsx("div",{className:"mt-3",children:e.recent.length?e.recent.map(n=>s.jsxs("div",{className:"flex items-baseline justify-between gap-3 border-t border-outline-faint py-2 text-body-xs",children:[s.jsxs("span",{className:"min-w-0 truncate font-mono text-text-secondary",children:[n.tracking_reference??"pending",n.lane==="dc_return"?" · return":""]}),s.jsx("span",{className:"shrink-0 text-text-secondary",children:rf(n.status)??n.status??"â"})]},n.id)):s.jsx(qt,{children:"No collections booked yet"})})]}):s.jsx(xt,{title:"Courier collections",meta:"Gadjet booked",children:s.jsx(qt,{})})}function UH(){const{slug:e=""}=jn(),t=Wc(),[n,r]=p.useState(null),[a,i]=p.useState(null),[o,l]=p.useState(!1),[c,u]=p.useState(null);p.useEffect(()=>{let h=!1;i(null),r(null);const f=(m=0)=>{K.seller(e).then(x=>{h||r(x)}).catch(x=>{if(((x==null?void 0:x.status)===429||(x==null?void 0:x.code)==="rate_limit_exceeded")&&m===0){window.setTimeout(()=>{h||f(1)},1500);return}h||i((x==null?void 0:x.message)||String(x))})};return f(),()=>{h=!0}},[e]);async function d(){if(!(!e||o)){l(!0),u(null);try{const{blob:h,filename:f}=await K.overviewPdf(e),m=URL.createObjectURL(h),x=document.createElement("a");x.href=m,x.download=f,document.body.appendChild(x),x.click(),x.remove(),setTimeout(()=>URL.revokeObjectURL(m),1500)}catch(h){u(String((h==null?void 0:h.message)||h))}finally{l(!1)}}}return s.jsxs(s.Fragment,{children:[!t&&s.jsx(Pt,{crumbs:[{label:"Overview",to:"/overview"},{label:(n==null?void 0:n.display_name)??e}],actions:(n==null?void 0:n.marketplace)==="makro"?void 0:s.jsxs(W,{onClick:d,disabled:o,"aria-label":"Download Overview as PDF",intent:"neutral",variant:"outline",size:"sm",title:"Download this Overview as a PDF (uses current data)",children:[s.jsx(Dr,{className:o?"w-3.5 h-3.5 animate-pulse":"w-3.5 h-3.5"}),s.jsx("span",{className:"hidden md:inline",children:o?"Renderingâ¦":"PDF"})]})}),s.jsx("div",{className:t?"overview-print bg-surface":"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full p-4 md:p-6 space-y-6",children:[!t&&s.jsx(oB,{slug:e}),!t&&c&&s.jsxs(V,{className:"p-3 text-xs text-text-error bg-surface-errorSubtle border-outline-error",children:["PDF export failed: ",c]}),a&&s.jsx(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:a}),(n==null?void 0:n.marketplace)==="makro"?s.jsx(xx,{view:"overview",chrome:!1}):s.jsx($H,{slug:e,sellerName:(n==null?void 0:n.display_name)??e,marketplace:n==null?void 0:n.marketplace})]})})]})}const JMe="â";function zH(e){const t=Math.round(e);return(t<0?"â":"")+String(Math.abs(t)).replace(/\B(?=(\d{3})+(?!\d))/g,JMe)}function QMe(e){return`R ${zH(e)}`}function e$e(e){return`${e.toFixed(1)}%`}const bk={storeName:"Blue Panda",period:"August 2026",subtitle:"Trading report · 1â31 August 2026",sellerId:"Seller 71829304",generatedOn:"29 Aug 2026",marketplace:"takealot",kpis:[{label:"GMV",value:"R 1 243 907",delta:"â² 8.2% vs prev 30d",tone:"success"},{label:"Units sold",value:"3 481",delta:"â² 3.1%",tone:"success"},{label:"Return rate",value:"4.1%",delta:"â² 0.6pp",tone:"error"},{label:"Net payout",value:"R 284 190",delta:"â² R 12 400",tone:"success"}],revenueSeries:[38,52,44,67,58,81,73,62,49,41,55,64,77,71,60,52,68,84,79,66,58,47,61,73,88,92,100,81,69,74,63],revenueAxis:["1 Aug","31 Aug · ZAR, incl. VAT"],revenuePeak:"R 41 380 peak",feeSplit:[{label:"Net profit",value:84},{label:"Takealot fee",value:38},{label:"Cost of goods",value:142},{label:"VAT",value:45}],feeCenterValue:"R 349",skus:[{sku:"BP-YM-6MM-BLK",title:"Yoga mat 6mm â black",units:312,revenue:108888,returnRatePct:2.1},{sku:"BP-FR-STD",title:"Foam roller standard",units:203,revenue:46487,returnRatePct:1.4},{sku:"BP-RB-SET-3",title:"Resistance band set",units:148,revenue:27972,returnRatePct:3},{sku:"BP-YM-6MM-PRP",title:"Yoga mat 6mm â purple",units:96,revenue:36384,returnRatePct:11.8},{sku:"BP-KB-12KG",title:"Kettlebell 12kg",units:87,revenue:56463,returnRatePct:.9}],callouts:[{warning:!0,title:"Returns on BP-YM-6MM-PRP tripled to 11.8%",body:"Every other SKU sits under 3%. The purple variant shares its listing images with the black one, so buyers may be receiving a colour they did not expect. Worth checking the images against what ships before the next campaign."},{title:"Three SKUs were skipped by the sync",body:"Missing barcodes. They are not counted in any figure above."}]},t$e={success:"text-text-success",warning:"text-text-warning",error:"text-text-error",body:"text-text-body"};function n$e(e){const{storeName:t,period:n,subtitle:r,sellerId:a,generatedOn:i,marketplace:o="takealot",kpis:l,revenueSeries:c,revenueAxis:u,revenuePeak:d,feeSplit:h,feeCenterValue:f,skus:m,callouts:x}=e;return s.jsx("div",{className:"seller-report bg-surface p-[0.7in] text-text-body text-body-md",children:s.jsxs("table",{className:"w-full border-collapse",children:[s.jsx("thead",{children:s.jsx("tr",{children:s.jsx("td",{children:s.jsxs("div",{className:"flex items-center justify-between gap-4 pb-2 border-b border-outline-subtle",children:[s.jsx(w2,{height:20,on:"light"}),s.jsx("span",{className:"shrink-0 whitespace-nowrap text-body-xs uppercase tracking-wider text-text-tertiary",children:"Monthly trading report"})]})})})}),s.jsx("tfoot",{children:s.jsx("tr",{children:s.jsx("td",{children:s.jsxs("div",{className:"flex items-center justify-between gap-4 pt-2 border-t border-outline-subtle text-body-xs text-text-tertiary",children:[s.jsxs("span",{children:[t," · ",n]}),s.jsxs("span",{children:["Generated ",i," · figures in ZAR incl. VAT"]})]})})})}),s.jsx("tbody",{children:s.jsx("tr",{children:s.jsxs("td",{className:"pt-6",children:[s.jsxs("div",{className:"flex items-start justify-between gap-6 mb-1.5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-body-xs font-semibold tracking-[0.09em] uppercase text-text-brand",children:n}),s.jsx("h1",{className:"mt-2 text-headline-2xl text-text-primary",children:t}),s.jsx("div",{className:"mt-1 text-body-md text-text-secondary",children:r})]}),s.jsx(kf,{marketplace:o,size:"lg",showLabel:!0,meta:a})]}),s.jsx("h2",{className:"mt-8 text-headline-sm text-text-primary",children:"The month in four numbers"}),s.jsx("div",{className:"mt-3 grid grid-cols-4 gap-3 break-inside-avoid",children:l.map(g=>s.jsxs("div",{className:"break-inside-avoid rounded-md border border-outline-subtle px-3 py-2.5",children:[s.jsx("div",{className:"text-body-xs uppercase tracking-wider text-text-tertiary",children:g.label}),s.jsx("div",{className:"mt-0.5 text-[18px] font-semibold tabular-nums text-text-primary",children:g.value}),g.delta&&s.jsx("div",{className:`mt-0.5 text-body-sm ${t$e[g.tone??"body"]}`,children:g.delta})]},g.label))}),s.jsx("h2",{className:"mt-8 text-headline-sm text-text-primary",children:"Daily revenue"}),s.jsx("p",{className:"mt-1.5",children:"Trading held through the mid-month dip and closed on the strongest single day of the peri
878od. The pattern follows payday weeks, as it has every month this quarter."}),s.jsxs("div",{className:"mt-3.5 break-inside-avoid rounded-lg border border-outline-subtle p-4",children:[s.jsxs("div",{className:"mb-3 flex items-baseline justify-between gap-4",children:[s.jsx("span",{className:"text-body-sm font-medium uppercase tracking-wider text-text-secondary",children:"Revenue per day"}),s.jsx("span",{className:"text-headline-sm tabular-nums text-text-primary",children:d})]}),s.jsx(r3,{data:c,height:120,axis:u})]}),s.jsx("h2",{className:"mt-8 text-headline-sm text-text-primary",children:"Where the money went"}),s.jsx("p",{className:"mt-1.5",children:"Per unit, on the best-selling SKU. Fee category and VAT are fixed; cost of goods is the only line you control."}),s.jsx("div",{className:"mt-3.5 break-inside-avoid rounded-lg border border-outline-subtle p-4",children:s.jsx(HDe,{data:h,size:132,centerValue:f,centerLabel:"Sell price"})}),s.jsx("h2",{className:"mt-8 text-headline-sm text-text-primary",children:"Top SKUs by revenue"}),s.jsxs("table",{className:"mt-3 w-full border-collapse text-body-sm",children:[s.jsx("thead",{children:s.jsx("tr",{children:["SKU","Product","Units","Revenue","Returns"].map((g,y)=>s.jsx("th",{className:`whitespace-nowrap border-b border-outline-subtle px-2.5 py-2 font-semibold text-text-body ${y>=2?"text-right":"text-left"}`,children:g},g))})}),s.jsx("tbody",{children:m.map((g,y)=>{const b=y===m.length-1,v=g.returnRatePct>=10,w=b?"px-2.5 py-2":"border-b border-outline-faint px-2.5 py-2";return s.jsxs("tr",{className:"break-inside-avoid",children:[s.jsx("td",{className:`${w} whitespace-nowrap text-text-body`,children:g.sku}),s.jsx("td",{className:`${w} font-medium text-text-primary`,children:g.title}),s.jsx("td",{className:`${w} text-right tabular-nums`,children:zH(g.units)}),s.jsx("td",{className:`${w} text-right tabular-nums`,children:QMe(g.revenue)}),s.jsx("td",{className:`${w} text-right tabular-nums ${v?"font-medium text-text-error":""}`,children:g.returnRatePct?e$e(g.returnRatePct):"â"})]},g.sku)})})]}),s.jsx("h2",{className:"mt-8 text-headline-sm text-text-primary",children:"What needs attention"}),x.map(g=>s.jsxs("div",{className:`mt-3 break-inside-avoid rounded-lg px-[15px] py-[13px] ${g.warning?"border border-outline-warning bg-surface-warningSubtle":"border border-outline-subtle"}`,children:[s.jsx("div",{className:"text-body-md font-medium text-text-primary",children:g.title}),s.jsx("p",{className:"mt-1 text-body-sm leading-relaxed",children:g.body})]},g.title)),s.jsx("p",{className:"mt-8 text-body-sm leading-relaxed text-text-tertiary",children:"All figures are net of returns and include VAT at 15%. Fee categories are as published by the marketplace on the report date and may be restated. Ask your account manager if a number here disagrees with your Seller Portal statement."})]})})})]})})}function vM(e=new Date){return e.toLocaleDateString("en-ZA",{month:"long",year:"numeric"})}function r$e(e=new Date){return e.toLocaleDateString("en-ZA",{day:"numeric",month:"short",year:"numeric"})}function s$e(){const{slug:e=""}=jn(),[t,n]=p.useState(null);p.useEffect(()=>{K.seller(e).then(n).catch(()=>{})},[e]);const r={...bk,storeName:(t==null?void 0:t.display_name)??e??bk.storeName,sellerId:t!=null&&t.seller_id?`Seller ${t.seller_id}`:bk.sellerId,generatedOn:r$e(),marketplace:(t==null?void 0:t.marketplace)??"takealot",period:vM(),subtitle:`Trading report · ${vM()}`};return s.jsx("div",{className:"min-h-screen bg-surface",children:s.jsx(n$e,{...r})})}function Ye({label:e,value:t,tone:n="default",hint:r,delta:a,deltaIsBadWhenUp:i=!1,className:o}){const l=n==="error"?"text-text-error":n==="warn"?"text-text-warning":n==="success"?"text-text-success":"text-text-primary";let c="text-text-tertiary";return a&&(c=(i?a.positive:!a.positive)?"text-text-error":"text-text-success"),s.jsxs("div",{className:B("rounded-md border border-outline-subtle bg-surface px-3 py-2.5",o),children:[s.jsx("div",{className:"text-body-xs uppercase tracking-wider text-text-tertiary",children:e}),s.jsx("div",{className:B("mt-0.5 text-lg font-semibold tabular-nums",l),children:t}),a||r?s.jsxs("div",{className:"mt-0.5 flex items-center gap-1.5 text-xs",children:[a?s.jsxs("span",{className:B("inline-flex items-center gap-0.5",c),children:[a.positive?s.jsx(Xi,{className:"h-3 w-3"}):s.jsx(ax,{className:"h-3 w-3"}),a.text]}):null,r?s.jsx("span",{className:"text-text-tertiary",children:r}):null]}):null]})}function dr({children:e,cols:t=4,className:n}){const r=t===6?"md:grid-cols-3 lg:grid-cols-6":t===5?"md:grid-cols-5":t===3?"md:grid-cols-3":t===2?"md:grid-cols-2":"md:grid-cols-4";return s.jsx("div",{className:B("grid grid-cols-2 gap-3",r,n),children:e})}const a$e=[{key:"display_name",label:"Account",sortable:!0,sticky:!0,render:e=>s.jsx(st,{to:`/overview/${e.seller_slug}`,className:"font-medium text-text-primary hover:text-text-brand hover:underline",children:e.display_name}),className:"truncate max-w-[260px]"}
878,{key:"gmv",label:"Sales · 30d",sortable:!0,align:"right",format:"zar"},{key:"orders",label:"Orders",sortable:!0,align:"right",format:"number"},{key:"units",label:"Units",sortable:!0,align:"right",format:"number"},{key:"return_rate",label:"Return rate",sortable:!0,align:"right",format:"percent"}];function i$e(){const[e,t]=p.useState(null),[n,r]=p.useState(null);p.useEffect(()=>{t(null),r(null),K.overviewRollup().then(t).catch(i=>r(String(i)))},[]);const a=e==null?void 0:e.totals;return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Overview"}]}),s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full p-4 md:p-6 space-y-6",children:[n&&s.jsx(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:n}),s.jsxs(dr,{children:[s.jsx(Ye,{label:"Sales · 30d",value:ge(a==null?void 0:a.sales_30d,{compact:!0}),hint:`${de(a==null?void 0:a.orders_30d)} orders · ${de(a==null?void 0:a.units_30d)} units`}),s.jsx(Ye,{label:"Sales · 90d",value:ge(a==null?void 0:a.sales_90d,{compact:!0}),hint:`${de(a==null?void 0:a.units_90d)} units`}),s.jsx(Ye,{label:"Return rate · 90d",value:Yn(a==null?void 0:a.return_rate_90d),hint:`${de(a==null?void 0:a.returns_units_90d)}
878 units returned`,tone:(a==null?void 0:a.return_rate_90d)!=null&&a.return_rate_90d>.08?"warn":"default"}),s.jsx(Ye,{label:"Accounts",value:de(e==null?void 0:e.seller_count),hint:"in this rollup"})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsx("div",{className:"px-5 py-3 border-b border-outline-faint text-sm font-semibold text-text-primary",children:"By account · last 30 days"}),s.jsx(dt,{rows:(e==null?void 0:e.sellers)??null,columns:a$e,getRowKey:i=>i.seller_slug,defaultSort:{key:"gmv",direction:"desc"},empty:{title:"No accounts in scope yet."}})]}),s.jsx($H,{slug:JF,sellerName:"All accounts",rollup:!0})]})})]})}const o$e=["AElig","AMP","Aacute","Acirc","Agrave","Aring","Atilde","Auml","COPY","Ccedil","ETH","Eacute","Ecirc","Egrave","Euml","GT","Iacute","Icirc","Igrave","Iuml","LT","Ntilde","Oacute","Ocirc","Ograve","Oslash","Otilde","Ouml","QUOT","REG","THORN","Uacute","Ucirc","Ugrave","Uuml","Yacute","aacute","acirc","acute","aelig","agrave","amp","aring","atilde","auml","brvbar","ccedil","cedil","cent","copy","curren","deg","divide","eacute","ecirc","egrave","eth","euml","frac12","frac14","frac34","gt","iacute","icirc","iexcl","igrave","iquest","iuml","laquo","lt","macr","micro","middot","nbsp","not","ntilde","oacute","ocirc","ograve","ordf","ordm","oslash","otilde","ouml","para","plusmn","pound","quot","raquo","reg","sect","shy","sup1","
878sup2","sup3","szlig","thorn","times","uacute","ucirc","ugrave","uml","uuml","yacute","yen","yuml"],wM={0:"�",128:"â¬",130:"â",131:"Æ",132:"â",133:"â¦",134:"â ",135:"â¡",136:"Ë",137:"â°",138:"Å ",139:"â¹",140:"Å",142:"Ž",145:"â",146:"â",147:"â",148:"â",149:"â¢",150:"â",151:"â",152:"Ë",153:"â¢",154:"Å¡",155:"âº",156:"Å",158:"ž",159:"Ÿ"};function WH(e){const t=typeof e=="string"?e.charCodeAt(0):e;return t>=48&&t<=57}function l$e(e){const t=typeof e=="string"?e.charCodeAt(0):e;return t>=97&&t<=102||t>=65&&t<=70||t>=48&&t<=57}function c$e(e){const t=typeof e=="string"?e.charCodeAt(0):e;return t>=97&&t<=122||t>=65&&t<=90}function _M(e){return c$e(e)||WH(e)}const u$e=["","Named character references must be terminated by a semicolon","Numeric character references must be terminated by a semicolon","Named character references cannot be empty","Numeric character references cannot be empty","Named character references must be known","Numeric character references cannot be disallowed","Numeric character references cannot be outside the permissible Unicode range"];function i3(e,t){const n=t||{},r=typeof n.additional=="string"?n.additional.charCodeAt(0):n.additional,a=[];let i=0,o=-1,l="",c,u;n.position&&("start"in n.position||"indent"in n.position?(u=n.position.indent,c=n.position.start):c=n.position);let d=(c?c.line:0)||1,h=(c?c.column:0)||1,f=x(),m;for(i--;++i<=e.length;)if(m===10&&(h=(u?u[o]:0)||1),m=e.charCodeAt(i),m===38){const b=e.charCodeAt(i+1);if(b===9||b===10||b===12||b===32||b===38||b===60||Number.isNaN(b)||r&&b===r){l+=String.fromCharCode(m),h++;continue}const v=i+1;let w=v,_=v,k;if(b===35){_=++w;const O=e.charCodeAt(_);O===88||O===120?(k="hexadecimal",_=++w):k="decimal"}else k="named";let j="",N="",E="";const A=k==="named"?_M:k==="decimal"?WH:l$e;for(_--;++_<=e.length;){const O=e.charCodeAt(_);if(!A(O))break;E+=String.fromCharCode(O),k==="named"&&o$e.includes(E)&&(j=E,N=Np(E))}let C=e.charCodeAt(_)===59;if(C){_++;const O=k==="named"?Np(E):!1;O&&(j=E,N=O)}let T=1+_-v,S="";if(!(!C&&n.nonTerminated===!1))if(!E)k!=="named"&&g(4,T);else if(k==="named"){if(C&&!N)g(5,1);else if(j!==E&&(_=w+j.length,T=1+_-w,C=!1),!C){const O=j?1:3;if(n.attribute){const R=e.charCodeAt(_);R===61?(g(O,T),N=""):_M(R)?N="":g(O,T)}else g(O,T)}S=N}else{C||g(2,T);let O=Number.parseInt(E,k==="hexadecimal"?16:10);if(d$e(O))g(7,T),S="�";else if(O in wM)g(6,T),S=wM[O];else{let R="";h$e(O)&&g(6,T),O>65535&&(O-=65536,R+=String.fromCharCode(O>>>10|55296),O=56320|O&1023),S=R+String.fromCharCode(O)}}if(S){y(),f=x(),i=_-1,h+=_-v+1,a.push(S);const O=x();O.offset++,n.reference&&n.reference.call(n.referenceContext||void 0,S,{start:f,end:O},e.slice(v-1,_)),f=O}else E=e.slice(v-1,_),l+=E,h+=E.length,i=_-1}else m===10&&(d++,o++,h=0),Number.isNaN(m)?y():(l+=String.fromCharCode(m),h++);return a.join("");function x(){return{line:d,column:h,offset:i+((c?c.offset:0)||0)}}function g(b,v){let w;n.warning&&(w=x(),w.column+=v,w.offset+=v,n.warning.call(n.warningContext||void 0,u$e[b],w,b))}function y(){l&&(a.push(l),n.text&&n.text.call(n.textContext||void 0,l,{start:f,end:x()}),l="")}}function d$e(e){return e>=55296&&e<=57343||e>1114111}function h$e(e){return e>=1&&e<=8||e===11||e>=13&&e<=31||e>=127&&e<=159||e>=64976&&e<=65007||(e&65535)===65535||(e&65535)===65534}const f$e=/["&'<>`]/g,m$e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,p$e=/[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g,x$e=/[|\\{}()[\]^$+*?.]/g,kM=new WeakMap;function g$e(e,t){if(e=e.replace(t.subset?y$e(t.subset):f$e,r),t.subset||t.escapeOnly)return e;return e.replace(m$e,n).replace(p$e,r);function n(a,i,o){return t.format((a.charCodeAt(0)-55296)*1024+a.charCodeAt(1)-56320+65536,o.charCodeAt(i+2),t)}function r(a,i,o){return t.format(a.charCodeAt(0),o.charCodeAt(i+1),t)}}function y$e(e){let t=kM.get(e);return t||(t=b$e(e),kM.set(e,t)),t}function b$e(e){const t=[];let n=-1;for(;++n<e.length;)t.push(e[n].replace(x$e,"\\$&"));return new RegExp("(?:"+t.join("|")+")","g")}function v$e(e){return"&#x"+e.toString(16).toUpperCase()+";"}function w$e(e,t){return g$e(e,Object.assign({format:v$e},t))}const _$e={}.hasOwnProperty,k$e={},jM=/^[^\t\n\r "#'.<=>`}]+$/,j$e=/^[^\t\n\r "'<=>`}]+$/;
878function N$e(){return{canContainEols:["textDirective"],enter:{directiveContainer:C$e,directiveContainerAttributes:wk,directiveContainerLabel:T$e,directiveLeaf:E$e,directiveLeafAttributes:wk,directiveText:A$e,directiveTextAttributes:wk},exit:{directiveContainer:Ck,directiveContainerAttributeClassValue:kk,directiveContainerAttributeIdValue:_k,directiveContainerAttributeName:Nk,directiveContainerAttributeValue:jk,directiveContainerAttributes:Sk,directiveContainerLabel:O$e,directiveContainerName:vk,directiveLeaf:Ck,directiveLeafAttributeClassValue:kk,directiveLeafAttributeIdValue:_k,directiveLeafAttributeName:Nk,directiveLeafAttributeValue:jk,directiveLeafAttributes:Sk,directiveLeafName:vk,directiveText:Ck,directiveTextAttributeClassValue:kk,directiveTextAttributeIdValue:_k,directiveTextAttributeName:Nk,directiveTextAttributeValue:jk,directiveTextAttributes:Sk,directiveTextName:vk}}}function S$e(e){const t=k$e;if(t.quote!=='"'&&t.quote!=="'"&&t.quote!==null&&t.quote!==void 0)throw new Error("Invalid quote `"+t.quote+"`, expected `'` or `\"`");return n.peek=I$e,{handlers:{containerDirective:n,leafDirective:n,textDirective:n},unsafe:[{character:"\r",inConstruct:["leafDirectiveLabel","containerDirectiveLabel"]},{character:` 879`,inConstruct:["leafDirectiveLabel","containerDirectiveLabel"]},{before:"[^:]",character:":",after:"[A-Za-z]",inConstruct:["phrasing"]},{atBreak:!0,character:":",after:":"}]};function n(i,o,l,c){const u=l.createTracker(c),d=P$e(i),h=l.enter(i.type);let f=u.move(d+(i.name||"")),m;if(i.type==="containerDirective"){const x=(i.children||[])[0];m=NM(x)?x:void 0}else m=i;if(m&&m.children&&m.children.length>0){const x=l.enter("label"),g=`${i.type}Label`,y=l.enter(g);f+=u.move("["),f+=u.move(l.containerPhrasing(m,{...u.current(),before:f,after:"]"})),f+=u.move("]"),y(),x()}if(f+=u.move(r(i,l)),i.type==="containerDirective"){const x=(i.children||[])[0];let g=i;NM(x)&&(g=Object.assign({},i,{children:i.children.slice(1)})),g&&g.children&&g.children.length>0&&(f+=u.move(` 880`),f+=u.move(l.containerFlow(g,u.current()))),f+=u.move(` 881`+d)}return h(),f}function r(i,o){const l=i.attributes||{},c=[];let u,d,h,f;for(f in l)if(_$e.call(l,f)&&l[f]!==void 0&&l[f]!==null){const m=String(l[f]);if(f==="id")h=t.preferShortcut!==!1&&jM.test(m)?"#"+m:a("id",m,i,o);else if(f==="class"){const x=m.split(/[\t\n\r ]+/g),g=[],y=[];let b=-1;for(;++b<x.length;)(t.preferShortcut!==!1&&jM.test(x[b])?y:g).push(x[b]);u=g.length>0?a("class",g.join(" "),i,o):"",d=y.length>0?"."+y.join("."):""}else c.push(a(f,m,i,o))}return u&&c.unshift(u),d&&c.unshift(d),h&&c.unshift(h),c.length>0?"{"+c.join(" ")+"}":""}function a(i,o,l,c){if(t.collapseEmptyAttributes!==!1&&!o)return i;if(t.preferUnquoted&&j$e.test(o))return i+"="+o;const u=t.quote||c.options.quote||'"',d=u==='"'?"'":'"',h=t.quoteSmart&&db(o,u)>db(o,d)?d:u,f=l.type==="textDirective"?[h]:[h,` 882`,"\r"];return i+"="+h+w$e(o,{subset:f})+h}}function C$e(e){o3.call(this,"containerDirective",e)}function E$e(e){o3.call(this,"leafDirective",e)}function A$e(e){o3.call(this,"textDirective",e)}function o3(e,t){this.enter({type:e,name:"",attributes:{},children:[]},t)}function vk(e){const t=this.stack[this.stack.length-1];t.type==="containerDirective"||t.type==="leafDirective"||t.type,t.name=this.sliceSerialize(e)}function T$e(e){this.enter({type:"paragraph",data:{directiveLabel:!0},children:[]},e)}function O$e(e){this.exit(e)}function wk(){this.data.directiveAttributes=[],this.buffer()}function _k(e){this.data.directiveAttributes.push(["id",i3(this.sliceSerialize(e),{attribute:!0})])}function kk(e){this.data.directiveAttributes.push(["class",i3(this.sliceSerialize(e),{attribute:!0})])}function jk(e){const t=this.data.directiveAttributes;t[t.length-1][1]=i3(this.sliceSerialize(e),{attribute:!0})}function Nk(e){this.data.directiveAttributes.push([this.sliceSerialize(e),""])}function Sk(){const e=this.data.directiveAttributes,t={};let n=-1;for(;++n<e.length;){const a=e[n];a[0]==="class"&&t.class?t.class+=" "+a[1]:t[a[0]]=a[1]}this.data.directiveAttributes=void 0,this.resume();const r=this.stack[this.stack.length-1];r.type==="containerDirective"||r.type==="leafDirective"||r.type,r.attributes=t}function Ck(e){this.exit(e)}function I$e(){return":"}function NM(e){return!!(e&&e.type==="paragraph"&&e.data&&e.data.directiveLabel)}function P$e(e){let t=0;return e.type==="containerDirective"?(CC(e,function(n,r){if(n.type==="containerDirective"){let a=r.length,i=0;for(;a--;)r[a].type==="containerDirective"&&i++;i>t&&(t=i)}}),t+=3):e.type==="leafDirective"?t=2:t=1,":".repeat(t)}function l3(e,t,n,r,a,i,o,l,c,u,d,h,f,m,x){let g,y;return b;function b(I){return e.enter(r),e.enter(a),e.consume(I),e.exit(a),v}
882function v(I){return I===35?(g=o,w(I)):I===46?(g=l,w(I)):x&&Vt(I)?Bt(e,v,"whitespace")(I):!x&&on(I)?zl(e,v)(I):I===null||ft(I)||jo(I)||ru(I)&&I!==45&&I!==95?R(I):(e.enter(i),e.enter(c),e.consume(I),j)}function w(I){const $=g+"Marker";return e.enter(i),e.enter(g),e.enter($),e.consume(I),e.exit($),_}function _(I){if(I===null||I===34||I===35||I===39||I===46||I===60||I===61||I===62||I===96||I===125||on(I))return n(I);const $=g+"Value";return e.enter($),e.consume(I),k}function k(I){if(I===null||I===34||I===39||I===60||I===61||I===62||I===96)return n(I);if(I===35||I===46||I===125||on(I)){const $=g+"Value";return e.exit($),e.exit(g),e.exit(i),v(I)}return e.consume(I),k}function j(I){return I===null||ft(I)||jo(I)||ru(I)&&I!==45&&I!==46&&I!==58&&I!==95?(e.exit(c),x&&Vt(I)?Bt(e,N,"whitespace")(I):!x&&on(I)?zl(e,N)(I):N(I)):(e.consume(I),j)}function N(I){return I===61?(e.enter(u),e.consume(I),e.exit(u),E):(e.exit(i),v(I))}function E(I){return I===null||I===60||I===61||I===62||I===96||I===125||x&&ft(I)?n(I):I===34||I===39?(e.enter(d),e.enter(f),e.consume(I),e.exit(f),y=I,C):x&&Vt(I)?Bt(e,E,"whitespace")(I):!x&&on(I)?zl(e,E
882)(I):(e.enter(h),e.enter(m),e.consume(I),y=void 0,A)}function A(I){return I===null||I===34||I===39||I===60||I===61||I===62||I===96?n(I):I===125||on(I)?(e.exit(m),e.exit(h),e.exit(i),v(I)):(e.consume(I),A)}function C(I){return I===y?(e.enter(f),e.consume(I),e.exit(f),e.exit(d),e.exit(i),O):(e.enter(h),T(I))}function T(I){return I===y?(e.exit(h),C(I)):I===null?n(I):ft(I)?x?n(I):zl(e,T)(I):(e.enter(m),e.consume(I),S)}function S(I){return I===y||I===null||ft(I)?(e.exit(m),T(I)):(e.consume(I),S)}function O(I){return I===125||on(I)?v(I):R(I)}function R(I){return I===125?(e.enter(a),e.consume(I),e.exit(a),e.exit(r),t):n(I)}}function c3(e,t,n,r,a,i,o){let l=0,c=0,u;return d;function d(y){return e.enter(r),e.enter(a),e.consume(y),e.exit(a),h}function h(y){return y===93?(e.enter(a),e.consume(y),e.exit(a),e.exit(r),t):(e.enter(i),f(y))}function f(y){if(y===93&&!c)return g(y);const b=e.enter("chunkText",{_contentTypeTextTrailing:!0,contentType:"text",previous:u});return u&&(u.next=b),u=b,m(y)}function m(y){return y===null||l>999||y===91&&++c>32?n(y):y===93&&!c--?(e.exit("chunkText"),g(y)):ft(y)?o?n(y):(e.consume(y),e.exit("chunkText"),f):(e.consume(y),y===92?x:m)}function x(y){return y===91||y===92||y===93?(e.consume(y),l++,m):m(y)}function g(y){return e.exit(i),e.enter(a),e.consume(y),e.exit(a),e.exit(r),t}}function u3(e,t,n,r){const a=this;return i;function i(l){return l===null||ft(l)||ru(l)||jo(l)?n(l):(e.enter(r),e.consume(l),o)}function o(l){return l===null||ft(l)||jo(l)||ru(l)&&l!==45&&l!==95?(e.exit(r),a.previous===45||a.previous===95?n(l):t(l)):(e.consume(l),o)}}const R$e={tokenize:$$e,concrete:!0},D$e={tokenize:L$e,partial:!0},M$e={tokenize:F$e,partial:!0},$g={tokenize:B$e,partial:!0};function $$e(e,t,n){const r=this,a=r.events[r.events.length-1],i=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0;let o=0,l;return c;function c(A){return e.enter("directiveContainer"),e.enter("directiveContainerFence"),e.enter("directiveContainerSequence"),u(A)}function u(A){return A===58?(e.consume(A),o++,u):o<3?n(A):(e.exit("directiveContainerSequence"),u3.call(r,e,d,n,"directiveContainerName")(A))}function d(A){return A===91?e.attempt(D$e,h,h)(A):h(A)}function h(A){return A===123?e.attempt(M$e,f,f)(A):f(A)}function f(A){return Bt(e,m,"whitespace")(A)}function m(A){return e.exit("directiveContainerFence"),A===null?N(A):ft(A)?r.interrupt?t(A):e.attempt($g,x,N)(A):n(A)}function x(A){return A===null?N(A):ft(A)?e.check($g,w,N)(A):(e.enter("directiveContainerContent"),g(A))}function g(A){return e.attempt({tokenize:E,partial:!0},j,i?Bt(e,y,"linePrefix",i+1):y)(A)}function y(A){return A===null?j(A):ft(A)?e.check($g,v,j)(A):v(A)}function b(A){if(A===null){const C=e.exit("chunkDocument");return r.parser.lazy[C.start.line]=!1,j(A)}return ft(A)?e.check($g,_,k)(A):(e.consume(A),b)}function v(A){const C=e.enter("chunkDocument",{contentType:"document",previous:l});return l&&(l.next=C),l=C,b(A)}function w(A){return e.enter("directiveContainerContent"),g(A)}function _(A){e.consume(A);const C=e.exit("chunkDocument");return r.parser.lazy[C.start.line]=!1,g}function k(A){const C=e.exit("chunkDocument");return r.parser.lazy[C.start.line]=!1,j(A)}function j(A){return e.exit("directiveContainerContent"),N(A)}function N(A){return e.exit("directiveContainer"),t(A)}function E(A,C,T){let S=0;return Bt(A,O,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4);function O($){return A.enter("directiveContainerFence"),A.enter("directiveContainerSequence"),R($)}function R($){return $===58?(A.consume($),S++,R):S<o?T($):(A.exit("directiveContainerSequence"),Bt(A,I,"whitespace")($))}function I($){return $===null||ft($)?(A.exit("directiveContainerFence"),C($)):T($)}}}function L$e(e,t,n){return c3(e,t,n,"directiveContainerLabel","directiveContainerLabelMarker","directiveContainerLabelString",!0)}function F$e(e,t,n){return l3(e,t,n,"directiveContainerAttributes","directiveContainerAttributesMarker","directiveContainerAttribute","directiveContainerAttributeId","directiveContainerAttributeClass","directiveContainerAttributeName","directiveContainerAttributeInitializerMarker","directiveContainerAttributeValueLiteral","directiveContainerAttributeValue","directiveContainerAttributeValueMarker","directiveContainerAttributeValueData",!0)}function B$e(e,t,n){const r=this;return a;function a(o){return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),i}function i(o){return r.parser.lazy[r.now().line]?n(o):t(o)}}const U$e={tokenize:K$e},z$e={tokenize:H$e,partial:!0},W$e={tokenize:V$e,partial:!0};function K$e(e,t,n){const r=this;return a;function a(d){return e.enter("directiveLeaf"),e.enter("directiveLeafSequence"),e.consume(d),i}function i(d){return d===58?(e.consume(d),e.exit("directiveLeafSequence"),u3.call(r,e,o,n,"directiveLeafName")):n(d)}function o(d){return d===91?e.attempt(z$e,l,l)(d):l(d)}function l(d){return d===123?e.attempt(W$e,c,c)(d):c(d)}function c(d){return Bt(e,u,"whitespace")(d)}function u(d){return d===null||ft(d)?(e.exit("directiveLeaf"),t(d)):n(d)}}function H$e(e,t,n){return c3(e,t,n,"directiveLeafLabel","directiveLeafLabelMarker","directiveLeafLabelString",!0)}function V$e(e,t,n){return l3(e,t,n,"directiveLeafAttributes","directiveLeafAttributesMarker","directiveLeafAttribute","directiveLeafAttributeId","directiveLeafAttributeClass","directiveLeafAttributeName","directiveLeafAttributeInitializerMarker","directiveLeafAttributeValueLiteral","directiveLeafAttributeValue","directiveLeafAttributeValueMarker","directiveLeafAttributeValueData",!0)}const q$e={tokenize:X$e,previous:Z$e},G$e={tokenize:J$e,partial:!0},Y$e={tokenize:Q$e,partial:!0};function Z$e(e){return e!==58||this.events[this.events.length-1][1].type==="characterEscape"}function X$e(e,t,n){const r=this;return a;function a(c){return e.enter("directiveText"),e.enter("directiveTextMarker"),e.consume(c),e.exit("directiveTextMarker"),u3.call(r,e,i,n,"directiveTextName")}function i(c){return c===58?n(c):c===91?e.attempt(G$e,o,o)(c):o(c)}function o(c){return c===123?e.attempt(Y$e,l,l)(c):l(c)}function l(c){return e.exit("directiveText"),t(c)}}function J$e(e,t,n){return c3(e,t,n,"directiveTextLabel","directiveTextLabelMarker","directiveTextLabelString")}function Q$e(e,t,n){return l3(e,t,n,"directiveTextAttributes","directiveTextAttributesMarker","directiveTextAttribute","directiveTextAttributeId","directiveTextAttributeClass","directiveTextAttributeName","directiveTextAttributeInitializerMarker","directiveTextAttributeValueLiteral","directiveTextAttributeValue","directiveTextAttributeValueMarker","directiveTextAttributeValueData")}function eLe(){return{text:{58:q$e},flow:{58:[R$e,U$e]}}}function d3(){const t=this.data(),n=t.micromarkExtensions||(t.micromarkExtensions=[]),r=t.fromMarkdownExtensions||(t.fromMarkdownExtensions=[]),a=t.toMarkdownExtensions||(t.toMarkdownExtensions=[]);n.push(eLe()),r.push(N$e()),a.push(S$e())}const SM=(function(e,t,n){const r=hx(n);if(!e||!e.type||!e.children)throw new Error("Expected parent node");if(typeof t=="number"){if(t<0||t===Number.POSITIVE_INFINITY)throw new Error("Expected positive finite number as index")}else if(t=e.children.indexOf(t),t<0)throw new Error("Expected child node or index");for(;++t<e.children.length;)if(r(e.children[t],t,e))return e.children[t]}),Wd=(function(e){if(e==null)return rLe;if(typeof e=="string")return nLe(e);if(typeof e=="object")return tLe(e);if(typeof e=="function")return h3(e);throw new Error("Expected function, string, or array as `test`")});function tLe(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=Wd(e[n]);return h3(r);function r(...a){let i=-1;for(;++i<t.length;)if(t[i].apply(this,a))return!0;return!1}}function nLe(e){return h3(t);function t(n){return n.tagName===e}}function h3(e){return t;function t(n,r,a){return!!(sLe(n)&&e.call(this,n,typeof r=="number"?r:void 0,a||void 0))}}function rLe(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="element"&&"tagName"in e&&typeof e.tagName=="string")}function sLe(e){return e!==null&&typeof e=="object"&&"type"in e&&"tagName"in e}const CM=/\n/g,EM=/[\t ]+/g,$S=Wd("br"),AM=Wd(hLe),aLe=Wd("p"),TM=Wd("tr"),iLe=Wd(["datalist","head","noembed","noframes","noscript","rp","script","style","template","title",dLe,fLe]),KH=Wd(["address","article","aside","blockquote","body","caption","center","dd","dialog","dir","dl","dt","div","figure","figcaption","footer","form,","h1","h2","h3","h4","h5","h6","header","hgroup","hr","html","legend","li","listing","main","menu","nav","ol","p","plaintext","pre","section","ul","xmp"]);function oLe(e,t){const n=t||{}
882,r="children"in e?e.children:[],a=KH(e),i=qH(e,{whitespace:n.whitespace||"normal"}),o=[];(e.type==="text"||e.type==="comment")&&o.push(...VH(e,{breakBefore:!0,breakAfter:!0}));let l=-1;for(;++l<r.length;)o.push(...HH(r[l],e,{whitespace:i,breakBefore:l?void 0:a,breakAfter:l<r.length-1?$S(r[l+1]):a}));const c=[];let u;for(l=-1;++l<o.length;){const d=o[l];typeof d=="number"?u!==void 0&&d>u&&(u=d):d&&(u!==void 0&&u>-1&&c.push(` 883`.repeat(u)||" "),u=-1,c.push(d))}return c.join("")}function HH(e,t,n){return e.type==="element"?lLe(e,t,n):e.type==="text"?n.whitespace==="normal"?VH(e,n):cLe(e):[]}function lLe(e,t,n){const r=qH(e,n),a=e.children||[];let i=-1,o=[];if(iLe(e))return o;let l,c;for($S(e)||TM(e)&&SM(t,e,TM)?c=` 884`:aLe(e)?(l=2,c=2):KH(e)&&(l=1,c=1);++i<a.length;)o=o.concat(HH(a[i],e,{whitespace:r,breakBefore:i?void 0:l,breakAfter:i<a.length-1?$S(a[i+1]):c}));return AM(e)&&SM(t,e,AM)&&o.push(" "),l&&o.unshift(l),c&&o.push(c),o}function VH(e,t){const n=String(e.value),r=[],a=[];let i=0;for(;i<=n.length;){CM.lastIndex=i;const c=CM.exec(n),u=c&&"index"in c?c.index:n.length;r.push(uLe(n.slice(i,u).replace(/[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g,""),i===0?t.breakBefore:!0,u===n.length?t.breakAfter:!0)),i=u+1}let o=-1,l;for(;++o<r.length;)r[o].charCodeAt(r[o].length-1)===8203||o<r.length-1&&r[o+1].charCodeAt(0)===8203?(a.push(r[o]),l=void 0):r[o]?(typeof l=="number"&&a.push(l),a.push(r[o]),l=0):(o===0||o===r.length-1)&&a.push(0);return a}function cLe(e){return[String(e.value)]}function uLe(e,t,n){const r=[];let a=0,i;for(;a<e.length;){EM.lastIndex=a;const o=EM.exec(e);i=o?o.index:e.length,!a&&!i&&o&&!t&&r.push(""),a!==i&&r.push(e.slice(a,i)),a=o?i+o[0].length:i}return a!==i&&!n&&r.push(""),r.join(" ")}function qH(e,t){if(e.type==="element"){const n=e.properties||{};switch(e.tagName){case"listing":case"plaintext":case"xmp":return"pre";case"nobr":return"nowrap";case"pre":return n.wrap?"pre-wrap":"pre";case"td":case"th":return n.noWrap?"nowrap":t.whitespace;case"textarea":return"pre-wrap"}}return t.whitespace}function dLe(e){return!!(e.properties||{}).hidden}function hLe(e){return e.tagName==="td"||e.tagName==="th"}function fLe(e){return e.tagName==="dialog"&&!(e.properties||{}).open}function mLe(e){const t=e.regex,n=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",a="[a-zA-Z_]\\w*::",o="(?!struct)("+r+"|"+t.optional(a)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",l={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},u={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},d={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},h={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(u,{className:"string"}),{className:"string",begin:/<.*?>/},n,e.C_BLOCK_COMMENT_MODE]},f={className:"title",begin:t.optional(a)+e.IDENT_RE,relevance:0},m=t.optional(a)+e.IDENT_RE+"\\s*\\(",x=["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_
884noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],g=["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],y=["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"],b=["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"],_={type:g,keyword:x,literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:y},k={className:"function.dispatch",relevance:0,keywords:{_hint:b},begin:t.concat(/\b/,`(?!${x.join("|")})`,e.IDENT_RE,t.lookahead(/(<[^<>]+>|)\s*\(/))},j=[k,h,l,n,e.C_BLOCK_COMMENT_MODE,d,u],N={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:_,contains:j.concat([{begin:/\(/,end:/\)/,keywords:_,contains:j.concat(["self"]),relevance:0}]),relevance:0},E={className:"function",begin:"("+o+"[\\*&\\s]+)+"+m,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:_,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:_,relevance:0},{begin:m,returnBegin:!0,contains:[f],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[u,d]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:_,relevance:0,contains:[n,e.C_BLOCK_COMMENT_MODE,u,d,l,{begin:/\(/,end:/\)/,keywords:_,relevance:0,contains:["self",n,e.C_BLOCK_COMMENT_MODE,u,d,l]}]},l,n,e.C_BLOCK_COMMENT_MODE,h]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:_,illegal:"</",classNameAliases:{"function.dispatch":"built_in"},contains:[].concat(N,E,k,j,[h,{begin:"\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",end:">",keywords:_,contains:["self",l]},{begin:e.IDENT_RE+"::",keywords:_},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}function pLe(e){const t={type:["boolean","byte","word","String"],built_in:["KeyboardController","MouseController","SoftwareSerial","
884EthernetServer","EthernetClient","LiquidCrystal","RobotControl","GSMVoiceCall","EthernetUDP","EsploraTFT","HttpClient","RobotMotor","WiFiClient","GSMScanner","FileSystem","Scheduler","GSMServer","YunClient","YunServer","IPAddress","GSMClient","GSMModem","Keyboard","Ethernet","Console","GSMBand","Esplora","Stepper","Process","WiFiUDP","GSM_SMS","Mailbox","USBHost","Firmata","PImage","Client","Server","GSMPIN","FileIO","Bridge","Serial","EEPROM","Stream","Mouse","Audio","Servo","File","Task","GPRS","WiFi","Wire","TFT","GSM","SPI","SD"],_hints:["setup","loop","runShellCommandAsynchronously","analogWriteResolution","retrieveCallingNumber","printFirmwareVersion","analogReadResolution","sendDigitalPortPair","noListenOnLocalhost","readJoystickButton","setFirmwareVersion","readJoystickSwitch","scrollDisplayRight","getVoiceCallStatus","scrollDisplayLeft","writeMicroseconds","delayMicroseconds","beginTransmission","getSignalStrength","runAsynchronously","getAsynchronously","listenOnLocalhost","getCurrentCarrier","readAccelerometer","messageAvailable","sendDigitalPorts","lineFollowConfig","countryNameWrite","runShellCommand","readStringUntil","rewindDirectory","readTemperature","setClockDivider","readLightSensor","endTransmission","analogReference","detachInterrupt","countryNameRead","attachInterrupt","encryptionType","readBytesUntil","robotNameWrite","readMicrophone","robotNameRead","cityNameWrite","userNameWrite","readJoystickY","readJoystickX","mouseReleased","openNextFile","scanNetworks","noInterrupts","digitalWrite","beginSpeaker","mousePressed","isActionDone","mouseDragged","displayLogos","noAutoscroll","addParameter","remoteNumber","getModifiers","keyboardRead","userNameRead","waitContinue","processInput","parseCommand","printVersion","readNetworks","writeMessage","blinkVersion","cityNameRead","readMessage","setDataMode","parsePacket","isListening","setBitOrder","beginPacket","isDirectory","motorsWrite","drawCompass","digitalRead","clearScreen","serialEvent","rightToLeft","setTextSize","leftToRight","requestFrom","keyReleased","compassRead","analogWrite","interrupts","WiFiServer","disconnect","playMelody","parseFloat","autoscroll","getPINUsed","setPINUsed","setTimeout","sendAnalog","readSlider","analogRead","beginWrite","createChar","motorsStop","keyPressed","tempoWrite","readButton","subnetMask","debugPrint","macAddress","writeGreen","randomSeed","attachGPRS","readString","sendString","remotePort","releaseAll","mouseMoved","background","getXChange","getYChange","answerCall","getResult","voiceCall","endPacket","constrain","getSocket","writeJSON","getButton","available","connected","findUntil","readBytes","exitValue","readGreen","writeBlue","startLoop","IPAddress","isPressed","sendSysex","pauseMode","gatewayIP","setCursor","getOemKey","tuneWrite","noDisplay","loadImage","switchPIN","onRequest","onReceive","changePIN","playFile","noBuffer","parseInt","overflow","checkPIN","knobRead","beginTFT","bitClear","updateIR","bitWrite","position","writeRGB","highByte","writeRed","setSpeed","readBlue","noStroke","remoteIP","transfer","shutdown","hangCall","beginSMS","endWrite","attached","maintain","noCursor","checkReg","checkPUK","shiftOut","isValid","shiftIn","pulseIn","connect","println","localIP","pinMode","getIMEI","display","noBlink","process","getBand","running","beginSD","drawBMP","lowByte","setBand","release","bitRead","prepare","pointTo","readRed","setMode","noFill","remove","listen","stroke","detach","attach","noTone","exists","buffer","height","bitSet","circle","config","cursor","random","IRread","setDNS","endSMS","getKey","micros","millis","begin","print","write","ready","flush","width","isPIN","blink","clear","press","mkdir","rmdir","close","point","yield","image","BSSID","click","delay","read","text","move","peek","beep","rect","line","open","seek","fill","size","turn","stop","home","find","step","tone","sqrt","RSSI","SSID","end","bit","tan","cos","sin","pow","map","abs","max","min","get","run","put"],literal:["DIGITAL_MESSAGE","FIRMATA_STRING","ANALOG_MESSAGE","REPORT_DIGITAL","REPORT_ANALOG","INPUT_PULLUP","SET_PIN_MODE","INTERNAL2V56","SYSTEM_RESET","LED_BUILTIN","INTERNAL1V1","SYSEX_START","INTERNAL","EXTERNAL","DEFAULT","OUTPUT","INPUT","HIGH","LOW"]},n=mLe(e),r=n.keywords;return r.type=[...r.type,...t.type],r.literal=[...r.literal,...t.literal],r.built_in=[...r.built_in,...t.built_in],r._hints=t._hints,n.name="Arduino",n.aliases=["ino"],n.supersetOf="cpp",n}function xLe(e){const t=e.regex,n={},r={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[n]}]};Object.assign(n,{className:"variable",variants:[{begin:t.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},r]});const a={className:"subst",begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},i=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),o={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},l={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,n,a]};a.contains.push(l);const c={match:/\\"/},u={className:"string",begin:/'/,end:/'/},d={match:/\\'/},h={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},e.NUMBER_MODE,n]},f=["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"],m=e.SHEBANG({binary:`(${f.join("|")})`,relevance:10}),x={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0},g=["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],y=["true","false"],b={match:/(\/[a-z._-]+)+/},v=["break","cd","continue","eval","exec","exit","export","getopts","hash","pwd","readonly","return","shift","test","times","trap","umask","unset"],w=["alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias"],_=["autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","echotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp"],k=["chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors","ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link","logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"];return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:g,literal:y,built_in:[...v,...w,"set","shopt",..._,...k]},contains:[m,e.SHEBANG(),x,h,i,o,b,l,c,u,d,n]}}function gLe(e){const t=e.regex,n=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}
vendor: 5,534 bytes, line 884
884),r="decltype\\(auto\\)",a="[a-zA-Z_]\\w*::",o="("+r+"|"+t.optional(a)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",l={className:"type",variants:[{begin:"\\b[a-z\\d_]*_t\\b"},{match:/\batomic_[a-z]{3,6}\b/}]},u={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},d={className:"number",variants:[{match:/\b(0b[01']+)/},{match:/(-?)\b([\d']+(\.[\d']*)?|\.[\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)/},{match:/(-?)\b(0[xX][a-fA-F0-9]+(?:'[a-fA-F0-9]+)*(?:\.[a-fA-F0-9]*(?:'[a-fA-F0-9]*)*)?(?:[pP][-+]?[0-9]+)?(l|L)?(u|U)?)/},{match:/(-?)\b\d+(?:'\d+)*(?:\.\d*(?:'\d*)*)?(?:[eE][-+]?\d+)?/}],relevance:0},h={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef elifdef elifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(u,{className:"string"}),{className:"string",begin:/<.*?>/},n,e.C_BLOCK_COMMENT_MODE]},f={className:"title",begin:t.optional(a)+e.IDENT_RE,relevance:0},m=t.optional(a)+e.IDENT_RE+"\\s*\\(",y={keyword:["asm","auto","break","case","continue","default","do","else","enum","extern","for","fortran","goto","if","inline","register","restrict","return","sizeof","typeof","typeof_unqual","struct","switch","typedef","union","volatile","while","_Alignas","_Alignof","_Atomic","_Generic","_Noreturn","_Static_assert","_Thread_local","alignas","alignof","noreturn","static_assert","thread_local","_Pragma"],type:["float","double","signed","unsigned","int","short","long","char","void","_Bool","_BitInt","_Complex","_Imaginary","_Decimal32","_Decimal64","_Decimal96","_Decimal128","_Decimal64x","_Decimal128x","_Float16","_Float32","_Float64","_Float128","_Float32x","_Float64x","_Float128x","const","static","constexpr","complex","bool","imaginary"],literal:"true false NULL",built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr"},b=[h,l,n,e.C_BLOCK_COMMENT_MODE,d,u],v={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:y,contains:b.concat([{begin:/\(/,end:/\)/,keywords:y,contains:b.concat(["self"]),relevance:0}]),relevance:0},w={begin:"("+o+"[\\*&\\s]+)+"+m,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:y,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:y,relevance:0},{begin:m,returnBegin:!0,contains:[e.inherit(f,{className:"title.function"})],relevance:0},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:y,relevance:0,contains:[n,e.C_BLOCK_COMMENT_MODE,u,d,l,{begin:/\(/,end:/\)/,keywords:y,relevance:0,contains:["self",n,e.C_BLOCK_COMMENT_MODE,u,d,l]}]},l,n,e.C_BLOCK_COMMENT_MODE,h]};return{name:"C",aliases:["h"],keywords:y,disableAutodetect:!0,illegal:"</",contains:[].concat(v,w,b,[h,{begin:e.IDENT_RE+"::",keywords:y},{className:"class",beginKeywords:"enum class struct union",end:/[{;:<>=]/,contains:[{beginKeywords:"final class struct"},e.TITLE_MODE]}]),exports:{preprocessor:h,strings:u,keywords:y}}}function yLe(e){const t=e.regex,n=e.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),r="decltype\\(auto\\)",a="[a-zA-Z_]\\w*::",o="(?!struct)("+r+"|"+t.optional(a)+"[a-zA-Z_]\\w*"+t.optional("<[^<>]+>")+")",l={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},u={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]},{begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},e.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,end:/\)([^()\\ ]{0,16})"/})]},d={className:"number",variants:[{begin:"[+-]?(?:(?:[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},h={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(u,{className:"string"}),{className:"string",begin:/<.*?>/},n,e.C_BLOCK_COMMENT_MODE]},f={className:"title",begin:t.optional(a)+e.IDENT_RE,relevance:0},m=t.optional(a)+e.IDENT_RE+"\\s*\\(",x=["alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_
884noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator","or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],g=["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t","unsigned","signed","const","static"],y=["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_future","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"],b=["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod","forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat","strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"],_={type:g,keyword:x,literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:y},k={className:"function.dispatch",relevance:0,keywords:{_hint:b},begin:t.concat(/\b/,`(?!${x.join("|")})`,e.IDENT_RE,t.lookahead(/(<[^<>]+>|)\s*\(/))},j=[k,h,l,n,e.C_BLOCK_COMMENT_MODE,d,u],N={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:_,contains:j.concat([{begin:/\(/,end:/\)/,keywords:_,contains:j.concat(["self"]),relevance:0}]),relevance:0},E={className:"function",begin:"("+o+"[\\*&\\s]+)+"+m,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:_,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:r,keywords:_,relevance:0},{begin:m,returnBegin:!0,contains:[f],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[u,d]},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:_,relevance:0,contains:[n,e.C_BLOCK_COMMENT_MODE,u,d,l,{begin:/\(/,end:/\)/,keywords:_,relevance:0,contains:["self",n,e.C_BLOCK_COMMENT_MODE,u,d,l]}]},l,n,e.C_BLOCK_COMMENT_MODE,h]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:_,illegal:"</",classNameAliases:{"function.dispatch":"built_in"},contains:[].concat(N,E,k,j,[h,{begin:"\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",end:">",keywords:_,contains:["self",l]},{begin:e.IDENT_RE+"::",keywords:_},{match:[/\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}function bLe(e){const t=["bool","byte","char","decimal","delegate","double","dynamic","enum","float","int","long","nint","nuint","object","sbyte","short","string","ulong","uint","ushort"],n=["public","private","protected","static","internal","protected","abstract","async","extern","override","unsafe","virtual","new","sealed","partial"],r=["default","false","null","true"],a=["abstract","as","base","break","case","catch","class","const","continue","do","else","event","explicit","extern","finally","fixed","for","foreach","goto","if","implicit","in","interface","internal","is","lock","namespace","new","operator","out","override","params","private","protected","public","readonly","record","ref","return","scoped","sealed","
884sizeof","stackalloc","static","struct","switch","this","throw","try","typeof","unchecked","unsafe","using","virtual","void","volatile","while"],i=["add","alias","and","ascending","args","async","await","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","nameof","not","notnull","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value|0","var","when","where","with","yield"],o={keyword:a.concat(i),built_in:t,literal:r},l=e.inherit(e.TITLE_MODE,{begin:"[a-zA-Z](\\.?\\w)*"}),c={className:"number",variants:[{begin:"\\b(0b[01']+)"},{begin:"(-?)\\b([\\d']+(\\.[\\d']*)?|\\.[\\d']+)(u|U|l|L|ul|UL|f|F|b|B)"},{begin:"(-?)(\\b0[xX][a-fA-F0-9'_]+|(\\b[\\d'_]+(\\.[\\d'_]*)?|\\.[\\d'_]+)([eE][-+]?[\\d'_]+)?)"}],relevance:0},u={className:"string",begin:/"""("*)(?!")(.|\n)*?"""\1/,relevance:1},d={className:"string",begin:'@"',end:'"',contains:[{begin:'""'}]},h=e.inherit(d,{illegal:/\n/}),f={className:"subst",begin:/\{/,end:/\}/,keywords:o},m=e.inherit(f,{illegal:/\n/}),x={className:"string",begin:/\$"/,end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},e.BACKSLASH_ESCAPE,m]},g={className:"string",begin:/\$@"/,end:'"',contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},f]},y=e.inherit(g,{illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},m]});f.contains=[g,x,d,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,c,e.C_BLOCK_COMMENT_MODE],m.contains=[y,x,h,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,c,e.inherit(e.C_BLOCK_COMMENT_MODE,{illegal:/\n/})];const b={variants:[u,g,x,d,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},v={begin:"<",end:">",contains:[{beginKeywords:"in out"},l]},w=e.IDENT_RE+"(<"+e.IDENT_RE+"(\\s*,\\s*"+e.IDENT_RE+")*>)?(\\[\\])?",_={begin:"@"+e.IDENT_RE,relevance:0};return{name:"C#",aliases:["cs","c#"],keywords:o,illegal:/::/,contains:[e.COMMENT("///","$",{returnBegin:!0,contains:[{className:"doctag",variants:[{begin:"///",relevance:0},{begin:"<!--|-->"},{begin:"</?",end:">"}]}]}),e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"meta",begin:"#",end:"$",keywords:{keyword:"if else elif endif define undef warning error line region endregion pragma checksum"}},b,c,{beginKeywords:"class interface",relevance:0,end:/[{;=]/,illegal:/[^\s:,]/,contains:[{beginKeywords:"where class"},l,v,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"namespace",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[l,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"record",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[l,v,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"meta",begin:"^\\s*\\[(?=[\\w])",excludeBegin:!0,end:"\\]",excludeEnd:!0,contains:[{className:"string",begin:/"/,end:/"/}]},{beginKeywords:"new return throw await else",relevance:0},{className:"function",begin:"("+w+"\\s+)+"+e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,end:/\s*[{;=]/,excludeEnd:!0,keywords:o,contains:[{beginKeywords:n.join(" "),relevance:0},{begin:e.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,contains:[e.TITLE_MODE,v],relevance:0},{match:/\(\)/},{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:o,relevance:0,contains:[b,c,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},_]}}const vLe=e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},UNICODE_RANGE:{scope:"number",begin:/\b[Uu]\+[0-9A-Fa-f][0-9A-Fa-f?]{0,4}(-[0-9A-Fa-f][0-9A-Fa-f]{0,4})?/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),wLe=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],_Le=["def
884s","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],kLe=[...wLe,..._Le],jLe=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),NLe=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),SLe=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),CLe=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-
884area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","unicode-range","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function ELe(e){const t=e.regex,n=vLe(e),r={begin:/-(webkit|moz|ms|o)-(?=[a-z])/},a="and or not only",i=/@-?\w[\w]*(-\w+)*/,o="[a-zA-Z-][a-zA-Z0-9_-]*",l=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return{name:"CSS",case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:"from to"},classNameAliases:{keyframePosition:"selector-tag"},contains:[n.BLOCK_COMMENT,r,n.CSS_NUMBER_MODE,{className:"selector-id",begin:/#[A-Za-z0-9_-]+/,relevance:0}
vendor: 8,779 bytes, line 884
884,{className:"selector-class",begin:"\\."+o,relevance:0},n.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",variants:[{begin:":("+NLe.join("|")+")"},{begin:":(:)?("+SLe.join("|")+")"}]},n.CSS_VARIABLE,{className:"attribute",begin:"\\b("+CLe.join("|")+")\\b"},{begin:/:/,end:/[;}{]/,contains:[n.BLOCK_COMMENT,n.HEXCOLOR,n.IMPORTANT,n.CSS_NUMBER_MODE,n.UNICODE_RANGE,...l,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:"url data-uri"},contains:[...l,{className:"string",begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},n.FUNCTION_DISPATCH]},{begin:t.lookahead(/@/),end:"[{;]",relevance:0,illegal:/:/,contains:[{className:"keyword",begin:i},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:a,attribute:jLe.join(" ")},contains:[{begin:/[a-z-]+(?=:)/,className:"attribute"},...l,n.CSS_NUMBER_MODE]}]},{className:"selector-tag",begin:"\\b("+kLe.join("|")+")\\b"}]}}function ALe(e){const t=e.regex;return{name:"Diff",aliases:["patch"],contains:[{className:"meta",relevance:10,match:t.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^@@ +-\d+ +\+\d+,\d+ +@@/,/^@@ +-\d+,\d+ +\+\d+ +@@/,/^@@ +-\d+ +\+\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:"comment",variants:[{begin:t.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:"addition",begin:/^\+/,end:/$/},{className:"deletion",begin:/^-/,end:/$/},{className:"addition",begin:/^!/,end:/$/}]}}function TLe(e){const i={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","complex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return{name:"Go",aliases:["golang"],keywords:i,illegal:"</",contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"string",variants:[e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,{begin:"`",end:"`"}]},{className:"number",variants:[{match:/-?\b0[xX]\.[a-fA-F0-9](_?[a-fA-F0-9])*[pP][+-]?\d(_?\d)*i?/,relevance:0},{match:/-?\b0[xX](_?[a-fA-F0-9])+((\.([a-fA-F0-9](_?[a-fA-F0-9])*)?)?[pP][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b0[oO](_?[0-7])*i?/,relevance:0},{match:/-?\.\d(_?\d)*([eE][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b\d(_?\d)*(\.(\d(_?\d)*)?)?([eE][+-]?\d(_?\d)*)?i?/,relevance:0}]},{begin:/:=/},{className:"function",beginKeywords:"func",end:"\\s*(\\{|$)",excludeEnd:!0,contains:[e.TITLE_MODE,{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:i,illegal:/["']/}]}]}}function OLe(e){const t=e.regex,n=/[_A-Za-z][_0-9A-Za-z]*/;return{name:"GraphQL",aliases:["gql"],case_insensitive:!0,disableAutodetect:!1,keywords:{keyword:["query","mutation","subscription","type","input","schema","directive","interface","union","scalar","fragment","enum","on"],literal:["true","false","null"]},contains:[e.HASH_COMMENT_MODE,e.QUOTE_STRING_MODE,e.NUMBER_MODE,{scope:"punctuation",match:/[.]{3}/,relevance:0},{scope:"punctuation",begin:/[\!\(\)\:\=\[\]\{\|\}]{1}/,relevance:0},{scope:"variable",begin:/\$/,end:/\W/,excludeEnd:!0,relevance:0},{scope:"meta",match:/@\w+/,excludeEnd:!0},{scope:"symbol",begin:t.concat(n,t.lookahead(/\s*:/)),relevance:0}],illegal:[/[;<']/,/BEGIN/]}}function ILe(e){const t=e.regex,n={className:"number",relevance:0,variants:[{begin:/([+-]+)?[\d]+_[\d_]+/},{begin:e.NUMBER_RE}]},r=e.COMMENT();r.variants=[{begin:/;/,end:/$/},{begin:/#/,end:/$/}];const a={className:"variable",variants:[{begin:/\$[\w\d"][\w\d_]*/},{begin:/\$\{(.*?)\}/}]},i={className:"literal",begin:/\bon|off|true|false|yes|no\b/},o={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:"'''",end:"'''",relevance:10},{begin:'"""',end:'"""',relevance:10},{begin:'"',end:'"'},{begin:"'",end:"'"}]},l={begin:/\[/,end:/\]/,contains:[r,i,a,o,n,"self"],relevance:0},c=/[A-Za-z0-9_-]+/,u=/"(\\"|[^"])*"/,d=/'[^']*'/,h=t.either(c,u,d),f=t.concat(h,"(\\s*\\.\\s*",h,")*",t.lookahead(/\s*=\s*[^#\s]/));return{name:"TOML, also INI",aliases:["toml"],case_insensitive:!0,illegal:/\S/,contains:[r,{className:"section",begin:/\[+/,end:/\]+/},{begin:f,className:"attr",starts:{end:/$/,contains:[r,l,i,a,o,n]}}]}}var wh="[0-9](_*[0-9])*",Lg=`\\.(${wh})`,Fg="[0-9a-fA-F](_*[0-9a-fA-F])*",OM={className:"number",variants:[{begin:`(\\b(${wh})((${Lg})|\\.)?|(${Lg}))[eE][+-]?(${wh})[fFdD]?\\b`},{begin:`\\b(${wh})((${Lg})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${Lg})[fFdD]?\\b`},{begin:`\\b(${wh})[fFdD]\\b`},{begin:`\\b0[xX]((${Fg})\\.?|(${Fg})?\\.(${Fg}))[pP][+-]?(${wh})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${Fg})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function GH(e,t,n){return n===-1?"":e.replace(t,r=>GH(e,t,n-1))}function PLe(e){const t=e.regex,n="[Ã-ʸa-zA-Z_$][Ã-ʸa-zA-Z_$0-9]*",r=n+GH("(?:<"+n+"~~~(?:\\s*,\\s*"+n+"~~~)*>)?",/~~~/g,2),c={keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","default","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"],literal:["false","true","null"],type:["char","boolean","long","float","int","byte","short","double"],built_in:["super","this"]},u={className:"meta",begin:"@"+n,contains:[{begin:/\(/,end:/\)/,contains:["self"]}]},d={className:"params",begin:/\(/,end:/\)/,keywords:c,relevance:0,contains:[e.C_BLOCK_COMMENT_MODE],endsParent:!0};return{name:"Java",aliases:["jsp"],keywords:c,illegal:/<\/|#/,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{begin:/import java\.[a-z]+\./,keywords:"import",relevance:2},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/,className:"string",contains:[e.BACKSLASH_ESCAPE]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{match:[/\b(?:class|interface|enum|extends|implements|new)/,/\s+/,n],className:{1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{begin:[t.concat(/(?!else)/,n),/\s+/,n,/\s+/,/=(?!=)/],className:{1:"type",3:"variable",5:"operator"}},{begin:[/record/,/\s+/,n],className:{1:"keyword",3:"title.class"},contains:[d,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{beginKeywords:"new throw return else",relevance:0},{begin:["(?:"+r+"\\s+)",e.UNDERSCORE_IDENT_RE,/\s*(?=\()/],className:{2:"title.function"},keywords:c,contains:[{className:"params",begin:/\(/,end:/\)/,keywords:c,relevance:0,contains:[u,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,OM,e.C_BLOCK_COMMENT_MODE]},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},OM,u]}}const IM="[A-Za-z$_][0-9A-Za-z$_]*",RLe=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],DLe=["true","false","null","undefined","NaN","Infinity"],YH=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],ZH=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],XH=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],MLe=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],$Le=[].concat(XH,YH,ZH);function LLe(e){const t=e.regex,n=(F,{after:Z})=>{const D="</"+F[0].slice(1);return F.input.indexOf(D,Z)!==-1},r=IM,a={begin:"<>",end:"</>"},i=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(F,Z)=>{const D=F[0].length+F.index,H=F.input[D];if(H==="<"||H===","){Z.ignoreMatch();return}H===">
884"&&(n(F,{after:D})||Z.ignoreMatch());let Y;const M=F.input.substring(D);if(Y=M.match(/^\s*=/)){Z.ignoreMatch();return}if((Y=M.match(/^\s+extends\s+/))&&Y.index===0){Z.ignoreMatch();return}}},l={$pattern:IM,keyword:RLe,literal:DLe,built_in:$Le,"variable.language":MLe},c="[0-9](_?[0-9])*",u=`\\.(${c})`,d="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",h={className:"number",variants:[{begin:`(\\b(${d})((${u})|\\.)?|(${u}))[eE][+-]?(${c})\\b`},{begin:`\\b(${d})\\b((${u})\\b|\\.)?|(${u})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},f={className:"subst",begin:"\\$\\{",end:"\\}",keywords:l,contains:[]},m={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:"xml"}},x={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:"css"}},g={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:"graphql"}},y={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,f]},v={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:r+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},w=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,m,x,g,y,{match:/\$\d+/},h];f.contains=w.concat({begin:/\{/,end:/\}/,keywords:l,contains:["self"].concat(w)});const _=[].concat(v,f.contains),k=_.concat([{begin:/(\s*)\(/,end:/\)/,keywords:l,contains:["self"].concat(_)}]),j={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:k},N={variants:[{match:[/class/,/\s+/,r,/\s+/,/extends/,/\s+/,t.concat(r,"(",t.concat(/\./,r),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,r],scope:{1:"keyword",3:"title.class"}}]},E={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...YH,...ZH]}},A={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},C={variants:[{match:[/function/,/\s+/,r,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[j],illegal:/%/},T={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function S(F){return t.concat("(?!",F.join("|"),")")}const O={match:t.concat(/\b/,S([...XH,"super","import","await"].map(F=>`${F}\\s*\\(`)),r,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},R={begin:t.concat(/\./,t.lookahead(t.concat(r,/(?![0-9A-Za-z$_(])/))),end:r,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},I={match:[/get|set/,/\s+/,r,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},j]},$="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",P={match:[/const|var|let/,/\s+/,r,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead($)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[j]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:l,exports:{PARAMS_CONTAINS:k,CLASS_REFERENCE:E},illegal:/#(?![$_A-Za-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),A,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,m,x,g,y,v,{match:/\$\d+/},h,E,{scope:"attr",match:r+t.lookahead(":"),relevance:0},P,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[v,e.REGEXP_MODE,{className:"function",begin:$,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:k}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:a.begin,end:a.end},{match:i},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:"xml",contains:[{begin:o.begin,end:o.end,skip:!0,contains:["self"]}]}]},C,{beginKeywords:"while if switch catch for"}
vendor: 4,124 bytes, line 884
884,{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[j,e.inherit(e.TITLE_MODE,{begin:r,className:"title.function"})]},{match:/\.\.\./,relevance:0},R,{match:"\\$"+r,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[j]},O,T,N,I,{match:/\$[(.]/}]}}const FLe="([-+]?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)|NaN|[-+]?Infinity",BLe={scope:"number",match:FLe,relevance:0};function ULe(e){const t={className:"attr",begin:/(("(\\.|[^\\"\r\n])*")|('(\\.|[^\\'\r\n])*'))(?=\s*:)/,relevance:1.01},n={match:/[{}[\],:]/,className:"punctuation",relevance:0},r=["true","false","null"],a={scope:"literal",beginKeywords:r.join(" ")};return{name:"JSON",aliases:["jsonc","json5"],keywords:{literal:r},contains:[t,n,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,a,BLe,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}var _h="[0-9](_*[0-9])*",Bg=`\\.(${_h})`,Ug="[0-9a-fA-F](_*[0-9a-fA-F])*",zLe={className:"number",variants:[{begin:`(\\b(${_h})((${Bg})|\\.)?|(${Bg}))[eE][+-]?(${_h})[fFdD]?\\b`},{begin:`\\b(${_h})((${Bg})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${Bg})[fFdD]?\\b`},{begin:`\\b(${_h})[fFdD]\\b`},{begin:`\\b0[xX]((${Ug})\\.?|(${Ug})?\\.(${Ug}))[pP][+-]?(${_h})[fFdD]?\\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${Ug})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function WLe(e){const t={keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed internal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing",literal:"true false null"},n={className:"keyword",begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol",begin:/@\w+/}]}},r={className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"@"},a={className:"subst",begin:/\$\{/,end:/\}/,contains:[e.C_NUMBER_MODE]},i={className:"variable",begin:"\\$"+e.UNDERSCORE_IDENT_RE},o={className:"string",variants:[{begin:'"""',end:'"""(?=[^"])',contains:[i,a]},{begin:"'",end:"'",illegal:/\n/,contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/,contains:[e.BACKSLASH_ESCAPE,i,a]}]};a.contains.push(o);const l={className:"meta",begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+e.UNDERSCORE_IDENT_RE+")?"},c={className:"meta",begin:"@"+e.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/,end:/\)/,contains:[e.inherit(o,{className:"string"}),"self"]}]},u=zLe,d=e.COMMENT("/\\*","\\*/",{contains:[e.C_BLOCK_COMMENT_MODE]}),h={variants:[{className:"type",begin:e.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/,contains:[]}]},f=h;return f.variants[1].contains=[h],h.variants[1].contains=[f],{name:"Kotlin",aliases:["kt","kts"],keywords:t,contains:[e.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"}]}),e.C_LINE_COMMENT_MODE,d,n,r,l,c,{className:"function",beginKeywords:"fun",end:"[(]|$",returnBegin:!0,excludeEnd:!0,keywords:t,relevance:5,contains:[{begin:e.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,relevance:0,contains:[e.UNDERSCORE_TITLE_MODE]},{className:"type",begin:/</,end:/>/,keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:t,relevance:0,contains:[{begin:/:/,end:/[=,\/]/,endsWithParent:!0,contains:[h,e.C_LINE_COMMENT_MODE,d],relevance:0},e.C_LINE_COMMENT_MODE,d,l,c,o,e.C_NUMBER_MODE]},d]},{begin:[/class|interface|trait/,/\s+/,e.UNDERSCORE_IDENT_RE],beginScope:{3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0,illegal:"extends implements",contains:[{beginKeywords:"public protected internal private constructor"},e.UNDERSCORE_TITLE_MODE,{className:"type",begin:/</,end:/>/,excludeBegin:!0,excludeEnd:!0,relevance:0}
vendor: 7,614 bytes, lines 884-885
884,{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/,excludeBegin:!0,returnEnd:!0},l,c]},o,{className:"meta",begin:"^#!/usr/bin/env",end:"$",illegal:` 885`},u]}}const KLe=e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},UNICODE_RANGE:{scope:"number",begin:/\b[Uu]\+[0-9A-Fa-f][0-9A-Fa-f?]{0,4}(-[0-9A-Fa-f][0-9A-Fa-f]{0,4})?/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),HLe=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],VLe=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],qLe=[...HLe,...VLe],GLe=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),JH=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invalid","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),QH=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),YLe=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-
885area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","unicode-range","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse(),ZLe=JH.concat(QH).sort().reverse();function XLe(e){const t=KLe(e),n=ZLe,r="and or not only",a="[\\w-]+",i="("+a+"|@\\{"+a+"\\})",o=[],l=[],c=function(w){return{className:"string",begin:"~?"+w+".*?"+w}},u=function(w,_,k){return{className:w,begin:_,relevance:k}},d={$pattern:/[a-z-]+/,keyword:r,attribute:GLe.join(" ")},h={begin:"\\(",end:"\\)",contains:l,keywords:d,relevance:0};l.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,c("'"),c('"'),t.CSS_NUMBER_MODE,{begin:"(url|data-uri)\\(",starts:{className:"string",end:"[\\)\\n]",excludeEnd:!0}}
vendor: 36,953 bytes, lines 885-886
885,t.UNICODE_RANGE,t.HEXCOLOR,h,u("variable","@@?"+a,10),u("variable","@\\{"+a+"\\}"),u("built_in","~?`[^`]*?`"),{className:"attribute",begin:a+"\\s*:",end:":",returnBegin:!0,excludeEnd:!0},t.IMPORTANT,{beginKeywords:"and not"},t.FUNCTION_DISPATCH);const f=l.concat({begin:/\{/,end:/\}/,contains:o}),m={beginKeywords:"when",endsWithParent:!0,contains:[{beginKeywords:"and not"}].concat(l)},x={begin:i+"\\s*:",returnBegin:!0,end:/[;}]/,relevance:0,contains:[{begin:/-(webkit|moz|ms|o)-/},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+YLe.join("|")+")\\b",end:/(?=:)/,starts:{endsWithParent:!0,illegal:"[<=$]",relevance:0,contains:l}}]},g={className:"keyword",begin:"@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b",starts:{end:"[;{}]",keywords:d,returnEnd:!0,contains:l,relevance:0}},y={className:"variable",variants:[{begin:"@"+a+"\\s*:",relevance:15},{begin:"@"+a}],starts:{end:"[;}]",returnEnd:!0,contains:f}},b={variants:[{begin:"[\\.#:&\\[>]",end:"[;{}]"},{begin:i,end:/\{/}],returnBegin:!0,returnEnd:!0,illegal:`[<='$"]`,relevance:0,contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,m,u("keyword","all\\b"),u("variable","@\\{"+a+"\\}"),{begin:"\\b("+qLe.join("|")+")\\b",className:"selector-tag"},t.CSS_NUMBER_MODE,u("selector-tag",i,0),u("selector-id","#"+i),u("selector-class","\\."+i,0),u("selector-tag","&",0),t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-pseudo",begin:":("+JH.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+QH.join("|")+")"},{begin:/\(/,end:/\)/,relevance:0,contains:f},{begin:"!important"},t.FUNCTION_DISPATCH]},v={begin:a+`:(:)?(${n.join("|")})`,returnBegin:!0,contains:[b]};return o.push(e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,g,y,v,x,b,m,t.FUNCTION_DISPATCH),{name:"Less",case_insensitive:!0,illegal:`[=>'/<($"]`,contains:o}}function JLe(e){const t="\\[=*\\[",n="\\]=*\\]",r={begin:t,end:n,contains:["self"]},a=[e.COMMENT("--(?!"+t+")","$"),e.COMMENT("--"+t,n,{contains:[r],relevance:10})];return{name:"Lua",aliases:["pluto"],keywords:{$pattern:e.UNDERSCORE_IDENT_RE,literal:"true false nil",keyword:"and break do else elseif end for goto if in local not or repeat return then until while",built_in:"_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove"},contains:a.concat([{className:"function",beginKeywords:"function",end:"\\)",contains:[e.inherit(e.TITLE_MODE,{begin:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),{className:"params",begin:"\\(",endsWithParent:!0,contains:a}].concat(a)},e.C_NUMBER_MODE,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,{className:"string",begin:t,end:n,contains:[r],relevance:5}])}}function QLe(e){const t={className:"variable",variants:[{begin:"\\$\\("+e.UNDERSCORE_IDENT_RE+"\\)",contains:[e.BACKSLASH_ESCAPE]},{begin:/\$[@%<?\^\+\*]/}]},n={className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,t]},r={className:"variable",begin:/\$\([\w-]+\s/,end:/\)/,keywords:{built_in:"subst patsubst strip findstring filter filter-out sort word wordlist firstword lastword dir notdir suffix basename addsuffix addprefix join wildcard realpath abspath error warning shell origin flavor foreach if or and call eval file value"},contains:[t,n]},a={begin:"^"+e.UNDERSCORE_IDENT_RE+"\\s*(?=[:+?]?=)"},i={className:"meta",begin:/^\.PHONY:/,end:/$/,keywords:{$pattern:/[\.\w]+/,keyword:".PHONY"}},o={className:"section",begin:/^[^\s]+:/,end:/$/,contains:[t]};return{name:"Makefile",aliases:["mk","mak","make"],keywords:{$pattern:/[\w-]+/,keyword:"define endef undefine ifdef ifndef ifeq ifneq else endif include -include sinclude override export unexport private vpath"},contains:[e.HASH_COMMENT_MODE,t,n,r,a,i,o]}}function e8e(e){const t=e.regex,n={begin:/<\/?[A-Za-z_]/,end:">",subLanguage:"xml",relevance:0},r={begin:"^[-\\*]{3,}",end:"$"},a={className:"code",variants:[{begin:"(`{3,})[^`](.|\\n)*?\\1`*[ ]*"},{begin:"(~{3,})[^~](.|\\n)*?\\1~*[ ]*"},{begin:"```",end:"```+[ ]*$"},{begin:"~~~",end:"~~~+[ ]*$"},{begin:"`.+?`"},{begin:"(?=^( {4}|\\t))",contains:[{begin:"^( {4}|\\t)",end:"(\\n)$"}],relevance:0}]},i={className:"bullet",begin:"^[ ]*([*+-]|(\\d+\\.))(?=\\s+)",end:"\\s+",excludeEnd:!0},o={begin:/^\[[^\n]+\]:/,returnBegin:!0,contains:[{className:"symbol",begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0},{className:"link",begin:/:\s*/,end:/$/,excludeBegin:!0}]},l=/[A-Za-z][A-Za-z0-9+.-]*/,c={variants:[{begin:/\[.+?\]\[.*?\]/,relevance:0},{begin:/\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,relevance:2},{begin:t.concat(/\[.+?\]\(/,l,/:\/\/.*?\)/),relevance:2},{begin:/\[.+?\]\([./?&#].*?\)/,relevance:1},{begin:/\[.*?\]\(.*?\)/,relevance:0}],returnBegin:!0,contains:[{match:/\[(?=\])/},{className:"string",relevance:0,begin:"\\[",end:"\\]",excludeBegin:!0,returnEnd:!0},{className:"link",relevance:0,begin:"\\]\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0},{className:"symbol",relevance:0,begin:"\\]\\[",end:"\\]",excludeBegin:!0,excludeEnd:!0}]},u={className:"strong",contains:[],variants:[{begin:/_{2}(?!\s)/,end:/_{2}/},{begin:/\*{2}(?!\s)/,end:/\*{2}/}]},d={className:"emphasis",contains:[],variants:[{begin:/\*(?![*\s])/,end:/\*/},{begin:/_(?![_\s])/,end:/_/,relevance:0}]},h=e.inherit(u,{contains:[]}),f=e.inherit(d,{contains:[]});u.contains.push(f),d.contains.push(h);let m=[n,c];return[u,d,h,f].forEach(b=>{b.contains=b.contains.concat(m)}),m=m.concat(u,d),{name:"Markdown",aliases:["md","mkdown","mkd"],contains:[{className:"section",variants:[{begin:"^#{1,6}",end:"$",contains:m},{begin:"(?=^.+?\\n[=-]{2,}$)",contains:[{begin:"^[=-]*$"},{begin:"^",end:"\\n",contains:m}]}]},n,i,u,d,{className:"quote",begin:"^>\\s+",contains:m,end:"$"},a,r,c,o,{scope:"literal",match:/&([a-zA-Z0-9]+|#[0-9]{1,7}|#[Xx][0-9a-fA-F]{1,6});/}]}}function t8e(e){const t={className:"built_in",begin:"\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+"},n=/[a-zA-Z@][a-zA-Z0-9_]*/,l={"variable.language":["this","super"],$pattern:n,keyword:["while","export","sizeof","typedef","const","struct","for","union","volatile","static","mutable","if","do","return","goto","enum","else","break","extern","asm","case","default","register","explicit","typename","switch","continue","inline","readonly","assign","readwrite","self","@synchronized","id","typeof","nonatomic","IBOutlet","IBAction","strong","weak","copy","in","out","inout","bycopy","byref","oneway","__strong","__weak","__block","__autoreleasing","@private","@protected","@public","@try","@property","@end","@throw","@catch","@finally","@autoreleasepool","@synthesize","@dynamic","@selector","@optional","@required","@encode","@package","@import","@defs","@compatibility_alias","__bridge","__bridge_transfer","__bridge_retained","__bridge_retain","__covariant","__contravariant","__kindof","_Nonnull","_Nullable","_Null_unspecified","__FUNCTION__","__PRETTY_FUNCTION__","__attribute__","getter","setter","retain","unsafe_unretained","nonnull","nullable","null_unspecified","null_resettable","class","instancetype","NS_DESIGNATED_INITIALIZER","NS_UNAVAILABLE","NS_REQUIRES_SUPER","NS_RETURNS_INNER_POINTER","NS_INLINE","NS_AVAILABLE","NS_DEPRECATED","NS_ENUM","NS_OPTIONS","NS_SWIFT_UNAVAILABLE","NS_ASSUME_NONNULL_BEGIN","NS_ASSUME_NONNULL_END","NS_REFINED_FOR_SWIFT","NS_SWIFT_NAME","NS_SWIFT_NOTHROW","NS_DURING","NS_HANDLER","NS_ENDHANDLER","NS_VALUERETURN","NS_VOIDRETURN"],literal:["false","true","FALSE","TRUE","nil","YES","NO","NULL"],built_in:["dispatch_once_t","dispatch_queue_t","dispatch_sync","dispatch_async","dispatch_once"],type:["int","float","char","unsigned","signed","short","long","double","wchar_t","unichar","void","bool","BOOL","id|0","_Bool"]},c={$pattern:n,keyword:["@interface","@class","@protocol","@implementation"]};return{name:"Objective-C",aliases:["mm","objc","obj-c","obj-c++","objective-c++"],keywords:l,illegal:"</",contains:[t,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,e.C_NUMBER_MODE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,{className:"string",variants:[{begin:'@"',end:'"',illegal:"\\n",contains:[e.BACKSLASH_ESCAPE]}]},{className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),{className:"string",begin:/<.*?>/,end:/$/,illegal:"\\n"},e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE]},{className:"class",begin:"("+c.keyword.join("|")+")\\b",end:/(\{|$)/,excludeEnd:!0,keywords:c,contains:[e.UNDERSCORE_TITLE_MODE]},{begin:"\\."+e.UNDERSCORE_IDENT_RE,relevance:0}]}}function n8e(e){const t=e.regex,n=["abs","accept","alarm","and","atan2","bind","binmode","bless","break","caller","chdir","chmod","chomp","chop","chown","chr","chroot","class","close","closedir","connect","continue","cos","crypt","dbmclose","dbmopen","defined","delete","die","do","dump","each","else","elsif","endgrent","endhostent","endnetent","endprotoent","endpwent","endservent","eof","eval","exec","exists","exit","exp","fcntl","field","fileno","flock","for","foreach","fork","format","formline","getc","getgrent","getgrgid","getgrnam","gethostbyaddr","gethostbyname","gethostent","getlogin","getnetbyaddr","getnetbyname","getnetent","getpeername","getpgrp","getpriority","getprotobyname","getprotobynumber","getprotoent","getpwent","getpwnam","getpwuid","getservbyname","getservbyport","getservent","getsockname","getsockopt","given","glob","gmtime","goto","grep","gt","hex","if","index","int","ioctl","join","keys","kill","last","lc","lcfirst","length","link","listen","local","localtime","log","lstat","lt","ma","map","method","mkdir","msgctl","msgget","msgrcv","msgsnd","my","ne","next","no","not","oct","open","opendir","or","ord","our","pack","package","pipe","pop","pos","print","printf","prototype","push","q|0","qq","quotemeta","qw","qx","rand","read","readdir","readline","readlink","readpipe","recv","redo","ref","rename","require","reset","return","reverse","rewinddir","rindex","rmdir","say","scalar","seek","seekdir","select","semctl","semget","semop","send","setgrent","sethostent","setnetent","setpgrp","setpriority","setprotoent","setpwent","setservent","setsockopt","shift","shmctl","shmget","shmread","shmwrite","shutdown","sin","sleep","socket","socketpair","sort","splice","split","sprintf","sqrt","srand","stat","state","study","sub","substr","symlink","syscall","sysopen","sysread","sysseek","system","syswrite","tell","telldir","tie","tied","time","times","tr","truncate","uc","ucfirst","umask","undef","unless","unlink","unpack","unshift","untie","until","use","utime","values","vec","wait","waitpid","wantarray","warn","when","while","write","x|0","xor","y|0"],r=/[dualxmsipngr]{0,12}/,a={$pattern:/[\w.]+/,keyword:n.join(" ")},i={className:"subst",begin:"[$@]\\{",end:"\\}",keywords:a},o={begin:/->\{/,end:/\}/},l={scope:"attr",match:/\s+:\s*\w+(\s*\(.*?\))?/},c={scope:"variable",variants:[{begin:/\$\d/},{begin:t.concat(/[$%@](?!")(\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,"(?![A-Za-z])(?![@$%])")},{begin:/[$%@](?!")[^\s\w{=]|\$=/,relevance:0}],contains:[l]},u={className:"number",variants:[{match:/0?\.[0-9][0-9_]+\b/},{match:/\bv?(0|[1-9][0-9_]*(\.[0-9_]+)?|[1-9][0-9_]*)\b/},{match:/\b0[0-7][0-7_]*\b/},{match:/\b0x[0-9a-fA-F][0-9a-fA-F_]*\b/},{match:/\b0b[0-1][0-1_]*\b/}],relevance:0},d=[e.BACKSLASH_ESCAPE,i,c],h=[/!/,/\//,/\|/,/\?/,/'/,/"/,/#/],f=(g,y,b="\\1")=>{const v=b==="\\1"?b:t.concat(b,y);return t.concat(t.concat("(?:",g,")"),y,/(?:\\.|[^\\\/])*?/,v,/(?:\\.|[^\\\/])*?/,b,r)},m=(g,y,b)=>t.concat(t.concat("(?:",g,")"),y,/(?:\\.|[^\\\/])*?/,b,r),x=[c,e.HASH_COMMENT_MODE,e.COMMENT(/^=\w/,/=cut/,{endsWithParent:!0}),o,{className:"string",contains:d,variants:[{begin:"q[qwxr]?\\s*\\(",end:"\\)",relevance:5},{begin:"q[qwxr]?\\s*\\[",end:"\\]",relevance:5},{begin:"q[qwxr]?\\s*\\{",end:"\\}",relevance:5},{begin:"q[qwxr]?\\s*\\|",end:"\\|",relevance:5},{begin:"q[qwxr]?\\s*<",end:">",relevance:5},{begin:"qw\\s+q",end:"q",relevance:5},{begin:"'",end:"'",contains:[e.BACKSLASH_ESCAPE]},{begin:'"',end:'"'},{begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE]},{begin:/\{\w+\}/,relevance:0},{begin:"-?\\w+\\s*=>",relevance:0}]},u,{begin:"(\\/\\/|"+e.RE_STARTERS_RE+"|\\b(split|return|print|reverse|grep)\\b)\\s*",keywords:"split return print reverse grep",relevance:0,contains:[e.HASH_COMMENT_MODE,{className:"regexp",variants:[{begin:f("s|tr|y",t.either(...h,{capture:!0}))},{begin:f("s|tr|y","\\(","\\)")},{begin:f("s|tr|y","\\[","\\]")},{begin:f("s|tr|y","\\{","\\}")}],relevance:2},{className:"regexp",variants:[{begin:/(m|qr)\/\//,relevance:0},{begin:m("(?:m|qr)?",/\//,/\//)},{begin:m("m|qr",t.either(...h,{capture:!0}),/\1/)},{begin:m("m|qr",/\(/,/\)/)},{begin:m("m|qr",/\[/,/\]/)},{begin:m("m|qr",/\{/,/\}/)}]}]},{className:"function",beginKeywords:"sub method",end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,l]},{className:"class",beginKeywords:"class",end:"[;{]",excludeEnd:!0,relevance:5,contains:[e.TITLE_MODE,l,u]},{begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$",end:"^__END__$",subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$",className:"comment"}]}];return i.contains=x,o.contains=x,{name:"Perl",aliases:["pl","pm"],keywords:a,contains:x}}function r8e(e){const t=e.regex,n=/(?![A-Za-z0-9])(?![$])/,r=t.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,n),a=t.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,n),i=t.concat(/[A-Z]+/,n),o={scope:"variable",match:"\\$+"+r},l={scope:"meta",variants:[{begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{begin:/\?>/}]},c={scope:"subst",variants:[{begin:/\$\w+/},{begin:/\{\$/,end:/\}/}]},u=e.inherit(e.APOS_STRING_MODE,{illegal:null}),d=e.inherit(e.QUOTE_STRING_MODE,{illegal:null,contains:e.QUOTE_STRING_MODE.contains.concat(c)}),h={begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/,contains:e.QUOTE_STRING_MODE.contains.concat(c),"on:begin":(R,I)=>{I.data._beginMatch=R[1]||R[2]},"on:end":(R,I)=>{I.data._beginMatch!==R[1]&&I.ignoreMatch()}},f=e.END_SAME_AS_BEGIN({begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/}),m=`[ 886]`,x={scope:"string",variants:[d,u,h,f]},g={scope:"number",variants:[{begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?"}],relevance:0},y=["false","null","true"],b=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","isset","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],v=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroError","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveDirectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess","BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],_={keyword:b,literal:(R=>{const I=[];return R.forEach($=>{I.push($),$.toLowerCase()===$?I.push($.toUpperCase()):I.push($.toLowerCase())}),I})(y),built_in:v},k=R=>R.map(I=>I.replace(/\|\d+$/,"")),j={variants:[{match:[/new/,t.concat(m,"+"),t.concat("(?!",k(v).join("\\b|"),"\\b)"),a],scope:{1:"keyword",4:"title.class"}}]},N=t.concat(r,"\\b(?!\\()"),E={variants:[{match:[t.concat(/::/,t.lookahead(/(?!class\b)/)),N],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.language"}},{match:[a,t.concat(/::/,t.lookahead(/(?!class\b)/)),N],scope:{1:"title.class",3:"variable.constant"}},{match:[a,t.concat("::",t.lookahead(/(?!class\b)/))],scope:{1:"title.class"}},{match:[a,/::/,/class/],scope:{1:"title.class",3:"variable.language"}}]},A={scope:"attr",match:t.concat(r,t.lookahead(":"),t.lookahead(/(?!::)/))},C={relevance:0,begin:/\(/,end:/\)/,keywords:_,contains:[A,o,E,e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE,e.HASH_COMMENT_MODE,x,g,j]},T={relevance:0,match:[/\b/,t.concat("(?!fn\\b|function\\b|",k(b).join("\\b|"),"|",k(v).join("\\b|"),"\\b)"),r,t.concat(m,"*"),t.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[C]};C.contains.push(T);const S=[A,E,e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE,e.HASH_COMMENT_MODE,x,g,j],O={begin:t.concat(/#\[\s*\\?/,t.either(a,i)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:y,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:y,keyword:["new","array"]},contains:["self",...S]},...S,{scope:"meta",variants:[{match:a},{match:i}]}]};return{case_insensitive:!1,keywords:_,contains:[O,e.HASH_COMMENT_MODE,e.COMMENT("//","$"),e.COMMENT("/\\*","\\*/",{contains:[{scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/,keywords:"__halt_compiler",starts:{scope:"comment",end:e.MATCH_NOTHING_RE,contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},l,{scope:"variable.language",match:/\$this\b/},o,T,E,{match:[/const/,/\s/,r],scope:{1:"keyword",3:"variable.constant"}},j,{scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/,excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use"},e.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params",begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:_,contains:["self",O,o,E,e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE,e.HASH_COMMENT_MODE,x,g]}]},{scope:"class",variants:[{beginKeywords:"enum",illegal:/[($"]/},{beginKeywords:"class interface trait",illegal:/[:($"]/}],relevance:0,end:/\{/,excludeEnd:!0,contains:[{beginKeywords:"extends implements"},e.UNDERSCORE_TITLE_MODE]},{beginKeywords:"namespace",relevance:0,end:";",illegal:/[.']/,contains:[e.inherit(e.UNDERSCORE_TITLE_MODE,{scope:"title.class"})]},{beginKeywords:"use",relevance:0,end:";",contains:[{match:/\b(as|const|function)\b/,scope:"keyword"},e.UNDERSCORE_TITLE_MODE]},x,g]}}function s8e(e){return{name:"PHP template",subLanguage:"xml",contains:[{begin:/<\?(php|=)?/,end:/\?>/,subLanguage:"php",contains:[{begin:"/\\*",end:"\\*/",skip:!0},{begin:'b"',end:'"',skip:!0},{begin:"b'",end:"'",skip:!0},e.inherit(e.APOS_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0}),e.inherit(e.QUOTE_STRING_MODE,{illegal:null,className:null,contains:null,skip:!0})]}]}}function a8e(e){return{name:"Plain text",aliases:["text","txt"],disableAutodetect:!0}}function i8e(e){const t=e.regex,n=new RegExp("[\\p{XID_Start}_]\\p{XID_Continue}*","u"),r=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],l={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:r,built_in:["__import__","abs","all","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},c={className:"meta",begin:/^(>>>|\.\.\.) /},u={className:"subst",begin:/\{/,end:/\}/,keywords:l,illegal:/#/},d={begin:/\{\{/,relevance:0},h={className:"string",contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,c],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,c],relevance:10},{begin:/([fF][rR]|[rR][fF]|[fF])'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,c,d,u]},{begin:/([fF][rR]|[rR][fF]|[fF])"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,c,d,u]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fF][rR]|[rR][fF]|[fF])'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,d,u]},{begin:/([fF][rR]|[rR][fF]|[fF])"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,d,u]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},f="[0-9](_?[0-9])*",m=`(\\b(${f}))?\\.(${f})|\\b(${f})\\.`,x=`\\b|${r.join("|")}`,g={className:"number",relevance:0,variants:[{begin:`(\\b(${f})|(${m}))[eE][+-]?(${f})[jJ]?(?=${x})`},{begin:`(${m})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${x})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${x})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${x})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${x})`},{begin:`\\b(${f})[jJ](?=${x})`}]},y={className:"comment",begin:t.lookahead(/# type:/),end:/$/,keywords:l,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},b={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:["self",c,g,h,e.HASH_COMMENT_MODE]}]};return u.contains=[h,g,c],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:l,illegal:/(<\/|\?)|=>/,contains:[c,g,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},h,y,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[b]},{variants:[{match:[/\bclass/,/\s+/,n,/\s*/,/\(\s*/,n,/\s*\)/]},{match:[/\bclass/,/\s+/,n]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[g,b,h]}]}}function o8e(e){return{aliases:["pycon"],contains:[{className:"meta.prompt",starts:{end:/ |$/,starts:{end:"$",subLanguage:"python"}},variants:[{begin:/^>>>(?=[ ]|$)/},{begin:/^\.\.\.(?=[ ]|$)/}]}]}}function l8e(e){const t=e.regex,n=/(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/,r=t.either(/0[xX][0-9a-fA-F]+\.[0-9a-fA-F]*[pP][+-]?\d+i?/,/0[xX][0-9a-fA-F]+(?:[pP][+-]?\d+)?[Li]?/,/(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?[Li]?/),a=/[=!<>:]=|\|\||&&|:::?|<-|<<-|->>|->|\|>|[-+*\/?!$&|:<=>@^~]|\*\*/,i=t.either(/[()]/,/[{}]/,/\[\[/,/[[\]]/,/\\/,/,/);return{name:"R",keywords:{$pattern:n,keyword:"function if in break next repeat else for while",literal:"NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 NA_character_|10 NA_complex_|10",built_in:"LETTERS letters month.abb month.name pi T F abs acos acosh all any anyNA Arg as.call as.character as.complex as.double as.environment as.integer as.logical as.null.default as.numeric as.raw asin asinh atan atanh attr attributes baseenv browser c call ceiling class Conj cos cosh cospi cummax cummin cumprod cumsum digamma dim dimnames emptyenv exp expression floor forceAndCall gamma gc.time globalenv Im interactive invisible is.array is.atomic is.call is.character is.complex is.double is.environment is.expression is.finite is.function is.infinite is.integer is.language is.list is.logical is.matrix is.na is.name is.nan is.null is.numeric is.object is.pairlist is.raw is.recursive is.single is.symbol lazyLoadDBfetch length lgamma list log max min missing Mod names nargs nzchar oldClass on.exit pos.to.env proc.time prod quote range Re rep retracemem return round seq_along seq_len seq.int sign signif sin sinh sinpi sqrt standardGeneric substitute sum switch tan tanh tanpi tracemem trigamma trunc unclass untracemem UseMethod xtfrm"},contains:[e.COMMENT(/#'/,/$/,{contains:[{scope:"doctag",match:/@examples/,starts:{end:t.lookahead(t.either(/\n^#'\s*(?=@[a-zA-Z]+)/,/\n^(?!#')/)),endsParent:!0}},{scope:"doctag",begin:"@param",end:/$/,contains:[{scope:"variable",variants:[{match:n},{match:/`(?:\\.|[^`\\])+`/}],endsParent:!0}]},{scope:"doctag",match:/@[a-zA-Z]+/},{scope:"keyword",match:/\\[a-zA-Z]+/}]}),e.HASH_COMMENT_MODE,{scope:"string",contains:[e.BACKSLASH_ESCAPE],variants:[e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\(/,end:/\)(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\{/,end:/\}(-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]"(-*)\[/,end:/\](-*)"/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\(/,end:/\)(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\{/,end:/\}(-*)'/}),e.END_SAME_AS_BEGIN({begin:/[rR]'(-*)\[/,end:/\](-*)'/}),{begin:'"',end:'"',relevance:0},{begin:"'",end:"'",relevance:0}]},{relevance:0,variants:[{scope:{1:"operator",2:"number"},match:[a,r]},{scope:{1:"operator",2:"number"},match:[/%[^%]*%/,r]},{scope:{1:"punctuation",2:"number"},match:[i,r]},{scope:{2:"number"},match:[/[^a-zA-Z0-9._]|^/,r]}]},{scope:{3:"operator"},match:[n,/\s+/,/<-/,/\s+/]},{scope:"operator",relevance:0,variants:[{match:a},{match:/%[^%]*%/}]},{scope:"punctuation",relevance:0,match:i},{begin:"`",end:"`",contains:[{begin:/\\./}]}]}}function c8e(e){const t=e.regex,n="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",r=t.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),a=t.concat(r,/(::\w+)*/),o={"variable.constant":["__FILE__","__LINE__","__ENCODING__"],"variable.language":["self","super"],keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end","END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield",...["include","extend","prepend","public","private","protected","raise","throw"]],built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"],literal:["true","false","nil"]},l={className:"doctag",begin:"@[A-Za-z]+"},c={begin:"#<",end:">"},u=[e.COMMENT("#","$",{contains:[l]}),e.COMMENT("^=begin","^=end",{contains:[l],relevance:10}),e.COMMENT("^__END__",e.MATCH_NOTHING_RE)],d={className:"subst",begin:/#\{/,end:/\}/,keywords:o},h={className:"string",contains:[e.BACKSLASH_ESCAPE,d],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?</,end:/>/},{begin:/%[qQwWx]?\//,end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{begin:t.concat(/<<[-~]?'?/,t.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)),contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,contains:[e.BACKSLASH_ESCAPE,d]})]}]},f="[1-9](_?[0-9])*|0",m="[0-9](_?[0-9])*",x={className:"number",relevance:0,variants:[{begin:`\\b(${f})(\\.(${m}))?([eE][+-]?(${m})|r)?i?\\b`},{begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{begin:"\\b0(_?[0-7])+r?i?\\b"}]},g={variants:[{match:/\(\)/},{className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0,keywords:o}]},j=[h,{variants:[{match:[/class\s+/,a,/\s+<\s+/,a]},{match:[/\b(class|module)\s+/,a]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:o},{match:[/(include|extend)\s+/,a],scope:{2:"title.class"},keywords:o},{relevance:0,match:[a,/\.new[. (]/],scope:{1:"title.class"}},{relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},{relevance:0,match:r,scope:"title.class"},{match:[/def/,/\s+/,n],scope:{1:"keyword",3:"title.function"},contains:[g]},{begin:e.IDENT_RE+"::"},{className:"symbol",begin:e.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[h,{begin:n}],relevance:0},x,{className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{className:"params",begin:/\|(?!=)/,end:/\|/,excludeBegin:!0,excludeEnd:!0,relevance:0,keywords:o},{begin:"("+e.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[{className:"regexp",contains:[e.BACKSLASH_ESCAPE,d],illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[",end:"\\][a-z]*"}]}].concat(c,u),relevance:0}].concat(c,u);d.contains=j,g.contains=j;const C=[{begin:/^\s*=>/,starts:{end:"$",contains:j}},{className:"meta.prompt",begin:"^("+"[>?]>"+"|"+"[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]"+"|"+"(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>"+")(?=[ ])",starts:{end:"$",keywords:o,contains:j}}];return u.unshift(c),{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:o,illegal:/\/\*/,contains:[e.SHEBANG({binary:"ruby"})].concat(C).concat(u).concat(j)}}function u8e(e){const t=e.regex,n=/(r#)?/,r=t.concat(n,e.UNDERSCORE_IDENT_RE),a=t.concat(n,e.IDENT_RE),i={className:"title.function.invoke",relevance:0,begin:t.concat(/\b/,/(?!let|for|while|if|else|match\b)/,a,t.lookahead(/\s*\(/))},o="([ui](8|16|32|64|128|size)|f(32|64))?",l=["abstract","as","async","await","become","box","break","const","continue","crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"],c=["true","false","Some","None","Ok","Err"],u=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOrd","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unreachable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],d=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f32","f64","str","char","bool","Box","Option","Result","String","Vec"];return{name:"Rust",aliases:["rs"],keywords:{$pattern:e.IDENT_RE+"!?",type:d,keyword:l,literal:c,built_in:u},illegal:"</",contains:[e.C_LINE_COMMENT_MODE,e.COMMENT("/\\*","\\*/",{contains:["self"]}),e.inherit(e.QUOTE_STRING_MODE,{begin:/b?"/,illegal:null}),{className:"symbol",begin:/'[a-zA-Z_][a-zA-Z0-9_]*(?!')/},{scope:"string",variants:[{begin:/b?r(#*)"(.|\n)*?"\1(?!#)/},{begin:/b?'/,end:/'/,contains:[{scope:"char.escape",match:/\\('|\w|x\w{2}|u\w{4}|U\w{8})/}]}]},{className:"number",variants:[{begin:"\\b0b([01_]+)"+o},{begin:"\\b0o([0-7_]+)"+o},{begin:"\\b0x([A-Fa-f0-9_]+)"+o},{begin:"\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)"+o}],relevance:0},{begin:[/fn/,/\s+/,r],className:{1:"keyword",3:"title.function"}},{className:"meta",begin:"#!?\\[",end:"\\]",contains:[{className:"string",begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE]}]},{begin:[/let/,/\s+/,/(?:mut\s+)?/,r],className:{1:"keyword",3:"keyword",4:"variable"}},{begin:[/for/,/\s+/,r,/\s+/,/in/],className:{1:"keyword",3:"variable",5:"keyword"}},{begin:[/type/,/\s+/,r],className:{1:"keyword",3:"title.class"}},{begin:[/(?:trait|enum|struct|union|impl|for)/,/\s+/,r],className:{1:"keyword",3:"title.class"}},{begin:e.IDENT_RE+"::",keywords:{keyword:"Self",built_in:u,type:d}},{className:"punctuation",begin:"->"},i]}}const d8e=e=>({IMPORTANT:{scope:"meta",begin:"!important"},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:"number",begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},UNICODE_RANGE:{scope:"number",begin:/\b[Uu]\+[0-9A-Fa-f][0-9A-Fa-f?]{0,4}(-[0-9A-Fa-f][0-9A-Fa-f]{0,4})?/},FUNCTION_DISPATCH:{className:"built_in",begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:"selector-attr",begin:/\[/,end:/\]/,illegal:"$",contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:"number",begin:e.NUMBER_RE+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",relevance:0},CSS_VARIABLE:{className:"attr",begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),h8e=["a","abbr","address","article","aside","audio","b","blockquote","body","button","canvas","caption","cite","code","dd","del","details","dfn","div","dl","dt","em","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hgroup","html","i","iframe","img","input","ins","kbd","label","legend","li","main","mark","menu","nav","object","ol","optgroup","option","p","picture","q","quote","samp","section","select","source","span","strong","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","ul","var","video"],f8e=["defs","g","marker","mask","pattern","svg","switch","symbol","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feFlood","feGaussianBlur","feImage","feMerge","feMorphology","feOffset","feSpecularLighting","feTile","feTurbulence","linearGradient","radialGradient","stop","circle","ellipse","image","line","path","polygon","polyline","rect","text","use","textPath","tspan","foreignObject","clipPath"],m8e=[...h8e,...f8e],p8e=["any-hover","any-pointer","aspect-ratio","color","color-gamut","color-index","device-aspect-ratio","device-height","device-width","display-mode","forced-colors","grid","height","hover","inverted-colors","monochrome","orientation","overflow-block","overflow-inline","pointer","prefers-color-scheme","prefers-contrast","prefers-reduced-motion","prefers-reduced-transparency","resolution","scan","scripting","update","width","min-width","max-width","min-height","max-height"].sort().reverse(),x8e=["active","any-link","blank","checked","current","default","defined","dir","disabled","drop","empty","enabled","first","first-child","first-of-type","fullscreen","future","focus","focus-visible","focus-within","has","host","host-context","hover","indeterminate","in-range","invali
886d","is","lang","last-child","last-of-type","left","link","local-link","not","nth-child","nth-col","nth-last-child","nth-last-col","nth-last-of-type","nth-of-type","only-child","only-of-type","optional","out-of-range","past","placeholder-shown","read-only","read-write","required","right","root","scope","target","target-within","user-invalid","valid","visited","where"].sort().reverse(),g8e=["after","backdrop","before","cue","cue-region","first-letter","first-line","grammar-error","marker","part","placeholder","selection","slotted","spelling-error"].sort().reverse(),y8e=["accent-color","align-content","align-items","align-self","alignment-baseline","all","anchor-name","animation","animation-composition","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-range","animation-range-end","animation-range-start","animation-timeline","animation-timing-function","appearance","aspect-ratio","backdrop-filter","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-position-x","background-position-y","background-repeat","background-size","baseline-shift","block-size","border","border-block","border-block-color","border-block-end","border-block-end-color","border-block-end-style","border-block-end-width","border-block-start","border-block-start-color","border-block-start-style","border-block-start-width","border-block-style","border-block-width","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-end-end-radius","border-end-start-radius","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-inline","border-inline-color","border-inline-end","border-inline-end-color","border-inline-end-style","border-inline-end-width","border-inline-start","border-inline-start-color","border-inline-start-style","border-inline-start-width","border-inline-style","border-inline-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-start-end-radius","border-start-start-radius","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-align","box-decoration-break","box-direction","box-flex","box-flex-group","box-lines","box-ordinal-group","box-orient","box-pack","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","color-scheme","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","contain","contain-intrinsic-block-size","contain-intrinsic-height","contain-intrinsic-inline-size","contain-intrinsic-size","contain-intrinsic-width","container","container-name","container-type","content","content-visibility","counter-increment","counter-reset","counter-set","cue","cue-after","cue-before","cursor","cx","cy","direction","display","dominant-baseline","empty-cells","enable-background","field-sizing","fill","fill-opacity","fill-rule","filter","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","flood-color","flood-opacity","flow","font","font-display","font-family","font-feature-settings","font-kerning","font-language-override","font-optical-sizing","font-palette","font-size","font-size-adjust","font-smooth","font-smoothing","font-stretch","font-style","font-synthesis","font-synthesis-position","font-synthesis-small-caps","font-synthesis-style","font-synthesis-weight","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-emoji","font-variant-ligatures","font-variant-numeric","font-variant-position","font-variation-settings","font-weight","forced-color-adjust","gap","glyph-orientation-horizontal","glyph-orientation-vertical","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphenate-character","hyphenate-limit-chars","hyphens","icon","image-orientation","image-rendering","image-resolution","ime-mode","initial-letter","initial-letter-align","inline-size","inset","inset-
886area","inset-block","inset-block-end","inset-block-start","inset-inline","inset-inline-end","inset-inline-start","isolation","justify-content","justify-items","justify-self","kerning","left","letter-spacing","lighting-color","line-break","line-height","line-height-step","list-style","list-style-image","list-style-position","list-style-type","margin","margin-block","margin-block-end","margin-block-start","margin-bottom","margin-inline","margin-inline-end","margin-inline-start","margin-left","margin-right","margin-top","margin-trim","marker","marker-end","marker-mid","marker-start","marks","mask","mask-border","mask-border-mode","mask-border-outset","mask-border-repeat","mask-border-slice","mask-border-source","mask-border-width","mask-clip","mask-composite","mask-image","mask-mode","mask-origin","mask-position","mask-repeat","mask-size","mask-type","masonry-auto-flow","math-depth","math-shift","math-style","max-block-size","max-height","max-inline-size","max-width","min-block-size","min-height","min-inline-size","min-width","mix-blend-mode","nav-down","nav-index","nav-left","nav-right","nav-up","none","normal","object-fit","object-position","offset","offset-anchor","offset-distance","offset-path","offset-position","offset-rotate","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-anchor","overflow-block","overflow-clip-margin","overflow-inline","overflow-wrap","overflow-x","overflow-y","overlay","overscroll-behavior","overscroll-behavior-block","overscroll-behavior-inline","overscroll-behavior-x","overscroll-behavior-y","padding","padding-block","padding-block-end","padding-block-start","padding-bottom","padding-inline","padding-inline-end","padding-inline-start","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","paint-order","pause","pause-after","pause-before","perspective","perspective-origin","place-content","place-items","place-self","pointer-events","position","position-anchor","position-visibility","print-color-adjust","quotes","r","resize","rest","rest-after","rest-before","right","rotate","row-gap","ruby-align","ruby-position","scale","scroll-behavior","scroll-margin","scroll-margin-block","scroll-margin-block-end","scroll-margin-block-start","scroll-margin-bottom","scroll-margin-inline","scroll-margin-inline-end","scroll-margin-inline-start","scroll-margin-left","scroll-margin-right","scroll-margin-top","scroll-padding","scroll-padding-block","scroll-padding-block-end","scroll-padding-block-start","scroll-padding-bottom","scroll-padding-inline","scroll-padding-inline-end","scroll-padding-inline-start","scroll-padding-left","scroll-padding-right","scroll-padding-top","scroll-snap-align","scroll-snap-stop","scroll-snap-type","scroll-timeline","scroll-timeline-axis","scroll-timeline-name","scrollbar-color","scrollbar-gutter","scrollbar-width","shape-image-threshold","shape-margin","shape-outside","shape-rendering","speak","speak-as","src","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","tab-size","table-layout","text-align","text-align-all","text-align-last","text-anchor","text-combine-upright","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-skip-ink","text-decoration-style","text-decoration-thickness","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-indent","text-justify","text-orientation","text-overflow","text-rendering","text-shadow","text-size-adjust","text-transform","text-underline-offset","text-underline-position","text-wrap","text-wrap-mode","text-wrap-style","timeline-scope","top","touch-action","transform","transform-box","transform-origin","transform-style","transition","transition-behavior","transition-delay","transition-duration","transition-property","transition-timing-function","translate","unicode-bidi","unicode-range","user-modify","user-select","vector-effect","vertical-align","view-timeline","view-timeline-axis","view-timeline-inset","view-timeline-name","view-transition-name","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","white-space","white-space-collapse","widows","width","will-change","word-break","word-spacing","word-wrap","writing-mode","x","y","z-index","zoom"].sort().reverse();function b8e(e){const t=d8e(e),n=g8e,r=x8e,a="@[a-z-]+",i="and or not only",l={className:"variable",begin:"(\\$"+"[a-zA-Z-][a-zA-Z0-9_-]*"+")\\b",relevance:0};return{name:"SCSS",case_insensitive:!0,illegal:"[=/|']",contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,t.CSS_NUMBER_MODE,{className:"selector-id",begin:"#[A-Za-z0-9_-]+",relevance:0}
vendor: 1,113 bytes, line 886
886,{className:"selector-class",begin:"\\.[A-Za-z0-9_-]+",relevance:0},t.ATTRIBUTE_SELECTOR_MODE,{className:"selector-tag",begin:"\\b("+m8e.join("|")+")\\b",relevance:0},{className:"selector-pseudo",begin:":("+r.join("|")+")"},{className:"selector-pseudo",begin:":(:)?("+n.join("|")+")"},l,{begin:/\(/,end:/\)/,contains:[t.CSS_NUMBER_MODE]},t.CSS_VARIABLE,{className:"attribute",begin:"\\b("+y8e.join("|")+")\\b"},{begin:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inl
886ine-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{begin:/:/,end:/[;}{]/,relevance:0,contains:[t.BLOCK_COMMENT,l,t.HEXCOLOR,t.CSS_NUMBER_MODE,t.UNICODE_RANGE,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,t.IMPORTANT,t.FUNCTION_DISPATCH]},{begin:"@(page|font-face)",keywords:{$pattern:a,keyword:"@page @font-face"}},{begin:"@",end:"[{;]",returnBegin:!0,keywords:{$pattern:/[a-z-]+/,keyword:i,attribute:p8e.join(" ")},contains:[{begin:a,className:"keyword"},{begin:/[a-z-]+(?=:)/,className:"attribute"},l,e.QUOTE_STRING_MODE,e.APOS_STRING_MODE,t.HEXCOLOR,t.CSS_NUMBER_MODE]},t.FUNCTION_DISPATCH]}}function v8e(e){return{name:"Shell Session",aliases:["console","shellsession"],contains:[{className:"meta.prompt",begin:/^\s{0,3}[/~\w\d[\]()@-]*[>%$#][ ]?/,starts:{end:/[^\\](?=\s*$)/,subLanguage:"bash"}}]}}function w8e(e){const t=e.regex,n=e.COMMENT("--","$"),r={scope:"string",variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},a={begin:/"/,end:/"/,contains:[{match:/""/}]},i=["true","false","unknown"],o=["double precision","large object","with timezone","without timezone"],l=["bigint","binary","blob","boolean","char","character","clob","date","dec","decfloat","decimal","float","int","integer","interval","nchar","nclob","national","numeric","real","row","smallint","time","timestamp","varchar","varying","varbinary"],c=["add","asc","collation","desc","final","first","last","view"],u=["abs","acos","all","allocate","alter","and","any","are","array","array_agg","array_max_cardinality","as","asensitive","asin","asymmetric","at","atan","atomic","authorization","avg","begin","begin_frame","begin_partition","between","bigint","binary","blob","boolean","both","by","call","called","cardinality","cascaded","case","cast","ceil","ceiling","char","char_length","character","character_length","check","classifier","clob","close","coalesce","collate","collect","column","commit","condition","connect","constraint","contains","convert","copy","corr","corresponding","cos","cosh","count","covar_pop","covar_samp","create","cross","cube","cume_dist","current","current_catalog","current_date","current_default_transform_group","current_path","current_role","current_row","current_schema","current_time","current_timestamp","current_path","current_role","current_transform_group_for_type","current_user","cursor","cycle","date","day","deallocate","dec","decimal","decfloat","declare","default","define","delete","dense_rank","deref","describe","deterministic","disconnect","distinct","double","drop","dynamic","each","element","else","empty","end","end_frame","end_partition","end-exec","equals","escape","every","except","exec","execute","exists","exp","external","extract","false","fetch","filter","first_value","float","floor","for","foreign","frame_row","free","from","full","function","fusion","get","global","grant","group","grouping","groups","having","hold","hour","identity","in","indicator","initial","inner","inout","insensitive","insert","int","integer","intersect","intersection","interval","into","is","join","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","language","large","last_value","lateral","lead","leading","left","like","like_regex","listagg","ln","local","localtime","localtimestamp","log","log10","lower","match","match_number","match_recognize","matches","max","member","merge","method","min","minute","mod","modifies","module","month","multiset","national","natural","nchar","nclob","new","no","none","normalize","not","nth_value","ntile","null","nullif","numeric","octet_length","occurrences_regex","of","offset","old","omit","on","one","only","open","or","order","out","outer","over","overlaps","overlay","parameter","partition","pattern","per","percent","percent_rank","percentile_cont","percentile_disc","period","portion","position","position_regex","power","precedes","precision","prepare","primary","procedure","ptf","range","rank","reads","real","recursive","ref","references","referencing","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","release","result","return","returns","revoke","right","rollback","rollup","row","row_number","rows","running","savepoint","scope","scroll","search","second","seek","select","sensitive","session_user","set","show","similar","sin","sinh","skip","smallint","some","specific","specifictype","sql","sqlexception","sqlstate","sqlwarning","sqrt","start","static","stddev_pop","stddev_samp","submultiset","subset","substring","substring_regex","succeeds","sum","symmetric","system","system_time","system_user","table","tablesample","tan","tanh","then","time","timestamp","timezone_hour","timezone_minute","to","trailing","translate","translate_regex","translation","treat","trigger","trim","trim_array","true","truncate","uescape","union","unique","unknown","unnest","update","upper","user","using","value","values","value_of","var_pop","var_samp","varbinary","varchar","varying","ver
886sioning","when","whenever","where","width_bucket","window","with","within","without","year"],d=["abs","acos","array_agg","asin","atan","avg","cast","ceil","ceiling","coalesce","corr","cos","cosh","count","covar_pop","covar_samp","cume_dist","dense_rank","deref","element","exp","extract","first_value","floor","json_array","json_arrayagg","json_exists","json_object","json_objectagg","json_query","json_table","json_table_primitive","json_value","lag","last_value","lead","listagg","ln","log","log10","lower","max","min","mod","nth_value","ntile","nullif","percent_rank","percentile_cont","percentile_disc","position","position_regex","power","rank","regr_avgx","regr_avgy","regr_count","regr_intercept","regr_r2","regr_slope","regr_sxx","regr_sxy","regr_syy","row_number","sin","sinh","sqrt","stddev_pop","stddev_samp","substring","substring_regex","sum","tan","tanh","translate","translate_regex","treat","trim","trim_array","unnest","upper","value_of","var_pop","var_samp","width_bucket"],h=["current_catalog","current_date","current_default_transform_group","current_path","current_role","current_schema","current_transform_group_for_type","current_user","session_user","system_time","system_user","current_time","localtime","current_timestamp","localtimestamp"],f=["create table","insert into","primary key","foreign key","not null","alter table","add constraint","grouping sets","on overflow","character set","respect nulls","ignore nulls","nulls first","nulls last","depth first","breadth first"],m=d,x=[...u,...c].filter(k=>!d.includes(k)),g={scope:"variable",match:/@[a-z0-9][a-z0-9_]*/},y={scope:"operator",match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0},b={match:t.concat(/\b/,t.either(...m),/\s*\(/),relevance:0,keywords:{built_in:m}};function v(k){return t.concat(/\b/,t.either(...k.map(j=>j.replace(/\s+/,"\\s+"))),/\b/)}const w={scope:"keyword",match:v(f),relevance:0};function _(k,{exceptions:j,when:N}={}){const E=N;return j=j||[],k.map(A=>A.match(/\|\d+$/)||j.includes(A)?A:E(A)?`${A}|0`:A)}return{name:"SQL",case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:_(x,{when:k=>k.length<3}),literal:i,type:l,built_in:h},contains:[{scope:"type",match:v(o)},w,b,g,r,a,e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,n,y]}}function eV(e){return e?typeof e=="string"?e:e.source:null}function gm(e){return Mn("(?=",e,")")}function Mn(...e){return e.map(n=>eV(n)).join("")}function _8e(e){const t=e[e.length-1];return typeof t=="object"&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}function ja(...e){return"("+(_8e(e).capture?"":"?:")+e.map(r=>eV(r)).join("|")+")"}const f3=e=>Mn(/\b/,e,/\w$/.test(e)?/\b/:/\B/),k8e=["Protocol","Type"].map(f3),PM=["init","self"].map(f3),j8e=["Any","Self"],Ek=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distributed","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","package","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows","return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],RM=["false","nil","true"],N8e=["assignment","associativity","higherThan","left","lowerThan","none","right"],S8e=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","#imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],DM=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","withUnsafePointer","withVaList","
vendor: 41,185 bytes, lines 886-888
886withoutActuallyEscaping","zip"],tV=ja(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),nV=ja(tV,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,/[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),Ak=Mn(tV,nV,"*"),rV=ja(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,/[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),xv=ja(rV,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),Wo=Mn(rV,xv,"*"),zg=Mn(/[A-Z]/,xv,"*"),C8e=["attached","autoclosure",Mn(/convention\(/,ja("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen","GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",Mn(/objc\(/,Wo,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],E8e=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCatalystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];function A8e(e){const t={match:/\s+/,relevance:0},n=e.COMMENT("/\\*","\\*/",{contains:["self"]}),r=[e.C_LINE_COMMENT_MODE,n],a={match:[/\./,ja(...k8e,...PM)],className:{2:"keyword"}},i={match:Mn(/\./,ja(...Ek)),relevance:0},o=Ek.filter(je=>typeof je=="string").concat(["_|0"]),l=Ek.filter(je=>typeof je!="string").concat(j8e).map(f3),c={variants:[{className:"keyword",match:ja(...l,...PM)}]},u={$pattern:ja(/\b\w+/,/#\w+/),keyword:o.concat(S8e),literal:RM},d=[a,i,c],h={match:Mn(/\./,ja(...DM)),relevance:0},f={className:"built_in",match:Mn(/\b/,ja(...DM),/(?=\()/)},m=[h,f],x={match:/->/,relevance:0},g={className:"operator",relevance:0,variants:[{match:Ak},{match:`\\.(\\.|${nV})+`}]},y=[x,g],b="([0-9]_*)+",v="([0-9a-fA-F]_*)+",w={className:"number",relevance:0,variants:[{match:`\\b(${b})(\\.(${b}))?([eE][+-]?(${b}))?\\b`},{match:`\\b0x(${v})(\\.(${v}))?([pP][+-]?(${b}))?\\b`},{match:/\b0o([0-7]_*)+\b/},{match:/\b0b([01]_*)+\b/}]},_=(je="")=>({className:"subst",variants:[{match:Mn(/\\/,je,/[0\\tnr"']/)},{match:Mn(/\\/,je,/u\{[0-9a-fA-F]{1,8}\}/)}]}),k=(je="")=>({className:"subst",match:Mn(/\\/,je,/[\t ]*(?:[\r\n]|\r\n)/)}),j=(je="")=>({className:"subst",label:"interpol",begin:Mn(/\\/,je,/\(/),end:/\)/}),N=(je="")=>({begin:Mn(je,/"""/),end:Mn(/"""/,je),contains:[_(je),k(je),j(je)]}),E=(je="")=>({begin:Mn(je,/"/),end:Mn(/"/,je),contains:[_(je),j(je)]}),A={className:"string",variants:[N(),N("#"),N("##"),N("###"),E(),E("#"),E("##"),E("###")]},C=[e.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[e.BACKSLASH_ESCAPE]}],T={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//,contains:C},S=je=>{const $e=Mn(je,/\//),J=Mn(/\//,je);return{begin:$e,end:J,contains:[...C,{scope:"comment",begin:`#(?!.*${J})`,end:/$/}]}},O={scope:"regexp",variants:[S("###"),S("##"),S("#"),T]},R={match:Mn(/`/,Wo,/`/)},I={className:"variable",match:/\$\d+/},$={className:"variable",match:`\\$${xv}+`},P=[R,I,$],F={match:/(@|#(un)?)available/,scope:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:E8e,contains:[...y,w,A]}]}},Z={scope:"keyword",match:Mn(/@/,ja(...C8e),gm(ja(/\(/,/\s+/)))},D={scope:"meta",match:Mn(/@/,Wo)},H=[F,Z,D],Y={match:gm(/\b[A-Z]/),relevance:0,contains:[{className:"type",match:Mn(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,xv,"+")},{className:"type",match:zg,relevance:0},{match:/[?!]+/,relevance:0},{match:/\.\.\./,relevance:0},{match:Mn(/\s+&\s+/,gm(zg)),relevance:0}]},M={begin:/</,end:/>/,keywords:u,contains:[...r,...d,...H,x,Y]};Y.contains.push(M);const z={match:Mn(Wo,/\s*:/),keywords:"_|0",relevance:0},G={begin:/\(/,end:/\)/,relevance:0,keywords:u,contains:["self",z,...r,O,...d,...m,...y,w,A,...P,...H,Y]},te={begin:/</,end:/>/,keywords:"repeat each",contains:[...r,Y]},re={begin:ja(gm(Mn(Wo,/\s*:/)),gm(Mn(Wo,/\s+/,Wo,/\s*:/))),end:/:/,relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:Wo}]},L={begin:/\(/,end:/\)/,keywords:u,contains:[re,...r,...d,...y,w,A,...H,Y,G],endsParent:!0,illegal:/["']/},q={match:[/(func|macro)/,/\s+/,ja(R.match,Wo,Ak)],className:{1:"keyword",3:"title.function"},contains:[te,L,t],illegal:[/\[/,/%/]},me={match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"},contains:[te,L,t],illegal:/\[|%/},ee={match:[/operator/,/\s+/,Ak],className:{1:"keyword",3:"title"}},ne={begin:[/precedencegroup/,/\s+/,zg],className:{1:"keyword",3:"title"},contains:[Y],keywords:[...N8e,...RM],end:/}/},X={match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{1:"keyword",3:"keyword",5:"title.function"}},he={match:[/class\b/,/\s+/,/var\b/],scope:{1:"keyword",3:"keyword"}},ae={begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,Wo,/\s*/],beginScope:{1:"keyword",3:"title.class"},keywords:u,contains:[te,...d,{begin:/:/,end:/\{/,keywords:u,contains:[{scope:"title.class.inherited",match:zg},...d],relevance:0}]};for(const je of A.variants){const $e=je.contains.find(Ne=>Ne.label==="interpol");$e.keywords=u;const J=[...d,...m,...y,w,A,...P];$e.contains=[...J,{begin:/\(/,end:/\)/,contains:["self",...J]}]}return{name:"Swift",keywords:u,contains:[...r,q,me,X,he,ae,ee,ne,{beginKeywords:"import",end:/$/,contains:[...r],relevance:0},O,...d,...m,...y,w,A,...P,...H,Y,G]}}const gv="[A-Za-z$_][0-9A-Za-z$_]*",sV=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],aV=["true","false","null","undefined","NaN","Infinity"],iV=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],oV=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],lV=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],cV=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","global"],uV=[].concat(lV,iV,oV);function T8e(e){const t=e.regex,n=(F,{after:Z})=>{const D="</"+F[0].slice(1);return F.input.indexOf(D,Z)!==-1},r=gv,a={begin:"<>",end:"</>"},i=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(F,Z)=>{const D=F[0].length+F.index,H=F.input[D];if(H==="<"||H===","){Z.ignoreMatch();return}H===">"&&(n(F,{after:D})||Z.ignoreMatch());let Y;const M=F.input.substring(D);if(Y=M.match(/^\s*=/)){Z.ignoreMatch();return}if((Y=M.match(/^\s+extends\s+/))&&Y.index===0){Z.ignoreMatch();return}}},l={$pattern:gv,keyword:sV,literal:aV,built_in:uV,"variable.language":cV},c="[0-9](_?[0-9])*",u=`\\.(${c})`,d="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",h={className:"number",variants:[{begin:`(\\b(${d})((${u})|\\.)?|(${u}))[eE][+-]?(${c})\\b`},{begin:`\\b(${d})\\b((${u})\\b|\\.)?|(${u})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},f={className:"subst",begin:"\\$\\{",end:"\\}",keywords:l,contains:[]},m={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:"xml"}},x={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:"css"}},g={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:"graphql"}},y={className:"string",begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,f]},v={className:"comment",variants:[e.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:r+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},w=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,m,x,g,y,{match:/\$\d+/},h];f.contains=w.concat({begin:/\{/,end:/\}/,keywords:l,contains:["self"].concat(w)});const _=[].concat(v,f.contains),k=_.concat([{begin:/(\s*)\(/,end:/\)/,keywords:l,contains:["self"].concat(_)}]),j={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:k},N={variants:[{match:[/class/,/\s+/,r,/\s+/,/extends/,/\s+/,t.concat(r,"(",t.concat(/\./,r),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,r],scope:{1:"keyword",3:"title.class"}}]},E={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...iV,...oV]}},A={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},C={variants:[{match:[/function/,/\s+/,r,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[j],illegal:/%/},T={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function S(F){return t.concat("(?!",F.join("|"),")")}const O={match:t.concat(/\b/,S([...lV,"super","import","await"].map(F=>`${F}\\s*\\(`)),r,t.lookahead(/\s*\(/)),className:"title.function",relevance:0},R={begin:t.concat(/\./,t.lookahead(t.concat(r,/(?![0-9A-Za-z$_(])/))),end:r,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},I={match:[/get|set/,/\s+/,r,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},j]},$="(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+e.UNDERSCORE_IDENT_RE+")\\s*=>",P={match:[/const|var|let/,/\s+/,r,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead($)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[j]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:l,exports:{PARAMS_CONTAINS:k,CLASS_REFERENCE:E},illegal:/#(?![$_A-Za-z])/,contains:[e.SHEBANG({label:"shebang",binary:"node",relevance:5}),A,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,m,x,g,y,v,{match:/\$\d+/},h,E,{scope:"attr",match:r+t.lookahead(":"),relevance:0},P,{begin:"("+e.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[v,e.REGEXP_MODE,{className:"function",begin:$,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:l,contains:k}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:a.begin,end:a.end},{match:i},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:"xml",contains:[{begin:o.begin,end:o.end,skip:!0,contains:["self"]}]}]},C,{beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+e.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[j,e.inherit(e.TITLE_MODE,{begin:r,className:"title.function"})]},{match:/\.\.\./,relevance:0},R,{match:"\\$"+r,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[j]},O,T,N,I,{match:/\$[(.]/}]}}function O8e(e){const t=e.regex,n=T8e(e),r=gv,a=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],i={begin:[/namespace/,/\s+/,e.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},o={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:a},contains:[n.exports.CLASS_REFERENCE]},l={className:"meta",relevance:10,begin:/^\s*['"]use strict['"]/},c=["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"],u={$pattern:gv,keyword:sV.concat(c),literal:aV,built_in:uV.concat(a),"variable.language":cV},d={className:"meta",begin:"@"+r},h=(g,y,b)=>{const v=g.contains.findIndex(w=>w.label===y);if(v===-1)throw new Error("can not find mode to replace");g.contains.splice(v,1,b)};Object.assign(n.keywords,u),n.exports.PARAMS_CONTAINS.push(d);const f=n.contains.find(g=>g.scope==="attr"),m=Object.assign({},f,{match:t.concat(r,t.lookahead(/\s*\?:/))});n.exports.PARAMS_CONTAINS.push([n.exports.CLASS_REFERENCE,f,m]),n.contains=n.contains.concat([d,i,o,m]),h(n,"shebang",e.SHEBANG()),h(n,"use_strict",l);const x=n.contains.find(g=>g.label==="func.def");return x.relevance=0,Object.assign(n,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),n}function I8e(e){const t=e.regex,n={className:"string",begin:/"(""|[^/n])"C\b/},r={className:"string",begin:/"/,end:/"/,illegal:/\n/,contains:[{begin:/""/}]},a=/\d{1,2}\/\d{1,2}\/\d{4}/,i=/\d{4}-\d{1,2}-\d{1,2}/,o=/(\d|1[012])(:\d+){0,2} *(AM|PM)/,l=/\d{1,2}(:\d{1,2}){1,2}/,c={className:"literal",variants:[{begin:t.concat(/# */,t.either(i,a),/ *#/)},{begin:t.concat(/# */,l,/ *#/)},{begin:t.concat(/# */,o,/ *#/)},{begin:t.concat(/# */,t.either(i,a),/ +/,t.either(o,l),/ *#/)}]},u={className:"number",relevance:0,variants:[{begin:/\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/},{begin:/\b\d[\d_]*((U?[SIL])|[%&])?/},{begin:/&H[\dA-F_]+((U?[SIL])|[%&])?/},{begin:/&O[0-7_]+((U?[SIL])|[%&])?/},{begin:/&B[01_]+((U?[SIL])|[%&])?/}]},d={className:"label",begin:/^\w+:/},h=e.COMMENT(/'''/,/$/,{contains:[{className:"doctag",begin:/<\/?/,end:/>/}]}),f=e.COMMENT(null,/$/,{variants:[{begin:/'/},{begin:/([\t ]|^)REM(?=\s)/}]});return{name:"Visual Basic .NET",aliases:["vb"],case_insensitive:!0,classNameAliases:{label:"symbol"},keywords:{keyword:"addhandler alias aggregate ansi as async assembly auto binary by byref byval call case catch class compare const continue custom declare default delegate dim distinct do each equals else elseif end enum erase error event exit explicit finally for friend from function get global goto group handles if implements imports in inherits interface into iterator join key let lib loop me mid module mustinherit mustoverride mybase myclass namespace narrowing new next notinheritable notoverridable of off on operator option optional order overloads overridable overrides paramarray partial preserve private property protected public raiseevent readonly redim removehandler resume return select set shadows shared skip static step stop structure strict sub synclock take text then throw to try unicode until using when where while widening with withevents writeonly yield",built_in:"addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort",type:"boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort",literal:"true false nothing"},illegal:"//|\\{|\\}|endif|gosub|variant|wend|^\\$ ",contains:[n,r,c,u,d,h,f,{className:"meta",begin:/[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/,end:/$/,keywords:{keyword:"const disable else elseif enable end externalsource if region then"},contains:[f]}]}}function P8e(e){e.regex;const t=e.COMMENT(/\(;/,/;\)/);t.contains.push("self");const n=e.COMMENT(/;;/,/$/),r=["anyfunc","block","br","br_if","br_table","call","call_indirect","data","drop","elem","else","end","export","func","global.get","global.set","local.get","local.set","local.tee","get_global","get_local","global","if","import","local","loop","memory","memory.grow","memory.size","module","mut","nop","offset","param","result","return","select","set_global","set_local","start","table","tee_local","then","type","unreachable"],a={begin:[/(?:func|call|call_indirect)/,/\s+/,/\$[^\s)]+/],className:{1:"keyword",3:"title.function"}},i={className:"variable",begin:/\$[\w_]+/},o={match:/(\((?!;)|\))+/,className:"punctuation",relevance:0},l={className:"number",relevance:0,match:/[+-]?\b(?:\d(?:_?\d)*(?:\.\d(?:_?\d)*)?(?:[eE][+-]?\d(?:_?\d)*)?|0x[\da-fA-F](?:_?[\da-fA-F])*(?:\.[\da-fA-F](?:_?[\da-fA-D])*)?(?:[pP][+-]?\d(?:_?\d)*)?)\b|\binf\b|\bnan(?::0x[\da-fA-F](?:_?[\da-fA-D])*)?\b/},c={match:/(i32|i64|f32|f64)(?!\.)/,className:"type"},u={className:"keyword",match:/\b(f32|f64|i32|i64)(?:\.(?:abs|add|and|ceil|clz|const|convert_[su]\/i(?:32|64)|copysign|ctz|demote\/f64|div(?:_[su])?|eqz?|extend_[su]\/i32|floor|ge(?:_[su])?|gt(?:_[su])?|le(?:_[su])?|load(?:(?:8|16|32)_[su])?|lt(?:_[su])?|max|min|mul|nearest|neg?|or|popcnt|promote\/f32|reinterpret\/[fi](?:32|64)|rem_[su]|rot[lr]|shl|shr_[su]|store(?:8|16|32)?|sqrt|sub|trunc(?:_[su]\/f(?:32|64))?|wrap\/i64|xor))\b/};return{name:"WebAssembly",keywords:{$pattern:/[\w.]+/,keyword:r},contains:[n,t,{match:[/(?:offset|align)/,/\s*/,/=/],className:{1:"keyword",3:"operator"}},i,o,a,e.QUOTE_STRING_MODE,c,u,l]}}function R8e(e){const t=e.regex,n=t.concat(/[\p{L}_]/u,t.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),r=/[\p{L}0-9._:-]+/u,a={className:"symbol",begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},i={begin:/\s/,contains:[{className:"keyword",begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},o=e.inherit(i,{begin:/\(/,end:/\)/}),l=e.inherit(e.APOS_STRING_MODE,{className:"string"}),c=e.inherit(e.QUOTE_STRING_MODE,{className:"string"}),u={endsWithParent:!0,illegal:/</,relevance:0,contains:[{className:"attr",begin:r,relevance:0},{begin:/=\s*/,relevance:0,contains:[{className:"string",endsParent:!0,variants:[{begin:/"/,end:/"/,contains:[a]},{begin:/'/,end:/'/,contains:[a]},{begin:/[^\s"'=<>`]+/}]}]}]};return{name:"HTML, XML",aliases:["html","xhtml","rss","atom","xjb","xsd","xsl","plist","wsf","svg"],case_insensitive:!0,unicodeRegex:!0,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,relevance:10,contains:[i,c,l,o,{begin:/\[/,end:/\]/,contains:[{className:"meta",begin:/<![a-z]/,end:/>/,contains:[i,o,c,l]}]}]},e.COMMENT(/<!--/,/-->/,{relevance:10}),{begin:/<!\[CDATA\[/,end:/\]\]>/,relevance:10},a,{className:"meta",end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[c]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:"tag",begin:/<style(?=\s|>)/,end:/>/,keywords:{name:"style"},contains:[u],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:["css","xml"]}},{className:"tag",begin:/<script(?=\s|>)/,end:/>/,keywords:{name:"script"},contains:[u],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:["javascript","handlebars","xml"]}},{className:"tag",begin:/<>|<\/>/},{className:"tag",begin:t.concat(/</,t.lookahead(t.concat(n,t.either(/\/>/,/>/,/\s/)))),end:/\/?>/,contains:[{className:"name",begin:n,relevance:0,starts:u}]},{className:"tag",begin:t.concat(/<\//,t.lookahead(t.concat(n,/>/))),contains:[{className:"name",begin:n,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}function D8e(e){const t="true false yes no null",n="[\\w#;/?:@&=+$,.~*'()[\\]]+",r={className:"attr",variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},a={className:"template-variable",variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]},i={className:"string",relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:"char.escape",relevance:0}]},o={className:"string",relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,a]},l=e.inherit(o,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),f={className:"number",begin:"\\b"+"[0-9]{4}(-[0-9][0-9]){0,2}"+"([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?"+"(\\.[0-9]*)?"+"([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?"+"\\b"},m={end:",",endsWithParent:!0,excludeEnd:!0,keywords:t,relevance:0},x={begin:/\{/,end:/\}/,contains:[m],illegal:"\\n",relevance:0},g={begin:"\\[",end:"\\]",contains:[m],illegal:"\\n",relevance:0},y=[r,{className:"meta",begin:"^---\\s*$",relevance:10},{className:"string",begin:"[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*"},{begin:"<%[%=-]?",end:"[%-]?%>",subLanguage:"ruby",excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:"!\\w+!"+n},{className:"type",begin:"!<"+n+">"},{className:"type",begin:"!"+n},{className:"type",begin:"!!"+n},{className:"meta",begin:"&"+e.UNDERSCORE_IDENT_RE+"$"},{className:"meta",begin:"\\*"+e.UNDERSCORE_IDENT_RE+"$"},{className:"bullet",begin:"-(?=[ ]|$)",relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},f,{className:"number",begin:e.C_NUMBER_RE+"\\b",relevance:0},x,g,i,o],b=[...y];return b.pop(),b.push(l),m.contains=b,{name:"YAML",case_insensitive:!0,aliases:["yml"],contains:y}}const M8e={arduino:pLe,bash:xLe,c:gLe,cpp:yLe,csharp:bLe,css:ELe,diff:ALe,go:TLe,graphql:OLe,ini:ILe,java:PLe,javascript:LLe,json:ULe,kotlin:WLe,less:XLe,lua:JLe,makefile:QLe,markdown:e8e,objectivec:t8e,perl:n8e,php:r8e,"php-template":s8e,plaintext:a8e,python:i8e,"python-repl":o8e,r:l8e,ruby:c8e,rust:u8e,scss:b8e,shell:v8e,sql:w8e,swift:A8e,typescript:O8e,vbnet:I8e,wasm:P8e,xml:R8e,yaml:D8e};var Tk,MM;function $8e(){if(MM)return Tk;MM=1;function e(le){return le instanceof Map?le.clear=le.delete=le.set=function(){throw new Error("map is read-only")}:le instanceof Set&&(le.add=le.clear=le.delete=function(){throw new Error("set is read-only")}),Object.freeze(le),Object.getOwnPropertyNames(le).forEach(De=>{const Ie=le[De],Ge=typeof Ie;(Ge==="object"||Ge==="function")&&!Object.isFrozen(Ie)&&e(Ie)}),le}class t{constructor(De){De.data===void 0&&(De.data={}),this.data=De.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}}function n(le){return le.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function r(le,...De){const Ie=Object.create(null);for(const Ge in le)Ie[Ge]=le[Ge];return De.forEach(function(Ge){for(const ye in Ge)Ie[ye]=Ge[ye]}),Ie}const a="</span>",i=le=>!!le.scope,o=(le,{prefix:De})=>{if(le.startsWith("language:"))return le.replace("language:","language-");if(le.includes(".")){const Ie=le.split(".");return[`${De}${Ie.shift()}`,...Ie.map((Ge,ye)=>`${Ge}${"_".repeat(ye+1)}`)].join(" ")}return`${De}${le}`};class l{constructor(De,Ie){this.buffer="",this.classPrefix=Ie.classPrefix,De.walk(this)}addText(De){this.buffer+=n(De)}openNode(De){if(!i(De))return;const Ie=o(De.scope,{prefix:this.classPrefix});this.span(Ie)}closeNode(De){i(De)&&(this.buffer+=a)}value(){return this.buffer}span(De){this.buffer+=`<span class="${De}">`}}const c=(le={})=>{const De={children:[]};return Object.assign(De,le),De};class u{constructor(){this.rootNode=c(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(De){this.top.children.push(De)}openNode(De){const Ie=c({scope:De});this.add(Ie),this.stack.push(Ie)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(De){return this.constructor._walk(De,this.rootNode)}static _walk(De,Ie){return typeof Ie=="string"?De.addText(Ie):Ie.children&&(De.openNode(Ie),Ie.children.forEach(Ge=>this._walk(De,Ge)),De.closeNode(Ie)),De}static _collapse(De){typeof De!="string"&&De.children&&(De.children.every(Ie=>typeof Ie=="string")?De.children=[De.children.join("")]:De.children.forEach(Ie=>{u._collapse(Ie)}))}}class d extends u{constructor(De){super(),this.options=De}addText(De){De!==""&&this.add(De)}startScope(De){this.openNode(De)}endScope(){this.closeNode()}__addSublanguage(De,Ie){const Ge=De.root;Ie&&(Ge.scope=`language:${Ie}`),this.add(Ge)}toHTML(){return new l(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}}function h(le){return le?typeof le=="string"?le:le.source:null}function f(le){return g("(?=",le,")")}function m(le){return g("(?:",le,")*")}function x(le){return g("(?:",le,")?")}function g(...le){return le.map(Ie=>h(Ie)).join("")}function y(le){const De=le[le.length-1];return typeof De=="object"&&De.constructor===Object?(le.splice(le.length-1,1),De):{}}function b(...le){return"("+(y(le).capture?"":"?:")+le.map(Ge=>h(Ge)).join("|")+")"}function v(le){return new RegExp(le.toString()+"|").exec("").length-1}function w(le,De){const Ie=le&&le.exec(De);return Ie&&Ie.index===0}const _=/\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./;function k(le,{joinWith:De}){let Ie=0;return le.map(Ge=>{Ie+=1;const ye=Ie;let ie=h(Ge),pe="";for(;ie.length>0;){const xe=_.exec(ie);if(!xe){pe+=ie;break}pe+=ie.substring(0,xe.index),ie=ie.substring(xe.index+xe[0].length),xe[0][0]==="\\"&&xe[1]?pe+="\\"+String(Number(xe[1])+ye):(pe+=xe[0],xe[0]==="("&&Ie++)}return pe}).map(Ge=>`(${Ge})`).join(De)}const j=/\b\B/,N="[a-zA-Z]\\w*",E="[a-zA-Z_]\\w*",A="\\b\\d+(\\.\\d+)?",C="(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",T="\\b(0b[01]+)",S="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",O=(le={})=>{const De=/^#![ ]*\//;return le.binary&&(le.begin=g(De,/.*\b/,le.binary,/\b.*/)),r({scope:"meta",begin:De,end:/$/,relevance:0,"on:begin":(Ie,Ge)=>{Ie.index!==0&&Ge.ignoreMatch()}},le)},R={begin:"\\\\[\\s\\S]",relevance:0},I={scope:"string",begin:"'",end:"'",illegal:"\\n",contains:[R]},$={scope:"string",begin:'"',end:'"',illegal:"\\n",contains:[R]},P={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},F=function(le,De,Ie={}){const Ge=r({scope:"comment",begin:le,end:De,contains:[]},Ie);Ge.contains.push({scope:"doctag",begin:"[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)",end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});const ye=b("I","a","is","so","us","to","at","if","in","it","on",/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return Ge.contains.push({begin:g(/[ ]+/,"(",ye,/[.]?[:]?([.][ ]|[ ])/,"){3}")}),Ge},Z=F("//","$"),D=F("/\\*","\\*/"),H=F("#","$"),Y={scope:"number",begin:A,relevance:0},M={scope:"number",begin:C,relevance:0},z={scope:"number",begin:T,relevance:0},G={scope:"regexp",begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[R,{begin:/\[/,end:/\]/,relevance:0,contains:[R]}]},te={scope:"title",begin:N,relevance:0},re={scope:"title",begin:E,relevance:0},L={begin:"\\.\\s*"+E,relevance:0};var me=Object.freeze({__proto__:null,APOS_STRING_MODE:I,BACKSLASH_ESCAPE:R,BINARY_NUMBER_MODE:z,BINARY_NUMBER_RE:T,COMMENT:F,C_BLOCK_COMMENT_MODE:D,C_LINE_COMMENT_MODE:Z,C_NUMBER_MODE:M,C_NUMBER_RE:C,END_SAME_AS_BEGIN:function(le){return Object.assign(le,{"on:begin":(De,Ie)=>{Ie.data._beginMatch=De[1]},"on:end":(De,Ie)=>{Ie.data._beginMatch!==De[1]&&Ie.ignoreMatch()}})},HASH_COMMENT_MODE:H,IDENT_RE:N,MATCH_NOTHING_RE:j,METHOD_GUARD:L,NUMBER_MODE:Y,NUMBER_RE:A,PHRASAL_WORDS_MODE:P,QUOTE_STRING_MODE:$,REGEXP_MODE:G,RE_STARTERS_RE:S,SHEBANG:O,TITLE_MODE:te,UNDERSCORE_IDENT_RE:E,UNDERSCORE_TITLE_MODE:re});function ee(le,De){le.input[le.index-1]==="."&&De.ignoreMatch()}function ne(le,De){le.className!==void 0&&(le.scope=le.className,delete le.className)}function X(le,De){De&&le.beginKeywords&&(le.begin="\\b("+le.beginKeywords.split(" ").join("|")+")(?!\\.)(?=\\b|\\s)",le.__beforeBegin=ee,le.keywords=le.keywords||le.beginKeywords,delete le.beginKeywords,le.relevance===void 0&&(le.relevance=0))}function he(le,De){Array.isArray(le.illegal)&&(le.illegal=b(...le.illegal))}function ae(le,De){if(le.match){if(le.begin||le.end)throw new Error("begin & end are not supported with match");le.begin=le.match,delete le.match}}function je(le,De){le.relevance===void 0&&(le.relevance=1)}const $e=(le,De)=>{if(!le.beforeMatch)return;if(le.starts)throw new Error("beforeMatch cannot be used with starts");const Ie=Object.assign({},le);Object.keys(le).forEach(Ge=>{delete le[Ge]}),le.keywords=Ie.keywords,le.begin=g(Ie.beforeMatch,f(Ie.begin)),le.starts={relevance:0,contains:[Object.assign(Ie,{endsParent:!0})]},le.relevance=0,delete Ie.beforeMatch},J=["of","and","for","in","not","or","if","then","parent","list","value"],Ne="keyword";function ve(le,De,Ie=Ne){const Ge=Object.create(null);return typeof le=="string"?ye(Ie,le.split(" ")):Array.isArray(le)?ye(Ie,le):Object.keys(le).forEach(function(ie){Object.assign(Ge,ve(le[ie],De,ie))}),Ge;function ye(ie,pe){De&&(pe=pe.map(xe=>xe.toLowerCase())),pe.forEach(function(xe){const Ke=xe.split("|");Ge[Ke[0]]=[ie,Me(Ke[0],Ke[1])]})}}function Me(le,De){return De?Number(De):Xe(le)?0:1}function Xe(le){return J.includes(le.toLowerCase())}const ze={},Fe=le=>{console.error(le)},tt=(le,...De)=>{console.log(`WARN: ${le}`,...De)},fe=(le,De)=>{ze[`${le}/${De}`]||(console.log(`Deprecated as of ${le}. ${De}`),ze[`${le}/${De}`]=!0)},U=new Error;function ce(le,De,{key:Ie}){let Ge=0;const ye=le[Ie],ie={},pe={};for(let xe=1;xe<=De.length;xe++)pe[xe+Ge]=ye[xe],ie[xe+Ge]=!0,Ge+=v(De[xe-1]);le[Ie]=pe,le[Ie]._emit=ie,le[Ie]._multi=!0}function ue(le){if(Array.isArray(le.begin)){if(le.skip||le.excludeBegin||le.returnBegin)throw Fe("skip, excludeBegin, returnBegin not compatible with beginScope: {}"),U;if(typeof le.beginScope!="object"||le.beginScope===null)throw Fe("beginScope must be object"),U;ce(le,le.begin,{key:"beginScope"}),le.begin=k(le.begin,{joinWith:""})}}function Ee(le){if(Array.isArray(le.end)){if(le.skip||le.excludeEnd||le.returnEnd)throw Fe("skip, excludeEnd, returnEnd not compatible with endScope: {}"),U;if(typeof le.endScope!="object"||le.endScope===null)throw Fe("endScope must be object"),U;ce(le,le.end,{key:"endScope"}),le.end=k(le.end,{joinWith:""})}}function bt(le){le.scope&&typeof le.scope=="object"&&le.scope!==null&&(le.beginScope=le.scope,delete le.scope)}function Ze(le){bt(le),typeof le.beginScope=="string"&&(le.beginScope={_wrap:le.beginScope}),typeof le.endScope=="string"&&(le.endScope={_wrap:le.endScope}),ue(le),Ee(le)}function vt(le){function De(pe,xe){return new RegExp(h(pe),"m"+(le.case_insensitive?"i":"")+(le.unicodeRegex?"u":"")+(xe?"g":""))}class Ie{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(xe,Ke){Ke.position=this.position++,this.matchIndexes[this.matchAt]=Ke,this.regexes.push([Ke,xe]),this.matchAt+=v(xe)+1}compile(){this.regexes.length===0&&(this.exec=()=>null);const xe=this.regexes.map(Ke=>Ke[1]);this.matcherRe=De(k(xe,{joinWith:"|"}),!0),this.lastIndex=0}exec(xe){this.matcherRe.lastIndex=this.lastIndex;const Ke=this.matcherRe.exec(xe);if(!Ke)return null;const St=Ke.findIndex((yn,no)=>no>0&&yn!==void 0),Jt=this.matchIndexes[St];return Ke.splice(0,St),Object.assign(Ke,Jt)}}class Ge{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(xe){if(this.multiRegexes[xe])return this.multiRegexes[xe];const Ke=new Ie;return this.rules.slice(xe).forEach(([St,Jt])=>Ke.addRule(St,Jt)),Ke.compile(),this.multiRegexes[xe]=Ke,Ke}resumingScanAtSamePosition(){return this.regexIndex!==0}considerAll(){this.regexIndex=0}addRule(xe,Ke){this.rules.push([xe,Ke]),Ke.type==="begin"&&this.count++}exec(xe){const Ke=this.getMatcher(this.regexIndex);Ke.lastIndex=this.lastIndex;let St=Ke.exec(xe);if(this.resumingScanAtSamePosition()&&!(St&&St.index===this.lastIndex)){const Jt=this.getMatcher(0);Jt.lastIndex=this.lastIndex+1,St=Jt.exec(xe)}return St&&(this.regexIndex+=St.position+1,this.regexIndex===this.count&&this.considerAll()),St}}function ye(pe){const xe=new Ge;return pe.contains.forEach(Ke=>xe.addRule(Ke.begin,{rule:Ke,type:"begin"})),pe.terminatorEnd&&xe.addRule(pe.terminatorEnd,{type:"end"}),pe.illegal&&xe.addRule(pe.illegal,{type:"illegal"}),xe}function ie(pe,xe){const Ke=pe;if(pe.isCompiled)return Ke;[ne,ae,Ze,$e].forEach(Jt=>Jt(pe,xe)),le.compilerExtensions.forEach(Jt=>Jt(pe,xe)),pe.__beforeBegin=null,[X,he,je].forEach(Jt=>Jt(pe,xe)),pe.isCompiled=!0;let St=null;return typeof pe.keywords=="object"&&pe.keywords.$pattern&&(pe.keywords=Object.assign({},pe.keywords),St=pe.keywords.$pattern,delete pe.keywords.$pattern),St=St||/\w+/,pe.keywords&&(pe.keywords=ve(pe.keywords,le.case_insensitive)),Ke.keywordPatternRe=De(St,!0),xe&&(pe.begin||(pe.begin=/\B|\b/),Ke.beginRe=De(Ke.begin),!pe.end&&!pe.endsWithParent&&(pe.end=/\B|\b/),pe.end&&(Ke.endRe=De(Ke.end)),Ke.terminatorEnd=h(Ke.end)||"",pe.endsWithParent&&xe.terminatorEnd&&(Ke.terminatorEnd+=(pe.end?"|":"")+xe.terminatorEnd)),pe.illegal&&(Ke.illegalRe=De(pe.illegal)),pe.contains||(pe.contains=[]),pe.contains=[].concat(...pe.contains.map(function(Jt){return It(Jt==="self"?pe:Jt)})),pe.contains.forEach(function(Jt){ie(Jt,Ke)}),pe.starts&&ie(pe.starts,xe),Ke.matcher=ye(Ke),Ke}if(le.compilerExtensions||(le.compilerExtensions=[]),le.contains&&le.contains.includes("self"))throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return le.classNameAliases=r(le.classNameAliases||{}),ie(le)}function Ot(le){return le?le.endsWithParent||Ot(le.starts):!1}function It(le){return le.variants&&!le.cachedVariants&&(le.cachedVariants=le.variants.map(function(De){return r(le,{variants:null},De)})),le.cachedVariants?le.cachedVariants:Ot(le)?r(le,{starts:le.starts?r(le.starts):null}):Object.isFrozen(le)?r(le):le}var Ut="11.11.2";class Lr extends Error{constructor(De,Ie){super(De),this.name="HTMLInjectionError",this.html=Ie}}const en=n,Hs=r,Os=Symbol("nomatch"),gr=7,Vs=function(le){const De=Object.create(null),Ie=Object.create(null),Ge=[];let ye=!0;const ie="Could not find the language '{}', did you forget to load/include a language module?",pe={disableAutodetect:!0,name:"Plain text",contains:[]};let xe={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:"hljs-",cssSelector:"pre code",languages:null,__emitter:d};function Ke(Qe){return xe.noHighlightRe.test(Qe)}function St(Qe){let kt=Qe.className+" ";kt+=Qe.parentNode?Qe.parentNode.className:"";const Ft=xe.languageDetectRe.exec(kt);if(Ft){const Wt=za(Ft[1]);return Wt||(tt(ie.replace("{}",Ft[1])),tt("Falling back to no-highlight mode for this block.",Qe)),Wt?Ft[1]:"no-highlight"}return kt.split(/\s+/).find(Wt=>Ke(Wt)||za(Wt))}function Jt(Qe,kt,Ft){let Wt="",Or="";typeof kt=="object"?(Wt=Qe,Ft=kt.ignoreIllegals,Or=kt.language):(fe("10.7.0","highlight(lang, code, ...args) has been deprecated."),fe("10.7.0",`Please use highlight(code, options) instead. 887https://github.com/highlightjs/highlight.js/issues/2277`),Or=Qe,Wt=kt),Ft===void 0&&(Ft=!0);const Wa={code:Wt,language:Or};Vd("before:highlight",Wa);const Ei=Wa.result?Wa.result:yn(Wa.language,Wa.code,Ft);return Ei.code=Wa.code,Vd("after:highlight",Ei),Ei}function yn(Qe,kt,Ft,Wt){const Or=Object.create(null);function Wa(lt,Nt){return lt.keywords[Nt]}function Ei(){if(!ct.keywords){Fr.addText(Wn);return}let lt=0;ct.keywordPatternRe.lastIndex=0;let Nt=ct.keywordPatternRe.exec(Wn),Gt="";for(;Nt;){Gt+=Wn.substring(lt,Nt.index);const Cn=qe.case_insensitive?Nt[0].toLowerCase():Nt[0],Gs=Wa(ct,Cn);if(Gs){const[_l,gY]=Gs;if(Fr.addText(Gt),Gt="",Or[Cn]=(Or[Cn]||0)+1,Or[Cn]<=gr&&(eg+=gY),_l.startsWith("_"))Gt+=Nt[0];else{const yY=qe.classNameAliases[_l]||_l;qs(Nt[0],yY)}}else Gt+=Nt[0];lt=ct.keywordPatternRe.lastIndex,Nt=ct.keywordPatternRe.exec(Wn)}Gt+=Wn.substring(lt),Fr.addText(Gt)}function Au(){if(Wn==="")return;let lt=null;if(typeof ct.subLanguage=="string"){if(!De[ct.subLanguage]){Fr.addText(Wn);return}lt=yn(ct.subLanguage,Wn,!0,ms[ct.subLanguage]),ms[ct.subLanguage]=lt._top}else lt=bc(Wn,ct.subLanguage.length?ct.subLanguage:null);ct.relevance>0&&(eg+=lt.relevance),Fr.__addSublanguage(lt._emitter,lt.language)}function ya(){ct.subLanguage!=null?Au():Ei(),Wn=""}function qs(lt,Nt){lt!==""&&(Fr.startScope(Nt),Fr.addText(lt),Fr.endScope())}function Zf(lt,Nt){let Gt=1;const Cn=Nt.length-1;for(;Gt<=Cn;){if(!lt._emit[Gt]){Gt++;continue}const Gs=qe.classNameAliases[lt[Gt]]||lt[Gt],_l=Nt[Gt];Gs?qs(_l,Gs):(Wn=_l,Ei(),Wn=""),Gt++}}function Xf(lt,Nt){return lt.scope&&typeof lt.scope=="string"&&Fr.openNode(qe.classNameAliases[lt.scope]||lt.scope),lt.beginScope&&(lt.beginScope._wrap?(qs(Wn,qe.classNameAliases[lt.beginScope._wrap]||lt.beginScope._wrap),Wn=""):lt.beginScope._multi&&(Zf(lt.beginScope,Nt),Wn="")),ct=Object.create(lt,{parent:{value:ct}}),ct}function Jf(lt,Nt,Gt){let Cn=w(lt.endRe,Gt);if(Cn){if(lt["on:end"]){const Gs=new t(lt);lt["on:end"](Nt,Gs),Gs.isMatchIgnored&&(Cn=!1)}if(Cn){for(;lt.endsParent&<.parent;)lt=lt.parent;return lt}}if(lt.endsWithParent)return Jf(lt.parent,Nt,Gt)}function Xx(lt){return ct.matcher.regexIndex===0?(Wn+=lt[0],1):(Gw=!0,0)}function Jx(lt){const Nt=lt[0],Gt=lt.rule,Cn=new t(Gt),Gs=[Gt.__beforeBegin,Gt["on:begin"]];for(const _l of Gs)if(_l&&(_l(lt,Cn),Cn.isMatchIgnored))return Xx(Nt);return Gt.skip?Wn+=Nt:(Gt.excludeBegin&&(Wn+=Nt),ya(),!Gt.returnBegin&&!Gt.excludeBegin&&(Wn=Nt)),Xf(Gt,lt),Gt.returnBegin?0:Nt.length}function Qx(lt){const Nt=lt[0],Gt=kt.substring(lt.index),Cn=Jf(ct,lt,Gt);if(!Cn)return Os;const Gs=ct;ct.endScope&&ct.endScope._wrap?(ya(),qs(Nt,ct.endScope._wrap)):ct.endScope&&ct.endScope._multi?(ya(),Zf(ct.endScope,lt)):Gs.skip?Wn+=Nt:(Gs.returnEnd||Gs.excludeEnd||(Wn+=Nt),ya(),Gs.excludeEnd&&(Wn=Nt));do ct.scope&&Fr.closeNode(),!ct.skip&&!ct.subLanguage&&(eg+=ct.relevance),ct=ct.parent;while(ct!==Cn.parent);return Cn.starts&&Xf(Cn.starts,lt),Gs.returnEnd?0:Nt.length}function se(){const lt=[];for(let Nt=ct;Nt!==qe;Nt=Nt.parent)Nt.scope&<.unshift(Nt.scope);lt.forEach(Nt=>Fr.openNode(Nt))}let ke={};function Te(lt,Nt){const Gt=Nt&&Nt[0];if(Wn+=lt,Gt==null)return ya(),0;if(ke.type==="begin"&&Nt.type==="end"&&ke.index===Nt.index&&Gt===""){if(Wn+=kt.slice(Nt.index,Nt.index+1),!ye){const Cn=new Error(`0 width match regex (${Qe})`);throw Cn.languageName=Qe,Cn.badRule=ke.rule,Cn}return 1}if(ke=Nt,Nt.type==="begin")return Jx(Nt);if(Nt.type==="illegal"&&!Ft){const Cn=new Error('Illegal lexeme "'+Gt+'" for mode "'+(ct.scope||"<unnamed>")+'"');throw Cn.mode=ct,Cn}else if(Nt.type==="end"){const Cn=Qx(Nt);if(Cn!==Os)return Cn}if(Nt.type==="illegal"&&Gt==="")return Nt.index===kt.length||(Wn+=` 888`),1;if(qw>1e5&&qw>Nt.index*3)throw new Error("potential infinite loop, way more iterations than matches");return Wn+=Gt,Gt.length}const qe=za(Qe);if(!qe)throw Fe(ie.replace("{}",Qe)),new Error('Unknown language: "'+Qe+'"');const ht=vt(qe);let ut="",ct=Wt||ht;const ms={},Fr=new xe.__emitter(xe);se();let Wn="",eg=0,Tu=0,qw=0,Gw=!1;try{if(qe.__emitTokens)qe.__emitTokens(kt,Fr);else{for(ct.matcher.considerAll();;){qw++,Gw?Gw=!1:ct.matcher.considerAll(),ct.matcher.lastIndex=Tu;const lt=ct.matcher.exec(kt);if(!lt)break;const Nt=kt.substring(Tu,lt.index),Gt=Te(Nt,lt);Tu=lt.index+Gt}Te(kt.substring(Tu))}return Fr.finalize(),ut=Fr.toHTML(),{language:Qe,value:ut,relevance:eg,illegal:!1,_emitter:Fr,_top:ct}}catch(lt){if(lt.message&<.message.includes("Illegal"))return{language:Qe,value:en(kt),illegal:!0,relevance:0,_illegalBy:{message:lt.message,index:Tu,context:kt.slice(Tu-100,Tu+100),mode:lt.mode,resultSoFar:ut},_emitter:Fr};if(ye)return{language:Qe,value:en(kt),illegal:!1,relevance:0,errorRaised:lt,_emitter:Fr,_top:ct};throw lt}}function no(Qe){const kt={value:en(Qe),illegal:!1,relevance:0,_top:pe,_emitter:new xe.__emitter(xe)};return kt._emitter.addText(Qe),kt}function bc(Qe,kt){kt=kt||xe.languages||Object.keys(De);const Ft=no(Qe),Wt=kt.filter(za).filter(Eu).map(ya=>yn(ya,Qe,!1));Wt.unshift(Ft);const Or=Wt.sort((ya,qs)=>{if(ya.relevance!==qs.relevance)return qs.relevance-ya.relevance;if(ya.language&&qs.language){if(za(ya.language).supersetOf===qs.language)return 1;if(za(qs.language).supersetOf===ya.language)return-1}return 0}),[Wa,Ei]=Or,Au=Wa;return Au.secondBest=Ei,Au}function Ce(Qe,kt,Ft){const Wt=kt&&Ie[kt]||Ft;Qe.classList.add("hljs"),Qe.classList.add(`language-${Wt}`)}function yr(Qe){let kt=null;const Ft=St(Qe);if(Ke(Ft))return;if(Vd("before:highlightElement",{el:Qe,language:Ft}),Qe.dataset.highlighted){console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",Qe);return}if(Qe.children.length>
8880&&(xe.ignoreUnescapedHTML||(console.warn("One of your code blocks includes unescaped HTML. This is a potentially serious security risk."),console.warn("https://github.com/highlightjs/highlight.js/wiki/security"),console.warn("The element with unescaped HTML:"),console.warn(Qe)),xe.throwUnescapedHTML))throw new Lr("One of your code blocks includes unescaped HTML.",Qe.innerHTML);kt=Qe;const Wt=kt.textContent,Or=Ft?Jt(Wt,{language:Ft,ignoreIllegals:!0}):bc(Wt);Qe.innerHTML=Or.value,Qe.dataset.highlighted="yes",Ce(Qe,Ft,Or.language),Qe.result={language:Or.language,re:Or.relevance,relevance:Or.relevance},Or.secondBest&&(Qe.secondBest={language:Or.secondBest.language,relevance:Or.secondBest.relevance}),Vd("after:highlightElement",{el:Qe,result:Or,text:Wt})}function Ua(Qe){xe=Hs(xe,Qe)}const Ci=()=>{ro(),fe("10.6.0","initHighlighting() deprecated. Use highlightAll() now.")};function or(){ro(),fe("10.6.0","initHighlightingOnLoad() deprecated. Use highlightAll() now.")}let vc=!1;function ro(){function Qe(){ro()}if(document.readyState==="loading"){vc||window.addEventListener("DOMContentLoaded",Qe,!1),vc=!0;return}document.querySelectorAll(xe.cssSelector).forEach(yr)}function Su(Qe,kt){let Ft=null;try{Ft=kt(le)}catch(Wt){if(Fe("Language definition for '{}' could not be registered.".replace("{}",Qe)),ye)Fe(Wt);else throw Wt;Ft=pe}Ft.name||(Ft.name=Qe),De[Qe]=Ft,Ft.rawDefinition=kt.bind(null,le),Ft.aliases&&Cu(Ft.aliases,{languageName:Qe})}function wc(Qe){delete De[Qe];for(const kt of Object.keys(Ie))Ie[kt]===Qe&&delete Ie[kt]}function so(){return Object.keys(De)}function za(Qe){return Qe=(Qe||"").toLowerCase(),De[Qe]||De[Ie[Qe]]}function Cu(Qe,{languageName:kt}){typeof Qe=="string"&&(Qe=[Qe]),Qe.forEach(Ft=>{Ie[Ft.toLowerCase()]=kt})}function Eu(Qe){const kt=za(Qe);return kt&&!kt.disableAutodetect}function Ww(Qe){Qe["before:highlightBlock"]&&!Qe["before:highlightElement"]&&(Qe["before:highlightElement"]=kt=>{Qe["before:highlightBlock"](Object.assign({block:kt.el},kt))}),Qe["after:highlightBlock"]&&!Qe["after:highlightElement"]&&(Qe["after:highlightElement"]=kt=>{Qe["after:highlightBlock"](Object.assign({block:kt.el},kt))})}function Kw(Qe){Ww(Qe),Ge.push(Qe)}function Hw(Qe){const kt=Ge.indexOf(Qe);kt!==-1&&Ge.splice(kt,1)}function Vd(Qe,kt){const Ft=Qe;Ge.forEach(function(Wt){Wt[Ft]&&Wt[Ft](kt)})}function Vw(Qe){return fe("10.7.0","highlightBlock will be removed entirely in v12.0"),fe("10.7.0","Please use highlightElement now."),yr(Qe)}Object.assign(le,{highlight:Jt,highlightAuto:bc,highlightAll:ro,highlightElement:yr,highlightBlock:Vw,configure:Ua,initHighlighting:Ci,initHighlightingOnLoad:or,registerLanguage:Su,unregisterLanguage:wc,listLanguages:so,getLanguage:za,registerAliases:Cu,autoDetection:Eu,inherit:Hs,addPlugin:Kw,removePlugin:Hw}),le.debugMode=function(){ye=!1},le.safeMode=function(){ye=!0},le.versionString=Ut,le.regex={concat:g,lookahead:f,either:b,optional:x,anyNumberOfTimes:m};for(const Qe in me)typeof me[Qe]=="object"&&e(me[Qe]);return Object.assign(le,me),le},Xn=Vs({});return Xn.newInstance=()=>Vs({}),Tk=Xn,Xn.HighlightJS=Xn,Xn.default=Xn,Tk}var L8e=$8e();const F8e=hl(L8e),$M={},B8e="hljs-";function U8e(e){const t=F8e.newInstance();return e&&i(e),{highlight:n,highlightAuto:r,listLanguages:a,register:i,registerAlias:o,registered:l};function n(c,u,d){const h=d||$M,f=typeof h.prefix=="string"?h.prefix:B8e;if(!t.getLanguage(c))throw new Error("Unknown language: `"+c+"` is not registered");t.configure({__emitter:z8e,classPrefix:f});const m=t.highlight(u,{ignoreIllegals:!0,language:c});if(m.errorRaised)throw new Error("Could not highlight with `Highlight.js`",{cause:m.errorRaised});const x=m._emitter.root,g=x.data;return g.language=m.language,g.relevance=m.relevance,x}function r(c,u){const h=(u||$M).subset||a();let f=-1,m=0,x;for(;++f<h.length;){const g=h[f];if(!t.getLanguage(g))continue;const y=n(g,c,u);y.data&&y.data.relevance!==void 0&&y.data.relevance>m&&(m=y.data.relevance,x=y)}return x||{type:"root",children:[],data:{language:void 0,relevance:m}}}function a(){return t.listLanguages()}function i(c,u){if(typeof c=="string")t.registerLanguage(c,u);else{let d;for(d in c)Object.hasOwn(c,d)&&t.registerLanguage(d,c[d])}}function o(c,u){if(typeof c=="string")t.registerAliases(typeof u=="string"?u:[...u],{languageName:c});else{let d;for(d in c)if(Object.hasOwn(c,d)){const h=c[d];t.registerAliases(typeof h=="string"?h:[...h],{languageName:d})}}}function l(c){return!!t.getLanguage(c)}}class z8e{constructor(t){this.options=t,this.root={type:"root",children:[],data:{language:void 0,relevance:0}},this.stack=[this.root]}addText(t){if(t==="")return;const n=this.stack[this.stack.length-1],r=n.children[n.children.length-1];r&&r.type==="text"?r.value+=t:n.children.push({type:"text",value:t})}startScope(t){this.openNode(String(t))}endScope(){this.closeNode()}__addSublanguage(t,n){const r=this.stack[this.stack.length-1],a=t.root.children;n?r.children.push({type:"element",tagName:"span",properties:{className:[n]},children:a}):r.children.push(...a)}openNode(t){const n=this,r=t.split(".").map(function(o,l){return l?o+"_".repeat(l):n.options.classPrefix+o}),a=this.stack[this.stack.length-1],i={type:"element",tagName:"span",properties:{className:r},children:[]};a.children.push(i),this.stack.push(i)}closeNode(){this.stack.pop()}finalize(){}toHTML(){return""}}const W8e={};function m3(e){const t=e||W8e,n=t.aliases,r=t.detect||!1,a=t.languages||M8e,
888i=t.plainText,o=t.prefix,l=t.subset;let c="hljs";const u=U8e(a);if(n&&u.registerAlias(n),o){const d=o.indexOf("-");c=d===-1?o:o.slice(0,d)}return function(d,h){p0(d,"element",function(f,m,x){if(f.tagName!=="code"||!x||x.type!=="element"||x.tagName!=="pre")return;const g=K8e(f);if(g===!1||!g&&!r||g&&i&&i.includes(g))return;Array.isArray(f.properties.className)||(f.properties.className=[]),f.properties.className.includes(c)||f.properties.className.unshift(c);const y=oLe(f,{whitespace:"pre"});let b;try{b=g?u.highlight(g,y,{prefix:o}):u.highlightAuto(y,{prefix:o,subset:l})}catch(v){const w=v;if(g&&/Unknown language/.test(w.message)){h.message("Cannot highlight as `"+g+"`, itâs not registered",{ancestors:[x,f],cause:w,place:f.position,ruleId:"missing-language",source:"rehype-highlight"});return}throw w}!g&&b.data&&b.data.language&&f.properties.className.push("language-"+b.data.language),b.children.length>0&&(f.children=b.children)})}}function K8e(e){const t=e.properties.className;let n=-1;if(!Array.isArray(t))return;let r;for(;++n<t.length;){const a=String(t[n]);if(a==="no-highlight"||a==="nohighlight")return!1;!r&&a.slice(0,5)==="lang-"&&(r=a.slice(5)),!r&&a.slice(0,9)==="language-"&&(r=a.slice(9))}return r}function _w(e){const t=String(e??"").trim();return!t||t.startsWith("//")||/[\u0000-\u001F\u007F]/.test(t)?!1:/^(https?:|mailto:|\/|#|\?)/i.test(t)}function yv(e){const t=String(e??"").trim();return _w(t)?t:"#"}const LM=Be().min(1).max(2e3).refine(_w,"url must be http(s), mailto, or a same-origin path"),dV=Dt({file:Be().min(1).max(200),url:LM,size:Be().max(20).optional(),kind:Be().max(40).optional(),expires:Be().max(40).optional(),destination_url:LM.optional()}),H8e=Be().min(1).max(400).refine(e=>e.toLowerCase().endsWith(".md"),"path must end in .md").refine(e=>!e.includes("..")&&!e.startsWith("/"),"path must be relative"),hV=Dt({slug:Be().min(1).max(80),path:H8e,title:Be().min(1).max(200).optional()}),fV=Dt({url:Be().min(1).max(2e3).refine(_w,"url must be http(s), mailto, or a same-origin path"),label:Be().min(1).max(80),service:Be().max(80).optional()}),mV=Dt({title:Be().min(1).max(200),type:Ia(["general","listing_upgrade","customer_communication","stockout_followup","returns_followup","billing","other"]).default("general"),assignee:Be().max(80).optional(),due:Be().max(40).optional(),seller:Be().max(80).optional()}),pV=Dt({name:Be().min(1).max(80),seller:Be().max(80).optional(),label:Be().max(120).optional()}),xV=Dt({label:Be().min(1).max(80),value:Be().min(1).max(60),delta:Be().max(40).optional(),trend:Ia(["up","down","flat"]).optional(),subtitle:Be().max(120).optional()}),gV=Dt({data:Be().min(1).max(2e3),label:Be().max(80).optional(),height:Jy().min(12).max(120).optional(),width:Jy().min(40).max(600).optional()}),yV=Dt({state:Ia(["pending","running","ok","error"]),message:Be().max(200).optional(),progress:Jy().min(0).max(100).optional()}),bV=Dt({label:Be().min(1).max(80),url:Be().min(1).max(2e3).refine(_w,"url must be http(s) or a same-origin path").optional(),path:Be().min(1).max(400).optional(),mode:Ia(["angle","lifestyle"]).default("angle"),bypass:Ia(["true","false"]).optional()}).refine(e=>e.url||e.path,{message:"image-thumb requires either `path` (preferred) or `url`"}),vV=Dt({sku:Be().min(1).max(120).optional()}),wV=Dt({search_id:Be().min(1),limit:Jy().int().min(1).max(20).optional().default(10),title:Be().max(120).optional()}),Wf=Be().regex(/^[a-z_][a-z0-9_]*$/).max(40),Wg=Dt({type:Ia(["text","textarea","number","date"]),name:Wf,label:Be().min(1).max(200),placeholder:Be().max(200).optional(),default:pf([Be(),Ur()]).optional(),required:ac().optional(),pattern:Be().max(500).optional(),minlength:Ur().int().min(0).max(5e4).optional(),maxlength:Ur().int().min(1).max(5e4).optional(),min:Ur().optional(),max:Ur().optional(),help:Be().max(500).optional()}),V8e=Dt({type:kn("checkbox-group"),name:Wf,label:Be().min(1).max(200),options:Nr(Be().min(1).max(200)).min(1).max(30),default:Nr(Be()).optional(),required:ac().optional(),help:Be().max(500).optional()}),q8e=Dt({type:kn("radio-group"),name:Wf,label:Be().min(1).max(200),options:Nr(Be().min(1).max(200)).min(2).max(20),default:Be().optional(),required:ac().optional(),help:Be().max(500).optional()}),G8e=Dt({endpoint:Be().min(1).max(200)}),Y8e=Dt({type:kn("select"),name:Wf,label:Be().min(1).max(200),options:Nr(Be().min(1).max(200)).min(1).max(500).optional(),options_source:G8e.optional(),default:Be().optional(),required:ac().optional(),help:Be().max(500).optional()}),Z8e=Dt({type:kn("confirm"),name:Wf,label:Be().min(1).max(200),expected:Be().min(1).max(80),help:Be().max(500).optional()}),X8e=Dt({type:kn("file"),name:Wf,label:Be().min(1).max(200),accept:Be().max(200).optional(),multiple:ac().optional(),required:ac().optional(),help:Be().max(500).optional()}),J8e=H6("type",[Wg.extend({type:kn("text")}),Wg.extend({type:kn("textarea")}),Wg.extend({type:kn("number")}),Wg.extend({type:kn("date")}),V8e,q8e,Y8e,Z8e,X8e]),_V=Dt({id:Be().regex(/^[a-z0-9_-]+$/i).min(1).max(80),fields:Nr(J8e).min(1).max(20),submit_label:Be().max(40).optional(),cancel_label:Be().max(40).optional(),intro:Be().max(500).optional()});function Q8e(e,t){const n={},r={};for(const a of e.fields){const i=t==null?void 0:t[a.name],o=i==null||i===""||Array.isArray(i)&&i.length===0;if(a.required&&o){n[a.name]="Required.";continue}if(o){r[a.name]=a.default??(a.type==="checkbox-group"?[]:"");continue}if(a.type==="text"||a.type==="textarea"){const l=String(i);if(a.minlength!=null&&l.length<a.minlength){n[a.name]=`Must be at least ${a.minlength} characters.`;continue}if(a.maxlength!=null&&l.length>a.maxlength){n[a.name]=`Must be at most ${a.maxlength} characters.`;continue}
888if(a.pattern)try{if(!new RegExp(a.pattern).test(l)){n[a.name]="Doesn't match the required format.";continue}}catch{}r[a.name]=l}else if(a.type==="number"){const l=Number(i);if(!Number.isFinite(l)){n[a.name]="Must be a number.";continue}if(a.min!=null&&l<a.min){n[a.name]=`Must be at least ${a.min}.`;continue}if(a.max!=null&&l>a.max){n[a.name]=`Must be at most ${a.max}.`;continue}r[a.name]=l}else if(a.type==="date"){const l=new Date(String(i));if(Number.isNaN(l.getTime())){n[a.name]="Must be a valid date.";continue}r[a.name]=String(i)}else if(a.type==="checkbox-group"){const l=Array.isArray(i)?i:[i],c=new Set(a.options),u=l.filter(d=>c.has(d));if(u.length!==l.length){n[a.name]="Some selections aren't valid options.";continue}r[a.name]=u}else if(a.type==="radio-group"||a.type==="select")if(a.options_source||!Array.isArray(a.options))r[a.name]=String(i);else if(a.options.includes(String(i)))r[a.name]=String(i);else{n[a.name]="Not a valid option.";continue}else if(a.type==="confirm"){if(String(i)!==a.expected){n[a.name]=`Must type "${a.expected}" exactly.`;continue}r[a.name]=String(i)}else if(a.type==="file"){const c=(Array.isArray(i)?i:[i]).map(u=>typeof u=="string"?u:(u==null?void 0:u.filename)??(u==null?void 0:u.name)??"");if(c.some(u=>!u)){n[a.name]="File upload is missing a filename.";continue}if(a.accept){const u=a.accept.split(",").map(d=>d.trim().toLowerCase()).filter(d=>d.startsWith("."));if(u.length>0&&c.some(d=>!u.some(h=>d.toLowerCase().endsWith(h)))){n[a.name]=`Must be a ${u.join(" / ")} file.`;continue}}r[a.name]=a.multiple?c:c[0]}}return{ok:Object.keys(n).length===0,errors:n,values:r}}const kw=Ia(["neutral","good","warn","bad"]),kV=Ia(["neutral","good","warn","bad","info"]),e6e=Ia(["up","down","flat"]),t6e=Ia(["info","success","warn","danger"]),n6e=Ia(["info","success","warn","danger","tip","note"]),jV=Ia(["currency","percent","number"]),NV=Dt({type:kn("gadjet-header"),title:Be().min(1).max(200),subtitle:Be().max(300).optional(),period:Be().max(80).optional(),updated:Be().max(80).optional()}),SV=Dt({type:kn("gadjet-section"),title:Be().min(1).max(200),subtitle:Be().max(300).optional()}),CV=Dt({type:kn("gadjet-kpi-grid"),columns:Ur().int().min(1).max(6).optional()}),EV=Dt({type:kn("gadjet-divider"),label:Be().max(120).optional()}),AV=Dt({type:kn("gadjet-stat-card"),label:Be().min(1).max(120),value:Be().min(1).max(80),trend:e6e.optional(),delta:Be().max(40).optional(),tone:kw.optional()}),TV=Dt({type:kn("gadjet-callout"),callout_type:n6e,title:Be().max(200).optional()}),OV=Dt({type:kn("gadjet-empty-state"),message:Be().max(300).optional(),icon:Be().max(40).optional()}),IV=Dt({type:kn("gadjet-alert-banner"),alert_type:t6e,title:Be().min(1).max(200),body:Be().max(500).optional(),cta_label:Be().max(80).optional(),cta_href:Be().max(2e3).optional()}),PV=Dt({type:kn("gadjet-bullet-list"),items:Nr(Be().max(500)).min(1).max(50),icon:Be().max(40).optional()}),RV=Dt({type:kn("gadjet-badge-row"),items:Nr(pf([Be().max(80),Dt({label:Be().max(80),tone:kV.optional()})])).min(1).max(20)}),DV=Dt({type:kn("gadjet-rank-list"),items:Nr(Dt({label:Be().max(200),value:pf([Be(),Ur()]).optional(),delta:Be().max(40).optional(),sub:Be().max(200).optional(),image:Be().max(2e3).optional()})).min(1).max(50),numbered:ac().optional(),value_format:jV.optional()}),MV=Dt({type:kn("gadjet-timeline"),items:Nr(Dt({when:Be().max(80),title:Be().max(200),body:Be().max(500).optional(),tone:kV.optional()})).min(1).max(30)}),$V=Dt({type:kn("gadjet-progress-bar"),value:Ur(),max:Ur().positive(),label:Be().max(200).optional(),caption:Be().max(200).optional(),tone:kw.optional(),show_percent:ac().optional()}),LV=Dt({type:kn("gadjet-spark-bar"),values:Nr(Ur()).min(1).max(60),labels:Nr(Be()).max(60).optional(),height:Ur().int().min(20).max(120).optional(),tone:kw.optional()}),FV=Dt({type:kn("gadjet-trend-line"),values:Nr(Ur()).min(2).max(365),values_prior:Nr(Ur()).max(365).optional(),labels:Nr(Be()).max(365).optional(),height:Ur().int().min(60).max(360).optional(),tone:kw.optional(),y_label:Be().max(80).optional()}),BV=Dt({type:kn("gadjet-donut"),slices:Nr(Dt({label:Be().max(120),value:Ur().nonnegative(),color:Be().max(40).optional()})).min(1).max(12),total_label:Be().max(80).optional(),total_value:Be().max(80).optional(),size:Ur().int().min(80).max(400).optional()}),UV=Dt({type:kn("gadjet-waterfall"),steps:Nr(Dt({label:Be().max(120),value:Ur(),step_type:Ia(["auto","total","subtotal"]).optional()})).min(1).max(20),starting_value:Ur().optional(),height:Ur().int().min(120).max(480).optional()}),zV=Dt({type:kn("gadjet-data-table"),columns:Nr(Dt({key:Be().regex(/^[a-z_][a-z0-9_]*$/).max(40),label:Be().max(80),format:jV.optional(),align:Ia(["left","right","center"]).optional()})).min(1).max(20),rows:Nr(I2(Be(),pf([Be(),Ur(),Nee()]))).max(500),caption:Be().max(200).optional()}),WV=Dt({type:kn("gadjet-ask-ai"),label:Be().min(1).max(80),prompt:Be().min(1).max(500),seller:Be().max(80).optional()}),KV=Dt({type:kn("gadjet-run-skill"),label:Be().min(1).max(80),skill:Be().min(1).max(80),args:I2(Be(),pf([Be(),Ur(),ac()])).optional(),seller:Be().max(80).optional()}),HV=Dt({type:kn("gadjet-link"),label:Be().min(1).max(80),href:Be().min(1).max(2e3)}),$y=Xee(()=>H6("type",[NV,SV.extend({children:Nr($y).max(50)}),CV.extend({children:Nr($y).max(20)}),EV,AV,TV.extend({children:Nr($y).max(20)}),OV,IV,PV,RV,DV,MV,$V,LV,FV,BV,UV,zV,WV,KV,HV]));Dt({version:kn(1).optional().default(1),components:Nr($y).min(1).max(100),data_spec:I2(Be(),nN()).optional()});const r6e={"gadjet-header":NV,"gadjet-section":SV,"gadjet-kpi-grid":CV,"gadjet-divider":EV,"gadjet-stat-card":AV,"gadjet-callout":TV,"gadjet-empty-state":OV,"gadjet-alert-banner":IV,"gadjet-bullet-list":PV,"gadjet-badge-row":RV,"gadjet-rank-list":DV,"gadjet-timeline":MV,"gadjet-progress-bar":$V,"gadjet-spark-bar":LV,"gadjet-trend-line":FV,"gadjet-donut":BV,"gadjet-waterfall":UV,"gadjet-data-table":zV,"gadjet-ask-ai":WV,"gadjet-run-skill":KV,"gadjet-link":HV},s6e={"download-card":{schema:dV,category:"artifact",interactive:!0},"report-card":{schema:hV,category:"artifact",interactive:!0},"upload-prompt":{schema:fV,category:"action",interactive:!0},"task-card":{schema:mV,category:"action",interactive:!0},"skill-suggest":{schema:pV,category:"display",interactive:!0},"stat-card":{schema:xV,category:"display",interactive:!1}
888,sparkline:{schema:gV,category:"display",interactive:!1},"sync-status":{schema:yV,category:"display",interactive:!1},"image-thumb":{schema:bV,category:"display",interactive:!0},"image-gallery":{schema:vV,category:"display",interactive:!1},"market-explorer-table":{schema:wV,category:"display",interactive:!1},form:{schema:_V,category:"form",interactive:!0},...Object.fromEntries(Object.entries(r6e).map(([e,t])=>[e,{schema:t,category:"dashboard",interactive:e==="gadjet-ask-ai"||e==="gadjet-run-skill"||e==="gadjet-link"}]))};function a6e(e){return Object.prototype.hasOwnProperty.call(s6e,e)}function VV(e,t){if(!(!e||typeof e!="object")&&Array.isArray(e.children)){for(const n of e.children)if(n&&typeof n=="object"&&"type"in n){const r=n;(r.type==="containerDirective"||r.type==="leafDirective"||r.type==="textDirective")&&t(r),VV(r,t)}}}const p3=()=>e=>{VV(e,t=>{if(!a6e(t.name))return;const n=t.data||(t.data={});n.hName=`gadjet-${t.name}`;const r=t.attributes||{},a={};for(const[i,o]of Object.entries(r))o!=null&&(a[i]=String(o));n.hProperties=a})},i6e={replen:{url:"https://sellers.takealot.com/existing-offers/manage-offers?m=replenish-stock",label:"Open Takealot replen",service:"Takealot Seller Portal · Existing Offers â Replenish Stock"},"edit-request":{url:"https://help.takealot.com/hc/en-us/requests/new?ticket_form_id=316708&&tf_34289967=internal_department_catalogue&&tf_80896587=edit_request",label:"Open Edit Request form",service:"Takealot Seller Support · Catalogue â Edit Request"},"stock-recon-claim":{url:"https://help.takealot.com/hc/en-us/requests/new?ticket_form_id=316708&&tf_34289967=internal_department_marketplace&&tf_24926807=merchant_queries",label:"Open Seller Support ticket",service:"Takealot Seller Support · Marketplace â Merchant Queries"},promotion:{url:null,label:"Open promotion on Takealot",service:"Takealot Seller Portal · Promotions"},"fba-inbound-manifest":{url:"https://sellercentral.amazon.co.za/fba/sendtoamazon/confirm_content_step",label:"Open Send to Amazon",service:"Amazon Seller Central · Send to Amazon â Confirm content"}};function qV(e){return!e||typeof e!="string"?null:i6e[e]??null}function ni({type:e,inline:t=!1}){return s.jsx(Ta,{variant:t?"text":"block",className:t?"not-prose":"not-prose my-3","aria-label":`Loading ${e}`})}function o6e(e){var n;const t=((n=e.split(".").pop())==null?void 0:n.toLowerCase())??"";return["xlsx","xls","csv"].includes(t)?nF:["pdf","doc","docx","txt","md"].includes(t)?il:["zip","tar","gz"].includes(t)?hne:["png","jpg","jpeg","gif","webp"].includes(t)?mne:vne}const l6e=/^(?:https?:\/\/[^/]+)?\/exports\/(\d+)\/?$/;async function c6e(e,t){const n=await oe(`/api/exports/${encodeURIComponent(e)}`);
888if(!n.ok)throw new Error(`Could not fetch download link (${n.status})`);const r=await n.json();if(!(r!=null&&r.signed_url))throw new Error("Server did not return a download link.");const a=document.createElement("a");a.href=r.signed_url,a.download=r.filename||t,a.rel="noopener",document.body.appendChild(a),a.click(),a.remove()}function u6e(e){var j,N;const t=dV.safeParse(e),[n,r]=p.useState(!1),[a,i]=p.useState(null),[o,l]=p.useState(null),[c,u]=p.useState(!1),d=t.success?(j=t.data.url.match(l6e))==null?void 0:j[1]:void 0;if(p.useEffect(()=>{if(!d)return;let E=!1;return oe(`/api/exports/${encodeURIComponent(d)}`).then(A=>A.ok?A.json():null).then(A=>{var C,T,S;E||!((T=(C=A==null?void 0:A.preview)==null?void 0:C.columns)!=null&&T.length)||!((S=A.preview.rows)!=null&&S.length)||l(A.preview)}).catch(()=>{}),()=>{E=!0}},[d]),!t.success)return s.jsx(ni,{type:"download-card"});const{file:h,url:f,size:m,expires:x,kind:g,destination_url:y}=t.data,b=o6e(h),v=(N=h.split(".").pop())==null?void 0:N.toUpperCase(),w=qV(g),_=y??(w==null?void 0:w.url)??null;async function k(E){if(d&&(E.preventDefault(),!n)){r(!0),i(null);try{await c6e(d,h)}catch(A){i(A instanceof Error?A.message:String(A))}finally{r(!1)}}}return s.jsxs("div",{className:"not-prose my-3 rounded-lg border border-outline-subtle bg-surface shadow-xs overflow-hidden",children:[s.jsxs("div",{className:"flex items-start gap-3 px-4 py-3",children:[s.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-surface-sunken text-text-secondary",children:s.jsx(b,{className:"h-5 w-5"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx("div",{className:"truncate text-body-md font-medium text-text-primary",children:h}),v?s.jsxs("span",{className:"shrink-0 rounded border border-outline-subtle bg-surface-subtle px-1.5 py-0.5 text-body-xs font-medium uppercase tracking-wider text-text-secondary",children:[".",v.toLowerCase()]}):null]}),e.children?s.jsx("div",{className:"mt-0.5 text-body-sm leading-snug text-text-body",children:e.children}):null,s.jsxs("div",{className:"mt-1 flex flex-wrap gap-x-3 gap-y-0.5 text-body-xs text-text-secondary",children:[m?s.jsx("span",{children:m}):null,x&&!d?s.jsxs("span",{children:["Expires ",x]}):null,a?s.jsx("span",{className:"text-text-error",children:a}):null]})]}),s.jsxs("div",{className:"flex shrink-0 flex-wrap items-center justify-end gap-2",children:[d&&(v==null?void 0:v.toLowerCase())==="pdf"?s.jsxs("a",{href:`/exports/${d}?view=1`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 rounded-md border border-outline-subtle bg-surface px-3 py-1.5 text-body-sm font-medium text-text-primary shadow-xs transition hover:bg-surface-subtle focus-visible:outline-none focus-visible:shadow-focus",children:[s.jsx(Qt,{className:"h-3.5 w-3.5"}),"View"]}
888):null,s.jsxs("a",{href:yv(f),onClick:d?k:void 0,target:d?void 0:"_blank",rel:d?void 0:"noopener noreferrer","aria-busy":n||void 0,className:"inline-flex items-center gap-1.5 rounded-md bg-intent-brand px-3 py-1.5 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover focus-visible:outline-none focus-visible:shadow-focus",children:[n?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):s.jsx(Dr,{className:"h-3.5 w-3.5"}),"Download"]})]})]}),o?s.jsx(d6e,{preview:o,open:c,onToggle:()=>u(E=>!E)}):null,w&&_?s.jsxs("a",{href:yv(_),target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-between gap-3 border-t border-outline-subtle bg-surface-brandSubtle/40 px-4 py-2.5 text-body-sm text-text-body hover:bg-surface-brandSubtle/70 transition",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary",children:"Next step â upload to Takealot"}),s.jsx("div",{className:"truncate text-body-xs text-text-secondary",children:w.service})]}),s.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-md bg-intent-brand px-3 py-1.5 text-body-sm font-medium text-text-inverse shadow-xs",children:[w.label,s.jsx(Qt,{className:"h-3.5 w-3.5"})]})]}):null]})}function d6e({preview:e,open:t,onToggle:n}){const r=e.rows.length,a=e.row_count??r,i=a>r?`Preview ${r} of ${a} rows`:`Preview ${r} row${r===1?"":"s"}`;return s.jsxs("div",{className:"border-t border-outline-subtle",children:[s.jsxs("button",{type:"button",onClick:n,"aria-expanded":t,className:"flex w-full items-center justify-between gap-2 px-4 py-2 text-left text-body-xs font-medium text-text-secondary hover:bg-surface-subtle",children:[s.jsx("span",{children:i}),s.jsx(Pn,{className:B("h-3.5 w-3.5 transition",t&&"rotate-180")})]}),t?s.jsx(JY,{className:"border-t border-outline-faint",children:s.jsxs("table",{className:"w-full min-w-max text-body-xs",children:[s.jsx("thead",{children:s.jsx("tr",{className:"border-b border-outline-subtle text-text-tertiary",children:e.columns.map(o=>s.jsx("th",{className:"px-3 py-1.5 text-left font-medium whitespace-nowrap",children:o.label},o.key))})}),s.jsx("tbody",{children:e.rows.map((o,l)=>s.jsx("tr",{className:"border-b border-outline-faint last:border-0",children:e.columns.map(c=>s.jsx("td",{className:"px-3 py-1.5 text-text-body whitespace-nowrap tabular-nums",children:o[c.key]==null||o[c.key]===""?"â":String(o[c.key])},c.key))},l))})]})}):null]})}const h6e=["xlsx","csv","pdf"],f6e={xlsx:{label:"Excel (.xlsx)",hint:"Formatted, frozen header, auto-width"},csv:{label:"CSV (.csv)",hint:"Plain rows for scripts / accountants"},pdf:{label:"PDF (.pdf)",hint:"Printable hardcopy, A4 landscape"}},FM=5e3;function Kf({onDownload:e,rowCount:t,formats:n,label:r="Download",compact:a=!1,extraItems:i,onExtraDownload:o}){const[l,c]=p.useState(!1),[u,d]=p.useState(null),f=(n??h6e).map(g=>{const y=g==="pdf"&&typeof t=="number"&&t>FM;return{format:g,...f6e[g],disabled:y,disabledReason:y?`${t==null?void 0:t.toLocaleString()} rows â PDF capped at ${FM.toLocaleString()}. Use XLSX or narrow the window.`:void 0}});async function m(g){if(!(g.disabled||u)){d(g.format),c(!1);try{await e(g.format)}finally{d(null)}}}async function x(g){if(!(u||!o)){d(g.id),c(!1);try{await o(g.id)}finally{d(null)}}}return s.jsxs(Tf,{open:l,onOpenChange:c,children:[s.jsx(Of,{asChild:!0,children:s.jsxs("button",{type:"button",disabled:!!u,className:B("text-xs text-text-body hover:text-text-primary flex items-center gap-1 rounded-md border border-outline-subtle hover:bg-surface-subtle disabled:opacity-50",a?"px-2 py-1":"px-2 py-1.5 md:py-1"),title:"Download as CSV, Excel, or PDF",children:[u?s.jsx(_e,{className:"w-3.5 h-3.5 animate-spin"}):s.jsx(Dr,{className:"w-3.5 h-3.5"}),s.jsx("span",{className:"hidden md:inline",children:u?"Preparingâ¦":r}),s.jsx(Pn,{className:"w-3 h-3 opacity-60"})]})}),s.jsxs($d,{align:"end",className:"w-64",children:[f.map(g=>s.jsxs(Gh,{onClick:()=>m(g),disabled:!!g.disabled||!!u,className:"flex-col items-start gap-0.5",title:g.disabledReason||g.hint,children:[s.jsx("span",{className:"font-medium",children:g.label}),s.jsx("span",{className:"text-body-xs text-text-secondary leading-tight font-normal",children:g.disabledReason||g.hint})]},g.format)),i&&i.length>0?s.jsxs(s.Fragment,{children:[s.jsx(aye,{}),i.map(g=>s.jsxs(Gh,{onClick:()=>x(g),disabled:!!u,className:"flex-col items-start gap-0.5",title:g.hint,children:[s.jsx("span",{className:"font-medium",children:g.label}),s.jsx("span",{className:"text-body-xs text-text-secondary leading-tight font-normal",children:g.hint})]},g.id))]}):null]})]})}function uc(e,t){const n=URL.createObjectURL(e),r=document.createElement("a");r.href=n,r.download=t,document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),1500)}function m6e(e){return(e.split("/").pop()||e).replace(/\.md$/i,"").replace(/[-_]+/g," ")}function p6e(e,t){return`/sellers/${e}/reports/${t}`}function x6e(e){const t=hV.safeParse(e),[n,r]=p.useState(!1),[a,i]=p.useState(null);if(!t.success)return s.jsx(ni,{type:"report-card"});const{slug:o,path:l,title:c}=t.data,u=c||m6e(l),d=p6e(o,l);async function h(){if(!n){r(!0),i(null);try{const{blob:f,filename:m}=await K.downloadReportPdf(o,l,{title:u});uc(f,m)}catch(f){i(f instanceof Error?f.message:String(f))}finally{r(!1)}}}return s.jsxs("div",{className:"not-prose my-3 rounded-lg border border-outline-subtle bg-surface shadow-xs overflow-hidden",children:[s.jsxs("div",{className:"flex items-start gap-3 px-4 py-3",children:[s.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-surface-sunken text-text-secondary",children:s.jsx(il,{className:"h-5 w-5"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"truncate text-body-md font-medium text-text-primary",children:u}),e.children?s.jsx("div",{className:"mt-0.5 text-body-sm leading-snug text-text-body",children:e.children}):null,a?s.jsx("div",{className:"mt-1 text-body-xs text-text-error",children:a}):null]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 border-t border-outline-subtle bg-surface-subtle/50 px-4 py-2.5",children:[s.jsx(st,{to:d,className:"inline-flex items-center rounded-md bg-intent-brand px-3 py-1.5 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover focus-visible:outline-none focus-visible:shadow-focus",children:"Open report"}),s.jsxs("button",{type:"button",onClick:h,disabled:n,"aria-busy":n||void 0,className:"inline-flex items-center gap-1.5 rounded-md border border-outline-subtle bg-surface px-3 py-1.5 text-body-sm font-medium text-text-primary shadow-xs transition hover:bg-surface-subtle focus-visible:outline-none focus-visible:shadow-focus disabled:opacity-60",children:[n?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):null,"Download PDF"]})]})]})}function g6e(e){const t=fV.safeParse(e);if(!t.success)return s.jsx(ni,{type:"upload-prompt"});const{url:n,label:r,service:a}=t.data;return s.jsx("div",{className:"not-prose my-3 rounded-lg border border-outline-subtle bg-surface-brandSubtle/40 px-4 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-surface text-text-brand",children:s.jsx(ti,{className:"h-5 w-5"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-body-md font-medium text-text-primary",children:"Next step"}),e.children?s.jsx("div",{className:"mt-0.5 text-body-sm leading-snug text-text-body",children:e.children}):null,a?s.jsx("div",{className:"mt-1 text-body-xs text-text-secondary",children:a}):null]}),s.jsxs("a",{href:yv(n),target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 rounded-md bg-intent-brand px-3 py-1.5 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover focus-visible:outline-none focus-visible:shadow-focus",children:[r,s.jsx(Qt,{className:"h-3.5 w-3.5"})]})]})})}const y6e={general:"General",listing_upgrade:"Listing upgrade",customer_communication:"Customer comms",stockout_followup:"Stockout follow-up",returns_followup:"Returns follow-up",billing:"Billing",other:"Other"},b6e={general:6,listing_upgrade:3,customer_communication:5,stockout_followup:2,returns_followup:4,billing:5,other:6};function v6e(e){const t=mV.safeParse(e);if(!t.success)return s.jsx(ni,{type:"task-card"});const{title:n,type:r,assignee:a,due:i}=t.data,o=y6e[r]??r;return s.jsx("div",{className:"not-prose my-3 rounded-lg border border-outline-warning bg-surface-warningSubtle px-4 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-surface-warningSubtle text-text-warning",children:s.jsx(Uh,{className:"h-5 w-5"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-body-md font-medium text-text-primary",children:n}),e.children?s.jsx("div",{className:"mt-0.5 text-body-sm leading-snug text-text-body",children:e.children}
888):null,s.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:[s.jsx(_n,{category:b6e[r]??6,dot:!0,children:o}),a?s.jsx(_n,{variant:"outline",children:a}):null,i?s.jsxs(_n,{variant:"outline",children:["Due ",i]}):null]})]})]})})}function w6e(e){const t=pV.safeParse(e);if(!t.success)return s.jsx(ni,{type:"skill-suggest",inline:!0});const{name:n,label:r,seller:a}=t.data,i=r??`/${n}`;return s.jsxs("button",{type:"button",className:"not-prose my-1.5 inline-flex items-center gap-1.5 rounded-md border border-outline-subtle bg-surface px-2.5 py-1 text-body-xs font-medium text-text-body shadow-xs transition hover:border-outline hover:bg-surface-subtle focus-visible:outline-none focus-visible:shadow-focus",onClick:()=>{const o=new CustomEvent("gadjet:skill-suggest",{detail:{name:n,seller:a}});window.dispatchEvent(o)},children:[s.jsx(Ht,{className:"h-3 w-3 text-text-warning"}),i,s.jsx(lte,{className:"h-3 w-3 text-text-tertiary"})]})}const _6e={up:Xi,down:ax,flat:Hv},k6e={up:"text-text-success",down:"text-text-error",flat:"text-text-secondary"};function j6e(e){const t=xV.safeParse(e);if(!t.success)return s.jsx(ni,{type:"stat-card"});const{label:n,value:r,delta:a,trend:i,subtitle:o}=t.data,l=i?_6e[i]:null,c=i?k6e[i]:"";return s.jsxs("div",{className:"not-prose my-3 inline-flex min-w-[160px] flex-col rounded-lg border border-outline-subtle bg-surface px-3.5 py-2.5 shadow-xs",children:[s.jsx("div",{className:"text-body-xs font-medium uppercase tracking-wide text-text-secondary",children:n}),s.jsx("div",{className:"mt-0.5 text-xl font-semibold tabular-nums text-text-primary",children:r}),s.jsxs("div",{className:"mt-0.5 flex items-center gap-1 text-body-xs",children:[l&&a?s.jsxs("span",{className:`inline-flex items-center gap-0.5 font-medium ${c}`,children:[s.jsx(l,{className:"h-3 w-3"}),a]}):a?s.jsx("span",{className:"font-medium text-text-body",children:a}):null,o?s.jsx("span",{className:"text-text-secondary",children:o}):null]})]})}function N6e(e){const t=gV.safeParse(e);if(!t.success)return s.jsx(ni,{type:"sparkline",inline:!0});const{data:n,label:r,height:a=24,width:i=100}=t.data,o=n.split(/[,\s]+/).map(g=>Number(g)).filter(g=>Number.isFinite(g));if(o.length<2)return s.jsx(ni,{type:"sparkline",inline:!0});const l=Math.min(...o),u=Math.max(...o)-l||1,d=i/(o.length-1),h=o.map((g,y)=>{const b=y*d,v=a-(g-l)/u*a;return`${y===0?"M":"L"}${b.toFixed(2)},${v.toFixed(2)}`}).join(" "),f=o[o.length-1],m=o[0],x=f>m?"text-text-success":f<m?"text-text-error":"text-text-secondary";return s.jsxs("span",{className:`not-prose inline-flex items-center gap-1.5 align-middle ${x}`,children:[s.jsx("svg",{width:i,height:a,viewBox:`0 0 ${i} ${a}`,className:"overflow-visible",children:s.jsx("path",{d:h,fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round"})}),r?s.jsx("span",{className:"text-body-xs text-text-secondary",children:r}):null]})}const S6e={pending:{Icon:pu,color:"text-text-secondary",spin:!1},running:{Icon:_e,color:"text-text-info",spin:!0},ok:{Icon:Xt,color:"text-text-success",spin:!1},error:{Icon:yt,color:"text-text-error",spin:!1}};function C6e(e){const t=yV.safeParse(e);if(!t.success)return s.jsx(ni,{type:"sync-status"});const{state:n,message:r,progress:a}=t.data,{Icon:i,color:o,spin:l}=S6e[n];return s.jsxs("div",{className:"not-prose my-2 flex items-center gap-2.5 rounded-md border border-outline-subtle bg-surface-subtle px-3 py-2 text-body-md",children:[s.jsx(i,{className:`h-4 w-4 shrink-0 ${o} ${l?"animate-spin":""}`}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"truncate text-text-body",children:r??n}),typeof a=="number"?s.jsx(Nf,{className:"mt-1",value:a,valueLabel:`${Math.max(0,Math.min(100,Math.round(a)))}%`,intent:"info"}):null]})]})}function E6e(e){const t=bV.safeParse(e),{url:n,failed:r}=A6e(t.success?t.data.url:void 0,t.success?t.data.path:void 0);if(!t.success)return s.jsx(ni,{type:"image-thumb"});const{label:a,mode:i,bypass:o}=t.data;if(r)return s.jsxs("span",{title:`Couldn't load "${a}" â the image link could not be signed for your account.`,className:"not-prose inline-flex w-32 items-center gap-1 rounded-md border border-outline-subtle bg-surface-sunken px-1.5 py-1 align-top text-body-xs text-text-secondary",children:[s.jsx(Qy,{className:"h-3 w-3 shrink-0"}),s.jsx("span",{className:"truncate",children:"Image unavailable"})]});if(!n)return s.jsx(ni,{type:"image-thumb"});const l=yv(n);if(l==="#")return s.jsx(ni,{type:"image-thumb"});const c=i==="lifestyle";return s.jsxs("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"not-prose group block w-32 overflow-hidden rounded-md border border-outline-subtle bg-surface align-top shadow-xs transition hover:shadow-sm focus-visible:outline-none focus-visible:shadow-focus",children:[s.jsxs("div",{className:"relative aspect-square w-full overflow-hidden bg-surface-sunken",children:[s.jsx("img",{src:l,alt:a,loading:"lazy",className:"h-full w-full object-contain transition group-hover:scale-[1.02]"}),o==="true"?s.jsx("span",{title:"Source was already white-BG â cutout step bypassed",className:"absolute right-1 top-1 inline-flex items-center rounded-full bg-surface px-1 py-0.5 text-body-xs font-medium text-text-secondary ring-1 ring-outline-subtle",children:s.jsx(Ht,{className:"h-2.5 w-2.5"})}):null,c?s.jsx("span",{className:"absolute left-1 top-1 inline-flex items-center rounded bg-intent-brand px-1 py-0.5 text-body-xs font-medium text-text-inverse",children:"scene"}):null]}),s.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-1",children:[s.jsx(Qy,{className:"h-3 w-3 shrink-0 text-text-secondary"}),s.jsx("span",{className:"truncate text-body-xs font-medium text-text-primary",children:a})]})]})}function A6e(e,t){const[n,r]=p.useState(null),[a,i]=p.useState(!1);return p.useEffect(()=>{if(i(!1),e){r(e);return}if(!t){r(null);return}let o=!0;return r(null),oe("/api/image-jobs/sign",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({path:t})}).then(async l=>{if(!l.ok)return console.error(`[image-thumb] sign failed (HTTP ${l.status}) for path ${t}`),null;const c=await l.json();return(c==null?void 0:c.durable_url)??(c==null?void 0:c.signed_url)??null}).then(l=>{o&&(r(l),l||i(!0))}).catch(l=>{o&&(console.error(`[image-thumb] sign threw for path ${t}:`,l),r(null),i(!0))}),()=>{o=!1}},[e,t]),{url:n,failed:a}}function T6e(e){const t=vV.safeParse(e),n=t.success?t.data.sku:void 0;return s.jsxs("div",{className:"not-prose my-3 rounded-lg border border-outline-subtle bg-surface p-3",children:[s.jsxs("div",{className:"mb-2 flex items-center gap-1.5 px-1 text-body-sm font-medium text-text-secondary",children:[s.jsx(Fne,{className:"h-3.5 w-3.5"}),s.jsx("span",{children:"Studio"}),n?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:n})]}):null]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:e.children})]})}function O6e(e){return e.plid?`https://www.takealot.com/${e.slug||"x"}/PLID${e.plid}`:null}function I6e(e){const t=e.filter_spec||{};return t.keyword?`â${t.keyword}â`:t.category_slug?t.category_slug:t.preset_key?t.preset_key.replace(/_/g," "):e.marketplace}const P6e=[{key:"position",label:"#",className:"w-8",getValue:e=>e.position,render:e=>s.jsx("span",{className:"text-text-tertiary tabular-nums",children:e.position+1})},{key:"image",label:"",className:"w-10",header:s.jsx("span",{className:"sr-only",children:"Image"}),render:e=>e.image_url?s.jsx("img",{src:e.image_url,alt:"",loading:"lazy",className:"h-8 w-8 rounded object-contain bg-surface-subtle"}):s.jsx("div",{className:"grid h-8 w-8 place-items-center rounded bg-surface-subtle text-text-tertiary",children:s.jsx(nx,{className:"h-3 w-3"})})},{key:"title",label:"Title",className:"max-w-xs",getValue:e=>e.title,render:e=>s.jsx("div",{className:"truncate text-text-primary",title:e.title||"",children:e.title||"â"})},{key:"opportunity_score",label:"Opp",align:"right",title:"Opportunity = demand à beatability à margin headroom (after Takealot's standard fees). 0â100.",getValue:e=>e.opportunity_score,render:e=>e.opportunity_score!=null?s.jsx("span",{className:B("inline-block rounded px-1 text-xs font-semibold",e.opportunity_score>=67?"bg-intent-success/10 text-intent-success":e.opportunity_score>=34?"bg-surface-brandSubtle text-text-brand":"bg-surface-subtle text-text-tertiary"),children:e.opportunity_score}):s.jsx("span",{className:"text-text-tertiary",children:"â"})},{key:"brand",label:"Brand",getValue:e=>e.brand,render:e=>s.jsx("span",{className:"text-text-secondary",children:e.brand||"â"})},{key:"selling_price",label:"Price",align:"right",getValue:e=>e.selling_price,render:e=>s.jsx("span",{className:"tabular-nums text-text-primary",children:e.selling_price!=null?ge(e.selling_price):"â"})},{key:"star_rating",label:"â
",align:"right",getValue:e=>e.star_rating,render:e=>s.jsx("span",{className:"tabular-nums text-text-secondary",children:e.star_rating!=null?e.star_rating.toFixed(1):"â"})},{key:"est_revenue_rand_30d",label:"Est Rev",align:"right",getValue:e=>e.est_revenue_rand_30d,render:e=>s.jsx("span",{className:"tabular-nums text-text-secondary",children:e.est_revenue_rand_30d!=null?ge(e.est_revenue_rand_30d,{compact:!0}):"â"})},{key:"pdp",label:"",className:"w-7",align:"right",header:s.jsx("span",{className:"sr-only",children:"PDP"}),render:e=>{const t=O6e(e);return t?s.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",title:"View on Takealot",className:"inline-flex text-text-tertiary hover:text-intent-brand",children:s.jsx(Qt,{className:"h-3.5 w-3.5"})}):null}}];function R6e(e){const t=wV.safeParse(e),n=t.success?t.data.search_id:"",r=t.success?t.data.limit:10,a=t.success?t.data.title:void 0,[i,o]=p.useState(null),[l,c]=p.useState(null),[u,d]=p.useState(null);if(p.useEffect(()=>{if(!n)return;let g=!1;return o(null),c(null),d(null),$t.getSearch(n).then(y=>
888{g||(o(y.search),c(y.rows))}).catch(y=>{g||d(y!=null&&y.message?String(y.message):"Could not load this search.")}),()=>{g=!0}},[n]),!t.success)return s.jsx(ni,{type:"market-explorer-table"});if(u)return s.jsxs("div",{className:"not-prose my-2 flex items-center gap-2.5 rounded-md border border-outline-subtle bg-surface-subtle px-3 py-2 text-body-md",children:[s.jsx(yt,{className:"h-4 w-4 shrink-0 text-text-error"}),s.jsxs("span",{className:"text-text-secondary",children:["Market Explorer results unavailable: ",u]})]});if(!i||!l)return s.jsx(ni,{type:"market-explorer-table"});const h=l.slice(0,r),{price:f,total_listings:m,total_est_revenue_rand_30d:x}=i.rollup;return s.jsxs("div",{className:"not-prose my-2 overflow-hidden rounded-lg border border-outline-subtle bg-surface",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b border-outline-subtle bg-surface-subtle px-3 py-2",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium text-text-secondary",children:[s.jsx(y2,{className:"h-3.5 w-3.5 text-intent-brand"}),s.jsx("span",{className:"text-text-primary",children:a||I6e(i)}),s.jsxs("span",{className:"text-text-tertiary",children:["· ",m.toLocaleString()," listings"]})]}),s.jsxs("div",{className:"flex items-center gap-3 text-xs text-text-tertiary tabular-nums",children:[(f==null?void 0:f.min)!=null&&(f==null?void 0:f.max)!=null&&s.jsxs("span",{children:[ge(f.min),"â",ge(f.max)]}),x!=null&&s.jsxs("span",{title:"Estimated revenue across shown listings, last 30 days",children:["~",ge(x,{compact:!0}),"/mo"]})]})]}),s.jsx(dt,{rows:h,columns:P6e,getRowKey:g=>`${g.plid??g.position}-${g.position}`,paginate:!1,persist:!1,tableClassName:"w-full text-sm",empty:{title:"No listings."}}),s.jsxs("div",{className:"flex items-center justify-between border-t border-outline-subtle px-3 py-1.5 text-xs text-text-tertiary",children:[s.jsx("span",{children:l.length>h.length?`Showing top ${h.length} of ${l.length}`:`${l.length} listing${l.length===1?"":"s"}`}),s.jsxs("a",{href:"/market-explorer",className:B("inline-flex items-center gap-1 font-medium text-intent-brand hover:text-intent-brandHover"),children:["Open in Market Explorer",s.jsx(Qt,{className:"h-3 w-3"})]})]})]})}const GV={"gadjet-download-card":u6e,"gadjet-report-card":x6e,"gadjet-upload-prompt":g6e,"gadjet-task-card":v6e,"gadjet-skill-suggest":w6e,"gadjet-stat-card":j6e,"gadjet-sparkline":N6e,"gadjet-sync-status":C6e,"gadjet-image-thumb":E6e,"gadjet-image-gallery":T6e,"gadjet-market-explorer-table":R6e},YV={a:({node:e,...t})=>s.jsx("a",{...t,target:"_blank",rel:"noopener noreferrer"}),img:({src:e,alt:t,...n})=>typeof e=="string"&&(e.startsWith("/")||e.startsWith("https://app.gadjet.ai/")||e.startsWith("https://opmvesjizkkbrvkxfgtl.supabase.co/"))?s.jsx("img",{src:e,alt:t??"",...n}):null,table:({node:e,...t})=>s.jsx("div",{className:"overflow-x-auto",children:s.jsx("table",{...t})}),...GV};function D6e(){const e=jn(),t=e.slug??"",n=e["*"]??"",[r,a]=p.useState(null),[i,o]=p.useState(null),[l,c]=p.useState(null);p.useEffect(()=>{a(null),c(null),K.seller(t).then(o).catch(()=>{}),K.report(t,n).then(a).catch(d=>c(String(d)))},[t,n]);async function u(){if(r)try{const{blob:d,filename:h}=await K.downloadReportPdf(t,n,{title:r.name,subtitle:i==null?void 0:i.display_name});uc(d,h)}catch(d){c(String((d==null?void 0:d.message)||d))}}return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Sellers",to:"/"},{label:(i==null?void 0:i.display_name)??t,to:`/sellers/${t}`},{label:"Documents"},{label:(r==null?void 0:r.name)??"â¦"}],actions:r?s.jsx(Kf,{onDownload:u,formats:["pdf"],label:"Download PDF"}):null}),s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"max-w-4xl mx-auto p-4 md:p-8",children:[l&&s.jsx("div",{className:"text-sm text-text-error bg-surface-errorSubtle border border-outline-error rounded-lg p-4",children:l}),!l&&!r&&s.jsx("div",{className:"text-sm text-text-tertiary",children:"Loadingâ¦"}),r&&s.jsxs("article",{className:"bg-surface border border-outline-subtle rounded-xl p-5 md:p-10 shadow-sm",children:[s.jsxs("header",{className:"mb-6 pb-6 border-b border-outline-faint",children:[s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-brand mb-2",children:r.kind.replace(/-/g," ")}),s.jsx("h1",{className:"text-2xl font-semibold text-text-primary tracking-tight",children:r.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:["Updated ",cn(r.updated_at)]})]}),s.jsx("div",{className:"prose",children:s.jsx(mx,{remarkPlugins:[px,d3,p3],rehypePlugins:[m3],components:YV,children:r.body})})]})]})})]})}function M6e(){const{id:e}=jn(),[t]=ki(),n=t.get("view")==="1",[r,a]=p.useState(null),[i,o]=p.useState(!1);return p.useEffect(()=>{if(!e){a("Missing export id.");return}let l=!1;return(async()=>{try{const c=n?"?download=0":"",u=await oe(`/api/exports/${encodeURIComponent(e)}${c}`);if(l)return;if(u.status===404){o(!0);return}if(!u.ok){a(`${u.status} â could not fetch ${n?"view":"download"} link`);return}const d=await u.json();if(!(d!=null&&d.signed_url)){a(`Server did not return a ${n?"view":"download"} link.`);return}window.location.replace(d.signed_url)}catch(c){if(l)return;const u=c instanceof Error?c.message:String(c);a(u)}})(),()=>{l=!0}},[e,n]),i?s.jsx(Yt,{to:"/",replace:!0}):s.jsx("div",{className:"min-h-[40vh] flex items-center justify-center",children:s.jsx("div",{className:"text-sm text-text-secondary flex items-center gap-2",children:r?s.jsx("span",{className:"text-text-error",children:r}):s.jsxs(s.Fragment,{children:[s.jsx(_e,{className:"w-4 h-4 animate-spin"}),s.jsx("span",{children:n?"Openingâ¦":"Preparing your downloadâ¦"})]})})})}const $6e={"4xl":"max-w-4xl","5xl":"max-w-5xl","6xl":"max-w-6xl",full:"max-w-none"};function BM(e){return B("flex items-center gap-1.5 px-3 py-2 text-sm border-b-2 -mb-px transition-colors whitespace-nowrap shrink-0",e?"border-outline-brand text-text-primary font-medium":"border-transparent text-text-secondary hover:text-text-primary")}function As({items:e,maxWidth:t="full",tone:n="surface",actions:r,className:a}){return s.jsx("div",{className:B("border-b border-outline-subtle px-4 md:px-6",n==="subtle"?"bg-surface-subtle/50":"bg-surface",a),children:s.jsxs("div",{className:B("mx-auto flex items-center",$6e[t]),children:[s.jsx("nav",{className:"flex items-center gap-1 overflow-x-auto scrollbar-on-hover min-w-0",children:e.map(i=>"to"in i?s.jsxs(si,{to:i.to,end:i.end,className:({isActive:o})=>BM(o),children:[i.icon,s.jsx("span",{children:i.label}),i.trailing]},i.key):s.jsxs("button",{type:"button",onClick:i.onClick,className:BM(i.active),children:[i.icon,s.jsx("span",{children:i.label}),i.trailing]},i.key))}),r!=null&&s.jsx("div",{className:"ml-auto pl-3 shrink-0",children:r})]})})}
888const L6e={id:"amazon-gtin-exemption",label:"Amazon GTIN exemption pack",hint:"Excel for Amazon barcode exemption â products, brands, notes"};function F6e({slug:e,search:t,status:n,rowCount:r,onFreshness:a,onError:i}){const o=Lt(),l=o.kind==="ready"&&o.me.role==="super_admin";async function c(d){try{const f=!!(t||n)?"listings":"inventory",{blob:m,filename:x,dataAsOf:g,dataLagHours:y}=await K.downloadExport(e,f,{format:d,search:t,status:n});uc(m,x),g&&y!=null&&y>24?a({asOf:g,lagHours:y}):a(null)}catch(h){const f=h;i(String((f==null?void 0:f.message)||h))}}async function u(d){if(d==="amazon-gtin-exemption")try{const{blob:h,filename:f}=await K.downloadAmazonGtinExemption(e);uc(h,f)}catch(h){const f=h instanceof Error?h.message:String(h);Ae.error("Couldn't build the Amazon GTIN exemption pack.",{description:f}),i(f)}}return s.jsx(Kf,{onDownload:c,rowCount:r,extraItems:l?[L6e]:void 0,onExtraDownload:l?u:void 0})}function Ws({data:e,width:t=60,height:n=16,className:r}){if(!e||e.length<2)return s.jsx("span",{className:B("inline-block text-text-tertiary text-xs",r),style:{width:t,height:n,lineHeight:`${n}px`},"aria-hidden":!0,children:"â"});const a=Math.max(...e,1),i=1,o=n-i*2,l=t-i*2,c=e.map((h,f)=>{const m=i+f/(e.length-1)*l,x=i+o-h/a*o;return`${m.toFixed(2)},${x.toFixed(2)}`}).join(" "),d=[...e].reverse().findIndex(h=>h>0)===-1;return s.jsx("svg",{width:t,height:n,viewBox:`0 0 ${t} ${n}`,className:B("inline-block",r),"aria-hidden":!0,children:s.jsx("polyline",{fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinejoin:"round",strokeLinecap:"round",points:c,opacity:d?.3:1})})}var B6e=Object.defineProperty,dc=(e,t)=>B6e(e,"name",{value:t,configurable:!0}),x3="Checkbox",[U6e,grt]=du(x3),[z6e,g3]=U6e(x3);function ZV(e){const{__scopeCheckbox:t,checked:n,children:r,defaultChecked:a,disabled:i,form:o,name:l,onCheckedChange:c,required:u,value:d="on",internal_do_not_use_render:h}=e,[f,m]=Jp({prop:n,defaultProp:a??!1,onChange:c,caller:x3}),[x,g]=p.useState(null),[y,b]=p.useState(null),v=p.useRef(!1),[w,_]=p.useReducer(N=>N+1,0),k=x?!!o||!!x.closest("form"):!0,j={checked:f,disabled:i,setChecked:m,control:x,setControl:g,name:l,form:o,value:d,hasConsumerStoppedPropagationRef:v,userInteractionCount:w,onUserInteraction:_,required:u,defaultChecked:ec(a)?!1:a,isFormControl:k,bubbleInput:y,setBubbleInput:b};return s.jsx(z6e,{scope:t,...j,children:XV(h)?h(j):r})}dc(ZV,"CheckboxProvider");var W6e="CheckboxTrigger",K6e=p.forwardRef(dc(function({__scopeCheckbox:t,onKeyDown:n,onClick:r,...a},i){const{control:o,value:l,disabled:c,checked:u,required:d,setControl:h,setChecked:f,hasConsumerStoppedPropagationRef:m,onUserInteraction:x,isFormControl:g,bubbleInput:y}=g3(W6e,t),b=oa(i,h),v=p.useRef(u);return p.useEffect(()=>{const w=o==null?void 0:o.form;if(w){const _=dc(()=>f(v.current),"reset");return w.addEventListener("reset",_),()=>w.removeEventListener("reset",_)}},[o,f]),s.jsx(ji.button,{type:"button",role:"checkbox","aria-checked":ec(u)?"mixed":u,"aria-required":d,"data-state":y3(u),"data-disabled":c?"":void 0,disabled:c,value:l,...a,ref:b,onKeyDown:cs(n,w=>{w.key==="Enter"&&w.preventDefault()}),onClick:cs(r,w=>{x(),f(_=>ec(_)?!0:!_),y&&g&&(m.current=w.isPropagationStopped(),m.current||w.stopPropagation())})})},"CheckboxTrigger")),H6e=p.forwardRef(dc(function(t,n){const{__scopeCheckbox:r,name:a,checked:i,defaultChecked:o,required:l,disabled:c,value:u,onCheckedChange:d,form:h,...f}=t;return s.jsx(ZV,{__scopeCheckbox:r,checked:i,defaultChecked:o,disabled:c,required:l,onCheckedChange:d,name:a,form:h,value:u,internal_do_not_use_render:({isFormControl:m})=>s.jsxs(s.Fragment,{children:[s.jsx(K6e,{...f,ref:n,__scopeCheckbox:r}),m&&s.jsx(Y6e,{__scopeCheckbox:r})]})})},"Checkbox")),V6e="CheckboxIndicator",q6e=p.forwardRef(dc(function(t,n){const{__scopeCheckbox:r,forceMount:a,...i}=t,o=g3(V6e,r);return s.jsx(Wv,{present:a||ec(o.checked)||o.checked===!0,children:s.jsx(ji.span,{"data-state":y3(o.checked),"data-disabled":o.disabled?"":void 0,...i,ref:n,style:{pointerEvents:"none",...t.style}})})},"CheckboxIndicator")),G6e="CheckboxBubbleInput",Y6e=p.forwardRef(dc(function({__scopeCheckbox:t,onClick:n,...r},a){const{control:i,hasConsumerStoppedPropagationRef:o,userInteractionCount:l,checked:c,defaultChecked:u,required:d,disabled:h,name:f,value:m,form:x,bubbleInput:g,setBubbleInput:y}=g3(G6e,t),b=oa(a,y),v=_2(i),w=p.useRef(!1),_=p.useRef(c),k=p.useRef(l);p.useEffect(()=>{const N=g;if(!N)return;const E=window.HTMLInputElement.prototype,C=Object.getOwnPropertyDescriptor(E,"checked").set,T=l!==k.current;k.current=l;const S=_.current!==c;_.current=c;const O=!(T&&o.current);if(S&&C){w.current=!T;const R=new Event("click",{bubbles:O});N.indeterminate=ec(c),C.call(N,ec(c)?!1:c),N.dispatchEvent(R),w.current=!1}},[g,c,o,l]);const j=p.useRef(ec(c)?!1:c);return s.jsx(ji.input,{type:"checkbox","aria-hidden":!0,defaultChecked:u??j.current,required:d,disabled:h,name:f,value:m,form:x,...r,tabIndex:-1,ref:b,onClick:cs(n,N=>{w.current&&N.stopPropagation()}),style:{...r.style,...v,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"CheckboxBubbleInput"));function XV(e){return typeof e=="function"}dc(XV,"isFunction");function ec(e){return e==="indeterminate"}dc(ec,"isIndeterminate");function y3(e){return ec(e)?"indeterminate":e?"checked":"unchecked"}dc(y3,"getState");const ei=p.forwardRef(({className:e,...t},n)=>
888s.jsx(H6e,{ref:n,className:B("shrink-0 h-4 w-4 rounded border border-outline bg-surface focus:outline-none focus-visible:shadow-focus data-[state=checked]:bg-intent-brand data-[state=checked]:border-intent-brand data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 transition",e),...t,children:s.jsx(q6e,{className:"flex items-center justify-center text-text-inverse",children:s.jsx(fn,{className:"w-3 h-3",strokeWidth:3})})}));ei.displayName="Checkbox";function Kd({variant:e="icon",...t}){const[n,r]=p.useState(!1),a=i=>{i.stopPropagation(),r(!0)};return s.jsxs(s.Fragment,{children:[e==="link"?s.jsxs("button",{type:"button",onClick:a,className:"flex items-center gap-2 text-text-brand hover:underline",children:[s.jsx(KT,{className:"w-3.5 h-3.5"}),"Profit calculator"]}):s.jsx("button",{type:"button",onClick:a,title:"Profit calculator",className:"inline-flex items-center justify-center rounded p-1 text-text-tertiary hover:text-text-brand hover:bg-surface-brandSubtle transition-colors",children:s.jsx(KT,{className:"w-4 h-4"})}),s.jsx("span",{style:{display:"contents"},onClick:i=>i.stopPropagation(),children:s.jsx(Z6e,{...t,open:n,onClose:()=>r(!1)})})]})}function Z6e({plid:e,sellPrice:t,slug:n,sku:r,title:a,open:i,onClose:o}){const[l,c]=p.useState(""),[u,d]=p.useState(""),[h,f]=p.useState(null),[m,x]=p.useState(null),[g,y]=p.useState(!1),[b,v]=p.useState(!1),[w,_]=p.useState(!1),[k,j]=p.useState(null),[N,E]=p.useState(!0),A=p.useRef(!0);p.useEffect(()=>{i&&(A.current=!0,c(t!=null?String(t):""),d(""),f(null),x(null),j(null))},[i,t]);const C=p.useCallback(async(P,F)=>{const Z=Number(P);if(!Number.isFinite(Z)||Z<=0){f(null);return}y(!0),x(null);try{const D=F.trim()===""?null:Number(F),H=await K.profitCalc({sell_price:Z,cost_price:D,plid:e??null,slug:n??null,sku:r??null});f(H),A.current&&H.cost_source==="stored"&&H.has_cost&&d(H.cost_incl_vat.toFixed(2))}catch(D){x(D instanceof Error?D.message:"Calculation failed"),f(null)}finally{y(!1)}},[e,n,r]);p.useEffect(()=>{if(!i)return;const P=setTimeout(()=>C(l,u),350);return()=>clearTimeout(P)},[i,l,u,C]);const T=h!=null&&(N?h.profit_incl_vat:h.profit)>=0,S=Number(u),O=!!n&&!!r&&u.trim()!==""&&Number.isFinite(S)&&S>=0,R=!!n&&!!(h!=null&&h.offer_id)&&!w&&!g;async function I(){if(R){_(!0),j(null),x(null);try{const P=await K.refreshOffer(n,h.offer_id);await C(l,u);const F=new Date(P.checked_at).toLocaleTimeString("en-ZA",{hour:"2-digit",minute:"2-digit"});j(P.changed?`Updated from Takealot · ${F}`:`Already up to date · checked ${F}`)}catch(P){x(P instanceof Error?P.message:"Couldn't refresh from Takealot")}finally{_(!1)}}}async function $(){if(!(!O||b)){v(!0),j(null),x(null);try{const P=Number((S/1.15).toFixed(2)),F=await K.setSkuCost(n,r,P);j(F.repriced_subscriptions>0?`Saved to catalogue · repricer re-queued (${F.repriced_subscriptions})`:"Saved to catalogue"),A.current=!0}catch(P){x(P instanceof Error?P.message:"Couldn't save cost")}finally{v(!1)}}}return s.jsx(Cr,{open:i,onOpenChange:P=>!P&&o(),children:s.jsxs(mr,{side:"right",size:"md",children:[s.jsxs(Er,{children:[s.jsx(xr,{children:"Profit calculator"}),a&&s.jsx(Mr,{className:"truncate",title:a,children:a})]}),s.jsxs(pr,{className:"p-4 space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Sell price (incl. VAT)"}),s.jsx(Re,{type:"number",inputMode:"decimal",min:"0",step:"0.01",value:l,onChange:P=>c(P.target.value),placeholder:"0.00"})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Cost (incl. VAT)"}),s.jsx(Re,{type:"number",inputMode:"decimal",min:"0",step:"0.01",value:u,onChange:P=>{A.current=!1,d(P.target.value)},placeholder:n?"auto / enter":"enter"})]})]}),(h==null?void 0:h.cost_source)==="stored"&&s.jsx("p",{className:"text-xs text-text-tertiary",children:"Cost prefilled from your stored COGS â edit to override."}),k&&s.jsx("p",{className:"text-xs text-success-text",children:k}),m&&s.jsx("div",{className:"text-sm text-error-text bg-error-bg border border-error-border rounded p-2",children:m}),h&&s.jsxs("div",{children:[h.category_lineage&&s.jsxs("p",{className:"text-xs text-text-secondary mb-2",children:[s.jsx("span",{className:"text-text-tertiary",children:"Category: "}),h.category_lineage]}),s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer w-fit",children:[s.jsx(ei,{checked:N,onCheckedChange:P=>E(P===!0)}),s.jsx("span",{className:"text-xs font-medium text-text-secondary",children:"Include VAT"})]}),h.offer_id&&n&&s.jsxs("button",{type:"button",onClick:I,disabled:!R,title:"Pull the latest price and fees from Takealot",className:"inline-flex items-center gap-1.5 text-xs text-text-brand hover:underline disabled:opacity-50 disabled:cursor-not-allowed disabled:no-underline",children:[s.jsx(vi,{className:B("w-3.5 h-3.5",w&&"animate-spin")}),w?"Refreshingâ¦":"Refresh"]})]}),s.jsxs("div",{className:"rounded-lg border border-outline-subtle divide-y divide-outline-subtle text-sm",children:[s.jsx(ym,{label:`Selling price (${N?"incl":"excl"}. VAT)`,value:oh(N?h.sell_incl_vat:h.sell_excl_vat)}),s.jsx(ym,{label:`Success fee (${X6e(h.success_fee_pct)})`,value:`â ${oh(N?h.success_fee_incl_vat:h.success_fee)}`,muted:!0}
888),s.jsx(ym,{label:"Fulfilment fee",value:`â ${oh(N?h.fulfilment_fee_incl_vat:h.fulfilment_fee)}`,muted:!0}),s.jsx(ym,{label:"Net sales",value:oh(N?h.net_payout:h.net_sales_excl_vat)}),h.has_cost&&s.jsx(ym,{label:`Cost of product (${N?"incl":"excl"}. VAT)`,value:`â ${oh(N?h.cost_incl_vat:h.cost_excl_vat)}`,muted:!0}),s.jsxs("div",{className:"flex items-center justify-between px-3 py-2",children:[s.jsx("span",{className:"font-medium text-text-primary",children:h.has_cost?"Net profit":"Net sales before cost"}),s.jsx("span",{className:B("font-semibold tabular-nums",T?"text-success-text":"text-error-text"),children:oh(N?h.profit_incl_vat:h.profit)})]}),h.has_cost&&s.jsxs("div",{className:"flex items-center justify-between px-3 py-2 text-text-secondary",children:[s.jsx("span",{children:"ROI / Net margin"}),s.jsxs("span",{className:"tabular-nums",children:[UM(N?h.roi_incl_vat:h.roi)," /"," ",UM(N?h.margin_incl_vat:h.margin)]})]})]})]}),s.jsxs("p",{className:"text-[11px] leading-snug text-text-tertiary",children:[(h==null?void 0:h.fee_basis)==="offer_charges"?"Fees use Takealot's own per-offer estimate for this item. ":(h==null?void 0:h.fee_basis)==="category"&&h.category_name?`Fees use the ${h.category_name} department rate. `:"Fees use Takealot's default rate (category not resolved for this PLID). ",(h==null?void 0:h.fee_basis)!=="offer_charges"&&s.jsxs(s.Fragment,{children:["Fulfilment fee is a Standard-size, light-weight estimate â heavy or oversized items pay more."," "]}),N?s.jsx(s.Fragment,{children:"With VAT included these match your Takealot statement line for line. If you're VAT-registered, untick to see what you actually keep â you owe the VAT on the sale and reclaim the VAT on Takealot's fees."}):s.jsx(s.Fragment,{children:"Net of VAT: the real cost to a VAT-registered seller, who reclaims the VAT Takealot charges on its fees. Tick Include VAT to compare against your Takealot statement."})]})]}),s.jsxs(ml,{children:[s.jsx(W,{type:"button",variant:"outline",onClick:o,children:g?"Calculatingâ¦":"Close"}),n&&r&&s.jsx(W,{type:"button",onClick:$,disabled:!O||b,children:b?"Savingâ¦":"Save cost to catalogue"})]})]})})}function oh(e){return new Intl.NumberFormat("en-ZA",{style:"currency",currency:"ZAR",minimumFractionDigits:2,maximumFractionDigits:2}).format(e)}function X6e(e){return`${Number(e.toFixed(1))}%`}function UM(e){return e!=null?`${e.toFixed(1)}%`:"â"}function ym({label:e,value:t,muted:n}){return s.jsxs("div",{className:"flex items-center justify-between px-3 py-2",children:[s.jsx("span",{className:n?"text-text-secondary":"text-text-primary",children:e}),s.jsx("span",{className:"tabular-nums text-text-primary",children:t})]})}function J6e({slug:e,sku:t}){const[n,r]=p.useState(null);p.useEffect(()=>{let o=!1;return K.searchVisibilityProduct(e,t,7).then(l=>{o||r(l.product)}).catch(()=>{o||r(null)}),()=>{o=!0}},[e,t]);const a=`/sellers/${e}/inventory?tab=search-visibility&sku=${encodeURIComponent(t)}`,i=n==null?void 0:n.visibility;return s.jsxs(V,{className:"p-4",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-tertiary",children:"Search visibility"}),s.jsx("p",{className:"mt-0.5 text-xs text-text-secondary",children:"Organic and sponsored search appearance vs the previous 7 days."})]}),s.jsxs(st,{to:a,className:"inline-flex items-center gap-1 text-xs font-medium text-text-secondary hover:text-text-primary",children:["Open",s.jsx(os,{className:"h-3.5 w-3.5"})]})]}),s.jsxs("dl",{className:"mt-3 grid grid-cols-2 gap-x-4 gap-y-2 text-sm",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-tertiary",children:"Organic score"}),s.jsxs("div",{className:"mt-0.5 flex items-baseline gap-2",children:[s.jsx("span",{className:"font-semibold tabular-nums",children:Ql((n==null?void 0:n.organic.score)??(i==null?void 0:i.score))}),s.jsx(sf,{delta:(n==null?void 0:n.organic.delta)??(i==null?void 0:i.delta)})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-tertiary",children:"Sponsored score"}),s.jsxs("div",{className:"mt-0.5 flex items-baseline gap-2",children:[s.jsx("span",{className:"font-semibold tabular-nums",children:Ql(n==null?void 0:n.sponsored.score)}),s.jsx(sf,{delta:n==null?void 0:n.sponsored.delta})]})]})]})]})}function JV({slug:e,offer:t,open:n,onClose:r,onChanged:a,marketplace:i=null}){const o=_f(i),l=_p(o?i:i??"takealot"),c=((t==null?void 0:t.daily_units_30d)??[]).reduce((D,H)=>D+H,0),u=((t==null?void 0:t.total_seller_stock)??0)+((t==null?void 0:t.total_takealot_stock)??0),d=c>0?Math.round(u/c*30):u>0?null:0,h=c>0?((t==null?void 0:t.quantity_returned_30_days)??0)/c:null,f=t!=null&&t.rrp&&t.selling_price&&t.rrp>0?1-t.selling_price/t.rrp:null,[m,x]=p.useState(null),[g,y]=p.useState(""),[b,v]=p.useState(""),[w,_]=p.useState(""),[k,j]=p.useState(null),[N,E]=p.useState(null);p.useEffect(()=>{x(null),j(null),E(null)},[t==null?void 0:t.offer_id]);function A(){x("pricing"),y((t==null?void 0:t.selling_price)!=null?String(t.selling_price):""),v((t==null?void 0:t.rrp)!=null?String(t.rrp):"")}function C(){x("stock"),_((t==null?void 0:t.total_seller_stock)!=null?String(t.total_seller_stock):"")}function T(){x(null)}
888async function S(D){if(t){j(D),E({kind:"saving"});try{const H=await K.patchOffer(e,t.offer_id,{changes:D,confirm:!1});H.ok&&"preview"in H?E({kind:"preview",result:H}):H.ok||E({kind:"error",message:H.messages&&H.messages.join(` 889`)||H.message||H.error})}catch(H){E({kind:"error",message:(H==null?void 0:H.message)||String(H)})}}}async function O(){if(!(!t||!k)){E({kind:"saving"});try{const D=await K.patchOffer(e,t.offer_id,{changes:k,confirm:!0});D.ok&&"applied"in D?(E({kind:"success",result:D}),a==null||a()):D.ok||E({kind:"error",message:D.message||D.error})}catch(D){E({kind:"error",message:(D==null?void 0:D.message)||String(D)})}}}function R(){E(null),j(null),(N==null?void 0:N.kind)==="success"&&x(null)}function I(){const D={},H=g===""?null:Number(g),Y=b===""?null:Number(b);if(H!=null&&H!==(t==null?void 0:t.selling_price)&&(D.selling_price=H),!o&&Y!=null&&Y!==(t==null?void 0:t.rrp)&&(D.rrp=Y),Object.keys(D).length===0){T();return}S(D)}function $(){const D=w===""?null:Number(w);if(D==null||D===(t==null?void 0:t.total_seller_stock)){T();return}S({stock:D})}function P(){if(!t)return;const D=(t.status??"").toLowerCase()==="disabled_by_seller";S({status_action:D?"Re-enable":"Disable"})}const F=N!=null,Z=((t==null?void 0:t.status)??"").toLowerCase()==="disabled_by_seller";return s.jsxs(s.Fragment,{children:[s.jsx(Cr,{open:n,onOpenChange:D=>{D||r()},children:s.jsxs(mr,{side:"right",size:"lg",children:[s.jsx(Er,{children:s.jsxs("div",{className:"flex items-start justify-between gap-3 pr-8",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx(xr,{className:"font-mono",children:(t==null?void 0:t.sku)??"â"}),s.jsx(Mr,{className:"line-clamp-2",children:(t==null?void 0:t.title)??"Offer detail"})]}),(t==null?void 0:t.status)&&s.jsx(nFe,{status:t.status})]})}),s.jsx(pr,{className:"p-4 space-y-4",children:t?s.jsxs(s.Fragment,{children:[s.jsxs(V,{className:"p-4",children:[s.jsx(bm,{children:"Identifiers"}),s.jsxs("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-3 text-sm",children:[s.jsx(ps,{label:"SKU",value:t.sku??"â",mono:!0}),s.jsx(ps,{label:"TSIN",value:t.tsin_id!=null?String(t.tsin_id):"â",mono:!0}),s.jsx(ps,{label:"PLID",value:t.productline_id!=null?String(t.productline_id):"â",mono:!0}),s.jsx(ps,{label:"Offer ID",value:String(t.offer_id),mono:!0,muted:!0})]})]}),s.jsxs(V,{className:"p-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary",children:"Pricing"}),m!=="pricing"&&s.jsx(KM,{onClick:A})]}),m==="pricing"?s.jsxs("div",{className:"space-y-3",children:[s.jsx(Ok,{label:"Selling price (R)",value:g,onChange:y}),!o&&s.jsx(Ok,{label:"RRP (R)",value:b,onChange:v}),s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx(W,{intent:"brand",size:"sm",onClick:I,children:"Save"}),s.jsx(W,{intent:"neutral",variant:"ghost",size:"sm",onClick:T,children:"Cancel"})]})]}):s.jsxs("dl",{className:"grid grid-cols-3 gap-x-4 gap-y-3 text-sm",children:[s.jsx(ps,{label:"Selling price",value:ge(t.selling_price),emphasis:!0}),!o&&s.jsx(ps,{label:"RRP",value:ge(t.rrp),muted:!0}),!o&&s.jsx(ps,{label:"Discount",value:f!=null?Yn(f,0):"â",muted:!0})]})]}),s.jsxs(V,{className:"p-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary",children:"Stock & cover"}),m!=="stock"&&s.jsx(KM,{onClick:C,label:"Edit seller stock"})]}),m==="stock"?s.jsxs("div",{className:"space-y-3",children:[s.jsx(Ok,{label:"Seller-warehouse stock",value:w,onChange:_}),s.jsx("p",{className:"text-xs text-text-tertiary",children:o?"Only merchant-fulfilled (MFN) quantity is editable. Amazon owns FBA stock.":"Only seller-warehouse stock is editable here. Takealot-warehouse stock changes via shipment receipts."}),s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx(W,{intent:"brand",size:"sm",onClick:$,children:"Save"}),s.jsx(W,{intent:"neutral",variant:"ghost",size:"sm",onClick:T,children:"Cancel"})]})]}):s.jsxs("dl",{className:"grid grid-cols-3 gap-x-4 gap-y-3 text-sm",children:[s.jsx(ps,{label:"Seller stock",value:de(t.total_seller_stock??0)}),s.jsx(ps,{label:o?"At Amazon":"At Takealot",value:de(t.total_takealot_stock??0)}),s.jsx(ps,{label:"Total",value:de(u),emphasis:!0}),s.jsx(ps,{label:"Days of cover",value:d===0?"0d (OOS)":d==null?"â":`${d}d`,error:d===0,warn:d!=null&&d>0&&d<7}),!o&&s.jsx(ps,{label:"Listing quality",value:t.listing_quality!=null?`${t.listing_quality} / 3`:"â"})]}
889),m!=="stock"&&!o&&t.wh_item_qty_at_warehouse!=null&&s.jsxs("div",{className:"mt-4 pt-3 border-t border-outline-faint flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-tertiary",children:"In your warehouse · Gadjet"}),s.jsx("div",{className:"text-base font-semibold tabular-nums text-text-primary",children:de(t.wh_item_qty_at_warehouse)}),s.jsx("div",{className:"text-xs text-text-tertiary mt-0.5",children:"Tracked by the scanner; not yet on Takealot."})]}),t.wh_item_qty_at_warehouse!==(t.total_seller_stock??0)&&s.jsx(W,{intent:"brand",variant:"outline",size:"sm",onClick:()=>S({stock:t.wh_item_qty_at_warehouse}),children:"Push to Takealot"})]})]}),s.jsxs(V,{className:"p-4",children:[s.jsx(bm,{children:"Last 30 days"}),s.jsxs("div",{className:"mb-3 -ml-1",children:[s.jsx(Ws,{data:t.daily_units_30d,width:240,height:48,className:"text-brand-500"}),s.jsx("div",{className:"text-[10px] text-text-tertiary uppercase tracking-wider mt-1",children:"Daily units sold"})]}),s.jsxs("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-3 text-sm",children:[s.jsx(ps,{label:"Units sold",value:de(c),emphasis:!0}),s.jsx(ps,{label:"Units returned",value:de(t.quantity_returned_30_days??0)}),s.jsx(ps,{label:"Page views",value:de(t.page_views_30_days??0)}),!o&&s.jsx(ps,{label:"Wishlist 30d",value:t.wishlist_30_days!=null?de(t.wishlist_30_days):"â"}),s.jsx(ps,{label:"Conversion",value:t.conversion_percentage_30_days!=null?Yn(t.conversion_percentage_30_days/100,1):"â"}),s.jsx(ps,{label:"Return rate",value:h!=null?Yn(h,1):"â",error:h!=null&&h>.15})]}),!o&&s.jsx("p",{className:"mt-3 text-[11px] leading-4 text-text-tertiary",children:"Wishlist is for the product page (PLID), not this offer â every seller on the listing sees the same count."})]}),!o&&t.sku?s.jsx(J6e,{slug:e,sku:t.sku}):null,t.sku&&s.jsxs(V,{className:"p-4",children:[s.jsx(bm,{children:"Cost"}),s.jsx("p",{className:"mb-2 text-xs text-text-tertiary",children:"Used for margin and profit reports, and the repricer's margin/ROI floor. Stored in your Master Catalogue."}),s.jsx(tFe,{slug:e,sku:t.sku,sellPrice:t.selling_price})]}),s.jsxs(V,{className:"p-4",children:[s.jsx(bm,{children:"Trace this SKU"}),s.jsxs("div",{className:"space-y-2 text-sm",children:[t.productline_id!=null&&!o&&s.jsxs("a",{href:`https://www.takealot.com/x/PLID${t.productline_id}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-text-brand hover:underline",children:[s.jsx(Qt,{className:"w-3.5 h-3.5"}),"View product page on Takealot"]}),t.productline_id!=null&&!o&&s.jsx(Kd,{variant:"link",plid:t.productline_id,sellPrice:t.selling_price,slug:e,sku:t.sku,title:t.title}),t.sku&&s.jsxs(s.Fragment,{children:[s.jsxs(st,{to:`/sellers/${e}/sales?q=${encodeURIComponent(t.sku)}`,className:"flex items-center gap-2 text-text-brand hover:underline",children:[s.jsx(os,{className:"w-3.5 h-3.5"}),"Find in Sales"]}),s.jsxs(st,{to:`/sellers/${e}/returns?q=${encodeURIComponent(t.sku)}`,className:"flex items-center gap-2 text-text-brand hover:underline",children:[s.jsx(os,{className:"w-3.5 h-3.5"}),"Find in Returns"]})]})]})]}),s.jsxs(V,{className:"p-4 bg-surface-subtle/40",children:[s.jsx(bm,{children:"Listing status"}),s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("p",{className:"text-xs text-text-secondary",children:o?Z?"Amazon has no Re-enable action. Set merchant-fulfilled stock above 0 to make the listing buyable again.":"Disable sets merchant-fulfilled quantity to 0. FBA listings cannot be disabled from here.":Z?"Currently disabled. Re-enabling lets Takealot reassess and set the next status (buyable / not buyable).":"Currently active. Disabling hides the listing without deleting it â you can re-enable any time."}),!(o&&Z)&&s.jsxs(W,{intent:Z?"success":"warning",variant:"outline",size:"sm",onClick:P,children:[s.jsx(Cre,{className:"w-3.5 h-3.5"}),Z?"Re-enable":"Disable listing"]})]})]})]}):s.jsx("div",{className:"text-sm text-text-tertiary",children:"This offer isn't in the current view. Clear the search or status filter to find it."})})]})}),s.jsx(Q6e,{open:F,phase:N,offerSku:(t==null?void 0:t.sku)??null,marketName:l,onConfirm:O,onClose:R})]})}function Q6e({open:e,phase:t,offerSku:n,marketName:r,onConfirm:a,onClose:i}){return s.jsx(js,{open:e,onOpenChange:o=>{o||i()},children:s.jsxs(Ns,{size:"md",children:[s.jsxs(La,{children:[s.jsx(ma,{children:(t==null?void 0:t.kind)==="success"?"Patched":(t==null?void 0:t.kind)==="error"?"Couldn't patch":`Apply to ${r}?`}),n&&s.jsx(hc,{className:"font-mono",children:n})]}),s.jsxs("div",{className:"px-5 py-4",children:[(t==null?void 0:t.kind)==="saving"&&s.jsxs("div",{className:"flex items-center gap-3 text-sm text-text-secondary",children:[s.jsx(_e,{className:"w-4 h-4 animate-spin"}),"Talking to ",r,"â¦"]}),(t==null?void 0:t.kind)==="preview"&&"preview"in t.result&&s.jsx("div",{className:"space-y-3",children:t.result.noop?s.jsx("p",{className:"text-sm text-text-secondary",children:t.result.message}):s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"text-sm text-text-secondary",children:["This will hit the live ",r," listing API. Audit row will be recorded either way."]}),s.jsx(zM,{diff:t.result.diff})]})}),(t==null?void 0:t.kind)==="success"&&"applied"in t.result&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-success",children:[s.jsx(fn,{className:"w-4 h-4"}),t.result.async?"Submitted. Status will refresh on the next sync.":"Applied."]}),!t.result.async&&t.result.diff&&s.jsx(zM,{diff:t.result.diff})]}),(t==null?void 0:t.kind)==="error"&&s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-error",children:[s.jsx(yt,{className:"w-4 h-4"}),"Patch failed"]}),s.jsx("pre",{className:"text-xs text-text-body whitespace-pre-wrap bg-surface-subtle p-3 rounded border border-outline-faint",children:t.message})]})]}),s.jsx(da,{children:(t==null?void 0:t.kind)==="preview"&&!("noop"in t.result&&t.result.noop)?s.jsxs(s.Fragment,{children:[s.jsx(W,{intent:"neutral",variant:"ghost",onClick:i,children:"Cancel"}),s.jsxs(W,{intent:"brand",onClick:a,children:[s.jsx(fn,{className:"w-3.5 h-3.5"}),"Confirm + apply"]})]}):s.jsx(W,{intent:"neutral",variant:"ghost",onClick:i,children:"Close"})})]})})}function zM({diff:e}){if(!e)return null;const t=Object.entries(e);return t.length===0?null:s.jsx("ul",{className:"space-y-1.5 text-sm",children:t.map(([n,r])=>s.jsxs("li",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-text-tertiary uppercase tracking-wider text-[10px] w-28 shrink-0",children:eFe(n)}),s.jsx("span",{className:"font-mono text-xs text-text-tertiary",children:WM(r.from)}),s.jsx(os,{className:"w-3 h-3 text-text-tertiary"}),s.jsx("span",{className:"font-mono text-xs text-text-body font-semibold",children:WM(r.to)})]},n))})}function eFe(e){switch(e){case"selling_price":return"Selling price";case"rrp":return"RRP";case"stock":return"Stock";case"status":return"Status";default:return e}}function WM(e){return e==null?"â":typeof e=="number"?ge(e):String(e)}function Ok({label:e,value:t,onChange:n}){return s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"block text-[10px] text-text-tertiary uppercase tracking-wider mb-1",children:e}),s.jsx(Re,{type:"number",inputMode:"decimal",step:"0.01",value:t,onChange:r=>n(r.target.value),inputSize:"sm"})]})}function KM({onClick:e,label:t="Edit"}){return s.jsxs("button",{type:"button",onClick:e,className:"inline-flex items-center gap-1.5 text-xs text-text-secondary hover:text-text-primary rounded px-1.5 py-0.5 hover:bg-surface-subtle transition","aria-label":t,children:[s.jsx(Qi,{className:"w-3 h-3"}),s.jsx("span",{children:t})]})}function bm({children:e}){return s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary mb-3",children:e})}function tFe({slug:e,sku:t,sellPrice:n}){const[r,a]=p.useState(""),[i,o]=p.useState(!1),[l,c]=p.useState(!1),[u,d]=p.useState(null),[h,f]=p.useState(null);p.useEffect(()=>{let y=!0;return o(!1),d(null),f(null),K.profitCalc({sell_price:n&&n>0?n:1,slug:e,sku:t,cost_price:null}).then(b=>{y&&b.has_cost&&b.cost_excl_vat!=null&&a(b.cost_excl_vat.toFixed(2))}).catch(()=>{}).finally(()=>{y&&o(!0)}),()=>{y=!1}},[e,t,n]);const m=Number(r),x=r.trim()!==""&&Number.isFinite(m)&&m>=0&&!l;async function g(){if(x){c(!0),d(null),f(null);try{const y=await K.setSkuCost(e,t,Number(m.toFixed(2)));d(y.repriced_subscriptions>0?`Saved · repricer re-queued (${y.repriced_subscriptions})`:"Saved")}catch(y){f(y instanceof Error?y.message:"Couldn't save cost")}finally{c(!1)}}}return s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"flex items-end gap-2",children:[s.jsxs("label",{className:"block flex-1",children:[s.jsx("span",{className:"mb-1 block text-xs font-medium text-text-secondary",children:"Cost (excl. VAT)"}),s.jsx(Re,{type:"number",inputMode:"decimal",min:"0",step:"0.01",value:r,onChange:y=>{d(null),a(y.target.value)},placeholder:i?"none set":"â¦"})]}),s.jsx(W,{type:"button",onClick:g,disabled:!x,children:l?"Savingâ¦":"Save"})]}),u&&s.jsx("p",{className:"text-xs text-success-text",children:u}),h&&s.jsx("p",{className:"text-xs text-error-text",children:h})]})}function ps({label:e,value:t,emphasis:n,muted:r,warn:a,error:i,mono:o}){return s.jsxs("div",{children:[s.jsx("dt",{className:"text-[10px] text-text-tertiary uppercase tracking-wider",children:e}),s.jsx("dd",{className:B("font-medium tabular-nums mt-0.5",o&&"font-mono text-xs",i?"text-text-error font-semibold":a?"text-text-warning font-semibold":n?"text-text-body font-semibold text-base":r?"text-text-secondary":"text-text-body"),children:t})]})}function nFe({status:e}){const t=e.toLowerCase(),n=["buyable","active","available"].includes(t),r=["disabled","not_available","not_buyable"].some(a=>t.includes(a));return s.jsx("span",{className:B("text-xs uppercase tracking-wider px-2 py-1 rounded border font-medium shrink-0",n&&"bg-surface-successSubtle text-text-success border-outline-success",r&&"bg-surface-subtle text-text-secondary border-outline-subtle",!n&&!r&&"bg-surface-subtle text-text-secondary border-outline-subtle"),children:e})}const rFe=[{label:"7d",value:7},{label:"30d",value:30},{label:"90d",value:90}];function jw({days:e,onDays:t,loading:n,error:r,children:a}){return s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full space-y-4 p-4 md:p-6",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-body-xs text-text-secondary",children:"Rolled-up statistics for the selected window. Click any card for the full chart."}),s.jsx(Pa,{value:String(e),onValueChange:i=>t(Number(i)),className:"shrink-0",children:rFe.map(i=>
889s.jsx(Ln,{value:String(i.value),className:"tabular-nums",children:i.label},i.value))})]}),r&&s.jsxs(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:["Couldn't load statistics: ",r]}),n&&!r?s.jsxs("div",{className:"flex items-center gap-2 py-10 text-body-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Loading statisticsâ¦"]}):!r&&s.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:a})]})})}const Kg=[Ue.purple,Ue.blue,Ue.green,Ue.amber,Ue.violet,Ue.teal,Ue.red,Ue.slate];function rl(e,t){switch(t){case"zar":return ge(e);case"zarCompact":return ge(e,{compact:!0});case"percent":return Yn(e);case"number":default:return de(e)}}function Tn({title:e,subtitle:t,accent:n=Ue.purple,onClick:r,className:a,wide:i=!1,children:o}){const l=!!r;return s.jsxs(V,{padding:"md",interactive:l,onClick:r,role:l?"button":void 0,tabIndex:l?0:void 0,onKeyDown:l?c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),r==null||r())}:void 0,className:B("group border-t-2 flex flex-col",i&&"sm:col-span-2 lg:col-span-3",a),style:{borderTopColor:n},children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-body-sm font-semibold text-text-primary",children:e}),t!=null&&s.jsx("div",{className:"text-body-xs text-text-secondary",children:t})]}),l&&s.jsx(fr,{className:"h-4 w-4 shrink-0 text-text-tertiary transition-colors group-hover:text-text-secondary"})]}),s.jsx("div",{className:"flex-1",children:o})]})}const Up={contentStyle:{background:"rgb(var(--color-surface))",border:"1px solid rgb(var(--color-outline-subtle))",borderRadius:8,fontSize:12,padding:"6px 10px"},labelStyle:{color:vw,fontWeight:600,marginBottom:2}};function Yo({data:e,series:t,xKey:n="day",format:r="number",variant:a="preview",height:i}){const o=a==="full",l=i??(o?280:90);if(!e||e.length===0)return s.jsx(Nw,{h:l});const c=t[0],u=t.length===1,d=h=>rl(h,r==="percent"?"percent":"zarCompact");return s.jsx(li,{width:"100%",height:l,children:u?s.jsxs(DH,{data:e,margin:{top:4,right:4,bottom:0,left:0},children:[s.jsx("defs",{children:s.jsxs("linearGradient",{id:`grad-${c.key}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[s.jsx("stop",{offset:"0%",stopColor:c.color,stopOpacity:.28}),s.jsx("stop",{offset:"100%",stopColor:c.color,stopOpacity:0})]})}),o&&s.jsx(Ma,{strokeDasharray:"3 3",stroke:Co,vertical:!1}),s.jsx($a,{dataKey:n,hide:!o,tick:{fontSize:11,fill:kr},tickFormatter:Eh,minTickGap:24}),o&&s.jsx(zr,{tick:{fontSize:11,fill:kr},tickFormatter:h=>d(Number(h)),width:56}),s.jsx(Da,{...Up,labelFormatter:Eh,formatter:h=>[rl(Number(h),r),c.label]}),s.jsx(xw,{type:"monotone",dataKey:c.key,stroke:c.color,strokeWidth:2,fill:`url(#grad-${c.key})`})]}):s.jsxs(PH,{data:e,margin:{top:4,right:4,bottom:0,left:0},children:[o&&s.jsx(Ma,{strokeDasharray:"3 3",stroke:Co,vertical:!1}),s.jsx($a,{dataKey:n,hide:!o,tick:{fontSize:11,fill:kr},tickFormatter:Eh,minTickGap:24}),o&&s.jsx(zr,{tick:{fontSize:11,fill:kr},tickFormatter:h=>d(Number(h)),width:56}),s.jsx(Da,{...Up,labelFormatter:Eh,formatter:(h,f)=>[rl(Number(h),r),String(f)]}),o&&s.jsx(yE,{wrapperStyle:{fontSize:12}}),t.map(h=>s.jsx(Vi,{type:"monotone",dataKey:h.key,name:h.label,stroke:h.color,strokeWidth:2,strokeDasharray:h.comparison?"4 3":void 0,strokeOpacity:h.comparison?.55:1,dot:!1},h.key))]})})}function Gr({data:e,labelKey:t,valueKey:n,color:r=Ue.purple,colorFor:a,format:i="number",variant:o="preview",height:l,maxRows:c}){const u=o==="full",d=c?e.slice(0,c):e,h=l??Math.max(u?220:90,d.length*(u?30:20)+16);return!d||d.length===0?s.jsx(Nw,{h}):s.jsx(li,{width:"100%",height:h,children:s.jsxs(zx,{data:d,layout:"vertical",margin:{top:0,right:u?48:8,bottom:0,left:0},children:[u&&s.jsx(Ma,{strokeDasharray:"3 3",stroke:Co,horizontal:!1}),s.jsx($a,{type:"number",hide:!0,tickFormatter:f=>rl(Number(f),i)}),s.jsx(zr,{type:"category",dataKey:t,width:u?160:96,tick:{fontSize:11,fill:vw},tickFormatter:f=>aFe(f,u?28:14)}),s.jsx(Da,{...Up,cursor:{fill:Nu},formatter:f=>[rl(Number(f),i),""]}),s.jsx(vo,{dataKey:n,fill:r,radius:[0,4,4,0],maxBarSize:u?22:14,children:a&&d.map((f,m)=>s.jsx(zd,{fill:a(f)},m))})]})})}function Ki({data:e,labelKey:t,valueKey:n,format:r="number",variant:a="preview",height:i}){const o=a==="full",l=i??(o?260:110),c=(e??[]).filter(h=>Number(h[n])>0);if(c.length===0)return s.jsx(Nw,{h:l});const u=o?100:50,d=o?64:32;return s.jsxs("div",{className:o?"flex flex-col items-center gap-3":"flex items-center gap-3",children:[s.jsx(li,{width:o?"100%":"55%",height:l,children:s.jsxs(FDe,{children:[s.jsx(TK,{data:c,dataKey:n,nameKey:t,innerRadius:d,outerRadius:u,paddingAngle:1,stroke:"none",children:c.map((h,f)=>s.jsx(zd,{fill:Kg[f%Kg.length]},f))}),s.jsx(Da,{...Up,formatter:(h,f,m)=>{var x;return[rl(Number(h),r),String(((x=m==null?void 0:m.payload)==null?void 0:x[t])??"")]}})]})}),s.jsx("ul",{className:B("space-y-1",o?"w-full max-w-sm":"min-w-0 flex-1"),children:c.slice(0,o?12:4).map((h,f)=>s.jsxs("li",{className:"flex items-center gap-2 text-body-xs",children:[s.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{background:Kg[f%Kg.length]}}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-text-secondary",children:String(h[t])}),s.jsx("span",{className:"shrink-0 font-semibold tabular-nums text-text-primary",children:rl(Number(h[n]),r)})]},f))})]})}function bv({data:e,xKey:t="label",areas:n=[],bars:r=[],lines:a=[],leftFormat:i="number",rightFormat:o="percent",variant:l="preview",height:c,xIsDate:u=!1,referenceRight:d}){const h=l==="full",f=c??(h?300:120);if(!e||e.length===0)return s.jsx(Nw,{h:f});const m=[...a,...r,...n].some(x=>x.axis==="right");return s.jsx(li,{width:"100%",height:f,children:s.jsxs(Wx,{data:e,margin:{top:6,right:4,bottom:0,left:0},children:[h&&s.jsx(Ma,{strokeDasharray:"3 3",stroke:Co,vertical:!1}),s.jsx($a,{dataKey:t,hide:!h,tick:{fontSize:11,fill:kr},tickFormatter:u?Eh:void 0,minTickGap:24}),h&&s.jsx(zr,{yAxisId:"left",tick:{fontSize:11,fill:kr},tickFormatter:x=>rl(Number(x),i==="percent"?"percent":"zarCompact"),width:56}),h&&m&&s.jsx(zr,{yAxisId:"right",orientation:"right",tick:{fontSize:11,fill:kr},tickFormatter:x=>rl(Number(x),o),width:48}),!h&&s.jsx(zr,{yAxisId:"left",hide:!0}),!h&&m&&s.jsx(zr,{yAxisId:"right",orientation:"right",hide:!0}),s.jsx(Da,{...Up,labelFormatter:u?Eh:void 0,formatter:(x,g)=>{const y=[...n,...r,...a].find(v=>v.label===g),b=(y==null?void 0:y.axis)==="right"?o:i;return[rl(Number(x),b),String(g)]}}),h&&s.jsx(yE,{wrapperStyle:{fontSize:12}}),d&&s.jsx(UK,{yAxisId:"right",y:d.y,stroke:Ue.slate,strokeDasharray:"4 3",label:h?{value:d.label,fontSize:10,fill:kr,position:"right"}:void 0}),n.map(x=>s.jsx(xw,{yAxisId:x.axis==="right"?"right":"left",type:"monotone",dataKey:x.key,name:x.label,stroke:x.color,strokeWidth:2,fill:x.color,fillOpacity:.12},x.key)),r.map(x=>s.jsx(vo,{yAxisId:x.axis==="right"?"right":"left",dataKey:x.key,name:x.label,fill:x.color,radius:[3,3,0,0],maxBarSize:28},x.key)),a.map(x=>s.jsx(Vi,{yAxisId:x.axis==="right"?"right":"left",type:"monotone",dataKey:x.key,name:x.label,stroke:x.color,strokeWidth:2,dot:!1},x.key))]})})}function sFe({value:e,label:t,variant:n="preview",bands:r=[{upTo:40,color:Ue.red},{upTo:70,color:Ue.amber},{upTo:100,color:Ue.green}]}){var g,y;const a=n==="full",i=Math.max(0,Math.min(100,Number(e??0))),o=a?260:180,l=o/2-12,c=o/2,u=o/2,d=a?18:14,h=b=>{const v=Math.PI*(1-b);return{x:c+l*Math.cos(v),y:u-l*Math.sin(v)}},f=(b,v)=>{const w=h(b),_=h(v);return`M ${w.x} ${w.y} A ${l} ${l} 0 0 1 ${_.x} ${_.y}`},m=((g=r.find(b=>i<=b.upTo))==null?void 0:g.color)??((y=r[r.length-1])==null?void 0:y.color)??Ue.green;let x=0;return s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsxs("svg",{width:o,height:u+8,viewBox:`0 0 ${o} ${u+8}`,children:[s.jsx("path",{d:f(0,1),fill:"none",stroke:Co,strokeWidth:d,strokeLinecap:"round"}),r.map((b,v)=>{const w=s.jsx("path",{d:f(x/100,b.upTo/100),fill:"none",stroke:b.color,strokeOpacity:.18,strokeWidth:d},v);return x=b.upTo,w}),s.jsx("path",{d:f(0,i/100),fill:"none",stroke:m,strokeWidth:d,strokeLinecap:"round"}),s.jsx("text",{x:c,y:u-2,textAnchor:"middle",className:"tabular-nums",fontSize:a?40:30,fontWeight:700,fill:et.ink,children:Math.round(i)})]}),t!=null&&s.jsx("div",{className:"mt-1 text-body-xs text-text-secondary",children:t})]})}function Nw({h:e}){return s.jsx("div",{className:"flex items-center justify-center text-body-xs text-text-tertiary",style:{height:e},children:"No data for this window"})}function aFe(e,t){return e?e.length>t?e.slice(0,t-1)+"â¦":e:""}function Eh(e){const t=String(e??"");if(!/^(\d{4})-(\d{2})-(\d{2})/.exec(t))return t;const r=new Date(`${t}T00:00:00Z`);return Number.isNaN(r.getTime())?t:r.toLocaleDateString("en-ZA",{day:"numeric",month:"short",timeZone:"UTC"})}function br({open:e,onClose:t,slug:n,title:r,subtitle:a,accent:i=Ue.purple,askPrompt:o,children:l,table:c}){const u=Rt(),[d,h]=p.useState(!1);async function f(){if(!(!o||d)){h(!0);try{const m=await K.createChat(n);sessionStorage.setItem(`gadjet:seed:${m.id}`,o),u(`/sellers/${n}/chats/${m.id}`)}catch(m){console.error("StatDetailDrawer: seeded chat creation failed",m),h(!1)}}}return s.jsx(Cr,{open:e,onOpenChange:m=>!m&&t(),children:s.jsxs(mr,{side:"right",size:"xl",className:"border-t-2",style:{borderTopColor:i},children:[s.jsxs(Er,{children:[s.jsx(xr,{children:r}),a!=null&&s.jsx(Mr,{children:a})]}),s.jsxs(pr,{className:"px-4 py-4 space-y-5",children:[s.jsx("div",{children:l}),c!=null&&s.jsx("div",{children:c}),o&&s.jsx("div",{className:"pt-1",children:s.jsxs("button",{type:"button",onClick:f,disabled:d,className:"inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-body-sm font-semibold text-text-inverse transition disabled:opacity-50",style:{background:Ue.purple},children:[s.jsx(Rd,{className:"h-3.5 w-3.5"}),d?"Openingâ¦":"Ask Gadjet about this"]})})]})]})})}function rp({title:e,sku:t}){return s.jsxs("div",{className:"max-w-[280px]",children:[s.jsx("div",{className:"truncate text-text-primary",title:e??t,children:e??t}),e&&t?s.jsx("div",{className:"truncate font-mono text-[11px] text-text-tertiary",children:t}):null]})}function Ls({rows:e,cols:t,rowKey:n,empty:r="No rows"}){return s.jsx("div",{className:"overflow-hidden rounded-lg border border-outline-subtle",children:s.jsx(dt,{rows:e,columns:t.map((a,i)=>({key:`c${i}`,label:a.header,align:a.align,render:a.render})),getRowKey:n,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:r}}
889)})}const iFe=40;function HM(e){return e<2?Ue.red:e<=16?Ue.green:Ue.amber}const oFe={stockout:"Out of stock",under_7:"< 7 days",under_30:"7â30 days",under_90:"30â90 days",over_90:"> 90 days",no_velocity:"No sales (dead)"},lFe=["stockout","under_7","under_30","under_90","over_90","no_velocity"],cFe={3:"Excellent",2:"Moderate",1:"Poor",0:"Missing"};function uFe({slug:e,sellerName:t}){const n=t||e,[r,a]=it("statdays","30"),i=Number(r)||30,[o,l]=p.useState(null),[c,u]=p.useState(!0),[d,h]=p.useState(null),[f,m]=p.useState(null);p.useEffect(()=>{let T=!1;return u(!0),h(null),K.inventoryStats(e,i).then(S=>!T&&(l(S),u(!1))).catch(S=>!T&&(h(String((S==null?void 0:S.message)??S)),u(!1))),()=>{T=!0}},[e,i]);const x=o==null?void 0:o.cover,g=o==null?void 0:o.quality,y=o==null?void 0:o.snapshot,b=(o==null?void 0:o.stockout_risk)??[],v=(o==null?void 0:o.velocity)??[],w=o==null?void 0:o.cogs,_=p.useMemo(()=>{const T=new Map(((x==null?void 0:x.buckets)??[]).map(S=>[S.bucket,S.sku_count]));return lFe.map(S=>({label:oFe[S]??S,sku_count:T.get(S)??0}))},[x]),k=p.useMemo(()=>((g==null?void 0:g.buckets)??[]).map(T=>({label:cFe[T.score]??String(T.score),sku_count:T.sku_count})),[g]),j=p.useMemo(()=>y?[{region:"Johannesburg",stock:y.jhb_stock},{region:"Cape Town",stock:y.cpt_stock},{region:"Durban",stock:y.dbn_stock}]:[],[y]),N=p.useMemo(()=>v.map(T=>{const S=T.total_takealot_stock+T.total_seller_stock,O=T.units_sold_30d*7/30,R=O>0?S/O:null;return{sku:T.sku,title:T.title,weeks:R,weeks_capped:R==null?0:Math.min(R,iFe),units_sold_30d:T.units_sold_30d,stock:S}}).filter(T=>T.weeks!=null).sort((T,S)=>T.weeks-S.weeks),[v]),E=p.useMemo(()=>{var S;const T=[];if(x&&x.total_skus>0){const O=((S=x.buckets.find(R=>R.bucket==="stockout"))==null?void 0:S.sku_count)??0;T.push(1-O/x.total_skus),T.push(1-x.at_risk_skus/x.total_skus),T.push(1-x.dead_stock_skus/x.total_skus)}return g&&g.total_skus>0&&T.push(1-g.weak_skus/g.total_skus),T.length?T.reduce((O,R)=>O+R,0)/T.length*100:null},[x,g]),A=o==null?void 0:o.sell_through,C=p.useMemo(()=>((A==null?void 0:A.points)??[]).map(T=>({label:T.week,units_in:T.units_in,units_out:T.units_out,ratio:T.units_in>0?T.units_out/T.units_in:null})),[A]);return s.jsxs(jw,{days:i,onDays:T=>a(String(T)),loading:c,error:d,children:[s.jsx(Tn,{title:"Stock health",subtitle:"Across the catalogue",accent:Ue.purple,children:s.jsxs(dr,{cols:2,children:[s.jsx(Ye,{label:"SKUs",value:de(x==null?void 0:x.total_skus)}),s.jsx(Ye,{label:"At risk (â¤7d)",value:de(x==null?void 0:x.at_risk_skus),tone:((x==null?void 0:x.at_risk_skus)??0)>0?"warn":"default"}),s.jsx(Ye,{label:"Dead stock",value:de(x==null?void 0:x.dead_stock_skus),tone:((x==null?void 0:x.dead_stock_skus)??0)>0?"warn":"default"}),s.jsx(Ye,{label:"On hand (DC)",value:de(y==null?void 0:y.total_takealot_stock)})]})}),s.jsx(Tn,{title:"Inventory Health",subtitle:"Composite 0â100",accent:Ue.teal,children:s.jsx(sFe,{value:E,variant:"preview",label:E==null?"Not enough data":E>=70?"Healthy":E>=40?"Needs attention":"At risk"})}),s.jsx(Tn,{title:"Weeks of cover â top movers",subtitle:"Red < 2w understocked · green healthy · amber overstock",accent:Ue.blue,wide:!0,onClick:()=>m("woc"),children:s.jsx(Gr,{data:N,labelKey:"sku",valueKey:"weeks_capped",colorFor:T=>HM(Number(T.weeks)),format:"number",variant:"preview",maxRows:10})}),s.jsx(Tn,{title:"Days of cover",subtitle:"SKUs by stock runway",accent:Ue.blue,onClick:()=>m("cover"),children:s.jsx(Gr,{data:_,labelKey:"label",valueKey:"sku_count",color:Ue.blue,format:"number",variant:"preview"})}),s.jsx(Tn,{title:"Stockout risk",subtitle:"Revenue at risk",accent:Ue.red,onClick:()=>m("risk"),children:s.jsx(Gr,{data:b,labelKey:"sku",valueKey:"revenue_at_risk",color:Ue.red,format:"zarCompact",variant:"preview",maxRows:5})}),s.jsx(Tn,{title:"Listing quality",subtitle:"SKUs by quality score",accent:Ue.amber,onClick:()=>m("quality"),children:s.jsx(Gr,{data:k,labelKey:"label",valueKey:"sku_count",color:Ue.amber,format:"number",variant:"preview"})}),s.jsx(Tn,{title:"Stock by DC",subtitle:"Takealot-held units",accent:Ue.green,onClick:()=>m("dc"),children:s.jsx(Ki,{data:j,labelKey:"region",valueKey:"stock",format:"number",variant:"preview"})}),s.jsx(Tn,{title:"Top movers",subtitle:"Units sold · 30 days",accent:Ue.violet,onClick:()=>m("velocity"),children:s.jsx(Gr,{data:v,labelKey:"sku",valueKey:"units_sold_30d",color:Ue.violet,format:"number",variant:"preview",maxRows:5})}),s.jsx(Tn,{title:"Sell-through â received vs sold",subtitle:A&&A.total_sell_through!=null?`${A.total_sell_through.toFixed(2)}à sell-through (${de(A.total_units_out)} sold / ${de(A.total_units_in)} received)`:"Weekly inbound vs sales",accent:Ue.green,wide:!0,onClick:()=>m("sell_through"),children:s.jsx(bv,{data:C,xKey:"label",xIsDate:!0,bars:[{key:"units_in",label:"Received",color:Ue.blue},{key:"units_out",label:"Sold",color:Ue.green}],lines:[{key:"ratio",label:"Sell-through",color:Ue.purple,axis:"right"}],leftFormat:"number",rightFormat:"number",variant:"preview",height:170})}
889),s.jsx(Tn,{title:"COGS coverage",subtitle:"Cost data completeness",accent:Ue.teal,children:s.jsxs(dr,{cols:2,children:[s.jsx(Ye,{label:"Revenue costed",value:Yn(w==null?void 0:w.gmv_coverage_pct),tone:((w==null?void 0:w.gmv_coverage_pct)??0)<.8?"warn":"success"}),s.jsx(Ye,{label:"SKUs costed",value:Yn(w==null?void 0:w.sku_coverage_pct)}),s.jsx(Ye,{label:"SKUs with sales",value:de(w==null?void 0:w.skus_with_sales)}),s.jsx(Ye,{label:"Missing cost",value:de(w==null?void 0:w.skus_uncovered),tone:((w==null?void 0:w.skus_uncovered)??0)>0?"warn":"default"})]})}),s.jsx(br,{open:f==="woc",onClose:()=>m(null),slug:e,title:"Weeks of cover â top movers",subtitle:"Red < 2 weeks (reorder now) · green healthy · amber overstock",accent:Ue.blue,askPrompt:`Review ${n}'s weeks-of-cover on top-selling SKUs. Which need a replen right now, and which are overstocked and tying up cash?`,table:s.jsx(Ls,{rows:N,rowKey:T=>T.sku,cols:[{header:"Product",render:T=>s.jsx(rp,{title:T.title,sku:T.sku})},{header:"Weeks",align:"right",render:T=>T.weeks==null?"â":T.weeks.toFixed(1)},{header:"On hand",align:"right",render:T=>de(T.stock)},{header:"Units 30d",align:"right",render:T=>de(T.units_sold_30d)}]}),children:s.jsx(Gr,{data:N,labelKey:"sku",valueKey:"weeks_capped",colorFor:T=>HM(Number(T.weeks)),format:"number",variant:"full"})}),s.jsx(br,{open:f==="sell_through",onClose:()=>m(null),slug:e,title:"Sell-through â units received vs sold",subtitle:A&&A.total_sell_through!=null?`${A.total_sell_through.toFixed(2)}à over the window (>1 depleting, <1 building)`:void 0,accent:Ue.green,askPrompt:`Analyse ${n}'s sell-through (inbound vs sales) by week. Am I building or depleting inventory, and does inbound match demand?`,table:s.jsx(Ls,{rows:C,rowKey:T=>T.label,cols:[{header:"Week",render:T=>T.label},{header:"Received",align:"right",render:T=>de(T.units_in)},{header:"Sold",align:"right",render:T=>de(T.units_out)},{header:"Sell-through",align:"right",render:T=>T.ratio==null?"â":`${T.ratio.toFixed(2)}Ã`}]}),children:s.jsx(bv,{data:C,xKey:"label",xIsDate:!0,bars:[{key:"units_in",label:"Received",color:Ue.blue},{key:"units_out",label:"Sold",color:Ue.green}],lines:[{key:"ratio",label:"Sell-through",color:Ue.purple,axis:"right"}],leftFormat:"number",rightFormat:"number",variant:"full"})}),s.jsx(br,{open:f==="cover",onClose:()=>m(null),slug:e,title:"Days of cover â SKUs by stock runway",subtitle:x?`${de(x.total_skus)} SKUs`:void 0,accent:Ue.blue,askPrompt:`Look at ${n}'s days-of-cover distribution. Which SKUs need reordering now and which are overstocked?`,table:s.jsx(Ls,{rows:_,rowKey:T=>T.label,cols:[{header:"Cover",render:T=>T.label},{header:"SKUs",align:"right",render:T=>de(T.sku_count)}]}),children:s.jsx(Gr,{data:_,labelKey:"label",valueKey:"sku_count",color:Ue.blue,format:"number",variant:"full"})}),s.jsx(br,{open:f==="risk",onClose:()=>m(null),slug:e,title:"Stockout risk â revenue at risk",subtitle:`Next ${i} days`,accent:Ue.red,askPrompt:`Which of ${n}'s SKUs are about to stock out over the next ${i} days, and how much revenue is at risk? Suggest a reorder priority.`,table:s.jsx(Ls,{rows:b,rowKey:T=>T.sku,cols:[{header:"Product",render:T=>s.jsx(rp,{title:T.title,sku:T.sku})},{header:"Stock",align:"right",render:T=>de(T.total_stock)},{header:"Days left",align:"right",render:T=>T.days_until_stockout==null?"â":de(T.days_until_stockout)},{header:"Rev at risk",align:"right",render:T=>ge(T.revenue_at_risk)}]}),children:s.jsx(Gr,{data:b,labelKey:"sku",valueKey:"revenue_at_risk",color:Ue.red,format:"zarCompact",variant:"full"})}),s.jsx(br,{open:f==="quality",onClose:()=>m(null),slug:e,title:"Listing quality distribution",subtitle:g?`${de(g.weak_skus)} weak of ${de(g.total_skus)}`:void 0,accent:Ue.amber,askPrompt:`Break down ${n}'s listing-quality scores. Which SKUs are weakest and what would most improve them?`,table:s.jsx(Ls,{rows:k,rowKey:T=>T.label,cols:[{header:"Quality",render:T=>T.label},{header:"SKUs",align:"right",render:T=>de(T.sku_count)}]}),children:s.jsx(Gr,{data:k,labelKey:"label",valueKey:"sku_count",color:Ue.amber,format:"number",variant:"full"})}),s.jsx(br,{open:f==="dc",onClose:()=>m(null),slug:e,title:"Stock by DC â Takealot-held units",subtitle:y!=null&&y.captured_at?void 0:"No stock snapshot yet",accent:Ue.green,askPrompt:`How is ${n}'s Takealot stock split across JHB / CPT / DBN, and does it match where demand is?`,table:s.jsx(Ls,{rows:j,rowKey:T=>T.region,cols:[{header:"DC",render:T=>T.region},{header:"Units",align:"right",render:T=>de(T.stock)}]}),children:s.jsx(Ki,{data:j,labelKey:"region",valueKey:"stock",format:"number",variant:"full"})}),s.jsx(br,{open:f==="velocity",onClose:()=>m(null),slug:e,title:"Top movers â units sold in 30 days",accent:Ue.violet,askPrompt:`What are ${n}'s fastest-moving SKUs over the last 30 days, and are any at risk of stocking out?`,table:s.jsx(Ls,{rows:v,rowKey:T=>T.sku,cols:[{header:"Product",render:T=>s.jsx(rp,{title:T.title,sku:T.sku})},{header:"Units 30d",align:"right",render:T=>de(T.units_sold_30d)},{header:"DC stock",align:"right",render:T=>de(T.total_takealot_stock)}]}),children:s.jsx(Gr,{data:v,labelKey:"sku",valueKey:"units_sold_30d",color:Ue.violet,format:"number",variant:"full"})})]})}const dFe=["improved","declined","newly_visible","lost_coverage"];function hFe({slug:e,sku:t,days:n,view:r,open:a,onClose:i,fixtureProduct:o=null}){var v,w;const[l,c]=p.useState(o),[u,d]=p.useState(null),[h,f]=p.useState(!1);p.useEffect(()=>{if(!a||!t){c(o),d(null);return}if(o){c(o),f(!1);return}let _=!1;return f(!0),d(null),K.searchVisibilityProduct(e,t,n).then(k=>{_||(c(k.product),f(!1))}).catch(k=>{_||(d(String((k==null?void 0:k.message)??k)),f(!1))}),()=>{_=!0}},[a,e,t,n,o]);const m=(l==null?void 0:l.keywords)??[],x=r==="sponsored"?"sponsored":"organic",g=x==="sponsored"?(l==null?void 0:l.top_sponsored_contributors)??[]:(l==null?void 0:l.top_organic_contributors)??[],y=l==null?void 0:l.visibility,b=((v=m.find(_=>_.is_primary))==null?void 0:v.keyword)??((w=m[0])==null?void 0:w.keyword)??"";return s.jsx(Cr,{open:a,onOpenChange:_=>{_||i()},children:s.jsxs(mr,{side:"right",size:"lg",children:[s.jsx(Er,{children:s.jsxs("div",{className:"pr-8 min-w-0",children:[s.jsx(xr,{className:"font-mono",children:t??"â"}),s.jsx(Mr,{className:"line-clamp-2",children:(l==null?void 0:l.title)??"Search visibility"})]})}),s.jsx(pr,{className:"min-h-0 p-4 space-y-4",children:h?s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-tertiary py-8 justify-center",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"}),"Loading keyword changesâ¦"]}):u?s.jsx(V,{className:"p-4 text-sm text-text-error",children:u}):l?s.jsxs(s.Fragment,{children:[s.jsxs(dr,{cols:3,children:[s.jsx(Ye,{label:"Visibility score",value:Ql(y==null?void 0:y.score),delta:Ik(y==null?void 0:y.delta)}),s.jsx(Ye,{label:"Keyword coverage",value:(y==null?void 0:y.coverage)==null?"â":`${Ql(y.coverage)}%`,hint:`${l.organic.visible} of ${l.keyword_count} terms`,delta:Ik(y==null?void 0:y.coverage_delta)}),s.jsx(Ye,{label:"Ranking position",value:Ql(y==null?void 0:y.ranking_score),delta:Ik(y==null?void 0:y.ranking_delta)})]}),b?s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(W,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs(st,{to:qDe(b),children:["Discover competitor keywords",s.jsx(Qt,{className:"h-3.5 w-3.5"})]})}),s.jsx(W,{variant:"outline",size:"sm",asChild:!0,children:s.jsxs(st,{to:a3(b),children:["Keywords research",s.jsx(Qt,{className:"h-3.5 w-3.5"})]})})]}
889):null,s.jsxs(V,{className:"p-4 space-y-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-tertiary",children:"Largest contribution to the change"}),g.length===0?s.jsx("p",{className:"text-sm text-text-tertiary",children:"No period-over-period keyword movement in this window."}):s.jsx("ul",{className:"space-y-1.5",children:g.slice(0,6).map(_=>s.jsxs("li",{className:"flex items-center justify-between gap-3 text-sm",children:[s.jsxs("span",{className:"min-w-0 truncate",children:[s.jsx("span",{className:"text-text-primary",children:_.keyword}),s.jsx("span",{className:"ml-2 text-xs text-text-tertiary",children:RS(x==="sponsored"?_.sponsored_change:_.organic_change)})]}),s.jsx(sf,{delta:x==="sponsored"?_.sponsored_contribution:_.organic_contribution})]},_.keyword))})]}),dFe.map(_=>{const k=m.filter(j=>x==="sponsored"?j.sponsored_change===_:j.organic_change===_);return k.length?s.jsx(fFe,{title:RS(_),rows:k,channel:x},_):null}),s.jsx(mFe,{keywords:m,channel:x})]}):s.jsx("div",{className:"text-sm text-text-tertiary",children:"Select a product."})})]})})}function Ik(e){return e==null?void 0:{text:`${e>0?"+":""}${Number.isInteger(e)?e:e.toFixed(1)}`,positive:e>=0}}function fFe({title:e,rows:t,channel:n}){return s.jsxs(V,{className:"p-4",children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-tertiary mb-2",children:[e,s.jsx("span",{className:"ml-1.5 normal-case tracking-normal text-text-secondary",children:t.length})]}),s.jsx("ul",{className:"space-y-1",children:t.slice(0,12).map(r=>s.jsxs("li",{className:"flex items-center justify-between gap-2 text-sm",children:[s.jsx(st,{to:a3(r.keyword),className:"min-w-0 truncate text-text-primary hover:underline",children:r.keyword}),s.jsx("span",{className:"shrink-0 text-xs text-text-tertiary tabular-nums",children:n==="sponsored"?`${r.sponsored_slots_prior} â ${r.sponsored_slots} slots`:`${fv(r.organic_rank_prior)} â ${fv(r.organic_rank)}`})]},r.keyword))})]})}function mFe({keywords:e,channel:t}){const n=[{key:"keyword",label:"Keyword",sticky:!0,sortable:!0,getValue:r=>r.keyword,render:r=>s.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s.jsx("span",{className:B(r.is_primary&&"font-medium"),children:r.keyword}),r.is_primary?s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-tertiary",children:"primary"}):null]})},{key:"volume",label:"Volume",align:"right",sortable:!0,getValue:r=>r.monthly_searches,render:r=>s.jsx("span",{className:"text-text-secondary",children:de(r.monthly_searches)})},...t==="sponsored"?[{key:"slots",label:"Slots",align:"right",sortable:!0,getValue:r=>r.sponsored_slots,render:r=>s.jsxs("span",{className:"tabular-nums",children:[r.sponsored_slots,s.jsxs("span",{className:"ml-1 text-text-tertiary",children:["was ",r.sponsored_slots_prior]})]})}]:[{key:"rank",label:"Rank",align:"right",sortable:!0,getValue:r=>r.organic_rank,render:r=>s.jsxs("span",{className:"tabular-nums",children:[fv(r.organic_rank),s.jsx("span",{className:"ml-1 text-text-tertiary",children:fv(r.organic_rank_prior)})]})}],{key:"change",label:"Change",sortable:!0,getValue:r=>t==="sponsored"?r.sponsored_change:r.organic_change,render:r=>s.jsx(pFe,{change:t==="sponsored"?r.sponsored_change:r.organic_change})},{key:"open",label:"",stopRowClick:!0,render:r=>s.jsx(st,{to:a3(r.keyword),className:"inline-flex items-center text-text-tertiary hover:text-text-primary",title:"Open in Keywords research",children:s.jsx(os,{className:"h-3.5 w-3.5"})})}];return s.jsx(dt,{rows:e,columns:n,getRowKey:r=>r.keyword,persist:!1,paginate:e.length>25,empty:{title:"No keywords tracked for this product yet."}})}function pFe({change:e}){const t=e==="improved"||e==="newly_visible",n=e==="declined"||e==="lost_coverage";return s.jsx("span",{className:B("text-[10px] uppercase tracking-wider px-1.5 py-0.5 rounded border font-medium",t&&"bg-surface-successSubtle text-text-success border-outline-success",n&&"bg-surface-errorSubtle text-text-error border-outline-error",!t&&!n&&"bg-surface-subtle text-text-secondary border-outline-subtle"),children:RS(e)})}function xFe({slug:e,seller:t,fixture:n=null}){const r=_f(t==null?void 0:t.marketplace),[a,i]=it("days","7"),o=Number(a)||7,l=xM.includes(o)?o:7,[c,u]=it("view","organic"),d=c==="sponsored"?"sponsored":"organic",[h,f]=it("q",""),[m,x]=it("sku",""),[g,y]=p.useState(n),[b,v]=p.useState(null),[w,_]=p.useState(!n);p.useEffect(()=>{if(n){y(n),_(!1);return}if(r){_(!1);return}let P=!1;return _(!0),v(null),K.searchVisibility(e,l).then(F=>{P||(y(F),_(!1))}).catch(F=>{P||(v(String((F==null?void 0:F.message)??F)),_(!1))}),()=>{P=!0}},[e,l,r,n]);const k=p.useMemo(()=>[{key:"gaining",label:"Gaining visibility",predicate:P=>((d==="sponsored"?P.sponsored.delta:P.organic.delta)??0)>0},{key:"declining",label:"Losing ranking",predicate:P=>((d==="sponsored"?P.sponsored.delta:P.organic.delta)??0)<0},{key:"new-coverage",label:"More search terms",predicate:P=>((d==="sponsored"?P.sponsored.coverage_delta:P.organic.coverage_delta)??0)>0},{key:"lost-coverage",label:"Fewer search terms",predicate:P=>((d==="sponsored"?P.sponsored.coverage_delta:P.organic.coverage_delta)??0)<0},{key:"no-data",label:"No search data",predicate:P=>d==="sponsored"?P.sponsored.score==null:P.organic.score==null}],[d]),j=p.useMemo(()=>
889{if(!g)return null;const P=h.trim().toLowerCase();return P?g.products.filter(F=>`${F.sku??""} ${F.title??""} ${F.plid??""}`.toLowerCase().includes(P)):g.products},[g,h]),{activeChips:N,toggleChip:E,clearChips:A,filtered:C}=tu(j,k),T=p.useMemo(()=>gFe(d),[d]);if(r)return s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-surface-subtle/30",children:s.jsx("div",{className:"w-full px-4 py-6",children:s.jsx(V,{className:"p-6 text-sm text-text-secondary",children:"Search visibility is built from Takealot organic and sponsored search captures. It is not available on Amazon stores."})})});const S=g==null?void 0:g.summary,O=d==="sponsored"?S==null?void 0:S.gaining_sponsored:S==null?void 0:S.gaining_organic,R=d==="sponsored"?S==null?void 0:S.declining_sponsored:S==null?void 0:S.declining_organic,I=d==="sponsored"?S==null?void 0:S.avg_sponsored_score:S==null?void 0:S.avg_organic_score,$=d==="sponsored"?S==null?void 0:S.products_with_sponsored:S==null?void 0:S.products_with_organic;return s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full px-4 py-6 space-y-4",children:[s.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("h2",{className:"text-base font-semibold text-text-primary",children:"Search visibility"}),s.jsxs("p",{className:"mt-1 text-sm text-text-secondary",children:["Whether a product is appearing for more or fewer search terms, and whether its ",d," ranking is improving or declining, compared with the previous ",l,"-day period."]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("div",{className:"flex items-center gap-1 rounded-md border border-outline-subtle p-0.5",children:["organic","sponsored"].map(P=>s.jsx("button",{type:"button",onClick:()=>u(P),className:B("px-2.5 py-1 text-body-xs rounded capitalize",d===P?"bg-surface-inverse text-text-inverse":"text-text-secondary hover:text-text-primary"),children:P},P))}),s.jsx("div",{className:"flex items-center gap-1 rounded-md border border-outline-subtle p-0.5",children:xM.map(P=>s.jsxs("button",{type:"button",onClick:()=>i(String(P)),className:B("px-2.5 py-1 text-body-xs rounded",l===P?"bg-surface-inverse text-text-inverse":"text-text-secondary hover:text-text-primary"),children:[P,"d"]},P))})]})]}),b?s.jsx(V,{className:"p-4 text-sm text-text-error",children:b}):s.jsxs(dr,{cols:4,children:[s.jsx(Ye,{label:d==="sponsored"?"Avg sponsored score":"Avg organic score",value:Ql(I),hint:$!=null?`${$} products with data`:void 0}),s.jsx(Ye,{label:"Gaining",value:O??"â",tone:"success"}),s.jsx(Ye,{label:"Declining",value:R??"â",tone:"warn"}),s.jsx(Ye,{label:"Catalogue",value:(S==null?void 0:S.product_count)??"â",hint:"Takealot listings with a PLID"})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsx(Ni,{value:h,onChange:f,placeholder:"Search SKU, title, PLID"}),s.jsx(hu,{chips:k,activeChips:N,onToggle:E,onClear:A})]}),s.jsx(dt,{rows:w?null:C,columns:T,getRowKey:P=>P.offer_id,loading:w,sortUrlKey:"svsort",pageKey:"svpage",sizeKey:"svsize",defaultSort:{key:d==="sponsored"?"sponsored":"organic",direction:"desc"},onRowClick:P=>P.sku&&x(P.sku),empty:g!=null&&g.products.length?{title:"No products match these filters"}:{title:"No search ranking history yet",hint:"Rankings appear as Market Explorer keyword searches and nightly tracked-keyword captures land. Open Keywords research or Discover competitor keywords from a product to start building history.",icon:Fa}}),s.jsx(hFe,{slug:e,sku:m||null,days:l,view:d,open:!!m,onClose:()=>x(""),fixtureProduct:n?n.products.find(P=>P.sku===m)??null:null})]})})}function gFe(e){return[{key:"sku",label:"SKU",sortable:!0,sticky:!0,getValue:n=>n.sku,render:n=>s.jsx("span",{className:"whitespace-nowrap font-mono text-xs text-text-body",children:n.sku??"â"})},{key:"title",label:"Title",sortable:!0,getValue:n=>n.title,render:n=>s.jsx("span",{className:"max-w-[360px] truncate text-text-primary",children:n.title??"â"}),className:"max-w-[360px] truncate"},{key:e==="sponsored"?"sponsored":"organic",label:e==="sponsored"?"Sponsored score":"Organic score",sortable:!0,align:"right",getValue:n=>e==="sponsored"?n.sponsored.score:n.organic.score,render:n=>e==="sponsored"?s.jsx(DS,{score:n.sponsored.score,delta:n.sponsored.delta}):s.jsx(DS,{score:n.organic.score,delta:n.organic.delta})},{key:"coverage",label:"Coverage",sortable:!0,align:"right",title:"Share of tracked keywords the product currently appears for",getValue:n=>e==="sponsored"?n.sponsored.coverage:n.organic.coverage,render:n=>{const r=e==="sponsored"?n.sponsored.coverage:n.organic.coverage,a=e==="sponsored"?n.sponsored.coverage_delta:n.organic.coverage_delta;return s.jsxs("span",{className:"inline-flex flex-col items-end leading-tight",children:[s.jsx("span",{className:"tabular-nums text-text-primary",children:r==null?"â":`${Ql(r)}%`}),s.jsx(sf,{delta:a})]})}},{key:"keywords",label:"Keywords",sortable:!0,align:"right",getValue:n=>n.keyword_count,render:n=>s.jsxs("span",{className:"tabular-nums text-text-secondary",children:[e==="sponsored"?n.sponsored.visible:n.organic.visible,s.jsxs("span",{className:"text-text-tertiary",children:["/",n.keyword_count]})]})},{key:"price",label:"Price",sortable:!0,align:"right",getValue:n=>n.selling_price,render:n=>s.jsx("span",{className:"text-text-secondary",children:ge(n.selling_price)})}]}const yFe=[{key:"row",label:"Row",sortable:!1,render:e=>s.jsx("span",{className:"tabular-nums text-text-secondary",children:e.row??"â"})},{key:"sku",label:"SKU",sortable:!1,render:e=>s.jsx("span",{className:"font-mono text-xs",children:e.sku||"â"})},{key:"detail",label:"Problem",sortable:!1,render:e=>s.jsx("span",{children:e.detail||bFe(e.reason)})}];function bFe(e){switch(e){case"missing_sku":return"Missing SKU";case"missing_cost":return"No cost entered";case"bad_cost":return"Couldn't read the cost";case"negative_cost":return"Negative cost";case"not_in_catalogue":return"Not in your catalogue";case"ambiguous":return"Matched more than one product";case"write_failed":return"Couldn't save";default:return e}}function vFe(e,t){return e?e.phase==="parsing"?"Reading spreadsheetâ¦":e.phase==="matching"?"Matching products in your catalogueâ¦":e.phase==="saving"?e.total?`Saving costs⦠${de(e.done??0)} of ${de(e.total)}`:"Saving costsâ¦":e.phase==="done"?"Done":e.phase==="error"?"Couldn't finish the import":t:t}function wFe(e,t){return t!=null&&t<100?Math.min(30,Math.round(t*.3)):e?e.phase==="parsing"?35:e.phase==="matching"?55:e.phase==="saving"&&e.total&&e.total>0?Math.min(99,55+Math.round(44*(e.done??0)/e.total)):e.phase==="saving"?70:e.phase==="done"?100:null:t}async function _Fe(e,t){const{base64:n,mime_type:r}=await new Promise((a,i)=>{const o=new FileReader;o.onprogress=l=>{l.lengthComputable&&t(Math.round(l.loaded/l.total*100))},o.onload=()=>{t(100);const l=String(o.result||""),c=l.includes(",")?l.split(",")[1]:l;a({base64:c,mime_type:e.type})},o.onerror=()=>i(o.error||new Error("Couldn't read the file")),o.readAsDataURL(e)});return{filename:e.name,base64:n,mime_type:r}}async function kFe(e,t="missing",n=!1){const{blob:r,filename:a}=await K.downloadCogsTemplate(e,{scope:t,includeDisabled:n});uc(r,a)}function QV({slug:e,includeDisabled:t=!1,size:n="sm"}){const[r,a]=p.useState(!1),[i,o]=p.useState(null);async function l(c){if(!i){o(c),a(!1);try{await kFe(e,c,t)}catch(u){Ae.error(c==="all"?"Couldn't download the full cost sheet.":"Couldn't download the missing-cost sheet.",{description:u instanceof Error?u.message:String(u)})}finally{o(null)}}}return s.jsxs(Tf,{open:r,onOpenChange:a,children:[s.jsx(Of,{asChild:!0,children:s.jsxs(W,{type:"button",variant:"outline",intent:"neutral",size:n,disabled:!!i,children:[i?s.jsx(_e,{className:"w-3.5 h-3.5 animate-spin"}):s.jsx(Dr,{className:"w-3.5 h-3.5"}),i?"Downloadingâ¦":"Download costs",s.jsx(Pn,{className:"w-3 h-3 opacity-60"})]})}),s.jsxs($d,{align:"start",className:"w-72",children:[s.jsxs(Gh,{onClick:()=>void l("missing"),disabled:!!i,className:"flex-col items-start gap-0.5",children:[s.jsx("span",{className:"font-medium",children:"Missing costs"}),s.jsx("span",{className:"text-body-xs text-text-secondary font-normal leading-tight",children:"Only products with no cost yet"})]}),s.jsxs(Gh,{onClick:()=>void l("all"),disabled:!!i,className:"flex-col items-start gap-0.5",children:[s.jsx("span",{className:"font-medium",children:"All products"}),s.jsx("span",{className:"text-body-xs text-text-secondary font-normal leading-tight",children:"Full catalogue â existing costs filled in so you can update them"})]})]})]})}function jFe({slug:e,open:t,onClose:n,onApplied:r,includeDisabled:a=!1}){var F,Z,D,H,Y;const i=p.useRef(null),[o,l]=p.useState("pick"),[c,u]=p.useState(null),[d,h]=p.useState(null),[f,m]=p.useState(null),[x,g]=p.useState(null),[y,b]=p.useState(null),[v,w]=p.useState("Workingâ¦"),[_,k]=p.useState(""),[j,N]=p.useState(!1),E=p.useCallback(()=>
889{l("pick"),u(null),h(null),m(null),g(null),b(null),k(""),N(!1),i.current&&(i.current.value="")},[]);p.useEffect(()=>{t&&E()},[t,E]);async function A(M,z){var G,te,re;l("working"),w("Reading fileâ¦"),g(null),b(0);try{const L=await _Fe(M,b),q=z?{...L,column_overrides:z}:L;u(q),w("Checking your sheetâ¦");const me=await K.previewCogsImport(e,q);if(!me.ok&&me.error==="ambiguous_cost"){h(me),k(((re=(te=(G=me.candidates)==null?void 0:G.cost)==null?void 0:te[0])==null?void 0:re.raw)??""),l("preview");return}if(!me.ok){h(me),l("preview");return}h(me),l("preview")}catch(L){Ae.error("Couldn't read that file.",{description:L instanceof Error?L.message:String(L)}),l("pick")}}async function C(){if(!(!c||!(d!=null&&d.ok))){l("working"),w("Saving costsâ¦"),g({phase:"parsing"});try{const M=await K.applyCogsImport(e,c,z=>{g(z),w(vFe(z,"Saving costsâ¦"))});if(!M.ok){h(M),l("preview"),Ae.error("Couldn't save costs.",{description:M.message||M.error});return}m(M),l("result"),(M.saved??0)>0&&(Ae.success(`Saved ${de(M.saved??0)} product cost${(M.saved??0)===1?"":"s"}.`),r())}catch(M){Ae.error("Couldn't save costs.",{description:M instanceof Error?M.message:String(M)}),l("preview")}}}async function T(){if(!c||!_)return;const M={...c,column_overrides:{...c.column_overrides,cost:_}};u(M),l("working"),w("Checking your sheetâ¦");try{const z=await K.previewCogsImport(e,M);h(z),l("preview")}catch(z){Ae.error("Couldn't re-check the file.",{description:z instanceof Error?z.message:String(z)}),l("preview")}}const S=wFe(x,y),O=(o==="result"?f==null?void 0:f.issues:d==null?void 0:d.issues)??[],R=(o==="result"?f==null?void 0:f.issues_total:d==null?void 0:d.issues_total)??O.length,I=(d==null?void 0:d.error)==="ambiguous_cost",$=(d==null?void 0:d.would_save)??0,P=((F=d==null?void 0:d.headers_detected)==null?void 0:F.cost_vat_mode)==="incl"?"Treating the cost column as incl. VAT (we store excl.).":((Z=d==null?void 0:d.headers_detected)==null?void 0:Z.cost_vat_mode)==="excl"?"Treating the cost column as excl. VAT.":(D=d==null?void 0:d.headers_detected)!=null&&D.cost?"Couldn't tell VAT from the header â values will be saved as entered. Rename the column to Cost Incl. VAT if that's what you filled.":null;return s.jsx(js,{open:t,onOpenChange:M=>!M&&n(),children:s.jsxs(Ns,{size:"xl",className:"max-h-[90vh] overflow-hidden flex flex-col",children:[s.jsxs(La,{children:[s.jsx(ma,{children:"Upload product costs"}),s.jsxs(hc,{children:["Download missing costs, or the full catalogue with existing costs filled in. Edit the yellow"," ",s.jsx("strong",{children:"Cost Incl. VAT"})," column, then drop the file here."]})]}),s.jsxs(Oa,{className:"space-y-4 overflow-y-auto max-h-[60vh]",children:[o==="pick"&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-center gap-2",children:s.jsx(QV,{slug:e,includeDisabled:a,size:"md"})}),s.jsxs("div",{className:B("rounded-lg border border-dashed p-6 text-center transition-colors",j?"border-outline-brand bg-surface-brandSubtle":"border-outline-subtle"),onDragOver:M=>{M.preventDefault(),N(!0)},onDragLeave:()=>N(!1),onDrop:M=>{var G;M.preventDefault(),N(!1);const z=(G=M.dataTransfer.files)==null?void 0:G[0];z&&A(z)},children:[s.jsx("input",{ref:i,type:"file",accept:".csv,.xlsx,.xls,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel",className:"hidden",onChange:M=>{var G;const z=(G=M.target.files)==null?void 0:G[0];M.target.value="",z&&A(z)}}),s.jsx(ti,{className:"w-6 h-6 mx-auto text-text-tertiary"}),s.jsx("p",{className:"mt-2 text-sm text-text-primary",children:"Drop a CSV or Excel file here"}),s.jsx("p",{className:"mt-1 text-xs text-text-tertiary",children:"Our template, or your own export â we detect SKU and cost columns."}),s.jsx(W,{type:"button",variant:"outline",intent:"brand",className:"mt-3",onClick:()=>{var M;return(M=i.current)==null?void 0:M.click()},children:"Choose file"})]})]}),o==="working"&&s.jsxs("div",{className:"space-y-3 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-primary",children:[s.jsx(_e,{className:"w-4 h-4 animate-spin shrink-0"}),v]}),s.jsx("div",{className:"h-2 rounded-full bg-surface-subtle overflow-hidden",children:s.jsx("div",{className:B("h-full bg-intent-brand transition-[width] duration-300",S==null&&"w-1/3 animate-pulse"),style:S!=null?{width:`${Math.min(100,S)}%`}:void 0})})]}),o==="preview"&&d&&s.jsxs("div",{className:"space-y-3",children:[I?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-sm text-text-primary",children:"This sheet has more than one cost column. Which should we use?"}),s.jsx("div",{className:"flex flex-col gap-1.5",children:(((H=d.candidates)==null?void 0:H.cost)??[]).map(M=>s.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[s.jsx("input",{type:"radio",name:"cost-col",checked:_===M.raw,onChange:()=>k(M.raw),className:"accent-brand-500"}),s.jsxs("span",{children:[M.raw,M.vat_mode&&M.vat_mode!=="unknown"?s.jsxs("span",{className:"text-text-tertiary",children:[" · ",M.vat_mode,". VAT"]}):null]})]},M.raw))})]}):d.ok?s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"text-sm text-text-primary",children:[s.jsx("b",{children:de($)})," of ",de(d.total_rows??0)," rows are ready to save",(Y=d.headers_detected)!=null&&Y.cost?s.jsxs(s.Fragment,{children:[" ","from ",s.jsx("span",{className:"font-mono text-xs",children:d.headers_detected.cost})]}):null,".",(d.zero_skipped??0)>0&&s.jsxs(s.Fragment,{children:[" ",de(d.zero_skipped??0)," blank/zero rows will be skipped."]})]}),P&&s.jsx("p",{className:"text-xs text-text-secondary",children:P}),d.preview&&d.preview.length>0&&s.jsx("ul",{className:"text-xs text-text-secondary space-y-0.5 font-mono",children:d.preview.map(M=>s.jsxs("li",{children:[M.sku," â R",M.cost_incl_vat.toFixed(2)," incl."]},M.sku))})]}):s.jsx("p",{className:"text-sm text-text-error",children:d.message||d.error}),s.jsx(VM,{issues:O,total:R,truncated:d.issues_truncated})]}),o==="result"&&f&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("p",{className:"text-sm text-text-primary",children:[s.jsx("b",{children:de(f.saved??0)})," cost",(f.saved??0)===1?"":"s"," saved.",(f.issues_total??0)>0&&s.jsxs(s.Fragment,{children:[" ",s.jsxs("span",{className:"text-text-warning",children:[de(f.issues_total??0)," couldn't be updated."]})]})]}
889),s.jsx(VM,{issues:O,total:R,truncated:f.issues_truncated})]})]}),s.jsxs(da,{children:[o==="pick"&&s.jsx(W,{type:"button",variant:"outline",intent:"neutral",onClick:n,children:"Close"}),o==="preview"&&I&&s.jsxs(s.Fragment,{children:[s.jsx(W,{type:"button",variant:"outline",intent:"neutral",onClick:E,children:"Choose another file"}),s.jsx(W,{type:"button",onClick:()=>void T(),disabled:!_,children:"Use this column"})]}),o==="preview"&&!I&&s.jsxs(s.Fragment,{children:[s.jsx(W,{type:"button",variant:"outline",intent:"neutral",onClick:E,children:"Choose another file"}),s.jsx(W,{type:"button",onClick:()=>void C(),disabled:!(d!=null&&d.ok)||$<1,children:$>0?`Save ${de($)} costs`:"Nothing to save"})]}),o==="result"&&s.jsxs(s.Fragment,{children:[s.jsx(W,{type:"button",variant:"outline",intent:"neutral",onClick:E,children:"Upload another"}),s.jsx(W,{type:"button",onClick:n,children:"Done"})]})]})]})})}function VM({issues:e,total:t,truncated:n}){return e.length?s.jsxs("div",{className:"space-y-2",children:[s.jsxs("p",{className:"text-xs font-medium text-text-warning",children:[de(t)," row",t===1?"":"s"," we couldn't update",n?` (showing first ${e.length})`:""]}),s.jsx("div",{className:"max-h-56 overflow-y-auto border border-outline-subtle rounded",children:s.jsx(dt,{rows:e,columns:yFe,getRowKey:(r,a)=>`${r.row??"x"}-${r.sku??""}-${a}`,persist:!1,paginate:!1})})]}):null}function eq(e){return e==null?null:e>=3?{label:"Excellent",cls:"text-text-success"}:e===2?{label:"Moderate",cls:"text-text-secondary"}:e===1?{label:"Poor",cls:"text-text-warning"}:{label:"Missing",cls:"text-text-error"}}function NFe(e){const t=_f(e.marketplace),n=kp(e.fulfillment_channel);return t&&n==="FBA"?e.fba_qty_available??0:(e.total_takealot_stock??0)+(e.total_seller_stock??0)}function SFe(e){switch(e){case"takealot":return"TA";case"amazon_za":return"AMZ-ZA";case"amazon_us":return"AMZ-US";case"shopify":return"SFY";case"makro":return"MAK";default:return e.slice(0,3).toUpperCase()}}function CFe({listing:e}){const t=NFe(e),n=SFe(e.marketplace),r=_f(e.marketplace)?kp(e.fulfillment_channel):null,a=e.is_disabled?"bg-surface-errorSubtle text-text-error border-outline-error":t>0?"bg-surface-successSubtle text-text-success border-outline-success":"bg-surface-subtle text-text-secondary border-outline-subtle",i=e.selling_price!=null?ge(e.selling_price):"â",o=t===0?"OOS":`${de(t)}u`,l=eq(e.listing_quality),c=e.listing_quality!=null&&e.listing_quality<=1;return s.jsxs("span",{title:[`${e.marketplace} · ${e.seller_slug}`,`SKU: ${e.sku??"â"}`,r?`Fulfillment: ${r}`:null,`Status: ${e.status??"â"}`,`Price: ${i}`,`Stock: ${o}`,l?`Quality: ${l.label}`:null,e.link_quantity>1?`Bundle qty: ${e.link_quantity}`:null].filter(Boolean).join(` 890`),className:B("inline-flex items-center gap-1 text-body-xs px-1.5 py-0.5 rounded border tabular-nums",a),children:[s.jsx("span",{className:"font-semibold",children:n}),r?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-tertiary",children:"·"}),s.jsx("span",{className:"font-medium",children:r})]}):null,s.jsx("span",{children:"·"}),s.jsx("span",{children:i}),s.jsx("span",{className:"text-text-tertiary",children:"·"}),s.jsx("span",{children:o}),c?s.jsx(zn,{className:"h-3 w-3 text-text-warning","aria-label":"Low listing quality"}):null]})}const EFe=[{key:"sku",label:"SKU",sortable:!0,sticky:!0,getValue:e=>e.internal_sku,render:e=>s.jsx("span",{className:"whitespace-nowrap font-mono text-xs text-text-body",children:e.internal_sku??"â"})},{key:"title",label:"Title",sortable:!0,getValue:e=>e.title,className:"max-w-[360px] truncate",render:e=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"truncate",children:e.title??"â"}),e.bundle_count>0&&s.jsxs("span",{title:`Component of ${e.bundle_count} bundle${e.bundle_count>1?"s":""}`,className:"shrink-0 text-body-xs px-1.5 py-0.5 rounded border bg-surface-brandSubtle text-text-brand border-outline-brand font-medium",children:["in ",e.bundle_count," bundle",e.bundle_count>1?"s":""]})]})},{key:"barcode",label:"Barcode",sortable:!0,getValue:e=>e.barcode,render:e=>s.jsx("span",{className:"whitespace-nowrap font-mono text-xs text-text-secondary",children:e.barcode??"â"})},{key:"onhand",label:"On hand",sortable:!0,align:"right",getValue:e=>e.qty_at_warehouse,render:e=>s.jsx("span",{className:e.qty_at_warehouse===0?"font-semibold text-text-warning":void 0,children:de(e.qty_at_warehouse)})},{key:"price",label:"Current",sortable:!0,align:"right",title:"Current Takealot selling price (incl. VAT) on the primary listing.",getValue:e=>e.current_price,render:e=>s.jsx("span",{className:e.current_price==null?"text-text-tertiary":void 0,children:e.current_price!=null?ge(e.current_price):"â"})},{key:"cost",label:"Cost",sortable:!0,align:"right",title:"Master Catalogue COGS, excl. VAT.",getValue:e=>e.cost_excl_vat,render:e=>s.jsx("span",{className:e.cost_excl_vat==null?"text-text-tertiary":void 0,children:e.cost_excl_vat!=null?ge(e.cost_excl_vat):"â"})},{key:"fees",label:"Fees",sortable:!0,align:"right",title:"Takealot success + fulfilment at the current selling price (incl. VAT).",getValue:e=>e.unit_fees_incl_vat,render:e=>s.jsx("span",{className:e.unit_fees_incl_vat==null?"text-text-tertiary":void 0,children:e.unit_fees_incl_vat!=null?ge(e.unit_fees_incl_vat):"â"})},{key:"margin",label:"Nett margin",sortable:!0,align:"right",title:"Nett margin after Takealot fees at the current selling price (incl. VAT).",getValue:e=>e.margin_pct_incl_vat,render:e=>{const t=e.margin_pct_incl_vat;return t==null?s.jsx("span",{className:"text-text-tertiary",children:"â"}):s.jsx("span",{className:`tabular-nums ${t<0?"text-text-error":"text-text-success"}`,children:Yn(t/100,1)})}},{key:"listed",label:"Listed on",render:e=>s.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.listings.length===0&&s.jsx("span",{className:"text-body-xs text-text-tertiary italic",children:"Not listed"}),e.listings.map(t=>s.jsx(CFe,{listing:t},t.offer_id))]})}],LS=[{key:"statistics",label:"Statistics",icon:s.jsx(fc,{className:"w-3.5 h-3.5"}),render:({slug:e,seller:t})=>s.jsx(uFe,{slug:e,sellerName:(t==null?void 0:t.display_name)??void 0})},{key:"catalogue",label:"Master Catalogue",icon:s.jsx(Si,{className:"w-3.5 h-3.5"}),render:({slug:e,seller:t})=>s.jsx(LFe,{slug:e,seller:t})},{key:"listings",label:"Listings",icon:s.jsx(j2,{className:"w-3.5 h-3.5"}),render:({slug:e,seller:t})=>s.jsx(IFe,{slug:e,seller:t})},{key:"search-visibility",label:"Search visibility",icon:s.jsx(Fa,{className:"w-3.5 h-3.5"}),takealotOnly:!0,render:({slug:e,seller:t})=>s.jsx(xFe,{slug:e,seller:t})}],AFe=LS[0].key,tq=5e3;function zp(e){return(e.daily_units_30d??[]).reduce((t,n)=>t+n,0)}function Yc(e){return kp(e.fulfillment_channel)==="FBA"?e.fba_qty_available??0:(e.total_seller_stock??0)+(e.total_takealot_stock??0)}function FS(e){const t=Yc(e),n=zp(e);return n<=0?t>0?null:0:t/n*30}const qM=[{key:"dc-oos",label:"DC out of stock",predicate:e=>!rd(e)&&(e.total_takealot_stock??0)===0},{key:"wh-empty",label:"Warehouse empty",predicate:e=>!rd(e)&&Yc(e)===0},{key:"low-cover",label:"Low cover (<7d)",predicate:e=>{if(Yc(e)===0)return!1;const n=FS(e);return n!=null&&n<7}},{key:"dead",label:"Dead stock",predicate:e=>Yc(e)>0&&zp(e)===0},{key:"poor-conv",label:"Poor conversion",predicate:e=>(e.page_views_30_days??0)>50&&e.conversion_percentage_30_days!=null&&e.conversion_percentage_30_days<1},{key:"wanted",label:"Wanted, not selling",predicate:e=>!rd(e)&&(e.wishlist_30_days??0)>=10&&zp(e)===0},{key:"low-quality",label:"Low quality",predicate:e=>!rd(e)&&(e.listing_quality??0)<=1},{key:"losing-buybox",label:"Losing buybox",predicate:e=>!!e.repricer_enabled&&e.is_buybox_owner===!1}];function rd(e){return!!(e.disabled_by_seller||e.disabled_by_takealot)}function TFe(){const{slug:e=""}=jn(),[t,n]=p.useState(null),[r,a]=it("tab",AFe),i=LS.filter(l=>!l.takealotOnly||!_f(t==null?void 0:t.marketplace)),o=i.find(l=>l.key===r)??i[0]??LS[0];return p.useEffect(()=>{K.seller(e).then(n).catch(()=>{})},[e]),s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Sellers",to:"/"},{label:(t==null?void 0:t.display_name)??e,to:`/sellers/${e}`},{label:"Inventory"}]}),s.jsx(As,{items:i.map(l=>({key:l.key,label:l.key==="listings"?Ile(t==null?void 0:t.marketplace):l.label,icon:l.icon,active:o.key===l.ke
890y,onClick:()=>a(l.key)}))}),o.render({slug:e,seller:t}),s.jsx(OFe,{slug:e})]})}function OFe({slug:e}){return s.jsxs(st,{to:`/sellers/${e}/inventory/scan`,"aria-label":"Open barcode scanner",className:"md:hidden fixed bottom-5 right-5 z-30 flex items-center gap-2 px-4 py-3 rounded-full bg-brand-500 text-text-inverse shadow-lg shadow-brand-500/30 hover:bg-intent-brand active:scale-95 transition-transform",children:[s.jsx(Bre,{className:"w-5 h-5"}),s.jsx("span",{className:"text-sm font-medium",children:"Scan"})]})}function IFe({slug:e,seller:t}){var T;const n=_f(t==null?void 0:t.marketplace),r=n?qM.filter(S=>S.key!=="low-quality"&&S.key!=="losing-buybox"&&S.key!=="dc-oos"&&S.key!=="poor-conv"&&S.key!=="wanted"):qM,[a,i]=p.useState(null),[o,l]=it("q",""),[c,u]=it("disabled",""),d=c==="1",[h,f]=p.useState(null),[m,x]=p.useState(null),[g,y]=it("offer",""),b=g?(a==null?void 0:a.find(S=>String(S.offer_id)===g))??null:null,[v,w]=p.useState(0);p.useEffect(()=>{i(null),f(null);const S=setTimeout(()=>{K.offers(e,o,tq).then(i).catch(O=>f(String(O)))},200);return()=>clearTimeout(S)},[e,o,v]);const _=p.useMemo(()=>a?d?a:a.filter(S=>!rd(S)):null,[a,d]),{activeChips:k,toggleChip:j,clearChips:N,filtered:E}=tu(_,r),A=gd(E,p.useCallback(S=>S.status,[]),{urlKey:"status"}),C=p.useMemo(()=>A.filtered?{total:A.filtered.length,dcOos:A.filtered.filter(S=>!rd(S)&&(S.total_takealot_stock??0)===0).length,warehouseEmpty:A.filtered.filter(S=>!rd(S)&&Yc(S)===0).length}:null,[A.filtered]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full p-4 md:p-6 space-y-4",children:[C&&s.jsxs(dr,{cols:n?2:3,children:[s.jsx(Ye,{label:"Listings",value:de(C.total)}),!n&&s.jsx(Ye,{label:"DC out of stock",value:de(C.dcOos),tone:C.dcOos>0?"warn":void 0}),s.jsx(Ye,{label:"Warehouse empty",value:de(C.warehouseEmpty),tone:C.warehouseEmpty>0?"warn":void 0})]}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx(Ni,{value:o,onChange:l,placeholder:"Search by SKU or titleâ¦",className:"flex-1 min-w-[200px]"}),s.jsx(nu,{value:A.value,onChange:A.setValue,options:A.options,allLabel:"All statuses"}),s.jsxs("label",{className:"inline-flex items-center gap-1.5 text-xs text-text-secondary cursor-pointer select-none",children:[s.jsx("input",{type:"checkbox",checked:d,onChange:S=>u(S.target.checked?"1":""),className:"h-3.5 w-3.5 accent-brand-500"}),"Show disabled"]}),s.jsx(F6e,{slug:e,search:o||void 0,status:A.value||void 0,rowCount:(T=A.filtered)==null?void 0:T.length,onFreshness:x,onError:f})]}),s.jsx(hu,{chips:r,activeChips:k,onToggle:j,onClear:N}),m&&s.jsxs(V,{className:"p-3 text-xs text-text-warning bg-surface-warningSubtle border-outline-warning flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold",children:"Heads up â data may be stale."})," ","Offers were last synced ",s.jsx("span",{className:"font-mono",children:cn(m.asOf)})," ","(",Math.round(m.lagHours),"h ago). Re-sync to see current stock and listing changes."]}),s.jsx("button",{onClick:()=>x(null),className:"text-text-warning underline underline-offset-2 shrink-0",children:"Dismiss"})]}),h&&s.jsx(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:h}),s.jsx(V,{className:"overflow-hidden",children:s.jsx(dt,{rows:A.filtered,columns:$Fe(e,n),getRowKey:S=>S.offer_id,empty:{title:"No offers match."},onRowClick:S=>y(String(S.offer_id))})})]})}),s.jsx(JV,{slug:e,marketplace:t==null?void 0:t.marketplace,offer:b,open:!!g,onClose:()=>y(""),onChanged:()=>w(S=>S+1)})]})}function PFe({q:e}){const t=eq(e);return t?s.jsx("span",{className:B("text-xs font-medium",t.cls),children:t.label}):s.jsx("span",{className:"text-text-tertiary",children:"â"})}function RFe({o:e}){if(e.repricer_tier==null)return s.jsx("span",{className:"text-text-tertiary",children:"â"});if(!e.repricer_enabled)return s.jsx("span",{className:"text-xs text-text-tertiary",title:`Repricer paused · tier ${e.repricer_tier}`,children:"Paused"});const t=!!e.is_buybox_owner;return s.jsx("span",{className:B("text-xs font-medium",t?"text-text-success":"text-text-warning"),title:`Repricer running · tier ${e.repricer_tier}`,children:t?"Winning":"Lost"})}function DFe({cover:e,stock:t}){if(t===0)return s.jsx("span",{className:"font-semibold text-text-warning",children:"0d"});if(e==null)return s.jsx("span",{className:"text-text-tertiary",title:"No sales in the last 30 days â can't estimate cover",children:"â"});const n=Math.round(e),r=n<7;return s.jsxs("span",{className:r?"font-medium text-text-error":"text-text-secondary",children:[n,"d"]})}function MFe({status:e}){const t=(e??"").toLowerCase(),n=["buyable","active","available"].includes(t),r=["disabled","not_available","not_buyable"].some(a=>t.includes(a));return s.jsx("span",{className:B("text-body-xs uppercase tracking-wider px-1.5 py-0.5 rounded border font-medium",n&&"bg-surface-successSubtle text-text-success border-outline-success",r&&"bg-surface-subtle text-text-secondary border-outline-subtle",!n&&!r&&"bg-surface-subtle text-text-secondary border-outline-subtle"),children:e??"â"})}function $Fe(e,t=!1){const n=[{key:"sku",label:"SKU",sortable:!0,sticky:!0,getValue:r=>r.sku,render:r=>s.jsx("span",{className:"whitespace-nowrap font-mono text-xs text-text-body",children:r.sku??"â"})},{key:"title",label:"Title",sortable:!0,getValue:r=>r.title,render:r=>s.jsx("span",{className:"max-w-[420px] truncate text-text-primary",children:r.title??"â"}),className:"max-w-[420px] truncate"},{key:"status",label:"Status",sortable:!0,getValue:r=>r.status,render:r=>s.jsx(MFe,{status:r.status})},...t?[{key:"fulfillment",label:"Fulfillment",sortable:!0,getValue:r=>kp(r.fulfillment_channel)??"â",render:r=>s.jsx("span",{className:"text-xs font-medium text-text-secondary",children:kp(r.fulfillment_channel)??"â"})}]:[],{key:"price",label:"Price",sortable:!0,align:"right",getValue:r=>r.selling_price,render:r=>s.jsxs("span",{className:"inline-flex items-center justify-end gap-1.5",children:[ge(r.selling_price),r.productline_id!=null&&s.jsx(Kd,{plid:r.productline_id,sellPrice:r.selling_price,slug:e,sku:r.sku,title:r.title})]})},{key:"stock",label:"Stock",sortable:!0,align:"right",getValue:r=>Yc(r),render:r=>{const a=Yc(r);return s.jsx("span",{className:a===0?"font-semibold text-text-warning":void 0,children:de(a)})}},{key:"cover",label:"Cover",sortable:!0,align:"right",getValue:r=>FS(r),render:r=>s.jsx(DFe,{cover:FS(r),stock:Yc(r)})},{key:"sales30d",label:"Sales 30d",sortable:!0,align:"right",getValue:r=>zp(r),render:r=>{const a=zp(r);return s.jsxs("span",{className:"inline-flex items-center justify-end gap-2",children:[s.jsx(Ws,{data:r.daily_units_30d,className:"text-brand-500"}),s.jsx("span",{className:"min-w-[2ch] text-right text-text-secondary",children:a>0?de(a):"â"})]})}},{key:"views",label:"Page views 30d",sortable:!0,align:"right",getValue:r=>r.page_views_30_days,render:r=>s.jsx("span",{className:"text-text-secondary",children:de(r.page_views_30_days)})},{key:"wishlist",label:"Wishlist 30d",sortable:!0,align:"right",getValue:r=>r.wishlist_30_days,render:r=>s.jsx("span",{className:"text-text-secondary",title:"Product-level â every seller on this PLID sees the same count",children:r.wishlist_30_days!=null?de(r.wishlist_30_days):"â"})},{key:"conv",label:"Conv. 30d",sortable:!0,align:"right",getValue:r=>r.conversion_percentage_30_days,render:r=>s.jsx("span",{className:"text-text-secondary",children:r.conversion_percentage_30_days!=null?Yn(r.conversion_percentage_30_days/100,1):"â"})},{key:"quality",label:"Quality",sortable:!0,align:"right",getValue:r=>r.listing_quality,render:r=>s.jsx(PFe,{q:r.listing_quality})},{key:"repricer",label:"Repricer",align:"right",render:r=>s.jsx(RFe,{o:r})},{key:"returns",label:"Returns 30d",sortable:!0,align:"right",getValue:r=>r.quantity_returned_30_days,render:r=>s.jsx("span",{className:"text-text-secondary",children:de(r.quantity_returned_30_days)})}];return t?n.filter(r=>
890r.key!=="quality"&&r.key!=="repricer"&&r.key!=="views"&&r.key!=="wishlist"&&r.key!=="conv"):n}function LFe({slug:e,seller:t}){const[n,r]=p.useState(null),[a,i]=it("q",""),[o,l]=it("disabled",""),c=o==="1",[u,d]=p.useState(null),[h,f]=it("offer",""),[m,x]=it("upload",""),g=m==="cogs",[y,b]=p.useState(0),v=`gadjet:inv-banner-dismissed:${e}`,[w,_]=p.useState(()=>{try{return localStorage.getItem(v)==="1"}catch{return!1}});p.useEffect(()=>{r(null),d(null);const S=setTimeout(()=>{K.catalogue(e,a,tq,c).then(r).catch(O=>d(String(O)))},200);return()=>clearTimeout(S)},[e,a,c,y]);const k=p.useMemo(()=>{if(!h||!n)return null;for(const S of n){const O=S.listings.find(R=>R.offer_id===h);if(O)return{listing:O,product:S}}return null},[h,n]),j=(k==null?void 0:k.listing)??null,N=k?{offer_id:Number(k.listing.offer_id),tsin_id:null,productline_id:null,sku:k.listing.sku,title:k.listing.title,status:k.listing.status,selling_price:k.listing.selling_price,rrp:null,total_seller_stock:k.listing.total_seller_stock,total_takealot_stock:k.listing.total_takealot_stock,page_views_30_days:k.listing.page_views_30_days,wishlist_30_days:null,total_wishlist:null,conversion_percentage_30_days:null,quantity_returned_30_days:null,listing_quality:k.listing.listing_quality,disabled_by_seller:null,disabled_by_takealot:null,wh_item_qty_at_warehouse:k.product.qty_at_warehouse}:null,E=p.useMemo(()=>n?{total:n.length,withCost:n.filter(S=>S.cost_excl_vat!=null).length,onHand:n.reduce((S,O)=>S+(O.qty_at_warehouse||0),0)}:null,[n]),A=!w&&E!=null&&E.total>0&&E.withCost<E.total,C=E?E.total-E.withCost:0;function T(){try{localStorage.setItem(v,"1")}catch{}_(!0)}return s.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:[s.jsxs("div",{className:"w-full p-4 md:p-6 space-y-4",children:[E&&s.jsxs(dr,{cols:3,children:[s.jsx(Ye,{label:"SKUs",value:de(E.total)}),s.jsx(Ye,{label:"On-hand units",value:de(E.onHand)}),s.jsx(Ye,{label:"COGS set",value:`${de(E.withCost)} / ${de(E.total)}`,tone:E.total>0&&E.withCost<E.total?"warn":"success"})]}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx(Ni,{value:a,onChange:i,placeholder:"Search by SKU, title or barcodeâ¦",className:"flex-1 min-w-[200px]"}),s.jsxs("label",{className:"inline-flex items-center gap-1.5 text-xs text-text-secondary cursor-pointer select-none",children:[s.jsx("input",{type:"checkbox",checked:c,onChange:S=>l(S.target.checked?"1":""),className:"h-3.5 w-3.5 accent-brand-500"}),"Show disabled"]}),s.jsx(QV,{slug:e,includeDisabled:c,size:"sm"}),s.jsxs(W,{type:"button",variant:"outline",intent:"brand",size:"sm",onClick:()=>x("cogs"),children:[s.jsx(ti,{className:"w-3.5 h-3.5"}),"Upload costs"]}),E&&s.jsxs("div",{className:"text-xs text-text-secondary ml-auto",children:[de(E.total)," products ·"," ",de(E.onHand)," on hand ·"," ",s.jsxs("span",{className:B(E.withCost<E.total&&"text-text-warning"),children:["cost set on ",de(E.withCost)," / ",de(E.total)]})]})]}),A&&s.jsxs(V,{className:"p-3 bg-surface-brandSubtle border-outline-brand flex items-start gap-3",children:[s.jsxs("div",{className:"flex-1 text-sm text-text-primary",children:[s.jsxs("span",{className:"font-semibold",children:[de(E.total)," products in your Master Catalogue."]})," ",s.jsxs("span",{className:"text-text-secondary",children:["Cost unknown for ",de(C)," of them â download missing costs, fill Cost Incl. VAT, and upload. Use all products to update costs you already set."]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsxs("button",{type:"button",onClick:()=>x("cogs"),className:"inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded border border-outline-brand bg-surface text-text-brand hover:bg-surface-brandSubtle",children:[s.jsx(ti,{className:"w-3.5 h-3.5"}),"Upload costs"]}),s.jsx("button",{type:"button",onClick:T,title:"Dismiss","aria-label":"Dismiss banner",className:"p-1 text-text-tertiary hover:text-text-secondary rounded hover:bg-surface",children:s.jsx(Bn,{className:"w-3.5 h-3.5"})})]})]}),u&&s.jsx(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:u}),s.jsx(V,{className:"overflow-hidden",children:s.jsx(dt,{rows:n,columns:EFe,getRowKey:S=>S.id,empty:{title:a?"No products match.":"No products in your catalogue yet.",icon:zv},onRowClick:S=>{const O=S.listings[0];O&&f(O.offer_id)},rowClassName:S=>S.listings.length===0?"opacity-90":void 0})})]}),s.jsx(JV,{slug:(j==null?void 0:j.seller_slug)??e,marketplace:(j==null?void 0:j.marketplace)??(t==null?void 0:t.marketplace),offer:N,open:!!j,onClose:()=>f(""),onChanged:()=>b(S=>S+1)}),s.jsx(jFe,{slug:e,open:g,onClose:()=>x(""),onApplied:()=>b(S=>S+1),includeDisabled:c})]})}function Hg(){const e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),r=String(e.getDate()).padStart(2,"0");return`${t}-${n}-${r}`}function GM(e){const t=new Date;t.setDate(t.getDate()-e);const n=t.getFullYear(),r=String(t.getMonth()+1).padStart(2,"0"),a=String(t.getDate()).padStart(2,"0");return`${n}-${r}-${a}`}function Sw({value:e,presets:t,onPreset:n,onCustom:r,className:a}){const[i,o]=p.useState(!1),l=!!(e.since&&e.until),[c,u]=p.useState(e.since||GM(e.days)),[d,h]=p.useState(e.until||Hg());p.useEffect(()=>
890{i&&(u(e.since||GM(e.days)),h(e.until||Hg()))},[i,e.since,e.until,e.days]);function f(){!c||!d||c>d||(r(c,d),o(!1))}let m;if(l)m=`${cn(e.since)} â ${cn(e.until)}`;else{const x=t.find(g=>g.days===e.days);m=x?x.label:`Last ${e.days} days`}return s.jsxs(Tf,{open:i,onOpenChange:o,children:[s.jsx(Of,{asChild:!0,children:s.jsxs("button",{type:"button",className:B("inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-md","border border-outline-subtle bg-surface text-text-primary","hover:bg-surface-subtle transition",a),children:[s.jsx(yd,{className:"w-3.5 h-3.5 text-text-tertiary"}),m,s.jsx(Pn,{className:"w-3 h-3 text-text-tertiary"})]})}),s.jsxs($d,{align:"start",className:"w-72 p-2",children:[s.jsx("div",{className:"space-y-0.5",children:t.map(x=>{const g=!l&&e.days===x.days;return s.jsxs("button",{type:"button",onClick:()=>{n(x.days),o(!1)},className:B("w-full flex items-center justify-between px-3 py-1.5 text-xs rounded transition",g?"bg-surface-brandSubtle text-text-brand font-medium":"text-text-body hover:bg-surface-subtle"),children:[s.jsx("span",{children:x.label}),g&&s.jsx(fn,{className:"w-3.5 h-3.5"})]},x.days)})}),s.jsx("div",{className:"my-2 border-t border-outline-faint"}),s.jsxs("div",{className:"px-2 pb-1",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("div",{className:"text-xs font-medium text-text-secondary",children:"Custom range"}),l&&s.jsx("span",{className:"text-[10px] text-text-brand font-medium uppercase tracking-wider",children:"Active"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"block text-[10px] text-text-tertiary uppercase tracking-wider mb-0.5",children:"From"}),s.jsx("input",{type:"date",value:c,max:d||Hg(),onChange:x=>u(x.target.value),className:"block w-full text-xs px-2 py-1 rounded border border-outline bg-surface focus:outline-none focus:border-outline-brand focus-visible:shadow-focus"})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"block text-[10px] text-text-tertiary uppercase tracking-wider mb-0.5",children:"To"}),s.jsx("input",{type:"date",value:d,min:c||void 0,max:Hg(),onChange:x=>h(x.target.value),className:"block w-full text-xs px-2 py-1 rounded border border-outline bg-surface focus:outline-none focus:border-outline-brand focus-visible:shadow-focus"})]})]}),s.jsx(W,{onClick:f,disabled:!c||!d||c>d,size:"sm",className:"w-full mt-2",children:"Apply"})]})]})]})}function FFe(e,t){if(!e||!t)return null;const n=new Date(e).getTime(),r=new Date(t).getTime();if(!isFinite(n)||!isFinite(r))return null;const a=r-n;return a<0?0:Math.round(a/864e5)}function BFe({slug:e,ret:t,open:n,onClose:r}){const a=jf(),i=t?FFe(t.original_order_date,t.return_date):null,o=(t==null?void 0:t.sku_units_sold_in_window)??0,l=(t==null?void 0:t.sku_units_returned_in_window)??0,c=o>0?l/o:null;return s.jsx(Cr,{open:n,onOpenChange:u=>{u||r()},children:s.jsxs(mr,{side:"right",size:"lg",children:[s.jsxs(Er,{children:[s.jsx(xr,{children:t!=null&&t.title?s.jsx("span",{title:t.title,children:t.title}):s.jsxs(s.Fragment,{children:["Return · ",s.jsx("span",{className:"font-mono",children:(t==null?void 0:t.sku)??"â"})]})}),s.jsx(Mr,{children:t?`${t.title&&t.sku?`${t.sku} · `:""}${cn(t.return_date)}${t.return_region?` · ${t.return_region}`:""}${t.primary_outcome?` · ${t.primary_outcome}`:""}`:"Return detail"})]}),s.jsx(pr,{className:"p-4 space-y-4",children:t?s.jsxs(s.Fragment,{children:[s.jsxs(V,{className:"p-4",children:[s.jsx(lh,{children:"Return summary"}),s.jsxs("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-3 text-sm",children:[s.jsx(Bo,{label:"Quantity returned",value:de(t.quantity),emphasis:!0}),s.jsx(Bo,{label:"Days from order",value:i==null?"â":i===0?"Same day":`${i}d`,warn:i!=null&&i===0,muted:i!=null&&i>30}),s.jsx(Bo,{label:"Region",value:t.return_region??"â"}),s.jsx(Bo,{label:"Outcome",value:t.primary_outcome??"â"}),s.jsx(Bo,{label:"Return ID",value:String(t.seller_return_id),mono:!0,muted:!0})]})]}),t.customer_comment&&t.customer_comment.trim()&&s.jsxs(V,{className:"p-4 bg-surface-warningSubtle/40 border-outline-warning/40",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx(VT,{className:"w-4 h-4 text-text-warning"}),s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary",children:"Customer comment"})]}),s.jsx("p",{className:"text-sm text-text-body whitespace-pre-wrap",children:t.customer_comment})]}),s.jsxs(V,{className:"p-4",children:[s.jsx(lh,{children:"Reason"}),s.jsx("p",{className:"text-sm text-text-body whitespace-pre-wrap",children:t.return_reason??"â"})]}),t.order_id!=null&&s.jsxs(V,{className:"p-4",children:[s.jsx(lh,{children:"Original order"}),s.jsxs("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-3 text-sm",children:[s.jsx(Bo,{label:"Order #",value:`#${t.order_id}`,mono:!0}),s.jsx(Bo,{label:"Ordered",value:t.original_order_date?cn(t.original_order_date):"â",muted:!t.original_order_date})]})]}),s.jsxs(V,{className:"p-4",children:[s.jsx(lh,{children:"SKU in this window"}),s.jsxs("dl",{className:"grid grid-cols-3 gap-x-4 gap-y-3 text-sm",children:[s.jsx(Bo,{label:"Units sold",value:de(o)}),s.jsx(Bo,{label:"Units returned",value:de(l)}),s.jsx(Bo,{label:"Return rate",value:c==null?"â":Yn(c,1),error:c!=null&&c>.15,emphasis:c!=null&&c<=.15})]})]}),s.jsxs(V,{className:"p-4",children:[s.jsx(lh,{children:"Trace this return"}),s.jsxs("div",{className:"space-y-2 text-sm",children:[t.sku&&s.jsxs(st,{to:`/sellers/${e}/inventory?q=${encodeURIComponent(t.sku)}`,className:"flex items-center gap-2 text-text-brand hover:underline",children:[s.jsx(os,{className:"w-3.5 h-3.5"}),"Open SKU dossier"]}),t.order_id!=null&&s.jsxs(s.Fragment,{children:[s.jsxs(st,{to:`/sellers/${e}/sales?q=${t.order_id}`,className:"flex items-center gap-2 text-text-brand hover:underline",children:[s.jsx(os,{className:"w-3.5 h-3.5"}),"Find the original sale"]}),s.jsxs(st,{to:`/sellers/${e}/transactions?q=${t.order_id}`,className:"flex items-center gap-2 text-text-brand hover:underline",children:[s.jsx(os,{className:"w-3.5 h-3.5"}),"Find refund transactions"]})]})]})]}),t.sku&&s.jsxs(V,{className:"p-4",children:[s.jsx(lh,{children:"Act on it"}),s.jsxs("button",{type:"button",onClick:()=>a(`Returns are high for SKU ${t.sku}`+(c!=null?` (about ${Math.round(c*100)}% of units sold)`:"")+(t.return_reason?`. The stated reason is "${t.return_reason}".`:".")+" Diagnose the likely cause (listing accuracy, pricing, packaging, or variant clarity) and tell me how to cut the return rate.",e),className:"mt-1 inline-flex items-center gap-2 rounded-md bg-intent-brand px-3 py-1.5 text-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover",children:[s.jsx(VT,{className:"w-3.5 h-3.5"}),"Help me reduce returns for this SKU"]})]})]}):s.jsx("div",{className:"text-sm text-text-tertiary",children:"This return isn't in the current view. Widen the date range or clear the filters to find it."})})]})})}function lh({children:e}){return s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary mb-3",children:e})}function Bo({label:e,value:t,emphasis:n,muted:r,warn:a,error:i,mono:o}){return s.jsxs("div",{children:[s.jsx("dt",{className:"text-[10px] text-text-tertiary uppercase tracking-wider",children:e}),s.jsx("dd",{className:B("font-medium tabular-nums mt-0.5",o&&"font-mono text-xs",i?"text-text-error font-semibold":a?"text-text-warning font-semibold":n?"text-text-body font-semibold text-base":r?"text-text-secondary":"text-text-body"),children:t})]})}const Fs=p.forwardRef(({className:e,...t},n)=>s.jsx("label",{ref:n,className:B("text-body-sm font-medium text-text-primary",e),...t}));Fs.displayName="Label";const vv=p.forwardRef(({className:e,...t},n)=>s.jsx(z7,{ref:n,className:B("flex flex-col gap-2",e),...t}));vv.displayName="RadioGroup";const b3=p.forwardRef(({className:e,...t},n)=>
890s.jsx(K7,{ref:n,className:B("shrink-0 h-4 w-4 rounded-full border border-outline bg-surface focus:outline-none focus-visible:shadow-focus data-[state=checked]:border-intent-brand data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 transition",e),...t,children:s.jsx(Cge,{className:"flex items-center justify-center h-full w-full",children:s.jsx("span",{className:"h-2 w-2 rounded-full bg-intent-brand"})})}));b3.displayName="RadioGroupItem";function Vg({value:e,label:t,description:n,disabled:r}){const a=p.useId();return s.jsxs("div",{className:B("flex items-start gap-2",r&&"opacity-50"),children:[s.jsx(b3,{id:a,value:e,disabled:r,className:"mt-0.5"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx(Fs,{htmlFor:a,className:B("font-normal text-text-body",r&&"cursor-not-allowed"),children:t}),n&&s.jsx("div",{className:"text-body-sm text-text-secondary mt-0.5",children:n})]})]})}const Pk=e=>e==null?"â":`R${Number(e).toFixed(2)}`,Rk={length:"40",width:"30",height:"20",weight:"5"};function YM(e){return e?[e.street_address,e.local_area,e.city,e.code].filter(Boolean).join(", "):"â"}function UFe(e){const t=[];for(const n of e){if(n==null||n==="")continue;const r=Number(n);Number.isFinite(r)&&r>0&&!t.includes(r)&&t.push(r)}return t}function nq({slug:e,shipmentId:t=null,poNumber:n=null,removalOrderId:r=null,removalOrderIds:a=null,removalOrderRef:i=null,removalOrderRefs:o=null,open:l,onOpenChange:c,onBooked:u}){var q,me;const d=UFe([...Array.isArray(a)?a:[],r]),h=d.length>0,[f,m]=p.useState("loading"),[x,g]=p.useState(null),[y,b]=p.useState([Rk]),[v,w]=p.useState(null),[_,k]=p.useState(null),[j,N]=p.useState(null),[E,A]=p.useState(null),[C,T]=p.useState(!1),[S,O]=p.useState(null),[R,I]=p.useState("");p.useEffect(()=>{l&&(m("loading"),w(null),k(null),N(null),A(null),O(null),I(typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():String(Date.now())),K.courier.bookContext(e,h?{removalOrderIds:d}:{shipmentId:t}).then(ee=>{var X;g(ee),k(ee.provider??null);const ne=((X=ee.parcels)!=null&&X.length?ee.parcels:[{}]).map(he=>({length:String(he.submitted_length_cm??40),width:String(he.submitted_width_cm??30),height:String(he.submitted_height_cm??20),weight:String(he.submitted_weight_kg??5),description:he.parcel_description}));b(ne.length?ne:[Rk]),m("form")}).catch(ee=>{O((ee==null?void 0:ee.message)||"Couldn't load the booking details."),m("form")}))},[l,e,t,d.join(","),h]);const $=(ee,ne,X)=>b(he=>he.map((ae,je)=>je===ee?{...ae,[ne]:X.replace(/[^0-9.]/g,"")}:ae)),P=()=>b(ee=>[...ee,{...Rk}]),F=ee=>b(ne=>ne.length>1?ne.filter((X,he)=>he!==ee):ne),Z=p.useCallback(()=>y.map(ee=>{var ne;return{submitted_length_cm:Number(ee.length)||0,submitted_width_cm:Number(ee.width)||0,submitted_height_cm:Number(ee.height)||0,submitted_weight_kg:Number(ee.weight)||0,parcel_description:ee.description??((ne=x==null?void 0:x.removal_order_references)!=null&&ne.length?`Return ${x.removal_order_references.join(" + ")}`:x!=null&&x.removal_order_reference?`Return ${x.removal_order_reference}`:x!=null&&x.purchase_order_number?`Inbound PO ${x.purchase_order_number}`:h?"Return from Takealot DC":"Inbound to Takealot")}}),[y,x,h]),D=y.every(ee=>Number(ee.weight)>0&&Number(ee.length)>0&&Number(ee.width)>0&&Number(ee.height)>0),H=y.reduce((ee,ne)=>ee+(Number(ne.weight)||0),0),Y=async()=>{if(!(x!=null&&x.collection_address)||!(x!=null&&x.delivery_address)){O(h?"Missing a collection or delivery address for this return.":"Missing a collection or delivery address for this PO.");return}if(!D){O("Every parcel needs a length, width, height and weight greater than zero.");return}T(!0),O(null);try{const ee=await K.courier.rates(e,{collection_address:x.collection_address,delivery_address:x.delivery_address,parcels:Z(),lane:x.lane,destination_node:x.destination_node??void 0});k(ee.provider??x.provider??null);const ne=[...ee.rates??[]].sort((X,he)=>X.takealot_eligible!==he.takealot_eligible?X.takealot_eligible?-1:1:(X.price??X.seller_price??0)-(he.price??he.seller_price??0));w(ne),N(ne.find(X=>X.takealot_eligible)??null),m("rates")}catch(ee){O((ee==null?void 0:ee.message)||"Couldn't get rates.")}finally{T(!1)}},M=async()=>{var ee,ne,X,he,ae,je,$e;if(!(!j||!x)){T(!0),O(null);
890try{const J=await K.courier.book(e,{provider_slug:j.courier_slug,service_level_code:j.service_level_code,collection_address:x.collection_address,collection_contact:x.collection_contact,delivery_address:x.delivery_address,delivery_contact:x.delivery_contact,parcels:Z(),takealot_shipment_id:x.takealot_shipment_id?Number(x.takealot_shipment_id):void 0,removal_order_id:x.removal_order_id??(h?d[0]:void 0),removal_order_ids:h?(ee=x.removal_order_ids)!=null&&ee.length?x.removal_order_ids:d:void 0,removal_order_reference:x.removal_order_reference??i??void 0,removal_order_references:h?(ne=x.removal_order_references)!=null&&ne.length?x.removal_order_references:[x.removal_order_reference??i,...o??[]].filter(Boolean):void 0,lane:h||x.lane==="dc_return"?"dc_return":"inbound",destination_node:x.destination_node??void 0,expected_cost_zar:j.rate_incl_vat??void 0,idempotency_key:R});A({waybill:J.waybill??((X=J.booking)==null?void 0:X.tracking_reference),label_url:J.label_url??((he=J.booking)==null?void 0:he.label_url),booking_id:((ae=J.booking)==null?void 0:ae.id)??null}),m("done"),u==null||u(),!(J.label_url??((je=J.booking)==null?void 0:je.label_url))&&(($e=J.booking)!=null&&$e.id)&&K.courier.label(e,J.booking.id).then(Ne=>{Ne.label_url&&A(ve=>ve&&{...ve,label_url:Ne.label_url})}).catch(()=>{})}catch(J){O((J==null?void 0:J.message)||"Booking failed.")}finally{T(!1)}}},z=ee=>ee.price??ee.seller_price??null,G=y.map((ee,ne)=>({...ee,idx:ne})),te=[{key:"n",label:"#",className:"w-8",render:ee=>s.jsx("span",{className:"text-text-tertiary tabular-nums",children:ee.idx+1})},{key:"length",label:"Length (cm)",render:ee=>s.jsx(Re,{className:"tabular-nums",inputSize:"sm",value:ee.length,inputMode:"decimal",onChange:ne=>$(ee.idx,"length",ne.target.value),"aria-label":`Parcel ${ee.idx+1} length`})},{key:"width",label:"Width (cm)",render:ee=>s.jsx(Re,{className:"tabular-nums",inputSize:"sm",value:ee.width,inputMode:"decimal",onChange:ne=>$(ee.idx,"width",ne.target.value),"aria-label":`Parcel ${ee.idx+1} width`})},{key:"height",label:"Height (cm)",render:ee=>s.jsx(Re,{className:"tabular-nums",inputSize:"sm",value:ee.height,inputMode:"decimal",onChange:ne=>$(ee.idx,"height",ne.target.value),"aria-label":`Parcel ${ee.idx+1} height`})},{key:"weight",label:"Weight (kg)",render:ee=>s.jsx(Re,{className:"tabular-nums",inputSize:"sm",value:ee.weight,inputMode:"decimal",onChange:ne=>$(ee.idx,"weight",ne.target.value),"aria-label":`Parcel ${ee.idx+1} weight`})},{key:"remove",label:"",className:"w-8",align:"right",render:ee=>y.length>1?s.jsx(W,{type:"button",intent:"destructive",variant:"ghost",size:"sm",onClick:()=>F(ee.idx),"aria-label":`Remove parcel ${ee.idx+1}`,children:s.jsx(Bn,{className:"h-4 w-4"})}):null}],re=[...(x==null?void 0:x.removal_order_references)??[],x==null?void 0:x.removal_order_reference,...o??[],i].filter((ee,ne,X)=>!!ee&&X.indexOf(ee)===ne),L=h?null:n?`Takealot PO ${n}${x!=null&&x.destination_node?` · ${x.destination_node} DC`:""}`:"Inbound collection";return s.jsx(Cr,{open:l,onOpenChange:c,children:s.jsxs(mr,{side:"right",size:"xl",children:[s.jsxs(Er,{children:[s.jsx(xr,{children:h?"Book return collection":"Book courier collection"}),h?s.jsx(Mr,{asChild:!0,children:s.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-1.5 text-body-sm text-text-secondary",children:[re.length>0?re.map(ee=>s.jsx(_n,{tone:"brand",variant:"outline",children:ee},ee)):s.jsx("span",{children:"Removal order"}),x!=null&&x.destination_node?s.jsxs("span",{children:["· ",x.destination_node," DC"]}):null]})}):s.jsx(Mr,{children:L})]}),s.jsxs(pr,{className:"p-4 space-y-4",children:[S&&s.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-outline-error bg-surface-errorSubtle p-3 text-sm text-text-error",children:[s.jsx(yt,{className:"h-4 w-4 mt-0.5 shrink-0"}),s.jsx("div",{children:S})]}),f==="loading"&&s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Loading booking detailsâ¦"]}),f==="form"&&x&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsxs(V,{className:"p-4",children:[s.jsx(Dk,{children:h?"Collection · Takealot DC":"Collection · your warehouse"}),s.jsx("div",{className:"text-sm font-medium text-text-primary",children:(q=x.collection_address)==null?void 0:q.company}),s.jsx("div",{className:"text-sm text-text-secondary",children:YM(x.collection_address)})]}),s.jsxs(V,{className:"p-4",children:[s.jsx(Dk,{children:h?"Delivery · your warehouse":"Delivery · Takealot DC"}),s.jsx("div",{className:"text-sm font-medium text-text-primary",children:((me=x.delivery_address)==null?void 0:me.company)??(h?"Your warehouse":"Pick a destination")}),s.jsx("div",{className:"text-sm text-text-secondary",children:YM(x.delivery_address)})]})]}),h&&x.portal_note&&s.jsx(V,{variant:"sunken",className:"p-4 text-sm text-text-secondary",children:x.portal_note}),s.jsxs(V,{className:"p-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs(Dk,{className:"mb-0",children:["Parcels · ",y.length," · ",H?`${H} kg total`:"â"]}),x.weight_estimated&&s.jsx("span",{className:"text-xs font-medium text-text-warning",children:"Confirm dimensions & weight"})]}),s.jsx(dt,{rows:G,columns:te,getRowKey:ee=>ee.idx,persist:!1,paginate:!1}),s.jsxs(W,{type:"button",intent:"brand",variant:"link",size:"sm",className:"mt-2",onClick:P,children:[s.jsx(In,{className:"h-3.5 w-3.5"}),"Add another parcel"]})]})]}),f==="rates"&&v&&s.jsxs("div",{className:"space-y-2",children:[(_==="tcs"||(x==null?void 0:x.provider)==="tcs")&&s.jsx("div",{className:"text-xs text-text-secondary bg-surface-subtle border border-outline-faint rounded px-3 py-2",children:"Booking on this seller's Takealot Courier (TFS) account. Takealot invoices them â the Gadjet courier wallet is not charged."}),v.length===0&&s.jsx("div",{className:"text-sm text-text-secondary",children:"No couriers returned a rate for this lane."}),s.jsx(vv,{value:j?`${j.courier_slug}:${j.service_level_code}`:"",onValueChange:ee=>{const ne=v.find(X=>`${X.courier_slug}:${X.service_level_code}`===ee);ne&&N(ne)},children:v.map(ee=>{const ne=!ee.takealot_eligible,X=`${ee.courier_slug}:${ee.service_level_code}`,he=(j==null?void 0:j.courier_slug)===ee.courier_slug&&(j==null?void 0:j.service_level_code)===ee.service_level_code,ae=`courier-rate-${ee.courier_slug}-${ee.service_level_code}`;return s.jsx(V,{padding:"sm",className:B(ne&&"opacity-50",he&&"border-outline-brand ring-1 ring-outline-brand"),children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(b3,{id:ae,value:X,disabled:ne,className:"mt-1"}),s.jsxs(Fs,{htmlFor:ae,className:B("flex-1 min-w-0 font-normal",ne&&"curs
890or-not-allowed"),children:[s.jsxs("span",{className:"flex items-center justify-between gap-3",children:[s.jsxs("span",{className:"text-body-sm font-medium text-text-primary",children:[ee.courier_name," · ",ee.service_level_name??ee.service_level_code]}),s.jsx("span",{className:"tabular-nums text-body-sm font-semibold text-text-primary",children:Pk(z(ee))})]}),s.jsx("span",{className:"block text-body-sm text-text-secondary mt-0.5",children:ne?h?"Can't collect from Takealot":"Can't ship to Takealot":`${ee.service_type??""}${ee.collection_cutoff?` · cutoff ${ee.collection_cutoff.slice(0,5)}`:""}${ee.margin!=null?` · cost ${Pk(ee.rate_incl_vat)}`:""}`})]})]})},X)})})]}),f==="done"&&s.jsxs(V,{className:"p-6 text-center space-y-3",children:[s.jsx(Xt,{className:"h-8 w-8 mx-auto text-text-success"}),s.jsx("div",{className:"text-headline-sm text-text-primary",children:h?"Return collection booked":"Collection booked"}),(E==null?void 0:E.waybill)&&s.jsxs("div",{className:"text-sm text-text-secondary",children:["Waybill ",s.jsx("span",{className:"font-mono font-medium text-text-primary",children:E.waybill})]}),(E==null?void 0:E.label_url)&&s.jsx(W,{asChild:!0,variant:"link",children:s.jsx("a",{href:E.label_url,target:"_blank",rel:"noreferrer",children:"Download waybill (PDF)"})}),!(E!=null&&E.label_url)&&(E==null?void 0:E.booking_id)&&s.jsx(W,{type:"button",variant:"link",onClick:async()=>{try{const ee=await K.courier.label(e,E.booking_id,!0);ee.label_url&&(A(ne=>ne&&{...ne,label_url:ee.label_url}),window.open(ee.label_url,"_blank","noopener,noreferrer"))}catch(ee){O((ee==null?void 0:ee.message)||"Couldn't fetch the waybill.")}},children:"Fetch waybill"}),s.jsx("div",{className:"text-xs text-text-tertiary",children:h?`Linked to ${re.length?re.join(", "):"this removal order"} · charged to courier credit.`:`Linked to PO ${n??"â"} · charged to courier credit.`}),h&&s.jsx(V,{variant:"sunken",className:"p-3 text-sm text-text-secondary text-left",children:(x==null?void 0:x.portal_note)??(re.length>1?`Paste this one waybill on all ${re.length} removal orders in Takealot Seller Portal â Removal Orders so the DC prepares the stock.`:"Paste this waybill on Takealot Seller Portal â Removal Orders so the DC prepares the stock.")})]})]}),s.jsxs(ml,{children:[f==="form"&&s.jsxs(s.Fragment,{children:[s.jsx(W,{type:"button",intent:"neutral",variant:"outline",onClick:()=>c(!1),children:"Cancel"}),s.jsx(W,{type:"button",onClick:Y,disabled:C||!(x!=null&&x.delivery_address)||!D,children:C?"Getting ratesâ¦":"Get rates"})]}),f==="rates"&&s.jsxs(s.Fragment,{children:[s.jsx(W,{type:"button",intent:"neutral",variant:"outline",onClick:()=>m("form"),children:"Back"}),s.jsx(W,{type:"button",onClick:M,disabled:C||!j,children:C?"Bookingâ¦":`Book collection${j?` â ${Pk(z(j))}`:""}`})]}),(f==="done"||f==="loading")&&s.jsx(W,{type:"button",intent:"neutral",variant:"outline",onClick:()=>c(!1),children:"Close"})]})]})})}function Dk({children:e,className:t}){return s.jsx("div",{className:B("text-xs font-medium uppercase tracking-wider text-text-secondary mb-3",t),children:e})}function ZM(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?String(e):t.toLocaleString("en-ZA",{dateStyle:"medium",timeStyle:"short"})}function XM(e){return e?[e.company,e.street_address,e.city,e.code].filter(Boolean).join(", "):"â"}function zFe(e){const t=String(e||"").toLowerCase();return t?t==="delivered"?"success":t==="cancelled"||t==="failed"||t==="undeliverable"?"error":t.includes("exception")||t.includes("failed-attempt")||t==="on-hold"?"warning":t==="collected"||t.includes("transit")||t.includes("delivery")||t.includes("hub")||t==="manifested"?"info":"brand":"neutral"}function rq({slug:e,bookingId:t,open:n,onOpenChange:r}){const[a,i]=p.useState(null),[o,l]=p.useState([]),[c,u]=p.useState(null),[d,h]=p.useState(!1),[f,m]=p.useState(!1),x=p.useCallback(async _=>{var k;if(t){h(!0),u(null);try{const j=await K.courier.booking(e,t);i(j.booking),l(j.booking.tracking_events??[]);const N=j.booking.source==="booked";
890if(_&&N&&j.booking.tracking_reference)try{const E=await K.courier.refresh(e,t);i(E.booking),l(((k=E.tracking)==null?void 0:k.events)??E.booking.tracking_events??[])}catch(E){u((E==null?void 0:E.message)||"Couldn't refresh live tracking.")}}catch(j){u((j==null?void 0:j.message)||"Couldn't load this collection.")}finally{h(!1)}}},[e,t]);p.useEffect(()=>{!n||!t||(i(null),l([]),x(!0))},[n,t,x]);const g=async()=>{if(t){m(!0),u(null);try{const _=await K.courier.label(e,t,!0);_.booking&&i(_.booking),_.label_url&&window.open(_.label_url,"_blank","noopener,noreferrer")}catch(_){u((_==null?void 0:_.message)||"Couldn't fetch the waybill.")}finally{m(!1)}}},y=rf(a==null?void 0:a.status)??(a==null?void 0:a.status_label)??(a==null?void 0:a.status),b=(a==null?void 0:a.lane)==="dc_return",v=(a==null?void 0:a.source)==="booked",w=a?[a.tracking_reference,y,a.destination_node?`${a.destination_node} DC`:null].filter(Boolean).join(" · "):"Courier collection";return s.jsx(Cr,{open:n,onOpenChange:r,children:s.jsxs(mr,{side:"right",size:"lg",children:[s.jsxs(Er,{children:[s.jsx(xr,{children:b?"Return collection":"Courier collection"}),s.jsx(Mr,{children:w})]}),s.jsxs(pr,{className:"p-4 space-y-4",children:[c&&s.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-outline-error bg-surface-errorSubtle p-3 text-sm text-text-error",children:[s.jsx(yt,{className:"h-4 w-4 mt-0.5 shrink-0"}),s.jsx("div",{children:c})]}),!a&&!c&&s.jsx("div",{className:"flex items-center gap-2 text-sm text-text-secondary",children:d?s.jsxs(s.Fragment,{children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Loading trackingâ¦"]}):"No booking selected."}),a&&s.jsxs(s.Fragment,{children:[s.jsxs(V,{className:"p-4",children:[s.jsx(Mk,{children:"Summary"}),s.jsxs("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-3 text-sm",children:[s.jsx(vm,{label:"Waybill",value:a.tracking_reference??"â",mono:!0,emphasis:!0}),s.jsxs("div",{children:[s.jsx("dt",{className:"text-[10px] text-text-tertiary uppercase tracking-wider",children:"Status"}),s.jsx("dd",{className:"mt-1",children:s.jsx(_n,{tone:zFe(a.status),dot:!0,children:y??"â"})})]}),s.jsx(vm,{label:"Booked",value:ZM(a.created_at)||"â",muted:!a.created_at}),s.jsx(vm,{label:"Price",value:a.price!=null?`R${Number(a.price).toFixed(2)}`:"â",muted:a.price==null})]})]}),s.jsxs(V,{className:"p-4",children:[s.jsx(Mk,{children:"Lane"}),s.jsxs("dl",{className:"grid grid-cols-1 gap-y-3 text-sm",children:[s.jsx(vm,{label:"Collect",value:XM(a.collection_address)}),s.jsx(vm,{label:"Deliver",value:XM(a.delivery_address)})]})]}),b&&s.jsx(V,{variant:"sunken",className:"p-4 text-sm text-text-secondary",children:"Paste this waybill on Takealot Seller Portal â Removal Orders so the DC prepares the stock."}),s.jsxs(V,{className:"p-4",children:[s.jsx(Mk,{children:"Tracking"}),o.length===0?s.jsx("div",{className:"text-sm text-text-secondary",children:d?"Refreshingâ¦":"No tracking events yet â the courier updates after collection is assigned."}):s.jsx("ol",{className:"space-y-3",children:[...o].reverse().map((_,k)=>s.jsxs("li",{className:"border-l-2 border-outline-subtle pl-3",children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:rf(_.status)??_.message??_.status??"Update"}),s.jsx("div",{className:"text-xs text-text-secondary",children:[ZM(_.at),_.location,_.message].filter(Boolean).join(" · ")})]},`${_.at}-${_.status}-${k}`))})]})]})]}),s.jsxs(ml,{children:[s.jsx(W,{intent:"neutral",variant:"outline",onClick:()=>x(!0),disabled:d||!t||!v,children:d?"Refreshingâ¦":"Refresh"}),v&&s.jsx(W,{onClick:g,disabled:f||!t,children:f?"Fetchingâ¦":"Fetch waybill"})]})]})})}function Mk({children:e}){return s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary mb-3",children:e})}function vm({label:e,value:t,emphasis:n,muted:r,mono:a}){return s.jsxs("div",{children:[s.jsx("dt",{className:"text-[10px] text-text-tertiary uppercase tracking-wider",children:e}),s.jsx("dd",{className:B("font-medium mt-0.5 break-words",a&&"font-mono text-xs",n?"text-text-body font-semibold text-base":r?"text-text-secondary":"text-text-body"),children:t})]})}function WFe({slug:e,sellerName:t}){var k,j;
890const n=t||e,[r,a]=it("statdays","30"),i=Number(r)||30,[o,l]=p.useState(null),[c,u]=p.useState(!0),[d,h]=p.useState(null),[f,m]=p.useState(null);p.useEffect(()=>{let N=!1;return u(!0),h(null),K.returnStats(e,i).then(E=>!N&&(l(E),u(!1))).catch(E=>!N&&(h(String((E==null?void 0:E.message)??E)),u(!1))),()=>{N=!0}},[e,i]);const x=o==null?void 0:o.kpis,g=((k=o==null?void 0:o.reasons)==null?void 0:k.rows)??[],y=(o==null?void 0:o.top_skus)??[],b=p.useMemo(()=>{var N;return(((N=o==null?void 0:o.rate_trend)==null?void 0:N.points)??[]).map(E=>({label:E.day,rate:E.rate}))},[o]),v=p.useMemo(()=>{var N;return(((N=o==null?void 0:o.rate_trend)==null?void 0:N.points)??[]).map(E=>({label:E.day,units_returned:E.units_returned}))},[o]),w=(o==null?void 0:o.by_region)??[],_=((j=o==null?void 0:o.rate_trend)==null?void 0:j.avg_rate)??(x==null?void 0:x.return_rate)??null;return s.jsxs(jw,{days:i,onDays:N=>a(String(N)),loading:c,error:d,children:[s.jsx(Tn,{title:"Returns summary",subtitle:"Window totals",accent:Ue.purple,children:s.jsxs(dr,{cols:2,children:[s.jsx(Ye,{label:"Return rate",value:Yn(x==null?void 0:x.return_rate),tone:((x==null?void 0:x.return_rate)??0)>.05?"warn":"default"}),s.jsx(Ye,{label:"Units returned",value:de(x==null?void 0:x.units_returned)}),s.jsx(Ye,{label:"Units sold",value:de(x==null?void 0:x.units_sold)}),s.jsx(Ye,{label:"Return events",value:de(x==null?void 0:x.returns_count)})]})}),s.jsx(Tn,{title:"Return-rate trend",subtitle:_!=null?`Avg ${Yn(_)}`:void 0,accent:Ue.red,onClick:()=>m("rate"),children:s.jsx(Yo,{data:b,xKey:"label",series:[{key:"rate",label:"Return rate",color:Ue.red}],format:"percent",variant:"preview"})}),s.jsx(Tn,{title:"Units returned",subtitle:o!=null&&o.rate_trend?`${de(o.rate_trend.total_units_returned)} in window`:void 0,accent:Ue.violet,onClick:()=>m("units"),children:s.jsx(Yo,{data:v,xKey:"label",series:[{key:"units_returned",label:"Units returned",color:Ue.violet}],format:"number",variant:"preview"})}),s.jsx(Tn,{title:"Returns by region",subtitle:"Where returns cluster",accent:Ue.green,onClick:()=>m("region"),children:s.jsx(Ki,{data:w,labelKey:"region",valueKey:"units",format:"number",variant:"preview"})}),s.jsx(Tn,{title:"Why they come back",subtitle:"Return reasons",accent:Ue.amber,onClick:()=>m("reasons"),children:s.jsx(Ki,{data:g,labelKey:"reason",valueKey:"units",format:"number",variant:"preview"})}),s.jsx(Tn,{title:"Worst offenders",subtitle:"By units returned",accent:Ue.blue,onClick:()=>m("skus"),children:s.jsx(Gr,{data:y,labelKey:"sku",valueKey:"units_returned",color:Ue.blue,format:"number",variant:"preview",maxRows:5})}),s.jsx(br,{open:f==="rate",onClose:()=>m(null),slug:e,title:"Return-rate trend",subtitle:_!=null?`Average ${Yn(_)} over ${i} days`:void 0,accent:Ue.red,askPrompt:`Analyse ${n}'s return-rate trend over the last ${i} days. Is it rising, and which SKUs or reasons are driving it?`,children:s.jsx(Yo,{data:b,xKey:"label",series:[{key:"rate",label:"Return rate",color:Ue.red}],format:"percent",variant:"full"})}),s.jsx(br,{open:f==="units",onClose:()=>m(null),slug:e,title:"Units returned over time",subtitle:o!=null&&o.rate_trend?`${de(o.rate_trend.total_units_returned)} of ${de(o.rate_trend.total_units_sold)} sold`:void 0,accent:Ue.violet,askPrompt:`Look at ${n}'s units-returned trend over the last ${i} days. Is the volume rising, and does it track a specific SKU or reason?`,children:s.jsx(Yo,{data:v,xKey:"label",series:[{key:"units_returned",label:"Units returned",color:Ue.violet}],format:"number",variant:"full"})}),s.jsx(br,{open:f==="region",onClose:()=>m(null),slug:e,title:"Returns by region",accent:Ue.green,askPrompt:`Which regions drive ${n}'s returns over the last ${i} days? Does one DC's catchment stand out, and what might explain it?`,table:s.jsx(Ls,{rows:w,rowKey:N=>N.region,cols:[{header:"Region",render:N=>N.region},{header:"Events",align:"right",render:N=>de(N.return_count)},{header:"Units",align:"right",render:N=>de(N.units)}]}),children:s.jsx(Ki,{data:w,labelKey:"region",valueKey:"units",format:"number",variant:"full"})}),s.jsx(br,{open:f==="reasons",onClose:()=>m(null),slug:e,title:"Why items come back â return reasons",accent:Ue.amber,askPrompt:`Break down ${n}'s return reasons over the last ${i} days. Which are addressable through listing or packaging fixes?`,table:s.jsx(Ls,{rows:g,rowKey:N=>N.reason,cols:[{header:"Reason",render:N=>N.reason},{header:"Events",align:"right",render:N=>de(N.return_count)},{header:"Units",align:"right",render:N=>de(N.units)}]}),children:s.jsx(Ki,{data:g,labelKey:"reason",valueKey:"units",format:"number",variant:"full"})}),s.jsx(br,{open:f==="skus",onClose:()=>m(null),slug:e,title:"Worst offenders â most-returned SKUs",accent:Ue.blue,askPrompt:`Which of ${n}'s SKUs have the worst returns over the last ${i} days, and what's the likely cause for each?`,table:s.jsx(Ls,{rows:y,rowKey:N=>N.sku,cols:[{header:"SKU",render:N=>s.jsx("span",{className:"font-mono text-xs",children:N.sku})},{header:"Returned",align:"right",render:N=>de(N.units_returned)},{header:"Events",align:"right",render:N=>de(N.returns_count)},{header:"Top reason",render:N=>N.top_reason??"â"}]}),children:s.jsx(Gr,{data:y,labelKey:"sku",valueKey:"units_returned",color:Ue.blue,format:"number",variant:"full"})})]})}function KFe(e){const t=new Date,n=new Date(t.getTime()+86400*1e3);return{since:new Date(t.getTime()-e*86400*1e3).toISOString().slice(0,10),until:n.toISOString().slice(0,10)}}const HFe=[{label:"Last 30 days",days:30},{label:"Last 90 days",days:90},{label:"Last 180 days",days:180},{label:"Last 12 months",days:365}],JM=5e3;function wv(e){if(!e.original_order_date)return null;const t=new Date(e.original_order_date).getTime(),n=new Date(e.return_date).getTime();if(!isFinite(t)||!isFinite(n))return null;const r=n-t;return r<0?0:Math.round(r/864e5)}function _v(e){const t=e.sku_units_sold_in_window??0,n=e.sku_units_returned_in_window??0;return t<=0?null:n/t}function QM(e){const t=(e.return_reason??"").toLowerCase();if(/damag|broke|defect|faulty|not work|cracked|spoil|leak/.test(t))return"Quality / packaging";if(/not as described|wrong|different|mismatch|incorrect|misleading|misled/.test(t))return"Listing accuracy";if(/too (big|small|large)|size|fit|colou?r/.test(t))return"Sizing / variant clarity";if(/changed mind|no longer|unwanted|mistake|accident|duplicate/.test(t))return"Buyer's remorse";const n=_v(e),r=wv(e);return n!=null&&n>.2&&r!=null&&r<=7?"Expectation gap":null}const e$=[{key:"open",label:"Open",predicate:e=>e.primary_outcome==null||e.primary_outcome===""},{key:"high-rate",label:"High return rate (>20%)",predicate:e=>{const t=_v(e);return t!=null&&t>.2}}];function VFe(){const{slug:e=""}=jn(),[t,n]=it("tab","statistics"),[r,a]=p.useState(null),[i,o]=p.useState(null),[l]=it("range","90"),c=Number(l)||90,[u]=it("since",""),[d]=it("until",""),h=!!(u&&d),f=mc(),[m,x]=it("return",""),g=m?(i==null?void 0:i.find($=>String($.seller_return_id)===m))??null:null,[y,b]=p.useState(null),[v,w]=p.useState(null);p.useEffect(()=>{K.seller(e).then(a).catch(()=>{})},[e]),p.useEffect(()=>{o(null),b(null),K.returns(e,h?{since:u,until:d,limit:JM}:{days:c,limit:JM}).then(o).catch($=>b(String($)))},[e,c,u,d,h]);const _=Id(i,p.useCallback($=>[$.sku,$.order_id,$.return_reason],[]),{urlKey:"q"}),k=gd(_.filtered,p.useCallback($=>$.return_reason,[]),{urlKey:"reason"}),j=gd(k.filtered,p.useCallback($=>$.return_region,[]),{urlKey:"region"}),{activeChips:N,toggleChip:E,clearChips:A,filtered:C}=tu(j.filtered,e$),T=(C==null?void 0:C.reduce(($,P)=>$+P.quantity,0))??0,S=p.useMemo(()=>
890{if(!C)return null;let $=0,P=0,F=0;for(const Z of C){const D=wv(Z);D!=null&&($+=D,P+=1),(Z.primary_outcome==null||Z.primary_outcome==="")&&(F+=1)}return{count:C.length,units:T,avgTtr:P?$/P:null,open:F}},[C,T]),O=p.useMemo(()=>{if(!i)return null;const $=new Map;for(const P of i){const F=P.return_reason??"Unknown";$.set(F,($.get(F)??0)+P.quantity)}return[...$.entries()].map(([P,F])=>({reason:P,units:F})).sort((P,F)=>F.units-P.units).slice(0,6)},[i]),R=(i==null?void 0:i.reduce(($,P)=>$+P.quantity,0))??0;async function I($){try{const P=h?{since:u,until:d}:KFe(c),{blob:F,filename:Z,dataAsOf:D,dataLagHours:H}=await K.downloadExport(e,"returns",{format:$,since:P.since,until:P.until,search:_.q||void 0,reason:k.value||void 0,region:j.value||void 0});uc(F,Z),D&&H!=null&&H>24?w({asOf:D,lagHours:H}):w(null)}catch(P){b(String((P==null?void 0:P.message)||P))}}return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Sellers",to:"/"},{label:(r==null?void 0:r.display_name)??e,to:`/sellers/${e}`},{label:"Returns"}],actions:t==="list"?s.jsx(Kf,{onDownload:I,rowCount:C==null?void 0:C.length}):void 0}),s.jsx(As,{items:[{key:"statistics",label:"Statistics",icon:s.jsx(fc,{className:"w-3.5 h-3.5"}),active:t==="statistics",onClick:()=>n("statistics")},{key:"list",label:"Returns",icon:s.jsx(vd,{className:"w-3.5 h-3.5"}),active:t==="list",onClick:()=>n("list")},{key:"pickup",label:"Pickup ready",icon:s.jsx(qi,{className:"w-3.5 h-3.5"}),active:t==="pickup",onClick:()=>n("pickup")}]}),t==="statistics"?s.jsx(WFe,{slug:e,sellerName:(r==null?void 0:r.display_name)??void 0}):t==="pickup"?s.jsx(QFe,{slug:e}):s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full p-4 md:p-6 space-y-4",children:[S&&s.jsxs(dr,{children:[s.jsx(Ye,{label:"Returns",value:de(S.count)}),s.jsx(Ye,{label:"Units",value:de(S.units)}),s.jsx(Ye,{label:"Avg time to return",value:S.avgTtr==null?"â":`${Math.round(S.avgTtr)}d`}),s.jsx(Ye,{label:"Open",value:de(S.open),tone:S.open>0?"warn":void 0})]}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx(Sw,{value:{days:c,since:u,until:d},presets:HFe,onPreset:$=>f({range:$===90?"":String($),since:"",until:""}),onCustom:($,P)=>f({range:"",since:$,until:P})}),s.jsx(Ni,{value:_.q,onChange:_.setQ,placeholder:"Search by SKU, order #, or reasonâ¦",className:"flex-1 min-w-[220px]"}),s.jsx(nu,{value:k.value,onChange:k.setValue,options:k.options,allLabel:"All reasons"}),s.jsx(nu,{value:j.value,onChange:j.setValue,options:j.options,allLabel:"All regions"}),s.jsx(hu,{chips:e$,activeChips:N,onToggle:E,onClear:A}),i&&s.jsxs("div",{className:"text-xs text-text-secondary ml-auto",children:[de((C==null?void 0:C.length)??0)," returns ·"," ",de(T)," units"]})]}),v&&s.jsxs(V,{className:"p-3 text-xs text-text-warning bg-surface-warningSubtle border-outline-warning flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold",children:"Heads up â data may be stale."})," ","Returns were last synced ",s.jsx("span",{className:"font-mono",children:cn(v.asOf)})," ","(",Math.round(v.lagHours),"h ago). Re-sync before relying on this for finance."]}),s.jsx("button",{onClick:()=>w(null),className:"text-text-warning underline underline-offset-2 shrink-0",children:"Dismiss"})]}),y&&s.jsx(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:y}),O&&O.length>0&&s.jsxs(V,{className:"p-5",children:[s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary mb-3",children:"Top reasons"}),s.jsx("div",{className:"space-y-2",children:O.map($=>{const P=R?$.units/R*100:0;return s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{type:"button",onClick:()=>k.setValue(k.value===$.reason?"":$.reason),className:B("text-sm text-left w-56 truncate hover:text-text-primary transition",k.value===$.reason?"text-text-primary font-medium":"text-text-body"),children:$.reason}),s.jsx(Nf,{className:"min-w-0 flex-1",value:P,valueLabel:`${de($.units)} (${P.toFixed(0)}%)`})]},$.reason)})})]}),s.jsx(V,{className:"overflow-hidden",children:s.jsx(dt,{rows:C,columns:YFe(e),getRowKey:$=>$.seller_return_id,defaultSort:{key:"date",direction:"desc"},empty:{title:"No returns match.",icon:vd},onRowClick:$=>x(String($.seller_return_id))})})]})}),s.jsx(BFe,{slug:e,ret:g,open:!!m,onClose:()=>x("")})]})}function qFe({days:e}){if(e==null)return s.jsx("span",{className:"text-text-tertiary",title:"Couldn't match this return to its original sale",children:"â"});const t=e===0,n=e<=2,r=e>30;return s.jsxs("span",{className:t?"font-medium text-text-error":n?"text-text-warning":r?"text-text-tertiary":"text-text-secondary",title:t?"Returned the same day â likely damaged-on-arrival":r?"Returned weeks after delivery â likely buyer's regret":void 0,children:[e,"d"]})}function GFe({rate:e,sold:t,returned:n}){if(e==null)return s.jsx("span",{className:"text-text-tertiary",title:"No sales in this window for this SKU â can't compute a rate",children:"â"});const r=e*100,a=r>15;return s.jsxs("span",{className:a?"font-medium text-text-error":"text-text-secondary",title:`${n} returned of ${t} sold in this window`,children:[r.toFixed(r>=10?0:1),"%"]})}function YFe(e){return[{key:"date",label:"Date",sortable:!0,sticky:!0,getValue:t=>t.return_date,render:t=>s.jsx("span",{className:"whitespace-nowrap text-text-secondary",children:cn(t.return_date)})},{key:"order",label:"Order #",sortable:!0,getValue:t=>t.order_id,render:t=>s.jsx("span",{className:"tabular-nums text-text-secondary",children:t.order_id?`#${t.order_id}`:"â"})},{key:"sku",label:"Product",sortable:!0,getValue:t=>t.sku,className:"max-w-[280px]",render:t=>t.title||t.sku?s.jsxs(st,{to:`/sellers/${e}/inventory?q=${encodeURIComponent(t.sku??t.title??"")}`,onClick:n=>n.stopPropagation(),className:"block hover:underline",children:[s.jsx("div",{className:"truncate text-xs text-text-primary",title:t.title??t.sku??"",children:t.title??t.sku}),t.title&&t.sku?s.jsx("div",{className:"truncate font-mono text-[11px] text-text-tertiary",children:t.sku}):null]}):s.jsx("span",{className:"text-text-secondary",children:"â"})},{key:"reason",label:"Reason",sortable:!0,getValue:t=>t.return_reason,className:"max-w-[260px]",render:t=>s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"block truncate text-text-body",children:t.return_reason??"â"}),QM(t)?s.jsxs("span",{className:"mt-0.5 block text-body-xs text-text-tertiary",children:["likely: ",QM(t)]}):null]})},{key:"qty",label:"Qty",sortable:!0,align:"right",getValue:t=>t.quantity,format:"number"},{key:"ttr",label:"TTR",sortable:!0,align:"right",getValue:t=>wv(t),render:t=>s.jsx(qFe,{days:wv(t)})},{key:"rate",label:"Return rate",sortable:!0,align:"right",getValue:t=>_v(t),render:t=>s.jsx(GFe,{rate:_v(t),sold:t.sku_units_sold_in_window??0,returned:t.sku_units_returned_in_window??0})}
890,{key:"region",label:"Region",sortable:!0,getValue:t=>t.return_region,render:t=>s.jsx("span",{className:"text-text-secondary",children:t.return_region??"â"})},{key:"outcome",label:"Primary outcome",sortable:!0,getValue:t=>t.primary_outcome,render:t=>s.jsx("span",{className:"text-xs text-text-secondary",children:t.primary_outcome??"â"})}]}function $k(e){return(e||[]).filter(t=>t.sku).map(t=>`${t.sku}${t.qty?` à ${t.qty}`:""}`).join(", ")}function sd(e){return String(e.warehouse_code||e.warehouse_region||"").trim()||null}function sp(e){return e.stage==="pickup_ready"&&!e.courier_booking_id&&!e.courier_tracking_reference}function ZFe(e){const t=n=>e.reduce((r,a)=>r+(Number(n(a))||0),0);return{ros:e.length,units:t(n=>n.units),fees_rand:Number(t(n=>n.fee_rand).toFixed(2)),urgent_count:e.filter(n=>n.urgent).length,expiring_within_7d:e.filter(n=>(n.days_until_expiry??99)<=7).length}}function XFe(e,t){const n=[...e.pickup_ready,...e.ignored??[]],r=new Set,a=[];for(const l of n)r.has(l.removal_order_id)||(r.add(l.removal_order_id),a.push(l));const i=a.filter(l=>!t.has(l.removal_order_id)),o=a.filter(l=>t.has(l.removal_order_id));return i.sort((l,c)=>l.urgent!==c.urgent?l.urgent?-1:1:(l.days_until_expiry??999)-(c.days_until_expiry??999)),{...e,pickup_ready:i,ignored:o,ignored_count:o.length,totals:{...e.totals,pickup_ready:ZFe(i)}}}function JFe(e){const t=Array.isArray(e.removal_order_ids)?e.removal_order_ids.map(Number):[];return e.removal_order_id!=null&&t.push(Number(e.removal_order_id)),[...new Set(t.filter(Number.isFinite))]}function QFe({slug:e}){var Z,D;const[t,n]=p.useState(null),[r,a]=p.useState([]),[i,o]=p.useState(null),[l,c]=p.useState(null),[u,d]=p.useState(null),[h,f]=p.useState(()=>new Set),[m,x]=p.useState(!1),[g,y]=p.useState(!1),b=p.useCallback(()=>{o(null),K.pickupReady(e).then(n).catch(H=>o(String((H==null?void 0:H.message)||H))),K.courier.bookings(e,{lane:"dc_return",limit:30}).then(H=>a(H.bookings??[])).catch(()=>a([]))},[e]);p.useEffect(()=>{n(null),f(new Set),b()},[b]);const v=(t==null?void 0:t.pickup_ready)??[],w=(t==null?void 0:t.submitted)??[],_=(t==null?void 0:t.ignored)??[],k=t==null?void 0:t.totals,j=(H,Y)=>{n(M=>{if(!M)return M;const z=new Set((M.ignored??[]).map(G=>G.removal_order_id));for(const G of H)Y?z.add(G):z.delete(G);return XFe(M,z)}),f(M=>{const z=new Set(M);for(const G of H)z.delete(G);return z})},N=async H=>{const Y=H.map(M=>M.removal_order_id);if(!(!Y.length||m)){x(!0),o(null);try{await K.ignorePickupReady(e,Y),j(Y,!0),y(!0)}catch(M){o(String((M==null?void 0:M.message)||M))}finally{x(!1)}}},E=async H=>{const Y=H.map(M=>M.removal_order_id);if(!(!Y.length||m)){x(!0),o(null);try{await K.unignorePickupReady(e,Y),j(Y,!1)}catch(M){o(String((M==null?void 0:M.message)||M))}finally{x(!1)}}},A=new Set([...v,...w].map(H=>Number(H.removal_order_id)).filter(Number.isFinite)),C=r.filter(H=>{if(!H.tracking_reference)return!1;const Y=JFe(H);return Y.length?Y.every(M=>!A.has(M)):!0}),T=v.filter(H=>h.has(H.removal_order_id)),S=T.length?sd(T[0]):null,O=v.filter(H=>sp(H)&&(!S||sd(H)===S)),R=O.length>0&&O.every(H=>h.has(H.removal_order_id)),I=O.some(H=>h.has(H.removal_order_id)),$=H=>sp(H)&&(!S||sd(H)===S),P=H=>{!$(H)&&!h.has(H.removal_order_id)||f(Y=>{const M=new Set(Y);return M.has(H.removal_order_id)?M.delete(H.removal_order_id):M.add(H.removal_order_id),M})},F=()=>{S&&f(H=>{const Y=new Set(H);if(R)for(const M of O)Y.delete(M.removal_order_id);else for(const M of O)Y.add(M.removal_order_id);return Y})};return s.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:[s.jsxs("div",{className:"w-full p-4 md:p-6 space-y-4",children:[k&&s.jsxs(dr,{children:[s.jsx(Ye,{label:"Pickup ready",value:de(k.pickup_ready.ros)}),s.jsx(Ye,{label:"Units waiting",value:de(k.pickup_ready.units)}),s.jsx(Ye,{label:"Expiring â¤7 days",value:de(k.pickup_ready.expiring_within_7d),tone:k.pickup_ready.expiring_within_7d>0?"warn":void 0}),s.jsx(Ye,{label:"Submitted",value:de(k.submitted.ros)})]}),s.jsx(V,{className:"p-4 text-sm text-text-secondary",children:"Book Gadjet's courier to collect customer returns from the Takealot DC and deliver them to your warehouse. After booking, paste the waybill on Takealot Seller Portal â Removal Orders so the DC prepares the stock. Same-DC removal orders can share one waybill. Ignore a row if you're not collecting it â restore anytime."}),i&&s.jsx(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:i}),!t&&!i&&s.jsx(V,{className:"p-4 text-sm text-text-secondary",children:"Loading pickup-ready removal ordersâ¦"}),t&&v.length===0&&w.length===0&&_.length===0&&s.jsx(V,{className:"p-6 text-sm text-text-secondary",children:"Nothing at the DC waiting for you â no pickup-ready or submitted removal orders."}),v.length>0&&s.jsxs(V,{className:"overflow-hidden",children:[s.jsx("div",{className:"px-4 pt-4 pb-2 text-sm font-semibold text-text-primary",children:"Pickup ready â book this week"}),h.size>0&&s.jsxs("div",{className:"border-b border-outline-subtle bg-surface-brandSubtle/50 px-3 py-2 flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-xs font-semibold text-text-primary whitespace-nowrap",children:[h.size," selected",S?` · ${S}`:""]}),s.jsx(W,{type:"button",size:"sm",onClick:()=>c(T),children:"Book collection"}),s.jsx(W,{type:"button",size:"sm",intent:"neutral",variant:"ghost",disabled:m,onClick:()=>N(T),children:"Ignore"}),s.jsx(W,{type:"button",size:"sm",intent:"neutral",variant:"ghost",onClick:()=>f(new Set),children:"Clear"})]}),s.jsx(dt,{rows:v,columns:Lk({onBook:H=>c([H]),onIgnore:H=>N([H]),onTrack:H=>d(H),selectedIds:h,lockedDc:S,onToggle:P,onToggleEligible:F,allEligibleSelected:R,someEligibleSelected:I,canSelect:$,busy:m}),getRowKey:H=>String(H.removal_order_id),persist:!1,empty:{title:"No pickup-ready removal orders.",icon:qi},rowClassName:H=>{if(h.has(H.removal_order_id))return"bg-surface-brandSubtle/50";if(S&&sp(H)&&sd(H)!==S)return"opacity-50"}})]}),_.length>0&&s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 px-4 pt-4 pb-2 text-sm font-semibold text-text-primary",onClick:()=>y(H=>!H),"aria-expanded":g,children:[g?s.jsx(Pn,{className:"h-4 w-4"}):s.jsx(fr,{className:"h-4 w-4"}),"Ignored â ",_.length," not booking"]}),g&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"px-4 pb-2 flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:"text-xs text-text-secondary",children:"Hidden from this list and from the weekly digest. Still at the DC until Takealot closes the removal order."}),s.jsx(W,{type:"button",size:"sm",intent:"neutral",variant:"ghost",disabled:m,onClick:()=>E(_),className:"ml-auto",children:"Restore all"})]}),s.jsx(dt,{rows:_,columns:Lk({onBook:null,onRestore:H=>E([H]),onTrack:H=>d(H),busy:m}),getRowKey:H=>String(H.removal_order_id),persist:!1,empty:{title:"No ignored removal orders.",icon:qi}})]})]}),w.length>0&&s.jsxs(V,{className:"overflow-hidden",children:[s.jsx("div",{className:"px-4 pt-4 pb-2 text-sm font-semibold text-text-primary",children:"Submitted â awaiting collection"}),s.jsx(dt,{rows:w,columns:Lk({onBook:null,onTrack:H=>d(H)}),getRowKey:H=>String(H.removal_order_id),persist:!1})]}),C.length>0&&s.jsxs(V,{className:"overflow-hidden",children:[s.jsx("div",{className:"px-4 pt-4 pb-2 text-sm font-semibold text-text-primary",children:"Gadjet collections â in transit or recently booked"}),s.jsx(dt,{rows:C,columns:eBe(H=>d(H)),getRowKey:H=>String(H.id),persist:!1})]})]}),s.jsx(nq,{slug:e,removalOrderId:((Z=l==null?void 0:l[0])==null?void 0:Z.removal_order_id)??null,removalOrderIds:(l==null?void 0:l.map(H=>H.removal_order_id))??null,removalOrderRef:((D=l==null?void 0:l[0])==null?void 0:D.reference)??null,removalOrderRef
890s:(l==null?void 0:l.map(H=>H.reference).filter(H=>!!H))??null,open:!!(l!=null&&l.length),onOpenChange:H=>{H||(c(null),f(new Set))},onBooked:b}),s.jsx(rq,{slug:e,bookingId:u,open:u!=null,onOpenChange:H=>!H&&d(null)})]})}function Lk({onBook:e,onIgnore:t,onRestore:n,onTrack:r,selectedIds:a,lockedDc:i,onToggle:o,onToggleEligible:l,allEligibleSelected:c,someEligibleSelected:u,canSelect:d,busy:h}){const f=!!(e&&a&&o),m=[];return f&&m.push({key:"select",label:"",sticky:!0,stopRowClick:!0,className:"w-10",headerPrefix:s.jsx("span",{title:i?`Select all ${i} rows`:"Tick a row to lock the DC",children:s.jsx(ei,{checked:c?!0:u?"indeterminate":!1,disabled:!i,onCheckedChange:()=>l==null?void 0:l(),"aria-label":i?`Select all at ${i}`:"Select all at this DC"})}),render:x=>{const g=(d==null?void 0:d(x))??!1,y=a.has(x.removal_order_id),b=!!(i&&sp(x)&&sd(x)!==i);return s.jsx("span",{title:b?`This collection is at ${sd(x)} â pick ${i} rows only, or clear and start with ${sd(x)}.`:void 0,children:s.jsx(ei,{checked:y,disabled:!g&&!y,onCheckedChange:()=>o(x),"aria-label":`Select ${x.reference??x.removal_order_id}`})})}}),m.push({key:"reference",label:"RO ref",sortable:!0,sticky:!0,stickyLeft:f?"left-10":void 0,getValue:x=>x.reference,render:x=>s.jsx("span",{className:"font-mono text-xs text-text-primary",children:x.reference??`#${x.removal_order_id}`})},{key:"type",label:"Type",sortable:!0,getValue:x=>x.order_type,render:x=>s.jsx("span",{className:"text-text-secondary",children:x.order_type??"â"})},{key:"dc",label:"DC",sortable:!0,getValue:x=>x.warehouse_code??x.warehouse_region,render:x=>s.jsx("span",{className:"text-text-secondary",children:x.warehouse_code??x.warehouse_region??"â"})},{key:"units",label:"Units",sortable:!0,align:"right",format:"number",getValue:x=>x.units},{key:"days",label:"Days to expiry",sortable:!0,align:"right",getValue:x=>x.days_until_expiry,render:x=>{const g=x.days_until_expiry;return g==null?s.jsx("span",{className:"text-text-tertiary",children:"â"}
890):s.jsxs("span",{className:g<=7?"font-medium text-text-warning":"text-text-secondary",children:[g,"d",x.urgent?" · urgent":""]})}},{key:"skus",label:"SKUs",className:"max-w-[280px]",getValue:x=>$k(x.skus),render:x=>s.jsx("span",{className:"block truncate text-xs text-text-secondary",title:$k(x.skus),children:$k(x.skus)||"â"})},{key:"courier",label:"Courier",stopRowClick:!0,getValue:x=>x.courier_tracking_reference??x.courier_status,render:x=>x.courier_tracking_reference?s.jsx("button",{type:"button",onClick:g=>{g.stopPropagation(),x.courier_booking_id&&r&&r(x.courier_booking_id)},className:"inline-flex items-center gap-1 rounded border border-outline-subtle bg-surface-subtle px-1.5 py-0.5 text-body-xs font-medium text-text-secondary hover:border-outline-brand hover:text-text-brand",title:rf(x.courier_status)??x.courier_status??"Track collection",children:x.courier_tracking_reference}):n?s.jsx("button",{type:"button",disabled:h,onClick:g=>{g.stopPropagation(),n(x)},className:"text-body-xs font-medium text-text-brand hover:underline disabled:opacity-50",children:"Restore"}):!e||x.stage!=="pickup_ready"?s.jsx("span",{className:"text-text-tertiary",children:"â"}):s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:g=>{g.stopPropagation(),e(x)},className:"text-body-xs font-medium text-text-brand hover:underline",children:"Book"}),t&&sp(x)&&s.jsx("button",{type:"button",disabled:h,onClick:g=>{g.stopPropagation(),t(x)},className:"text-body-xs font-medium text-text-secondary hover:underline disabled:opacity-50",children:"Ignore"})]})}),m}function eBe(e){return[{key:"waybill",label:"Waybill",getValue:t=>t.tracking_reference,render:t=>s.jsx("button",{type:"button",onClick:()=>e(t.id),className:"font-mono text-xs text-text-brand hover:underline",children:t.tracking_reference??`#${t.id}`})},{key:"status",label:"Status",getValue:t=>t.status,render:t=>s.jsx("span",{className:"text-text-secondary",children:rf(t.status)??t.status??"â"})},{key:"dc",label:"DC",getValue:t=>t.destination_node,render:t=>s.jsx("span",{className:"text-text-secondary",children:t.destination_node??"â"})},{key:"created_at",label:"Booked",getValue:t=>t.created_at,render:t=>s.jsx("span",{className:"text-text-secondary",children:t.created_at?cn(t.created_at):"â"})}]}const tBe=/cancel/i;function Fk(e){return tBe.test(e.sale_status??"")}function nBe({slug:e,orderId:t,rows:n,open:r,onClose:a}){const i=t==null?null:String(t),o=i==null?[]:(n??[]).filter(x=>String(x.order_id)===i),l=o[0],c=o.filter(x=>!Fk(x)),u=o.filter(Fk),d=c.reduce((x,g)=>x+(g.selling_price??0),0),h=c.reduce((x,g)=>x+(g.total_fees??0),0),f=c.reduce((x,g)=>x+(g.quantity??0),0),m=d-h;return s.jsx(Cr,{open:r,onOpenChange:x=>{x||a()},children:s.jsxs(mr,{side:"right",size:"lg",children:[s.jsxs(Er,{children:[s.jsxs(xr,{children:["Order #",t??"â"]}),s.jsx(Mr,{children:l?`${cn(l.order_date)} · ${l.sales_region??"Region unknown"}`:"Order detail"})]}),s.jsx(pr,{className:"p-4 space-y-4",children:l?s.jsxs(s.Fragment,{children:[s.jsxs(V,{className:"p-4",children:[s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary mb-3",children:"Order summary"}),s.jsxs("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-3 text-sm",children:[s.jsx(wm,{label:"Line items",value:`${de(c.length)}${u.length>0?` (+${u.length} cancelled)`:""}`}),s.jsx(wm,{label:"Units",value:de(f)}),s.jsx(wm,{label:"Gross",value:ge(d)}),s.jsx(wm,{label:"Total fees",value:ge(h),muted:!0}),s.jsx(wm,{label:"Net to seller",value:ge(m),emphasis:!0})]})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-4 py-2 border-b border-outline-faint text-xs font-medium uppercase tracking-wider text-text-secondary flex items-center justify-between",children:[s.jsx("span",{children:"Line items"}),s.jsxs("span",{className:"text-text-tertiary normal-case tracking-normal font-normal",children:[o.length," on this order"]})]}),s.jsx("ul",{className:"divide-y divide-outline-faint",children:o.map(x=>{const g=Fk(x);return s.jsxs("li",{className:B("p-3 flex items-start justify-between gap-3",g&&"bg-surface-errorSubtle/40"),children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[x.title||x.sku?s.jsxs(st,{to:`/sellers/${e}/inventory?q=${encodeURIComponent(x.sku??x.title??"")}`,className:"block hover:underline",children:[s.jsx("div",{className:"text-xs text-text-primary truncate",title:x.title??x.sku??"",children:x.title??x.sku}),x.title&&x.sku?s.jsx("div",{className:"font-mono text-[11px] text-text-tertiary truncate",children:x.sku}):null]}):s.jsx("span",{className:"text-text-tertiary text-xs",children:"â"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-1",children:[s.jsx("span",{className:B("uppercase tracking-wider",g?"text-text-error font-medium":"text-text-secondary"),children:x.sale_status??"â"}),s.jsx("span",{className:"mx-1.5 text-text-tertiary",children:"·"}),"Qty ",x.quantity]})]}),s.jsxs("div",{className:"text-right tabular-nums shrink-0",children:[s.jsx("div",{className:B("font-semibold",g?"text-text-tertiary line-through":"text-text-body"),children:ge(x.selling_price)}),s.jsxs("div",{className:"text-xs text-text-secondary",children:[ge(x.total_fees)," fees"]})]})]},x.order_item_id)})})]}),s.jsxs(V,{className:"p-4",children:[s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary mb-3",children:"Trace this order"}),s.jsxs("div",{className:"space-y-2 text-sm",children:[s.jsxs(st,{to:`/sellers/${e}/transactions?q=${t}`,className:"flex items-center gap-2 text-text-brand hover:underline",children:[s.jsx(os,{className:"w-3.5 h-3.5"}),"Find in Transactions ledger"]}),s.jsxs(st,{to:`/sellers/${e}/returns?q=${t}`,className:"flex items-center gap-2 text-text-brand hover:underline",children:[s.jsx(os,{className:"w-3.5 h-3.5"}),"Find in Returns"]})]})]})]}):s.jsx("div",{className:"text-sm text-text-tertiary",children:"This order isn't in the current view. Adjust the date range or clear the filters to find it."})})]})})}function wm({label:e,value:t,emphasis:n,muted:r}){return s.jsxs("div",{children:[s.jsx("dt",{className:"text-[10px] text-text-tertiary uppercase tracking-wider",children:e}),s.jsx("dd",{className:B("font-medium tabular-nums mt-0.5",n?"text-text-body font-semibold text-base":r?"text-text-secondary":"text-text-body"),children:t})]})}function rBe({slug:e,sellerName:t}
890){const n=t||e,[r,a]=it("statdays","30"),i=Number(r)||30,[o,l]=p.useState(null),[c,u]=p.useState(!0),[d,h]=p.useState(null),[f,m]=p.useState(null);p.useEffect(()=>{let N=!1;return u(!0),h(null),K.salesStats(e,i).then(E=>!N&&(l(E),u(!1))).catch(E=>!N&&(h(String((E==null?void 0:E.message)??E)),u(!1))),()=>{N=!0}},[e,i]);const x=p.useMemo(()=>{const N=o==null?void 0:o.trend;return N?N.current.map((E,A)=>{var C,T;return{label:E.day,current:E.gmv,prior:((C=N.prior[A])==null?void 0:C.gmv)??0,units:E.units,units_prior:((T=N.prior[A])==null?void 0:T.units)??0,aov:E.orders>0?E.gmv/E.orders:0}}):[]},[o]),g=o==null?void 0:o.trend,y=o==null?void 0:o.sku_pareto,b=p.useMemo(()=>((y==null?void 0:y.rows)??[]).map(N=>({label:N.sku,revenue:N.revenue,cumulative_pct:N.cumulative_pct})),[y]),v=(o==null?void 0:o.by_region)??[],w=(o==null?void 0:o.by_dow)??[],_=(o==null?void 0:o.top_skus)??[],k=o==null?void 0:o.cancellations,j=g&&g.prior_total>0?(g.current_total-g.prior_total)/g.prior_total*100:null;return s.jsxs(jw,{days:i,onDays:N=>a(String(N)),loading:c,error:d,children:[s.jsx(Tn,{title:"Revenue",accent:Ue.purple,subtitle:g?s.jsxs("span",{children:[ge(g.current_total,{compact:!0}),j!=null&&s.jsxs("span",{className:j>=0?"text-text-success":"text-text-error",children:[" ",j>=0?"+":"",j.toFixed(1),"% vs prior"]})]}):void 0,onClick:()=>m("revenue"),children:s.jsx(Yo,{data:x,xKey:"label",series:[{key:"current",label:"Revenue",color:Ue.purple}],format:"zar",variant:"preview"})}),s.jsx(Tn,{title:"Revenue concentration (80/20)",subtitle:y&&y.sku_count>0?`${de(y.skus_to_80)} of ${de(y.sku_count)} SKUs (${Yn(y.pct_of_skus_to_80)}) make 80% of revenue`:"How concentrated revenue is across SKUs",accent:Ue.purple,wide:!0,onClick:()=>m("pareto"),children:s.jsx(bv,{data:b,xKey:"label",bars:[{key:"revenue",label:"Revenue",color:Ue.purple}],lines:[{key:"cumulative_pct",label:"Cumulative %",color:Ue.amber,axis:"right"}],leftFormat:"zarCompact",rightFormat:"percent",variant:"preview",height:170,referenceRight:{y:.8,label:"80%"}})}),s.jsx(Tn,{title:"Units sold",subtitle:g?`${de(g.current.reduce((N,E)=>N+E.units,0))} in window`:void 0,accent:Ue.blue,onClick:()=>m("units"),children:s.jsx(Yo,{data:x,xKey:"label",series:[{key:"units",label:"Units",color:Ue.blue}],format:"number",variant:"preview"})}),s.jsx(Tn,{title:"Average order value",subtitle:g&&g.current.reduce((N,E)=>N+E.orders,0)>0?ge(g.current_total/g.current.reduce((N,E)=>N+E.orders,0),{compact:!0}):void 0,accent:Ue.teal,onClick:()=>m("aov"),children:s.jsx(Yo,{data:x,xKey:"label",series:[{key:"aov",label:"AOV",color:Ue.teal}],format:"zar",variant:"preview"})}),s.jsx(Tn,{title:"Top SKUs",subtitle:"By units sold",accent:Ue.blue,onClick:()=>m("skus"),children:s.jsx(Gr,{data:_,labelKey:"sku",valueKey:"units",color:Ue.blue,format:"number",variant:"preview",maxRows:5})}),s.jsx(Tn,{title:"Sales by region",subtitle:"Share of revenue",accent:Ue.green,onClick:()=>m("region"),children:s.jsx(Ki,{data:v,labelKey:"region",valueKey:"gmv",format:"zarCompact",variant:"preview"})}),s.jsx(Tn,{title:"Day-of-week pattern",subtitle:"Revenue by weekday",accent:Ue.violet,onClick:()=>m("dow"),children:s.jsx(Gr,{data:w,labelKey:"dow_label",valueKey:"gmv",color:Ue.violet,format:"zarCompact",variant:"preview"})}),s.jsx(Tn,{title:"Order quality",subtitle:"Cancellations in window",accent:Ue.amber,children:s.jsxs(dr,{cols:2,children:[s.jsx(Ye,{label:"Cancellation rate",value:Yn(k==null?void 0:k.cancellation_rate),tone:((k==null?void 0:k.cancellation_rate)??0)>.05?"warn":"default"}),s.jsx(Ye,{label:"Orders cancelled",value:de(k==null?void 0:k.orders_cancelled)}),s.jsx(Ye,{label:"Units cancelled",value:de(k==null?void 0:k.units_cancelled)}),s.jsx(Ye,{label:"Revenue lost",value:ge(k==null?void 0:k.gmv_cancelled,{compact:!0})})]})}),s.jsx(br,{open:f==="revenue",onClose:()=>
890m(null),slug:e,title:"Revenue â this period vs prior",subtitle:g?`${ge(g.current_total)} vs ${ge(g.prior_total)} prior ${i} days`:void 0,accent:Ue.purple,askPrompt:`Analyse ${n}'s revenue trend over the last ${i} days vs the prior period. What's driving the change and what should I do about it?`,children:s.jsx(Yo,{data:x,xKey:"label",series:[{key:"current",label:"This period",color:Ue.purple},{key:"prior",label:"Prior period",color:Ue.slate,comparison:!0}],format:"zar",variant:"full"})}),s.jsx(br,{open:f==="pareto",onClose:()=>m(null),slug:e,title:"Revenue concentration â the 80/20 of SKUs",subtitle:y&&y.sku_count>0?`${de(y.skus_to_80)} of ${de(y.sku_count)} SKUs drive 80% of revenue`:void 0,accent:Ue.purple,askPrompt:`Look at ${n}'s revenue concentration over the last ${i} days. Which SKUs are the vital few I must protect, and which long-tail SKUs could I cull?`,table:s.jsx(Ls,{rows:(y==null?void 0:y.rows)??[],rowKey:N=>N.sku,cols:[{header:"Product",render:N=>s.jsx(rp,{title:N.title,sku:N.sku})},{header:"Revenue",align:"right",render:N=>ge(N.revenue)},{header:"Units",align:"right",render:N=>de(N.units)},{header:"Cumulative",align:"right",render:N=>Yn(N.cumulative_pct)}]}),children:s.jsx(bv,{data:b,xKey:"label",bars:[{key:"revenue",label:"Revenue",color:Ue.purple}],lines:[{key:"cumulative_pct",label:"Cumulative %",color:Ue.amber,axis:"right"}],leftFormat:"zar",rightFormat:"percent",variant:"full",referenceRight:{y:.8,label:"80%"}})}),s.jsx(br,{open:f==="units",onClose:()=>m(null),slug:e,title:"Units sold â this period vs prior",accent:Ue.blue,askPrompt:`Analyse ${n}'s unit-sales momentum over the last ${i} days vs the prior period. Is growth coming from volume or price?`,children:s.jsx(Yo,{data:x,xKey:"label",series:[{key:"units",label:"This period",color:Ue.blue},{key:"units_prior",label:"Prior period",color:Ue.slate,comparison:!0}],format:"number",variant:"full"})}),s.jsx(br,{open:f==="aov",onClose:()=>m(null),slug:e,title:"Average order value",accent:Ue.teal,askPrompt:`How has ${n}'s average order value moved over the last ${i} days, and what would lift it â bundling, cross-sell, or price?`,children:s.jsx(Yo,{data:x,xKey:"label",series:[{key:"aov",label:"Avg order value",color:Ue.teal}],format:"zar",variant:"full"})}),s.jsx(br,{open:f==="skus",onClose:()=>m(null),slug:e,title:"Top SKUs by units sold",accent:Ue.blue,askPrompt:`Which of ${n}'s top SKUs over the last ${i} days should I focus on, and why?`,table:s.jsx(Ls,{rows:_,rowKey:N=>N.sku,cols:[{header:"Product",render:N=>s.jsx(rp,{title:N.title,sku:N.sku})},{header:"Units",align:"right",render:N=>de(N.units)},{header:"Orders",align:"right",render:N=>de(N.orders)},{header:"Revenue",align:"right",render:N=>ge(N.revenue)}]}),children:s.jsx(Gr,{data:_,labelKey:"sku",valueKey:"units",color:Ue.blue,format:"number",variant:"full"})}),s.jsx(br,{open:f==="region",onClose:()=>m(null),slug:e,title:"Sales by region",accent:Ue.green,askPrompt:`Break down ${n}'s sales by region over the last ${i} days. Where is demand concentrated and what does that imply for DC stock allocation?`,table:s.jsx(Ls,{rows:v,rowKey:N=>N.region,cols:[{header:"Region",render:N=>N.region},{header:"Revenue",align:"right",render:N=>ge(N.gmv)},{header:"Units",align:"right",render:N=>de(N.units)},{header:"Share",align:"right",render:N=>Yn(N.gmv_share)}]}),children:s.jsx(Ki,{data:v,labelKey:"region",valueKey:"gmv",format:"zar",variant:"full"})}),s.jsx(br,{open:f==="dow",onClose:()=>m(null),slug:e,title:"Day-of-week pattern",accent:Ue.violet,askPrompt:`What does ${n}'s day-of-week sales pattern over the last ${i} days tell me about when to schedule promotions or ad spend?`,table:s.jsx(Ls,{rows:w,rowKey:N=>N.dow,cols:[{header:"Day",render:N=>N.dow_label},{header:"Revenue",align:"right",render:N=>ge(N.gmv)},{header:"Units",align:"right",render:N=>de(N.units)},{header:"Orders",align:"right",render:N=>de(N.orders)}]}),children:s.jsx(Gr,{data:w,labelKey:"dow_label",valueKey:"gmv",color:Ue.violet,format:"zar",variant:"full"})})]})}function sBe(e){const t=new Date,n=new Date(t.getTime()+86400*1e3);return{since:new Date(t.getTime()-e*86400*1e3).toISOString().slice(0,10),until:n.toISOString().slice(0,10)}}const aBe=[{label:"Last 7 days",days:7},{label:"Last 30 days",days:30},{label:"Last 90 days",days:90}],t$=5e3,n$=[{key:"multi-unit",label:"Multi-unit",predicate:e=>(e.quantity??0)>1},{key:"high-value",label:"High value (â¥R500)",predicate:e=>(e.selling_price??0)>=500}];function iBe(){const{slug:e=""}=jn(),[t,n]=it("tab","statistics"),[r,a]=p.useState(null),[i,o]=p.useState(null),[l]=it("range","30"),c=Number(l)||30,[u]=it("since",""),[d]=it("until",""),h=!!(u&&d),f=mc(),[m,x]=it("order",""),g=m?Number(m):null,[y,b]=p.useState(null),[v,w]=p.useState(null);p.useEffect(()=>{K.seller(e).then(a).catch(()=>{})},[e]),p.useEffect(()=>{o(null),b(null),K.sales(e,h?{since:u,until:d,limit:t$}:{days:c,limit:t$}).then(o).catch(R=>b(String(R)))},[e,c,u,d,h]);const _=Id(i,p.useCallback(R=>[R.sku,R.order_id],[]),{urlKey:"q"}),k=gd(_.filtered,p.useCallback(R=>R.sale_status,[]),{urlKey:"status"}),j=gd(k.filtered,p.useCallback(R=>R.sales_region,[]),{urlKey:"region"}),{activeChips:N,toggleChip:E,clearChips:A,filtered:C}=tu(j.filtered,n$),T=p.useMemo(()=>
890{if(!C)return null;const R=new Set;let I=0,$=0,P=0,F=0,Z=0,D=0;for(const H of C){if((H.sale_status??"").toLowerCase().includes("cancel")){P+=1;continue}H.order_id!=null&&R.add(H.order_id),I+=H.quantity??0,$+=H.selling_price??0;const Y=Cw(H);Y!=null&&(F+=Y,Z+=H.selling_price??0,D+=1)}return{orders:R.size,units:I,gmv:$,cancelled:P,margin:F,gmvWithCost:Z,costRows:D}},[C]),S=p.useMemo(()=>{if(!C||C.length===0)return null;const R=new Map;let I=0;for(const $ of C){if(($.sale_status??"").toLowerCase().includes("cancel"))continue;const P=$.sales_region??"Unknown",F=$.selling_price??0;R.set(P,(R.get(P)??0)+F),I+=F}return I<=0?null:{total:I,rows:[...R.entries()].map(([$,P])=>({region:$,gmv:P,pct:P/I})).sort(($,P)=>P.gmv-$.gmv)}},[C]);async function O(R){try{const I=h?{since:u,until:d}:sBe(c),{blob:$,filename:P,dataAsOf:F,dataLagHours:Z}=await K.downloadExport(e,"sales",{format:R,since:I.since,until:I.until,search:_.q||void 0,status:k.value||void 0,region:j.value||void 0});uc($,P),F&&Z!=null&&Z>24?w({asOf:F,lagHours:Z}):w(null)}catch(I){b(String((I==null?void 0:I.message)||I))}}return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Sellers",to:"/"},{label:(r==null?void 0:r.display_name)??e,to:`/sellers/${e}`},{label:"Sales"}],actions:t==="statistics"?void 0:s.jsx(Kf,{onDownload:O,rowCount:C==null?void 0:C.length})}),s.jsx(As,{items:[{key:"statistics",label:"Statistics",icon:s.jsx(fc,{className:"w-3.5 h-3.5"}),active:t==="statistics",onClick:()=>n("statistics")},{key:"list",label:"Sales",icon:s.jsx(sN,{className:"w-3.5 h-3.5"}),active:t!=="statistics",onClick:()=>n("list")}]}),t==="statistics"?s.jsx(rBe,{slug:e,sellerName:(r==null?void 0:r.display_name)??void 0}):s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full p-4 md:p-6 space-y-4",children:[T&&s.jsxs(dr,{cols:T.costRows>0?6:5,children:[s.jsx(Ye,{label:"Orders",value:de(T.orders)}),s.jsx(Ye,{label:"Units",value:de(T.units)}),s.jsx(Ye,{label:"GMV",value:ge(T.gmv,{compact:!0})}),s.jsx(Ye,{label:"Avg order",value:T.orders>0?ge(T.gmv/T.orders,{compact:!0}):"â"}),T.costRows>0&&s.jsx(Ye,{label:"Gross margin",value:ge(T.margin,{compact:!0}),tone:T.margin<0?"error":"success",hint:T.gmvWithCost>0?`${Math.round(T.margin/T.gmvWithCost*100)}% on costed sales`:void 0}),s.jsx(Ye,{label:"Cancelled",value:de(T.cancelled),tone:T.cancelled>0?"warn":void 0})]}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx(Sw,{value:{days:c,since:u,until:d},presets:aBe,onPreset:R=>f({range:R===30?"":String(R),since:"",until:""}),onCustom:(R,I)=>f({range:"",since:R,until:I})}),s.jsx(Ni,{value:_.q,onChange:_.setQ,placeholder:"Search by SKU or order #â¦",className:"flex-1 min-w-[200px]"}),s.jsx(nu,{value:k.value,onChange:k.setValue,options:k.options,allLabel:"All statuses"}),s.jsx(nu,{value:j.value,onChange:j.setValue,options:j.options,allLabel:"All regions"}),s.jsx(hu,{chips:n$,activeChips:N,onToggle:E,onClear:A}),T&&s.jsxs("div",{className:"text-xs text-text-secondary ml-auto flex items-center gap-3 flex-wrap justify-end",children:[s.jsxs("span",{children:[de(T.orders)," orders · ",de(T.units)," units ·"," ",s.jsx("span",{className:"font-semibold text-text-body",children:ge(T.gmv,{compact:!0})})]}),T.cancelled>0&&s.jsxs("span",{className:"text-text-error",title:"Cancelled rows are excluded from GMV / orders / units.",children:[de(T.cancelled)," cancelled"]}),!j.value&&S&&S.rows.length>1&&s.jsx("span",{className:"text-text-tertiary flex items-center gap-2",children:S.rows.slice(0,4).map(R=>s.jsxs("span",{className:"inline-flex items-center gap-1",title:`${R.region}: ${ge(R.gmv)}`,children:[s.jsx("span",{className:"font-medium text-text-secondary",children:R.region}),s.jsxs("span",{children:[Math.round(R.pct*100),"%"]})]},R.region))})]})]}),v&&s.jsxs(V,{className:"p-3 text-xs text-text-warning bg-surface-warningSubtle border-outline-warning flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold",children:"Heads up â data may be stale."})," ","Sales were last synced ",s.jsx("span",{className:"font-mono",children:cn(v.asOf)})," ","(",Math.round(v.lagHours),"h ago). Re-sync before relying on this for finance."]}),s.jsx("button",{onClick:()=>w(null),className:"text-text-warning underline underline-offset-2 shrink-0",children:"Dismiss"})]}),y&&s.jsx(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:y}),s.jsx(V,{className:"overflow-hidden",children:s.jsx(dt,{rows:C,columns:dBe,getRowKey:R=>R.order_item_id,defaultSort:{key:"date",direction:"desc"},empty:{title:"No sales match.",icon:sN},renderBody:(R,I)=>!I||I.key==="date"?uBe(R).map(P=>s.jsxs(p.Fragment,{children:[s.jsx(lBe,{group:P}),P.rows.map(F=>r$(F,e,Z=>x(String(Z))))]},`day-${P.day}`)):R.map(P=>r$(P,e,F=>x(String(F))))})})]})}),s.jsx(nBe,{slug:e,orderId:g,rows:i,open:g!=null,onClose:()=>x("")})]})}function oBe(e){if(!e)return"â";const t=new Date(`${e}T00:00:00Z`);return isFinite(t.getTime())?t.toLocaleDateString("en-ZA",{weekday:"short",day:"numeric",month:"short",year:"numeric"}):e}function lBe({group:e}){const t=e.orders.size;return s.jsxs("tr",{className:"bg-surface-subtle/60 border-y border-outline-faint",children:[s.jsxs("td",{className:"sticky left-0 z-sticky bg-inherit py-1.5 pl-4 pr-3 text-xs font-medium text-text-secondary whitespace-nowrap",colSpan:3,children:[oBe(e.day),s.jsxs("span",{className:"ml-2 text-text-tertiary font-normal",children:["· ",t," order",t===1?"":"s"]}),e.cancelled>0&&s.jsxs("span",{className:"ml-2 text-text-error font-normal",children:["· ",e.cancelled," cancelled"]})]}),s.jsx("td",{className:"py-1.5 pr-3"}),s.jsx("td",{className:"py-1.5 pr-3 text-right tabular-nums text-xs text-text-tertiary",children:e.units||""}),s.jsx("td",{className:"py-1.5 pr-3 text-right tabular-nums text-xs font-semibold text-text-body",children:ge(e.gmv)}),s.jsx("td",{className:"py-1.5 pr-3 text-right tabular-nums text-xs text-text-tertiary",children:ge(e.fees)}),s.jsx("td",{className:"py-1.5 pr-3 text-right tabular-nums text-xs font-semibold text-text-body",children:e.hasCost?ge(e.margin):""}),s.jsx("td",{className:"py-1.5 pr-4"})]})}function cBe(e){return e.est_unit_fee!=null?(e.quantity??0)*e.est_unit_fee:e.total_fees??0}function Cw(e){return e.unit_cost==null?null:(e.selling_price??0)-cBe(e)-(e.quantity??0)*e.unit_cost}function uBe(e){const t=[];for(const n of e){const r=(n.order_date??"").slice(0,10);let a=t[t.length-1];if((!a||a.day!==r)&&(a={day:r,rows:[],orders:new Set,units:0,gmv:0,fees:0,margin:0,hasCost:!1,
890cancelled:0},t.push(a)),a.rows.push(n),(n.sale_status??"").toLowerCase().includes("cancel")){a.cancelled+=1;continue}n.order_id!=null&&a.orders.add(n.order_id),a.units+=n.quantity??0,a.gmv+=n.selling_price??0,a.fees+=n.total_fees??0;const i=Cw(n);i!=null&&(a.margin+=i,a.hasCost=!0)}return t}const dBe=[{key:"date",label:"Date",sortable:!0,sticky:!0,getValue:e=>e.order_date},{key:"order",label:"Order #",sortable:!0,getValue:e=>e.order_id},{key:"sku",label:"Product",sortable:!0,getValue:e=>e.sku},{key:"status",label:"Status",sortable:!0,getValue:e=>e.sale_status},{key:"qty",label:"Qty",sortable:!0,align:"right",getValue:e=>e.quantity},{key:"total",label:"Item total",sortable:!0,align:"right",getValue:e=>e.selling_price},{key:"fees",label:"Total fees",sortable:!0,align:"right",getValue:e=>e.total_fees},{key:"margin",label:"Margin",sortable:!0,align:"right",getValue:e=>Cw(e),title:"Gross margin = item total â fees â COGS. Fees use Takealot's per-offer estimate (offer_charges) where available, else the actual fee. Shown only where a unit cost is set."},{key:"region",label:"Customer region",sortable:!0,getValue:e=>e.sales_region}];function r$(e,t,n){return s.jsxs("tr",{onClick:()=>n(e.order_id),className:"border-b border-outline-faint last:border-0 bg-surface hover:bg-surface-subtle/50 cursor-pointer",children:[s.jsx("td",{className:"sticky left-0 z-sticky bg-inherit py-2 pl-4 pr-3 text-text-secondary whitespace-nowrap",children:cn(e.order_date)}),s.jsxs("td",{className:"py-2 pr-3 tabular-nums text-text-secondary",children:["#",e.order_id]}),s.jsx("td",{className:"py-2 pr-3 max-w-[280px]",children:e.title||e.sku?s.jsxs(st,{to:`/sellers/${t}/inventory?q=${encodeURIComponent(e.sku??e.title??"")}`,onClick:r=>r.stopPropagation(),className:"block hover:underline",children:[s.jsx("div",{className:"text-xs text-text-primary truncate",title:e.title??e.sku??"",children:e.title??e.sku}),e.title&&e.sku?s.jsx("div",{className:"font-mono text-[11px] text-text-tertiary truncate",children:e.sku}):null]}):"â"}),s.jsx("td",{className:"py-2 pr-3",children:s.jsx("span",{className:B("text-body-xs uppercase tracking-wider px-1.5 py-0.5 rounded border font-medium",(e.sale_status??"").toLowerCase().includes("cancel")?"bg-surface-errorSubtle text-text-error border-outline-error":"bg-surface-subtle text-text-secondary border-outline-subtle"),children:e.sale_status??"â"})}),s.jsx("td",{className:"py-2 pr-3 text-right tabular-nums",children:e.quantity}),s.jsx("td",{className:"py-2 pr-3 text-right tabular-nums",children:ge(e.selling_price)}),s.jsx("td",{className:"py-2 pr-3 text-right tabular-nums text-text-secondary",children:ge(e.total_fees)}),s.jsx("td",{className:"py-2 pr-3 text-right tabular-nums",children:(()=>{const r=Cw(e);return r==null?s.jsx("span",{className:"text-text-tertiary",children:"â"}):s.jsx("span",{className:r<0?"text-text-error":"text-text-body",children:ge(r)})})()}),s.jsx("td",{className:"py-2 pr-4 text-text-secondary",children:e.sales_region??"â"})]},e.order_item_id)}function hBe({slug:e,shipmentId:t,open:n,onClose:r}){const[a,i]=p.useState(null),[o,l]=p.useState(!1),[c,u]=p.useState(null),d=jf();p.useEffect(()=>{!n||!t||(i(null),u(null),l(!0),K.shipmentDetail(e,t).then(v=>i(v)).catch(v=>u(String((v==null?void 0:v.message)||v))).finally(()=>l(!1)))},[n,e,t]);const h=!!(a!=null&&a.date_unloaded),f=((a==null?void 0:a.items)??[]).filter(v=>!v.cancelled),m=f.reduce((v,w)=>v+w.units_sent,0),x=f.reduce((v,w)=>v+w.units_received,0),g=f.reduce((v,w)=>v+w.units_damaged,0),y=Math.max(m-x-g,0),b=(a==null?void 0:a.reference)||(a==null?void 0:a.purchase_order_number)||t;return s.jsx(Cr,{open:n,onOpenChange:v=>{v||r()},children:s.jsxs(mr,{side:"right",size:"lg",children:[s.jsxs(Er,{children:[s.jsxs(xr,{children:["Shipment ",b??"â"]}),s.jsx(Mr,{children:a?[a.destination_node??"Destination unknown",a.lifecycle_state??null,a.date_unloaded?`unloaded ${cn(a.date_unloaded)}`:a.created_at?`created ${cn(a.created_at)}`:null].filter(Boolean).join(" · "):"Shipment detail"})]}),s.jsxs(pr,{className:"p-4 space-y-4",children:[o&&s.jsx("div",{className:"text-sm text-text-tertiary",children:"Loadingâ¦"}),c&&s.jsx(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:c}),a&&s.jsxs(s.Fragment,{children:[s.jsxs(V,{className:"p-4",children:[s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary mb-3",children:"Receive reconciliation"}),s.jsxs("dl",{className:"grid grid-cols-4 gap-x-4 gap-y-3 text-sm",children:[s.jsx(qg,{label:"Sent",value:de(m)}),s.jsx(qg,{label:"Received",value:de(x)}),s.jsx(qg,{label:"Damaged",value:de(g),tone:g>0?"warn":void 0}),s.jsx(qg,{label:h?"Shortfall":"Outstanding",value:de(y),tone:y>0&&h?"error":void 0})]}),h&&y>0&&s.jsxs("div",{className:"mt-3 text-xs text-text-error bg-surface-errorSubtle border border-outline-error roun
890ded p-2",children:["This shipment was unloaded with"," ",s.jsx("span",{className:"font-semibold",children:de(y)})," ","unit",y===1?"":"s"," unaccounted for (sent but neither received nor logged as damaged). Worth a stock-loss claim."]})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-4 py-2 border-b border-outline-faint text-xs font-medium uppercase tracking-wider text-text-secondary flex items-center justify-between",children:[s.jsx("span",{children:"Line items"}),s.jsxs("span",{className:"text-text-tertiary normal-case tracking-normal font-normal",children:[a.items.length," line",a.items.length===1?"":"s"]})]}),s.jsx(dt,{rows:a.items,columns:fBe(e,h),getRowKey:(v,w)=>`${v.offer_id??"x"}-${w}`,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No line items recorded on this shipment."},rowClassName:v=>v.cancelled?"bg-surface-errorSubtle/40":void 0})]}),s.jsxs(V,{className:"p-4",children:[s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary mb-3",children:"Go deeper"}),s.jsx("div",{className:"space-y-2 text-sm",children:s.jsxs("button",{type:"button",onClick:()=>d(`stock-journey-recon for ${e}`,e),className:"flex items-center gap-2 text-text-brand hover:underline",children:[s.jsx(os,{className:"w-3.5 h-3.5"}),"Full inboundâorders reconciliation (stock-journey-recon)"]})})]})]})]})]})})}function fBe(e,t){return[{key:"product",label:"Product",className:"max-w-[240px]",render:n=>n.title||n.sku?s.jsxs(st,{to:`/sellers/${e}/inventory?q=${encodeURIComponent(n.sku??n.title??"")}`,className:"block hover:underline",children:[s.jsx("div",{className:"text-xs text-text-primary truncate",title:n.title??n.sku??"",children:n.title??n.sku}),n.title&&n.sku?s.jsx("div",{className:"font-mono text-[11px] text-text-tertiary truncate",children:n.sku}):null]}):s.jsx("span",{className:"text-text-tertiary text-xs",children:"â"})},{key:"sent",label:"Sent",align:"right",format:"number",getValue:n=>n.units_sent},{key:"received",label:"Rec'd",align:"right",format:"number",getValue:n=>n.units_received},{key:"damaged",label:"Dmg",align:"right",getValue:n=>n.units_damaged,render:n=>s.jsx("span",{className:B(n.units_damaged>0&&"text-text-warning"),children:de(n.units_damaged)})},{key:"outstanding",label:t?"Short":"Out",align:"right",getValue:n=>n.units_outstanding,render:n=>{const r=t&&n.units_outstanding>0;return s.jsx("span",{className:B(r?"text-text-error font-semibold":"text-text-secondary"),children:de(n.units_outstanding)})}}]}function qg({label:e,value:t,tone:n}){return s.jsxs("div",{children:[s.jsx("dt",{className:"text-[10px] text-text-tertiary uppercase tracking-wider",children:e}),s.jsx("dd",{className:B("font-medium tabular-nums mt-0.5",n==="error"?"text-text-error font-semibold":n==="warn"?"text-text-warning":"text-text-body"),children:t})]})}function mBe({slug:e,sellerName:t}){const n=t||e,[r,a]=it("statdays","30"),i=Number(r)||30,[o,l]=p.useState(null),[c,u]=p.useState(!0),[d,h]=p.useState(null),[f,m]=p.useState(null);p.useEffect(()=>{let _=!1;return u(!0),h(null),K.shipmentStats(e,i).then(k=>!_&&(l(k),u(!1))).catch(k=>!_&&(h(String((k==null?void 0:k.message)??k)),u(!1))),()=>{_=!0}},[e,i]);const x=o==null?void 0:o.kpis,g=(o==null?void 0:o.by_destination)??[],y=(o==null?void 0:o.recent)??[],b=p.useMemo(()=>{if(!x)return[];const _=Math.max(0,x.units_sent-x.units_received-x.units_damaged);return[{label:"Received",value:x.units_received},{label:"Outstanding",value:_},{label:"Damaged",value:x.units_damaged}]},[x]),v=p.useMemo(()=>y.map(_=>({label:_.reference||`#${_.shipment_id}`,units_sent:_.units_sent,units_received:_.units_received})),[y]),w=p.useMemo(()=>{const _=new Map;for(const k of y){const j=k.destination_region||"(unspecified)";_.set(j,(_.get(j)??0)+(k.units_damaged??0))}return[..._.entries()].map(([k,j])=>({region:k,units_damaged:j})).filter(k=>k.units_damaged>0).sort((k,j)=>j.units_damaged-k.units_damaged)},[y]);return s.jsxs(jw,{days:i,onDays:_=>a(String(_)),loading:c,error:d,children:[s.jsx(Tn,{title:"Inbound summary",subtitle:"Window totals",accent:Ue.purple,children:s.jsxs(dr,{cols:2,children:[s.jsx(Ye,{label:"Shipments",value:de(x==null?void 0:x.shipments_count)}),s.jsx(Ye,{label:"Units sent",value:de(x==null?void 0:x.units_sent)}),s.jsx(Ye,{label:"Receive rate",value:Yn(x==null?void 0:x.receive_rate),tone:((x==null?void 0:x.receive_rate)??1)<.9?"warn":"success"}),s.jsx(Ye,{label:"Damage rate",value:Yn(x==null?void 0:x.damage_rate),tone:((x==null?void 0:x.damage_rate)??0)>.02?"error":"default"})]})}),s.jsx(Tn,{title:"Receive quality",subtitle:"Of units sent",accent:Ue.green,onClick:()=>m("quality"),children:s.jsx(Ki,{data:b,labelKey:"label",valueKey:"value",format:"number",variant:"preview"})}),s.jsx(Tn,{title:"DC split",subtitle:"Units sent by destination",accent:Ue.blue,onClick:()=>m("dc"),children:s.jsx(Ki,{data:g,labelKey:"region",valueKey:"units_sent",format:"number",variant:"preview"})}),s.jsx(Tn,{title:"Damage by DC",subtitle:"Damaged units by destination",accent:Ue.red,onClick:()=>m("damage"),children:s.jsx(Gr,{data:w,labelKey:"region",valueKey:"units_damaged",color:Ue.red,format:"number",variant:"preview"})}),s.jsx(Tn,{title:"Recent shipments",subtitle:"Units sent per shipment",accent:Ue.violet,onClick:()=>m("recent"),children:s.jsx(Gr,{data:v,labelKey:"label",valueKey:"units_sent",color:Ue.violet,format:"number",variant:"preview",maxRows:5})}),s.jsx(br,{open:f==="quality",onClose:()=>m(null),slug:e,title:"Receive quality",subtitle:x?`${de(x.units_sent)} units sent in the last ${i} days`:void 0,accent:Ue.green,askPrompt:`Review ${n}'s inbound receive and damage rates over the last ${i} days. Are there shipments I should dispute or follow up on?`,children:s.jsx(Ki,{data:b,labelKey:"label",valueKey:"value",format:"number",variant:"full"})}),s.jsx(br,{open:f==="dc",onClose:()=>m(null),slug:e,title:"DC split â units sent by destination",accent:Ue.blue,askPrompt:`How is ${n}'s inbound stock split across Takealot DCs over the last ${i} days, and does that match where demand is?`,table:s.jsx(Ls,{rows:g,rowKey:_=>_.region,cols:[{header:"Destination",render:_=>_.region},{header:"Units sent",align:"right",render:_=>de(_.units_sent)}]}),children:s.jsx(Ki,{data:g,labelKey:"region",valueKey:"units_sent",format:"number",variant:"full"})}),s.jsx(br,{open:f==="damage",onClose:()=>m(null),slug:e,title:"Damage by DC â damaged units by destination",accent:Ue.red,askPrompt:`Where are ${n}'s inbound shipments losing units to damage over the last ${i} days, and should I dispute any of them?`,table:s.jsx(Ls,{rows:w,rowKey:_=>_.region,cols:[{header:"Destination",render:_=>_.region},{header:"Units damaged",align:"right",render:_=>de(_.units_damaged)}]}),children:s.jsx(Gr,{data:w,labelKey:"region",valueKey:"units_damaged",color:Ue.red,format:"number",variant:"full"})}),s.jsx(br,{open:f==="recent",onClose:()=>m(null),slug:e,title:"Recent shipments",accent:Ue.violet,askPrompt:`Summarise ${n}'s recent inbound shipments over the last ${i}
890 days and flag any that are underperforming on receive rate.`,table:s.jsx(Ls,{rows:y,rowKey:_=>_.shipment_id,cols:[{header:"Reference",render:_=>_.reference||`#${_.shipment_id}`},{header:"Dest",render:_=>_.destination_region??"â"},{header:"State",render:_=>_.state??"â"},{header:"Sent",align:"right",render:_=>de(_.units_sent)},{header:"Received",align:"right",render:_=>de(_.units_received)},{header:"Created",align:"right",render:_=>cn(_.created_at)}]}),children:s.jsx(Gr,{data:v,labelKey:"label",valueKey:"units_sent",color:Ue.violet,format:"number",variant:"full"})})]})}function pBe(e){const t=new Date,n=new Date(t.getTime()+86400*1e3);return{since:new Date(t.getTime()-e*86400*1e3).toISOString().slice(0,10),until:n.toISOString().slice(0,10)}}const xBe=[{label:"Last 30 days",days:30},{label:"Last 90 days",days:90},{label:"Last 180 days",days:180}],s$=5e3;function BS(e){return!!e.date_unloaded}const a$=[{key:"shortfall",label:"Has shortfall",predicate:e=>BS(e)&&e.units_outstanding>0},{key:"in-transit",label:"In transit",predicate:e=>!BS(e)&&!e.cancelled},{key:"damaged",label:"Damaged units",predicate:e=>e.units_damaged>0}];function gBe(){const{slug:e=""}=jn(),[t,n]=it("tab","statistics"),[r,a]=p.useState(null),[i,o]=p.useState(null),[l,c]=p.useState(null),[u,d]=p.useState(null),[h]=it("range","90"),f=Number(h)||90,[m]=it("since",""),[x]=it("until",""),g=!!(m&&x),y=mc(),[b,v]=it("open",""),[w,_]=it("inactive",""),k=w==="1",[j,N]=p.useState(null),[E,A]=p.useState(null);p.useEffect(()=>{K.seller(e).then(a).catch(()=>{})},[e]);const C=p.useCallback(()=>{o(null),N(null),K.shipments(e,g?{since:m,until:x,limit:s$}:{days:f,limit:s$}).then(o).catch(H=>N(String(H)))},[e,f,m,x,g]);p.useEffect(()=>{C()},[C]);const T=p.useMemo(()=>!i||k?i:i.filter(H=>!H.cancelled&&!H.archived),[i,k]),S=Id(T,p.useCallback(H=>[H.reference,H.purchase_order_number,H.shipment_id],[]),{urlKey:"q"}),O=gd(S.filtered,p.useCallback(H=>H.destination_node,[]),{urlKey:"node"}),R=gd(O.filtered,p.useCallback(H=>H.lifecycle_state,[]),{urlKey:"state"}),{activeChips:I,toggleChip:$,clearChips:P,filtered:F}=tu(R.filtered,a$),Z=p.useMemo(()=>{if(!F)return null;let H=0,Y=0,M=0,z=0;for(const G of F)H+=G.units_sent,Y+=G.units_received,M+=G.units_damaged,BS(G)&&G.units_outstanding>0&&(z+=1);return{count:F.length,sent:H,received:Y,damaged:M,shortfallShipments:z,receiveRate:H>0?Y/H:null,damageRate:H>0?M/H:null}},[F]);async function D(H){try{const Y=g?{since:m,until:x}:pBe(f),{blob:M,filename:z,dataAsOf:G,dataLagHours:te}=await K.downloadExport(e,"shipments",{format:H,since:Y.since,until:Y.until,search:S.q||void 0,region:O.value||void 0,status:R.value||void 0});uc(M,z),G&&te!=null&&te>24?A({asOf:G,lagHours:te}):A(null)}catch(Y){N(String((Y==null?void 0:Y.message)||Y))}}return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Sellers",to:"/"},{label:(r==null?void 0:r.display_name)??e,to:`/sellers/${e}`},{label:"Shipments"}],actions:t==="statistics"?void 0:s.jsx(Kf,{onDownload:D,rowCount:F==null?void 0:F.length})}),s.jsx(As,{items:[{key:"statistics",label:"Statistics",icon:s.jsx(fc,{className:"w-3.5 h-3.5"}),active:t==="statistics",onClick:()=>n("statistics")},{key:"list",label:"Shipments",icon:s.jsx(qi,{className:"w-3.5 h-3.5"}),active:t!=="statistics",onClick:()=>n("list")}]}),t==="statistics"?s.jsx(mBe,{slug:e,sellerName:(r==null?void 0:r.display_name)??void 0}):s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full p-4 md:p-6 space-y-4",children:[Z&&s.jsxs(dr,{cols:5,children:[s.jsx(Ye,{label:"Shipments",value:de(Z.count)}),s.jsx(Ye,{label:"Units sent",value:de(Z.sent)}),s.jsx(Ye,{label:"Receive rate",value:Z.receiveRate==null?"â":i$(Z.receiveRate)}),s.jsx(Ye,{label:"Damage rate",value:Z.damageRate==null?"â":i$(Z.damageRate),tone:Z.damaged>0?"warn":void 0}),s.jsx(Ye,{label:"With shortfall",value:de(Z.shortfallShipments),tone:Z.shortfallShipments>0?"error":void 0})]}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx(Sw,{value:{days:f,since:m,until:x},presets:xBe,onPreset:H=>y({range:H===90?"":String(H),since:"",until:""}),onCustom:(H,Y)=>y({range:"",since:H,until:Y})}),s.jsx(Ni,{value:S.q,onChange:S.setQ,placeholder:"Search by reference or PO #â¦",className:"flex-1 min-w-[200px]"}),s.jsx(nu,{value:O.value,onChange:O.setValue,options:O.options,allLabel:"All destinations"}),s.jsx(nu,{value:R.value,onChange:R.setValue,options:R.options,allLabel:"All statuses"}),s.jsx(hu,{chips:a$,activeChips:I,onToggle:$,onClear:P}),s.jsx("button",{type:"button",onClick:()=>_(k?"":"1"),className:B("text-xs px-2 py-1 rounded border whitespace-nowrap",k?"bg-surface-subtle text-text-secondary border-outline-subtle":"text-text-tertiary border-outline-faint hover:text-text-secondary"),title:"Cancelled and archived shipments are hidden by default",children:k?"Hiding none":"Show cancelled/archived"})]}),E&&s.jsxs(V,{className:"p-3 text-xs text-text-warning bg-surface-warningSubtle border-outline-warning flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold",children:"Heads up â data may be stale."})," ","Shipments were last synced"," ",s.jsx("span",{className:"font-mono",children:cn(E.asOf)})," ","(",Math.round(E.lagHours),"h ago)."]}),s.jsx("button",{onClick:()=>A(null),className:"text-text-warning underline underline-offset-2 shrink-0",children:"Dismiss"})]}),j&&s.jsx(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:j}),s.jsx(V,{className:"overflow-hidden",children:s.jsx(dt,{rows:F,columns:yBe(H=>c(H),H=>d(H)),getRowKey:H=>H.shipment_id,defaultSort:{key:"created",direction:"desc"},empty:{title:"No shipments match.",icon:qi},onRowClick:H=>v(H.shipment_id),rowClassName:H=>H.cancelled||H.archived?"opacity-60":void 0})})]})}),s.jsx(hBe,{slug:e,shipmentId:b||null,open:!!b,onClose:()=>v("")}),s.jsx(nq,{slug:e,shipmentId:(l==null?void 0:l.shipment_id)??null,poNumber:(l==null?void 0:l.purchase_order_number)??null,open:!!l,onOpenChange:H=>!H&&c(null),onBooked:C}),s.jsx(rq,{slug:e,bookingId:u,open:u!=null,onOpenChange:H=>!H&&d(null)})]})}function i$(e){return`${(e*100).toFixed(1)}%`}function yBe(e,t){return[{key:"created",label:"Created",sortable:!0,sticky:!0,getValue:n=>n.created_at,render:n=>s.jsx("span",{className:"whitespace-nowrap text-text-secondary",children:cn(n.created_at)})},{key:"reference",label:"Reference",sortable:!0,getValue:n=>n.reference??n.purchase_order_number,className:"max-w-[200px]",render:n=>s.jsxs("span",{className:"truncate text-text-primary",children:[n.reference||(n.purchase_order_number?`PO ${n.purchase_order_number}`:`#${n.shipment_id}`),n.cancelled?s.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wider text-text-error",children:"cancelled"}):n.archived?s.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wider text-text-tertiary",children:"archived"}):null]})},{key:"node",label:"Destination",sortable:!0,getValue:n=>n.destination_node,render:n=>s.jsx("span",{className:"text-text-secondary",children:n.destination_node??"â"})},{key:"state",label:"Status",sortable:!0,getValue:n=>n.lifecycle_state,render:n=>s.jsx("span",{className:"rounded border border-outline-subtle bg-surface-subtle px-1.5 py-0.5 text-body-xs font-medium uppercase tracking-wider text-text-secondary",children:n.lifecycle_state??"â"})},{key:"sent",label:"Sent",sortable:!0,align:"right",format:"number",getValue:n=>n.units_sent},{key:"received",label:"Received",sortable:!0,align:"right",getValue:n=>n.units_received,render:n=>s.jsx("span",{className:"text-text-secondary",children:de(n.units_received)})},{key:"damaged",label:"Damaged",sortable:!0,align:"right",getValue:n=>n.units_damaged,render:n=>s.jsx("span",{className:n.units_damaged>0?"text-text-warning":"text-text-secondary",children:de(n.units_damaged)})},{key:"outstanding",label:"Outstanding",sortable:!0,align:"right",getValue:n=>n.units_outstanding,render:n=>{const r=!!n.date_unloaded&&n.units_outstanding>0;return s.jsx("span",{className:r?"font-semibold text-text-error":"text-text-tertiary",children:de(n.units_outstanding)})}},{key:"unloaded",label:"Unloaded",sortable:!0,getValue:n=>n.date_unloaded,render:n=>s.jsx("span",{className:"whitespace-nowrap text-text-secondary",children:n.date_unloaded?cn(n.date_unloaded):"â"})},{key:"courier",label:"Courier",sortable:!0,getValue:n=>n.courier_status,render:n=>{const r=!!n.cancelled||!!n.archived;if(n.courier_status){const a=n.courier_booking_id!=null&&n.courier_booking_id!==void 0,i=s.jsxs(s.Fragment,{children:[rf(n.courier_status),n.courier_count>1&&s.jsxs("span",{className:"text-text-tertiary",children:["Ã",n.courier_count]})]}),o="inline-flex items-center gap-1 rounded border border-outline-subtle bg-surface-subtle px-1.5 py-0.5 text-body-xs font-medium text-text-secondary",l=n.courier_tracking_reference?`Waybill ${n.courier_tracking_reference}${n.courier_count>
8901?` (+${n.courier_count-1} more)`:""}`:void 0;return a?s.jsx("button",{type:"button",onClick:c=>{c.stopPropagation(),t(n.courier_booking_id)},className:`${o} hover:border-outline-brand hover:text-text-brand`,title:l,children:i}):s.jsx("span",{className:o,title:l,children:i})}return r?s.jsx("span",{className:"text-text-tertiary",children:"â"}):s.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),e(n)},className:"text-body-xs font-medium text-text-brand hover:underline",children:"Book"})}}]}function Ew({makro:e,other:t}){const{slug:n=""}=jn(),[r,a]=p.useState(void 0);return p.useEffect(()=>{let i=!0;return a(void 0),K.seller(n).then(o=>{i&&a(o.marketplace)}).catch(()=>{i&&a(null)}),()=>{i=!1}},[n]),r===void 0?s.jsx(Vv,{}):r==="makro"?e:t}function bBe(){return s.jsx(Ew,{makro:s.jsx(xx,{view:"sales"}),other:s.jsx(iBe,{})})}function vBe(){return s.jsx(Ew,{makro:s.jsx(xx,{view:"returns"}),other:s.jsx(VFe,{})})}function wBe(){return s.jsx(Ew,{makro:s.jsx(xx,{view:"inventory"}),other:s.jsx(TFe,{})})}function _Be(){return s.jsx(Ew,{makro:s.jsx(xx,{view:"shipments"}),other:s.jsx(gBe,{})})}const kBe=["ean_13","ean_8","upc_a","upc_e","code_128","code_39","itf"];function jBe(){const{slug:e=""}=jn(),[t]=p.useState(()=>crypto.randomUUID()),[n,r]=p.useState([]),[a,i]=p.useState(null),[o,l]=p.useState(null),[c,u]=p.useState(!1),d=p.useRef(null),[h,f]=p.useState("");p.useEffect(()=>{if(a)return;const y=window.setInterval(()=>{var b,v,w;((b=document.activeElement)==null?void 0:b.tagName)==="INPUT"||((v=document.activeElement)==null?void 0:v.tagName)==="TEXTAREA"||(w=d.current)==null||w.focus()},800);return()=>window.clearInterval(y)},[a]),p.useEffect(()=>{K.scanner.session(e,t).then(y=>r(y.movements)).catch(()=>{})},[e,t]),p.useEffect(()=>{if(!o)return;const y=window.setTimeout(()=>l(null),3e3);return()=>window.clearTimeout(y)},[o]);async function m(){try{const y=await K.scanner.session(e,t);r(y.movements)}catch{}}async function x(y){const b=y.trim();if(!(!b||c)){u(!0);try{const{matches:v}=await K.scanner.lookup(e,b);if(v.length===1){const w=await K.scanner.commit(e,{warehouse_item_id:v[0].id,qty_delta:1,session_id:t,scanned_code:b});l$(),l({kind:"ok",sku:w.warehouse_item.internal_sku??"â",newQty:w.warehouse_item.qty_at_warehouse}),await m()}else v.length===0?(c$(),i({kind:"no_match",code:b})):(c$(),i({kind:"multi_match",code:b,candidates:v}))}catch(v){IBe(),l({kind:"err",message:v.message})}finally{u(!1),f("")}}}async function g(y){try{await K.scanner.undo(e,y),await m()}catch(b){l({kind:"err",message:b.message})}}return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Sellers",to:"/"},{label:e,to:`/sellers/${e}`},{label:"Inventory",to:`/sellers/${e}/inventory`},{label:"Scan"}]}),s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"max-w-2xl mx-auto p-3 md:p-6 space-y-4",children:[s.jsx(NBe,{onCode:x,disabled:!!a}),s.jsx(V,{className:"p-3",children:s.jsxs("form",{onSubmit:y=>{y.preventDefault(),h.trim()&&x(h)},className:"flex items-center gap-2",children:[s.jsx("label",{className:"text-xs text-text-secondary shrink-0",children:"Code:"}),s.jsx("input",{ref:d,value:h,onChange:y=>f(y.target.value),placeholder:"Scan or type a barcode, then press Enterâ¦",autoFocus:!0,inputMode:"text",autoComplete:"off",autoCapitalize:"off",spellCheck:!1,className:"flex-1 px-3 py-2 text-sm font-mono rounded-md border border-outline-subtle bg-surface focus:outline-none focus:border-outline-brand focus-visible:shadow-focus"}),c&&s.jsx(_e,{className:"w-4 h-4 animate-spin text-text-tertiary"})]})}),o&&s.jsx(SBe,{flash:o}),s.jsx(CBe,{entries:n,onUndo:g,sessionId:t})]})}),a&&s.jsx(EBe,{slug:e,sessionId:t,scan:a,onResolved:async()=>{l$(),i(null),await m()},onCancel:()=>i(null),onError:y=>l({kind:"err",message:y})})]})}function NBe({onCode:e,disabled:t}){const n=p.useRef(null),r=p.useRef(null),a=p.useRef(null),i=p.useRef(null),[o,l]=p.useState(!1),[c,u]=p.useState(null),d=p.useRef(null);function h(g){const y=d.current,b=Date.now();y&&y.code===g&&b-y.t<1200||(d.current={code:g,t:b},e(g))}async function f(){u(null);try{const g=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:"environment"}},audio:!1});r.current=g,n.current&&(n.current.srcObject=g,await n.current.play()),l(!0);const y=window.BarcodeDetector;
890if(y)try{a.current=new y({formats:kBe}),m();return}catch{}const{BrowserMultiFormatReader:b}=await Yl(async()=>{const{BrowserMultiFormatReader:_}=await import("./index-C5PPNdDI.js");return{BrowserMultiFormatReader:_}},__vite__mapDeps([7,1,2])),w=await new b().decodeFromStream(g,n.current,_=>{_&&h(_.getText())});i.current={stop:()=>w.stop()}}catch(g){u(g.message||"Couldn't access the camera. Check the browser's permissions."),x()}}async function m(){const g=n.current,y=a.current;if(!g||!y)return;let b=!1;const v=()=>{b=!0};i.current={stop:v};const w=async()=>{if(!b){try{const _=await y.detect(g);_&&_.length>0&&h(_[0].rawValue)}catch{}window.setTimeout(w,100)}};w()}function x(){var g,y;(g=i.current)==null||g.stop(),i.current=null,a.current=null,(y=r.current)==null||y.getTracks().forEach(b=>b.stop()),r.current=null,n.current&&(n.current.srcObject=null),l(!1)}return p.useEffect(()=>()=>x(),[]),s.jsx(V,{className:"p-0 overflow-hidden",children:s.jsxs("div",{className:"relative aspect-[4/3] bg-black flex items-center justify-center",children:[s.jsx("video",{ref:n,playsInline:!0,muted:!0,className:B("w-full h-full object-cover",!o&&"hidden")}),!o&&s.jsxs("div",{className:"text-center p-6 text-text-inverse/80 text-sm space-y-3",children:[s.jsx(up,{className:"w-10 h-10 mx-auto opacity-50"}),s.jsx("div",{children:"Camera off. Tap to start scanning with your phone."}),s.jsx("button",{type:"button",onClick:f,disabled:t,className:"px-4 py-2 rounded-md bg-brand-500 text-text-inverse text-sm font-medium hover:bg-intent-brand disabled:opacity-40",children:"Start camera"}),c&&s.jsx("div",{className:"text-xs text-error-300 mt-2",children:c})]}),o&&s.jsxs("div",{className:"absolute inset-0 pointer-events-none",children:[s.jsx("div",{className:"absolute left-[10%] right-[10%] top-1/2 h-0.5 bg-brand-400 opacity-70 animate-pulse"}),s.jsx("div",{className:"absolute top-3 left-3 px-2 py-1 rounded bg-black/60 text-text-inverse text-xs",children:"Scanningâ¦"})]}),o&&s.jsx("button",{type:"button",onClick:x,className:"absolute top-2 right-2 p-1.5 rounded-md bg-black/60 hover:bg-black/80 text-text-inverse",title:"Stop camera","aria-label":"Stop camera",children:s.jsx(Ete,{className:"w-4 h-4"})})]})})}function SBe({flash:e}){return e.kind==="ok"?s.jsxs(V,{className:"p-3 bg-surface-successSubtle border-outline-success flex items-center gap-2",children:[s.jsx(Xt,{className:"w-4 h-4 text-text-success"}),s.jsxs("div",{className:"text-sm",children:[s.jsx("span",{className:"font-mono",children:e.sku})," ",s.jsx("span",{className:"text-text-secondary",children:"â now"})," ",s.jsx("span",{className:"font-semibold tabular-nums",children:e.newQty})," ",s.jsx("span",{className:"text-text-secondary",children:"on hand"})]})]}):s.jsxs(V,{className:"p-3 bg-surface-errorSubtle border-outline-error flex items-center gap-2",children:[s.jsx(yt,{className:"w-4 h-4 text-text-error"}),s.jsx("div",{className:"text-sm text-text-error",children:e.message})]})}function CBe({entries:e,onUndo:t,sessionId:n}){const r=p.useMemo(()=>{let a=0;const i=new Set;for(const o of e)o.kind==="inbound"&&(a+=o.qty_delta),o.kind==="manual_adjust"&&(a+=o.qty_delta),i.add(o.warehouse_item_id);return{units:a,skus:i.size}},[e]);return s.jsxs(V,{className:"p-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"This session"}),s.jsxs("div",{className:"text-xs text-text-secondary tabular-nums",children:[de(r.units)," units · ",r.skus," SKUs"]})]}),e.length===0&&s.jsxs("div",{className:"py-6 text-center text-text-tertiary text-xs",children:[s.jsx(Si,{className:"w-6 h-6 mx-auto opacity-30 mb-1"}),"Scans land here as you go."]}),e.length>0&&s.jsx("div",{className:"divide-y divide-outline-faint -mx-1",children:e.map(a=>s.jsxs("div",{className:"flex items-center gap-2 py-1.5 px-1 text-sm",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"font-mono text-xs text-text-body truncate",children:a.internal_sku??"â"}),s.jsx("div",{className:"text-text-tertiary text-xs truncate",children:a.title??""})]}),s.jsxs("div",{className:B("text-sm font-semibold tabular-nums shrink-0",a.qty_delta>0?"text-text-success":"text-text-error"),children:[a.qty_delta>0?"+":"",a.qty_delta]}),s.jsxs("div",{className:"text-xs text-text-tertiary tabular-nums shrink-0 w-12 text-right",children:["â ",de(a.qty_at_warehouse)]}),a.kind==="inbound"&&s.jsx("button",{type:"button",onClick:()=>
890t(a.id),title:"Undo this scan",className:"p-1 text-text-tertiary hover:text-text-secondary rounded hover:bg-surface-subtle",children:s.jsx(vd,{className:"w-3.5 h-3.5"})})]},a.id))}),s.jsxs("div",{className:"text-[10px] text-text-tertiary mt-2 font-mono opacity-60",children:["session ",n.slice(0,8)]})]})}function EBe({slug:e,sessionId:t,scan:n,onResolved:r,onCancel:a,onError:i}){const[o,l]=p.useState(n.kind==="multi_match"?"pick":"add"),[c,u]=p.useState(!1);return s.jsx("div",{className:"fixed inset-0 z-modal flex items-end md:items-center justify-center bg-black/50 p-2",children:s.jsxs(V,{className:"w-full max-w-md p-4 space-y-3",children:[s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:n.kind==="no_match"?"Barcode not in your catalogue":"Multiple matches â pick one"}),s.jsx("div",{className:"text-xs text-text-tertiary font-mono mt-0.5",children:n.code})]}),s.jsx("button",{type:"button",onClick:a,className:"p-1 text-text-tertiary hover:text-text-secondary rounded hover:bg-surface-subtle","aria-label":"Cancel",children:s.jsx(Bn,{className:"w-4 h-4"})})]}),n.kind==="no_match"&&s.jsxs("div",{className:"flex items-center gap-1 -mx-1 px-1 border-b border-outline-subtle pb-2",children:[s.jsx(o$,{active:o==="add",onClick:()=>l("add"),children:"Add as new product"}),s.jsx(o$,{active:o==="attach",onClick:()=>l("attach"),children:"Attach to existing"})]}),o==="pick"&&n.kind==="multi_match"&&s.jsx(ABe,{slug:e,sessionId:t,scan:n,submitting:c,setSubmitting:u,onDone:r,onError:i}),o==="add"&&n.kind==="no_match"&&s.jsx(TBe,{slug:e,sessionId:t,scannedCode:n.code,submitting:c,setSubmitting:u,onDone:r,onError:i,onFallbackToAttach:()=>l("attach")}),o==="attach"&&n.kind==="no_match"&&s.jsx(OBe,{slug:e,sessionId:t,scannedCode:n.code,submitting:c,setSubmitting:u,onDone:r,onError:i,onFallbackToAdd:()=>l("add")})]})})}function o$({active:e,onClick:t,children:n}){return s.jsx("button",{type:"button",onClick:t,className:B("px-2.5 py-1.5 text-xs font-medium rounded-md",e?"bg-brand-500 text-text-inverse":"text-text-secondary hover:bg-surface-subtle"),children:n})}function ABe({slug:e,sessionId:t,scan:n,submitting:r,setSubmitting:a,onDone:i,onError:o}){const[l,c]=p.useState(1);async function u(d){a(!0);try{await K.scanner.commit(e,{warehouse_item_id:d,qty_delta:l,session_id:t,scanned_code:n.code}),await i()}catch(h){o(h.message)}finally{a(!1)}}return s.jsxs("div",{className:"space-y-2",children:[s.jsx(v3,{qty:l,setQty:c}),s.jsxs("div",{className:"text-xs text-text-secondary",children:["This barcode resolves to ",n.candidates.length," products. Pick the one you're scanning into:"]}),s.jsx("div",{className:"divide-y divide-outline-faint border border-outline-subtle rounded-md max-h-64 overflow-y-auto",children:n.candidates.map(d=>s.jsxs("button",{type:"button",disabled:r,onClick:()=>u(d.id),className:"w-full text-left px-3 py-2 hover:bg-surface-subtle disabled:opacity-40",children:[s.jsx("div",{className:"font-mono text-xs text-text-body truncate",children:d.internal_sku??"â"}),s.jsxs("div",{className:"text-xs text-text-tertiary truncate",children:[d.title??"â"," · on hand ",de(d.qty_at_warehouse)]})]},d.id))})]})}function TBe({slug:e,sessionId:t,scannedCode:n,submitting:r,setSubmitting:a,onDone:i,onError:o,onFallbackToAttach:l}){const[c,u]=p.useState(""),[d,h]=p.useState(""),[f,m]=p.useState(""),[x,g]=p.useState(1);async function y(b){if(b.preventDefault(),!!c.trim()){a(!0);try{await K.scanner.create(e,{internal_sku:c.trim(),title:d.trim()||void 0,scanned_code:n,cost_excl_vat:f?Number(f):void 0,qty_delta:x,session_id:t}),await i()}catch(v){const w=v;w.code==="barcode_already_exists"?(o("That barcode is already in your catalogue. Switching to Attach."),l()):o(w.message)}finally{a(!1)}}}return s.jsxs("form",{onSubmit:y,className:"space-y-2",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs text-text-secondary",children:"Internal SKU *"}),s.jsx("input",{autoFocus:!0,value:c,onChange:b=>u(b.target.value),required:!0,placeholder:"ABC-001",className:"mt-0.5 w-full px-2 py-1.5 text-sm font-mono rounded-md border border-outline-subtle focus:outline-none focus:border-outline-brand focus-visible:shadow-focus"})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs text-text-secondary",children:"Title (optional)"}),s.jsx("input",{value:d,onChange:b=>h(b.target.value),placeholder:"Product name",className:"mt-0.5 w-full px-2 py-1.5 text-sm rounded-md border border-outline-subtle focus:outline-none focus:border-outline-brand focus-visible:shadow-focus"})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs text-text-secondary",children:"Cost ex-VAT (optional)"}),s.jsx("input",{value:f,onChange:b=>m(b.target.value),inputMode:"decimal",placeholder:"0.00",className:"mt-0.5 w-full px-2 py-1.5 text-sm font-mono rounded-md border border-outline-subtle focus:outline-none focus:border-outline-brand focus-visible:shadow-focus"})]}
890),s.jsx(v3,{qty:x,setQty:g}),s.jsx("button",{type:"submit",disabled:r||!c.trim(),className:"w-full py-2 rounded-md bg-brand-500 text-text-inverse text-sm font-medium hover:bg-intent-brand disabled:opacity-40",children:r?"Savingâ¦":`Save & receive ${x}`})]})}function OBe({slug:e,sessionId:t,scannedCode:n,submitting:r,setSubmitting:a,onDone:i,onError:o,onFallbackToAdd:l}){const[c,u]=p.useState(""),[d,h]=p.useState([]),[f,m]=p.useState(1),[x,g]=p.useState(null);p.useEffect(()=>{if(c.trim().length<2){h([]);return}const b=setTimeout(async()=>{try{const v=await K.catalogue(e,c,25);h(v.map(w=>({id:w.id,internal_sku:w.internal_sku,title:w.title})))}catch{h([])}},200);return()=>clearTimeout(b)},[c,e]);async function y(b){if(b.preventDefault(),!!x){a(!0);try{await K.scanner.attach(e,{warehouse_item_id:x,scanned_code:n,qty_delta:f,session_id:t}),await i()}catch(v){o(v.message)}finally{a(!1)}}}return s.jsxs("form",{onSubmit:y,className:"space-y-2",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs text-text-secondary",children:"Find product to attach this barcode to"}),s.jsx("input",{autoFocus:!0,value:c,onChange:b=>u(b.target.value),placeholder:"Type SKU or titleâ¦",className:"mt-0.5 w-full px-2 py-1.5 text-sm rounded-md border border-outline-subtle focus:outline-none focus:border-outline-brand focus-visible:shadow-focus"})]}),d.length>0&&s.jsx("div",{className:"divide-y divide-outline-faint border border-outline-subtle rounded-md max-h-40 overflow-y-auto",children:d.map(b=>s.jsxs("button",{type:"button",onClick:()=>g(b.id),className:B("w-full text-left px-2 py-1.5 hover:bg-surface-subtle",x===b.id&&"bg-surface-brandSubtle"),children:[s.jsx("div",{className:"font-mono text-xs text-text-body truncate",children:b.internal_sku??"â"}),s.jsx("div",{className:"text-xs text-text-tertiary truncate",children:b.title??"â"})]},b.id))}),c.trim().length>=2&&d.length===0&&s.jsxs("div",{className:"text-xs text-text-tertiary px-1",children:["No products match. Want to"," ",s.jsx("button",{type:"button",onClick:l,className:"underline text-text-brand",children:"add as new"})," ","instead?"]}),s.jsx(v3,{qty:f,setQty:m}),s.jsx("button",{type:"submit",disabled:r||!x,className:"w-full py-2 rounded-md bg-brand-500 text-text-inverse text-sm font-medium hover:bg-intent-brand disabled:opacity-40",children:r?"Savingâ¦":`Attach & receive ${f}`})]})}function v3({qty:e,setQty:t}){return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-xs text-text-secondary",children:"Receiving qty:"}),s.jsx("button",{type:"button",onClick:()=>t(Math.max(1,e-1)),className:"w-7 h-7 rounded-md border border-outline-subtle text-text-secondary hover:bg-surface-subtle flex items-center justify-center","aria-label":"Decrement quantity",children:s.jsx(Hv,{className:"w-3.5 h-3.5"})}),s.jsx("input",{value:e,onChange:n=>{const r=Number(n.target.value);Number.isFinite(r)&&r>0&&t(Math.floor(r))},inputMode:"numeric",className:"w-16 px-2 py-1 text-center font-mono text-sm rounded-md border border-outline-subtle focus:outline-none focus:border-outline-brand focus-visible:shadow-focus"}),s.jsx("button",{type:"button",onClick:()=>t(e+1),className:"w-7 h-7 rounded-md border border-outline-subtle text-text-secondary hover:bg-surface-subtle flex items-center justify-center","aria-label":"Increment quantity",children:s.jsx(In,{className:"w-3.5 h-3.5"})})]})}function w3(e,t,n=.15){try{const r=window.AudioContext||window.webkitAudioContext;if(!r)return;const a=new r,i=a.createOscillator(),o=a.createGain();i.frequency.value=e,o.gain.value=n,i.connect(o).connect(a.destination),i.start(),i.stop(a.currentTime+t/1e3),i.onended=()=>a.close()}catch{}}function l$(){w3(880,100)}function c$(){w3(440,180)}function IBe(){w3(220,250)}const u$=e=>e==null?null:Number(e);function Gg(e){return e==null?"â":`${e>0?"+":""}${e}%`}function sq(e){switch(e){case"looking_like_keep":return"Looking like a keep â profit is holding.";case"looking_like_revert":return"Leaning revert â profit is not paying for the step.";case"heading_for_stop":return"Units are falling off vs the rest of the book â heading for stop-loss.";case"too_early":default:return"Too early to call. We need a few more days."}}
890function aq(e){return e==="switchback"?"Switchback":e==="staircase"?"Staircase":"Step & hold"}function tc(e){return e.offer_title??e.title??e.offer_sku??e.sku??e.offer_id}function Bi({label:e,value:t,hint:n,strong:r}){return s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-secondary",children:e}),s.jsxs("div",{className:B("tabular-nums",r?"font-semibold text-text-primary":"text-text-primary"),children:[t,n&&s.jsxs("span",{className:"ml-1 text-xs text-text-secondary",children:["(",n,")"]})]})]})}function iq(e){var r;const t=u$(e.baseline_price),n=u$((r=e.test_prices)==null?void 0:r[0]);return`${t!=null?ge(t):"â"} â ${n!=null?ge(n):"â"}`}function oq(e){switch(e){case"no_plid":return"no Takealot product id on file";case"no_pdp":case"fetch_failed":return"couldn't read the live page";case"cloudflare_403":return"Takealot blocked the live page read";case"summary":case"verify_failed":return"couldn't resolve the variant page";default:return e||"live check didn't confirm"}}function d$(e){const t=[];for(const o of e.ineligible??[])t.push(`${o.sku??o.offer_id}: ${o.db_reason??"ineligible"}`);for(const o of e.deferred??[])t.push(`${o.sku??o.offer_id}: ${oq(o.live_reason)}`);const n=(e.ineligible??[]).filter(o=>/contested/i.test(o.db_reason||"")).length,r=t.length-n,a=t.slice(0,3).join("; "),i=t.length>3?` (+${t.length-3} more)`:"";return t.length?n&&!r?`None came back uncontested. ${a}${i}`:n?`No testable SKUs â ${n} contested, ${r} unconfirmed. ${a}${i}`:`Couldn't confirm these SKUs (not a contest call). ${a}${i}`:"None of the selected SKUs could be confirmed."}function h$(e,t,n){return n==="down"?t==="aggressive"?e.suggested_down_aggressive:e.suggested_down_conservative:t==="aggressive"?e.suggested_aggressive:e.suggested_conservative}const f$={fontSize:11,fill:kr};function Wp({slug:e,offerId:t,title:n,open:r,onOpenChange:a}){const[i,o]=p.useState(null),[l,c]=p.useState(null);return p.useEffect(()=>{if(!r||t==null){o(null),c(null);return}let u=!0;return o(null),c(null),K.experiments.history(e,t,12).then(d=>{u&&o(d)}).catch(d=>{u&&c(String((d==null?void 0:d.message)||d))}),()=>{u=!1}},[r,e,t]),s.jsx(Cr,{open:r,onOpenChange:a,children:s.jsxs(mr,{side:"right",size:"lg",children:[s.jsxs(Er,{children:[s.jsx(xr,{children:n!=null&&String(n)!==""?String(n):t!=null?`Offer ${t}`:"Sales history"}),s.jsx(Mr,{children:"Last 12 weeks of units. The faint line is the weekday / week-of-month expected â the same series Live uses instead of a flat average."})]}),s.jsxs(pr,{className:"p-4 space-y-3",children:[l&&s.jsx("p",{className:"text-sm text-text-secondary",children:l}),!i&&!l&&s.jsx("p",{className:"text-sm text-text-secondary",children:"Loadingâ¦"}),i&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"h-56",children:s.jsx(li,{width:"100%",height:"100%",children:s.jsxs(Wx,{data:i.days,margin:{top:8,right:8,left:0,bottom:0},children:[s.jsx(Ma,{stroke:Co,vertical:!1}),i.window&&s.jsx(zK,{x1:i.window.from,x2:i.window.to,fill:et.primary,fillOpacity:.08}),s.jsx($a,{dataKey:"date",tick:f$,tickFormatter:u=>String(u).slice(5),minTickGap:24}),s.jsx(zr,{tick:f$,width:32,allowDecimals:!1}),s.jsx(Da,{formatter:(u,d)=>[u??"â",String(d)==="expected"?"Expected":"Units"]}),s.jsx(vo,{dataKey:"units",fill:et.strong,radius:[2,2,0,0]}),s.jsx(Vi,{type:"monotone",dataKey:"expected",stroke:et.ink,strokeWidth:1.5,dot:!1})]})})}),s.jsxs("div",{className:"text-xs text-text-secondary space-y-1",children:[s.jsxs("div",{children:[i.totals.last_7," units last 7d · ",i.totals.last_28," last 28d ·"," ",i.totals.last_84," last 12 weeks"]}),i.caption&&s.jsx("div",{children:i.caption})]})]})]})]})})}function Od({children:e,onClick:t}){return s.jsx("button",{type:"button",onClick:t,className:"text-left hover:underline decoration-outline-subtle underline-offset-2",children:e})}function PBe({slug:e,pageSize:t=50}){const n=Rt(),[r]=ki(),a=r.get("sku")??"",i=r.get("offer_id"),[o,l]=p.useState(a),[c,u]=p.useState(""),[d,h]=p.useState([]),[f,m]=p.useState(!0),[x,g]=p.useState([]),[y,b]=p.useState(!1),[v,w]=p.useState(!1),[_,k]=p.useState({}),[j,N]=p.useState([]),[E,A]=p.useState(null),[C,T]=p.useState("pick"),[S,O]=p.useState(null),[R,I]=p.useState(!1),[$,P]=p.useState({}),[F,Z]=p.useState({}),[D,H]=p.useState("step_hold"),[Y,M]=p.useState("conservative"),[z,G]=p.useState("up"),[te,re]=p.useState("14"),[L,q]=p.useState("3"),[me,ee]=p.useState("revert"),[ne,X]=p.useState(!1),[he,ae]=p.useState(null),[je,$e]=p.useState([]),[J,Ne]=p.useState(null),ve=p.useCallback(async U=>{w(!0);try{const ce=U?0:x.length,ue=await K.experiments.catalog(e,{search:o,eligibleOnly:f,brand:c,limit:t,offset:ce});g(Ee=>U?ue.offers:[...Ee,...ue.offers]),b(ue.has_more)}catch(ce){Ae.error("Couldn't load catalogue",{description:String((ce==null?void 0:ce.message)||ce)})}finally{w(!1)}},[e,o,f,c,x.length,t]);p.useEffect(()=>{g([]),ve(!0)},[e,f,c]),p.useEffect(()=>{K.experiments.brands(e).then(U=>h(U.brands)).catch(()=>{}),K.experiments.shortlist(e).then(U=>{N(U.offers),k(ce=>{const ue={...ce};for(const Ee of U.offers)Ee.db_eligible&&(ue[Ee.offer_id]=!0);return ue})}).catch(()=>{}),K.experiments.portfolio(e).then(A).catch(()=>{}),K.experiments.context(e).then(ae).catch(()=>{}),K.experiments.drafts(e).then(U=>$e(U.batches)).catch(()=>$e([]))},[e]),p.useEffect(()=>{var ce;if(!i&&!a)return;const U=i?Number(i):(ce=x.find(ue=>ue.sku===a))==null?void 0:ce.offer_id;U&&k(ue=>({...ue,[U]:!0}))},[i,a,x]);const Me=p.useMemo(()=>Object.keys(_).filter(U=>_[+U]).map(Number),[_]);function Xe(U,ce=Y,ue=z){var vt,Ot;const Ee={},bt={};for(const It of U){const Ut=h$(It,ce,ue)??It.suggested_price;Ut!=null&&(Ee[It.offer_id]=String(Ut)),(vt=It.ladder)!=null&&vt.length&&(bt[It.offer_id]=It.ladder)}P(Ee),Z(bt);const Ze=U[0];
890(Ot=Ze==null?void 0:Ze.power)!=null&&Ot.suggested_window_days&&re(String(Ze.power.suggested_window_days))}async function ze(){if(!(!Me.length||R)){I(!0);try{const U=await K.experiments.candidates(e,Me,{appetite:Y,direction:z});O(U),Xe(U.eligible),U.capped&&Ae.info("Checked the first 25 selected â narrow further for the rest."),U.eligible.length?T("design"):Ae.info(d$(U))}catch(U){Ae.error("Live check failed",{description:String((U==null?void 0:U.message)||U)})}finally{I(!1)}}}async function Fe(U,ce){if(M(U),G(ce),!!(S!=null&&S.eligible.length))try{const ue=await K.experiments.resuggest(e,S.eligible,{appetite:U,direction:ce});O(Ee=>Ee&&{...Ee,eligible:ue.eligible}),Xe(ue.eligible,U,ce)}catch{Xe(S.eligible,U,ce)}}const tt=((S==null?void 0:S.eligible)??[]).filter(U=>{const ce=Number($[U.offer_id]);return!ce||!U.baseline_price?!1:z==="down"?ce<U.baseline_price:ce>U.baseline_price});async function fe(U){if(!(!tt.length||ne)){X(!0);try{const ce=tt.map(Ze=>({offer_id:Ze.offer_id,design:D,appetite:Y,direction:z,baseline_price:Ze.baseline_price,suggested_price:h$(Ze,Y,z)??Ze.suggested_price,suggestion_basis:Ze.suggestion_basis,test_prices:D==="staircase"?(F[Ze.offer_id]??[]).map(vt=>vt.price):[Number($[Ze.offer_id])],schedule:D==="switchback"?{type:"switchback",block_days:Number(L)||3}:D==="staircase"?{type:"staircase",steps:F[Ze.offer_id]??[]}:{type:"step_hold"},window_days:Number(te),end_policy:me,velocity_at_start:Ze.units_per_week/7,units_per_week:Ze.units_per_week,cost_excl_vat:Ze.cost_excl_vat,contest_ceiling:Ze.contest_ceiling})),ue=await K.experiments.create(e,ce,{status:U==="scheduled"?"scheduled":"draft",send_for_approval:U==="approve"}),Ee=ue.results.filter(Ze=>Ze.ok).length,bt=ue.results.filter(Ze=>!Ze.ok);U==="scheduled"&&Ee&&Ae.success(`Created ${Ee} experiment${Ee>1?"s":""}. Starts on the next hourly tick.`),U==="draft"&&Ee&&Ae.success(`Saved ${Ee} draft${Ee>1?"s":""}. Takealot prices are unchanged.`),U==="approve"&&Ee&&(ue.approval&&ue.approval.ok===!1?Ae.error("Drafts saved, but send for approval failed",{description:String(ue.approval.error||"not_migrated")}):Ae.success(`Sent ${Ee} SKU${Ee>1?"s":""} to the seller for sign-off.`)),bt.length&&Ae.error(`${bt.length} could not be created`,{description:bt.map(Ze=>`#${Ze.offer_id}: ${Ze.error}`).join("; ")}),Ee&&U==="scheduled"&&n(`/sellers/${e}/automations/experiments/live`),Ee&&U!=="scheduled"&&(T("pick"),O(null),K.experiments.drafts(e).then(Ze=>$e(Ze.batches)).catch(()=>{}))}catch(ce){Ae.error("Create failed",{description:String((ce==null?void 0:ce.message)||ce)})}finally{X(!1)}}}return C!=="pick"&&S?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"space-y-4",children:[s.jsxs("button",{className:"text-sm text-text-secondary hover:text-text-primary",onClick:()=>{C==="review"?T("design"):(T("pick"),O(null))},children:["â ",C==="review"?"Back to design":"Back to catalogue"]}),C==="design"&&s.jsx(RBe,{cands:S,selectedCount:Me.length,prices:$,setPrices:P,ladders:F,setLadders:Z,design:D,setDesign:H,appetite:Y,direction:z,onAppetiteOrDirection:Fe,windowDays:te,setWindowDays:re,blockDays:L,setBlockDays:q,endPolicy:me,setEndPolicy:ee,launchableCount:tt.length,onContinue:()=>T("review"),onOpenHistory:U=>Ne({offerId:U.offer_id,title:U.title??U.sku})}),C==="review"&&s.jsx(MBe,{launchable:tt,prices:$,ladders:F,design:D,appetite:Y,direction:z,windowDays:te,endPolicy:me,busy:ne,siblingWarning:S.sibling_warning??null,canLaunch:(he==null?void 0:he.can_launch)!==!1,canSendForApproval:!!(he!=null&&he.can_send_for_approval),onSaveDraft:()=>fe("draft"),onLaunch:()=>fe("scheduled"),onSendForApproval:()=>fe("approve"),onOpenHistory:U=>Ne({offerId:U.offer_id,title:U.title??U.sku})})]}),s.jsx(Wp,{slug:e,offerId:(J==null?void 0:J.offerId)??null,title:J==null?void 0:J.title,open:!!J,onOpenChange:U=>!U&&Ne(null)})]}):s.jsxs("div",{className:"space-y-4",children:[je.length>0&&s.jsxs(V,{className:"p-4 space-y-2",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Saved drafts"}),s.jsx("p",{className:"text-xs text-text-secondary",children:"Saved without going live. Prices and contest may have moved â Go live re-checks."}),je.map(U=>s.jsxs("div",{className:"flex items-start gap-3 text-sm py-1",children:[s.jsx("div",{className:"flex-1 min-w-0",children:U.experiments.map(ce=>{var ue;return s.jsxs("div",{className:"truncate",children:[s.jsx(Od,{onClick:()=>Ne({offerId:Number(ce.offer_id),title:ce.offer_title??ce.offer_sku}),children:ce.offer_title??ce.offer_sku??ce.offer_id}),s.jsxs("span",{className:"text-text-secondary",children:[" ",ge(Number(ce.baseline_price))," â ",ge(Number((ue=ce.test_prices)==null?void 0:ue[0]))]})]},ce.id)})}),s.jsxs("div",{className:"flex flex-col gap-1",children:[(he==null?void 0:he.can_send_for_approval)&&s.jsx(W,{type:"button",size:"sm",variant:"outline",onClick:async()=>{try{await K.experiments.sendForApproval(e,U.batch_id),Ae.success("Sent to the seller for sign-off.")}catch(ce){Ae.error("Send failed",{description:String((ce==null?void 0:ce.message)||ce)})}}
890,children:"Send to seller"}),(he==null?void 0:he.can_launch)!==!1&&s.jsx(W,{type:"button",size:"sm",onClick:async()=>{var ce,ue;try{const Ee=await K.experiments.scheduleBatch(e,U.batch_id),bt=((ce=Ee.scheduled)==null?void 0:ce.length)??0;bt&&Ae.success(`Go live: ${bt} scheduled.`),(ue=Ee.skipped)!=null&&ue.length&&Ae.error(`${Ee.skipped.length} still drafted`,{description:Ee.skipped.map(Ze=>Ze.error).join("; ")}),bt&&n(`/sellers/${e}/automations/experiments/live`),K.experiments.drafts(e).then(Ze=>$e(Ze.batches)).catch(()=>{})}catch(Ee){Ae.error("Go live failed",{description:String((Ee==null?void 0:Ee.message)||Ee)})}},children:"Go live"}),s.jsx(W,{type:"button",size:"sm",variant:"ghost",onClick:async()=>{try{await K.experiments.discardBatch(e,U.batch_id),Ae.success("Draft discarded."),$e(ce=>ce.filter(ue=>ue.batch_id!==U.batch_id))}catch(ce){Ae.error("Discard failed",{description:String((ce==null?void 0:ce.message)||ce)})}},children:"Discard"})]})]},U.batch_id))]}),E&&s.jsxs(V,{className:"p-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"This weekâs headroom"}),s.jsx("div",{className:"mt-1 text-sm text-text-secondary",children:E.readable}),E.est_monthly_rand>0&&s.jsxs("div",{className:"mt-2 text-lg font-semibold tabular-nums text-text-primary",children:[ge(E.est_monthly_rand),s.jsxs("span",{className:"ml-2 text-xs font-normal text-text-secondary",children:["/ month across ",E.eligible_count," testable SKUs"]})]})]}),j.length>0&&s.jsxs(V,{className:"p-4 space-y-2",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Monday ritual â this weekâs 5"}),s.jsx("div",{className:"text-xs text-text-secondary",children:"Pre-selected. Highest velocity à unused RRP room. Confirm uncontested, then launch."}),j.map(U=>s.jsxs("label",{className:"flex items-center gap-3 text-sm py-0.5",children:[s.jsx("input",{type:"checkbox",disabled:!U.db_eligible,checked:!!_[U.offer_id],onChange:ce=>k(ue=>({...ue,[U.offer_id]:ce.target.checked}))}),s.jsxs("span",{className:"flex-1 truncate text-text-primary",children:[U.title??U.sku," ",s.jsxs("span",{className:"text-text-secondary",children:["· ",U.units_per_week.toFixed(1),"/wk",U.brand?` · ${U.brand}`:""]})]}),s.jsx("span",{className:"text-text-secondary",children:U.baseline_price!=null?ge(U.baseline_price):"â"})]},U.offer_id))]}),s.jsxs(V,{className:"p-4 space-y-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("div",{className:"flex-1 min-w-[12rem]",children:s.jsx(Re,{placeholder:"Search title or SKUâ¦",value:o,onChange:U=>l(U.target.value),onKeyDown:U=>U.key==="Enter"&&ve(!0)})}),s.jsxs(Tt,{value:c,onChange:U=>u(U.target.value),children:[s.jsx("option",{value:"",children:"All brands"}),d.map(U=>s.jsxs("option",{value:U.brand,children:[U.brand," (",U.count,")"]},U.brand))]}),s.jsx(W,{type:"button",onClick:()=>ve(!0),disabled:v,children:v?"Loadingâ¦":"Search"})]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:f,onChange:U=>m(U.target.checked)}),"Eligible only (hide on-repricer / inactive / too-slow / stocked-out / live promo)"]})]}),S&&!S.eligible.length&&s.jsxs(V,{className:"p-4 space-y-2",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Live check â nothing to launch"}),s.jsx("p",{className:"text-sm text-text-secondary",children:d$(S)}),s.jsxs("ul",{className:"text-xs text-text-secondary space-y-1",children:[S.ineligible.map(U=>s.jsxs("li",{children:[U.sku??U.offer_id,": ",U.db_reason??"ineligible"]},`in-${U.offer_id}`)),S.deferred.map(U=>s.jsxs("li",{children:[U.sku??U.offer_id,": ",oq(U.live_reason)]},`de-${U.offer_id}`))]})]}),s.jsxs(V,{className:"p-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{className:"text-sm font-semibold text-text-primary",children:["Catalogue (",x.length,y?"+":"",")"]}),s.jsxs("div",{className:"flex gap-2",children:[c&&s.jsx(W,{type:"button",variant:"outline",onClick:()=>{const U={..._};for(const ce of x)ce.db_eligible&&(U[ce.offer_id]=!0);k(U)},children:"Select visible in brand"}),s.jsx(W,{type:"button",onClick:ze,disabled:!Me.length||R,children:R?"Confirming catalogue & live PDPsâ¦":`Find candidates (${Me.length})`})]})]}),x.length===0&&!v&&s.jsx("div",{className:"text-sm text-text-secondary",children:"No matching offers. Experiments raise price on things you already own alone. The repricer defends things you donât. They never share a SKU."}),s.jsx("div",{className:"space-y-1",children:x.map(U=>s.jsxs("div",{className:"flex items-center gap-3 text-sm py-1",children:[s.jsx("input",{type:"checkbox",disabled:!U.db_eligible,checked:!!_[U.offer_id],onChange:ce=>k(ue=>({...ue,[U.offer_id]:ce.target.checked}))}),s.jsxs("div",{className:"flex-1 truncate",children:[s.jsx("span",{className:U.db_eligible?"text-text-primary":"text-text-secondary",children:s.jsx(Od,{onClick:()=>Ne({offerId:U.offer_id,title:U.title??U.sku}),children:U.title??U.sku??U.offer_id})}),s.jsxs("span",{className:"text-text-secondary",children:[" ","· ",U.units_per_week.toFixed(1),"/wk",U.brand?` · ${U.brand}`:"",U.db_eligible?"":` · ${U.db_reason}`]})]}),s.jsx("span",{className:"text-text-secondary",children:U.baseline_price!=null?ge(U.baseline_price):"â"})]},U.offer_id))}),y&&s.jsx("div",{className:"mt-3",children:s.jsx(W,{type:"button",variant:"outline",onClick:()=>ve(!1),disabled:v,children:v?"Loadingâ¦":"Load more"})})]}),s.jsx(Wp,{slug:e,offerId:(J==null?void 0:J.offerId)??null,title:J==null?void 0:J.title,open:!!J,onOpenChange:U=>!U&&Ne(null)})]})}function RBe({cands:e,selectedCount:t,prices:n,setPrices:r,ladders:a,setLadders:i,design:o,setDesign:l,appetite:c,direction:u,onAppetiteOrDirection:d,windowDays:h,setWindowDays:f,blockDays:m,setBlockDays:x,endPolicy:g,setEndPolicy:y,launchableCount:b,onContinue:v,onOpenHistory:w}){return s.jsxs("div",{className:"space-y-4",children:[s.jsxs(V,{className:"p-4 space-y-3",children:[s.jsxs("div",{className:"text-sm font-semibold text-text-primary",children:["Design the test (",e.eligible.length," testable of ",t," selected)"]}),s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3",children:[s.jsxs("label",{className:"text-sm",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Direction"}),s.jsxs(Tt,{value:u,onChange:_=>d(c,_.target.value),children:[s.jsx("option",{value:"up",children:"Price up (headroom)"}),s.jsx("option",{value:"down",children:"Price down (discount depth)"})]})]}),s.jsxs("label",{className:"text-sm",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Design"}),s.jsxs(Tt,{value:o,onChange:_=>l(_.target.value),children:[s.jsx("option",{value:"step_hold",children:"Step & hold â one price, full window"}),s.jsx("option",{value:"switchback",children:"Switchback â A/B/A/B for rigor"}),s.jsx("option",{value:"staircase",children:"Staircase â walk up to the ceiling"})]})]}),s.jsxs("label",{className:"text-sm",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Appetite"}),s.jsxs(Tt,{value:c,onChange:_=>d(_.target.value,u),children:[s.jsx("option",{value:"conservative",children:"Conservative"}),s.jsx("option",{value:"aggressive",children:"Aggressive"})]})]}),s.jsxs("label",{className:"text-sm",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Window (days)"}),s.jsx(Re,{value:h,onChange:_=>f(_.target.value)})]}),o==="switchback"&&s.jsxs("label",{className:"text-sm",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Block (days)"}),s.jsx(Re,{value:m,onChange:_=>x(_.target.value)})]}),s.jsxs("label",{className:"text-sm",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"On finish"}),s.jsxs(Tt,{value:g,onChange:_=>y(_.target.value),children:[s.jsx("option",{value:"revert",children:"Revert unless I say keep"}),s.jsx("option",{value:"keep_if_win",children:"Keep automatically if it wins"})]})]})]}),o==="switchback"&&s.jsx("div",{className:"text-xs text-text-secondary",children:"Switchback starts on the current price for the first block, then alternates. We measure test-arm days vs baseline-arm days inside the window â not a naïve before/after."}),o==="staircase"&&s.jsx("div",{className:"text-xs text-text-secondary",children:"Each rung is a few days. Per-rung move stays under 25%. This is directional discovery, not a p-value."})]}),e.eligible.map(_=>s.jsx(DBe,{c:_,design:o,price:n[_.offer_id]??"",onPrice:k=>r(j=>({...j,[_.offer_id]:k})),ladder:a[_.offer_id]??_.ladder??[],onLadder:k=>i(j=>({...j,[_.offer_id]:k})),onOpenHistory:()=>w(_)},_.offer_id)),e.ineligible.length>0&&s.jsxs(V,{className:"p-4 text-xs text-text-secondary",children:[e.ineligible.length," excluded by the live check:"," ",e.ineligible.map(_=>`${_.sku??_.offer_id} (${_.db_reason}
890)`).join(", ")]}),s.jsx("div",{className:"flex justify-end",children:s.jsxs(W,{type:"button",onClick:v,disabled:!b,children:["Review ",b," experiment",b===1?"":"s"]})})]})}function DBe({c:e,design:t,price:n,onPrice:r,ladder:a,onLadder:i,onOpenHistory:o}){var c;const l=e.suggestion_basis;return s.jsxs(V,{className:"p-4 space-y-2",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:s.jsx(Od,{onClick:o,children:e.title??e.sku??e.offer_id})}),s.jsxs("div",{className:"text-xs text-text-secondary",children:[e.units_per_week.toFixed(1),"/wk · box held",e.brand?` · ${e.brand}`:"",e.cost_known?"":" · margin unknown",l!=null&&l.cold_start?" · first test":" · we have history"]})]}),e.implied_margin_pct!=null&&s.jsxs(_n,{tone:"neutral",variant:"subtle",children:[e.implied_margin_pct,"% implied margin"]})]}),s.jsx("div",{className:"flex flex-wrap gap-1.5",children:(c=l==null?void 0:l.signals)==null?void 0:c.slice(0,6).map(u=>s.jsx(_n,{tone:"info",variant:"subtle",children:u},u))}),e.power&&s.jsx("div",{className:"text-xs text-text-secondary",children:e.power.readable}),s.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[s.jsx("span",{className:"text-text-secondary",children:e.baseline_price!=null?ge(e.baseline_price):"â"}),s.jsx("span",{className:"text-text-secondary",children:"â"}),t==="staircase"?s.jsx("div",{className:"flex flex-wrap gap-2",children:a.map((u,d)=>s.jsx(Re,{className:"w-20",value:String(u.price),onChange:h=>{const f=a.map((m,x)=>x===d?{...m,price:Number(h.target.value)||m.price}:m);i(f)}},d))}):s.jsx("div",{className:"w-24",children:s.jsx(Re,{value:n,onChange:u=>r(u.target.value)})}),e.suggested_price!=null&&s.jsxs(W,{type:"button",variant:"ghost",size:"sm",onClick:()=>r(String(e.suggested_price)),children:["Use suggestion ",ge(e.suggested_price)]}),e.contest_ceiling!=null&&s.jsxs("span",{className:"text-xs text-text-secondary",children:["ceiling ",ge(e.contest_ceiling)]})]})]})}function MBe({launchable:e,prices:t,ladders:n,design:r,appetite:a,direction:i,windowDays:o,endPolicy:l,busy:c,siblingWarning:u,canLaunch:d,canSendForApproval:h,onSaveDraft:f,onLaunch:m,onSendForApproval:x,onOpenHistory:g}){const y=e.filter(v=>v.price_mismatch),b=e.filter(v=>v.upcoming_promo);return s.jsxs(V,{className:"p-4 space-y-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Review"}),s.jsxs("p",{className:"text-sm text-text-secondary",children:[e.length," uncontested SKU",e.length===1?"":"s"," for ",o," days (",r.replace("_"," "),", ",a,", ",i==="down"?"discount-depth":"price-up","). Your repricer is untouched â none of these are enrolled on it.",l==="revert"?" When the window ends we revert unless you keep a winner.":" If gross profit wins weâll keep the test price automatically."," ","Save draft does not change Takealot prices."]}),u&&s.jsx("p",{className:"text-sm text-text-warning",children:u}),b.length>0&&s.jsxs("p",{className:"text-sm text-text-secondary",children:[b.map(v=>{var w;return(w=v.upcoming_promo)==null?void 0:w.title}).filter(Boolean).join(", ")||"A promotion"," ","is In Review â if it goes Live during this window we abort and revert."]}),y.length>0&&s.jsxs("p",{className:"text-sm text-text-warning",children:["Takealotâs live page price differs from the catalogue on ",y.length," SKU",y.length===1?"":"s",". We will treat the PDP price as baseline."]}),s.jsx("ul",{className:"text-sm space-y-1",children:e.map(v=>{const w=r==="staircase"?(n[v.offer_id]??[]).map(j=>ge(j.price)).join(" â "):ge(Number(t[v.offer_id])),_=v.stored_selling_price??v.baseline_price,k=v.pdp_selling_price;return s.jsxs("li",{className:"text-text-primary",children:[s.jsx(Od,{onClick:()=>g(v),children:v.title??v.sku})," ",s.jsx("span",{className:"text-text-secondary",children:v.price_mismatch&&k!=null&&_!=null?`catalogue ${ge(_)} / PDP ${ge(k)} â ${w}`:`${v.baseline_price!=null?ge(v.baseline_price):"â"} â ${w}`})]},v.offer_id)})}),s.jsxs("div",{className:"flex flex-wrap justify-end gap-2",children:[s.jsx(W,{type:"button",variant:"outline",onClick:f,disabled:c,
890children:c?"Savingâ¦":"Save without going live"}),h&&s.jsx(W,{type:"button",variant:"outline",onClick:x,disabled:c,children:"Send to seller"}),d&&s.jsx(W,{type:"button",onClick:m,disabled:c,children:c?"Creatingâ¦":`Launch ${e.length} experiment${e.length===1?"":"s"}`})]})]})}function $Be({slug:e,experiment:t,progress:n,open:r,onClose:a,onAborted:i,onOpenHistory:o}){var g,y;const[l,c]=p.useState(!1),u=t,d=n,h=(d==null?void 0:d.day_index)??0,f=(d==null?void 0:d.daily.map(b=>b.units))??[],m=((g=d==null?void 0:d.preview)==null?void 0:g.label)==="heading_for_stop"?"text-text-error":((y=d==null?void 0:d.preview)==null?void 0:y.label)==="looking_like_keep"?"text-text-success":"text-text-secondary";async function x(){if(!(!u||l)){c(!0);try{await K.experiments.abort(e,u.id),Ae.success("Aborted and reverted."),i()}catch(b){Ae.error("Abort failed",{description:String((b==null?void 0:b.message)||b)})}finally{c(!1)}}}return s.jsx(Cr,{open:r,onOpenChange:b=>{b||a()},children:s.jsxs(mr,{side:"right",size:"lg",children:[s.jsxs(Er,{children:[s.jsx(xr,{children:u?tc(u):"Experiment"}),s.jsx(Mr,{children:u?`${iq(u)} · ${u.status==="scheduled"?"scheduled â starts on the next hourly tick":`day ${h}/${u.window_days}`} · ${aq(u.design)}${u.direction==="down"?" · discount":""}`:"Live experiment"})]}),s.jsx(pr,{className:"p-4 space-y-4",children:u?s.jsxs(s.Fragment,{children:[s.jsxs(V,{className:"p-4",children:[s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary mb-3",children:"Heartbeat"}),s.jsxs("div",{className:"grid grid-cols-2 gap-x-4 gap-y-3",children:[s.jsx(Bi,{label:"Now",value:(d==null?void 0:d.last_list_price)!=null?ge(d.last_list_price):"â",strong:!0}),s.jsx(Bi,{label:"Buybox held",value:(d==null?void 0:d.buybox_held_pct)==null?"â":`${d.buybox_held_pct}%`}),s.jsx(Bi,{label:"Units so far",value:d?String(d.units_so_far):"â",hint:(d==null?void 0:d.expected_units)!=null?`vs ~${d.expected_units}`:void 0}),s.jsx(Bi,{label:"Last PDP check",value:d!=null&&d.last_pdp_at?Ca(d.last_pdp_at):"â"})]}),f.length>=2&&s.jsxs("div",{className:"mt-4",children:[s.jsx("div",{className:"text-xs text-text-secondary mb-1",children:"Units by day"}),s.jsx(Ws,{data:f,width:240,height:36,className:"text-text-brand"})]})]}),(d==null?void 0:d.expected_caption)&&s.jsxs(V,{className:"p-4",children:[s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary mb-1",children:"Expected units"}),s.jsx("p",{className:"text-sm text-text-primary",children:d.expected_caption}),s.jsx("p",{className:"mt-1 text-xs text-text-secondary",children:"This follows the weekday / week-of-month pattern, not a flat daily average."})]}),(d==null?void 0:d.preview)&&s.jsxs(V,{className:"p-4",children:[s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary mb-1",children:"Early read"}),s.jsx("p",{className:B("text-sm",m),children:sq(d.preview.label)})]}),u.offer_id!=null&&s.jsx("button",{type:"button",className:"text-sm text-text-brand hover:underline underline-offset-2",onClick:()=>o(Number(u.offer_id),tc(u)??null),children:"Open 12-week sales history"})]}):s.jsx("div",{className:"text-sm text-text-tertiary",children:"This experiment is no longer in the live list."})}),u&&s.jsxs(ml,{children:[s.jsx(W,{type:"button",variant:"outline",onClick:a,disabled:l,children:"Close"}),s.jsx(W,{type:"button",intent:"destructive",variant:"outline",onClick:()=>void x(),disabled:l,children:l?"Revertingâ¦":"Abort & revert"})]})]})})}function LBe({slug:e}){const[t,n]=p.useState(null),[r,a]=p.useState({}),[i,o]=p.useState(null),[l,c]=p.useState(null),u=p.useCallback(()=>{K.experiments.list(e).then(async h=>{const f=h.experiments.filter(x=>x.status==="scheduled"||x.status==="running");n(f);const m={};await Promise.all(f.map(async x=>{try{const g=await K.experiments.progress(e,x.id);m[x.id]=g.progress}catch{}})),a(m)}).catch(()=>n([]))},[e]);if(p.useEffect(()=>{u();const h=setInterval(u,6e4);return()=>clearInterval(h)},[u]),!t)return s.jsx(V,{className:"p-4 text-sm text-text-secondary",children:"Loadingâ¦"});if(!t.length)return s.jsxs(V,{className:"p-4 text-sm text-text-secondary space-y-2",children:[s.jsx("div",{className:"font-medium text-text-primary",children:"No experiments running."}),s.jsx("p",{children:"Experiments raise price (or test a discount) on listings you already own alone. The repricer defends listings you donât. They never share a SKU."}),s.jsx("p",{children:"Pick this weekâs 5 on the Run tab to start one."})]});const d=t.find(h=>h.id===i)??null;return s.jsxs("div",{className:"space-y-3",children:[t.map(h=>{var y,b,v;const f=r[h.id],m=(f==null?void 0:f.day_index)??0,x=(f==null?void 0:f.daily.map(w=>w.units))??[],g=((y=f==null?void 0:f.preview)==null?void 0:y.label)==="heading_for_stop"?"text-text-error":((b=f==null?void 0:f.preview)==null?void 0:b.label)==="looking_like_keep"?"text-text-success":"text-text-secondary";return s.jsxs(V,{role:"button",tabIndex:0,className:"p-4 space-y-3 text-left",interactive:!0,onClick:()=>o(h.id),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),o(h.id))},children:[s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-sm font-medium text-text-primary truncate",children:tc(h)}),s.jsxs("div",{className:"text-xs text-text-secondary mt-0.5",children:[ge(Number(h.baseline_price))," â ",ge(Number((v=h.test_prices)==null?void 0:v[0])),s.jsx("span",{className:"text-text-tertiary",children:" · "}),h.status==="scheduled"?"starts on the next hourly tick":`day ${m}/${h.window_days}`,s.jsx("span",{className:"text-text-tertiary",children:" · "}),aq(h.design),h.direction==="down"?" · discount":""]})]}),s.jsx(Ws,{data:x.length>=2?x:null,width:72,height:20,className:"text-text-brand shrink-0"}),s.jsx(fr,{className:"w-4 h-4 text-text-tertiary shrink-0 mt-0.5"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[s.jsx(Bi,{label:"Now",value:(f==null?void 0:f.last_list_price)!=null?ge(f.last_list_price):"â"}),s.jsx(Bi,{label:"Buybox",value:(f==null?void 0:f.buybox_held_pct)==null?"â":`${f.buybox_held_pct}%`}),s.jsx(Bi,{label:"Units",value:f?String(f.units_so_far):"â",hint:(f==null?void 0:f.expected_units)!=null?`vs ~${f.expected_units}`:void 0})]}),(f==null?void 0:f.preview)&&s.jsx("p",{className:B("text-xs",g),children:sq(f.preview.label)})]}
890,h.id)}),s.jsx($Be,{slug:e,experiment:d,progress:d?r[d.id]:void 0,open:!!d,onClose:()=>o(null),onAborted:()=>{o(null),u()},onOpenHistory:(h,f)=>{o(null),c({offerId:h,title:f})}}),s.jsx(Wp,{slug:e,offerId:(l==null?void 0:l.offerId)??null,title:l==null?void 0:l.title,open:!!l,onOpenChange:h=>!h&&c(null)})]})}function FBe(e){var t,n;return((n=(t=e.verdict)==null?void 0:t.next_action)==null?void 0:n.label)??(e.status==="aborted"?`Stopped (${e.abort_reason}). Reverted to ${ge(Number(e.baseline_price))}.`:null)}function BBe({slug:e}){const t=Rt(),[n,r]=p.useState(null),[a,i]=p.useState({}),[o,l]=p.useState(null),c=p.useCallback(()=>{K.experiments.list(e).then(async x=>{const g=x.experiments.filter(b=>b.status==="complete"||b.status==="aborted");r(g);const y={};await Promise.all(g.slice(0,20).map(async b=>{try{y[b.id]=(await K.experiments.progress(e,b.id)).progress}catch{}})),i(y)}).catch(()=>r([]))},[e]);p.useEffect(()=>c(),[c]);const u=p.useMemo(()=>{if(!n)return[];const x=new Map;for(const g of n){const y=g.batch_id||g.id,b=x.get(y)??[];b.push(g),x.set(y,b)}return[...x.values()]},[n]);async function d(x,g){try{await K.experiments.decide(e,x,g),Ae.success(g==="keep"?"Kept the test price.":"Reverted to baseline."),c()}catch(y){Ae.error("Failed",{description:String((y==null?void 0:y.message)||y)})}}async function h(x){try{await K.experiments.extend(e,x,7),Ae.success("Extended by 7 days."),t(`/sellers/${e}/automations/experiments/live`)}catch(g){Ae.error("Extend failed",{description:String((g==null?void 0:g.message)||g)})}}async function f(x,g){try{await K.experiments.retry(e,x,g),Ae.success(g==="smaller"?"Queued a smaller-step retry.":"Queued a bigger-step retry."),t(`/sellers/${e}/automations/experiments/live`)}catch(y){Ae.error("Retry failed",{description:String((y==null?void 0:y.message)||y)})}}async function m(x){try{await K.experiments.graduate(e,x),Ae.success("Parked on Watch â weâll alert if a rival appears."),c()}catch(g){Ae.error("Couldn't add to Watch",{description:String((g==null?void 0:g.message)||g)})}}return n?n.length?s.jsxs("div",{className:"space-y-4",children:[u.map(x=>s.jsxs("div",{className:"space-y-3",children:[x.length>1&&s.jsx(UBe,{group:x}),x.map(g=>s.jsx(zBe,{exp:g,progress:a[g.id],onDecide:d,onExtend:h,onRetry:f,onGraduate:m,onOpenHistory:()=>l({offerId:Number(g.offer_id),title:tc(g)??null})},g.id))]},x[0].batch_id||x[0].id)),s.jsx(Wp,{slug:e,offerId:(o==null?void 0:o.offerId)??null,title:o==null?void 0:o.title,open:!!o,onOpenChange:x=>!x&&l(null)})]}):s.jsxs(V,{className:"p-4 text-sm text-text-secondary space-y-2",children:[s.jsx("div",{className:"font-medium text-text-primary",children:"No completed experiments yet."}),s.jsx("p",{children:"When a test finishes youâll see units, revenue, and gross profit â with market drift subtracted â and a keep or revert call. Nothing stays changed unless you say so."})]}):s.jsx(V,{className:"p-4 text-sm text-text-secondary",children:"Loadingâ¦"})}function UBe({group:e}){const t=e.filter(i=>{var o;return((o=i.verdict)==null?void 0:o.recommendation)==="keep"}).length,n=e.filter(i=>{var o;return((o=i.verdict)==null?void 0:o.recommendation)==="revert"}).length,r=e.filter(i=>{var o;return((o=i.verdict)==null?void 0:o.recommendation)==="inconclusive"}).length,a=e.filter(i=>i.status==="aborted").length;return s.jsxs(V,{className:"p-3 text-sm text-text-secondary",children:["Batch of ",e.length,":"," ",s.jsxs("span",{className:"text-text-primary",children:[t," keep"]})," · ",n," revert · ",r," inconclusive · ",a," aborted"]})}function zBe({exp:e,progress:t,onDecide:n,onExtend:r,onRetry:a,onGraduate:i,onOpenHistory:o}){var m,x;const l=e.verdict,c=l==null?void 0:l.operator_decision,u=l==null?void 0:l.recommendation,d=u==="keep"?"text-success-text":u==="revert"?"text-text-secondary":"text-warning-text",h=(t==null?void 0:t.daily.map(g=>g.units))??[],f=FBe(e);return e.status==="aborted"?s.jsxs(V,{className:"p-4 space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"text-sm text-text-primary",children:["â ",s.jsx(Od,{onClick:o,children:tc(e)})]}),s.jsx(Ws,{data:h.length>=2?h:null,width:72,height:20})]}),s.jsx("div",{className:"text-xs text-text-secondary",children:f}),e.abort_reason==="stop_loss"&&s.jsx(W,{type:"button",variant:"outline",size:"sm",onClick:()=>a(e.id,"smaller"),children:"Retry a smaller step"})]}):s.jsxs(V,{className:"p-4 space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-sm text-text-primary",children:s.jsx(Od,{onClick:o,children:tc(e)})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ws,{data:h.length>=2?h:null,width:72,height:20,className:"text-text-brand"}),s.jsxs("div",{className:"text-xs text-text-secondary",children:[iq(e)," · ",e.window_days,"d"]})]})]}),l&&s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-x-4 gap-y-1 text-sm",children:[s.jsx(Bi,{label:"Units",value:Gg(l.units_delta_pct),hint:l.units_ci_pct?`CI ${l.units_ci_pct[0]}â¦${l.units_ci_pct[1]}%`:void 0}),s.jsx(Bi,{label:"Revenue",value:Gg(l.revenue_delta_pct)}),s.jsx(Bi,{label:"Gross profit",value:Gg(l.gross_profit_delta_pct),strong:!0}),s.jsx(Bi,{label:"Buybox held",value:l.buybox_held_pct==null?"â":`${l.buybox_held_pct}%`}),s.jsx(Bi,{label:"Market drift removed",value:Gg(l.market_drift_pct)})]}),(l==null?void 0:l.drift_english)&&s.jsx("div",{className:"text-xs text-text-secondary",children:l.drift_english}),s.jsxs("div",{className:B("text-sm font-medium",d),children:[u==="keep"&&"â Recommend keeping the test price.",u==="revert"&&"â Recommend reverting.",u==="inconclusive"&&"â No call â couldn't distinguish from noise."]}),f&&u!=="keep"&&u!=="revert"&&s.jsx("div",{className:"text-xs text-text-secondary",children:f}),u==="keep"&&(l==null?void 0:l.next_action)&&s.jsx("div",{className:"text-xs text-text-secondary",children:l.next_action.label}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[c?s.jsxs("span",{className:"text-xs text-text-secondary",children:["Decision: ",c==="keep"?`kept ${ge(Number((m=e.test_prices)==null?void 0:m[0]))}`:"reverted"]}):s.jsxs(s.Fragment,{children:[s.jsxs(W,{type:"button",onClick:()=>n(e.id,"keep"),children:["Keep ",ge(Number((x=e.test_prices)==null?void 0:x[0]))]}),s.jsxs(W,{type:"button",variant:"outline",onClick:()=>n(e.id,"revert"),children:["Revert to ",ge(Number(e.baseline_price))]})]}),u==="inconclusive"&&!c&&s.jsxs(s.Fragment,{children:[s.jsx(W,{type:"button",variant:"outline",size:"sm",onClick:()=>r(e.id),children:"Extend 7 days"}),s.jsx(W,{type:"button",variant:"outline",size:"sm",onClick:()=>a(e.id,"bigger"),children:"Bigger step"})]}),u==="keep"&&c==="keep"&&s.jsx(W,{type:"button",variant:"outline",size:"sm",onClick:()=>i(e.id),children:"Hold on Watch"}),u==="keep"&&!c&&s.jsx(W,{type:"button",variant:"ghost",size:"sm",onClick:()=>i(e.id),children:"Keep + Watch"})]})]})}function WBe({slug:e}){const t=`/sellers/${e}/automations/experiments`;return s.jsxs(s.Fragment,{children:[s.jsx(As,{tone:"subtle",items:[{key:"run",label:"Run",to:`${t}/run`},{key:"live",label:"Live",to:`${t}/live`},{key:"results",label:"Results",to:`${t}/results`}]}),s.jsxs("div",{className:"w-full p-4 md:p-6 space-y-4",children:[s.jsx(V,{className:"p-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(rF,{className:"w-5 h-5 text-text-secondary mt-0.5"}),s.jsxs("div",{className:"text-sm text-text-secondary",children:[s.jsx("div",{className:"font-semibold text-text-primary",children:"Pricing Experiments"}),"Raise (or carefully cut) price on listings you already own outright â then keep or revert with a profit readout. The repricer is never touched: if a SKU is on it, it canât be in an experiment, and the other way around. We confirm you still own the buybox every hour and revert the moment that stops being true."]})]})}),s.jsxs(ld,{children:[s.jsx(He,{path:"experiments/run",element:s.jsx(PBe,{slug:e})}),s.jsx(He,{path:"experiments/live",element:s.jsx(LBe,{slug:e})}),s.jsx(He,{path:"experiments/results",element:s.jsx(BBe,{slug:e})}),s.jsx(He,{path:"*",element:s.jsx(Yt,{to:`${t}/run`,replace:!0})})]})]})]})}var KBe=Object.defineProperty,lu=(e,t)=>
890KBe(e,"name",{value:t,configurable:!0}),_3="Switch",[HBe,yrt]=du(_3),[VBe,k3]=HBe(_3);function lq(e){const{__scopeSwitch:t,checked:n,children:r,defaultChecked:a,disabled:i,form:o,name:l,onCheckedChange:c,required:u,value:d="on",internal_do_not_use_render:h}=e,[f,m]=Jp({prop:n,defaultProp:a??!1,onChange:c,caller:_3}),[x,g]=p.useState(null),[y,b]=p.useState(null),v=p.useRef(!1),[w,_]=p.useReducer(N=>N+1,0),k=x?!!o||!!x.closest("form"):!0,j={checked:f,setChecked:m,disabled:i,control:x,setControl:g,name:l,form:o,value:d,hasConsumerStoppedPropagationRef:v,userInteractionCount:w,onUserInteraction:_,required:u,defaultChecked:a,isFormControl:k,bubbleInput:y,setBubbleInput:b};return s.jsx(VBe,{scope:t,...j,children:cq(h)?h(j):r})}lu(lq,"SwitchProvider");var qBe="SwitchTrigger",GBe=p.forwardRef(lu(function({__scopeSwitch:t,onClick:n,...r},a){const{control:i,form:o,value:l,disabled:c,checked:u,required:d,setControl:h,setChecked:f,hasConsumerStoppedPropagationRef:m,onUserInteraction:x,isFormControl:g,bubbleInput:y}=k3(qBe,t),b=oa(a,h),v=p.useRef(u);return p.useEffect(()=>{const w=o?i==null?void 0:i.ownerDocument.getElementById(o):i==null?void 0:i.form;if(w instanceof HTMLFormElement){const _=lu(()=>f(v.current),"reset");return w.addEventListener("reset",_),()=>w.removeEventListener("reset",_)}},[i,o,f]),s.jsx(ji.button,{type:"button",role:"switch","aria-checked":u,"aria-required":d,"data-state":j3(u),"data-disabled":c?"":void 0,disabled:c,value:l,...r,ref:b,onClick:cs(n,w=>{x(),f(_=>!_),y&&g&&(m.current=w.isPropagationStopped(),m.current||w.stopPropagation())})})},"SwitchTrigger")),YBe=p.forwardRef(lu(function(t,n){const{__scopeSwitch:r,name:a,checked:i,defaultChecked:o,required:l,disabled:c,value:u,onCheckedChange:d,form:h,...f}=t;return s.jsx(lq,{__scopeSwitch:r,checked:i,defaultChecked:o,disabled:c,required:l,onCheckedChange:d,name:a,form:h,value:u,internal_do_not_use_render:({isFormControl:m})=>s.jsxs(s.Fragment,{children:[s.jsx(GBe,{...f,ref:n,__scopeSwitch:r}),m&&s.jsx(QBe,{__scopeSwitch:r})]})})},"Switch")),ZBe="SwitchThumb",XBe=p.forwardRef(lu(function(t,n){const{__scopeSwitch:r,...a}=t,i=k3(ZBe,r);return s.jsx(ji.span,{"data-state":j3(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:n})},"SwitchThumb")),JBe="SwitchBubbleInput",QBe=p.forwardRef(lu(function({__scopeSwitch:t,onClick:n,...r},a){const{control:i,hasConsumerStoppedPropagationRef:o,userInteractionCount:l,checked:c,defaultChecked:u,required:d,disabled:h,name:f,value:m,form:x,bubbleInput:g,setBubbleInput:y}=k3(JBe,t),b=oa(a,y),v=_2(i),w=p.useRef(!1),_=p.useRef(c),k=p.useRef(l);p.useEffect(()=>{const N=g;if(!N)return;const E=window.HTMLInputElement.prototype,C=Object.getOwnPropertyDescriptor(E,"checked").set,T=l!==k.current;k.current=l;const S=_.current!==c;_.current=c;const O=!(T&&o.current);if(S&&C){w.current=!T;const R=new Event("click",{bubbles:O});C.call(N,c),N.dispatchEvent(R),w.current=!1}},[g,c,o,l]);const j=p.useRef(c);return s.jsx(ji.input,{type:"checkbox","aria-hidden":!0,defaultChecked:u??j.current,required:d,disabled:h,name:f,value:m,form:x,...r,tabIndex:-1,ref:b,onClick:cs(n,N=>{w.current&&N.stopPropagation()}),style:{...r.style,...v,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"SwitchBubbleInput"));function cq(e){return typeof e=="function"}lu(cq,"isFunction");function j3(e){return e?"checked":"unchecked"}lu(j3,"getState");const N3=p.forwardRef(({className:e,...t},n)=>s.jsx(YBe,{ref:n,className:B("relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-0 transition-colors","focus:outline-none focus-visible:shadow-focus","data-[state=checked]:bg-intent-brand data-[state=unchecked]:bg-surface-sunken","data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",e),...t,children:s.jsx(XBe,{className:B("pointer-events-none block h-4 w-4 rounded-full bg-surface shadow transition-transform","data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0.5")})}));N3.displayName="Switch";function uq(e){const t=e.trim().split(/\s+/);if(t.length!==5)return e;const[n,r,a,i,o]=t;return a==="*"&&i==="*"&&o==="*"&&/^\d+$/.test(n)&&/^\d+$/.test(r)?`Daily ${r.padStart(2,"0")}:${n.padStart(2,"0")} UTC`:a==="*"&&i==="*"&&/^\d+$/.test(o)&&/^\d+$/.test(n)&&/^\d+$/.test(r)?`Weekly ${["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][Number(o)]} ${r.padStart(2,"0")}:${n.padStart(2,"0")} UTC`:n.startsWith("*/")&&r==="*"&&a==="*"&&i==="*"&&o==="*"?`Every ${n.slice(2)} min`:e}function e7e({slug:e}){const[t,n]=p.useState(null),[r,a]=p.useState(null),[i,o]=p.useState(null),[l,c]=p.useState(null),u=p.useCallback(()=>
890{a(null),K.agents.list(e).then(h=>n(h.agents)).catch(h=>a(String((h==null?void 0:h.message)||h)))},[e]);p.useEffect(()=>{n(null),u()},[u]);async function d(h,f){c(h.key);try{const m=await K.agents.update(e,h.key,{enabled:f});n(x=>(x??[]).map(g=>g.key===m.key?m:g)),Ae.success(f?`${h.label} is on`:`${h.label} is paused`)}catch(m){Ae.error((m==null?void 0:m.message)||"Couldnât save")}finally{c(null)}}return s.jsxs("div",{className:"w-full p-4 md:p-6 space-y-4",children:[s.jsx(V,{className:"p-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(X6,{className:"w-5 h-5 text-text-secondary mt-0.5"}),s.jsxs("div",{className:"text-sm text-text-secondary",children:[s.jsx("div",{className:"font-semibold text-text-primary",children:"Agents"}),"Gadjet logs into Seller Portal as this storeâs agent and runs each recipe on the schedule you set. Bulk replenishment weekdays follow the Managed Account Replenishment Shipment grid â this toggle is the write gate. Leave a recipe paused until you want it to run unattended. Staff-only for now â sellers cannot see this tab. A recipe cannot be turned on while a dependency is missing or known failed."]})]})}),t&&s.jsx(i7e,{agents:t}),r&&s.jsxs(V,{className:"p-4 border-error-border bg-error-bg text-error-text",children:["Failed to load: ",r]}),!t&&!r&&s.jsx(V,{className:"p-4 text-sm text-text-secondary",children:"Loadingâ¦"}),t&&s.jsx("div",{className:"space-y-3",children:t.map(h=>s.jsx(t7e,{agent:h,busy:l===h.key,onToggle:f=>d(h,f),onEdit:()=>o(h)},h.key))}),i&&s.jsx(n7e,{agent:i,slug:e,onClose:()=>o(null),onSaved:h=>{n(f=>(f??[]).map(m=>m.key===h.key?h:m)),o(null)}})]})}function t7e({agent:e,busy:t,onToggle:n,onEdit:r}){return s.jsxs(V,{className:"p-4",children:[s.jsxs("div",{className:"flex flex-wrap items-start gap-3",children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-sm text-text-primary",children:e.label}),s.jsx(_n,{tone:e.enabled?"success":"neutral",variant:"subtle",children:e.enabled?"On":"Paused"}),e.blocked&&s.jsx(_n,{tone:"error",variant:"subtle",children:e.enabled?"On · canât run":"Canât run"})]})}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsxs(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",onClick:r,children:[s.jsx(Qi,{className:"w-3.5 h-3.5"}),"Edit"]}),s.jsx(N3,{checked:e.enabled,disabled:t||e.blocked&&!e.enabled,onCheckedChange:n,"aria-label":`${e.enabled?"Pause":"Enable"} ${e.label}`,title:e.blocked&&!e.enabled?a7e(e.dependencies):void 0})]})]}),s.jsx("p",{className:"mt-1 text-sm text-text-secondary",children:e.description}),e.key==="replen_upload"&&e.config_summary&&s.jsxs("div",{className:"mt-2 text-xs text-text-body",children:["SOP: ",e.config_summary]}),s.jsxs("div",{className:"mt-2 text-xs text-text-secondary",children:[uq(e.cron_schedule),s.jsxs("span",{className:"font-mono text-text-tertiary",children:[" · ",e.cron_schedule]})]}),s.jsx(o7e,{deps:e.dependencies})]})}const m$=[{value:"everything",label:"Everything I sell",help:"Broad velocity list â the Chilla canary."},{value:"top_sellers",label:"Top sellers by revenue",help:"Top 50 SKUs by revenue at risk."},{value:"urgent",label:"Running low or out at Takealot",help:"Selling SKUs with â¤7 days of DC cover."},{value:"balance",label:"Rebalance only (no new stock)",help:"1 unit to each empty DC."}],p$=[{value:"order_new",label:"Order new stock",help:"Do not cap to warehouse SoH. Needed for pure-Takealot-DC sellers."},{value:"soh_only",label:"Current SOH only",help:"Ship only what is already in the seller warehouse."}],x$=[{label:"Daily 06:00 UTC",value:"0 6 * * *"},{label:"Daily 07:00 UTC",value:"0 7 * * *"},{label:"Weekly Mon 06:00 UTC",value:"0 6 * * 1"},{label:"Weekly Tue 09:00 UTC",value:"0 9 * * 2"},{label:"Weekly Wed 08:00 UTC",value:"0 8 * * 3"}];function n7e({agent:e,slug:t,onClose:n,onSaved:r}){var b,v;const[a,i]=p.useState(e.cron_schedule),[o,l]=p.useState(()=>r7e(e.config)),[c,u]=p.useState(!1),[d,h]=p.useState(null),f=e.key==="replen_upload",m=(b=m$.find(w=>w.value===o.coverage))==null?void 0:b.help,x=(v=p$.find(w=>w.value===o.source))==null?void 0:v.help,g=x$.some(w=>w.value===a),y=async()=>{u(!0),h(null);try{const w=await K.agents.update(t,e.key,{cron_schedule:a.trim(),...f?{config:o}:{}});Ae.success(`Saved ${e.label}`),r(w)}catch(w){h((w==null?void 0:w.message)||"Failed to save")}finally{u(!1)}};return s.jsx(Cr,{open:!0,onOpenChange:w=>{w||n()},children:s.jsxs(mr,{side:"right",size:"lg",children:[s.jsxs(Er,{className:"pr-12",children:[s.jsxs(xr,{children:["Edit â ",e.label]}),s.jsx(Mr,{children:f?"Choose the replen SOP this store runs unattended, then the UTC hour. Weekdays still follow the Managed Account Replenishment Shipment grid.":"Standard 5-field cron expression (UTC). Use a preset or write your own. To pause instead, close this and use the toggle."})]}),s.jsxs(pr,{className:"p-4 space-y-4",children:[f&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx(Fs,{htmlFor:"agent-coverage",children:"Which SKUs?"}),s.jsx(Tt,{id:"agent-coverage",className:"mt-1",value:o.coverage,onChange:w=>l(_=>({..._,coverage:w.target.value})),children:m$.map(w=>s.jsx("option",{value:w.value,children:w.label},w.value))}),m&&s.jsx("p",{className:"mt-1 text-body-sm text-text-secondary",children:m})]}),s.jsxs("div",{children:[s.jsx(Fs,{htmlFor:"agent-source",children:"Source from"}),s.jsx(Tt,{id:"agent-source",className:"mt-1",value:o.source,onCh
890ange:w=>l(_=>({..._,source:w.target.value})),children:p$.map(w=>s.jsx("option",{value:w.value,children:w.label},w.value))}),x&&s.jsx("p",{className:"mt-1 text-body-sm text-text-secondary",children:x})]}),s.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx(Fs,{htmlFor:"agent-cover-days",children:"Cover the next"}),s.jsx(Tt,{id:"agent-cover-days",className:"mt-1",value:String(o.target_days),onChange:w=>l(_=>({..._,target_days:Number(w.target.value)})),children:[15,30,45,60].map(w=>s.jsxs("option",{value:w,children:[w," days"]},w))})]}),s.jsxs("div",{children:[s.jsx(Fs,{htmlFor:"agent-dc",children:"Ship to"}),s.jsxs(Tt,{id:"agent-dc",className:"mt-1",value:o.dc,onChange:w=>l(_=>({..._,dc:w.target.value})),children:[s.jsx("option",{value:"all",children:"All DCs"}),s.jsx("option",{value:"CPT",children:"CPT"}),s.jsx("option",{value:"JHB",children:"JHB"}),s.jsx("option",{value:"DBN",children:"DBN"})]})]})]}),s.jsxs("label",{className:"flex items-start gap-3 min-h-11",children:[s.jsx(ei,{className:"mt-1",checked:o.balance_topup,onCheckedChange:w=>l(_=>({..._,balance_topup:w===!0}))}),s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block text-body-sm font-medium text-text-primary",children:"Also top up empty DCs"}),s.jsx("span",{className:"block text-body-sm text-text-secondary",children:"1 unit of each selling SKU to a DC that is empty but stocked elsewhere."})]})]})]}),s.jsxs("div",{children:[s.jsx(Fs,{htmlFor:"agent-cron",children:"Cron expression"}),s.jsx(Re,{id:"agent-cron",type:"text",value:a,onChange:w=>i(w.target.value),inputSize:"sm",placeholder:"0 6 * * 1",className:"mt-1 font-mono",autoComplete:"off",autoCapitalize:"off",spellCheck:!1}),s.jsx("p",{className:"mt-1 text-body-sm text-text-secondary",children:uq(a.trim())})]}),s.jsxs("div",{children:[s.jsx(Fs,{htmlFor:"agent-cron-preset",children:"Preset"}),s.jsxs(Tt,{id:"agent-cron-preset",className:"mt-1",value:g?a:"",onChange:w=>{w.target.value&&i(w.target.value)},children:[!g&&s.jsx("option",{value:"",children:"Custom â keep current"}),x$.map(w=>s.jsx("option",{value:w.value,children:w.label},w.value))]})]}),d&&s.jsx("div",{className:"rounded-md border border-outline-error bg-surface-errorSubtle p-2 text-body-sm text-text-error",children:d})]}),s.jsxs(ml,{children:[s.jsx(W,{type:"button",onClick:n,intent:"neutral",variant:"outline",size:"sm",children:"Cancel"}),s.jsx(W,{type:"button",onClick:y,disabled:c||a.trim()==="",intent:"brand",size:"sm",children:c?"Savingâ¦":"Save"})]})]})})}function r7e(e){const t=e&&typeof e=="object"?e:{};return{coverage:t.coverage??"everything",source:t.source??"order_new",target_days:t.target_days??30,dc:t.dc??"all",balance_topup:t.balance_topup??!1}}function s7e(e){const t=new Map;for(const n of e)for(const r of n.dependencies||[])r.status==="missing"&&!t.has(r.key)&&t.set(r.key,r);return[...t.values()]}function a7e(e){const t=(e||[]).filter(n=>n.status!=="ok");return t.length===0?"Can't turn on":`Can't turn on â ${t.map(n=>n.label).join(", ")}`}function i7e({agents:e}){const t=s7e(e);return t.length===0?null:s.jsx(V,{className:"p-4 border-outline-warning bg-surface-warningSubtle",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(zn,{className:"w-5 h-5 text-text-warning mt-0.5 shrink-0"}),s.jsxs("div",{className:"min-w-0 text-sm text-text-body",children:[s.jsx("div",{className:"font-semibold text-text-primary",children:"Missing dependencies"}),s.jsx("p",{className:"mt-1 text-text-secondary",children:"These recipes cannot run until every listed dependency is Ready â vault logins and the Gmail OTP mailbox grant. Known-failed paths (for example a recipe that is not yet recorded) stay flagged on the row."}),s.jsx("ul",{className:"mt-2 space-y-1",children:t.map(n=>s.jsx("li",{children:s.jsx(dq,{dep:n})},n.key))})]})]})})}function o7e({deps:e}){const t=e||[];return t.length===0?null:s.jsx("ul",{className:"mt-3 space-y-1",children:t.map(n=>s.jsx("li",{children:s.jsx(dq,{dep:n})},n.key))})}function l7e(e){return e==="ok"?"success":e==="missing"?"warning":"error"}function c7e(e){return e==="ok"?"Ready":e==="missing"?"Missing":"Failed"}function dq({dep:e}){return s.jsxs("div",{className:"flex flex-col items-start gap-1 text-xs sm:flex-row sm:gap-2",children:[s.jsx(_n,{tone:l7e(e.status),variant:"subtle",className:"shrink-0",children:c7e(e.status)}),s.jsxs("p",{className:"min-w-0 flex-1 leading-snug",children:[s.jsx("span",{className:"font-medium text-text-primary",children:e.label}),s.jsxs("span",{className:"text-text-secondary",children:[" â ",e.message]}),e.fix_href&&e.status!=="ok"&&s.jsxs(s.Fragment,{children:[" ",s.jsx(st,{to:e.fix_href,className:"text-text-brand underline-offset-2 hover:underline",children:e.fix_label||"Fix"})]}),!e.fix_href&&e.fix_label&&e.status!=="ok"&&s.jsxs("span",{className:"text-text-secondary",children:[" ",e.fix_label]})]})]})}function Kp(e){return e?e.seller_display_name?e.seller_display_name:e.seller_channel==="retail"?"Takealot Retail":e.seller_id!=null?`Seller #${e.seller_id}`:null:null}function u7e(e,t){const n=t.trim().toLowerCase().replace(/^(tsin|plid)\s+/,"");if(!n)return!0;const r=(e.seller_sku??"").toLowerCase(),a=(e.offer_title??e.productline_title??"").toLowerCase(),i=e.tsin_id!=null?String(e.tsin_id).toLowerCase():"",o=e.plid!=null?String(e.plid).toLowerCase():"";return r.includes(n)||a.includes(n)||i.includes(n)||o.includes(n)}function d7e(e){var n;const t=(n=e.next_competitor)==null?void 0:n.price;return t??(e.market_best_price!=null&&e.is_buybox_owner===!1?e.market_best_price:null)}function h7e(e){const t=Kp(e.next_competitor),n=d7e(e);return t&&n!=null?`vs ${t} at R${n}`:t?`vs ${t}`:n!=null?`lowest rival at R${n}`:null}const f7e={compete_undercut:"Undercut a rival",share_match:"Matched a rival",creep_compete:"Nudged up while winning",creep_share:"Nudged up while winning",uncontested:"Raised â no competition",uncontested_pdp:"Raised â confirmed sole seller",hit_floor_still_losing:"Held at floor â can't win profitably here",at_preferred:"At your target price",held_at_floor:"Held at your floor",no_change:"No change needed",no_offer:"No active offer",no_market_data:"Waiting for market data",unbuyable:"Paused â listing not buyable",synthetic_offer:"Skipped â test offer"},m7e=new Set(["compete_undercut","share_match","creep_compete","creep_share","hit_floor_still_losing"]);function p7e(e){return e.replace(/_/g," ").replace(/^\w/,t=>t.toUpperCase())}function hq(e){const t=e.reason??"",n=f7e[t]??(t?p7e(t):"Price change"),r=m7e.has(t)?h7e(e):null;return{label:n,detail:r}}const af={basic:"Basic",standard:"Standard",boosted:"Boosted",super_boosted:"Super Boosted",watch:"Watch"}
890,x7e={basic:0,standard:1,boosted:2,super_boosted:3,watch:4},US=["basic","standard","boosted","super_boosted","watch"],zS=["compete","share"],S3={compete:"Compete",share:"Share"},g$=["winning","losing","unknown","not_buyable","not_scanned","disabled"],fq={winning:"Winning",losing:"Losing",unknown:"Can't confirm",not_buyable:"Not buyable",not_scanned:"Not scanned",disabled:"Disabled"};function kv(e){return e.enabled?e.last_run_at==null?"not_scanned":e.buybox_state!=null?e.buybox_state:e.is_buybox_owner?"winning":"losing":"disabled"}function g7e(e){return e.current_margin_pct!=null&&e.current_margin_pct<0||(e.min_margin_pct!=null||e.min_roi_pct!=null)&&e.catalogue_cost_excl_vat==null}const y$=["contested","sole","unscanned"],y7e={contested:"Has competitor",sole:"Sole seller",unscanned:"Unscanned"};function b7e(e){return e.competing_offers_count==null?"unscanned":e.competing_offers_count>1?"contested":"sole"}function C3(e,t=Date.now()){if(!e.enabled)return!1;const n=e.tier==="watch"?3*1440:1440;if(!e.last_scan_at)return!0;const r=new Date(e.last_scan_at).getTime();return Number.isFinite(r)?(t-r)/6e4>n:!0}function v7e(e,t=Date.now()){if(!e)return"never";const n=new Date(e).getTime();if(!Number.isFinite(n))return"never";const r=Math.floor((t-n)/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const a=Math.floor(r/60);return a<48?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Hx({icon:e,title:t,right:n}){return s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary",children:[e,s.jsx("span",{children:t})]}),n]})}function ad({label:e,value:t,sub:n}){return s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface p-3",children:[s.jsx("div",{className:"text-xs font-medium text-text-tertiary uppercase tracking-wide",children:e}),s.jsx("div",{className:"mt-1 text-lg font-semibold text-text-primary",children:t}),n!=null&&s.jsx("div",{className:"mt-0.5 text-xs text-text-secondary",children:n})]})}const Bk={tier:"Tier",mode:"Mode",enabled:"Enabled / paused",hold_at_floor:"Hold at floor",min_price:"Floor (R)",preferred_price:"Preferred (R)",min_margin_pct:"Min margin %",min_roi_pct:"Min ROI %"};function w7e({open:e,slug:t,subscriptions:n,onClose:r,onApplied:a}){const[i,o]=p.useState("tier"),[l,c]=p.useState("basic"),[u,d]=p.useState(!1),h=n.length,f=y=>{o(y),c(y==="tier"?"basic":y==="mode"?"compete":y==="enabled"||y==="hold_at_floor"?"true":"")},m=()=>{switch(i){case"tier":return{patch:{tier:l}};case"mode":return{patch:{mode:l}};case"enabled":return{patch:{enabled:l==="true"}};case"hold_at_floor":return{patch:{hold_at_floor:l==="true"}};case"min_price":case"preferred_price":{const y=Number(l);return!Number.isFinite(y)||y<=0?{error:"Enter a Rand amount above 0."}:{patch:{[i]:Math.round(y)}}}case"min_margin_pct":case"min_roi_pct":{if(l.trim()==="")return{patch:{[i]:null}};const y=Number(l);return!Number.isFinite(y)||y<0?{error:"Enter a percentage ⥠0 (or leave blank to clear)."}:{patch:{[i]:y}}}}},x=async()=>{var v;const{patch:y,error:b}=m();if(b||!y){Ae.error(b??"Invalid value.");return}d(!0);try{const w=await K.bulkUpdateSubscriptions(t,{ids:n.map(j=>j.id),patch:y}),_=w.applied.length,k=w.skipped.length;if(k===0)Ae.success(`Updated ${_} SKU${_===1?"":"s"}.`);else{const j=new Map;for(const E of w.skipped){const A=E.error==="no_capacity"?"no slots free":E.error??"error";j.set(A,(j.get(A)??0)+1)}const N=[...j.entries()].map(([E,A])=>`${A} ${E}`).join(", ");Ae.warning(`Updated ${_}, skipped ${k} â ${N}.`)}a()}catch(w){Ae.error("Bulk update failed.",{description:(v=w==null?void 0:w.body)==null?void 0:v.message})}finally{d(!1)}},g=i==="min_price"||i==="preferred_price";return s.jsx(js,{open:e,onOpenChange:y=>!y&&r(),children:s.jsxs(Ns,{className:"max-w-md",children:[s.jsx(La,{children:s.jsxs(ma,{children:["Bulk edit ",h," SKU",h===1?"":"s"]})}),s.jsxs(Oa,{className:"space-y-3",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Field"}),s.jsx(Tt,{value:i,onChange:y=>f(y.target.value),children:Object.keys(Bk).map(y=>s.jsx("option",{value:y,children:Bk[y]},y))})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs font-medium text-text-secondary block mb-1",children:Bk[i]}
890),i==="tier"?s.jsx(Tt,{value:l,onChange:y=>c(y.target.value),children:US.map(y=>s.jsx("option",{value:y,children:af[y]},y))}):i==="mode"?s.jsx(Tt,{value:l,onChange:y=>c(y.target.value),children:zS.map(y=>s.jsx("option",{value:y,children:S3[y]},y))}):i==="enabled"?s.jsxs(Tt,{value:l,onChange:y=>c(y.target.value),children:[s.jsx("option",{value:"true",children:"Enabled"}),s.jsx("option",{value:"false",children:"Paused"})]}):i==="hold_at_floor"?s.jsxs(Tt,{value:l,onChange:y=>c(y.target.value),children:[s.jsx("option",{value:"true",children:"On"}),s.jsx("option",{value:"false",children:"Off"})]}):s.jsx(Re,{type:"number",inputMode:"decimal",value:l,onChange:y=>c(y.target.value),placeholder:i==="min_margin_pct"||i==="min_roi_pct"?"blank = clear floor":"Rand amount"})]}),g&&s.jsxs("p",{className:"text-xs text-text-warning",children:["â This sets the same Rand value on all ",h," selected SKUs â it does not adjust per-SKU cost. A profit-floor margin/ROI % is the safer way to protect margin across mixed SKUs. SKUs where the result breaks the floor ⤠preferred rule are reported as skipped."]})]}),s.jsxs(da,{children:[s.jsx(W,{variant:"outline",onClick:r,disabled:u,children:"Cancel"}),s.jsx(W,{onClick:x,disabled:u||h===0,children:u?"Applyingâ¦":`Apply to ${h}`})]})]})})}function Yg(e,t){if(!e)return[];const n=new Set(t);return e.split(",").filter(r=>n.has(r))}function _7e(e){const{selected:t,allFilteredSelected:n,someSelected:r,toggleAllFiltered:a,toggleOne:i,slug:o,onEdit:l}=e;return[{key:"select",label:"",sticky:!0,stopRowClick:!0,className:"w-8",header:s.jsx("input",{type:"checkbox",className:"rounded border-outline",checked:n,ref:c=>{c&&(c.indeterminate=r&&!n)},onChange:a,title:"Select all matching rows","aria-label":"Select all matching rows"}),render:c=>s.jsx("input",{type:"checkbox",className:"rounded border-outline",checked:t.has(c.id),onChange:()=>i(c.id),"aria-label":`Select ${c.seller_sku??"SKU"}`})},{key:"sku",label:"SKU",sortable:!0,getValue:c=>c.seller_sku,render:c=>s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"inline-flex items-center gap-1.5 font-medium text-text-primary",children:[c.seller_sku??"â",c.auto_managed&&s.jsx("span",{className:"text-[10px] px-1 py-0.5 rounded bg-surface-brandSubtle text-text-brand",title:"Watch-managed â auto-enables repricing when a competitor appears",children:"auto"})]}),s.jsx(C7e,{s:c})]})},{key:"tier",label:"Tier",sortable:!0,getValue:c=>x7e[c.tier],render:c=>s.jsx("span",{className:"text-text-secondary",children:af[c.tier]})},{key:"mode",label:"Mode",sortable:!0,getValue:c=>c.mode,render:c=>s.jsx("span",{className:"text-text-secondary",children:S3[c.mode]})},{key:"current",label:"Current",sortable:!0,align:"right",getValue:c=>c.current_price,render:c=>c.current_price!=null?`R${c.current_price}`:"â"},{key:"margin",label:"Margin",sortable:!0,align:"right",getValue:c=>c.current_margin_pct,render:c=>s.jsx(j7e,{s:c})},{key:"floor",label:"Floor",sortable:!0,align:"right",getValue:c=>c.min_price,render:c=>s.jsxs(s.Fragment,{children:[c.min_price!=null?`R${c.min_price}`:"â",(c.min_margin_pct!=null||c.min_roi_pct!=null)&&s.jsxs("div",{className:"text-[10px] font-medium text-text-brand",title:c.catalogue_cost_excl_vat==null?"Profit floor set but no Master Catalogue cost â falls back to the Floor (R)":"Profit floor: the repricer won't price below this margin/ROI",children:[[c.min_margin_pct!=null?`â¥${c.min_margin_pct}%m`:null,c.min_roi_pct!=null?`â¥${c.min_roi_pct}% ROI`:null].filter(Boolean).join(" · "),c.catalogue_cost_excl_vat==null?" â ":""]})]})},{key:"preferred",label:"Preferred",sortable:!0,align:"right",getValue:c=>c.preferred_price,render:c=>c.preferred_price!=null?`R${c.preferred_price}`:"â"},{key:"best",label:"Best",sortable:!0,align:"right",getValue:c=>c.best_price,render:c=>c.best_price!=null?`R${c.best_price}`:"â"},{key:"competitor",label:"Competitor",sortable:!0,getValue:c=>{var u,d;return Kp((u=c.last_decision)==null?void 0:u.next_competitor)??Kp((d=c.last_decision)==null?void 0:d.buybox_winner)??""},render:c=>s.jsx(E7e,{s:c})},{key:"sellers",label:"Sellers",sortable:!0,align:"right",getValue:c=>c.competing_offers_count,render:c=>s.jsx("span",{className:B("tabular-nums",c.competing_offers_count==null?"text-text-tertiary":c.competing_offers_count>1?"text-text-primary font-medium":"text-text-tertiary"),title:c.competing_offers_count==null?"Not yet scanned":c.competing_offers_count>1?`${c.competing_offers_count}
890 sellers on the buybox (you + ${c.competing_offers_count-1} competitor${c.competing_offers_count-1===1?"":"s"})`:"Sole seller â no competitors",children:c.competing_offers_count??"â"})},{key:"status",label:"Status",sortable:!0,getValue:c=>kv(c),render:c=>{const u=kv(c);return s.jsxs("span",{className:"text-xs text-text-secondary",title:u==="unknown"?"This is a lead-time offer, so the buybox can't be settled from synced data â it needs a live product-page read, and the last reprice didn't capture one. Not the same as losing.":u==="not_buyable"?"Takealot isn't currently selling this offer, so there's no buybox to win or lose. Fix the listing or stock position and the repricer picks it up again automatically.":void 0,children:[fq[u],c.last_decision&&s.jsx(S7e,{d:c.last_decision})]})}},{key:"scan",label:"Last scan",sortable:!0,title:"When this SKUâs product page was last scanned. Amber means older than 24 hours (3 days on Watch).",getValue:c=>c.last_scan_at?new Date(c.last_scan_at).getTime():0,render:c=>s.jsx(N7e,{s:c})},{key:"actions",label:"Actions",align:"right",stopRowClick:!0,render:c=>s.jsxs("div",{className:"inline-flex items-center gap-1",children:[s.jsx("button",{type:"button",onClick:()=>l(c),title:"Edit SKU","aria-label":"Edit SKU",className:"inline-flex items-center justify-center rounded p-1 text-text-tertiary hover:text-text-brand hover:bg-surface-brandSubtle transition-colors",children:s.jsx(Qi,{className:"w-4 h-4"})}),s.jsx(Kd,{plid:c.plid,sellPrice:c.current_price,slug:o,sku:c.seller_sku,title:c.offer_title??c.productline_title})]})}]}function k7e({subscriptions:e,slug:t,onEdit:n,onEnrol:r,onAdd:a,onChanged:i}){const[o,l]=ki(),c=o.get("q")??"",u=Yg(o.get("tier"),US),d=Yg(o.get("mode"),zS),h=Yg(o.get("status"),g$),f=Yg(o.get("comp"),y$),m=o.get("enabled")==="1",x=o.get("atrisk")==="1",g=o.get("stale")==="1",y=c.length>0||u.length>0||d.length>0||h.length>0||f.length>0||m||x||g,b=p.useCallback(P=>{l(F=>{const Z=new URLSearchParams(F);for(const[D,H]of Object.entries(P))H==null?Z.delete(D):Z.set(D,H);return Z},{replace:!0})},[l]),v=p.useCallback((P,F,Z)=>{const D=F.includes(Z)?F.filter(H=>H!==Z):[...F,Z];b({[P]:D.length?D.join(","):null,page:null})},[b]),w=p.useCallback(()=>{b({q:null,tier:null,mode:null,status:null,comp:null,enabled:null,atrisk:null,stale:null,page:null})},[b]),_=p.useMemo(()=>{const P=c.trim().toLowerCase(),F=new Set(u),Z=new Set(d),D=new Set(h),H=new Set(f);return e.filter(Y=>!(m&&!Y.enabled||x&&!g7e(Y)||g&&!C3(Y)||F.size>0&&!F.has(Y.tier)||Z.size>0&&!Z.has(Y.mode)||D.size>0&&!D.has(kv(Y))||H.size>0&&!H.has(b7e(Y))||P&&!u7e(Y,P)))},[e,c,u,d,h,f,m,x,g]),[k,j]=p.useState(()=>new Set),[N,E]=p.useState(!1),A=p.useMemo(()=>new Set(_.map(P=>P.id)),[_]);p.useEffect(()=>{j(P=>{let F=!1;const Z=new Set;for(const D of P)A.has(D)?Z.add(D):F=!0;return F?Z:P})},[A]);const C=_.length>0&&k.size===_.length,T=k.size>0,S=p.useCallback(P=>{j(F=>{const Z=new Set(F);return Z.has(P)?Z.delete(P):Z.add(P),Z})},[]),O=p.useCallback(()=>{j(P=>P.size===A.size?new Set:new Set(A))},[A]),R=p.useCallback(()=>j(new Set),[]),I=p.useMemo(()=>_.filter(P=>k.has(P.id)),[_,k]),$=p.useMemo(()=>_7e({selected:k,allFilteredSelected:C,someSelected:T,toggleAllFiltered:O,toggleOne:S,slug:t,onEdit:n}),[k,C,T,O,S,t,n]);return s.jsxs(s.Fragment,{children:[s.jsxs(V,{className:"p-0 overflow-hidden",children:[s.jsx("div",{className:"p-4 pb-3",children:s.jsx(Hx,{icon:s.jsx(ix,{className:"w-4 h-4"}),title:"SKUs",right:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xs text-text-tertiary",children:e.length===0?"no enrolments yet":y?`${_.length} of ${e.length}`:`${e.length} enrolled`}),s.jsxs(W,{variant:"outline",size:"sm",onClick:r,children:[s.jsx(ti,{className:"w-3.5 h-3.5 mr-1"}),"Enrol SKUs"]}),s.jsxs(W,{size:"sm",onClick:a,children:[s.jsx(In,{className:"w-3.5 h-3.5 mr-1"}),"Add SKUs"]})]})})}),e.length===0?s.jsxs("div",{className:"px-4 pb-4 text-sm text-text-secondary",children:["No SKUs enrolled yet. Click ",s.jsx("b",{children:"Add SKUs"})," to search your listings and enrol them one at a time, or ",s.jsx("b",{children:"Enrol SKUs"})," to bulk-upload a spreadsheet."]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"px-4 pb-3 border-b border-outline-subtle space-y-2",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsx(pc,{fieldClassName:"w-64",type:"text",placeholder:"Search SKU, title, TSINâ¦",value:c,onChange:P=>b({q:P.target.value||null,page:null})}),s.jsxs("label",{className:"flex items-center gap-2 text-sm text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:m,onChange:P=>b({enabled:P.target.checked?"1":null,page:null}),className:"rounded border-outline"}),"Enabled only"]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm text-text-secondary cursor-pointer",title:"SKUs selling at a loss, or with a profit floor that has no cost to enforce it",children:[s.jsx("input",{type:"checkbox",checked:x,onChange:P=>b({atrisk:P.target.checked?"1":null,page:null}),className:"rounded border-outline"}),"At-risk only"]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm text-text-secondary cursor-pointer",title:"Enabled SKUs whose last product-page scan is older than 24 hours (3 days on Watch) â or never scanned",children:[s.jsx("input",{type:"checkbox",checked:g,onChange:P=>b({stale:P.target.checked?"1":null,page:null}),className:"rounded border-outline"}),"Stale scan"]}),y&&s.jsx(W,{variant:"ghost",size:"sm",onClick:w,children:"Clear filters"})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[s.jsx(Zg,{label:"Tier",options:US.map(P=>({value:P,label:af[P]})),selected:u,onToggle:P=>v("tier",u,P)}),s.jsx(Zg,{label:"Mode",options:zS.map(P=>({value:P,label:S3[P]})),selected:d,onToggle:P=>v("mode",d,P)}),s.jsx(Zg,{label:"Status",options:g$.map(P=>({value:P,label:fq[P]})),selected:h,onToggle:P=>v("status",h,P)}),s.jsx(Zg,{label:"Competition",options:y$.map(P=>({value:P,label:y7e[P]})),selected:f,onToggle:P=>v("comp",f,P)})]})]}),T&&s.jsxs("div",{className:"mx-4 mb-3 flex flex-wrap items-center justify-between gap-2 rounded-md border border-outline-subtle bg-surface-brandSubtle px-3 py-2 text-sm",children:[s.jsxs("span",{className:"font-medium text-text-primary",children:[k.size," selected"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(W,{size:"sm",onClick:()=>E(!0),children:"Bulk editâ¦"}),s.jsx(W,{size:"sm",variant:"ghost",onClick:R,children:"Clear"})]})]}),s.jsx(dt,{rows:_,columns:$,getRowKey:P=>P.id,persist:!0,sortUrlKey:"sort",pageKey:"page",sizeKey:"size",pageSizes:[50,100,200],defaultSort:{key:"sku",direction:"asc"},empty:{title:"No SKUs match these filters.",hint:"Clear filters to
890see all enrolled SKUs."},rowClassName:P=>k.has(P.id)?"bg-surface-brandSubtle/40":void 0})]})]}),s.jsx(w7e,{open:N,slug:t,subscriptions:I,onClose:()=>E(!1),onApplied:()=>{E(!1),R(),i()}})]})}function j7e({s:e}){const t=e.current_margin_pct;if(t==null)return e.catalogue_cost_excl_vat==null?s.jsx("span",{className:"text-[11px] text-text-warning",title:"No Master Catalogue cost loaded â realized margin can't be computed and any profit floor falls back to the plain Floor (R).",children:"no cost â "}):s.jsx("span",{className:"text-text-tertiary",title:"Takealot fee estimate not yet available for this offer",children:"â"});const n=t<0?"text-text-error font-medium":t<5?"text-text-warning":"text-text-primary",r=e.current_roi_pct;return s.jsxs("span",{className:B("tabular-nums",n),title:"Realized margin on the current price (after Takealot fees + cost)"+(r!=null?` · ROI ${r.toFixed(0)}%`:""),children:[t.toFixed(0),"%"]})}function N7e({s:e}){const t=C3(e),n=e.last_scan_at?Ca(e.last_scan_at):null;return s.jsx("span",{className:B("tabular-nums text-xs",t?"text-text-warning font-medium":"text-text-secondary"),title:n?t?`${n} · older than 24 hours (3 days on Watch)`:n:"Never scanned",children:v7e(e.last_scan_at)})}function S7e({d:e}){const{label:t,detail:n}=hq(e),r=e.push_status==="failed",a=e.at?Ca(e.at):null,i=[t,n,a?`· ${a}`:null].filter(Boolean).join(" ");return s.jsxs("div",{className:B("mt-0.5 max-w-[12rem] truncate text-[11px]",r?"text-text-error":"text-text-tertiary"),title:r?`Last push failed â ${i}`:i,children:[r?"â ":"",t]})}function C7e({s:e}){const t=e.offer_title??e.productline_title,n=e.tsin_id!=null?String(e.tsin_id):null,r=e.plid?`https://www.takealot.com/x/PLID${e.plid}`:null;return s.jsxs(s.Fragment,{children:[t?r?s.jsxs("a",{href:r,target:"_blank",rel:"noopener noreferrer",title:`${t} â open on Takealot`,className:"mt-0.5 flex max-w-[20rem] items-center gap-1 text-xs text-text-secondary hover:text-text-brand hover:underline",children:[s.jsx("span",{className:"truncate",children:t}),s.jsx(Qt,{className:"w-3 h-3 shrink-0 opacity-70"})]}):s.jsx("div",{className:"mt-0.5 max-w-[20rem] truncate text-xs text-text-secondary",title:t,children:t}):null,n&&s.jsxs("div",{className:"mt-0.5 font-mono text-[10px] text-text-tertiary",title:"Takealot TSIN",children:["TSIN ",n]})]})}function E7e({s:e}){var o,l;const t=((o=e.last_decision)==null?void 0:o.next_competitor)??((l=e.last_decision)!=null&&l.buybox_winner&&!e.is_buybox_owner?e.last_decision.buybox_winner:null);if(!t)return s.jsx("span",{className:"text-text-tertiary",children:"â"});const n=Kp(t)??"Unknown seller",r=[t.price!=null?`R${t.price}`:null,t.seller_score!=null?`${Number(t.seller_score).toFixed(1)}â
`:null,t.is_lead_time?"slower":null].filter(Boolean),a=[n,t.seller_id!=null?`seller ${t.seller_id}`:null,t.seller_reviews!=null?`${t.seller_reviews} reviews`:null,t.seller_vat_registered?"VAT registered":null].filter(Boolean).join(" · "),i=s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"truncate text-text-primary",children:n}),r.length>0&&s.jsx("div",{className:"text-[10px] text-text-tertiary tabular-nums",children:r.join(" · ")})]});return t.seller_url?s.jsx("a",{href:t.seller_url,target:"_blank",rel:"noopener noreferrer",title:`${a} â open storefront`,className:"block max-w-[12rem] hover:text-text-brand",onClick:c=>c.stopPropagation(),children:i}):s.jsx("div",{className:"max-w-[12rem]",title:a,children:i})}function Zg({label:e,options:t,selected:n,onToggle:r}){const a=new Set(n);return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-xs uppercase tracking-wide text-text-tertiary",children:e}),s.jsx("div",{className:"flex flex-wrap items-center gap-1",children:t.map(i=>{const o=a.has(i.value);return s.jsx("button",{type:"button",onClick:()=>r(i.value),className:B("px-2.5 py-1 rounded-full text-xs border transition-colors",o?"bg-surface-brandSubtle border-outline-brand text-text-brand":"bg-surface border-outline-subtle text-text-secondary hover:text-text-primary hover:border-outline"),children:i.label},i.value)})})]})}function A7e({overview:e,slug:t,onEdit:n,onEnrol:r,onAdd:a,onChanged:i}){const o=e.capacity.tiers.find(l=>l.tier==="watch");return s.jsxs("div",{className:"space-y-4",children:[s.jsx(O7e,{slug:t,watchTile:o,onChanged:i}),e.leadtime_control_enabled&&s.jsx(T7e,{slug:t,value:e.leadtime_default,onCh
890anged:i}),s.jsx(k7e,{subscriptions:e.subscriptions,slug:t,onEdit:n,onEnrol:r,onAdd:a,onChanged:i})]})}function T7e({slug:e,value:t,onChanged:n}){const[r,a]=p.useState(t.policy),[i,o]=p.useState(t.threshold_pct!=null?String(t.threshold_pct):""),[l,c]=p.useState(!1),u=r!==t.policy||r==="threshold"&&Number(i||0)!==(t.threshold_pct??0);async function d(){var h;if(!l){c(!0);try{await K.setLeadtimeDefault(e,{policy:r,threshold_pct:r==="threshold"&&i.trim()!==""?Number(i):null}),Ae.success("Lead-time default updated."),n()}catch(f){const m=f;Ae.error("Failed to update.",{description:(h=m.body)==null?void 0:h.message})}finally{c(!1)}}}return s.jsx(V,{className:"p-4",children:s.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Slower (lead-time) competitors"}),s.jsx("div",{className:"text-xs text-text-secondary",children:"How the repricer treats rivals who are cheaper but ship slower. Set a per-SKU override in any listing to differ from this default."})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(Tt,{value:r,onChange:h=>a(h.target.value),children:[s.jsx("option",{value:"compete_all",children:"Compete with all"}),s.jsx("option",{value:"ignore_leadtime",children:"Win on speed"}),s.jsx("option",{value:"threshold",children:"Only if much cheaperâ¦"})]}),r==="threshold"&&s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(Re,{type:"number",min:1,max:90,step:1,value:i,onChange:h=>o(h.target.value),placeholder:"10",className:"w-16"}),s.jsx("span",{className:"text-xs text-text-secondary",children:"%"})]}),s.jsx(W,{type:"button",onClick:d,disabled:l||!u,children:l?"Savingâ¦":"Save"})]})]})})}function O7e({slug:e,watchTile:t,onChanged:n}){const[r,a]=p.useState(!1),i=(t==null?void 0:t.used)??0,o=(t==null?void 0:t.total)??null,l=(t==null?void 0:t.is_unlimited)??!1,c=i>0;async function u(d){var h;if(!r&&!(!d&&!confirm("Turn off Watch? This removes the monitoring on your catalogue (it won't affect SKUs you've enrolled on an active tier)."))){a(!0);try{const f=await K.setWatch(e,d);d?(Ae.success(`Watching ${f.watched??0} listing${f.watched===1?"":"s"}.`),(f.over_quota??0)>0&&Ae.warning(`${f.over_quota} more couldn't be watched â quota reached.`,{description:"Upgrade your plan to watch a bigger catalogue."})):Ae.success(`Watch turned off (${f.removed??0} removed).`),n()}catch(f){const m=f;Ae.error("Couldn't update Watch.",{description:(h=m.body)==null?void 0:h.message})}finally{a(!1)}}}return s.jsx(V,{className:"p-4",children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(al,{className:"w-4 h-4 text-text-brand"}),s.jsx("span",{className:"font-medium text-text-primary",children:"Watch"}),s.jsx("span",{className:B("text-[10px] px-1.5 py-0.5 rounded",c?"bg-success-bg text-success-text":"bg-surface-subtle text-text-tertiary"),children:c?"ON":"OFF"})]}),s.jsx("p",{className:"text-sm text-text-secondary max-w-xl",children:c?`Monitoring ${i}${l?"":` / ${o}`} listing${i===1?"":"s"} daily. A SKU auto-enables repricing the moment a competitor appears â no price changes until you set a floor.`:"Monitor your whole catalogue daily and auto-enable repricing the moment a competitor appears. Free â no price changes until you set a floor."})]}),s.jsx(W,{variant:c?"outline":"solid",size:"sm",disabled:r,onClick:()=>u(!c),children:r?"Workingâ¦":c?"Turn off":"Turn on Watch"})]})})}function I7e({trend:e}){const t=e.filter(a=>a.held_pct!=null),n=t.map(a=>a.held_pct),r=t.length?t[t.length-1]:null;return s.jsx(V,{className:"p-4",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-text-tertiary uppercase tracking-wide",children:"Buybox win-rate trend"}),s.jsx("div",{className:"text-[11px] text-text-tertiary mt-0.5",children:"Held among contested SKUs"})]}),n.length>=2?s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Ws,{data:n,width:120,height:28,className:"text-text-brand"}),s.jsxs("div",{className:"text-2xl font-semibold text-text-primary tabular-nums",children:[Math.round(r.held_pct),"%"]})]}):s.jsxs("div",{className:"text-sm text-text-tertiary text-right",children:["Filling forward â ",t.length," day",t.length===1?"":"s"," so far.",s.jsx("br",{}),s.jsx("span",{className:"text-[11px]",children:"A daily snapshot builds this trend."})]})]})})}function P7e({overview:e,slug:t,onBuySlots:n,onSchedulePause:r,onPauseCancelled:a}){const i=e.subscriptions,o=e.capacity.tiers,l=e.capacity.monthly_topup_cost_zar,c={winning:0,losing:0,unknown:0,not_buyable:0,not_scanned:0,disabled:0};for(const y of i)c[kv(y)]++;const u=i.filter(y=>C3(y)).length,d=c.winning+c.losing,h=d===0?null:Math.round(c.winning/d*100),f=
890o.reduce((y,b)=>y+b.used,0),m=o.reduce((y,b)=>y+(b.total??0),0),x=o.some(y=>y.is_unlimited),g=!x&&m>0?Math.round(f/m*100):null;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[s.jsx(ad,{label:"Enrolled SKUs",value:i.length,sub:i.length===0?"no enrolments yet":`${c.winning} winning · ${c.losing} losing`+(c.unknown>0?` · ${c.unknown} unconfirmed`:"")+(c.not_buyable>0?` · ${c.not_buyable} not buyable`:"")+(u>0?` · ${u} stale scan`:"")+` · ${c.not_scanned} pending`}),s.jsx(ad,{label:"Buybox win-rate",value:h==null?"â":`${h}%`,sub:d===0?"awaiting first scan":`${c.winning} of ${d} scanned`}),s.jsx(ad,{label:"Capacity used",value:x?`${f}`:`${f} / ${m}`,sub:x?"unlimited slots":g==null?"no slots provisioned":`${g}% of slots`}),s.jsx(ad,{label:"Monthly top-up",value:l>0?ge(l):"R0",sub:l>0?"above plan included":"no top-ups"})]}),s.jsx(I7e,{trend:e.winrate_trend}),e.metrics.watching>0&&s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-secondary px-1",children:[s.jsx(al,{className:"w-3.5 h-3.5 text-text-brand"}),s.jsxs("span",{children:[s.jsx("b",{className:"text-text-primary",children:e.metrics.watching})," watching"]}),s.jsx("span",{className:"text-text-tertiary",children:"·"}),s.jsxs("span",{children:[s.jsx("b",{className:"text-text-primary",children:e.metrics.auto_promoted_7d})," auto-promoted this week"]})]}),s.jsx(R7e,{plan:e.plan,tiers:o,monthlyTopupCost:l,onBuySlots:n}),s.jsx(D7e,{flags:e.flags,onBuySlots:n}),s.jsx(M7e,{pauses:e.pauses,slug:t,onSchedule:r,onCancelled:a})]})}function R7e({plan:e,tiers:t,monthlyTopupCost:n,onBuySlots:r}){return s.jsxs(V,{className:"p-4",children:[s.jsx(Hx,{icon:s.jsx(zv,{className:"w-4 h-4"}),title:"Capacity",right:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("span",{className:"text-xs text-text-tertiary capitalize",children:[e," plan"]}),s.jsxs(W,{variant:"outline",size:"sm",onClick:r,children:[s.jsx(tx,{className:"w-3.5 h-3.5 mr-1"}),"Buy more slots"]})]})}),s.jsx("div",{className:"mt-3 grid grid-cols-1 md:grid-cols-4 gap-3",children:t.map(a=>s.jsxs("div",{className:"rounded-lg border border-outline-subtle p-3 bg-surface",children:[s.jsx("div",{className:"text-xs font-medium text-text-tertiary uppercase tracking-wide",children:af[a.tier]}),s.jsx("div",{className:"mt-1 text-lg font-semibold text-text-primary",children:a.is_unlimited?`${a.used} used`:`${a.used} / ${a.total}`}),s.jsx("div",{className:"text-xs text-text-secondary",children:a.is_unlimited?"unlimited (plan)":`${a.included} included · ${a.topup} top-up`}),s.jsx("div",{className:"text-xs text-text-tertiary mt-1",children:a.tier==="watch"?"daily · monitor only":`every ${a.interval_minutes} min · R${a.topup_price_zar_per_slot}/slot`})]},a.tier))}),s.jsxs("div",{className:"mt-3 text-sm text-text-secondary",children:["Monthly top-up cost:"," ",s.jsx("span",{className:"font-medium text-text-primary",children:n>0?ge(n):"R0 (no top-ups)"})]})]})}function D7e({flags:e,onBuySlots:t}){var r,a;const n=e.losing_at_floor.count+e.tracking_unnecessary.count+e.not_buyable.count+e.contested_no_slot.count+e.floor_no_cost.count+e.pause_expiring.count+(((r=e.stale_scan)==null?void 0:r.count)??0)+(((a=e.bounce_uncontested)==null?void 0:a.count)??0);return s.jsxs(V,{className:"p-4",children:[s.jsx(Hx,{icon:s.jsx(zn,{className:"w-4 h-4"}),title:"Flagged issues",right:s.jsx("span",{className:"text-xs text-text-tertiary",children:n===0?"nothing to flag":`${n} total`})}),s.jsxs("div",{className:"mt-3 space-y-2 text-sm",children:[s.jsx(Nc,{label:"Losing the buybox at floor",bucket:e.losing_at_floor}),s.jsx(Nc,{label:"Scan older than 24h (3d on Watch)",bucket:e.stale_scan}),s.jsx(Nc,{label:"Uncontested bounce â cheaper rival on file",bucket:e.bounce_uncontested}),s.jsx(Nc,{label:"Tracking unnecessary",bucket:e.tracking_unnecessary}),s.jsx(Nc,{label:"Not buyable but enrolled",bucket:e.not_buyable}),s.jsx(Nc,{label:"Profit floor set but no cost loaded",bucket:e.floor_no_cost}),s.jsx(Nc,{label:"Contested â waiting for an active slot",bucket:e.contested_no_slot}),e.contested_no_slot.count>0&&s.jsx("button",{type:"button",onClick:t,className:"text-xs text-text-brand hover:underline",children:"Buy or free a slot to let these reprice â"}),s.jsx(Nc,{label:"Pause expiring (24h)",bucket:e.pause_expiring})]})]})}function Nc({label:e,bucket:t}){const n=(t==null?void 0:t.count)??0;return s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("span",{className:"text-text-primary",children:e}),s.jsx("span",{className:B("text-xs",n>0?"text-text-primary font-medium":"text-text-tertiary"),children:n})]})}function M7e({pauses:e,slug:t,onSchedule:n,onCancelled:r}){return s.jsxs(V,{className:"p-4",children:[s.jsx(Hx,{icon:s.jsx(K2,{className:"w-4 h-4"}),title:"Scheduled pauses",right:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xs text-text-tertiary",children:e.length===0?"none scheduled":`${e.length} active`}),s.jsxs(W,{variant:"outline",size:"sm",onClick:n,children:[s.jsx(In,{className:"w-3.5 h-3.5 mr-1"}),"Schedule pause"]})]})}),e.length===0?s.jsx("div",{className:"mt-2 text-sm text-text-secondary",children:"No pauses scheduled. Use Schedule pause to stop the repricer over a window â per
890-SKU or for the whole account."}):s.jsx("ul",{className:"mt-3 space-y-1 text-sm",children:e.map(a=>s.jsx($7e,{pause:a,slug:t,onCancelled:r},a.id))})]})}function $7e({pause:e,slug:t,onCancelled:n}){const[r,a]=p.useState(!1),i=new Date(e.starts_at)>new Date;async function o(){var l;if(!i){Ae.warning("Can't cancel an active or past pause window.",{description:"Only future windows can be cancelled."});return}a(!0);try{await K.cancelPauseWindow(t,e.id),Ae.success("Pause cancelled."),n()}catch(c){const u=c;Ae.error("Failed to cancel pause.",{description:(l=u.body)==null?void 0:l.message})}finally{a(!1)}}return s.jsxs("li",{className:"flex items-center justify-between gap-3",children:[s.jsx("span",{className:"text-text-primary",children:e.subscription_id?`${e.seller_sku??"â"} (this SKU)`:"Account-wide"}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("span",{className:"text-xs text-text-tertiary",children:[new Date(e.starts_at).toLocaleDateString()," â"," ",new Date(e.ends_at).toLocaleDateString(),e.reason?` · ${e.reason}`:""]}),i&&s.jsx("button",{type:"button",className:"text-text-tertiary hover:text-text-primary",onClick:o,disabled:r,title:"Cancel this pause",children:s.jsx(Bn,{className:"w-3.5 h-3.5"})})]})]})}function L7e({overview:e}){const t=e.activity,[n,r]=p.useState(""),{changes:a,up:i,down:o,flat:l,avg_delta:c}=e.activity_summary,u=i+o,d=u===0?"â":o>=i?`${Math.round(o/u*100)}% â`:`${Math.round(i/u*100)}% â`,h=n.trim().toLowerCase(),f=h?t.filter(m=>(m.seller_sku??"").toLowerCase().includes(h)):t;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[s.jsx(ad,{label:"Changes (7d)",value:a,sub:a===0?"no changes yet":`${i} up · ${o} down${l>0?` · ${l} flat`:""}`}),s.jsx(ad,{label:"Avg Î",value:c==null?"â":`${c>=0?"+":"â"}R${Math.abs(c).toFixed(2)}`,sub:a===0?"no priced changes":`across ${a} change${a===1?"":"s"}`}),s.jsx(ad,{label:"Direction",value:d,sub:u===0?"â":`${o} down · ${i} up${l>0?` · ${l} flat`:""}`})]}),s.jsxs(V,{className:"p-4",children:[s.jsx(Hx,{icon:s.jsx(Kh,{className:"w-4 h-4"}),title:"Recent price changes",right:s.jsxs("div",{className:"flex items-center gap-3",children:[t.length>0&&s.jsx(pc,{fieldClassName:"w-48",type:"text",placeholder:"Filter SKUâ¦",value:n,onChange:m=>r(m.target.value)}),s.jsx("span",{className:"text-xs text-text-tertiary",children:a>t.length?`latest ${t.length} of ${a} · 7d`:"last 7 days"})]})}),t.length===0?s.jsx("div",{className:"mt-2 text-sm text-text-secondary",children:"No price changes in the last 7 days."}):f.length===0?s.jsxs("div",{className:"mt-3 text-sm text-text-secondary",children:['No price changes match "',n,'".'," ",s.jsx("button",{type:"button",onClick:()=>r(""),className:"text-text-brand hover:underline",children:"Clear filter"})]}):s.jsx("ul",{className:"mt-3 space-y-2 text-sm",children:f.map(m=>{const{label:x,detail:g}=hq(m);return s.jsxs("li",{className:"flex items-start justify-between gap-3",children:[s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"text-text-primary",children:[m.seller_sku??"â"," ",s.jsxs("span",{className:"text-text-tertiary",children:["R",m.old_price," â R",m.new_price]})]}),s.jsxs("span",{className:"block text-xs text-text-secondary",children:[x,g&&s.jsxs("span",{className:"text-text-tertiary",children:[" · ",g]})]})]}),s.jsx("span",{className:"shrink-0 text-xs text-text-tertiary whitespace-nowrap",children:Ca(m.created_at)})]},m.id)})})]})]})}function b$(e){const t=n=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}T${t(e.getHours())}:${t(e.getMinutes())}`}function F7e({open:e,slug:t,onClose:n,onCreated:r}){const[a,i]=p.useState("account"),[o,l]=p.useState(""),[c,u]=p.useState(""),[d,h]=p.useState(""),[f,m]=p.useState(!1);p.useEffect(()=>{if(e){i("account");const g=new Date,y=new Date(g.getTime()+3600*1e3),b=new Date(g.getTime()+11520*60*1e3);l(b$(y)),u(b$(b)),h("")}},[e]);async function x(g){var y;if(g.preventDefault(),!f){m(!0);try{await K.setPauseWindow(t,{scope:a,starts_at:new Date(o).toISOString(),ends_at:new Date(c).toISOString(),reason:d||void 0}),Ae.success("Pause scheduled."),r()}catch(b){const v=b;Ae.error("Failed to schedule pause.",{description:(y=v.body)==null?void 0:y.message})}finally{m(!1)}}}return s.jsx(js,{open:e,onOpenChange:g=>!g&&n(),children:s.jsxs(Ns,{children:[s.jsx(La,{children:s.jsx(ma,{children:"Schedule pause"})}),s.jsxs("form",{onSubmit:x,children:[s.jsxs(Oa,{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Scope"}),s.jsxs(Tt,{value:a,onChange:g=>i(g.target.value),children:[s.jsx("option",{value:"account",children:"Account-wide (every subscription)"}),s.jsx("option",{value:"subscription",disabled:!0,children:"Per-SKU (use the SKU's Edit drawer)"})]}),s.jsx("p",{className:"text-xs text-text-tertiary mt-1",children:"Per-SKU pauses are set from each subscription's Edit panel â enrol a SKU first and open it from the Subscriptions list."})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Starts"}),s.jsx(Re,{type:"datetime-local",value:o,onChange:g=>l(g.target.value),required:!0})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Ends"}),s.jsx(Re,{type:"datetime-local",value:c,onChange:g=>u(g.target.value),required:!0})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Reason (optional)"}),s.jsx(Re,{value:d,onChange:g=>h(g.target.value),placeholder:"e.g. holiday, price experiment"})]})]}),s.jsxs(da,{children:[s.jsx(W,{type:"button",variant:"outline",onClick:n,children:"Cancel"}
890),s.jsx(W,{type:"submit",disabled:f,children:f?"Schedulingâ¦":"Schedule"})]})]})]})})}function B7e({open:e,slug:t,onClose:n}){const[r,a]=p.useState([]),[i,o]=p.useState("standard"),[l,c]=p.useState(null),[u,d]=p.useState(!1);p.useEffect(()=>{e&&(o("standard"),c(null),d(!1),K.slotPacks().then(g=>a(g.packs)).catch(()=>a([])))},[e]);const h=["basic","standard","boosted","super_boosted"],f=r.filter(g=>g.tier===i),m=f.find(g=>g.pack_size===l)??null;async function x(){var g;if(!(!m||u)){d(!0);try{const y=await K.buySlots(t,{tier:m.tier,pack_size:m.pack_size});window.location.href=y.authorization_url}catch(y){const b=y;Ae.error("Couldn't start the purchase.",{description:(g=b.body)==null?void 0:g.message}),d(!1)}}}return s.jsx(js,{open:e,onOpenChange:g=>!g&&n(),children:s.jsxs(Ns,{children:[s.jsx(La,{children:s.jsx(ma,{children:"Buy more slots"})}),s.jsxs(Oa,{className:"space-y-3",children:[s.jsx("p",{className:"text-sm text-text-secondary",children:"Each pack renews monthly until you cancel. Slots stack on top of what your plan includes."}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Tier"}),s.jsx("div",{className:"grid grid-cols-4 gap-2",children:h.map(g=>s.jsx("button",{type:"button",onClick:()=>{o(g),c(null)},className:B("px-3 py-2 text-sm rounded border transition-colors",i===g?"border-brand-600 bg-surface-brandSubtle text-text-brand font-medium":"border-outline-subtle text-text-secondary hover:border-outline"),children:af[g]},g))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Pack size"}),s.jsx("div",{className:"grid grid-cols-3 gap-2",children:f.map(g=>s.jsxs("button",{type:"button",onClick:()=>c(g.pack_size),className:B("px-3 py-3 text-sm rounded border text-left transition-colors",l===g.pack_size?"border-brand-600 bg-surface-brandSubtle font-medium":"border-outline-subtle hover:border-outline"),children:[s.jsxs("div",{className:"font-semibold text-text-primary",children:[g.pack_size," slots"]}),s.jsxs("div",{className:"text-xs text-text-tertiary",children:["R",g.amount_zar,"/mo · R",g.per_slot_zar,"/slot"]})]},g.pack_size))})]}),m&&s.jsxs("div",{className:"text-sm text-text-secondary",children:["You're buying ",s.jsx("b",{children:m.pack_size})," ",af[i]," slots for ",s.jsxs("b",{children:[ge(m.amount_zar),"/mo"]}),". You'll be redirected to Paystack to enter your card details."]})]}),s.jsxs(da,{children:[s.jsx(W,{variant:"outline",onClick:n,disabled:u,children:"Cancel"}),s.jsx(W,{onClick:x,disabled:!m||u,children:u?"Redirectingâ¦":m?`Pay ${ge(m.amount_zar)}`:"Pick a pack"})]})]})})}function U7e({subscription:e,slug:t,leadtimeEnabled:n,onClose:r,onSaved:a}){const[i,o]=p.useState("basic"),[l,c]=p.useState("compete"),[u,d]=p.useState(""),[h,f]=p.useState(""),[m,x]=p.useState(!1),[g,y]=p.useState(!0),[b,v]=p.useState(""),[w,_]=p.useState(""),[k,j]=p.useState(""),[N,E]=p.useState(""),[A,C]=p.useState(!1),[T,S]=p.useState(null),O=p.useRef(null);p.useEffect(()=>{e&&(o(e.tier),c(e.mode),d(e.min_price!=null?String(e.min_price):""),f(e.preferred_price!=null?String(e.preferred_price):""),x(e.hold_at_floor),y(e.enabled),v(e.leadtime_policy??""),_(e.leadtime_threshold_pct!=null?String(e.leadtime_threshold_pct):""),j(e.min_margin_pct!=null?String(e.min_margin_pct):""),E(e.min_roi_pct!=null?String(e.min_roi_pct):""))},[e]),p.useEffect(()=>{O.current&&clearTimeout(O.current);const P=k.trim()!==""||N.trim()!=="";if(!e||!P){S(null);return}const F=e.id;return O.current=setTimeout(()=>{K.previewMarginRoiFloor(t,F,{min_margin_pct:k.trim()===""?null:Number(k),min_roi_pct:N.trim()===""?null:Number(N)}).then(Z=>S(Z)).catch(()=>S(null))},350),()=>{O.current&&clearTimeout(O.current)}},[t,e,k,N]);const R=(e==null?void 0:e.tier)==="watch";async function I(){var P;if(!(!e||A)){C(!0);try{const F=k.trim()===""?null:Number(k),Z=N.trim()===""?null:Number(N);let D=null;if(F!=null||Z!=null)try{const Y=await K.previewMarginRoiFloor(t,e.id,{min_margin_pct:F,min_roi_pct:Z});if(Y.active&&Y.achievable&&Y.floor_price!=null){const M=u.trim()===""?null:Number(u);D=M!=null?Math.max(M,Y.floor_price):Y.floor_price,d(String(D))}}catch{}const H={preferred_price:h===""?null:Number(h),enabled:g};R?D!=null?H.min_price=D:u.trim()!==""&&(H.min_price=Number(u)):(H.tier=i,H.mode=l,H.min_price=D??Number(u),H.hold_at_floor=m,n&&(H.leadtime_policy=b===""?null:b,H.leadtime_threshold_pct=b==="threshold"&&w.trim()!==""?Number(w):null)),H.min_margin_pct=F,H.min_roi_pct=Z,await K.updateSubscription(t,e.id,H),Ae.success("Subscription updated."),a()}catch(F){const Z=F;Ae.error("Failed to update.",{description:(P=Z.body)==null?void 0:P.message})}finally{C(!1)}}}async function $(){var P;if(!(!e||A)&&confirm(`Unenrol ${e.seller_sku??"this SKU"}
890? This can't be undone.`)){C(!0);try{await K.unenrolSubscription(t,e.id),Ae.success("Unenrolled."),a()}catch(F){const Z=F;Ae.error("Failed to unenrol.",{description:(P=Z.body)==null?void 0:P.message})}finally{C(!1)}}}return s.jsx(Cr,{open:!!e,onOpenChange:P=>!P&&r(),children:s.jsxs(mr,{side:"right",size:"lg",children:[s.jsxs(Er,{children:[s.jsx(xr,{children:(e==null?void 0:e.seller_sku)??"Subscription"}),(e==null?void 0:e.tsin_id)!=null&&s.jsxs("div",{className:"mt-1 flex items-center gap-2 text-xs text-text-tertiary",children:[s.jsxs("span",{className:"font-mono",children:["TSIN ",e.tsin_id]}),s.jsx(z7e,{value:String(e.tsin_id),label:"Copy TSIN"}),e.plid!=null&&s.jsxs("a",{href:`https://www.takealot.com/x/PLID${e.plid}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 hover:text-text-brand",children:["PLID ",e.plid,s.jsx(Qt,{className:"w-3 h-3"})]})]})]}),s.jsxs(pr,{className:"p-4 space-y-4",children:[e&&s.jsx(W7e,{slug:t,subscription:e}),R&&s.jsxs("div",{className:"rounded-md bg-surface-subtle px-3 py-2 text-sm text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Watch · monitor only"})," â scanned daily, never reprices. Set a floor below to let it auto-enable repricing when a competitor appears."]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[!R&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Tier"}),s.jsxs(Tt,{value:i,onChange:P=>o(P.target.value),children:[s.jsx("option",{value:"basic",children:"Basic (60 min)"}),s.jsx("option",{value:"standard",children:"Standard (25 min)"}),s.jsx("option",{value:"boosted",children:"Boosted (15 min)"}),s.jsx("option",{value:"super_boosted",children:"Super Boosted (10 min)"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Mode"}),s.jsxs(Tt,{value:l,onChange:P=>c(P.target.value),children:[s.jsx("option",{value:"compete",children:"Compete (undercut R1)"}),s.jsx("option",{value:"share",children:"Share (match)"})]})]})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-xs font-medium text-text-secondary block mb-1",children:["Floor (R)",R?" â optional":""]}),s.jsx(Re,{type:"number",min:1,step:1,value:u,onChange:P=>d(P.target.value),required:!R,placeholder:R?"none (monitor only)":void 0})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Preferred (R)"}),s.jsx(Re,{type:"number",min:1,step:1,value:h,onChange:P=>f(P.target.value),placeholder:"optional"})]})]}),s.jsxs("div",{className:"rounded-md border border-border-subtle p-3 space-y-2",children:[s.jsx("div",{className:"text-xs font-medium text-text-secondary",children:"Profit floor (optional) â the repricer never prices below this"}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Min margin %"}),s.jsx(Re,{type:"number",min:0,max:99,step:.5,value:k,onChange:P=>j(P.target.value),placeholder:"none"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Min ROI %"}),s.jsx(Re,{type:"number",min:0,step:1,value:N,onChange:P=>E(P.target.value),placeholder:"none"})]})]}),(e==null?void 0:e.catalogue_cost_excl_vat)!=null?s.jsxs("div",{className:"text-xs text-text-tertiary",children:["Master Catalogue cost: R",e.catalogue_cost_excl_vat," excl VAT â floor is computed against this + Takealot fees."]}):s.jsx("div",{className:"text-xs text-text-warning",children:"No cost in the Master Catalogue for this SKU â the floor can't be enforced until a cost is set. The repricer falls back to your Floor (R) above."}),T&&T.active&&T.achievable&&T.floor_price!=null&&s.jsxs("div",{className:"text-xs font-medium text-text-primary",children:["Computed floor â ",s.jsxs("span",{className:"font-semibold",children:["R",T.floor_price]}),T.binding?` (${T.binding}-binding)`:""," â saving raises Floor (R) to at least this (a higher manual floor is kept)."]}),T&&T.active&&!T.achievable&&s.jsxs("div",{className:"text-xs text-text-warning",children:["That ",T.binding==="margin"?"margin":"ROI"," target can't be reached at any price (the Takealot fee already exceeds it). The repricer will hold rather than reprice."]})]}),!R&&s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:m,onChange:P=>x(P.target.checked)}),s.jsx("span",{children:"Hold at floor (suppress alerts when stuck)"})]}),!R&&n&&s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Slower (lead-time) competitors"}),s.jsxs(Tt,{value:b,onChange:P=>v(P.target.value),children:[s.jsx("option",{value:"",children:"Use account default"}),s.jsx("option",{value:"compete_all",children:"Compete with all (incl. slower)"}),s.jsx("option",{value:"ignore_leadtime",children:"Win on speed (ignore slower)"}),s.jsx("option",{value:"threshold",children:"Only if much cheaperâ¦"})]}),b==="threshold"&&s.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[s.jsx("span",{className:"text-xs text-text-secondary",children:"React only if they're more than"}),s.jsx(Re,{type:"number",min:1,max:90,step:1,value:w,onChange:P=>_(P.target.value),placeholder:"10",className:"w-20"}),s.jsx("span",{className:"text-xs text-text-secondary",children:"% cheaper"})]})]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:g,onChange:P=>y(P.target.checked)}),s.jsx("span",{children:"Enabled"})]})]}),s.jsxs(ml,{className:"justify-between",children:[s.jsx(W,{type:"button",variant:"outline",onClick:$,disabled:A,className:"text-error-text",children:"Unenrol"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx(W,{type:"button",variant:"outline",onClick:r,children:"Cancel"}),s.jsx(W,{type:"button",onClick:I,disabled:A,children:A?"Savingâ¦":"Save"})]})]})]})})}function z7e({value:e,label:t}){const[n,r]=p.useState(!1);return s.jsxs("button",{type:"button",title:t,"aria-label":t,className:"inline-flex items-center rounded p-0.5 text-text-tertiary hover:text-text-brand",onClick:()=>{navigator.clipboard.writeText(e).then(()=>{r(!0),setTimeout(()=>r(!1),1200)},()=>{})},children:[s.jsx(bi,{className:"w-3 h-3"}),s.jsx("span",{className:"sr-only",children:n?"Copied":t})]})}function W7e({slug:e,subscription:t}){var x,g;
890const[n,r]=p.useState(null),[a,i]=p.useState(!0),[o,l]=p.useState(null),c=p.useCallback((y=!1)=>{y||i(!0),l(null),K.subscriptionCompetitors(e,t.id).then(b=>{r(b),i(!1)}).catch(b=>{var v,w;l(((v=b.body)==null?void 0:v.message)||((w=b.body)==null?void 0:w.error)||b.message||"Couldn't load competitors"),i(!1)})},[e,t.id]);p.useEffect(()=>{c()},[c]);const u=[];if(n!=null&&n.our_offer&&u.push(n.our_offer),n!=null&&n.competitors)for(const y of n.competitors)u.push(y);const d=((x=n==null?void 0:n.buybox_winner)==null?void 0:x.seller_id)??null,h=((g=n==null?void 0:n.competitors)==null?void 0:g.length)??0,f=(n==null?void 0:n.tsin_id)??t.tsin_id,m=(n==null?void 0:n.source)==="live"?"Live from Takealot":(n==null?void 0:n.source)==="last_scan"?"Last scan":null;return s.jsxs("div",{className:"rounded-md border border-outline-subtle p-3 space-y-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-xs font-medium text-text-secondary",children:["All sellers on this listing",m&&s.jsxs("span",{className:"ml-2 font-normal text-text-tertiary",children:["· ",m]})]}),s.jsxs("div",{className:"text-[11px] text-text-tertiary",children:[f!=null?`TSIN ${f}`:"TSIN pending",h>0?` · you + ${h} competitor${h===1?"":"s"}`:n&&!a?" · you only":""]})]}),s.jsxs("button",{type:"button",onClick:()=>c(),disabled:a,className:"inline-flex items-center gap-1 text-xs text-text-tertiary hover:text-text-brand disabled:opacity-50",title:"Refresh live buybox",children:[a?s.jsx(_e,{className:"w-3 h-3 animate-spin"}):s.jsx(pa,{className:"w-3 h-3"}),"Refresh"]})]}),a&&!n?s.jsx("div",{className:"text-xs text-text-tertiary",children:"Loading every seller on this TSINâ¦"}):o?s.jsx("div",{className:"text-xs text-text-warning",children:o}):u.length===0?s.jsxs("div",{className:"text-xs text-text-tertiary",children:["No sellers on this listing yet",f!=null?` (TSIN ${f})`:"","."]}):s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("table",{className:"w-full text-left text-sm",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"text-[10px] uppercase tracking-wide text-text-tertiary",children:[s.jsx("th",{className:"py-1 pr-2 font-medium",children:"Seller"}),s.jsx("th",{className:"py-1 pr-2 font-medium",children:"ID"}),s.jsx("th",{className:"py-1 pr-2 font-medium text-right",children:"Price"}),s.jsx("th",{className:"py-1 pr-2 font-medium",children:"Stock"}),s.jsx("th",{className:"py-1 font-medium",children:"Rating"})]})}),s.jsx("tbody",{className:"divide-y divide-outline-subtle",children:u.map((y,b)=>{const v=Kp(y)??"Unknown seller",w=d!=null&&y.seller_id===d,_=y.is_lead_time?"slower":y.in_stock?"in stock":y.in_stock===!1?"out of stock":"â";return s.jsxs("tr",{className:"align-top",children:[s.jsxs("td",{className:"py-1.5 pr-2",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[y.seller_url?s.jsx("a",{href:y.seller_url,target:"_blank",rel:"noopener noreferrer",className:"truncate font-medium text-text-primary hover:text-text-brand hover:underline",children:v}):s.jsx("span",{className:"truncate font-medium text-text-primary",children:v}),y.is_ours&&s.jsx("span",{className:"text-[10px] px-1 py-0.5 rounded bg-surface-brandSubtle text-text-brand",children:"you"}),w&&s.jsx("span",{className:"text-[10px] px-1 py-0.5 rounded bg-surface-subtle text-text-secondary",children:"buy box"})]}),y.seller_vat_registered?s.jsx("div",{className:"text-[10px] text-text-tertiary",children:"VAT registered"}):null]}),s.jsx("td",{className:"py-1.5 pr-2 font-mono text-[11px] text-text-tertiary whitespace-nowrap",children:y.seller_id!=null?y.seller_id:"â"}),s.jsx("td",{className:"py-1.5 pr-2 text-right tabular-nums font-medium text-text-primary whitespace-nowrap",children:y.price!=null?`R${y.price}`:"â"}),s.jsx("td",{className:"py-1.5 pr-2 text-[11px] text-text-secondary whitespace-nowrap",children:_}),s.jsx("td",{className:"py-1.5 text-[11px] text-text-secondary whitespace-nowrap",children:y.seller_score!=null?`${Number(y.seller_score).toFixed(1)}â
${y.seller_reviews!=null?` (${y.seller_reviews})`:""}`:"â"})]},y.seller_id??b)})})]})})]})}const K7e=[{key:"row_number",label:"Row",getValue:e=>e.row_number,className:"text-text-tertiary"},{key:"sku",label:"SKU",render:e=>s.jsx("span",{className:"font-medium",children:e.sku})},{key:"tier",label:"Tier"},{key:"mode",label:"Mode"},{key:"min_price",label:"Floor",align:"right",getValue:e=>e.min_price,render:e=>e.min_price!=null?`R${e.min_price}`:"â"},{key:"preferred_price",label:"Preferred",align:"right",getValue:e=>e.preferred_price,render:e=>e.preferred_price!=null?`R${e.preferred_price}`:"â"},{key:"status",label:"Status",render:e=>e.error?s.jsx("span",{className:"text-xs text-error-text",children:e.error}):s.jsx("span",{className:"text-xs text-success-text",children:"val
890id"})}],H7e=[{key:"row_number",label:"Row",getValue:e=>e.row_number,className:"text-text-tertiary"},{key:"sku",label:"SKU",render:e=>s.jsx("span",{className:"font-medium",children:e.sku})},{key:"error",label:"Error",render:e=>s.jsx("span",{className:"text-xs text-error-text",children:e.message??e.error??"â"})}],V7e=[{key:"sku",label:"SKU",render:e=>s.jsx("span",{className:"font-medium",children:e.sku})},{key:"error",label:"Error",render:e=>s.jsx("span",{className:"text-xs text-error-text",children:e.message??e.error??"â"})}];function q7e({open:e,slug:t,onClose:n,onApplied:r}){const[a,i]=p.useState("pick"),[o,l]=p.useState([]),[c,u]=p.useState(null),[d,h]=p.useState(null),[f,m]=p.useState(!1),[x,g]=p.useState(!1);p.useEffect(()=>{e&&(i("pick"),l([]),u(null),h(null),g(!1))},[e]);async function y(){m(!0);try{await K.downloadEnrolTemplate(t)}catch(_){Ae.error("Couldn't download the template.",{description:_==null?void 0:_.message})}finally{m(!1)}}async function b(_){var E,A;const k=(E=_.target.files)==null?void 0:E[0];if(_.target.value="",!k)return;const j=await k.arrayBuffer(),N=Y7e(j);g(!0);try{const C=await K.enrolBatchPreview(t,{filename:k.name,base64:N});l(C.rows),u(C.summary),i("preview")}catch(C){const T=C;Ae.error("Couldn't parse the file.",{description:(A=T.body)==null?void 0:A.message})}finally{g(!1)}}async function v(){var k;i("applying");const _=o.filter(j=>!j.error);try{const j=await K.enrolBatchApply(t,_);h(j),i("result"),j.summary.enrolled>0&&Ae.success(`Enrolled ${j.summary.enrolled} SKUs.`,j.summary.promoted?{description:`${j.summary.promoted} promoted from watch to an active tier.`}:void 0),j.summary.failed>0&&Ae.warning(`${j.summary.failed} rows couldn't enrol.`,{description:"See per-row details in the modal."})}catch(j){const N=j;Ae.error("Apply failed.",{description:(k=N.body)==null?void 0:k.message}),i("preview")}}function w(){r()}return s.jsx(js,{open:e,onOpenChange:_=>!_&&n(),children:s.jsxs(Ns,{className:"max-w-3xl",children:[s.jsx(La,{children:s.jsx(ma,{children:"Enrol SKUs"})}),s.jsxs(Oa,{className:"space-y-3",children:[a==="pick"&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("p",{className:"text-sm text-text-secondary",children:["Download the template â it comes pre-filled with your enrollable SKUs at default settings, plus a ",s.jsx("strong",{children:"How to use"})," tab explaining every option. Adjust the values, delete any rows you don't want, save, then upload it back here. Required columns:"," ",s.jsx("code",{children:"sku"}),", ",s.jsx("code",{children:"tier"}),", ",s.jsx("code",{children:"mode"}),","," ",s.jsx("code",{children:"min_price"}),". Optional: ",s.jsx("code",{children:"preferred_price"}),","," ",s.jsx("code",{children:"hold_at_floor"}),"."]}),s.jsx("div",{className:"flex items-center gap-2",children:s.jsxs("button",{type:"button",onClick:y,disabled:f,className:"inline-flex items-center gap-1 text-sm text-text-brand hover:underline disabled:opacity-50",children:[s.jsx(Dr,{className:"w-3.5 h-3.5"}),f?"Downloadingâ¦":"Download template (XLSX)"]})}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Upload filled-in file"}),s.jsx("input",{type:"file",accept:".xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",onChange:b,disabled:x,className:"text-sm disabled:opacity-50"})]}),x&&s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-secondary",children:[s.jsx(_e,{className:"w-3.5 h-3.5 animate-spin"}),"Reading your fileâ¦"]})]}),a==="preview"&&c&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("p",{className:"text-sm text-text-secondary",children:[s.jsx("b",{children:c.valid})," of ",c.total," rows are valid."," ",c.invalid>0&&s.jsxs(s.Fragment,{children:[s.jsx("b",{children:c.invalid})," rows have errors and will be skipped on apply."]})]}),c.truncated?s.jsxs("p",{className:"text-sm text-text-warning",children:["Showing the first ",c.total," of"," ",c.file_total_rows??c.total," rows in the file. Enrol this batch, then re-upload the remainder."]}
890):null,s.jsx("div",{className:"max-h-72 overflow-y-auto border border-outline-subtle rounded",children:s.jsx(dt,{rows:o,columns:K7e,getRowKey:_=>_.row_number,persist:!1,paginate:!1})})]}),a==="applying"&&s.jsx("div",{className:"text-sm text-text-secondary",children:"Enrollingâ¦"}),a==="result"&&d&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("p",{className:"text-sm",children:[s.jsx("b",{children:d.summary.enrolled})," enrolled",d.summary.promoted?` (${d.summary.promoted} promoted from watch)`:"",", ",s.jsx("b",{children:d.summary.failed})," failed,"," ",s.jsx("b",{children:d.summary.skipped})," skipped (validation)."]}),d.summary.failed>0&&s.jsx("div",{className:"max-h-60 overflow-y-auto border border-outline-subtle rounded",children:s.jsx(dt,{rows:d.results.filter(_=>!_.ok),columns:H7e,getRowKey:_=>_.row_number,persist:!1,paginate:!1})})]})]}),s.jsxs(da,{children:[a==="pick"&&s.jsx(W,{variant:"outline",onClick:n,children:"Cancel"}),a==="preview"&&s.jsxs(s.Fragment,{children:[s.jsx(W,{variant:"outline",onClick:()=>i("pick"),children:"Back"}),s.jsxs(W,{onClick:v,disabled:(c==null?void 0:c.valid)===0,children:["Enrol ",(c==null?void 0:c.valid)??0," SKU",(c==null?void 0:c.valid)===1?"":"s"]})]}),a==="applying"&&s.jsx(W,{disabled:!0,children:"Enrollingâ¦"}),a==="result"&&s.jsx(W,{onClick:w,children:"Done"})]})]})})}function G7e({open:e,slug:t,onClose:n,onApplied:r}){const[a,i]=p.useState("search"),[o,l]=p.useState(""),[c,u]=p.useState([]),[d,h]=p.useState(!1),[f,m]=p.useState({}),[x,g]=p.useState("basic"),[y,b]=p.useState("compete"),[v,w]=p.useState({}),[_,k]=p.useState(null);p.useEffect(()=>{e&&(i("search"),l(""),u([]),m({}),g("basic"),b("compete"),w({}),k(null))},[e]),p.useEffect(()=>{if(!e||a!=="search")return;let I=!1;h(!0);const $=setTimeout(()=>{K.enrollableOffers(t,{search:o.trim(),limit:40}).then(P=>{I||u(P.offers)}).catch(P=>{I||Ae.error("Couldn't search listings.",{description:String((P==null?void 0:P.message)||P)})}).finally(()=>{I||h(!1)})},250);return()=>{I=!0,clearTimeout($)}},[e,a,t,o]);const j=p.useMemo(()=>Object.values(f),[f]);function N(I){m($=>{const P={...$};return P[I.sku]?delete P[I.sku]:P[I.sku]=I,P})}function E(){w(I=>{const $={...I};for(const P of j)if(!$[P.sku]){const F=P.selling_price!=null?String(Math.round(P.selling_price)):"";$[P.sku]={min_price:F,preferred_price:""}}return $}),i("configure")}function A(I,$){w(P=>({...P,[I]:{...P[I],...$}}))}function C(I){m($=>{const P={...$};return delete P[I],P})}const T=p.useMemo(()=>{if(j.length===0)return!1;const I=x==="watch";return j.every($=>{const P=v[$.sku],F=((P==null?void 0:P.min_price)??"").trim();if(!(I&&F==="")){const Z=Number(F);if(!Number.isFinite(Z)||Z<=0)return!1;if(P!=null&&P.preferred_price){const D=Number(P.preferred_price);if(!Number.isFinite(D)||D<Z)return!1}}return!0})},[j,v,x]);async function S(){var $;i("applying");const I=j.map((P,F)=>{var D;const Z=v[P.sku];return{row_number:F+1,sku:P.sku,tier:x,mode:y,min_price:(D=Z.min_price)!=null&&D.trim()?Number(Z.min_price):null,preferred_price:Z.preferred_price?Number(Z.preferred_price):null,hold_at_floor:!1}});try{const P=await K.enrolOffers(t,I);k(P),i("result"),P.summary.enrolled>0&&Ae.success(`Enrolled ${P.summary.enrolled} SKU${P.summary.enrolled===1?"":"s"}.`),P.summary.failed>0&&Ae.warning(`${P.summary.failed} couldn't enrol.`,{description:"See per-row details in the modal."})}catch(P){const F=P;Ae.error("Enrol failed.",{description:($=F.body)==null?void 0:$.message}),i("configure")}}const O=p.useMemo(()=>[{key:"select",label:"",className:"w-8",render:I=>s.jsx("input",{type:"checkbox",checked:!!f[I.sku],readOnly:!0,className:"rounded border-outline pointer-events-none"})},{key:"sku",label:"SKU",render:I=>s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"font-medium",children:I.sku}),I.status==="not_buyable"&&s.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-surface-subtle text-text-tertiary",children:"not buyable"})]}),s.jsx("div",{className:"text-xs text-text-tertiary truncate max-w-md",children:I.title??"â"}),I.tsin_id&&s.jsxs("div",{className:"font-mono text-[10px] text-text-tertiary",children:["TSIN ",I.tsin_id]})]})},{key:"price",label:"Price",align:"right",render:I=>s.jsxs("span",{className:"whitespace-nowrap",children:[I.selling_price!=null?ge(I.selling_price):"â",!I.variant_ready&&s.jsx("div",{className:"text-[10px] text-text-tertiary",children:"scans on add"})]})}],[f]),R=p.useMemo(()=>[{key:"sku",label:"SKU",sticky:!0,render:I=>s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"font-medium",children:I.sku}),s.jsx("div",{className:"text-xs text-text-tertiary truncate max-w-[14rem]",children:I.title??"â"}),I.tsin_id&&s.jsxs("div",{className:"font-mono text-[10px] text-text-tertiary",children:["TSIN ",I.tsin_id]})]})},{key:"price",label:"Price",align:"right",render:I=>s.jsx("span",{className:"text-text-secondary whitespace-nowrap",children:I.selling_price!=null?ge(I.selling_price):"â"})},{key:"floor",label:"Floor (R)",align:"right",render:I=>{const $=v[I.sku]??{min_price:""},P=Number($.min_price),F=!Number.isFinite(P)||P<=0;return s.jsx(Re,{type:"number",min:1,step:1,value:$.min_price,onChange:Z=>A(I.sku,{min_price:Z.target.value}),className:B("w-24 text-right",F&&"border-error-border")})}},{key:"target",label:"Target (R)",align:"right",render:I=>{const $=v[I.sku]??{min_price:"",preferred_price:""},P=Number($.min_price),F=Number($.preferred_price),Z=!!$.preferred_price&&(!Number.isFinite(F)||F<P);return s.jsx(Re,{type:"number",min:1,step:1,placeholder:"â",value:$.preferred_price,onChange:D=>A(I.sku,{preferred_price:D.target.value}),className:B("w-24 text-right",Z&&"border-error-border")})}},{key:"remove",label:"",align:"right",render:I=>s.jsx("button",{type:"button",onClick:()=>C(I.sku),className:"text-text-tertiary hover:text-error-text","aria-label":`Remove ${I.sku}`,children:s.jsx(Bn,{className:"w-3.5 h-3.5"})})}],[v]);return s.jsx(js,{open:e,onOpenChange:I=>!I&&n(),children:s.jsxs(Ns,{className:"max-w-3xl",children:[s.jsx(La,{children:s.jsx(ma,{children:a==="configure"?`Configure ${j.length} SKU${j.length===1?"":"s"}`:"Add SKUs"})}),s.jsxs(Oa,{className:"space-y-3",children:[a==="search"&&s.jsxs("div",{className:"space-y-3",children:[s.jsx(pc,{autoFocus:!0,t
890ype:"text",placeholder:"Search your listings by SKU or titleâ¦",value:o,onChange:I=>l(I.target.value)}),s.jsx("div",{className:"max-h-80 overflow-y-auto border border-outline-subtle rounded",children:d&&c.length===0?s.jsx("div",{className:"px-3 py-8 text-sm text-text-secondary text-center",children:"Searchingâ¦"}):c.length===0?s.jsx("div",{className:"px-3 py-8 text-sm text-text-secondary text-center",children:o.trim()?"No matching listings (already-enrolled SKUs are hidden).":"No enrollable listings found."}):s.jsx(dt,{rows:c,columns:O,getRowKey:I=>I.sku,persist:!1,paginate:!1,onRowClick:N,rowClassName:I=>f[I.sku]?"bg-surface-brandSubtle":void 0})})]}),a==="configure"&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Tier (all rows)"}),s.jsxs(Tt,{value:x,onChange:I=>g(I.target.value),children:[s.jsx("option",{value:"basic",children:"Basic (60 min)"}),s.jsx("option",{value:"standard",children:"Standard (25 min)"}),s.jsx("option",{value:"boosted",children:"Boosted (15 min)"}),s.jsx("option",{value:"super_boosted",children:"Super Boosted (10 min)"}),s.jsx("option",{value:"watch",children:"Watch (monitor only)"})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary block mb-1",children:"Mode (all rows)"}),s.jsxs(Tt,{value:y,onChange:I=>b(I.target.value),disabled:x==="watch",children:[s.jsx("option",{value:"compete",children:"Compete (undercut R1)"}),s.jsx("option",{value:"share",children:"Share (match)"})]})]})]}),x==="watch"&&s.jsx("p",{className:"text-xs text-text-tertiary",children:"Watch monitors these daily and auto-enables repricing when a competitor appears. Floor is optional â set one to allow auto-repricing; leave blank to monitor only."}),s.jsx("div",{className:"max-h-72 overflow-y-auto border border-outline-subtle rounded",children:s.jsx(dt,{rows:j,columns:R,getRowKey:I=>I.sku,persist:!1,paginate:!1})}),s.jsx("p",{className:"text-xs text-text-tertiary",children:"Floor is the lowest price the repricer will ever set. Target (optional) is used when there's no competition. Both default per-row; tier and mode apply to all."})]}),a==="applying"&&s.jsx("div",{className:"text-sm text-text-secondary",children:"Enrollingâ¦"}),a==="result"&&_&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("p",{className:"text-sm",children:[s.jsx("b",{children:_.summary.enrolled})," enrolled,"," ",s.jsx("b",{children:_.summary.failed})," failed."]}),_.summary.failed>0&&s.jsx("div",{className:"max-h-60 overflow-y-auto border border-outline-subtle rounded",children:s.jsx(dt,{rows:_.results.filter(I=>!I.ok),columns:V7e,getRowKey:I=>I.sku,persist:!1,paginate:!1})})]})]}),s.jsxs(da,{children:[a==="search"&&s.jsxs(s.Fragment,{children:[s.jsx(W,{variant:"outline",onClick:n,children:"Cancel"}),s.jsxs(W,{onClick:E,disabled:j.length===0,children:["Next: configure ",j.length||""]})]}),a==="configure"&&s.jsxs(s.Fragment,{children:[s.jsx(W,{variant:"outline",onClick:()=>i("search"),children:"Back"}),s.jsxs(W,{onClick:S,disabled:!T,children:["Enrol ",j.length," SKU",j.length===1?"":"s"]})]}),a==="applying"&&s.jsx(W,{disabled:!0,children:"Enrollingâ¦"}),a==="result"&&s.jsx(W,{onClick:r,children:"Done"})]})]})})}function Y7e(e){const t=new Uint8Array(e);let n="";const r=32768;for(let a=0;a<t.length;a+=r)n+=String.fromCharCode.apply(null,t.subarray(a,a+r));return btoa(n)}function Z7e({slug:e}){const[t,n]=p.useState(null),[r,a]=p.useState(null),[i,o]=p.useState(!1),[l,c]=p.useState(!1),[u,d]=p.useState(!1),[h,f]=p.useState(!1),[m,x]=p.useState(null),g=p.useCallback(()=>{K.automationsOverview(e).then(n).catch(b=>a(String((b==null?void 0:b.message)||b)))},[e]);p.useEffect(()=>{n(null),a(null),g()},[g]),p.useEffect(()=>{new URLSearchParams(window.location.search).get("paystack")==="return"&&(Ae.success("Payment received â applying your new slotsâ¦",{description:"It can take a few seconds for the slots to show up."}),window.history.replaceState({},"",window.location.pathname+window.location.hash),setTimeout(g,3e3),setTimeout(g,8e3))},[g]);const y=`/sellers/${e}/automations/repricer`;return s.jsxs(s.Fragment,{children:[s.jsx(As,{tone:"subtle",items:[{key:"health",label:"Health",to:`${y}/health`},{key:"activity",label:"Activity",to:`${y}/activity`},{key:"skus",label:"SKUs",to:`${y}/skus`}]}),s.jsxs("div",{className:"w-full p-4 md:p-6 space-y-4",children:[r&&s.jsxs(V,{className:"p-4 border-error-border bg-error-bg text-error-text",children:["Failed to load: ",r]}),!t&&!r&&s.jsx(V,{className:"p-4 text-sm text-text-secondary",children:"Loadingâ¦"}),t&&s.jsxs(ld,{children:[s.jsx(He,{path:"repricer/health",element:s.jsx(P7e,{overview:t,slug:e,onBuySlots:()=>f(!0),onSchedulePause:()=>o(!0),onPauseCancelled:g})}),s.jsx(He,{path:"repricer/activity",element:s.jsx(L7e,{overview:t})}),s.jsx(He,{path:"repricer/skus",element:s.jsx(A7e,{overview:t,slug:e,onEdit:x,onEnrol:()=>c(!0),onAdd:()=>d(!0),onChanged:g})}),s.jsx(He,{path:"*",element:s.jsx(Yt,{to:`${y}/health`,replace:!0})})]})]}),s.jsx(F7e,{open:i,slug:e,onClose:()=>o(!1),onCreated:()=>{o(!1),g()}}),s.jsx(U7e,{subscription:m,slug:e,leadtimeEnabled:(t==null?void 0:t.leadtime_control_enabled)??!1,onClose:()=>x(null),onSaved:()=>{x(null),g()}}),s.jsx(q7e,{open:l,slug:e,onClose:()=>c(!1),onApplied:()=>{c(!1),g()}}),s.jsx(G7e,{open:u,slug:e,onClose:()=>d(!1),onApplied:()=>{d(!1),g()}}),s.jsx(B7e,{open:h,slug:e,onClose:()=>f(!1)})]})}const X7e=[{key:"repricer",label:"Repricer",icon:s.jsx(ix,{className:"w-4 h-4"})},{key:"experiments",label:"Experiments",icon:s.jsx(rF,{className:"w-4 h-4"})},{key:"agents",label:"Agents",icon:s.jsx(X6,{className:"w-4 h-4"})}];function J7e(){const{slug:e=""}=jn(),[t,n]=p.useState(null),r=Lt(),a=Ba(),i=a.pathname.includes("/automations/experiments")?"experiments":a.pathname.includes("/automations/agents")?"agents":"repricer",o=r.kind==="ready"&&(r.me.role==="super_admin"||r.me.role==="am"),l=i==="agents"&&r.kind!=="ready",u=i==="agents"&&r.kind==="ready"&&!o?"repricer":i,d=X7e.filter(h=>h.key!=="agents"||o);return p.useEffect(()=>{K.seller(e).then(n).catch(()=>{})},[e]),s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Sellers",to:"/"},{label:(t==null?void 0:t.display_name)??e,to:`/sellers/${e}`},{label:"Automations"}]}),s.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:[s.jsx(As,{items:d.map(h=>({key:h.key,label:h.label,icon:h.icon,to:`/sellers/${e}/automations/${h.key}`}))}),l&&s.jsx("div",{className:"w-full p-4 md:p-6",children:s.jsx(V,{className:"p-4 text-sm text-text-secondary",children:"Loadingâ¦"})}),!l&&u==="repricer"&&s.jsx(Z7e,{slug:e}),!l&&u==="experiments"&&s.jsx(WBe,{slug:e}),!l&&u==="agents"&&o&&s.jsx(e7e,{slug:e})]})]})}const _m=100,Q7e=[{key:"open",label:"Open"},{key:"partial",label:"Partial"},{key:"repaid",label:"Repaid"}];function ap(e){const t=Number(e);return Number.isFinite(t)?new Intl.NumberFormat("en-ZA",{style:"currency",currency:"ZAR",minimumFractionDigits:2,maximumFractionDigits:2}).format(t):"â"}function e9e({status:e}){const t=e==="repaid"?"bg-surface-successSubtle text-text-success":e==="partial"?"bg-surface-errorSubtle text-text-error":"bg-surface-warningSubtle text-text-warning",n=e==="repaid"?"Repaid":e==="partial"?"Partial":"Open";return s.jsx("span",{className:B("inline-flex rounded-full px-2 py-0.5 text-xs font-medium",t),children:n})}const t9e=[{key:"date",label:"Date",getValue:e=>e.charged_at,render:e=>Ca(e.charged_at)},{key:"sku",label:"SKU",getValue:e=>e.sku,render:e=>s.jsx("span",{className:"font-mono text-xs",children:e.sku||"â"})},{key:"product",label:"Product",getValue:e=>e.title,render:e=>e.title||"â"},{key:"charged",label:"Charged",align:"right",getValue:e=>e.amount_owed,render:e=>ap(e.amount_owed)},{key:"repaid",label:"Repaid",align:"right",getValue:e=>e.repaid_amount,render:e=>ap(e.repaid_amount)},{key:"status",label:"Status",getValue:e=>e.status,render:e=>s.jsx(e9e,{status:e.status})}];function n9e({slug:e}){var h;const[t,n]=p.useState("open"),[r,a]=p.useState(0),[i,o]=p.useState(null),[l,c]=p.useState(null);p.useEffect(()=>{let f=!1;return o(null),c(null),K.storageFeeDuplicates(e,{status:t,limit:_m,offset:r}).then(m=>{f||o(m)}).catch(m=>{f||c(String((m==null?void 0:m.message)||m))}),()=>{f=!0}},[e,t,r]);const u=i&&i.total>0?r+1:0,d=i?Math.min(r+(((h=i.rows)==null?void 0:h.length)||0),i.total):0;return s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full p-4 md:p-6 space-y-4",children:[s.jsx(V,{className:"p-3 text-sm text-text-warning bg-surface-warningSubtle border-outline-warning",children:"Takealot charged these storage fees more than once. The first charge on each product is the real monthly fee. Each row stays here until that extra is paid back."}),(i==null?void 0:i.ready)&&s.jsxs(dr,{children:[s.jsx(Ye,{label:"Extras still open",value:String(i.open_lines),tone:i.open_lines>0?"warn":"default"}),s.jsx(Ye,{label:"Still on those charges",value:ap(i.amount_open),tone:i.amount_open>0?"warn":"default"}),s.jsx(Ye,{label:"Credit not yet tied",value:ap(i.unallocated_credit)}),s.jsx(Ye,{label:"Net still outstanding",value:ap(i.net_gap),tone:i.net_gap>0?"error":"success"})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Q7e.map(f=>s.jsx("button",{type:"button",onClick:()=>{n(f.key),a(0)},className:B("text-xs px-2.5 py-1 rounded-full border transition",t===f.key?"bg-brand-500 text-text-inverse border-outline-brand":"bg-surface-subtle text-text-secondary border-outline-subtle hover:text-text-primary"),children:f.label},f.key)),(i==null?void 0:i.matched_at)&&s.jsxs("span",{className:"text-xs text-text-tertiary ml-auto",children:["Tracked as of ",Ca(i.matched_at)]})]}),l&&s.jsx(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:l}),i&&!i.ready&&s.jsx(V,{className:"p-4 text-sm text-text-secondary",children:"The tracker is not in the database yet. It turns on with the next deploy."}),s.jsx(V,{className:"overflow-hidden",children:s.jsx(dt,{rows:i!=null&&i.ready?i.rows:i?[]:null,columns:t9e,getRowKey:f=>f.charge_transaction_id,persist:!1,paginate:!1,loading:!i&&!l,empty:{title:t==="repaid"?"No repaid extras yet.":"No extra charges in this view.",hint:"A row closes only when a credit pays that charge.",icon:Si}})}),i&&i.total>_m&&s.jsxs("div",{className:"flex items-center justify-between text-xs text-text-secondary",children:[s.jsxs("span",{children:[u,"â",d," of ",i.total]}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{type:"button",disabled:r===0,onClick:()=>a(f=>Math.max(0,f-_m)),className:"px-2 py-1 rounded border border-outline-subtle disabled:opacity-40",children:"Previous"}),s.jsx("button",{type:"button",disabled:r+_m>=i.total,onClick:()=>a(f=>f+_m),className:"px-2 py-1 rounded border border-outline-subtle disabled:opacity-40",children:"Next"})]})]})]})})}const r9e=[{key:"packaging",label:"Packaging"},{key:"inbound_freight",label:"Inbound freight"},{key:"advertising",label:"Advertising off Takealot"},{key:"software",label:"Software"},{key:"staff",label:"Staff"},{key:"photography",label:"Photography"},{key:"samples",label:"Samples"},{key:"agency_fee",label:"Agency fee"},{key:"other",label:"Other"}],mq=[{key:"this_month",label:"This month"},{key:"last_month",label:"Last month"},{key:"payout_week",label:"This payout week"},{key:"last_90",label:"Last 90 days"},{key:"tax_year",label:"This tax year"},{key:"custom",label:"Custom"}],s9e="block w-full rounded-md border border-outline bg-surface px-3 text-text-primary min-h-11 text-body-lg md:min-h-0 md:text-body-md md:px-3 md:py-2 focus:outline-none focus:border-outline-brand focus-visible:shadow-focus";function a9e({open:e,onOpenChange:t,onSave:n}){const r=new Date().toISOString().slice(0,10),[a,i]=p.useState("packaging"),[o,l]=p.useState(""),[c,u]=p.useState(""),[d,h]=p.useState(!0),[f,m]=p.useState(r),[x,g]=p.useState("once"),[y,b]=p.useState(""),[v,w]=p.useState(null),[_,k]=p.useState(!1);async function j(N){N.preventDefault(),w(null),k(!0);try{await n({category:a,description:o.trim(),amount:Number(c),vat_inclusive:d,occurred_on:f,recurrence:x,sku:y.trim()}),l(""),u(""),b(""),t(!1)}catch(E){w(E instanceof Error?E.message:String(E))}finally{k(!1)}}return s.jsx(js,{open:e,onOpenChange:t,children:s.jsx(Ns,{size:"md",children:s.jsxs("form",{onSubmit:j,children:[s.jsxs(La,{children:[s.jsx(ma,{children:"Add a cost"}),s.jsx(hc,{children:"Packaging, freight, ads outside Takealot, softw
890are. The buy price of a product belongs on the product, not here."})]}),s.jsxs(Oa,{className:"space-y-3",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(Fs,{htmlFor:"cost-category",children:"Category"}),s.jsx("select",{id:"cost-category",className:s9e,value:a,onChange:N=>i(N.target.value),children:r9e.map(N=>s.jsx("option",{value:N.key,children:N.label},N.key))})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsxs(Fs,{htmlFor:"cost-desc",children:["Description",a==="other"?"":" (optional)"]}),s.jsx(Re,{id:"cost-desc",value:o,onChange:N=>l(N.target.value),required:a==="other"})]}),s.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(Fs,{htmlFor:"cost-amount",children:"Amount (R)"}),s.jsx(Re,{id:"cost-amount",inputMode:"decimal",value:c,onChange:N=>u(N.target.value),required:!0})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(Fs,{htmlFor:"cost-date",children:"Date"}),s.jsx(Re,{id:"cost-date",type:"date",value:f,onChange:N=>m(N.target.value),required:!0})]})]}),s.jsxs(Pa,{value:d?"incl":"excl",onValueChange:N=>h(N==="incl"),className:"w-full",children:[s.jsx(Ln,{value:"incl",className:"flex-1 justify-center",children:"Incl. VAT"}),s.jsx(Ln,{value:"excl",className:"flex-1 justify-center",children:"Excl. VAT"})]}),s.jsxs(Pa,{value:x,onValueChange:N=>g(N==="monthly"?"monthly":"once"),className:"w-full",children:[s.jsx(Ln,{value:"once",className:"flex-1 justify-center",children:"Once"}),s.jsx(Ln,{value:"monthly",className:"flex-1 justify-center",children:"Every month"})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(Fs,{htmlFor:"cost-sku",children:"Product SKU (optional)"}),s.jsx(Re,{id:"cost-sku",value:y,onChange:N=>b(N.target.value),placeholder:"Leave blank for the whole store"})]}),v&&s.jsx("p",{className:"text-body-sm text-text-error",children:v})]}),s.jsxs(da,{className:"flex-col-reverse sm:flex-row",children:[s.jsx(W,{type:"button",intent:"neutral",variant:"outline",className:"w-full sm:w-auto",onClick:()=>t(!1),children:"Cancel"}),s.jsx(W,{type:"submit",intent:"brand",className:"w-full sm:w-auto",disabled:_,children:_?"Savingâ¦":"Add cost"})]})]})})})}function i9e(e,t){const n=e-t;if(Math.abs(n)<.5)return null;const r=ge(Math.abs(n));return`${n>0?"+":"â"}${r.replace(/^â/,"").replace(/^-/,"")}`}function WS({steps:e}){return s.jsx(V,{padding:"none",className:"overflow-hidden",children:s.jsx("ul",{children:e.map(t=>{const n=i9e(t.amount,t.prior);return s.jsxs("li",{className:B("flex items-baseline justify-between gap-3 px-3 py-2.5 sm:px-4",t.kind==="total"&&"bg-surface-subtle",t.kind!=="line"&&"border-t border-outline-subtle",t.kind==="line"&&"border-t border-outline-faint first:border-t-0"),children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:B("text-body-sm",t.kind==="line"?"pl-2 text-text-body sm:pl-3":"font-medium text-text-primary","break-words",t.kind==="total"&&"text-body-md"),children:t.label}),t.pct_of_net_sales!=null&&s.jsxs("div",{className:"pl-2 text-body-xs text-text-tertiary sm:pl-3",children:[Yn(t.pct_of_net_sales)," of net sales"]})]}),s.jsxs("div",{className:"shrink-0 text-right",children:[s.jsx("div",{className:B("tabular-nums text-body-sm",t.kind==="total"&&"text-body-md font-semibold",t.amount<0?"text-text-error":"text-text-primary"),children:ge(t.amount)}),n&&t.kind==="line"?s.jsx("div",{className:"text-body-xs tabular-nums text-text-tertiary",children:n}):null]})]},t.key)})})})}function E3(){const[e,t]=it("fpreset","this_month"),[n]=it("fsince",""),[r]=it("funtil",""),a=mc(),i=mq.some(o=>o.key===e)?e:"this_month";return{preset:i,since:n,until:r,query:{preset:i,since:i==="custom"?n:"",until:i==="custom"?r:""},choose(o){if(o==="custom"){t("custom");return}a({fpreset:o==="this_month"?"":o,fsince:"",funtil:""})},setCustom(o,l){a({fpreset:"custom",fsince:o,funtil:l})}}}function A3({preset:e,since:t,until:n,onChoose:r,onCustom:a}){const[i,o]=p.useState(t),[l,c]=p.useState(n);return s.jsxs("div",{className:"space-y-3",children:[s.jsx("div",{className:"-mx-4 flex snap-x snap-mandatory gap-2 overflow-x-auto px-4 pb-1 scrollbar-on-hover md:mx-0 md:flex-wrap md:overflow-visible md:px-0",children:mq.map(u=>{const d=u.key===e;return s.jsx(W,{type:"button",size:"sm",intent:d?"brand":"neutral",variant:d?"solid":"outline",className:"shrink-0 snap-start",onClick:()=>r(u.key),children:u.label},u.key)})}),e==="custom"&&s.jsxs("form",{className:"grid grid-cols-1 gap-2 sm:grid-cols-[1fr_1fr_auto] sm:items-end",onSubmit:u=>{u.preventDefault(),i&&l&&i<=l&&a(i,l)},children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx(Fs,{htmlFor:"period-from",children:"From"}),s.jsx(Re,{id:"period-from",type:"date",value:i,onChange:u=>o(u.target.value),required:!0})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(Fs,{htmlFor:"period-to",children:"To"}
890),s.jsx(Re,{id:"period-to",type:"date",value:l,onChange:u=>c(u.target.value),required:!0})]}),s.jsx(W,{type:"submit",intent:"brand",className:"w-full sm:w-auto",children:"Apply"})]}),s.jsx("p",{className:B("text-body-xs text-text-tertiary"),children:"Figures include VAT. Days are Johannesburg time."})]})}function o9e(e,t){if(!t)return null;const n=(e-t)/Math.abs(t);return{text:Yn(Math.abs(n)),positive:e>=t}}function l9e({slug:e}){const t=E3(),[n,r]=p.useState(null),[a,i]=p.useState(null),[o,l]=p.useState(!0),[c,u]=p.useState(!1),[d,h]=p.useState(null),[f,m]=p.useState(null),[x,g]=p.useState(0);p.useEffect(()=>{let w=!1;return l(!0),i(null),K.financialEarnings(e,t.query).then(_=>{w||r(_)}).catch(_=>{w||i(_ instanceof Error?_.message:String(_))}).finally(()=>{w||l(!1)}),()=>{w=!0}},[e,t.preset,t.since,t.until,x]);async function y(w,_){m(null);try{await K.deleteFinancialCost(e,w.id,_),h(null),g(k=>k+1)}catch(k){m(k instanceof Error?k.message:String(k))}}const b=n==null?void 0:n.bridge,v=(n==null?void 0:n.profit)!=null;return s.jsxs("div",{className:"min-w-0 flex-1 overflow-y-auto overflow-x-hidden bg-surface-subtle/30",children:[s.jsxs("div",{className:"w-full space-y-4 p-4 md:p-6",children:[s.jsx(A3,{preset:t.preset,since:t.since,until:t.until,onChoose:t.choose,onCustom:t.setCustom}),a&&s.jsxs(V,{className:"border-outline-error bg-surface-errorSubtle p-4 text-body-sm text-text-error",children:["Couldn't load earnings: ",a]}),o&&!n?s.jsxs("div",{className:"flex items-center gap-2 py-10 text-body-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Loading earningsâ¦"]}):n&&b?s.jsxs(s.Fragment,{children:[s.jsxs(dr,{cols:3,children:[s.jsx(Ye,{label:"Takealot net",value:ge(b.takealot_net,{compact:!0}),hint:"Added to your Takealot balance",tone:b.takealot_net<0?"error":"default",delta:o9e(b.takealot_net,b.prior_takealot_net)}),s.jsx(Ye,{label:"Take rate",value:Yn(b.take_rate),hint:"Takealot's cut of net sales"}),s.jsx(Ye,{className:"col-span-2 md:col-span-1",label:v?"Profit":"Gross profit, costed",value:ge(v?n.profit:n.costed.gross_profit,{compact:!0}),hint:v?"After your costs. Uncosted sales would only lower this.":`On ${Yn(n.costed.coverage_pct)} of sales with a cost`,tone:((v?n.profit:n.costed.gross_profit)??0)<0?"error":"success"})]}),n.what_changed&&s.jsx(V,{variant:"sunken",padding:"md",className:"text-body-sm text-text-body",children:n.what_changed}),s.jsx(WS,{steps:b.steps}),n.costed.covered_revenue>0&&s.jsxs(V,{padding:"md",className:"space-y-2",children:[s.jsxs("h2",{className:"text-body-sm font-medium text-text-primary",children:["On products with a cost (",Yn(n.costed.coverage_pct)," of sales)"]}),s.jsxs("dl",{className:"space-y-1.5 text-body-sm",children:[s.jsx(Xg,{label:"Net sales on those products",value:n.costed.covered_revenue}),s.jsx(Xg,{label:"Their Takealot fees",value:-n.costed.covered_fees}),s.jsx(Xg,{label:"Product cost",value:-n.costed.cogs}),s.jsx(Xg,{label:"Gross profit on that slice",value:n.costed.gross_profit,strong:!0})]})]}),s.jsxs("section",{className:"space-y-2",children:[s.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[s.jsx("h2",{className:"text-body-md font-medium text-text-primary",children:"Your costs"}),s.jsxs(W,{type:"button",size:"sm",intent:"brand",className:"w-full sm:w-auto",onClick:()=>u(!0),children:[s.jsx(In,{className:"h-4 w-4"})," Add a cost"]})]}),n.your_costs.length===0?s.jsx(V,{variant:"sunken",padding:"md",className:"text-body-sm text-text-secondary",children:"Gadjet appears here once an invoice is issued. Add packaging, freight, or anything else you pay from your own account."}):s.jsx(V,{padding:"none",children:s.jsxs("ul",{children:[n.your_costs.map(w=>s.jsxs("li",{className:"flex flex-col gap-3 border-b border-outline-faint px-3 py-3 last:border-0 sm:flex-row sm:items-center sm:justify-between sm:px-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"text-body-sm text-text-primary",children:w.label}),s.jsx(_n,{tone:w.source==="gadjet"?"brand":"neutral",children:w.source==="gadjet"?"Gadjet":"You"})]}),s.jsxs("div",{className:"mt-0.5 text-body-xs text-text-tertiary",children:[w.occurred_on,w.invoice_number?` · ${w.invoice_number}`:"",w.sku?` · ${w.sku}`:"",w.pdf_url?s.jsxs(s.Fragment,{children:[" · ",s.jsx(W,{asChild:!0,intent:"brand",variant:"link",size:"sm",children:s.jsx("a",{href:w.pdf_url,target:"_blank",rel:"noreferrer",children:"Invoice"})})]}):null]})]}),s.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-end",children:[s.jsx("span",{className:"tabular-nums text-body-sm text-text-error",children:ge(-w.amount)}),w.editable&&(d===w.id?s.jsxs("span",{className:"flex flex-col gap-2 sm:flex-row",children:[s.jsx(W,{type:"button",size:"sm",intent:"destructive",className:"w-full sm:w-auto",onClick:()=>y(w,"one"),children:"Remove"}),w.series_id&&s.jsx(W,{type:"button",size:"sm",intent:"destructive",variant:"outline",className:"w-full sm:w-auto",onClick:()=>y(w,"future"),children:"And future"}),s.jsx(W,{type:"button",size:"sm",intent:"neutral",variant:"outline",className:"w-full sm:w-auto",onClick:()=>h(null),children:"Cancel"})]}):s.jsx(W,{type:"button",size:"sm",intent:"neutral",variant:"outline",className:"w-full sm:w-auto",onClick:()=>h(w.id),children:"Remove"}))]})]},w.id)),s.jsxs("li",{className:"flex flex-col gap-1 bg-surface-subtle px-3 py-3 sm:flex-row sm:items-baseline sm:justify-between sm:px-4",children:[s.jsx("span",{className:"text-body-sm font-medium",children:"Left after Takealot and your costs"}),s.jsx("span",{className:"tabular-nums text-body-md font-semibold",children:ge(n.left_after_costs)})]})]})}),f&&s.jsx("p",{className:"text-body-sm text-text-error",children:f}),n.topups>0&&s.jsxs("p",{className:"text-body-xs text-text-tertiary",children:["Credit top-ups this period: ",ge(n.topups),". That is prepaid chat credit, not a cost of these sales."]})]}),n.flags.length>0&&s.jsx(V,{variant:"sunken",padding:"md",children:s.jsx("ul",{className:"space-y-2",children:n.flags.map(w=>s.jsx("li",{className:"text-body-sm text-text-secondary",children:w.text},w.key))})}),s.jsx("p",{className:"text-body-xs text-text-tertiary",children:"From your Takealot ledger. Sales shows orders placed; this shows what Takealot has booked. A return lands when Takealot processes it. Payouts to your bank are on Cash. Gadjet and the costs you add are paid from your own account."})]}):null]}),s.jsx(a9e,{open:c,onOpenChange:u,onSave:async w=>{await K.createFinancialCost(e,w),g(_=>_+1)}})]})}function Xg({label:e,value:t,strong:n}){return s.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[s.jsx("dt",{className:n?"min-w-0 font-medium text-text-primary":"min-w-0 text-text-secondary",children:e}),s.jsx("dd",{className:"shrink-0 tabular-nums",children:ge(t)})]})}function c9e({slug:e}){const t=E3(),[n,r]=it("payout",""),[a,i]=p.useState(null),[o,l]=p.useState(null),[c,u]=p.useState(!0);p.useEffect(()=>{let f=!1;return u(!0),l(null),K.financialCash(e,{...t.query,payout:n}).then(m=>{f||i(m)}).catch(m=>{f||l(m instanceof Error?m.message:String(m))}).finally(()=>{f||u(!1)}),()=>{f=!0}},[e,t.preset,t.since,t.until,n]);const d=a==null?void 0:a.balance,h=d&&a?Math.abs(d.current-a.ledger_balance):null;return s.jsx("div",{className:"min-w-0 flex-1 overflow-y-auto overflow-x-hidden bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full space-y-4 p-4 md:p-6",children:[s.jsx(A3,{preset:t.preset,since:t.since,until:t.until,onChoose:t.choose,onCustom:t.setCustom}),o&&s.jsxs(V,{className:"border-outline-error bg-surface-errorSubtle p-4 text-body-sm text-text-error",children:["Couldn't load cash: ",o]}),c&&!a?s.jsxs("div",{className:"flex items-center gap-2 py-10 text-body-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"}
890)," Loading cashâ¦"]}):a?s.jsxs(s.Fragment,{children:[s.jsxs(dr,{cols:3,children:[s.jsx(Ye,{label:"Available",value:ge(d==null?void 0:d.available,{compact:!0}),hint:d!=null&&d.live?"Live from Takealot":"Last stored balance",tone:"success"}),s.jsx(Ye,{label:"Held back",value:ge(d==null?void 0:d.held_back,{compact:!0}),hint:"Buffer Takealot keeps"}),s.jsx(Ye,{className:"col-span-2 md:col-span-1",label:"At Takealot",value:ge((d==null?void 0:d.current)??a.ledger_balance,{compact:!0}),hint:h!=null&&h<1?"Matches your ledger":`Ledger says ${ge(a.ledger_balance)}`})]}),a.selected&&s.jsxs("section",{className:"space-y-2",children:[s.jsxs("div",{className:"flex flex-col gap-1 sm:flex-row sm:items-baseline sm:justify-between",children:[s.jsxs("h2",{className:"text-body-md font-medium text-text-primary",children:["Paid to your bank · ",cn(a.selected.at)]}),s.jsx("div",{className:"text-headline-sm tabular-nums text-text-success",children:ge(a.selected.amount)})]}),a.payouts.length>1&&s.jsx("div",{className:"-mx-4 flex snap-x snap-mandatory gap-2 overflow-x-auto px-4 pb-1 scrollbar-on-hover md:mx-0 md:px-0",children:a.payouts.map(f=>{var x;const m=f.transaction_id===((x=a.selected)==null?void 0:x.transaction_id);return s.jsxs(W,{type:"button",size:"sm",intent:m?"brand":"neutral",variant:m?"solid":"outline",className:"h-auto min-w-[7.5rem] shrink-0 snap-start flex-col items-start",onClick:()=>{var g;return r(f.transaction_id===((g=a.payouts[0])==null?void 0:g.transaction_id)?"":f.transaction_id)},children:[s.jsx("span",{className:"text-body-xs opacity-80",children:cn(f.at)}),s.jsx("span",{className:"tabular-nums",children:ge(f.amount,{compact:!0})})]},f.transaction_id)})}),s.jsx(WS,{steps:a.selected.steps}),s.jsxs(V,{padding:"md",className:"space-y-1.5 text-body-sm",children:[s.jsx(Sc,{label:"Earned in this window",value:a.selected.earned}),s.jsx(Sc,{label:"Paid to your bank",value:-a.selected.paid}),s.jsx(Sc,{label:"Change in money still at Takealot",value:a.selected.held_change,strong:!0})]}),Math.abs(a.selected.held_change)>a.selected.paid*.05&&s.jsx("p",{className:"text-body-sm text-text-secondary",children:a.selected.held_change>0?"Takealot held more back than it paid out in this window.":"A previous hold was released into this payout."})]}),a.since_last&&s.jsxs("section",{className:"space-y-2",children:[s.jsx("h2",{className:"text-body-md font-medium text-text-primary",children:"Booked since your last payout"}),s.jsx("p",{className:"text-body-sm text-text-secondary",children:"This is not next Thursday's deposit. Takealot holds each line for about three days, and holds a buffer back."}),s.jsx(WS,{steps:a.since_last.steps}),s.jsxs("p",{className:"text-body-sm font-medium tabular-nums",children:["Earned since then: ",ge(a.since_last.earned)]})]}),s.jsxs(V,{padding:"md",className:"space-y-1.5",children:[s.jsx("h2",{className:"text-body-sm font-medium text-text-primary",children:"Ledger for this period"}),s.jsx(Sc,{label:"Opening balance",value:a.identity.opening}),s.jsx(Sc,{label:"Takealot net",value:a.identity.takealot_net}),s.jsx(Sc,{label:"Paid to your bank",value:-a.identity.paid}),a.identity.bounced!==0&&s.jsx(Sc,{label:"Payouts returned",value:a.identity.bounced}),s.jsx(Sc,{label:"Closing balance",value:a.identity.closing,strong:!0})]}),s.jsxs(V,{variant:"sunken",padding:"md",className:"flex items-baseline justify-between gap-3",children:[s.jsx("span",{className:"text-body-sm text-text-secondary",children:"Paid from your own account"}),s.jsx("span",{className:"tabular-nums text-body-sm font-medium",children:ge(a.paid_from_own_account)})]})]}):null]})})}function Sc({label:e,value:t,strong:n}){return s.jsxs("div",{className:"flex items-baseline justify-between gap-3 text-body-sm",children:[s.jsx("span",{className:n?"min-w-0 font-medium text-text-primary":"min-w-0 text-text-secondary",children:e}),s.jsx("span",{className:B("shrink-0 tabular-nums",n&&"font-semibold"),children:ge(t)})]})}function u9e({slug:e}){const t=E3(),[n,r]=p.useState(null),[a,i]=p.useState(null),[o,l]=p.useState(!0),[c,u]=p.useState(!1);p.useEffect(()=>{let x=!1;return l(!0),i(null),K.financialProducts(e,t.query).then(g=>{x||r(g)}).catch(g=>{x||i(g instanceof Error?g.message:String(g))}).finally(()=>{x||l(!1)}),()=>{x=!0}},[e,t.preset,t.since,t.until]);const d=p.useMemo(()=>c?((n==null?void 0:n.rows)||[]).filter(x=>x.contribution<0):(n==null?void 0:n.rows)||[],[n,c]),h=p.useCallback(x=>
890[x.sku,x.title],[]),f=Id(n?d:null,h,{urlKey:"pq"}),m=[{key:"product",label:"Product",sticky:!0,sortable:!0,getValue:x=>x.title,render:x=>s.jsxs("div",{className:"min-w-0 max-w-[9rem] sm:max-w-xs",children:[s.jsx("div",{className:"truncate text-body-sm text-text-primary",children:x.title||x.sku}),s.jsx("div",{className:"truncate text-body-xs text-text-tertiary",children:x.sku})]})},{key:"units",label:"Units",align:"right",format:"number",sortable:!0,hideBelow:"md",getValue:x=>x.units},{key:"net",label:"Net sales",align:"right",format:"zar",sortable:!0,hideBelow:"sm",getValue:x=>x.net_sales},{key:"fulfilment",label:"Fulfilment / unit",align:"right",sortable:!0,hideBelow:"lg",getValue:x=>x.fulfilment_per_unit,render:x=>x.fulfilment_per_unit==null?"â":ge(x.fulfilment_per_unit)},{key:"contribution",label:"Contribution",align:"right",sortable:!0,getValue:x=>x.contribution,render:x=>s.jsx("span",{className:x.contribution<0?"text-text-error":"text-text-primary",children:ge(x.contribution)})},{key:"profit",label:"Profit",align:"right",sortable:!0,hideBelow:"md",getValue:x=>x.profit,render:x=>x.profit==null?s.jsx("span",{className:"text-text-tertiary",children:"â"}):ge(x.profit)},{key:"margin",label:"Margin",align:"right",sortable:!0,hideBelow:"lg",getValue:x=>x.margin,render:x=>x.margin==null?"â":Yn(x.margin)}];return s.jsx("div",{className:"min-w-0 flex-1 overflow-y-auto overflow-x-hidden bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full space-y-4 p-4 md:p-6",children:[s.jsx(A3,{preset:t.preset,since:t.since,until:t.until,onChoose:t.choose,onCustom:t.setCustom}),a&&s.jsxs(V,{className:"border-outline-error bg-surface-errorSubtle p-4 text-body-sm text-text-error",children:["Couldn't load products: ",a]}),o&&!n?s.jsxs("div",{className:"flex items-center gap-2 py-10 text-body-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Loading productsâ¦"]}):n?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[s.jsx(Ni,{value:f.q,onChange:f.setQ,placeholder:"Search products",className:"w-full sm:max-w-xs"}),s.jsx(W,{type:"button",size:"sm",intent:c?"destructive":"neutral",variant:c?"solid":"outline",className:"w-full sm:w-auto",onClick:()=>u(x=>!x),children:"Losing money"})]}),(n.account_charges.length>0||n.your_costs.length>0)&&s.jsxs("div",{className:"grid grid-cols-1 gap-3 lg:grid-cols-2",children:[n.account_charges.length>0&&s.jsxs(V,{padding:"md",className:"space-y-1",children:[s.jsx("h2",{className:"text-body-sm font-medium",children:"Account charges"}),n.account_charges.map(x=>s.jsxs("div",{className:"flex justify-between gap-3 text-body-sm",children:[s.jsx("span",{className:"min-w-0 text-text-secondary",children:x.label}),s.jsx("span",{className:"tabular-nums",children:ge(x.amount)})]},x.key))]}),n.your_costs.length>0&&s.jsxs(V,{padding:"md",className:"space-y-1",children:[s.jsx("h2",{className:"text-body-sm font-medium",children:"Your costs"}),n.your_costs.map(x=>s.jsxs("div",{className:"flex justify-between gap-3 text-body-sm",children:[s.jsx("span",{className:"min-w-0 truncate text-text-secondary",children:x.label}),s.jsx("span",{className:"shrink-0 tabular-nums",children:ge(-x.amount)})]},x.id))]})]}),s.jsx(dt,{rows:f.filtered,columns:m,getRowKey:x=>x.sku,defaultSort:{key:"contribution",direction:"desc"},sortUrlKey:"psort",pageKey:"ppage",empty:{title:c?"No products are losing money":"No product lines in this period"}}),s.jsxs("p",{className:"text-body-xs text-text-tertiary",children:["Product contribution ",ge(n.contribution_total),n.unlinked!==0?` · not tied to a product ${ge(n.unlinked)}`:""," · ","Takealot net ",ge(n.takealot_net),". Gadjet is in Your costs, not on a product."]})]}):null]})})}function d9e(e){if(e.vat_multiplier==null||e.vat_multiplier<=0)return null;const t=e.amount_incl_vat/e.vat_multiplier,n=e.amount_incl_vat-t;return{excl:t,vat:n}}function h9e({slug:e,txn:t,open:n,onClose:r}){const a=t?d9e(t):null,i=t==null?null:t.amount_incl_vat>0?"inflow":t.amount_incl_vat<0?"outflow":"zero";return s.jsx(Cr,{open:n,onOpenChange:o=>{o||r()},children:s.jsxs(mr,{side:"right",size:"lg",children:[s.jsxs(Er,{children:[s.jsx(xr,{className:"font-mono",children:(t==null?void 0:t.transaction_type)??"â"}),s.jsx(Mr,{children:t?`${cn(t.created_at)} · Transaction #${t.transaction_id}`:"Transaction detail"})]}),s.jsx(pr,{className:"p-4 space-y-4",children:t?s.jsxs(s.Fragment,{children:[s.jsxs(V,{className:"p-4",children:[s.jsx(Jg,{children:"Amount"}),s.jsx("div",{className:B("text-2xl font-semibold tabular-nums mb-2",i==="inflow"?"text-text-success":i==="outflow"?"text-text-error":"text-text-body"),children:ge(t.amount_incl_vat)}),s.jsx("div",{className:"text-xs text-text-secondary mb-3",children:"Including VAT"}),a&&s.jsxs("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-2 text-sm pt-2 border-t border-outline-faint",children:[s.jsx(Oi,{label:"Excl. VAT",value:ge(a.excl),muted:!0}
890),s.jsx(Oi,{label:"VAT portion",value:ge(a.vat),muted:!0}),s.jsx(Oi,{label:"VAT rate",value:`${((t.vat_multiplier-1)*100).toFixed(0)}%`,muted:!0})]})]}),s.jsxs(V,{className:"p-4",children:[s.jsx(Jg,{children:"Transaction details"}),s.jsxs("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-3 text-sm",children:[s.jsx(Oi,{label:"Transaction ID",value:String(t.transaction_id),mono:!0}),s.jsx(Oi,{label:"Date",value:cn(t.created_at)}),s.jsx("div",{className:"col-span-2",children:s.jsx(Oi,{label:"Type",value:t.transaction_type,mono:!0})}),(t.rule||t.manual_reference)&&s.jsx("div",{className:"col-span-2",children:s.jsx(Oi,{label:t.rule?"Rule":"Manual reference",value:t.rule??t.manual_reference??"â"})})]})]}),(t.order_id!=null||t.return_reference_number!=null||t.offer_id!=null)&&s.jsxs(V,{className:"p-4",children:[s.jsx(Jg,{children:"Linked references"}),s.jsxs("dl",{className:"grid grid-cols-2 gap-x-4 gap-y-3 text-sm",children:[t.order_id!=null&&s.jsx(Oi,{label:"Order #",value:`#${t.order_id}`,mono:!0}),t.order_item_id!=null&&s.jsx(Oi,{label:"Order item ID",value:String(t.order_item_id),mono:!0,muted:!0}),t.offer_id!=null&&s.jsx(Oi,{label:"Offer ID",value:String(t.offer_id),mono:!0,muted:!0}),t.return_reference_number!=null&&s.jsx(Oi,{label:"Return ref",value:t.return_reference_number,mono:!0}),t.item_quantity!=null&&s.jsx(Oi,{label:"Item quantity",value:String(t.item_quantity)})]})]}),(t.order_id!=null||t.return_reference_number!=null||t.offer_id!=null)&&s.jsxs(V,{className:"p-4",children:[s.jsx(Jg,{children:"Trace this transaction"}),s.jsxs("div",{className:"space-y-2 text-sm",children:[t.offer_id!=null&&s.jsxs(st,{to:`/sellers/${e}/inventory?offer=${t.offer_id}`,className:"flex items-center gap-2 text-text-brand hover:underline",children:[s.jsx(os,{className:"w-3.5 h-3.5"}),"Open SKU dossier"]}),t.order_id!=null&&s.jsxs(s.Fragment,{children:[s.jsxs(st,{to:`/sellers/${e}/sales?q=${t.order_id}`,className:"flex items-center gap-2 text-text-brand hover:underline",children:[s.jsx(os,{className:"w-3.5 h-3.5"}),"Find the sale"]}),s.jsxs(st,{to:`/sellers/${e}/returns?q=${t.order_id}`,className:"flex items-center gap-2 text-text-brand hover:underline",children:[s.jsx(os,{className:"w-3.5 h-3.5"}),"Find related returns"]})]}),t.return_reference_number!=null&&s.jsxs(st,{to:`/sellers/${e}/returns?q=${encodeURIComponent(t.return_reference_number)}`,className:"flex items-center gap-2 text-text-brand hover:underline",children:[s.jsx(os,{className:"w-3.5 h-3.5"}),"Open the return (by ref)"]})]})]})]}):s.jsx("div",{className:"text-sm text-text-tertiary",children:"This transaction isn't in the current view. Adjust the window or clear the filters to find it."})})]})})}function Jg({children:e}){return s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary mb-3",children:e})}function Oi({label:e,value:t,muted:n,mono:r}){return s.jsxs("div",{children:[s.jsx("dt",{className:"text-[10px] text-text-tertiary uppercase tracking-wider",children:e}),s.jsx("dd",{className:B("font-medium tabular-nums mt-0.5 break-words",r&&"font-mono text-xs",n?"text-text-secondary":"text-text-body"),children:t})]})}function f9e(e){const t=new Date,n=new Date(t.getTime()+86400*1e3);return{since:new Date(t.getTime()-e*86400*1e3).toISOString().slice(0,10),until:n.toISOString().slice(0,10)}}const m9e=[{label:"Last 7 days",days:7},{label:"Last 30 days",days:30},{label:"Last 90 days",days:90}],p9e=5e3,v$=[{key:"money-in",label:"Money in",predicate:e=>e.amount_incl_vat>0},{key:"money-out",label:"Money out",predicate:e=>e.amount_incl_vat<0},{key:"manual",label:"Manual",predicate:e=>e.manual_reference!=null&&e.manual_reference!==""},{key:"returns",label:"Returns",predicate:e=>e.return_reference_number!=null&&e.return_reference_number!==""}];function x9e(){const{slug:e=""}=jn(),[t,n]=it("tab","earnings"),r=t==="storage-fees"?"storage-fees":t==="list"?"list":t==="cash"?"cash":t==="products"?"products":"earnings",[a,i]=p.useState(null),[o,l]=p.useState(null),[c,u]=p.useState(null),[d,h]=p.useState(null),[f]=it("range","30"),m=Number(f)||30,[x]=it("since",""),[g]=it("until",""),y=!!(x&&g),[b,v]=it("type",""),w=mc(),[_,k]=it("txn",""),j=_?(c==null?void 0:c.find(F=>String(F.transaction_id)===_))??null:null,[N,E]=p.useState(null),[A,C]=p.useState(null);p.useEffect(()=>{K.seller(e).then(l).catch(()=>{})},[e]),p.useEffect(()=>{let F=!1;return K.storageFeeDuplicates(e,{status:"open",limit:1}
890).then(Z=>{F||i(Z.ready?Z.open_lines:null)}).catch(()=>{F||i(null)}),()=>{F=!0}},[e]),p.useEffect(()=>{if(r!=="list")return;h(null);const F=y?{since:x,until:g}:{days:m};K.transactionTypes(e,F).then(h).catch(()=>h([]))},[e,m,x,g,y,r]),p.useEffect(()=>{if(r!=="list")return;u(null),E(null);const F=y?{since:x,until:g}:{days:m};K.transactions(e,{...F,limit:p9e,type:b}).then(u).catch(Z=>E(String(Z)))},[e,m,x,g,y,b,r]);const T=Id(c,p.useCallback(F=>[F.order_id,F.return_reference_number,F.manual_reference,F.rule],[]),{urlKey:"q"}),{activeChips:S,toggleChip:O,clearChips:R,filtered:I}=tu(T.filtered,v$),$=p.useMemo(()=>{if(!I)return null;const F=I.filter(H=>H.amount_incl_vat>0).reduce((H,Y)=>H+Y.amount_incl_vat,0),Z=I.filter(H=>H.amount_incl_vat<0).reduce((H,Y)=>H+Y.amount_incl_vat,0),D=I.reduce((H,Y)=>H+(Y.item_quantity??0),0);return{inflow:F,outflow:Z,net:F+Z,count:I.length,qty:D}},[I]);async function P(F){try{const Z=y?{since:x,until:g}:f9e(m),{blob:D,filename:H,dataAsOf:Y,dataLagHours:M}=await K.downloadExport(e,"transactions",{format:F,since:Z.since,until:Z.until,search:T.q||void 0,type:b||void 0});uc(D,H),Y&&M!=null&&M>24?C({asOf:Y,lagHours:M}):C(null)}catch(Z){E(String((Z==null?void 0:Z.message)||Z))}}return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Sellers",to:"/"},{label:(o==null?void 0:o.display_name)??e,to:`/sellers/${e}`},{label:"Transactions"}],actions:r==="list"?s.jsx(Kf,{onDownload:P,rowCount:I==null?void 0:I.length}):void 0}),s.jsx(As,{items:[{key:"earnings",label:"Earnings",icon:s.jsx(s0,{className:"w-3.5 h-3.5"}),active:r==="earnings",onClick:()=>n("earnings")},{key:"cash",label:"Cash",icon:s.jsx(z2,{className:"w-3.5 h-3.5"}),active:r==="cash",onClick:()=>n("cash")},{key:"products",label:"Products",icon:s.jsx(nse,{className:"w-3.5 h-3.5"}),active:r==="products",onClick:()=>n("products")},{key:"list",label:"Transactions",icon:s.jsx(WT,{className:"w-3.5 h-3.5"}),active:r==="list",onClick:()=>n("list")},{key:"storage-fees",label:"Storage fees",icon:s.jsx(Si,{className:"w-3.5 h-3.5"}),active:r==="storage-fees",onClick:()=>n("storage-fees"),trailing:a!=null&&a>0?s.jsx("span",{className:"ml-1 inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-surface-errorSubtle px-1 text-[11px] font-semibold text-text-error",children:a}):void 0}]}),r==="earnings"?s.jsx(l9e,{slug:e}):r==="cash"?s.jsx(c9e,{slug:e}):r==="products"?s.jsx(u9e,{slug:e}):r==="storage-fees"?s.jsx(n9e,{slug:e}):s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full p-4 md:p-6 space-y-4",children:[$&&s.jsxs(dr,{children:[s.jsx(Ye,{label:"Money in",value:ge($.inflow,{compact:!0}),tone:"success"}),s.jsx(Ye,{label:"Money out",value:ge($.outflow,{compact:!0})}),s.jsx(Ye,{label:"Net",value:ge($.net,{compact:!0}),tone:$.net<0?"error":"default"}),s.jsx(Ye,{label:"Transactions",value:de($.count)})]}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx(Sw,{value:{days:m,since:x,until:g},presets:m9e,onPreset:F=>w({range:F===30?"":String(F),since:"",until:""}),onCustom:(F,Z)=>w({range:"",since:F,until:Z})}),s.jsx(Ni,{value:T.q,onChange:T.setQ,placeholder:"Search by order #, return ref, or ruleâ¦",className:"flex-1 min-w-[220px]"}),s.jsx(nu,{value:b,onChange:v,options:(d==null?void 0:d.map(F=>({value:F.type,count:F.n})))??[],allLabel:"All types"}),s.jsx(hu,{chips:v$,activeChips:S,onToggle:O,onClear:R}),$&&s.jsxs("div",{className:"text-xs text-text-secondary ml-auto flex items-center gap-3 tabular-nums",children:[s.jsxs("span",{children:[de($.count)," rows"]}),s.jsxs("span",{className:"text-text-success",children:["+",ge($.inflow,{compact:!0})]}),s.jsx("span",{className:"text-text-error",children:ge($.outflow,{compact:!0})}),s.jsxs("span",{className:"font-semibold text-text-body",children:["net ",ge($.net,{compact:!0})]})]})]}),A&&s.jsxs(V,{className:"p-3 text-xs text-text-warning bg-surface-warningSubtle border-outline-warning flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold",children:"Heads up â data may be stale."})," ","Transactions were last synced ",s.jsx("span",{className:"font-mono",children:cn(A.asOf)})," ","(",Math.round(A.lagHours),"h ago). Re-sync before relying on this for finance."]}),s.jsx("button",{onClick:()=>C(null),className:"text-text-warning underline underline-offset-2 shrink-0",children:"Dismiss"})]}),N&&s.jsx(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:N}),s.jsx(V,{className:"overflow-hidden",children:s.jsx(dt,{rows:I,columns:b9e,getRowKey:F=>F.transaction_id,defaultSort:{key:"date",direction:"desc"},empty:{title:"No transactions match.",icon:WT},footer:I&&I.length>0&&$?s.jsx("tfoot",{children:s.jsxs("tr",{className:"bg-surface-subtle border-t-2 border-outline-subtle font-medium",children:[s.jsxs("td",{className:"py-2 pl-4 pr-3 text-text-secondary text-xs uppercase tracking-wider",colSpan:2,children:["Filtered total · ",de($.count)," rows"]}),s.jsx("td",{className:B("py-2 pr-3 text-right tabular-nums",$.net>0?"text-text-success":$.net<0?"text-text-error":"text-text-body"),children:ge($.net)}),s.jsx("td",{className:"py-2 pr-3 text-right tabular-nums text-text-secondary",children:de($.qty)}),s.jsx("td",{colSpan:3})]})}):void 0,renderBody:(F,Z)=>!Z||Z.key==="date"?y9e(F).map(H=>s.jsxs(p.Fragment,{children:[s.jsx(v9e,{group:H}),H.rows.map(Y=>w$(Y,M=>k(String(M))))]},`day-${H.day}`)):F.map(H=>w$(H,Y=>k(String(Y))))})})]})}),s.jsx(h9e,{slug:e,txn:j,open:!!_,onClose:()=>k("")})]})}function g9e(e){if(!e)return"â";const t=new Date(`${e}T00:00:00Z`);return isFinite(t.getTime())?t.toLocaleDateString("en-ZA",{weekday:"short",day:"numeric",month:"short",year:"numeric"}):e}function y9e(e){const t=[];for(const n of e){const r=(n.created_at??"").slice(0,10);let a=t[t.length-1];(!a||a.day!==r)&&(a={day:r,rows:[],inflow:0,outflow:0,qty:0},t.push(a)),a.rows.push(n),n.amount_incl_vat>0?a.inflow+=n.amount_incl_vat:n.amount_incl_vat<0&&(a.outflow+=n.amount_incl_vat),a.qty+=n.item_quantity??0}return t}const b9e=[{key:"date",label:"Date",sortable:!0,sticky:!0,getValue:e=>e.created_at},{key:"type",label:"Transaction type",sortable:!0,getValue:e=>e.transaction_type},{key:"amount",label:"Amount (incl. VAT)",sortable:!0,align:"right",getValue:e=>e.amount_incl_vat},{key:"qty",label:"Qty",sortable:!0,align:"right",getValue:e=>e.item_quantity},{key:"order",label:"Order #",sortable:!0,getValue:e=>e.order_id},{key:"return",label:"Return ref",sortable:!0,getValue:e=>e.return_reference_number},{key:"rule",label:"Rule / ref",sortable:!0,getValue:e=>e.rule??e.manual_reference}];function v9e({group:e}){const t=e.inflow+e.outflow,n=e.rows.length;return s.jsxs("tr",{className:"bg-surface-subtle/60 border-y border-outline-faint",children:[s.jsxs("td",{className:"sticky left-0 z-sticky bg-inherit py-1.5 pl-4 pr-3 text-xs font-medium text-text-secondary whitespace-nowrap",colSpan:2,children:[g9e(e.day),s.jsxs("span",{className:"ml-2 text-text-tertiary font-normal",children:["· ",n," txn",n===1?"":"s"]})]}),s.jsx("td",{className:B("py-1.5 pr-3 text-right tabular-nums text-xs font-semibold",t>0?"text-text-success":t<0?"text-text-error":"text-text-body"),title:`+${ge(e.inflow)} / ${ge(e.outflow)}`,children:ge(t)}),s.jsx("td",{className:"py-1.5 pr-3 text-right tabular-nums text-xs text-text-tertiary",children:e.qty||""}),s.jsx("td",{colSpan:3})]})}function w$(e,t){return s.jsxs("tr",{onClick:()=>t(e.transaction_id),className:"border-b border-outline-faint last:border-0 bg-surface hover:bg-surface-subtle/50 cursor-pointer",children:[s.jsx("td",{className:"sticky left-0 z-sticky bg-inherit py-2 pl-4 pr-3 text-text-secondary whitespace-nowrap",children:cn(e.created_at)}),s.jsx("td",{className:"py-2 pr-3 text-text-body font-mono text-body-sm",children:e.transaction_type}),s.jsx("td",{className:B("py-2 pr-3 text-right tabular-nums font-medium",e.amount_incl_vat>0?"text-text-success":e.amount_incl_vat<0?"text-text-error":"text-text-body"),children:ge(e.amount_incl_vat)}),s.jsx("td",{className:"py-2 pr-3 text-right tabular-nums text-text-secondary",children:e.item_quantity??"â"}),s.jsx("td",{className:"py-2 pr-3 tabular-nums text-text-secondary",children:e.order_id?`#${e.order_id}`:"â"}),s.jsx("td",{className:"py-2 pr-3 font-mono text-xs text-text-secondary",children:e.return_reference_number??"â"}),s.jsx("td",{className:"py-2 pr-4 text-text-secondary text-xs",children:e.rule??e.manual_reference??"â"})]},e.transaction_id)}function T3({formSpec:e,submittedValues:t,onSubmit:n,sellerSlug:r,prefill:a}){const i=p.useMemo(()=>_V.safeParse(e),[e]),o=!!t,l=p.useMemo(()=>
890{if(!i.success)return{};if(t)return t;const _={};for(const k of i.data.fields)k.type==="checkbox-group"?_[k.name]=("default"in k?k.default:void 0)??[]:_[k.name]=("default"in k?k.default:void 0)??"",a&&k.name in a&&(_[k.name]=a[k.name]);return _},[i,t,a]),[c,u]=p.useState(l),[d,h]=p.useState({}),[f,m]=p.useState({}),[x,g]=p.useState(!1),[y,b]=p.useState(null);if(!i.success)return s.jsx("div",{className:"not-prose my-3 rounded-lg border border-outline-error bg-surface-errorSubtle px-4 py-3 text-body-sm text-text-error",children:"Invalid form spec â couldn't render this form. The model may have malformed the request."});const v=i.data;async function w(){b(null);const _=Q8e(v,c);if(!_.ok){m(_.errors);return}m({}),g(!0);try{const k=await n(_.values,d)??{ok:!0};if(!k.ok){k.errors&&m(k.errors),k.message&&b(k.message),g(!1);return}}catch(k){b(k instanceof Error?k.message:String(k)),g(!1)}}return s.jsxs("div",{className:"not-prose my-3 rounded-lg border border-outline-subtle bg-surface px-4 py-3 shadow-xs",children:[v.intro?s.jsx("div",{className:"mb-3 text-body-sm text-text-body",children:v.intro}):null,s.jsx("div",{className:"flex flex-col gap-3",children:v.fields.map(_=>s.jsx(w9e,{field:_,value:c[_.name],error:f[_.name],disabled:o||x,sellerSlug:r,onChange:k=>u(j=>({...j,[_.name]:k})),onFile:k=>h(j=>({...j,[_.name]:k}))},_.name))}),o?s.jsxs("div",{className:"mt-3 flex items-center gap-1.5 text-body-sm text-text-success",children:[s.jsx(Xt,{className:"h-4 w-4"}),"Submitted."]}):s.jsxs("div",{className:"mt-4 flex items-center gap-2",children:[s.jsxs("button",{type:"button",disabled:x,onClick:w,className:"inline-flex items-center gap-1.5 rounded-md bg-intent-brand px-3.5 py-2 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover focus-visible:outline-none focus-visible:shadow-focus disabled:opacity-50 disabled:cursor-not-allowed",children:[x?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):null,v.submit_label??"Submit"]}),y?s.jsx("span",{className:"text-body-xs text-text-error",children:y}):null]})]})}function w9e({field:e,value:t,error:n,disabled:r,sellerSlug:a,onChange:i,onFile:o}){var v;const l="required"in e?e.required:e.type==="confirm",c=e.type==="select"&&"options_source"in e?(v=e.options_source)==null?void 0:v.endpoint:void 0,[u,d]=p.useState(null),[h,f]=p.useState(!1),[m,x]=p.useState(null);p.useEffect(()=>{if(!c||!a)return;let w=!1;return f(!0),x(null),K.sops.options(a,c).then(_=>{w||d(_.options??[])}).catch(_=>{w||x(_ instanceof Error?_.message:String(_))}).finally(()=>{w||f(!1)}),()=>{w=!0}},[c,a]);const g=s.jsxs("label",{className:"block text-body-sm font-medium text-text-primary",children:[e.label,l?s.jsx("span",{className:"text-text-error",children:" *"}):null]}),y=e.help?s.jsx("div",{className:"mt-1 text-body-xs text-text-secondary",children:e.help}):null,b=n?s.jsx("div",{className:"mt-1 text-body-xs text-text-error",children:n}):null;if(e.type==="text"||e.type==="date"||e.type==="number"){const w=e.type==="number"?"number":e.type==="date"?"date":"text";return s.jsxs("div",{children:[g,s.jsx("input",{type:w,name:e.name,value:t??"",placeholder:e.placeholder??"",disabled:r,onChange:_=>i(_.target.value),className:"mt-1 block w-full rounded-md border border-outline bg-surface px-3 py-1.5 text-body-md text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus disabled:bg-surface-subtle disabled:text-text-secondary"}),y,b]})}if(e.type==="textarea")return s.jsxs("div",{children:[g,s.jsx("textarea",{name:e.name,value:t??"",placeholder:e.placeholder??"",disabled:r,rows:4,onChange:w=>i(w.target.value),className:"mt-1 block w-full rounded-md border border-outline bg-surface px-3 py-1.5 text-body-md text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus disabled:bg-surface-subtle disabled:text-text-secondary"}),y,b]});if(e.type==="checkbox-group"){const w=new Set(t??[]);return s.jsxs("div",{children:[g,s.jsx("div",{className:"mt-1.5 flex flex-col gap-1",children:e.options.map(_=>s.jsxs("label",{className:"flex items-center gap-2 text-body-sm text-text-body",children:[s.jsx("input",{type:"checkbox",checked:w.has(_),disabled:r,onChange:k=>{const j=new Set(w);k.target.checked?j.add(_):j.delete(_),i(Array.from(j))},className:"rounded border-outline text-intent-brand focus-visible:shadow-focus"}),_]},_))}),y,b]})}if(e.type==="radio-group")return s.jsxs("div",{children:[g,s.jsx("div",{className:"mt-1.5 flex flex-col gap-1",children:e.options.map(w=>s.jsxs("label",{className:"flex items-center gap-2 text-body-sm text-text-body",children:[s.jsx("input",{type:"radio",name:e.name,value:w,checked:t===w,disabled:r,onChange:_=>i(_.target.value),className:"border-outline text-intent-brand focus-visible:shadow-focus"}),w]},w))}),y,b]});if(e.type==="select"){const w=!!c,_=w?u??[]:e.options??[],k=w?h?"Loadingâ¦":m?"Couldn't load options":_.length===0?"N
890one available yet":"Any (no filter)":"Selectâ¦";return s.jsxs("div",{children:[g,s.jsxs("select",{name:e.name,value:t??"",disabled:r||w&&h,onChange:j=>i(j.target.value),className:"mt-1 block w-full rounded-md border border-outline bg-surface px-3 py-1.5 text-body-md text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus disabled:bg-surface-subtle disabled:text-text-secondary",children:[s.jsx("option",{value:"",disabled:!w,children:k}),_.map(j=>s.jsx("option",{value:j,children:j},j))]}),w&&m?s.jsxs("div",{className:"mt-1 text-body-xs text-text-error",children:["Couldn't load options: ",m]}):null,y,b]})}if(e.type==="file"){const w=typeof t=="string"?t:"";return s.jsxs("div",{children:[g,s.jsx("input",{type:"file",name:e.name,accept:e.accept,disabled:r,onChange:_=>{var j;const k=(j=_.target.files)==null?void 0:j[0];k&&(o==null||o(k),i(k.name))},className:"mt-1 block w-full text-body-sm text-text-secondary file:mr-3 file:rounded-md file:border-0 file:bg-intent-brand file:px-3 file:py-1.5 file:text-body-sm file:font-medium file:text-text-inverse hover:file:bg-intent-brandHover disabled:opacity-50"}),w?s.jsxs("div",{className:"mt-1 text-body-xs text-text-secondary",children:["Selected: ",w]}):null,y,b]})}return e.type==="confirm"?s.jsxs("div",{children:[g,s.jsx("input",{type:"text",name:e.name,value:t??"",placeholder:`Type "${e.expected}" to confirm`,disabled:r,onChange:w=>i(w.target.value),className:"mt-1 block w-full rounded-md border border-outline-warning bg-surface px-3 py-1.5 text-body-md text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus disabled:bg-surface-subtle"}),y,b]}):null}function _9e({attachment:e,onRemove:t}){const n=Math.max(1,Math.round(e.size/1024)),r=e.kind==="image"&&e.data&&e.mediaType?`data:${e.mediaType};base64,${e.data}`:null,a=e.uploadState==="uploading"?_e:e.uploadState==="error"?yt:Xt,i=e.uploadState==="uploading"?"Uploading":e.uploadState==="error"?e.uploadError||"Upload failed":"Uploaded";return s.jsxs("div",{className:B("inline-flex items-center gap-1.5 bg-surface-subtle border rounded-md px-2 py-1 text-body-xs text-text-body max-w-[220px]",e.uploadState==="error"?"border-outline-error":"border-outline-subtle"),title:i,children:[r?s.jsx("img",{src:r,alt:"",className:"w-5 h-5 rounded object-cover shrink-0"}):e.kind==="image"?s.jsx(Qy,{className:"w-3 h-3 shrink-0 text-text-secondary"}):s.jsx(il,{className:"w-3 h-3 shrink-0 text-text-secondary"}),s.jsx("span",{className:"truncate",title:e.name,children:e.name}),s.jsxs("span",{className:"text-text-tertiary shrink-0",children:[n,"KB"]}),s.jsx(a,{className:B("w-3 h-3 shrink-0",e.uploadState==="uploading"&&"animate-spin text-text-secondary",e.uploadState==="uploaded"&&"text-text-success",e.uploadState==="error"&&"text-text-error"),"aria-hidden":!0}),s.jsx("span",{className:"sr-only",children:i}),s.jsx("button",{type:"button",onClick:t,className:"ml-0.5 -mr-0.5 p-0.5 rounded hover:bg-surface-sunken text-text-secondary shrink-0",title:"Remove","aria-label":`Remove ${e.name}`,children:s.jsx(Bn,{className:"w-3 h-3"})})]})}function k9e({status:e,messages:t,onRetry:n}){if(e.kind==="error"){const r=Nce(e.message),a=String(e.message||"").trim(),i=a.length>0&&a!==r;return s.jsxs("div",{className:"mt-4 text-sm text-text-error bg-surface-errorSubtle border border-outline-error rounded-lg p-3 space-y-2",children:[s.jsx("div",{children:r}),i&&s.jsxs("details",{className:"text-xs text-text-secondary",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:"Technical details"}),s.jsx("pre",{className:"mt-1 whitespace-pre-wrap break-words font-mono text-text-tertiary",children:a})]}),ZO(e,t)&&s.jsx(W,{type:"button",intent:"destructive",variant:"outline",size:"sm",onClick:n,children:"Try again"})]})}return e.kind==="stopped"?s.jsxs("div",{className:"mt-4 text-sm text-text-secondary bg-surface-sunken border border-outline-subtle rounded-lg px-3 py-2 flex items-center gap-3",children:[s.jsxs("span",{children:["Stopped at ",Sce(e.elapsedMs)]}),ZO(e,t)&&s.jsx(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",onClick:n,children:"Continue"})]}):null}function j9e({status:e}){const[t,n]=p.useState(""),r=p.useRef(e.kind);return p.useEffect(()=>{const a=r.current;r.current=e.kind,e.kind==="streaming"?n("Assistant is responding"):e.kind==="error"?n("The assistant ran into a problem"):e.kind==="stopped"?n("Generation stopped"):e.kind==="insufficient_credits"?n("Out of credits"):a==="streaming"&&e.kind==="idle"&&n("Response complete")},[e]),s.jsx("div",{className:"sr-only","aria-live":"polite","aria-atomic":"true",children:t})}function N9e({onClick:e}){return s.jsxs("button",{type:"button",onClick:e,className:"absolute bottom-3 left-1/2 -translate-x-1/2 z-10 inline-flex items-center gap-1.5 rounded-full border border-outline-subtle bg-surface px-3 py-1.5 text-xs font-medium text-text-body shadow-md hover:bg-surface-subtle",children:[s.jsx(Pn,{className:"w-3.5 h-3.5"}),"Jump to latest"]})}function S9e(e){return Array.isArray(e)?e.filter(t=>t&&t.kind==="text"&&typeof t.text=="string").map(t=>t.text).join(` 891 892`).trim():""}
892function C9e(e,t=Date.now()){if(!e)return null;const n=new Date(String(e));if(Number.isNaN(n.getTime()))return null;const r=t-n.getTime();if(r<45e3)return"just now";if(r<3600*1e3)return`${Math.max(1,Math.round(r/6e4))}m ago`;if(r<1440*60*1e3)return`${Math.max(1,Math.round(r/36e5))}h ago`;const a=Math.floor(r/(1440*60*1e3));return a===1?"yesterday":a<30?`${a}d ago`:a<365?`${Math.floor(a/30)}mo ago`:`${Math.floor(a/365)}y ago`}function E9e({text:e,ts:t,showRetry:n,onRetry:r}){const[a,i]=p.useState(!1),o=C9e(t),l=e.trim().length>0;async function c(){if(l)try{await navigator.clipboard.writeText(e),i(!0),window.setTimeout(()=>i(!1),1500)}catch{i(!1)}}return!o&&!l&&!n?null:s.jsxs("div",{className:"flex items-center gap-2 pt-0.5",children:[o&&s.jsx("span",{className:"text-body-xs text-text-tertiary",children:o}),s.jsxs("div",{className:"flex items-center gap-0.5",children:[l&&s.jsx("button",{type:"button",onClick:()=>void c(),className:"p-1 rounded text-text-tertiary hover:text-text-body hover:bg-surface-sunken","aria-label":a?"Copied":"Copy reply",title:a?"Copied":"Copy",children:a?s.jsx(fn,{className:"w-3.5 h-3.5 text-text-success"}):s.jsx(bi,{className:"w-3.5 h-3.5"})}),n&&s.jsx("button",{type:"button",onClick:r,className:"p-1 rounded text-text-tertiary hover:text-text-body hover:bg-surface-sunken","aria-label":"Retry this reply",title:"Retry",children:s.jsx(_o,{className:"w-3.5 h-3.5"})})]})]})}const A9e=80;function T9e(e,t){const n=p.useRef(!0),[r,a]=p.useState(!1),i=p.useCallback(()=>{const l=e.current;if(!l)return;const u=l.scrollHeight-l.scrollTop-l.clientHeight<=A9e;n.current=u,a(!u)},[e]),o=p.useCallback(()=>{const l=e.current;l&&(l.scrollTop=l.scrollHeight,n.current=!0,a(!1))},[e]);return p.useEffect(()=>{const l=e.current;if(l){if(!n.current){a(!0);return}l.scrollTop=l.scrollHeight,a(!1)}},t),{showJump:r,onScroll:i,jumpToLatest:o}}function O9e(){return s.jsx("div",{className:"absolute inset-0 z-20 rounded-xl border-2 border-dashed border-outline-brand bg-surface-brandSubtle/80 flex items-center justify-center pointer-events-none",children:s.jsx("span",{className:"text-sm font-medium text-text-brand",children:"Drop files to attach"})})}function I9e(){const[e,t]=p.useState(()=>typeof window<"u"?window.matchMedia("(pointer: coarse)").matches:!1);return p.useEffect(()=>{const n=window.matchMedia("(pointer: coarse)"),r=()=>t(n.matches);return r(),n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),e}function P9e(e){const t=String(e??"").trim();return t?/type \//i.test(t)||/\/\s*for skills/i.test(t)?t:`${t.replace(/[.â¦]+$/,"")}, or type / for skills`:"Ask anything, or type / for skills"}function R9e(e,t){const n=String(e??""),r=Math.max(0,Math.min(Number(t)||0,n.length)),a=r>0?n[r-1]:"",o=r>0&&a!=="/"&&!/\s/.test(a)?" /":"/";return{next:n.slice(0,r)+o+n.slice(r),cursor:r+o.length}}function D9e(e){if(!e)return[];if(e.files&&e.files.length>0)return Array.from(e.files);const t=e.items;if(!t)return[];const n=[];for(let r=0;r<t.length;r++){const a=t[r];if(a&&a.kind==="file"&&typeof a.getAsFile=="function"){const i=a.getAsFile();i&&n.push(i)}}return n}const M9e={"find-bundle-candidates":"Looking for multi-pack opportunities","monthly-account-rollup":"Building the monthly review","quarterly-account-rollup":"Building the quarterly review","weekly-payout-rollup":"Building the weekly payout review","returns-report":"Looking into returns","sales-velocity":"Reviewing sales velocity","welcome-pack":"Putting together the welcome pack"},$9e=new Set(["run_skill","request_user_input","initiate_subscription","validate_and_attach_takealot_key"]);function O3(e){const t=String(e??"").replace(/[_-]+/g," ").trim();return t?t.charAt(0).toUpperCase()+t.slice(1).toLowerCase():""}function I3(e,t){const n=String(e??"").trim();return n&&(M9e[n]||t&&t[n]||O3(n))||"Working on your request"}function L9e(e,t){if(!e)return null;switch(e){case"get_bundle_candidates":return"Scoring bundle candidates";case"get_monthly_summary":return t!=null&&t.yearMonth?`Pulling numbers for ${t.yearMonth}`:"Pulling the month's numbers";case"get_quarterly_summary":return t!=null&&t.year&&(t!=null&&t.quarter)?`Pulling Q${t.quarter} ${t.year} (with YoY)`:"Pulling quarterly numbers";case"get_weekly_payout_summary":return"Reconstructing the payout bridge";case"get_returns_analysis":return"Analysing returns";case"get_sales_velocity":return"Comparing inbound vs sales";case"sync_one":return t!=null&&t.kind?`Refreshing ${t.kind}`:"Refreshing data";case"list_reports":return null;case"read_report":return"Reading prior findings";case"write_report":return"Drafting the report";default:return O3(e)}}function pq(e,t){var i;if(!e||e.length===0)return[];const n=[],r={};let a=null;for(const o of e){if(o.kind==="skill_start"){a={key:"intro",label:I3(o.skill_name,t),status:"running"},n.push(a);continue}if(o.kind==="tool_start"&&o.name){const l=L9e(o.name,o.input);if(!l)continue;const c={key:`${o.name}-${n.length}`,label:l,status:"running"};n.push(c),r[o.name]=c;continue}if(o.kind==="tool_result"&&o.name){const l=r[o.name];if(!l)continue;o.is_error?(l.status="failed",l.detail=typeof((i=o.summary)==null?void 0:i.error)=="str
892ing"?o.summary.error:"the step did not complete"):l.status="done";continue}if(o.kind==="skill_done"){a&&a.status==="running"&&(a.status=o.ok?"done":"failed");for(const l of n)l.status==="running"&&!o.ok&&(l.status="failed",l.detail=o.error)}}return n}function xq(e){const t=(e==null?void 0:e.status)==="running",n=(e==null?void 0:e.status)==="error",a={initiate_subscription:["Setting up your subscriptionâ¦","Subscription ready","Couldn't start your subscription"],validate_and_attach_takealot_key:["Validating your Takealot keyâ¦","Store connected","Couldn't validate your key"],run_skill:["Working on your requestâ¦","Done","That didn't go through"]}[e==null?void 0:e.name];if(a)return t?a[0]:n?a[2]:a[1];const i=O3(e==null?void 0:e.name)||"That step";return t?`${i}â¦`:n?`Couldn't ${i.charAt(0).toLowerCase()}${i.slice(1)}`:i}function F9e(e){if(!e||$9e.has(e.name)||e.awaitingConfirm||e.status==="running"||e.status==="error")return!1;const t=e.summary&&typeof e.summary=="object"?e.summary:null;return t&&(t.authorization_url||t.manage_url||t.invite_link)?!1:e.status==="done"}function B9e(e){const t=[];let n=0;const r=()=>{n>0&&(t.push({kind:"folded",count:n}),n=0)};return(e||[]).forEach((a,i)=>{if((a==null?void 0:a.kind)==="tool"&&F9e(a)){n+=1;return}r(),t.push({kind:"part",part:a,index:i})}),r(),t}function U9e(e,t){var o;if(!Array.isArray(e)||e.length===0)return"Working";const n=e[e.length-1];if(!n||n.role!=="assistant")return"Working";const r=Array.isArray(n.parts)?n.parts:[],a=r.filter(l=>l&&l.kind==="tool"),i=a[a.length-1];if(!i)return r.length===0?"Working":"Writing";if(i.name==="run_skill"){const l=pq(i.progress,t),c=[...l].reverse().find(u=>u.status==="running");return c?c.label:l.length?l[l.length-1].label:I3((o=i.input)==null?void 0:o.skill_name,t)}return xq(i)}const z9e=[{name:"What to do",description:"Your weekly action list.",skills:["action-list","my-week"]},{name:"See what's happening",description:"Sales, top sellers, anomalies.",skills:["whats-selling","wishlist-demand","sales-velocity","abc-classification","anomaly-scan","sales-export"]},{name:"Grow sales",description:"New products, bundles, advertising.",skills:["new-product-ideas","find-bundle-candidates","demand-forecast","whitespace-keywords","autocomplete-expansion","customer-language-miner","keyword-trend","brainstorm-variants","new-arrival-ramp","promotion-builder","promo-effectiveness","ppc-strategy-advisor","ppc-opportunity-finder","sponsored-ad-intel","ad-performance-report","ads-watchdog"]},{name:"Fix returns",description:"Why customers return, what to fix.",skills:["return-coaching","return-reason-deepdive","review-vs-returns","return-rate-spike","damaged-in-transit","returns-report","returns-export","new-low-star-review-alert"]},{name:"Fix listings",description:"Title, image, attribute, suppression.",skills:["listing-quality-audit","listing-suppression-watch","variant-consolidation","pdp-variant-audit","attribute-completion","image-gap","title-rewrite","normalize-skus","category-mismatch","taxonomy-mapper"]},{name:"Stock & inventory",description:"Stockouts, replens, seasonality.",skills:["stockout-risk","overstock-flush","replen-plan","replen-builder","seasonality-map","dc-allocation-plan","inventory-snapshot-export","inbound-receive-audit"]},{name:"Money & tax",description:"Payouts, VAT, fees, margins.",skills:["payout-explainer","weekly-payout-rollup","payout-statement-pdf","payouts-export","transactions-ledger-export","vat-export","stock-recon-claim","cash-flow-projection","fees-export","margin-audit","packaging-cost-audit","fee-shock-detector","balance-mismatch"]},{name:"Get found on Takealot",description:"Search rank, competitors, brand mix.",skills:["keyword-rank-tracker","share-of-shelf","competitor-scan","review-themes","brand-share-snapshot","category-rank-snapshot","category-demand-pulse","search-share-of-voice","trending-watch","market-intel-pack","competitive-pricing","product-buybox-lookup","pricing-strategy-advisor"]},{name:"Account reviews",description:"Monthly/quarterly rollups, welcome pack.",skills:["monthly-account-rollup","quarterly-account-rollup","qbr-builder","welcome-pack","am-handover-pack"]},{name:"AM portfolio",description:"Cross-seller view for AMs.",skills:["portfolio-overview","at-risk-seller","seller-comparison","call-prep-brief","weekly-am-digest"]}];function W9e(e){const t=e.filter(l=>l.origin==="user"),n=e.filter(l=>l.origin!=="user"),r=[];t.length>0&&r.push({name:"Your skills",description:"Skills you created.",skills:t});const a=new Map(n.map(l=>[l.name,l])),i=new Set;for(const l of z9e){const c=[];for(const u of l.skills){const d=a.get(u);d&&(c.push(d),i.add(u))}c.length>0&&r.push({name:l.name,description:l.description,skills:c})}const o=n.filter(l=>!i.has(l.name));return o.length>0&&r.push({name:"Other",skills:o}),r}function K9e(){const[e,t]=p.useState(null),n=Rt();if(p.useEffect(()=>{let d=!0;const h=()=>{K.billingUsageSummary().then(m=>d&&t(m)).catch(()=>{})};h();const f=()=>h();return window.addEventListener("gadjet:chat-saved",f),()=>{d=!1,window.removeEventListener("gadjet:chat-saved",f)}},[]),!e||e.kind==="not_applicable"||e.kind==="no_account")return null;if(e.kind==="included"){const d=B("text-body-xs font-medium px-2 py-1 rounded border transition-colors","bg-surface-successSubtle text-text-success border-outline-success");return wr()?s.jsx("span",{title:"Chat is included in your managed retainer",className:d,children:"Included"}):s.jsx("button",{onClick:()=>n("/settings/workspace/billing"),title:"Chat is included in your managed retainer",className:d,children:"Included"})}if(e.kind!=="cycle")return null;const r=Number(e.grant.balance_zar||0),a=Number(e.topup.balance_zar||0),i=r+a,o=e.grant.remaining_pct,l=o>25?"bg-surface-subtle text-text-secondary border-outline-subtle hover:bg-surface-sunken":o>10?"bg-surface-warningSubtle text-text-warning border-outline-warning":"bg-surface-errorSubtle text-text-error border-outline-error",c=i>=100?`R${Math.round(i)}`:`R${i.toFixed(2)}`,u=a>0?`R${r.toFixed(2)} grant + R${a.toFixed(2)} top-up â ${o}% of this month's grant remaining (renews in ${e.cycle.days_remaining} days)`:`R${r.toFixed(2)} remaining â ${o}% of this month's grant (renews in ${e.cycle.days_remaining} days)`;return wr()?s.jsx("span",{title:u,className:B("text-body-xs font-medium px-2 py-1 rounded border",l),children:c}):s.jsx("button",{onClick:()=>n("/settings/workspace/billing"),title:u,className:B("text-body-xs font-medium px-2 py-1 rounded border transition-colors",l),children:c})}function jv({brand:e,className:t}){const n=B("w-4 h-4 shrink-0",t);return e==="gadjet"?s.jsx("img",{src:"/favicon.png",alt:"",className:B(n,"object-contain")}):e==="anthropic"?s.jsx("svg",{viewBox:"0 0 24 24",className:n,fill:"#d97757","aria-hidden":"true",children:s.jsx("path",{d:"M13.827 3.52h3.603L24 20h-3.603l-6.57-16.48zm-7.258 0h3.767L16.906 20h-3.674l-1.343-3.461H5.017l-1.344 3.46H0L6.57 3.522zm4.132 9.959L8.453 7.687 6.205 13.48H10.7z"})}):e==="xai"?s.jsx("svg",{viewBox:"0 0 24 24",className:B(n,"text-text-primary"),fill:"currentColor","aria-hidden":"true",children:s.jsx("path",{d:"M9.27 15.29l7.978-5.897c.391-.29.95-.177 1.137.272.98 2.369.542 5.215-1.41 7.169-1.951 1.954-4.667 2.382-7.149 1.406l-2.711 1.257c3.889 2.661 8.611 2.003 11.562-.953 2.341-2.344 3.066-5.539 2.388-8.42l.006.007c-.983-4.232.242-5.924 2.75-9.383.06-.082.12-.164.179-.248l-3.301 3.305v-.01L9.267 15.292M7.623 16.723c-2.792-2.67-2.31-6.801.071-9.184
8921.761-1.763 4.647-2.483 7.166-1.425l2.705-1.25a7.808 7.808 0 00-1.829-1A8.975 8.975 0 005.984 5.83c-2.533 2.536-3.33 6.436-1.962 9.764 1.022 2.487-.653 4.246-2.34 6.022-.599.63-1.199 1.259-1.682 1.925l7.62-6.815"})}):e==="openai"?s.jsx("svg",{viewBox:"0 0 24 24",className:B(n,"text-text-primary"),fill:"currentColor","aria-hidden":"true",children:s.jsx("path",{d:"M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z"})}):s.jsx(Ht,{className:n})}const H9e={price:5,data:"wontTrain",vision:!0,reasoning:5,speed:2,writing:5},gq={price:4,data:"wontTrain",vision:!0,reasoning:5,speed:3,writing:5},yq={price:3,data:"wontTrain",vision:!0,reasoning:4,speed:4,writing:4},bq={price:1,data:"wontTrain",vision:!0,reasoning:2,speed:5,writing:3},V9e={price:2,data:"wontTrain",vision:!0,reasoning:5,speed:3,writing:4},q9e={price:2,data:"wontTrain",vision:!1,reasoning:4,speed:3,writing:4},G9e={price:1,data:"wontTrain",vision:!1,reasoning:3,speed:4,writing:3},Y9e={price:1,data:"wontTrain",vision:!1,reasoning:5,speed:2,writing:3},Z9e={price:5,data:"wontTrain",vision:!0,reasoning:5,speed:2,writing:5},X9e={price:3,data:"wontTrain",vision:!0,reasoning:5,speed:4,writing:5},J9e={price:1,data:"wontTrain",vision:!0,reasoning:3,speed:5,writing:4},P3=[{id:"sonnet",name:"Gadjet Pro",hint:"Everyday default",detail:yq},{id:"opus",name:"Gadjet Max",hint:"Deepest analysis, heaviest work",detail:gq},{id:"haiku",name:"Gadjet Lite",hint:"Quick questions, fast replies",detail:bq}],R3=[{name:"Anthropic",brand:"anthropic",connected:!0,models:[{id:"fable-5.1",name:"Fable 5.1",detail:H9e},{id:"opus-5.5",name:"Opus 5.5",detail:gq},{id:"sonnet-5.5",name:"Sonnet 5.5",detail:yq},{id:"haiku-4.5",name:"Haiku 4.5",detail:bq}]},{name:"xAI",brand:"xai",connected:!0,models:[{id:"grok-4.7",name:"Grok 4.7",detail:V9e},{id:"grok-4.5",name:"Grok 4.5",detail:q9e},{id:"grok-4.3",name:"Grok 4.3",detail:G9e},{id:"grok-4.20-reasoning",name:"Grok 4.20 (reasoning)",detail:Y9e}]},{name:"OpenAI",brand:"openai",connected:!0,models:[{id:"gpt-6-astra",name:"GPT-6 Astra",detail:Z9e},{id:"gpt-6.1-sol",name:"GPT-6.1 Sol",detail:X9e},{id:"gpt-6-luna",name:"GPT-6 Luna",detail:J9e}]}];function Q9e(e,t){if(e==="auto")return t;const n=P3.find(r=>r.id===e);if(n)return n.name;for(const r of R3){const a=r.models.find(i=>i.id===e);if(a)return a.name}return t}function eUe(e){if(e==="auto"||P3.some(t=>t.id===e))return"gadjet";for(const t of R3)if(t.models.some(n=>n.id===e))return t.brand;return"gadjet"}function Uk({value:e}){return s.jsx("span",{className:"flex items-center gap-0.5","aria-hidden":"true",children:Array.from({length:5},(t,n)=>s.jsx("span",{className:B("h-1.5 w-1.5 rounded-full",n<e?"bg-surface-inverse":"bg-outline-faint")},n))})}function tUe({value:e}){return s.jsx("span",{className:"flex items-center gap-0.5","aria-hidden":"true",children:Array.from({length:5},(t,n)=>s.jsx("span",{className:B("text-[10px] font-semibold leading-none w-2 text-center",n<e?"text-text-brand":"text-outline-faint"),children:"$"},n))})}function ch({label:e,children:t}){return s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-tertiary",children:e}),t]})}function nUe({brand:e,name:t,d:n}){return s.jsxs("div",{className:"w-56 rounded-md border border-outline-subtle bg-surface shadow-lg p-3",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm font-medium text-text-primary",children:[s.jsx(jv,{brand:e,className:"w-4 h-4"}),t]}),s.jsxs("div",{className:"space-y-1.5",children:[s.jsx(ch,{label:"Price",children:s.jsx(tUe,{value:n.price})}),s.jsx(ch,{label:"Data",children:n.data==="wontTrain"?s.jsxs("span",{className:"flex items-center gap-1 text-body-xs font-medium text-success",children:[s.jsx(Kre,{className:"w-3.5 h-3.5"}),"Won't train"]}):s.jsx("span",{className:"text-body-xs text-text-tertiary",children:"May be used"})}),s.jsx(ch,{label:"Vision",children:n.vision?s.jsx(fn,{className:"w-3.5 h-3.5 text-success"}):s.jsx(Bn,{className:"w-3.5 h-3.5 text-text-tertiary"})})]}),s.jsx("div",{className:"my-2 border-t border-outline-faint"}),s.jsxs("div",{className:"space-y-1",children:[s.jsx(ch,{label:"Reasoning",children:s.jsx(Uk,{value:n.reasoning})}),s.jsx(ch,{label:"Speed",children:s.jsx(Uk,{value:n.speed})}),s.jsx(ch,{label:"Writing",children:s.jsx(Uk,{value:n.writing})})]})]})}function _$({row:e,brand:t,selected:n,disabled:r,onPick:a}){const i=s.jsxs("button",{type:"button",role:"menuitem",disabled:r,onClick:()=>!r&&a(e.id),title:r?"Not connected yet":void 0,className:B("w-full text-left px-3 py-1.5 rounded flex items-center justify-between gap-2",r?"opacity-40 cursor-not-allowed":"hover:bg-surface-subtle",n&&"bg-surface-subtle"),children:[s.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(jv,{brand:t}),s.jsxs("span",{className:"flex flex-col min-w-0",children:[s.jsx("span",{className:"text-xs font-medium text-text-primary truncate",children:e.name}),e.hint&&s.jsx("span",{className:"text-body-xs text-text-secondary leading-tight truncate",children:e.hint})]})]}),s.jsxs("span",{className:"flex items-center gap-1.5 shrink-0",children:[n&&s.jsx("span",{className:"text-text-brand text-xs leading-none",children:"â"}),e.detail&&s.jsx(fr,{className:"w-3.5 h-3.5 opacity-40 group-hover/row:opacity-80"})]})]});return e.detail?s.jsxs(QY,{delayDuration:0,disableHoverableContent:!0,children:[s.jsx(eZ,{asChild:!0,children:s.jsx("div",{className:"group/row relative",children:i})}),s.jsx(tZ,{children:s.jsx(nZ,{side:"right",align:"center",sideOffset:6,collisionPadding:8,className:"z-tooltip",children:s.jsx(nUe,{brand:t,name:e.name,d:e.detail})})})]}):s.jsx("div",{className:"group/row relative",children:i})}function k$({children:e,right:t}){return s.jsxs("div",{className:"flex items-center justify-between px-3 pt-2 pb-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-tertiary font-semibold",children:e}),t]})}
892function rUe({value:e,onChange:t,defaultLabel:n="Auto"}){const[r,a]=p.useState(!1),i=o=>{t(o),a(!1)};return s.jsxs(Tf,{open:r,onOpenChange:a,children:[s.jsx(Of,{asChild:!0,children:s.jsxs("button",{type:"button",className:"text-body-xs font-medium flex items-center gap-1.5 rounded-md border border-outline-subtle hover:bg-surface-subtle px-2 py-1 text-text-secondary",title:"Switch model",children:[s.jsx(jv,{brand:eUe(e),className:"w-3.5 h-3.5"}),Q9e(e,n),s.jsx(Pn,{className:"w-3 h-3 opacity-60"})]})}),s.jsxs($d,{side:"top",align:"start",className:"w-72 overflow-visible",children:[s.jsxs("button",{type:"button",role:"menuitem",onClick:()=>i("auto"),className:B("w-full text-left px-3 py-2 flex items-center gap-2 rounded hover:bg-surface-subtle",e==="auto"&&"bg-surface-subtle"),children:[s.jsx(jv,{brand:"gadjet"}),s.jsxs("span",{className:"flex flex-col",children:[s.jsxs("span",{className:"text-xs font-medium text-text-primary",children:["Auto (",n,")"]}),s.jsx("span",{className:"text-body-xs text-text-secondary leading-tight",children:"Use the default for this chat surface."})]})]}),s.jsx("div",{className:"my-1 border-t border-outline-faint"}),s.jsx(k$,{children:"Gadjet"}),P3.map(o=>s.jsx(_$,{row:o,brand:"gadjet",selected:e===o.id,onPick:i},o.id)),R3.map(o=>s.jsxs("div",{children:[s.jsx("div",{className:"my-1 border-t border-outline-faint"}),s.jsx(k$,{right:o.connected?void 0:s.jsxs("span",{className:"text-[10px] flex items-center gap-1 text-text-tertiary",children:[s.jsx(Bl,{className:"w-3 h-3"}),"Connect"]}),children:o.name}),o.models.map(l=>s.jsx(_$,{row:l,brand:o.brand,selected:e===l.id,disabled:!o.connected,onPick:i},l.id))]},o.name))]})]})}const sUe=[{zar:250,label:"R250",hint:"starter top-up"},{zar:500,label:"R500",hint:"matches monthly grant"},{zar:1e3,label:"R1000",hint:"heavy user"}];function vq({context:e="billing",returnTo:t,onToppedUp:n,className:r=""}){const[a,i]=p.useState({kind:"idle"}),o=p.useRef(null),l=p.useRef(!1);p.useEffect(()=>{let d=!0;return K.billingUsageSummary().then(h=>{d&&(h.kind==="cycle"?o.current=Number(h.grant.balance_zar||0)+Number(h.topup.balance_zar||0):o.current=0)}).catch(()=>{o.current=0}),()=>{d=!1}},[]);const c=p.useCallback(async()=>{if(l.current)return!0;const d=o.current;if(d===null)return!1;try{const h=await K.billingUsageSummary();if(h.kind!=="cycle")return!1;const f=Number(h.grant.balance_zar||0)+Number(h.topup.balance_zar||0);if(f>d+10){l.current=!0;const m=a.kind==="waiting"||a.kind==="opening"?a.packZar:0;return i({kind:"success",packZar:m,newTotalZar:f}),window.dispatchEvent(new CustomEvent("gadjet:chat-saved")),n==null||n({packZar:m,newTotalZar:f}),!0}}catch{}return!1},[a,n]);p.useEffect(()=>{if(a.kind!=="waiting"&&a.kind!=="opening")return;let d=!1;const h=()=>{d||c()};window.addEventListener("focus",h);const f=setInterval(()=>{d||c()},5e3),m=setTimeout(()=>{d=!0,clearInterval(f)},180*1e3);return()=>{d=!0,window.removeEventListener("focus",h),clearInterval(f),clearTimeout(m)}},[a,c]);async function u(d){if(!(a.kind==="opening"||a.kind==="waiting")){i({kind:"opening",packZar:d});try{const h=t||(typeof window<"u"?window.location.pathname+window.location.search:"/settings/workspace/billing"),{authorization_url:f}=await K.billingTopup(d,h);window.open(f,"_blank","noopener,noreferrer"),i({kind:"waiting",packZar:d,openedAt:Date.now()})}catch(h){i({kind:"error",message:(h==null?void 0:h.message)||"Couldn't start Paystack checkout"})}}}return wr()?null:a.kind==="success"?s.jsxs("div",{className:B("rounded-lg border border-outline-success bg-surface-successSubtle px-4 py-3 text-sm text-text-success",r),children:[s.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[s.jsx(Xt,{className:"w-4 h-4"}),"Topped up",a.packZar?` R${a.packZar}`:"","."]}),e==="chat"&&s.jsx("div",{className:"mt-1 text-xs text-text-success",children:"Send your message again to keep going."})]}):s.jsxs("div",{className:B("space-y-3",r),children:[s.jsx("div",{className:"grid grid-cols-3 gap-2",children:sUe.map(d=>{const h=(a.kind==="opening"||a.kind==="waiting")&&a.packZar===d.zar,f=(a.kind==="opening"||a.kind==="waiting")&&a.packZar!==d.zar;return s.jsxs("button",{type:"button",onClick:()=>u(d.zar),disabled:f||h,className:B("flex flex-col items-center justify-center rounded-lg border px-3 py-3 text-center transition-colors","border-outline-subtle bg-surface hover:border-intent-neutral hover:bg-surface-inverse hover:text-text-inverse","disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-surface disabled:hover:text-text-primary disabled:hover:border-outline-subtle"),children:[s.jsx("div",{className:"text-base font-semibold tabular-nums",children:h?s.jsx(_e,{className:"w-4 h-4 animate-spin"}):d.label}),s.jsx("div",{className:"text-body-xs text-text-secondary mt-0.5",children:d.hint})]},d.zar)})}),a.kind==="waiting"&&s.jsxs("div",{className:"text-xs text-text-secondary flex items-center gap-1.5",children:[s.jsx(Qt,{className:"w-3 h-3"}),"Complete payment in the Paystack tab. Credits land here within a few seconds â"," ",s.jsx("button",{type:"button",onClick:()=>c(),className:"underline underline-offset-2 hover:text-text-primary",children:"check now"}),"."]}),a.kind==="error"&&s.jsx("div",{className:"text-xs text-text-error bg-surface-errorSubtle border border-outline-error roun
892ded px-3 py-2",children:a.message}),s.jsx("div",{className:"text-body-xs text-text-tertiary",children:"Top-ups roll over and don't reset with your monthly renewal."})]})}const j$=5,aUe=10*1024*1024,iUe=10*1024*1024,N$=2e5;function oUe(e){return(e.type||"").startsWith("image/")?aUe:iUe}const lUe="image/png,image/jpeg,image/jpg,image/webp,image/gif,application/pdf,text/plain,text/csv,text/markdown,application/json,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,.md,.csv,.log,.txt,.json,.pdf,.png,.jpg,.jpeg,.webp,.gif,.xlsx,.xls";function of({initialMessages:e,initialInput:t="",autoSendInitial:n=!1,initialFiles:r,extraRequestBody:a,onConversationChange:i,onToolResult:o,onToolInputComplete:l,endpoint:c="/api/chat",welcome:u,topBanner:d,placeholder:h="Ask anything, or type / for skills",emptyClassName:f="",chatId:m=null,onCreateDraft:x}){const[g,y]=p.useState(t),[b,v]=p.useState(0),[w,_]=p.useState([]),k=p.useRef(null),j=p.useRef(null),N=p.useRef(!1),[E,A]=p.useState(m??null),C=cx(),T=Ice(E),S=I9e(),O=p.useRef({extraRequestBody:a,onConversationChange:i,onToolResult:o,onToolInputComplete:l});p.useEffect(()=>{O.current={extraRequestBody:a,onConversationChange:i,onToolResult:o,onToolInputComplete:l}});const R=p.useCallback(Fe=>{C.ensure(Fe,{endpoint:c,extraRequestBody:()=>{const tt=O.current.extraRequestBody;return typeof tt=="function"?tt():tt??{}},persist:async tt=>{var fe,U;await((U=(fe=O.current).onConversationChange)==null?void 0:U.call(fe,tt))},onToolResult:tt=>{var fe,U;return(U=(fe=O.current).onToolResult)==null?void 0:U.call(fe,tt)},onToolInputComplete:tt=>{var fe,U;return(U=(fe=O.current).onToolInputComplete)==null?void 0:U.call(fe,tt)}},e)},[c,C]);p.useEffect(()=>{E&&R(E)},[E,R]);const I=T&&T.messages.length>0?T.messages:e,$=(T==null?void 0:T.status)??{kind:"idle"},P=Lt(),F=p.useMemo(()=>{const Fe={};for(const tt of w)tt.title&&(Fe[tt.name]=tt.title);return Fe},[w]),Z=P.kind==="ready"&&P.me.role==="seller_user",D=P.kind==="ready"?!!P.me.is_demo_mode:!1,H=P.kind==="ready"?!!P.me.is_demo_showcase:!1,Y=D&&!H,[M,z]=p.useState(()=>{try{const Fe=window.localStorage.getItem("gadjet:model_choice");if(Fe)return Fe}catch{}return"auto"});p.useEffect(()=>{try{window.localStorage.setItem("gadjet:model_choice",M)}catch{}},[M]);const G=D&&H?"Gadjet Max":"Gadjet Pro",[te,re]=p.useState([]),[L,q]=p.useState(null);async function me(Fe){q(null);const tt=Array.from(Fe);if(te.length+tt.length>j$){q(`Max ${j$} attachments per message.`);return}const fe=[];for(const U of tt){const ce=oUe(U);if(U.size>ce){const Ee=Math.round(ce/1024/1024);q(`"${U.name}" is over ${Ee} MB â try shrinking it first.`);continue}const ue=await S$(U);if(!ue){q(`"${U.name}" â unsupported file type. Images, PDFs, spreadsheets (.xlsx/.xls), and text-ish files (.csv/.txt/.md/.json) only.`);continue}if(ue.kind==="text"&&ue.text.length>N$){q(`"${U.name}" is too long (${ue.text.length.toLocaleString()} chars > ${N$.toLocaleString()}). Excerpt the part you want me to look at.`);continue}fe.push(ue)}if(fe.length>0&&(re(U=>[...U,...fe]),E))for(const U of fe)C$(E,U).then(ce=>{re(ue=>ue.map(Ee=>Ee.id===U.id?{...Ee,uploadState:"uploaded",meta:ce}:Ee))}).catch(ce=>{re(ue=>ue.map(Ee=>Ee.id===U.id?{...Ee,uploadState:"error",uploadError:(ce==null?void 0:ce.message)||"upload failed"}:Ee)),q(`"${U.name}" â upload failed: ${(ce==null?void 0:ce.message)||"unknown"}`)})}function ee(Fe){re(tt=>tt.filter(fe=>fe.id!==Fe)),q(null)}p.useEffect(()=>{let Fe=!1;return K.listSkills().then(tt=>{Fe||_(tt)}).catch(tt=>{console.warn("[ChatView] listSkills failed:",tt)}),()=>{Fe=!0}},[]);const ne=p.useRef([]);p.useEffect(()=>{ne.current=te},[te]);const{showJump:X,onScroll:he,jumpToLatest:ae}=T9e(k,[I,$]);p.useEffect(()=>{if($.kind!=="streaming"){v(0);return}const Fe=$.startedAt,tt=setInterval(()=>{v(Math.floor((Date.now()-Fe)/1e3))},250);return()=>clearInterval(tt)},[$]),p.useEffect(()=>{const Fe=j.current;Fe&&(Fe.style.height="auto",Fe.style.height=Math.min(Fe.scrollHeight,200)+"px")},[g]),p.useEffect(()=>{N.current||n&&t.trim().length>0&&(N.current=!0,r&&r.length>0?(async()=>{const tt=(await Promise.all(r.map(S$))).filter(fe=>fe!==null);J(t,tt.length>0?tt:void 0)})():J(t))},[]);async function je(Fe,tt){E&&await C.postDecision(E,Fe,tt)}async function $e(Fe,tt){return E?C.submitToolInput(E,Fe,tt):{ok:!1,message:"no_chat_id"}}async function J(Fe,tt,fe){const U=(Fe??g).trim();if($.kind==="streaming")return;let ce=tt??te;if(!U&&ce.length===0)return;let ue=E;if(!ue&&x&&!fe)try{const Ze=await x();ue=Ze.chatId,A(Ze.chatId),R(ue);for(const vt of ce)vt.uploadState==="uploading"&&C$(ue,vt).then(Ot=>{re(It=>It.map(Ut=>Ut.id===vt.id?{...Ut,uploadState:"uploaded",meta:Ot}:Ut))}).catch(Ot=>{re(It=>It.map(Ut=>Ut.id===vt.id?{...Ut,uploadState:"error",uploadError:(Ot==null?void 0:Ot.message)||"upload failed"}:Ut))})}catch(Ze){q(`Couldn't start a new chat: ${(Ze==null?void 0:Ze.message)||String(Ze)}`);return}if(ue&&ce.some(Ze=>Ze.uploadState==="uploading")){const Ze=Date.now();for(;Date.now()-Ze<3e4;){const Ot=ne.current.filter(It=>ce.some(Ut=>Ut.id===It.id));if(Ot.every(It=>It.uploadState!=="uploading")){ce=Ot;break}await new Promise(It=>setTimeout(It,100))}}const Ee=ce.find(Ze=>Ze.uploadState==="error");
892if(Ee){q(`"${Ee.name}" â upload failed: ${Ee.uploadError||"unknown error"}. Remove the attachment and try again.`);return}if(!ue){q("This chat hasn't been set up. Refresh the page and try again.");return}R(ue);const bt=ce.map(Ze=>Ze.meta).filter(Ze=>!!Ze);fe||(y(""),re([]),q(null)),C.send(ue,U,bt,{modelChoice:Y?"auto":M,skipPushUser:fe})}function Ne(){E&&C.stop(E)}function ve(){E&&C.retry(E)}function Me(Fe){E&&C.regenerate(E,Fe)}function Xe(Fe){if(Fe.key==="Enter"&&!(Fe.nativeEvent.isComposing||Fe.nativeEvent.keyCode===229)&&!Fe.shiftKey){if(Fe.altKey||Fe.ctrlKey||Fe.metaKey||S){Fe.preventDefault();const tt=j.current,fe=(tt==null?void 0:tt.selectionStart)??g.length,U=(tt==null?void 0:tt.selectionEnd)??g.length,ce=g.slice(0,fe)+` 893`+g.slice(U);y(ce),requestAnimationFrame(()=>{tt&&(tt.selectionStart=tt.selectionEnd=fe+1)});return}Fe.preventDefault(),J()}}const ze=I.length===0;return s.jsxs("div",{className:"flex-1 flex flex-col min-h-0",children:[s.jsxs("div",{className:"relative flex-1 flex flex-col min-h-0",children:[s.jsx("div",{ref:k,onScroll:he,className:B("flex-1 overflow-y-auto bg-surface",ze&&"flex flex-col"),children:s.jsxs("div",{className:B("max-w-3xl mx-auto px-6 py-8 w-full",ze&&"flex-1 flex flex-col justify-center",f),children:[d&&s.jsx("div",{className:"mb-6",children:d}),ze&&(u==null?void 0:u({pickExample:Fe=>{J(Fe)}})),s.jsx("div",{className:"space-y-6",children:I.map((Fe,tt)=>s.jsx(dUe,{msg:Fe,msgIndex:tt,streaming:$.kind==="streaming"&&tt===I.length-1,onConfirm:je,onSubmitForm:$e,chatId:E,skillTitles:F,foldQuietTools:Z,onRetryTurn:Me},uUe(Fe,tt)))}),$.kind==="streaming"&&s.jsxs("div",{className:"mt-4 inline-flex items-center gap-2 text-xs text-text-secondary bg-surface-sunken px-3 py-1.5 rounded-full",children:[s.jsx(_e,{className:"w-3 h-3 animate-spin"}),U9e(I,F)," · ",SUe(b)]}),s.jsx(k9e,{status:$,messages:I,onRetry:ve}),s.jsx(j9e,{status:$}),$.kind==="insufficient_credits"&&s.jsx(mUe,{status:$,chatId:E,onRetry:ve})]})}),X&&s.jsx(N9e,{onClick:ae})]}),s.jsx(NUe,{input:g,setInput:y,onSend:J,onStop:Ne,onKeyDown:Xe,textareaRef:j,streaming:$.kind==="streaming",placeholder:h,skills:w,modelChoice:M,onModelChange:z,defaultModelLabel:G,showModelPicker:!Y,attachments:te,attachError:L,onAddFiles:me,onRemoveAttachment:ee})]})}function Hp(e){return e.map(t=>{if(t.role==="user"){const i={role:"user",content:t.content};return Array.isArray(t.attachments)&&t.attachments.length>0&&(i.attachments=t.attachments),t.meta&&(i.meta=t.meta),t.ts&&(i.ts=t.ts),i}const n=t.parts.filter(i=>i.kind==="text").map(i=>i.text).join(""),r=t.parts.map(i=>i.kind==="text"?{kind:"text",text:i.text}:{kind:"tool",id:i.id,name:i.name,input:i.input,status:i.status,summary:i.summary}),a={role:"assistant",content:n,parts:r};return t.meta&&(a.meta=t.meta),t.ts&&(a.ts=t.ts),a})}function Aw(e){return e.map(t=>{if(t.role==="user"){const n={role:"user",content:t.content};return Array.isArray(t.attachments)&&t.attachments.length>0&&(n.attachments=t.attachments),t.meta&&(n.meta=t.meta),t.ts&&(n.ts=t.ts),n}if(t.parts&&t.parts.length>0){const r={role:"assistant",parts:t.parts.map(a=>a.kind==="text"?{kind:"text",text:a.text}:{kind:"tool",id:a.id,name:a.name,partial_json:"",input:a.input,status:a.status,summary:a.summary})};return t.meta&&(r.meta=t.meta),t.ts&&(r.ts=t.ts),r}return{role:"assistant",parts:[{kind:"text",text:t.content}],...t.meta?{meta:t.meta}:{},...t.ts?{ts:t.ts}:{}}})}async function S$(e){const t=(e.type||"").toLowerCase(),n=e.name,r=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(t==="image/png"||t==="image/jpeg"||t==="image/jpg"||t==="image/webp"||t==="image/gif"){const l=t==="image/jpg"?"image/jpeg":t,c=await zk(e);return{id:r,kind:"image",name:n,size:e.size,mediaType:l,data:c,uploadState:"uploading"}}if(t==="application/pdf"||/\.pdf$/i.test(n)){const l=await zk(e);return{id:r,kind:"pdf",name:n,size:e.size,mediaType:"application/pdf",data:l,uploadState:"uploading"}}const a=t==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"||/\.xlsx$/i.test(n),i=t==="application/vnd.ms-excel"||/\.xls$/i.test(n);if(a||i){const l=await zk(e);return{id:r,kind:"spreadsheet",name:n,size:e.size,mediaType:a?"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"application/vnd.ms-excel",data:l,uploadState:"uploading"}}if(t.startsWith("text/")||t==="application/json"||/\.(md|csv|log|txt|json)$/i.test(n)){const l=await e.text();return{id:r,kind:"text",name:n,size:e.size,mediaType:t||"text/plain",text:l,uploadState:"uploading"}}return null}async function C$(e,t){let n,r;if(t.kind==="image"||t.kind==="pdf"||t.kind==="spreadsheet")n=t.data,r=t.mediaType;else{const i=new TextEncoder().encode(t.text);let o="";for(let l=0;l<i.length;l++)o+=String.fromCharCode(i[l]);n=btoa(o),r=t.mediaType.startsWith("text/csv")?"text/csv":"text/plain"}const a=await oe(`/api/chats/${e}/attachments`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:t.name,mime_type:r,base64_data:n})});if(!a.ok){let i=`upload failed (${a.status})`;try{const o=await a.json();i=(o==null?void 0:o.message)||i}catch{}throw new Error(i)}return await a.json()}function zk(e){return new Promise((t,n)=>{const r=new FileReader;r.onerror=()=>n(r.error),r.onload=()=>{const a=r.result;if(typeof a!="string"){n(new Error("FileReader returned non-string"));return}const i=a.indexOf(",");t(i>=0?a.slice(i+1):a)}
893,r.readAsDataURL(e)})}function cUe({attachment:e,chatId:t}){const[n,r]=p.useState(null),[a,i]=p.useState(null);p.useEffect(()=>{let u=!1;if(!t){i("(attachment unavailable â chat id missing)");return}return oe(`/api/chats/${t}/attachments/sign`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({storage_path:e.storage_path})}).then(async d=>{if(!d.ok){const h=await d.json().catch(()=>({}));throw new Error((h==null?void 0:h.message)||`sign failed (${d.status})`)}return d.json()}).then(d=>{u||r(d.signed_url)}).catch(d=>{u||i((d==null?void 0:d.message)||"failed to load")}),()=>{u=!0}},[t,e.storage_path]);const o=Math.max(1,Math.round(e.size_bytes/1024)),l=e.mime_type.startsWith("image/");if(a)return s.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-secondary bg-surface-sunken px-3 py-1.5 rounded-lg border border-outline-subtle",children:[s.jsx(yt,{className:"w-3.5 h-3.5 shrink-0"}),s.jsx("span",{className:"truncate",children:e.filename}),s.jsxs("span",{className:"text-text-tertiary",children:["â ",a]})]});if(!n)return s.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-tertiary bg-surface-subtle px-3 py-1.5 rounded-lg border border-outline-subtle",children:[s.jsx(_e,{className:"w-3.5 h-3.5 animate-spin shrink-0"}),s.jsx("span",{className:"truncate",children:e.filename})]});if(l)return s.jsx("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"block max-w-xs rounded-2xl overflow-hidden border border-outline-subtle hover:border-brand-400 transition-colors",title:`${e.filename} (${o} KB) â click to open full size`,children:s.jsx("img",{src:n,alt:e.filename,className:"block max-w-full max-h-72 object-contain bg-surface-subtle"})});const c=e.mime_type==="application/pdf"?s.jsx(il,{className:"w-4 h-4 text-error-500"}):s.jsx(il,{className:"w-4 h-4 text-text-secondary"});return s.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-sm bg-surface-subtle hover:bg-surface-sunken border border-outline-subtle px-3 py-2 rounded-lg max-w-xs",children:[c,s.jsx("span",{className:"truncate font-medium text-text-body",children:e.filename}),s.jsxs("span",{className:"text-xs text-text-secondary shrink-0",children:[o," KB"]})]})}function uUe(e,t){return e.role==="user"?`user-${t}`:`assistant-${t}`}function E$(e,t,n){return e.kind==="tool"?`tool-${e.id}`:`text-${t}-${n}`}function dUe({msg:e,msgIndex:t,streaming:n,onConfirm:r,onSubmitForm:a,chatId:i,skillTitles:o,foldQuietTools:l,onRetryTurn:c}){var f,m,x,g;if(e.role==="user"){const y=!!((f=e.meta)!=null&&f.sent_by_admin),b=Array.isArray(e.attachments)?e.attachments:[],v=b.length>0?e.content.replace(/\n*ð attached: .*$/m,"").trim():e.content;return s.jsx("div",{className:"flex gap-3 justify-end",children:s.jsxs("div",{className:"max-w-[85%] flex flex-col items-end gap-1.5",children:[y&&s.jsx("span",{className:"text-body-xs font-medium uppercase tracking-wider text-text-warning",children:"sent by admin"}),b.length>0&&s.jsx("div",{className:"flex flex-col items-end gap-1.5",children:b.map(w=>s.jsx(cUe,{attachment:w,chatId:i??null},w.id))}),v&&s.jsx("div",{className:"bg-intent-brand text-text-inverse rounded-2xl rounded-tr-sm px-4 py-2.5 text-sm whitespace-pre-wrap",children:wUe(v)})]})})}const u=e.parts.length===0,d=!!((m=e.meta)!=null&&m.from_am),h=(g=(x=e.meta)==null?void 0:x.am_name)==null?void 0:g.trim();return s.jsx("div",{className:"flex gap-3",children:s.jsxs("div",{className:"flex-1 min-w-0 space-y-2",children:[d&&s.jsxs("div",{className:"text-body-xs font-medium uppercase tracking-wider text-text-success",children:["Reply from ",h||"your account manager"]}),u&&n&&s.jsx("div",{className:"sr-only",children:"Assistant is responding"}),(l?B9e(e.parts):e.parts.map((y,b)=>({kind:"part",part:y,index:b}))).map((y,b)=>{if(y.kind==="folded")return s.jsxs("div",{className:"text-body-sm text-text-tertiary px-1",children:["Checked ",y.count," ",y.count===1?"source":"sources"]},`folded:${t}:${b}`);const v=y.part,w=y.index;return v.kind==="text"?s.jsx("div",{className:"prose text-body-lg",children:s.jsx(mx,{remarkPlugins:[px,d3,p3],rehypePlugins:[m3],components:YV,children:v.text})},E$(v,t,w)):s.jsx(hUe,{part:v,onConfirm:r,onSubmitForm:a,chatId:i??null,skillTitles:o},E$(v,t,w))}),!n&&s.jsx(E9e,{text:S9e(e.parts),ts:e.ts,showRetry:!d,onRetry:()=>c(t)})]})})}function hUe({part:e,onConfirm:t,onSubmitForm:n,chatId:r,skillTitles:a}){const[i,o]=p.useState(!1),l=Lt(),c=l.kind==="ready"?l.me.role:null,u=c==="super_admin"||c==="am";if(e.name==="run_skill")return s.jsx(yUe,{part:e,skillTitles:a});if(e.name==="request_user_input"&&r&&n)return s.jsx(xUe,{part:e,chatId:r,onSubmitForm:n});if(e.awaitingConfirm)return s.jsx(gUe,{part:e,onConfirm:t});const d=e.status==="running"?_e:e.status==="error"?yt:Xt,h=e.status==="running"?"text-text-tertiary animate-spin":e.status==="error"?"text-intent-error":"text-intent-success",f=pUe(e);return u?s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface-subtle/60 text-sm",children:[s.jsxs("button",{onClick:()=>o(m=>!m),className:"w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-surface-sunken/60 rounded-lg",children:[i?s.jsx(Pn,{className:"w-3.5 h-3.5 text-text-tertiary shrink-0"}):s.jsx(fr,{className:"w-3.5 h-3.5 text-text-tertiary shrink-0"}),s.jsx(xF,{className:"w-3.5 h-3.5 text-text-tertiary shrink-0"}),s.jsx("span",{className:"font-mono text-body-md text-text-body",children:e.name}),e.input&&s.jsxs("span",{className:"font-mono text-body-sm text-text-secondary truncate",children:["(",wq(e.input),")"]}),s.jsxs("span",{className:"ml-auto flex items-center gap-1 text-xs text-text-secondary",children:[e.summary&&_q(e.summary),s.jsx(d,{className:B("w-3.5 h-3.5",h)})]})]}),f,i&&s.jsxs("div",{className:"border-t border-outline-subtle px-3 py-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-body-xs uppercase tracking-wider text-text-tertiary mb-1",children:"Input"}),s.jsx("pre",{className:"text-body-sm font-mono bg-surface border border-outline-faint rounded p-2 overflow-x-auto",children:e.input?JSON.stringify(e.input,null,2):e.partial_json||"â"})]}),e.summary&&s.jsxs("div",{children:[s.jsx("div",{className:"text-body-xs uppercase tracking-wider text-text-tertiary mb-1",children:"Result summary"}),s.jsx("pre",{className:"text-body-sm font-mono bg-surface border border-outline-faint rounded p-2 overflow-x-auto",children:JSON.stringify(e.summary,null,2)})]})]})]}):s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface-subtle/60 text-sm overflow-hidden",children:[s.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[s.jsx(d,{className:B("w-3.5 h-3.5 shrink-0",h)}),s.jsx("span",{className:"text-body-md text-text-body",children:xq(e)})]}),f]})}function fUe(e,t){const n=t||{};switch(e){case"onboard_seller":return{title:`Onboard new seller: ${n.display_name||n.slug||"(unnamed)"}`,details:[n.slug?`Slug: ${n.slug}`:null,n.account_owner?`Account manager: ${n.account_owner}`:null,n.primary_region?`Region: ${n.primary_region}`:null,n.api_key?"API key: (provided, will be added to .env)":null,n.legal_name?`Legal name: ${n.legal_name}`:null,n.notes?`Notes: ${n.notes}
893`:null].filter(Boolean)};case"update_seller_field":return{title:`Update ${n.slug||"seller"}.${n.field||"field"}`,details:[`New value: ${typeof n.value=="string"?`"${n.value}"`:JSON.stringify(n.value)}`]};case"sync_seller":return{title:`Run a full data sync for ${n.slug||"seller"}`,details:[n.first_run?"Mode: first-run (90-day pull, 60s throttle, takes ~3-5 min)":"Mode: incremental (uses last sync watermark)",n.since?`Since: ${n.since}`:null,"This makes live Takealot API calls."].filter(Boolean)};case"sync_one":return{title:`Refresh ${n.slug||"seller"}'s ${n.kind||"data"}`,details:[n.since?`Since: ${n.since}`:null,"This makes a live Takealot API call."].filter(Boolean)};default:return{title:`Run ${e}`,details:[JSON.stringify(t).slice(0,200)]}}}function mUe({status:e,chatId:t,onRetry:n}){const r=cx(),[a,i]=p.useState(!1),[o,l]=p.useState(null),c=e.code,u=c==="past_due"?"Payment failed":c==="subscription_required"?"Subscription needed":"You're out of credits";async function d(){i(!0),l(null);try{const{link:f}=await K.billingManageSubscription();window.open(f,"_blank","noopener,noreferrer"),t&&r.markToppedUp(t)}catch(f){l(String((f==null?void 0:f.message)||f))}finally{i(!1)}}async function h(){i(!0),l(null);try{const f=await K.initiateSubscription(),m=f.manage_url||f.authorization_url;if(!m)throw new Error("Couldn't start checkout.");window.open(m,"_blank","noopener,noreferrer"),t&&r.markToppedUp(t)}catch(f){l(String((f==null?void 0:f.message)||f))}finally{i(!1)}}return s.jsxs("div",{className:"mt-6 rounded-lg border border-outline-subtle bg-surface-subtle p-4 space-y-4",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u}),s.jsx("div",{className:"text-sm text-text-secondary",children:e.reason}),o&&s.jsx("div",{className:"text-xs text-text-error",children:o})]}),c==="past_due"&&!wr()&&s.jsxs("button",{type:"button",onClick:d,disabled:a,className:"inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-md bg-surface-inverse text-text-inverse border border-surface-inverse hover:bg-intent-neutralHover disabled:opacity-60",children:[a?s.jsx(_e,{className:"w-3 h-3 animate-spin"}):s.jsx(tx,{className:"w-3 h-3"}),"Update payment"]}),c==="subscription_required"&&!wr()&&s.jsxs("button",{type:"button",onClick:h,disabled:a,className:"inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-md bg-surface-inverse text-text-inverse border border-surface-inverse hover:bg-intent-neutralHover disabled:opacity-60",children:[a?s.jsx(_e,{className:"w-3 h-3 animate-spin"}):s.jsx(Ht,{className:"w-3 h-3"}),"Start subscription"]}),(c==="credits_exhausted"||!c)&&!wr()&&s.jsx(vq,{context:"chat",onToppedUp:()=>{t&&r.markToppedUp(t)}}),wr()&&(c==="past_due"||c==="subscription_required"||c==="credits_exhausted"||!c)&&s.jsx("p",{className:"text-xs text-text-secondary",children:Hc}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:n,disabled:!e.toppedUp,className:B("text-xs font-medium px-3 py-1.5 rounded-md border transition-colors",e.toppedUp?"bg-surface-inverse text-text-inverse border-surface-inverse hover:bg-intent-neutralHover":"bg-surface text-text-tertiary border-outline-subtle cursor-not-allowed"),children:"Retry your message"}),s.jsx("button",{type:"button",onClick:()=>{t&&r.dismissStatus(t)},className:"text-xs text-text-secondary hover:text-text-primary",children:"Dismiss"})]})]})}function pUe(e){if(e.status!=="done"&&e.status!=="error")return null;const t=e.summary;if(!t)return null;if(t.error)return s.jsxs("div",{className:"border-t border-outline-subtle bg-surface-errorSubtle/60 px-3 py-2 text-body-md text-text-error flex items-start gap-2",children:[s.jsx(yt,{className:"w-4 h-4 shrink-0 mt-0.5 text-intent-error"}),s.jsx("span",{className:"flex-1",children:t.message||t.error})]});if(t.manage_url)return wr()?s.jsx("div",{className:"border-t border-outline-subtle bg-surface-warningSubtle/60 px-3 py-2 text-body-md text-text-secondary",children:Hc}):s.jsxs("div",{className:"border-t border-outline-subtle bg-surface-warningSubtle/60 px-3 py-2 flex items-center gap-3",children:[s.jsx(yt,{className:"w-4 h-4 shrink-0 text-text-warning"}),s.jsx("span",{className:"flex-1 text-body-md text-text-primary",children:"Last payment failed. Update your card on Paystack to resume â don't start a new subscription."}),s.jsx(W,{intent:"warning",size:"sm",asChild:!0,children:s.jsx("a",{href:t.manage_url,target:"_blank",rel:"noopener noreferrer",children:"Update payment â"})})]});if(t.authorization_url)return wr()?s.jsx("div",{className:"border-t border-outline-subtle bg-surface-successSubtle/60 px-3 py-2 text-body-md text-text-secondary",children:Hc}):s.jsxs("div",{className:"border-t border-outline-subtle bg-surface-successSubtle/60 px-3 py-2 flex items-center gap-3",children:[s.jsx(Ht,{className:"w-4 h-4 shrink-0 text-text-success"}),s.jsx("span",{className:"flex-1 text-body-md text-text-primary",children:e.name==="initiate_subscription"?`Ready to start your R${zc(fi.starter.priceZar)}/mo plan. Continue to Paystack to authorise payment.`:"Continue to Paystack to complete payment."}),s.jsx("a",{href:t.authorization_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center rounded-md bg-intent-success px-3 py-1.5 text-xs font-medium text-text-inverse hover:bg-intent-successHover",children:"Continue to Paystack â"})]});if(t.invite_link)return s.jsxs("div",{className:"border-t border-outline-subtle bg-surface-infoSubtle/60 px-3 py-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2 text-body-md text-text-primary",children:[s.jsx(Ht,{className:"w-4 h-4 shrink-0 text-text-info"}),s.jsxs("span",{children:["Invite link generated",t.display_name?` for ${t.dis
893play_name}`:"",". Forward this to the customer:"]})]}),s.jsx("code",{className:"block text-body-sm font-mono bg-surface border border-outline-info rounded px-2 py-1.5 break-all",children:t.invite_link})]});if(t.already_active)return s.jsx("div",{className:"border-t border-outline-subtle bg-surface-subtle px-3 py-2 text-body-md text-text-secondary",children:"Subscription already active â no checkout needed."});if(e.name==="validate_and_attach_takealot_key"&&t.display_name){const n=t.slug;return s.jsxs("div",{className:"border-t border-outline-subtle bg-surface-successSubtle/60 px-3 py-2 text-body-md text-text-success flex items-center gap-2",children:[s.jsx(Xt,{className:"w-4 h-4 shrink-0 text-text-success"}),s.jsx("span",{className:"flex-1",children:t.message||`Connected to ${t.display_name}.`}),n&&s.jsx("a",{href:`/sellers/${n}`,className:"shrink-0 inline-flex items-center rounded-md bg-intent-success px-2.5 py-1 text-xs font-medium text-text-inverse hover:bg-intent-successHover",children:"View overview â"})]})}return null}function xUe({part:e,chatId:t,onSubmitForm:n}){var o;const r=(o=e.input)==null?void 0:o.form,[a,i]=p.useState(null);return r?s.jsx(T3,{formSpec:r,submittedValues:a,onSubmit:async l=>{const c=await n(e.id,l);return(c==null?void 0:c.ok)!==!1&&i(l),c??{ok:!0}}}):s.jsx("div",{className:"not-prose my-2 rounded-md border border-outline-subtle bg-surface-subtle px-3 py-2 text-body-sm text-text-secondary",children:"Waiting for form detailsâ¦"})}function gUe({part:e,onConfirm:t}){const{title:n,details:r}=fUe(e.name,e.confirmInput||e.input||{}),a=e.confirmDecision!=null;return s.jsx("div",{className:"rounded-lg border-2 border-outline-warning bg-surface-warningSubtle/70 text-sm",children:s.jsxs("div",{className:"flex items-start gap-3 px-4 py-3",children:[s.jsx(yt,{className:"w-5 h-5 text-text-warning shrink-0 mt-0.5"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-body-md font-medium text-text-primary",children:n}),r.length>0&&s.jsx("ul",{className:"mt-1.5 space-y-0.5",children:r.map((i,o)=>s.jsx("li",{className:"text-body-md text-text-body",children:i},o))}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{onClick:()=>t(e.id,"confirm"),disabled:a,className:B("px-3 py-1.5 rounded-md text-body-md font-medium transition",a?"bg-surface-sunken text-text-tertiary cursor-not-allowed":"bg-intent-success text-text-inverse hover:bg-intent-successHover"),children:e.confirmDecision==="confirm"?"Confirmedâ¦":"Confirm"}),s.jsx("button",{onClick:()=>t(e.id,"cancel"),disabled:a,className:B("px-3 py-1.5 rounded-md text-body-md font-medium transition border",a?"bg-surface-subtle text-text-tertiary border-outline-subtle cursor-not-allowed":"bg-surface text-text-body border-outline hover:bg-surface-subtle"),children:e.confirmDecision==="cancel"?"Cancelled":"Cancel"}),s.jsx("span",{className:"ml-2 text-body-xs text-text-secondary",children:"This will only run after you click Confirm."})]})]})]})})}function yUe({part:e,skillTitles:t}){var h,f;const[n,r]=p.useState(!1),a=pq(e.progress,t),i=(h=e.input)==null?void 0:h.skill_name,o=I3(i,t),l=Lt(),c=l.kind==="ready"?l.me.role:null,u=c==="super_admin"||c==="am",d=e.status==="running"?{Comp:Ht,cls:"text-brand-500 animate-pulse"}:e.status==="error"?{Comp:yt,cls:"text-intent-error"}:{Comp:Xt,cls:"text-intent-success"};return s.jsxs("div",{className:"rounded-lg border border-outline-brand bg-surface-brandSubtle/40 text-sm",children:[s.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[s.jsx(d.Comp,{className:B("w-4 h-4 shrink-0",d.cls)}),s.jsx("span",{className:"text-body-md text-text-primary font-medium",children:o}),((f=e.input)==null?void 0:f.slug)&&s.jsxs("span",{className:"text-body-sm text-text-secondary",children:["· ",e.input.slug]})]}),a.length>0&&s.jsx("ul",{className:"px-3 pb-2 space-y-1",children:a.map(m=>s.jsxs("li",{className:"flex items-start gap-2 text-body-md",children:[s.jsx(bUe,{status:m.status}),s.jsxs("span",{className:B("leading-5",m.status==="failed"?"text-text-error":"text-text-body",m.status==="running"&&"text-text-body"),children:[m.label,m.status==="running"&&s.jsx("span",{className:"text-text-tertiary",children:"â¦"}),m.detail&&s.jsxs("span",{className:"ml-2 text-body-sm text-text-secondary",children:["â ",m.detail]})]})]},m.key))}),u&&s.jsxs("div",{className:"border-t border-outline-brand px-3 py-1.5",children:[s.jsxs("button",{onClick:()=>r(m=>!m),className:"flex items-center gap-1.5 text-body-xs text-text-tertiary hover:text-text-secondary",children:[n?s.jsx(Pn,{className:"w-3 h-3"}):s.jsx(fr,{className:"w-3 h-3"}),"Advanced"]}),n&&s.jsxs("div",{className:"mt-2 space-y-2 pb-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-body-xs uppercase tracking-wider text-text-tertiary mb-1",children:"Tool input"}),s.jsx("pre",{className:"text-body-sm font-mono bg-surface border border-outline-faint rounded p-2 overflow-x-auto",children:e.input?JSON.stringify(e.input,null,2):e.partial_json||"â"})]}),e.progress&&e.progress.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-body-xs uppercase tracking-wider text-text-tertiary mb-1",children:"Event log"}),s.jsx("ul",{className:"text-body-xs font-mono bg-surface border border-outline-faint rounded p-2 space-y-0.5 max-h-64 overflow-y-auto",children:e.progress.map((m,x)=>s.jsxs("li",{className:"flex gap-2 items-start",children:[s.jsx("span",{className:"text-text-tertiary shrink-0 w-3",children:m.kind==="tool_start"?"â¶":m.kind==="tool_result"?m.is_error?"â":"â":m.kind==="round_start"?"·":m.kind==="round_end"?"â":m.kind==="skill_start"?"â·":m.kind==="skill_done"?m.ok?"â":"â":" "}),s.jsx("span",{className:B("text-text-body break-all",m.is_error&&"text-text-error",m.kind==="skill_done"&&!m.ok&&"text-text-error"),children:vUe(m)})]},x))})]}),e.summary&&s.jsxs("div",{children:[s.jsx("div",{className:"text-body-xs uppercase tracking-wider text-text-tertiary mb-1",children:"Result summary"}),s.jsx("pre",{className:"text-body-sm font-mono bg-surface border border-outline-faint rounded p-2 overflow-x-auto",children:JSON.stringify(e.summary,null,2)})]})]})]})]})}function bUe({status:e}){return e==="running"?s.jsx(_e,{className:"w-3.5 h-3.5 mt-0.5 text-brand-400 animate-spin shrink-0"}):e==="failed"?s.jsx(yt,{className:"w-3.5 h-3.5 mt-0.5 text-intent-error shrink-0"}):s.jsx(Xt,{className:"w-3.5 h-3.5 mt-0.5 text-intent-success shrink-0"})}function vUe(e){var t,n,r;switch(e.kind){case"skill_start":return`Starting ${e.skill_name??"skill"}â¦`;case"round_start":return`Round ${(e.round??0)+1}â¦`;case"round_end":return`Round ${(e.round??0)+1} done (${e.stop_reason}, ${e.input_tokens}â ${e.output_tokens}â, ${e.latency_ms}ms)`;case"tool_start":return`Calling ${e.name}${e.input?` ${wq(e.input)}`:""}`;case"tool_result":return e.is_error?`${e.name} failed: ${((t=e.summary)==null?void 0:t.error)??"error"}`:`${e.name} ok ${_q(e.summary)||""}${e.latency_ms?` (${e.latency_ms}ms)`:""}`;case"skill_done":return e.ok?`Skill complete (${((n=e.usage)==null?void 0:n.input_tokens)??"?"}â ${((r=e.usage)==null?void 0:r.output_tokens)??"?"}â)`:`Skill failed: ${e.error??"unknown"}`;default:return e.kind}}const Qg=/\b[a-fA-F0-9]{60,}\b/g;function wUe(e){if(!e||!Qg.test(e))return Qg.lastIndex=0,e;Qg.lastIndex=0;const t=[];let n=0,r;const a=new RegExp(Qg.source,"g");for(;(r=a.exec(e))!==null;)r.index>n&&t.push(e.slice(n,r.index)),t.push(s.jsx("span",{className:"inline-flex items-center gap-1 rounded bg-surface/20 px-1.5 py-0.5 text-body-xs font-medium tracking-wide",title:"Sensitive value redacted from view. The server has the real value to attach your store.",children:"ð secret hidden"},r.index)),n=r.index+r[0].length;return n<e.length&&t.push(e.slice(n)),t}function wq(e){return!e||typeof e!="object"?"":Object.entries(e).slice(0,3).map(([t,n])=>{const r=typeof n=="string"?`"${n}"`:JSON.stringify(n);return`${t}=${r}`}).join(", ")}function _q(e){return e?typeof e.rows=="number"?`${e.rows} rows`:typeof e.bytes=="number"?`${(e.bytes/1024).toFixed(1)}kb`:"":""}const A$=8;function T$(e,t){let n=t-1;for(;n>=0;){const r=e[n];if(r==="/")return n===0||/\s/.test(e[n-1])?{start:n,end:t,query:e.slice(n+1,t)}:null;if(/\s/.test(r))return null;n--}return null}
893function _Ue(e){if(e.origin==="user")return`Run my "${e.title||e.name}" skill `;let t=(e.trigger_phrase||e.title||e.name).replace(/<[^>]+>/g,"").trim();return t||(t=e.title||e.name),t.charAt(0).toUpperCase()+t.slice(1)+" "}function kUe(e,t){const n=t.toLowerCase();if(!n)return e.slice(0,A$);const r=[];for(const a of e){const i=a.name.toLowerCase(),o=(a.title||"").toLowerCase(),l=(a.description||"").toLowerCase();let c=-1;i.startsWith(n)?c=0:o.startsWith(n)?c=1:i.includes(n)?c=2:o.includes(n)?c=3:l.includes(n)&&(c=4),c>=0&&r.push({skill:a,score:c})}return r.sort((a,i)=>a.score-i.score||a.skill.name.localeCompare(i.skill.name)),r.slice(0,A$).map(a=>a.skill)}function jUe(e,t){const n=[];for(const r of e){const a=t.has(r.name);if(n.push({kind:"header",group:r.name,description:r.description,total:r.skills.length,expanded:a}),a)for(const i of r.skills)n.push({kind:"skill",skill:i,group:r.name})}return n}function NUe({input:e,setInput:t,onSend:n,onStop:r,onKeyDown:a,textareaRef:i,streaming:o,placeholder:l,skills:c,modelChoice:u,onModelChange:d,defaultModelLabel:h,showModelPicker:f=!0,attachments:m,attachError:x,onAddFiles:g,onRemoveAttachment:y}){const b=p.useRef(null),[v,w]=p.useState(0),[_,k]=p.useState(!1),[j,N]=p.useState(!1),E=p.useRef(null),A=T$(e,v);p.useEffect(()=>{const L=(A==null?void 0:A.start)??null;L!==E.current&&(k(!1),E.current=L)},[A]);const C=A!==null&&!_&&c.length>0,T=C&&A.query==="",S=p.useMemo(()=>T?W9e(c):[],[T,c]),[O,R]=p.useState(new Set),I=p.useRef(!1);p.useEffect(()=>{T&&!I.current&&S.length>0&&(R(new Set([S[0].name])),I.current=!0)},[T,S]);const $=p.useMemo(()=>T?jUe(S,O):[],[T,S,O]),P=C&&!T?kUe(c,A.query):[],F=p.useMemo(()=>c.some(L=>L.origin==="user"),[c]),[Z,D]=p.useState(0);p.useEffect(()=>{D(0)},[A==null?void 0:A.query,P.length,T]),p.useEffect(()=>{T&&$.length>0&&D(L=>L>=$.length?0:L)},[T,$.length]);function H(L){R(q=>{const me=new Set(q);return me.has(L)?me.delete(L):me.add(L),me})}function Y(L){if(!A)return;const q=e.slice(0,A.start),me=e.slice(A.end),ee=q+L+me,ne=q.length+L.length;t(ee),requestAnimationFrame(()=>{const X=i.current;X&&(X.focus(),X.setSelectionRange(ne,ne),w(ne))})}function M(L){Y(_Ue(L))}function z(L){const q=L.selectionStart??L.value.length;w(q)}function G(){const L=i.current,q=(L==null?void 0:L.selectionStart)??e.length;if(T$(e,q)){L==null||L.focus();return}const{next:me,cursor:ee}=R9e(e,q);t(me),requestAnimationFrame(()=>{L&&(L.focus(),L.setSelectionRange(ee,ee),w(ee))})}function te(L){const q=D9e(L.clipboardData);q.length!==0&&(L.preventDefault(),g(q))}function re(L){if(C&&T&&$.length>0){if(L.key==="ArrowDown"){L.preventDefault(),D(q=>(q+1)%$.length);return}if(L.key==="ArrowUp"){L.preventDefault(),D(q=>(q-1+$.length)%$.length);return}if(L.key==="Enter"||L.key==="Tab"){L.preventDefault();const q=$[Z];q.kind==="header"?H(q.group):M(q.skill);return}if(L.key==="Escape"){L.preventDefault(),k(!0);return}}if(C&&!T&&P.length>0){if(L.key==="ArrowDown"){L.preventDefault(),D(q=>(q+1)%P.length);return}if(L.key==="ArrowUp"){L.preventDefault(),D(q=>(q-1+P.length)%P.length);return}if(L.key==="Enter"||L.key==="Tab"){L.preventDefault(),M(P[Z]);return}if(L.key==="Escape"){L.preventDefault(),k(!0);return}}a(L)}return s.jsx("div",{className:"border-t border-outline-subtle bg-surface px-4 py-3 md:px-6 md:py-4 shrink-0",children:s.jsxs("div",{className:"max-w-3xl mx-auto relative",children:[C&&T&&$.length>0&&s.jsxs("div",{className:"absolute left-0 right-0 bottom-full mb-2 z-10 bg-surface border border-outline-subtle rounded-xl shadow-lg overflow-hidden max-h-96 overflow-y-auto",children:[s.jsx("div",{className:"px-3 py-1.5 text-body-xs uppercase tracking-wide text-text-tertiary border-b border-outline-faint sticky top-0 bg-surface",children:"Skills · arrow to navigate · enter to select"}),s.jsxs("button",{type:"button",onMouseDown:L=>{L.preventDefault(),Y("Help me create a new skill ")},className:"w-full text-left px-3 py-2 flex items-center gap-2 border-b border-outline-faint bg-surface-brandSubtle/40 hover:bg-surface-brandSubtle",children:[s.jsx(In,{className:"w-3.5 h-3.5 text-text-brand shrink-0"}),s.jsx("span",{className:"text-sm font-medium text-text-brand",children:F?"New skill":"Create your first skill"}),s.jsx("span",{className:"text-body-xs text-text-secondary truncate ml-1",children:"â save a workflow you re-run"})]}),$.map((L,q)=>{const me=q===Z;if(L.kind==="header")return s.jsxs("button",{type:"button",onMouseDown:ne=>{ne.preventDefault(),H(L.group)},onMouseEnter:()=>D(q),className:B("w-full text-left px-3 py-1.5 flex items-center gap-2 border-b border-outline-faint",me?"bg-surface-sunken":"bg-surface-subtle/50 hover:bg-surface-sunken"),children:[L.expanded?s.jsx(Pn,{className:"w-3.5 h-3.5 text-text-secondary shrink-0"}):s.jsx(fr,{className:"w-3.5 h-3.5 text-text-secondary shrink-0"}),s.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-text-body",children:L.group}),s.jsx("span",{className:"text-body-xs text-text-tertiary",children:L.total}),L.description&&s.jsxs("span",{className:"text-body-xs text-text-secondary truncate ml-1",children:["â ",L.description]})]},`h:${L.group}`);const ee=L.skill;if(ee.origin==="user"){const ne=ee.title||ee.name;return s.jsxs("div",{onMouseEnter:()=>D(q),className:B("w-full flex items-stretch border-b border-outline-faint last:border-b-0",me?"bg-surface-sunken":"hover:bg-surface-subtle"),children:[s.jsxs("button",{type:"button",onMouseDown:X=>{X.preventDefault(),M(ee)},className:"flex-1 min-w-0 text-left pl-7 pr-2 py-2 flex flex-col gap-0.5",children:[s.jsx("span",{className:"text-sm font-medium text-text-primary truncate",children:ne}),ee.description&&s.jsx("span",{className:"text-xs text-text-secondary line-clamp-1",children:ee.description})]}),s.jsx("button",{type:"button",title:`Edit "${ne}"`,"aria-label":`Edit "${ne}"`,onMouseDown:X=>{X.preventDefault(),Y(`Edit my "${ne}" skill â `)},className:"px-1.5 flex items-center text-text-tertiary hover:text-text-primary",children:s.jsx(Qi,{className:"w-3.5 h-3.5"})}),s.jsx("button",{type:"button",title:`Delete "${ne}"`,"aria-label":`Delete "${ne}"`,onMouseDown:X=>{X.preventDefault(),Y(`Delete my "${ne}" skill `)},className:"pl-1.5 pr-2 flex items-center text-text-tertiary hover:text-text-error",children:s.jsx(us,{className:"w-3.5 h-3.5"})})]},`s:${ee.name}`)}return s.jsxs("button",{type:"button",onMouseDown:ne=>{ne.preventDefault(),M(ee)},onMouseEnter:()=>D(q),className:B("w-full text-left pl-7 pr-3 py-2 flex flex-col gap-0.5 border-b border-outline-faint last:border-b-0",me?"bg-surface-sunken":"hover:bg-surface-subtle"),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:"text-sm font-medium text-text-primary",children:["/",ee.name]}),ee.title&&ee.title!==ee.name&&s.jsx("span",{className:"text-xs text-text-secondary",children:ee.title})]}),ee.description&&s.jsx("span",{className:"text-xs text-text-secondary line-clamp-1",children:ee.description})]},`s:${ee.name}`)})]}),C&&!T&&P.length>0&&s.jsxs("div",{className:"absolute left-0 right-0 bottom-full mb-2 z-10 bg-surface border border-outline-subtle rounded-xl shadow-lg overflow-hidden max-h-72 overflow-y-auto",children:[s.jsx("div",{className:"px-3 py-1.5 text-body-xs uppercase tracking-wide text-text-tertiary border-b border-outline-faint",children:"Skills"}),P.map((L,q)=>s.jsxs("button",{type:"button",onMouseDown:me=>{me.preventDefault(),M(L)},onMouseEnter:()=>D(q),className:B("w-full text-left px-3 py-2 flex flex-col gap-0.5 border-b border-outline-faint last:border-b-0",q===Z?"bg-surface-sunken":"hover:bg-surface-subtle"),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-sm font-medium text-text-primary",children:L.origin==="user"?L.title||L.name:`/${L.name}`}),L.origin!=="user"&&L.title&&L.title!==L.name&&s.jsx("span",{className:"text-xs text-text-secondary",children:L.title})]}),L.description&&s.jsx("span",{className:"text-xs text-text-secondary line-clamp-1",children:L.description})]},L.name))]}),s.jsxs("div",{className:"relative border border-outline-subtle rounded-xl bg-surface shadow-sm focus-within:border-outline-brand focus-within:ring-2 focus-within:ring-outline-brand/20",onDragEnter:L=>{L.preventDefault(),N(!0)},onDragOver:L=>{L.preventDefault(),N(!0)},onDragLeave:L=>{L.currentTarget.contains(L.relatedTarget)||N(!1)},onDrop:L=>{var q;L.preventDefault(),N(!1),(q=L.dataTransfer.files)!=null&&q.length&&g(L.dataTransfer.files)},children:[j&&s.jsx(O9e,{}),(m.length>0||x)&&s.jsxs("div",{className:"px-3 pt-2 flex flex-wrap gap-1.5",children:[m.map(L=>s.jsx(_9e,{attachment:L,onRemove:()=>y(L.id)},L.id)),x&&s.jsxs("div",{className:"text-body-xs text-text-error bg-surface-errorSubtle border border-outline-error roun
893ded-md px-2 py-1 inline-flex items-center gap-1",children:[s.jsx(yt,{className:"w-3 h-3"}),x]})]}),s.jsx("textarea",{ref:i,value:e,onChange:L=>{t(L.target.value),z(L.target)},onSelect:L=>z(L.currentTarget),onKeyDown:re,onPaste:te,rows:1,placeholder:P9e(l),className:"w-full resize-none px-4 py-3 text-base md:text-sm bg-transparent focus:outline-none placeholder:text-text-tertiary"}),s.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-t border-outline-faint",children:[s.jsx("input",{ref:b,type:"file",multiple:!0,accept:lUe,className:"hidden",onChange:L=>{var q;(q=L.target.files)!=null&&q.length&&g(L.target.files),L.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var L;return(L=b.current)==null?void 0:L.click()},title:"Attach files (images, PDFs, text)","aria-label":"Attach files",className:"p-2.5 md:p-1.5 rounded-md text-text-tertiary hover:text-text-body hover:bg-surface-sunken",children:s.jsx(yre,{className:"w-4 h-4"})}),s.jsx("button",{type:"button",onClick:G,title:"Skills (type /)","aria-label":"Open skills",className:"p-2.5 md:p-1.5 rounded-md text-text-tertiary hover:text-text-body hover:bg-surface-sunken min-w-10 md:min-w-0",children:s.jsx("span",{className:"text-sm font-semibold leading-none",children:"/"})}),f&&s.jsx(rUe,{value:u,onChange:d,defaultLabel:h}),s.jsx(K9e,{}),s.jsx("div",{className:"ml-auto flex items-center gap-1",children:o?s.jsx(yT,{content:"Stop",children:s.jsx("button",{onClick:r,"aria-label":"Stop",className:"ml-1 w-10 h-10 md:w-8 md:h-8 rounded-full bg-surface-inverse text-text-inverse flex items-center justify-center hover:bg-intent-neutralHover",children:s.jsx(qte,{className:"w-4 h-4"})})}):s.jsx(yT,{content:"Send",children:s.jsx("button",{onClick:()=>n(),"aria-label":"Send",disabled:!e.trim()&&m.length===0,className:B("ml-1 w-10 h-10 md:w-8 md:h-8 rounded-full flex items-center justify-center",e.trim()||m.length>0?"bg-intent-brand text-text-inverse hover:bg-intent-brandHover":"bg-surface-sunken text-text-tertiary cursor-not-allowed"),children:s.jsx(d6,{className:"w-4 h-4"})})})})]})]})]})})}function SUe(e){return e<60?`${e}s`:`${Math.floor(e/60)}m ${e%60}s`}const kq=["How can I help today?","What's on your mind?","Where should we start?","Ready when you are.","What's the question?","What are we working on?","Just ask.","What needs a look?","What's the story?","I'm listening."],CUe=[{from:5,to:12,lines:["Morning. What's first?","What's first this morning?"]},{from:12,to:17,lines:["Afternoon. What's on the list?"]},{from:17,to:22,lines:["Still going?","Evening. What's left?"]},{from:22,to:24,lines:["Late one. What's up?"]},{from:0,to:5,lines:["Late one. What's up?"]}];function EUe(e=new Date){const t=e.getHours(),n=CUe.filter(r=>t>=r.from&&t<r.to).flatMap(r=>r.lines);return[...kq,...n]}function AUe(e=new Date){const t=EUe(e);return t[Math.floor(Math.random()*t.length)]??kq[0]}const O$=4;function TUe(e,t){const n=[...e];for(let r=n.length-1;r>0;r--){const a=Math.floor(Math.random()*(r+1));[n[r],n[a]]=[n[a],n[r]]}return n.slice(0,t)}function Vp(e){const{heading:t,subhead:n,onPick:r,slot:a,gridMaxWidth:i="xl"}=e,o=e.examples,l=e.pool,c=e.duties,[u,d]=p.useState(null),[h]=p.useState(()=>t??AUe()),f=t??h,m=p.useMemo(()=>o&&o.length>0?o.slice(0,O$):l&&l.length>0?TUe(l,O$):[],[o,l]);return s.jsxs("div",{className:"text-center py-4",children:[s.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-text-primary",children:f}),n?s.jsx("p",{className:"mt-2 text-sm text-text-secondary max-w-md mx-auto",children:n}):null,a&&s.jsx("div",{className:"mt-5 flex justify-center",children:a}),u?s.jsxs("div",{className:"mt-8 max-w-xl mx-auto text-left",children:[s.jsxs("button",{onClick:()=>d(null),className:"mb-2 inline-flex items-center gap-1 text-sm text-text-secondary hover:text-text-primary",children:[s.jsx(ud,{className:"w-4 h-4"})," Back"]}),s.jsx(T3,{formSpec:u.form,onSubmit:async x=>(r(u.compose(x)),{ok:!0})})]}):s.jsxs(s.Fragment,{children:[m.length>0&&s.jsx("div",{className:B("mt-8 grid grid-cols-1 sm:grid-cols-2 gap-2 mx-auto",i==="2xl"?"max-w-2xl":"max-w-xl"),children:m.map((x,g)=>s.jsx(OUe,{example:x,onPick:r},`${x.text}-${g}`))}),c&&c.length>0&&s.jsx("div",{className:"mt-5 flex flex-wrap justify-center gap-2 max-w-xl mx-auto",children:c.map(x=>s.jsxs("button",{onClick:()=>d(x),className:"inline-flex items-center gap-1.5 rounded-full border border-outline-subtle px-3 py-1.5 text-sm text-text-secondary hover:border-outline hover:text-text-body hover:bg-surface-subtle transition-colors",children:[x.Icon&&s.jsx(x.Icon,{className:"w-3.5 h-3.5 text-text-tertiary shrink-0"}),s.jsx("span",{children:x.label})]},x.id))})]})]})}function OUe({example:e,onPick:t}){const{text:n,Icon:r,prompt:a}=e;return s.jsxs("button",{onClick:()=>t(a??n),className:"flex items-center gap-2.5 text-left text-sm text-text-body px-3.5 py-2.5 rounded-xl border border-outline-subtle hover:bg-surface-subtle hover:border-outline transition-colors",children:[r&&s.jsx(r,{className:"w-4 h-4 text-text-tertiary shrink-0"}),s.jsx("span",{className:"line-clamp-2",children:n})]})}const KS=4,IUe=3;function HS(e,t){return[{text:"What's flying",prompt:`What's flying for ${e} over the last 30 days?`,Icon:Xi},{text:"Returns picture",prompt:`Summarise ${e}'s returns picture for the last 90 days.`,Icon:_o},{text:"Latest monthly rollup",prompt:`Read ${e}'s most recent monthly rollup.`,Icon:il},{text:"Sync now",prompt:`Sync ${t} now.`,Icon:pa},{text:"About to stock out",prompt:`What's about to stock out for ${e}?`,Icon:zn},{text:"Latest payout",prompt:`Explain ${e}'s most recent payout.`,Icon:s0},{text:"Worst margin after fees",prompt:`Which of ${e}'s SKUs have the worst margin after fees?`,Icon:H2},{text:"Where am I overstocked?",prompt:`Where is ${e} overstocked right now?`,Icon:Si},{text:"Top return reasons",prompt:`Top return reasons for ${e} this month.`,Icon:_o},{text:"Top 10 by revenue",prompt:`Show me ${e}'s top 10 SKUs by revenue.`,Icon:fc},{text:"Call-prep brief",prompt:`Give me a call-prep brief on ${e}.`,Icon:dF},{text:"Focus for this week",prompt:`What should ${e} focus on this week?`,Icon:h6}]}function VS(e,t){const n=[...e];for(let r=n.length-1;r>0;r--){const a=Math.floor(Math.random()*(r+1));[n[r],n[a]]=[n[a],n[r]]}return n.slice(0,t)}function PUe(e,t){var d,h,f,m,x,g,y;const n=[],r=((d=e.warehouse_alerts)==null?void 0:d.skus)??[];r.length&&n.push({rank:0,chip:{text:`${r.length} SKU${r.length===1?"":"s"} selling but out of stock`,prompt:`${t} has ${r.length} active SKU${r.length===1?"":"s"} that are still selling but out of stock at Takealot (e.g. ${r.slice(0,3).map(b=>b.title).join(", ")}). Show me the full list, what I'm losing, and a replen plan.`,Icon:zn}});const a=((h=e.alerts)==null?void 0:h.returns_over_5pct)??0;a>0&&n.push({rank:1,chip:{text:`${a} SKU${a===1?"":"s"} with returns over 5%`,prompt:`${t} has ${a} SKU${a===1?"":"s"} with a return rate over 5%. Do a return-reason deep-dive on them and tell me what to fix.`,Icon:_o}});const i=(((f=e.days_to_stockout)==null?void 0:f.skus)??[]).filter(b=>b.days!=null&&b.days<=7);i.length&&n.push({rank:2,chip:{text:`${i.length} SKU${i.length===1?"":"s"} critically low on cover`,prompt:`${t} has ${i.length} SKU${i.length===1?"":"s"} within 7 days of stocking out (e.g. ${i.slice(0,3).map(b=>b.title).join(", ")}). Give me a replenishment plan with quantities.`,Icon:yt}});const o=((m=e.repricer)==null?void 0:m.wasted)??0;o>0&&n.push({rank:3,chip:{text:`${o} wasted re-pricer${o===1?"":"s"}`,prompt:`${t} has ${o} re-pricer${o===1?"":"s"} active on non-buyable SKUs. Show me which ones and how to free up those re-pricer slots.`,Icon:iF}});const l=(((x=e.movers)==null?void 0:x.fallers)??[])[0];l&&l.delta<0&&n.push({rank:4,chip:{text:`${l.title} sales sliding`,prompt:`Sales on "${l.title}" dropped this week vs last for ${t}. What's going on and what should I do about it?`,Icon:ax}});const c=(g=e.fee_shift)==null?void 0:g.fee_pct_delta_pp;c!=null&&c>1&&n.push({rank:5,chip:{text:`Fees up ${c.toFixed(1)}pp this month`,prompt:`${t}'s fee load rose ${c.toFixed(1)} percentage points vs the prior 30 days. Break down what's driving it and where I'm losing margin.`,Icon:H2}});const u=((y=e.conversion_leaks)==null?void 0:y.skus)??[];return u.length&&n.push({rank:6,chip:{text:`${u.length} high-traffic, low-converting SKU${u.length===1?"":"s"}`,prompt:`${t} has ${u.length} SKU${u.length===1?"":"s"} getting traffic but converting below median. Run a conversion-leak audit and tell me what's losing the sale â only listing or price changes the seller can actually make, not unbranded Brand gaps, reviews, cancellations, or DC stock cover.`,Icon:Xi}}),n.sort((b,v)=>b.rank-v.rank).slice(0,IUe).map(b=>b.chip)}function RUe(e,t,n){const r=PUe(e,t),a=KS-r.length;if(a<=0)return r;const i=new Set(r.map(c=>c.text)),o=HS(t,n),l=VS(o,o.length).filter(c=>!i.has(c.text)).slice(0,a);return[...r,...l]}function jq(e,t){const[n,r]=p.useState(()=>VS(HS(t,e??""),KS));return p.useEffect(()=>{if(!e)return;let a=!1;return r(VS(HS(t,e),KS)),K.overviewScoreboard(e).then(i=>{a||r(RUe(i,t,e))}).catch(()=>{}),()=>{a=!0}},[e,t]),n}const DUe='EXISTING LISTING ATTRIBUTES â `get_product_mpv.summary.attribute_coverage` is the shared check (same function product-upgrade, listing-score, and the Listing Upgrades SOP use). NEVER conclude "nothing is missing" from empty `attribute_gaps` / "Not Specified" alone. Never-filled recommended attributes (especially Booleans like Machine Washable) do not appear in MPV at all. If `listing_quality` < 3 or `shortcoming_ids` contains 2 or 3, something is still incomplete â name `required.missing` and `recommended.missing`. Takealot needs â¥50% of recommended attributes to leave Moderate.',MUe='CONVERSION / LISTING DIAGNOSIS â distinguish seller-actionable listing fixes from context the seller cannot change. NEVER present as a "fix": (1) missing Brand on an unbranded listing (blank / Generic / Unbranded â do not invent a brand), (2) low review count (sellers cannot create Takealot reviews), (3) customer-cancellation or failed-delivery return rate (not seller-actionable), (4) low Takealot DC stock cover (replenishment already owns that). Those may explain conversion as FYI context only. If a SKU has no remaining listing/price/image gap the seller can actually edit, say so â do not flag it to the customer as something to fix. `score_listing.recommended_actions` carries `actionable`; emit task-cards / "What\'s Missing / Fix" only for `actionable: true`.',Nq=[{id:"replenish-stock",icon:"package",surfaces:["chat"],skill:"replen-builder",label:"{understocked} SKUs running low â plan a reorder",label_fallback:"Plan a stock replenishment",form:{id:"replenish-stock",intro:"I'll build your replenishment workbook. A few quick choices:",
893submit_label:"Build my replen workbook",fields:[{type:"radio-group",name:"horizon",label:"Plan to cover the nextâ¦",options:["30 days","60 days","90 days"],default:"60 days",required:!0},{type:"radio-group",name:"scope",label:"Which SKUs should I include?",options:["Only the ones running low","All my SKUs","Top sellers only (A-class)"],default:"Only the ones running low",required:!0},{type:"radio-group",name:"slow_movers",label:"Include slow movers?",options:["No â skip them","Yes â include everything"],default:"No â skip them",required:!0},{type:"text",name:"budget",label:"Budget cap (optional)",placeholder:"e.g. R50,000 â leave blank for no cap",required:!1}]},prompt_template:["Run the replen-builder skill for {sellerName} â build the bulk replenishment workbook (Takealot xlsx).","","- Cover the next: {horizon}","- SKUs: {scope}","- Slow movers: {slow_movers}","- Budget cap: {budget}","","Build the workbook directly and reply with only the download link and a one-line summary â no long write-up."].join(` 894`)},{id:"balance-dc-stock",icon:"scale",surfaces:["chat"],skill:"replen-builder",label:"Stock vs demand off in {region} â rebalance",label_fallback:"Balance your DC stock",form:{id:"balance-dc-stock",intro:"I'll build your DC balance workbook across Takealot's DCs (JHB / CPT / DBN).",submit_label:"Build my balance workbook",fields:[{type:"radio-group",name:"approach",label:"What should I plan?",options:["Split my next inbound shipment to match demand","Rebalance stock already sitting in the DCs","Just show me the demand-vs-stock split"],default:"Split my next inbound shipment to match demand",required:!0},{type:"radio-group",name:"window",label:"Weight demand byâ¦",options:["Last 30 days","Last 90 days"],default:"Last 90 days",required:!0}]},prompt_template:["Run the replen-builder skill in balance mode for {sellerName} â build the balance replen workbook (Takealot xlsx) that evens stock across the JHB / CPT / DBN DCs.","","- Approach: {approach}","- Weight demand by: {window}","","Build the workbook directly and reply with only the download link and a one-line summary â no long write-up."].join(` 895`)},{id:"run-promotion",icon:"megaphone",surfaces:["chat"],skill:"promotion-builder",label:"{joinable} promotions open â none running for you",label_fallback:"Run a promotion",form:{id:"run-promotion",intro:"I'll build your promotion application workbook.",submit_label:"Build my promotion workbook",fields:[{type:"radio-group",name:"goal",label:"What's the goal?",options:["Clear slow-moving stock","Push my best sellers","Seasonal / event push"],default:"Clear slow-moving stock",required:!0},{type:"radio-group",name:"skus",label:"Which SKUs should I consider?",options:["You pick the best candidates","My slow movers","My top sellers"],default:"You pick the best candidates",required:!0}]},prompt_template:["Run the promotion-builder skill for {sellerName} â build the Takealot promotion application workbook (xlsx).","","- Goal: {goal}","- SKUs to consider: {skus}","","Pick the best open promotion and the SKUs/discount, build the workbook directly, and reply with only the download link and a one-line summary â no long write-up."].join(` 896`)},{id:"stock-cover",icon:"gauge",surfaces:["sops"],mode:"direct",skill:"replen-builder",marketplaces:["takealot"],label:"Send stock to Takealot",label_fallback:"Send stock to Takealot",description:"A Takealot bulk-replenishment workbook â moves stock you already own into the DCs, sized to your sales velocity and target days of cover.",form:{id:"stock-cover",intro:"I'll build your Takealot bulk-replenishment workbook from current cover, velocity, and in-flight stock.",submit_label:"Build my replenishment workbook",fields:[{type:"radio-group",name:"horizon",label:"Cover the nextâ¦",options:["15 days","30 days","45 days","60 days"],default:"30 days",required:!0},{type:"number",name:"horizon_custom",label:"â¦or a custom number of days",placeholder:"e.g. 75",min:1,max:365,help:"Overrides the choice above when set."},{type:"radio-group",name:"coverage",label:"Which SKUs?",options:["Everything I sell","Top sellers by revenue","Running low or out at Takealot","Rebalance only (no new stock)"],default:"Everything I sell",required:!0,help:"âRunning low or out at Takealotâ = the urgent list: selling SKUs with â¤7 days of DC cover (includes out-of-stock), restocked off blended velocity â independent of your own warehouse stock."},{type:"radio-group",name:"source",label:"Source fromâ¦",options:["Order new stock","Current SOH only"],default:"Order new stock",required:!0,help:"âCurrent SOH onlyâ caps the workbook to stock you already hold â no new purchase order."},{type:"select",name:"dc",label:"Ship to which DC?",options:["All DCs","CPT","JHB","DBN"],default:"All DCs",required:!0},{type:"text",name:"sku_prefix",label:"Limit to SKUs starting withâ¦",placeholder:"e.g. YLG, ABC",maxlength:200,help:"Optional. Comma-separated prefixes; leave blank for every SKU."},{type:"number",name:"min_margin_pct",label:"Only SKUs above this margin %",placeholder:"e.g. 20 â leave blank for every SKU",min:0,max:100,required:!1,help:"True margin after Takealot fees and cost. SKUs without a cost on file are dropped when this is set."},{type:"checkbox-group",name:"balance_topup",label:"DC balance",options:["Also top up empty DCs"],help:"Sends 1 unit of each selling SKU to any DC where itâs out of stock but in stock elsewhere."}]}
896,prompt_template:["Discuss the bulk-replenishment reorder plan for {sellerName} (cover {horizon}, {coverage}).","The reorder workbook was already generated â help me interpret it and prioritise."].join(` 897`)},{id:"supplier-order",icon:"package-plus",surfaces:["sops"],mode:"direct",skill:"supplier-order",marketplaces:["takealot"],label:"Buy stock from your supplier",label_fallback:"Buy stock from your supplier",description:"A purchase-order workbook sized off your sales history â what to buy, and how much, to cover the months ahead.",form:{id:"supplier-order",intro:"I'll work out what you need to buy from your supplier, based on how fast each SKU sells and what you already hold.",submit_label:"Build my supplier order",fields:[{type:"radio-group",name:"horizon",label:"Order enough to coverâ¦",options:["1 month","2 months","3 months","6 months"],default:"2 months",required:!0,help:"There's no lead-time allowance â asking for 2 months buys exactly 2 months of demand. If your supplier takes 60 days, ask for a longer cover."},{type:"radio-group",name:"lookback",label:"Base the forecast on the lastâ¦",options:["30 days","60 days","90 days"],default:"90 days",required:!0,help:"Shorter reacts faster if you're growing; longer is steadier if your sales are lumpy."},{type:"radio-group",name:"slow_movers",label:"Include slow movers?",options:["No â skip them","Yes â include everything"],default:"No â skip them",required:!0,help:"Slow movers are SKUs with fewer than 5 units sold in the window â too little history to size an order from."},{type:"text",name:"sku_prefix",label:"Limit to SKUs starting withâ¦",placeholder:"e.g. YLG, ABC",maxlength:200,help:"Optional. Comma-separated prefixes; leave blank for every SKU."}]},prompt_template:["Discuss the supplier order for {sellerName} (covering {horizon}, forecast off the last {lookback}).","The purchase-order workbook was already generated â help me interpret it and prioritise what to buy first."].join(` 898`)},{id:"stock-recon",icon:"receipt",surfaces:["sops"],mode:"direct",skill:"stock-recon-claim",label:"File the monthly stock recon claim",label_fallback:"File the monthly stock recon claim",description:"A SARS-ready Stock Loss Claim tax invoice, built from your monthly Stock Recon CSV.",form:{id:"stock-recon",intro:"Upload your monthly Stock Recon CSV and I'll build the Stock Loss Claim tax invoice PDF.",submit_label:"Build my stock loss claim",fields:[{type:"file",name:"recon_csv",label:"Monthly Stock Recon CSV",accept:".csv",required:!0,help:"The Stock Recon export from the Takealot Seller Portal."},{type:"radio-group",name:"vat_registration",label:"VAT registration",options:["Use my account's VAT status","I'm VAT-registered","I'm not VAT-registered"],default:"Use my account's VAT status",required:!0,help:"Pick a status if your account's VAT details aren't on file yet."},{type:"text",name:"vat_number",label:"VAT number (if registered & not already on file)",placeholder:"10 digits, starts with 4",required:!1,help:"We'll use your account's number if you leave this blank."},{type:"text",name:"invoice_number",label:"Invoice number (optional)",placeholder:"e.g. 14444",required:!1,maxlength:60,help:"Leave blank for our default (SR-<seller id>-<month year>). Set it to match your own invoice sequence."}]},prompt_template:["Discuss the Stock Loss Claim for {sellerName} ({recon_csv}).","The invoice PDF was already generated â help me check it or explain the numbers."].join(` 899`)},{id:"listing-upgrades",icon:"sparkles",surfaces:["sops"],mode:"chat",skill:"product-upgrade",label:"Upgrade my listings",label_fallback:"Upgrade my listings",description:"AI rewrites titles, attributes and copy to lift SEO and conversion on listings you already have.",form:{id:"listing-upgrades",intro:"I'll upgrade your listings. What's the focus?",submit_label:"Start listing upgrades",fields:[{type:"radio-group",name:"focus",label:"What should I improve?",options:["SEO â titles & keywords","Fill missing attributes","Full content rewrite"],default:"SEO â titles & keywords",required:!0},{type:"radio-group",name:"scope",label:"Which listings?",options:["You pick the best candidates","My top sellers","A specific SKU list (I'll paste them)"],default:"You pick the best candidates",required:!0}]},prompt_template:["Run the product-upgrade skill for {sellerName}.","","- Focus: {focus}","- Listings: {scope}","",DUe,MUe,"product-upgrade / get_product_mpv / score_listing all call the same coverage check â trust `attribute_coverage.required.missing` and `recommended.missing`, not empty MPV Not Specified rows.","For one listing named by PLID, TSIN, barcode, or title, pass catalogue_search on build_edit_request_workbook (search_by plid|tsin|gtin|title). Dropdown values come from the live category fields. Warn on required_compliance_documents that are not compliant, and keep warranty months and YouTube video links inside Takealot's rules.","","Walk me through the upgrades step by step; if you need the SKU list or any choices, ask before changing anything."].join(` 900`)},{id:"listing-creation",icon:"file-plus",surfaces:["sops"],mode:"builder",skill:"create-takealot-listing",label:"Create new Takealot listings",label_fallback:"Create new Takealot listings",description:"Submit brand-new products to your Takealot catalogue, guided from category to publish.",form:{id:"listing-creation",intro:"I'll create new Takealot listings. How do you want to provide the products?",submit_label:"Start listing creation",fields:[{type:"radio-group",name:"source",label:"Product details fromâ¦",options:["I'll paste / type the details","Scrape from a product URL"],default:"I'll paste / type the details",required:!0}
900,{type:"textarea",name:"details",label:"Product details or URL (optional â you can add them next)",placeholder:"e.g. paste a product URL, or the title + key specs",required:!1}]},prompt_template:["Run the create-takealot-listing skill for {sellerName}.","","- Source: {source}","- Provided details: {details}","","Walk me through category, attributes, and images, and show a preview for my approval before anything is submitted to Takealot."].join(` 901`)},{id:"promotion-builder",icon:"megaphone",surfaces:["sops"],mode:"direct",skill:"promotion-builder",label:"Build a promotion application",label_fallback:"Build a promotion application",description:"A ready-to-submit application workbook for an open Takealot promotion.",form:{id:"promotion-builder",intro:"I'll build your Takealot Promotion Application workbook â pick a campaign, a strategy and a discount.",submit_label:"Build my promotion workbook",fields:[{type:"select",name:"takealot_promotion",label:"Takealot campaign (optional)",options_source:{endpoint:"open-promotions"},required:!1,help:"Pick the campaign so the seller sees when it goes live and ends on the approval page."},{type:"radio-group",name:"strategy",label:"Strategy",options:["My best sellers","Underperformers (boost)","Launch (in stock, no recent sales)","Most wished-for","Newest items","Clear overstock","Items with storage fees"],default:"My best sellers",required:!0},{type:"number",name:"top_n",label:"Number of items",placeholder:"e.g. 50",min:1,max:1e3,help:"Caps the workbook to the top N items by the strategy's ranking. Leave blank for 50."},{type:"text",name:"discount",label:"Discount %",placeholder:"e.g. 10",required:!1,help:"Suggested promo discount. Leave blank for 10%."},{type:"checkbox-group",name:"stock_options",label:"Stock to include",options:["Lead-time stock","Incoming stock at DC"],default:["Lead-time stock","Incoming stock at DC"],help:"Pre-fills the workbook's lead-time and incoming-stock columns. Both on by default."},{type:"select",name:"brand",label:"Brand (optional)",options_source:{endpoint:"taxonomy/brands"},required:!1,help:"Scope to one brand. Options come from your catalogue (captured from Takealot); the list fills in over the first few runs."},{type:"select",name:"department",label:"Department (optional)",options_source:{endpoint:"taxonomy/departments"},required:!1,help:"Scope to one Takealot department. Layers on top of the strategy above."},{type:"text",name:"filter",label:"Limit to (product name contains â optional)",required:!1}]},prompt_template:["Discuss the promotion application for {sellerName} ({strategy}, {discount}% off).","The workbook was already generated â help me sanity-check the picks and prices."].join(` 902`)},{id:"fba-inbound-manifest",icon:"truck",surfaces:["sops"],marketplaces:["amazon_za"],mode:"direct",skill:"fba-inbound-manifest",label:"Build an Amazon FBA inbound manifest",label_fallback:"Build an Amazon FBA inbound manifest",description:"A ready-to-upload Send to Amazon manifest of your FBA listings, with quantities sized to your sales velocity and target days of cover.",form:{id:"fba-inbound-manifest",intro:"I'll build your Send to Amazon FBA manifest from your FBA listings, 30-day velocity and current FBA stock.",submit_label:"Build my FBA manifest",fields:[{type:"radio-group",name:"horizon",label:"Cover the nextâ¦",options:["30 days","45 days","60 days","90 days"],default:"30 days",required:!0},{type:"number",name:"horizon_custom",label:"â¦or a custom number of days",placeholder:"e.g. 75",min:1,max:365,help:"Overrides the choice above when set."},{type:"radio-group",name:"prep_owner",label:"Who preps the units?",options:["Seller","Amazon"],default:"Seller",required:!0,help:"âSellerâ = you prep before they arrive; âAmazonâ = opt in to the FBA Prep Service."},{type:"radio-group",name:"labeling_owner",label:"Who labels the units?",options:["Seller","Amazon"],default:"Seller",required:!0,help:"âSellerâ = you label before they arrive; âAmazonâ = opt in to the FBA Label Service."},{type:"checkbox-group",name:"scope",label:"Scope",options:["Include all FBA SKUs (even with no recommended quantity)"],help:"By default the manifest lists only SKUs with a recommended send quantity. Tick to include your full FBA catalogue, with blank quantities to hand-fill where there's no recent velocity."}]}
902,prompt_template:["Discuss the Amazon FBA inbound manifest for {sellerName} (cover {horizon}).","The manifest was already generated â help me decide quantities and what to send."].join(` 903`)}];function $Ue(e){return Nq.find(t=>t.id===e)??null}const Vx={package:Si,scale:fF,megaphone:a6,gauge:iF,receipt:yf,sparkles:Ht,"file-plus":xne,truck:qi,"package-plus":Gm};function I$(e,t){return e.replace(/\{(\w+)\}/g,(n,r)=>t[r]!=null?String(t[r]):"")}function LUe(e,t){for(const n of e.matchAll(/\{(\w+)\}/g)){const r=t[n[1]];if(r==null||String(r).length===0)return!1}return!0}function Sq(e,t){const[n,r]=p.useState([]);return p.useEffect(()=>{if(!e){r([]);return}let a=!1;return r([]),K.sellerDuties(e).then(i=>{if(a)return;const o=(i.duties??[]).map(l=>{const c=$Ue(l.id);if(!c)return null;const u=l.context??{},d={sellerName:t,...u},h=c.label&&LUe(c.label,d)?I$(c.label,d):c.label_fallback??c.id;return{id:c.id,label:h,Icon:Vx[c.icon],form:c.form,compose:f=>{const m=f.budget!=null?String(f.budget).trim():"",x={sellerName:t,...u,...f,budget:m||"no cap"};return I$(c.prompt_template,x)}}}).filter(l=>l!==null);r(o)}).catch(()=>{a||r([])}),()=>{a=!0}},[e,t]),n}function D3({error:e,loading:t}){return e?s.jsxs("div",{className:"m-6 text-sm text-text-error bg-surface-errorSubtle border border-outline-error rounded-lg p-4 flex items-start gap-2",children:[s.jsx(yt,{className:"w-4 h-4 shrink-0 mt-0.5"}),s.jsx("span",{children:e})]}):t?s.jsx("div",{className:"flex-1 flex items-center justify-center text-xs text-text-tertiary",children:"Loadingâ¦"}):null}const Wk="gadjet:agent:lastSellerSlug",Kk="gadjet:agent:preferWorkspace";function P$(){var M;const{chatId:e}=jn(),t=Rt(),n=Lt(),[r]=ki(),[a,i]=p.useState(null),[o,l]=p.useState(null),c=p.useRef(null),u=p.useRef(null),[d,h]=p.useState(()=>`draft-${Date.now()}`),[f,m]=p.useState(""),[x,g]=p.useState(null),[y,b]=p.useState(null);p.useEffect(()=>{K.sellers().then(z=>g(z)).catch(()=>g([]))},[]);const v=p.useRef(null);p.useEffect(()=>{if(qo(e))return;const z=r.get("prompt")||"",G=r.get("skill")||"",te=r.get("seller")||"",re=r.get("args")||"";if(!z&&!G){v.current=null;return}if(!Ju(e)){t({pathname:Zl(),search:`?${r.toString()}`},{replace:!0});return}const L=`${z} 904${G} 905${te} 906${re}`;if(v.current===L)return;v.current=L;let q="";if(z)q=z;else if(G){const me=te?` for ${te}`:"",ee=re?` with args ${re}`:"";q=`Run the ${G} skill${me}${ee}.`}te&&b(te),m(q),h(`seeded-${Date.now()}`),t({pathname:Zl(),search:""},{replace:!0})},[e,t,r]),p.useEffect(()=>{const z=n.kind==="ready"?n.me.allowed_slugs:[],G=x&&x.length>0?x.map(q=>q.slug):z;if(G.length===0||y&&G.includes(y)||typeof window<"u"&&window.localStorage.getItem(Kk)==="1"&&y===null)return;const re=typeof window<"u"?window.localStorage.getItem(Wk):null,L=re&&G.includes(re)?re:G[0];b(L)},[x,y,n]);const w=p.useCallback(z=>{b(z),typeof window<"u"&&(z?(window.localStorage.setItem(Wk,z),window.localStorage.removeItem(Kk)):(window.localStorage.removeItem(Wk),window.localStorage.setItem(Kk,"1")))},[]);p.useEffect(()=>{c.current=null,u.current=null},[e]);const _=p.useCallback(z=>{c.current=null,u.current=null,typeof(z==null?void 0:z.sellerSlug)=="string"&&z.sellerSlug&&b(z.sellerSlug),m(typeof(z==null?void 0:z.prompt)=="string"?z.prompt:""),h(`draft-${Date.now()}`);const G=Zl();if(Ju(e)){window.location.pathname!==G&&window.history.replaceState(null,"",G);return}t(G)},[e,t]);p.useEffect(()=>{function z(G){const te=G.detail;_({prompt:te==null?void 0:te.prompt,sellerSlug:te==null?void 0:te.sellerSlug})}return window.addEventListener("gadjet:agent-new-chat",z),()=>window.removeEventListener("gadjet:agent-new-chat",z)},[_]),p.useEffect(()=>{const z=qo(e);if(!z){i(null);return}i(null),l(null),K.getGlobalChat(z).then(i).catch(G=>l(String(G)))},[e]);const k=p.useCallback(()=>{_()},[_]),j=p.useCallback(z=>{var re,L,q;if(z.is_error)return;new Set(["validate_and_attach_takealot_key","super_admin_onboard_seller","super_admin_onboard_managed_seller","convert_from_managed","convert_to_managed"]).has(z.name)&&((re=z.summary)!=null&&re.ok||(L=z.summary)!=null&&L.slug)&&ai(),new Set(["super_admin_onboard_managed_seller","super_admin_onboard_seller","validate_and_attach_takealot_key","sync_seller","sync_one"]).has(z.name)&&((q=z.summary)!=null&&q.slug)&&window.dispatchEvent(new CustomEvent("gadjet:sync-started",{detail:{slug:z.summary.slug}}))},[]),N=p.useCallback(z=>{var G;(z.name==="sync_seller"||z.name==="sync_one")&&typeof((G=z.input)==null?void 0:G.slug)=="string"&&window.dispatchEvent(new CustomEvent("gadjet:sync-started",{detail:{slug:z.input.slug}}))},[]),E=p.useCallback(async()=>
906{if(y){const G=await K.createChat(y);return c.current=G.id,u.current=y,window.history.replaceState(null,"",`/sellers/${y}/chats/${G.id}`),window.dispatchEvent(new CustomEvent("gadjet:chat-saved",{detail:{slug:y}})),{chatId:G.id,slug:y}}const z=await K.createGlobalChat();return c.current=z.id,u.current=null,window.history.replaceState(null,"",`/agent/${z.id}`),window.dispatchEvent(new CustomEvent("gadjet:chat-saved",{detail:{slug:"_global"}})),{chatId:z.id,slug:null}},[y]),A=p.useCallback(async z=>{const G=qo(e)||c.current;if(!G)return;const te=u.current;te?(await K.saveChat(te,G,{messages:Hp(z)}),window.dispatchEvent(new CustomEvent("gadjet:chat-saved",{detail:{slug:te}}))):(await K.saveGlobalChat(G,{messages:Hp(z)}),window.dispatchEvent(new CustomEvent("gadjet:chat-saved",{detail:{slug:"_global"}})))},[e]),C=n.kind==="ready"&&n.me.is_demo_mode,T=n.kind==="ready"&&n.me.allowed_slugs.length>0,S=p.useMemo(()=>(x??[]).find(z=>z.slug===y)??null,[x,y]),O=p.useMemo(()=>C?BUe:FUe,[C]),R=(S==null?void 0:S.display_name)??y??"",I=y&&!C?y:null,$=jq(I,R),P=Sq(I,R),F=I?P:void 0,Z=I?$:void 0,D=C?"You're exploring the demo store.":void 0,H=!qo(e),Y=H&&!C&&T;return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Agent",to:"/agent"},...Ju(e)?[{label:"New chat"}]:a?[{label:a.title}]:[]],actions:s.jsxs("button",{type:"button",onClick:k,className:"min-h-11 md:min-h-0 text-xs text-text-secondary hover:text-text-primary flex items-center gap-1 px-2.5 md:px-2 py-1 rounded-md border border-outline-subtle hover:bg-surface-subtle",children:[s.jsx(In,{className:"w-3 h-3"})," New chat"]})}),H&&s.jsx(of,{initialMessages:[],initialInput:f,autoSendInitial:f.length>0,onCreateDraft:E,extraRequestBody:()=>{const z={},G=c.current?u.current:y;return G&&(z.seller_slug=G),c.current&&(z.chat_id=c.current),z},onConversationChange:A,onToolResult:j,onToolInputComplete:N,welcome:({pickExample:z})=>s.jsx(Vp,{subhead:D,pool:O,examples:Z,duties:F,onPick:z,slot:Y?s.jsx(UUe,{sellers:x??[],selectedSlug:y,onSelect:w}):void 0}),placeholder:y&&x?`Ask about ${((M=x.find(z=>z.slug===y))==null?void 0:M.display_name)??y}â¦`:"Ask about a seller, a SKU, a rollupâ¦"},d),qo(e)&&s.jsx(D3,{error:o,loading:!o&&!a}),qo(e)&&!o&&a&&a.id===e&&s.jsx(of,{initialMessages:Aw(a.messages),extraRequestBody:{chat_id:e},chatId:e,onConversationChange:A,onToolResult:j,onToolInputComplete:N,welcome:({pickExample:z})=>s.jsx(Vp,{subhead:D,pool:O,examples:Z,duties:F,onPick:z}),placeholder:"Ask about a seller, a SKU, a rollupâ¦"},e)]})}const FUe=[{text:"Sellers that need attention",prompt:"Which sellers are pending and need attention?",Icon:yt},{text:"What's flying at Photo 24",prompt:"What's flying for Photo 24 over the last 30 days?",Icon:Xi},{text:"Ailon Naturals returns",prompt:"Summarise the returns picture for Ailon Naturals.",Icon:_o},{text:"Photo 24 monthly rollup",prompt:"Read Photo 24's most recent monthly rollup and pull out the action items.",Icon:il},{text:"Sellers at risk this week",prompt:"Which of my sellers are at risk this week?",Icon:zn},{text:"Who hasn't synced",prompt:"Who hasn't synced in the last 24 hours?",Icon:pa},{text:"Portfolio overview",prompt:"Show me the portfolio overview.",Icon:rx},{text:"Fee shocks this month",prompt:"Which sellers had a fee shock in the last 30 days?",Icon:ix},{text:"Meeting notes this week",prompt:"Round up my meeting notes from the past week.",Icon:ore},{text:"What's overdue",prompt:"What's overdue across my book?",Icon:pu}],BUe=[{text:"Top 5 SKUs this month",prompt:"What were the top 5 SKUs by units in the last 30 days?",Icon:fc},{text:"90-day sales trend",prompt:"Show me the sales trend for the last 90 days.",Icon:Xi},{text:"Weakest listings",prompt:"Which listings have the lowest listing quality?",Icon:yt},{text:"What's driving returns",prompt:"What's the return rate, and which products drive it?",Icon:_o},{text:"About to stock out",prompt:"Which SKUs are about to run out of stock?",Icon:zn},{text:"True margin on top SKUs",prompt:"What's the true margin on my top 10 SKUs after fees?",Icon:H2},{text:"Where am I overstocked?",prompt:"Where am I overstocked right now?",Icon:Si},{text:"Damage in transit",prompt:"Which SKUs have the worst damage-in-transit rate?",Icon:qi},{text:"What should I reorder?",prompt:"What's selling well that I should reorder?",Icon:pa},{text:"Last week's payout",prompt:"Show me last week's payout breakdown.",Icon:s0}];function UUe({sellers:e,selectedSlug:t,onSelect:n}){const r=Lt(),[a,i]=p.useState(!1),o=r.kind==="ready"?r.me.allowed_slugs:[],l=p.useMemo(()=>{const h=new Map;for(const f of e)h.set(f.slug,f.display_name);return h},[e]),c=e.length>0?e.map(h=>h.slug):o,u=h=>l.get(h)??h,d=t?u(t):"No seller (workspace)";return s.jsxs(zC,{open:a,onOpenChange:i,children:[s.jsx(WC,{asChild:!0,children:s.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-md border border-outline-subtle bg-surface text-sm text-text-body hover:bg-surface-subtle",children:[s.jsx(sx,{className:"w-3.5 h-3.5 text-text-secondary"}),s.jsx("span",{className:"font-medium",children:d}),s.jsx(Pn,{className:"w-3.5 h-3.5 text-text-secondary"})]})}),s.jsxs(b0,{align:"center",className:"w-64 max-h-72 overflow-auto p-1",children:[s.jsx("button",{type:"button",onClick:()=>{n(null),i(!1)},className:`w-full text-left px-3 py-1.5 text-sm rounded hover:bg-surface-subtle ${t===null?"text-text-brand font-medium":"text-text-body"}`,children:"No seller (workspace)"}),s.jsx("div",{className:"my-1 border-t border-outline-faint"}),c.map(h=>s.jsx("button",{type:"button",onClick:()=>{n(h),i(!1)},className:`w-full text-left px-3 py-1.5 text-sm rounded hover:bg-surface-subtle truncate ${h===t?"text-text-brand font-medium":"text-text-body"}`,children:u(h)},h))]})]})}function R$(){const{slug:e="",chatId:t}=jn(),n=Rt(),[r,a]=p.useState(null),[i,o]=p.useState(null),[l,c]=p.useState(null),[u,d]=p.useState(!1),[h,f]=p.useState(!1),[m,x]=p.useState(()=>`draft-${Date.now()}`),g=p.useRef(null),y=(r==null?void 0:r.display_name)??e,b=jq(e,y),v=Sq(e,y);p.useEffect(()=>{K.seller(e).then(a).catch(()=>{})},[e]),p.useEffect(()=>{g.current=null,t&&f(!1)},[t,e]),p.useEffect(()=>{if(t){d(!0);return}if(h){d(!0);return}let A=!1;return d(!1),(async()=>{try{const C=await K.listChats(e);if(A)return;C.length>0?n(`/sellers/${e}/chats/${C[0].id}`,{replace:!0}):d(!0)}catch(C){A||c(String((C==null?void 0:C.message)||C))}})(),()=>{A=!0}},[t,e,n,h]),p.useEffect(()=>{const A=qo(t);if(!A){o(null),Ju(t)&&c(null);return}o(null),c(null),K.getChat(e,A).then(o).catch(C=>c(String(C)))},[e,t]);const w=p.useCallback(()=>{g.current=null,f(!0),x(`draft-${Date.now()}`);const A=cC(e);if(Ju(t)){window.location.pathname!==A&&window.history.replaceState(null,"",A);return}n(A)},[t,n,e]);p.useEffect(()=>{function A(C){const T=C.detail;T!=null&&T.slug&&T.slug!==e||w()}return window.addEventListener("gadjet:seller-new-chat",A),()=>window.removeEventListener("gadjet:seller-new-chat",A)},[e,w]);const _=p.useMemo(()=>
906{if(!qo(t))return"";const A=`gadjet:seed:${t}`,C=sessionStorage.getItem(A);return C&&sessionStorage.removeItem(A),C||""},[t]),k=p.useCallback(async()=>{const A=await K.createChat(e);return g.current=A.id,window.history.replaceState(null,"",`/sellers/${e}/chats/${A.id}`),window.dispatchEvent(new CustomEvent("gadjet:chat-saved",{detail:{slug:e}})),{chatId:A.id,slug:e}},[e]),j=p.useCallback(async A=>{const C=qo(t)||g.current;C&&(await K.saveChat(e,C,{messages:Hp(A)}),window.dispatchEvent(new CustomEvent("gadjet:chat-saved",{detail:{slug:e}})))},[e,t]),N=Ju(t)||!t&&u&&!l,E=!!(qo(t)&&i&&i.id===t&&!l);return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Sellers",to:"/"},{label:(r==null?void 0:r.display_name)??e,to:`/sellers/${e}`},{label:"Chat History",to:`/sellers/${e}/chats`},...Ju(t)?[{label:"New chat"}]:i?[{label:i.title}]:[]],actions:s.jsxs("button",{type:"button",onClick:w,className:"min-h-11 md:min-h-0 text-xs text-text-secondary hover:text-text-primary flex items-center gap-1 px-2.5 md:px-2 py-1 rounded-md border border-outline-subtle hover:bg-surface-subtle",children:[s.jsx(In,{className:"w-3 h-3"})," New chat"]})}),s.jsx(D3,{error:l,loading:!l&&!N&&!E}),N&&s.jsx(of,{initialMessages:[],onCreateDraft:k,extraRequestBody:()=>{const A={seller_slug:e};return g.current&&(A.chat_id=g.current),A},onConversationChange:j,welcome:({pickExample:A})=>s.jsx(Vp,{examples:b,duties:v,onPick:A}),placeholder:`Ask about ${(r==null?void 0:r.display_name)??e}â¦`},m),E&&i&&s.jsx(of,{initialMessages:Aw(i.messages),initialInput:_,autoSendInitial:_.length>0,extraRequestBody:{seller_slug:e,chat_id:t},chatId:t??null,onConversationChange:j,welcome:({pickExample:A})=>s.jsx(Vp,{examples:b,duties:v,onPick:A}),placeholder:`Ask about ${(r==null?void 0:r.display_name)??e}â¦`},t)]})}const zUe={audience:[],surface:["cli","web"],side_effects:"read_only",data_scope:"single_seller",voice:"am-internal",cost:"medium",cron_schedule:null,enabled:!0},WUe=["super_admin","am","seller_user"],KUe=["cli","web","cron","webhook"],HUe=["read_only","internal_writes","external_writes"],VUe=["single_seller","portfolio","cross_seller","repo_meta"],qUe=["am-internal","seller-facing","engineer"],GUe=["cheap","medium","expensive"];function Hk(e){return{audience:e.audience??[],surface:e.surface??["cli","web"],side_effects:e.side_effects??"read_only",data_scope:e.data_scope??"single_seller",voice:e.voice??"am-internal",cost:e.cost??"medium",cron_schedule:e.cron_schedule??null,enabled:e.enabled??!0}}function YUe(e,t){return D$(e.audience,t.audience)&&D$(e.surface,t.surface)&&e.side_effects===t.side_effects&&e.data_scope===t.data_scope&&e.voice===t.voice&&e.cost===t.cost&&(e.cron_schedule??null)===(t.cron_schedule??null)&&e.enabled===t.enabled}function D$(e,t){if(e.length!==t.length)return!1;const n=[...e].sort(),r=[...t].sort();return n.every((a,i)=>a===r[i])}const ZUe=/^[a-z0-9]([a-z0-9-]{0,48}[a-z0-9])?$/;function XUe(){const{name:e=""}=jn(),t=Rt(),n=Lt(),r=n.kind==="ready"&&n.me.role==="super_admin",[a,i]=p.useState(null),[o,l]=p.useState(null),[c,u]=p.useState(e),[d,h]=p.useState(""),[f,m]=p.useState(""),[x,g]=p.useState(zUe),[y,b]=p.useState("edit"),[v,w]=p.useState(!1),[_,k]=p.useState(null),[j,N]=p.useState(null);p.useEffect(()=>{let S=!1;return l(null),K.getSkill(e).then(O=>{S||!O||(i(O),u(O.name),h(O.description||""),m(O.body||""),g(Hk(O)))}).catch(O=>{S||l(String((O==null?void 0:O.message)||O))}),()=>{S=!0}},[e]);const E=!!a&&(c!==a.name||d!==(a.description||"")||f!==(a.body||"")||!YUe(x,Hk(a))),A=ZUe.test(c);async function C(){if(!(!a||!A)){w(!0),k(null);try{const S=await K.saveSkill(a.name,{name:c,description:d,body:f,scope:x});i(S),g(Hk(S)),N(Date.now()),S.name!==e&&t(`/skills/${S.name}`,{replace:!0})}
906catch(S){k(String((S==null?void 0:S.message)||S))}finally{w(!1)}}}async function T(){if(a&&window.confirm(`Delete skill "${a.name}"? This removes .claude/skills/${a.name}/ from disk and cannot be undone.`))try{await K.deleteSkill(a.name),t("/settings/admin/skills")}catch(S){k(String((S==null?void 0:S.message)||S))}}return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Settings",to:"/settings/admin/skills"},{label:"Skills",to:"/settings/admin/skills"},{label:(a==null?void 0:a.name)??e}],actions:r?s.jsxs(s.Fragment,{children:[j&&Date.now()-j<4e3&&s.jsxs("span",{className:"text-xs text-text-success flex items-center gap-1",children:[s.jsx(fn,{className:"w-3 h-3"})," saved"]}),s.jsxs("button",{onClick:T,className:"text-xs text-text-secondary hover:text-text-error flex items-center gap-1 px-2 py-1 rounded-md border border-outline-subtle hover:bg-surface-errorSubtle hover:border-outline-error",children:[s.jsx(us,{className:"w-3 h-3"})," Delete"]}),s.jsxs("button",{onClick:C,disabled:!E||v||!A,className:B("text-xs flex items-center gap-1 px-2.5 py-1 rounded-md font-medium",E&&A&&!v?"bg-intent-brand text-text-inverse hover:bg-intent-brandHover":"bg-surface-sunken text-text-tertiary cursor-not-allowed"),children:[s.jsx(ko,{className:"w-3 h-3"})," ",v?"Savingâ¦":"Save"]})]}):s.jsx("span",{className:"text-xs text-text-secondary",children:"Read-only"})}),s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"max-w-4xl mx-auto p-6 space-y-4",children:[s.jsxs("button",{onClick:()=>t("/settings/admin/skills"),className:"text-xs text-text-secondary hover:text-text-body flex items-center gap-1",children:[s.jsx(ff,{className:"w-3 h-3"})," All skills"]}),o&&s.jsxs(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error flex items-start gap-2",children:[s.jsx(yt,{className:"w-4 h-4 shrink-0 mt-0.5"}),s.jsx("div",{children:o})]}),_&&s.jsxs(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error flex items-start gap-2",children:[s.jsx(yt,{className:"w-4 h-4 shrink-0 mt-0.5"}),s.jsx("div",{children:_})]}),!a&&!o&&s.jsx("div",{className:"text-xs text-text-tertiary",children:"Loadingâ¦"}),a&&s.jsxs(s.Fragment,{children:[s.jsxs(V,{className:"p-5 space-y-4",children:[s.jsx(Pl,{label:"Slug",hint:r?A?`Invoked as /${c}`:"Lowercase alphanumeric with optional hyphens (regex: ^[a-z0-9](-?[a-z0-9])*$)":`Invoked as /${a.name}`,hintTone:r&&!A?"error":"muted",children:r?s.jsx(Re,{value:c,onChange:S=>u(S.target.value.trim()),inputSize:"sm",invalid:!A,className:"font-mono"}):s.jsx("div",{className:"text-sm font-mono px-3 py-1.5 rounded-md border border-outline-subtle bg-surface-subtle text-text-body",children:a.name})}),s.jsx(Pl,{label:"Description",hint:r?"Shown on the cards and used by Claude to decide when to apply this skill.":void 0,children:r?s.jsx(Ui,{value:d,onChange:S=>h(S.target.value),rows:3,className:"resize-y",placeholder:"What does this skill do, and when should the agent use it?"}):s.jsx("div",{className:"text-sm px-3 py-2 rounded-md border border-outline-subtle bg-surface-subtle text-text-body whitespace-pre-wrap min-h-[2.5rem]",children:a.description||s.jsx("span",{className:"italic text-text-tertiary",children:"No description"})})})]}),r&&s.jsx(JUe,{scope:x,onChange:g,disabled:!1}),s.jsxs(V,{children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-outline-faint px-4 py-2",children:[s.jsx("div",{className:"flex items-center gap-1",children:r?s.jsxs(Pa,{value:y,onValueChange:S=>b(S),children:[s.jsxs(Ln,{value:"edit",children:[s.jsx(Qi,{className:"w-3 h-3"}),"Edit"]}),s.jsxs(Ln,{value:"preview",children:[s.jsx(al,{className:"w-3 h-3"}),"Preview"]})]}):s.jsxs("div",{className:"px-3 py-1.5 text-xs font-medium text-text-body flex items-center gap-1.5",children:[s.jsx(al,{className:"w-3 h-3"})," Preview"]})}),s.jsxs("div",{className:"text-body-xs text-text-tertiary",children:["Updated ",cn(a.updated_at)," ·"," ",(a.bytes/1024).toFixed(1),"kb"]})]}),r&&y==="edit"?s.jsx("textarea",{value:f,onChange:S=>m(S.target.value),spellCheck:!1,className:"w-full font-mono text-body-md leading-relaxed px-4 py-4 bg-surface focus:outline-none resize-none rounded-b-lg",style:{minHeight:480}}):s.jsx("div",{className:"px-6 py-5 prose",children:s.jsx(mx,{remarkPlugins:[px],rehypePlugins:[m3],children:f})})]}),r&&s.jsx("div",{className:"text-body-xs text-text-tertiary text-center",children:s.jsxs("code",{className:"font-mono",children:[".claude/skills/",a.name,"/SKILL.md"]})})]})]})})]})}function Pl({label:e,hint:t,hintTone:n="muted",children:r}){return s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs font-medium uppercase tracking-wider text-text-secondary mb-1.5",children:e}),r,t&&s.jsx("div",{className:B("mt-1 text-body-xs",n==="error"?"text-text-error":"text-text-secondary"),children:t})]})}function JUe({scope:e,onChange:t,disabled:n}){const r=(i,o)=>t({...e,[i]:o}),a=(i,o)=>i.includes(o)?i.filter(l=>l!==o):[...i,o];return s.jsxs(V,{className:"p-5 space-y-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Scope"}),s.jsxs("p",{className:"mt-0.5 text-body-xs text-text-secondary",children:["Controls who sees this skill, where it runs, and how risky it is.",n&&" Read-only â only super admins can edit scope."]})]}),s.jsx(Pl,{label:"Audience",hint:"Extra roles beyond super_admin who can see this skill. Empty = super_admin only.",children:s.jsx(M$,{options:WUe,values:e.audience,disabled:n,onToggle:i=>r("audience",a(e.audience,i))})}),s.jsx(Pl,{label:"Surface",hint:"Where this skill is exposed. 'web' must be set for the in-app picker.",children:s.jsx(M$,{options:KUe,values:e.surface,disabled:n,onToggle:i=>r("surface",a(e.surface,i))})}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsx(Pl,{label:"Side effects",hint:"read_only is safe. external_writes pins audie
906nce to super_admin only.",children:s.jsx(ey,{value:e.side_effects,options:HUe,disabled:n,onChange:i=>r("side_effects",i)})}),s.jsx(Pl,{label:"Data scope",hint:"single_seller is the default for reports.",children:s.jsx(ey,{value:e.data_scope,options:VUe,disabled:n,onChange:i=>r("data_scope",i)})}),s.jsx(Pl,{label:"Voice",hint:"seller-facing requires audience to include seller_user.",children:s.jsx(ey,{value:e.voice,options:qUe,disabled:n,onChange:i=>r("voice",i)})}),s.jsx(Pl,{label:"Cost",hint:"Hint to users about how heavy a run is.",children:s.jsx(ey,{value:e.cost,options:GUe,disabled:n,onChange:i=>r("cost",i)})})]}),s.jsx(Pl,{label:"Cron schedule",hint:"5-field cron (UTC). Empty = not scheduled. Requires 'cron' in Surface.",children:s.jsx(Re,{value:e.cron_schedule??"",onChange:i=>r("cron_schedule",i.target.value.trim()===""?null:i.target.value),placeholder:"e.g. 0 7 * * 1",disabled:n,inputSize:"sm",className:"font-mono"})}),s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx(ei,{id:"skill-enabled",checked:e.enabled,disabled:n,onCheckedChange:i=>r("enabled",i===!0)}),s.jsx("label",{htmlFor:"skill-enabled",className:"text-xs text-text-body cursor-pointer",children:"Enabled â appears in pickers and the cron tick."})]})]})}function M$({options:e,values:t,disabled:n,onToggle:r}){return s.jsx("div",{className:"flex flex-wrap gap-1.5",children:e.map(a=>{const i=t.includes(a);return s.jsx("button",{type:"button",disabled:n,onClick:()=>r(a),className:B("text-body-xs font-mono px-2 py-1 rounded-md border transition",i?"bg-surface-brandSubtle border-brand-300 text-text-brand":"bg-surface border-outline-subtle text-text-secondary hover:border-outline",n&&"opacity-60 cursor-not-allowed hover:border-outline-subtle"),children:a},a)})})}function ey({value:e,options:t,disabled:n,onChange:r}){return s.jsx("select",{value:e,disabled:n,onChange:a=>r(a.target.value),className:B("w-full text-sm font-mono px-3 py-1.5 rounded-md border bg-surface focus:outline-none focus-visible:shadow-focus","border-outline-subtle focus:border-outline-brand",n&&"bg-surface-subtle text-text-secondary cursor-not-allowed"),children:t.map(a=>s.jsx("option",{value:a,children:a},a))})}function QUe(){const[e,t]=p.useState([]);return p.useEffect(()=>{let n=!0;return K.sellers().then(r=>{n&&t(r.filter(a=>!a.status||a.status==="active").map(a=>a.slug).sort())}).catch(()=>{}),()=>{n=!1}},[]),e}function Cq(e){const t=e.trim().split(/\s+/);if(t.length!==5)return e;const[n,r,a,i,o]=t;return a==="*"&&i==="*"&&o==="*"&&/^\d+$/.test(n)&&/^\d+$/.test(r)?`Daily ${r.padStart(2,"0")}:${n.padStart(2,"0")} UTC`:a==="*"&&i==="*"&&/^\d+$/.test(o)&&/^\d+$/.test(n)&&/^\d+$/.test(r)?`Weekly ${["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][Number(o)]} ${r.padStart(2,"0")}:${n.padStart(2,"0")} UTC`:n.startsWith("*/")&&r==="*"&&a==="*"&&i==="*"&&o==="*"?`Every ${n.slice(2)} min`:e}const eze=[{key:"name",label:"Name",sortable:!0,sticky:!0,getValue:e=>e.name},{key:"kind",label:"Type",sortable:!0,getValue:e=>e.kind},{key:"schedule",label:"Schedule",sortable:!0,getValue:e=>e.cron_schedule},{key:"lastrun",label:"Last run",sortable:!0,getValue:e=>{var t;return((t=e.last_run)==null?void 0:t.started_at)??null}},{key:"status",label:"Status",sortable:!0,getValue:e=>e.enabled?1:0},{key:"actions",label:"Actions",align:"right"}],tze=[{key:"started",label:"Started",getValue:e=>e.started_at,render:e=>s.jsxs("span",{className:"font-mono",children:[new Date(e.started_at).toISOString().slice(0,16).replace("T"," "),"Z"]})},{key:"seller",label:"Seller",getValue:e=>e.slug,render:e=>e.slug||"â"},{key:"duration",label:"Duration",getValue:e=>e.finished_at&&e.started_at?Math.round((new Date(e.finished_at).getTime()-new Date(e.started_at).getTime())/1e3):null,render:e=>e.finished_at&&e.started_at?`${Math.round((new Date(e.finished_at).getTime()-new Date(e.started_at).getTime())/1e3)}s`:"â"},{key:"status",label:"Status",getValue:e=>e.ok===!0?1:e.ok===!1?0:-1,render:e=>e.ok===!0?s.jsx("span",{className:"text-text-success",children:"ok"}):e.ok===!1?s.jsx("span",{className:"text-text-error",children:"error"}):s.jsx("span",{className:"text-text-tertiary",children:"in-flight"})},{key:"error",label:"Error",render:e=>s.jsx("span",{className:"text-text-error line-clamp-1 max-w-md",children:e.error||""})}];function nze(e){if(!e)return"never";const t=new Date(e).getTime(),n=Date.now()-t,r=Math.floor(n/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const a=Math.floor(r/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Eq({embedded:e=!1}={}){const t=Lt(),n=Rt(),[r,a]=p.useState([]),[i,o]=p.useState(!0),[l,c]=p.useState(null),[u,d]=p.useState(null),[h,f]=p.useState(null),[m,x]=p.useState("all"),g=p.useMemo(()=>{const v=r.filter(w=>w.enabled).length;return{all:r.length,active:v,paused:r.length-v}},[r]),y=p.useMemo(()=>m==="active"?r.filter(v=>v.enabled):m==="paused"?r.filter(v=>!v.enabled):r,[r,m]);p.useEffect(()=>{e||t.kind==="ready"&&t.me.role!=="super_admin"&&n("/",{replace:!0})},[t,n,e]);const b=p.useCallback(async()=>{o(!0),c(null);try{const v=await K.listScheduledTasks();a(v.scheduled_tasks)}catch(v){const w=v;c((w==null?void 0:w.message)||"Failed to load scheduled tasks.")}finally{o(!1)}},[]);return p.useEffect(()=>{b()},[b]),!e&&t.kind==="ready"&&t.me.role!=="super_admin"?null:s.jsxs(s.Fragment,{children:[!e&&s.jsx(Pt,{crumbs:[{label:"Scheduled tasks"}],actions:s.jsxs(W,{type:"button",onClick:b,intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(vi,{className:"h-3.5 w-3.5"})," Refresh"]})}),s.jsx("div",{className:e?"space-y-4":"flex-1 overflow-y-auto p-6 space-y-4",children:s.jsxs(V,{children:[s.jsx("div",{className:"border-b border-outline-subtle p-4",children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{children:[s.jsxs("h2",{className:"text-sm font-semibold text-text-primary",children:[r.length," scheduled task",r.length===1?"":"s"]}),s.jsx("p",{className:"mt-1 text-xs text-text-secondary",children:"Cron-driven work â both LLM skills and system captures. Edit schedule, pause, or trigger an out-of-schedule run. Times are always UTC."})]}),s.jsx(sze,{value:m,onChange:x,counts:g})]})}),i&&s.jsx("div",{className:"p-6 text-sm text-text-secondary",children:"Loadingâ¦"}),l&&s.jsxs("div",{className:"m-4 flex items-start gap-2 rounded-md border border-outline-error bg-surface-errorSubtle p-3 text-sm text-text-error",children:[s.jsx(yt,{className:"h-4 w-4 flex-shrink-0"}),s.jsx("span",{children:l})]}),!i&&!l&&r.length===0&&s.jsx("div",{className:"p-6 text-sm text-text-secondary",children:"No scheduled tasks."}),!i&&!l&&r.length>0&&y.length===0&&s.jsxs("div",{className:"p-6 text-sm text-text-secondary",children:["No ",m==="active"?"active":"paused"," tasks."]}),!i&&!l&&y.length>0&&s.jsx(dt,{rows:y,columns:eze,getRowKey:v=>v.name,empty:{title:"No scheduled tasks."},renderRow:v=>s.jsx(rze,{task:v,expanded:u===v.name,onToggleExpand:()=>d(u===v.name?null:v.name),onEdit:()=>f(v),onChanged:b})})]})}),h&&s.jsx(cze,{task:h,onClose:()=>f(null),onSaved:()=>{f(null),b()}})]})}function rze({task:e,expanded:t,onToggleExpand:n,onEdit:r,onChanged:a}){var u,d;const[i,o]=p.useState(!1),l=async()=>{o(!0);try{await K.updateScheduledTask(e.name,{enabled:!e.enabled}),a(),Ae("success",e.enabled?"Task paused":"Task resumed")}catch(h){const f=h;Ae("error","Failed to toggle task",{description:(f==null?void 0:f.message)||"unknown error"})}finally{o(!1)}},c=((u=e.last_run)==null?void 0:u.ok)===!0?"ok":((d=e.last_run)==null?void 0:d.ok)===!1?"error":e.last_run?"running":"never";return s.jsxs(s.Fragment,{children:[s.jsxs("tr",{className:"border-t border-outline-faint bg-surface hover:bg-surface-subtle/50 cursor-pointer",onClick:n,children:[s.jsx("td",{className:"sticky left-0 z-sticky bg-inherit px-4 py-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"mt-0.5 text-text-tertiary shrink-0",children:t?s.jsx(Pn,{className:"h-4 w-4"}):s.jsx(fr,{className:"h-4 w-4"})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"font-medium text-text-primary",children:e.name}),e.description&&s.jsx("div",{className:"mt-0.5 text-xs text-text-secondary line-clamp-1",children:e.description})]})]})}),s.jsx("td",{className:"px-4 py-3",children:s.jsx(aze,{kind:e.kind})}),s.jsxs("td",{className:"px-4 py-3 text-text-body",children:[s.jsx("div",{className:"font-mono text-xs",children:e.cron_schedule}),s.jsx("div",{className:"mt-0.5 text-xs text-text-secondary",children:Cq(e.cron_schedule)})]}),s.jsx("td",{className:"px-4 py-3 text-text-body",children:e.last_run?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-xs",children:nze(e.last_run.started_at)}),e.last_run.slug&&s.jsx("div",{className:"text-xs text-text-secondary",children:e.last_run.slug})]}):s.jsx("span",{className:"text-xs text-text-tertiary",children:"never"})}),s.jsx("td",{className:"px-4 py-3",children:s.jsx(ize,{enabled:e.enabled,lastRunOk:c})}),s.jsx("td",{className:"px-4 py-3",onClick:h=>h.stopPropagation(),children:s.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[s.jsx(oze,{task:e,onDone:a}),s.jsxs(W,{type:"button",onClick:r,intent:"neutral",variant:"outline",size:"sm",title:"Edit schedule",children:[s.jsx(Qi,{className:"h-3 w-3"})," Edit"]}),s.jsx("button",{type:"button",onClick:l,disabled:i,className:e.enabled?"inline-flex items-center gap-1 rounded-md border border-outline-warning bg-surface-warningSubtle px-2 py-1 text-xs font-medium text-text-warning disabled:opacity-50":"inline-flex items-center gap-1 rounded-md border border-success-300 bg-surface-successSubtle px-2 py-1 text-xs font-medium text-text-success disabled:opacity-50",title:e.enabled?"Pause":"Resume",children:e.enabled?s.jsxs(s.Fragment,{children:[s.jsx(K2,{className:"h-3 w-3"})," Pause"]}):s.jsxs(s.Fragment,{children:[s.jsx(bd,{className:"h-3 w-3"})," Resume"]})}),e.kind==="skill"&&s.jsx(st,{to:`/skills/${encodeURIComponent(e.name)}
906`,className:"inline-flex items-center gap-1 rounded-md border border-outline bg-surface px-2 py-1 text-xs font-medium text-text-body hover:bg-surface-subtle",title:"Open full skill editor",onClick:h=>h.stopPropagation(),children:s.jsx(Qt,{className:"h-3 w-3"})})]})})]}),t&&s.jsx("tr",{className:"bg-surface-subtle/50",children:s.jsx("td",{colSpan:6,className:"px-4 py-3",children:s.jsx(lze,{name:e.name})})})]})}function sze({value:e,onChange:t,counts:n}){const r=[{key:"all",label:"All",count:n.all},{key:"active",label:"Active",count:n.active},{key:"paused",label:"Paused",count:n.paused}];return s.jsx(Pa,{value:e,onValueChange:a=>t(a),"aria-label":"Filter tasks by status",children:r.map(a=>{const i=a.key===e;return s.jsxs(Ln,{value:a.key,children:[s.jsx("span",{children:a.label}),s.jsx("span",{className:B("rounded px-1 text-body-xs tabular-nums",i?"bg-surface/20 text-text-inverse":"bg-surface-sunken text-text-secondary"),children:a.count})]},a.key)})})}function aze({kind:e}){return s.jsx(_n,{category:e==="system"?6:1,className:"capitalize",children:e})}function ize({enabled:e,lastRunOk:t}){return e?t==="error"?s.jsxs(_n,{tone:"error",children:[s.jsx(Q6,{className:"h-3 w-3"})," last failed"]}):t==="ok"?s.jsxs(_n,{tone:"success",children:[s.jsx(Xt,{className:"h-3 w-3"})," running"]}):t==="running"?s.jsxs(_n,{tone:"info",dot:!0,children:[s.jsx(pu,{className:"h-3 w-3"})," in-flight"]}):s.jsx(_n,{tone:"neutral",children:"idle"}):s.jsxs(_n,{tone:"warning",children:[s.jsx(K2,{className:"h-3 w-3"})," paused"]})}function oze({task:e,onDone:t}){const n=QUe(),[r,a]=p.useState(!1),[i,o]=p.useState(""),[l,c]=p.useState(!1),u=e.data_scope==="single_seller",d=async h=>{c(!0);try{const f=await K.runScheduledTaskNow(e.name,h);f.ok?Ae("success","Task triggered"):Ae("error","Run failed",{description:f.error||"unknown error"}),t()}catch(f){const m=f;Ae("error","Run failed",{description:(m==null?void 0:m.message)||"unknown error"})}finally{c(!1),a(!1)}};return u?s.jsx("span",{onClick:h=>h.stopPropagation(),children:s.jsxs(zC,{open:r,onOpenChange:a,children:[s.jsx(WC,{asChild:!0,children:s.jsxs("button",{type:"button",disabled:l,className:"inline-flex items-center gap-1 rounded-md border border-outline bg-surface px-2 py-1 text-xs font-medium text-text-body hover:bg-surface-subtle disabled:opacity-50",title:"Run now for one seller",children:[s.jsx(bd,{className:"h-3 w-3"})," ",l?"Runningâ¦":"Run now"]})}),s.jsxs(b0,{align:"end",className:"w-56 p-0",children:[s.jsx("div",{className:"border-b border-outline-faint px-3 py-2 text-xs font-medium text-text-body",children:"Pick a seller"}),s.jsxs("div",{className:"max-h-72 overflow-y-auto py-1",children:[n.map(h=>s.jsx("button",{type:"button",onClick:()=>{o(h),d(h)},className:"w-full px-3 py-1.5 text-left text-xs text-text-body hover:bg-surface-subtle",children:h},h)),n.length===0&&s.jsx("div",{className:"px-3 py-2 text-xs text-text-tertiary",children:"Loading sellersâ¦"})]})]})]})}):s.jsxs("button",{type:"button",onClick:h=>{h.stopPropagation(),d(null)},disabled:l,className:"inline-flex items-center gap-1 rounded-md border border-outline bg-surface px-2 py-1 text-xs font-medium text-text-body hover:bg-surface-subtle disabled:opacity-50",title:"Run now (out-of-schedule)",children:[s.jsx(bd,{className:"h-3 w-3"})," ",l?"Runningâ¦":"Run now"]})}function lze({name:e}){const[t,n]=p.useState([]),[r,a]=p.useState(!0),[i,o]=p.useState(null);return p.useEffect(()=>{let l=!0;return a(!0),o(null),K.listScheduledTaskRuns(e,10).then(c=>{l&&n(c.runs)}).catch(c=>{l&&o((c==null?void 0:c.message)||"Failed to load runs.")}).finally(()=>{l&&a(!1)}),()=>{l=!1}},[e]),r?s.jsx("div",{className:"text-xs text-text-secondary",children:"Loading runsâ¦"}):i?s.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-error",children:[s.jsx(zn,{className:"h-3 w-3"})," ",i]}):t.length===0?s.jsx("div",{className:"text-xs text-text-secondary",children:"No runs yet."}):s.jsxs("div",{children:[s.jsxs("div",{className:"mb-2 text-xs font-medium text-text-body",children:["Last ",t.length," run",t.length===1?"":"s"]}),s.jsx(dt,{rows:t,columns:tze,getRowKey:l=>l.id,paginate:!1,persist:!1,tableClassName:"text-xs",empty:{title:"No runs yet."}})]})}function cze({task:e,onClose:t,onSaved:n}){const[r,a]=p.useState(e.cron_schedule),[i,o]=p.useState(!1),[l,c]=p.useState(null),u=p.useMemo(()=>
906[{label:"Daily 03:00 UTC",value:"0 3 * * *"},{label:"Daily 06:00 UTC",value:"0 6 * * *"},{label:"Hourly",value:"0 * * * *"},{label:"Every 30 min",value:"*/30 * * * *"},{label:"Weekly Mon 07:00 UTC",value:"0 7 * * 1"}],[]),d=async()=>{o(!0),c(null);try{await K.updateScheduledTask(e.name,{cron_schedule:r.trim()}),n()}catch(h){c((h==null?void 0:h.message)||"Failed to save")}finally{o(!1)}};return s.jsx(js,{open:!0,onOpenChange:h=>{h||t()},children:s.jsxs(Ns,{size:"lg",className:"p-5",children:[s.jsxs(ma,{className:"text-sm",children:["Edit schedule â ",s.jsx("span",{className:"font-mono",children:e.name})]}),s.jsx(hc,{className:"mt-1 text-xs",children:"Standard 5-field cron expression (UTC). Use the presets or write your own. To pause the task instead, close this and use the Pause button."}),s.jsxs("div",{className:"mt-4",children:[s.jsx("label",{className:"text-xs font-medium text-text-body",children:"Cron expression"}),s.jsx(Re,{type:"text",value:r,onChange:h=>a(h.target.value),inputSize:"sm",placeholder:"0 3 * * *",className:"mt-1 font-mono"}),s.jsx("div",{className:"mt-1 text-xs text-text-secondary",children:Cq(r.trim())})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-xs font-medium text-text-body",children:"Presets"}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:u.map(h=>s.jsx("button",{type:"button",onClick:()=>a(h.value),className:"rounded-md border border-outline-subtle bg-surface-subtle px-2 py-1 text-xs text-text-body hover:bg-surface-sunken",children:h.label},h.value))})]}),l&&s.jsxs("div",{className:"mt-3 flex items-start gap-1.5 rounded-md border border-outline-error bg-surface-errorSubtle p-2 text-xs text-text-error",children:[s.jsx(yt,{className:"h-3.5 w-3.5 flex-shrink-0"})," ",l]}),s.jsxs("div",{className:"mt-5 flex items-center justify-end gap-2",children:[s.jsx(W,{type:"button",onClick:t,intent:"neutral",variant:"outline",size:"sm",children:"Cancel"}),s.jsx(W,{type:"button",onClick:d,disabled:i||r.trim()==="",intent:"brand",size:"sm",children:i?"Savingâ¦":"Save"})]})]})})}const cu={not_started:"Not started",scheduled:"Scheduled",in_progress:"In progress",monitoring_testing:"Monitoring",waiting_for_signoff:"Waiting on client",done:"Done",customer_completed:"Customer did it",customer_not_required:"Not required",cancelled:"Cancelled"},Aq={not_started:"neutral",scheduled:"info",in_progress:"info",monitoring_testing:"info",waiting_for_signoff:"warning",done:"success",customer_completed:"success",customer_not_required:"neutral",cancelled:"neutral"},M3={not_started:zo({tone:"neutral",variant:"subtle"}),scheduled:zo({tone:"info",variant:"subtle"}),in_progress:zo({tone:"info",variant:"subtle"}),monitoring_testing:zo({tone:"info",variant:"subtle"}),waiting_for_signoff:zo({tone:"warning",variant:"subtle"}),done:zo({tone:"success",variant:"subtle"}),customer_completed:zo({tone:"success",variant:"subtle"}),customer_not_required:zo({tone:"neutral",variant:"subtle"}),cancelled:zo({tone:"neutral",variant:"subtle"})},uze={high:"text-intent-error",medium:"text-warning-500",low:"text-text-tertiary"},dze=["done","customer_completed","customer_not_required","cancelled"],hze=["not_started","scheduled","in_progress","monitoring_testing","waiting_for_signoff"],fze=["replenishment","promotion","listing_creation","listing_upgrade","dc_allocation","stock_recon","overview_report"];function qS(e){return dze.includes(e)}function mze(e){const t=e.replace(/_/g," ");return t.charAt(0).toUpperCase()+t.slice(1)}function $$(e){if(!e)return{text:"â",tone:"neutral"};const t=new Date;t.setHours(0,0,0,0);const n=new Date(`${e}T00:00:00`),r=Math.round((n.getTime()-t.getTime())/864e5);return r<0?{text:`${Math.abs(r)}d overdue`,tone:"overdue"}:r===0?{text:"Today",tone:"soon"}:r===1?{text:"Tomorrow",tone:"soon"}:r<7?{text:`In ${r}d`,tone:"soon"}:r<31?{text:`In ${r}d`,tone:"neutral"}:{text:e,tone:"neutral"}}function pze(e){const t=[];let n=0;for(;n<e.length;){const r=e[n];if(fze.includes(r.type)){let a=n+1;for(;a<e.length&&e[a].type===r.type;)a++;const i=e.slice(n,a);i.length>=2?t.push({kind:"group",key:`${r.type}:${r.id}`,type:r.type,tasks:i}):t.push({kind:"task",task:r}),n=a}else t.push({kind:"task",task:r}),n++}return t}const xze=new Set;function Vk({checked:e,indeterminate:t=!1,onChange:n,title:r}){return s.jsx("input",{type:"checkbox",checked:e,title:r,ref:a=>{a&&(a.indeterminate=t&&!e)},onChange:n,onClick:a=>a.stopPropagation(),className:"h-4 w-4 cursor-pointer rounded border-outline accent-brand-600"})}function gze({tasks:e,loading:t,error:n,selectedId:r,onSelect:a,onQuickStatus:i,hideSellerColumn:o,sellerDisplay:l,selectable:c,selectedIds:u,onToggleSelect:d,onToggleSelectMany:h}){const f=p.useMemo(()=>pze(e),[e]),[m,x]=p.useState(new Set),g=!!(c&&u&&d&&h),y=u??xze,v=(o?4:5)+(g?1:0),w=p.useMemo(()=>e.map(A=>A.id),[e]),_=w.length>0&&w.every(A=>y.has(A)),k=w.some(A=>y.has(A)),j=p.useMemo(()=>{const A=[];return g&&A.push({key:"select",label:"",className:"w-8",header:s.jsx(Vk,{checked:_,indeterminate:k&&!_,onChange:()=>h(w,!_),title:_?"Clear selection":"Select all"})}),A.push({key:"priority",label:"",className:"w-8"},{key:"title",label:"Title"},{key:"status",label:"Status",className:"w-36"}),o||A.push({key:"seller",label:"Seller",className:"w-40"}),A.push({key:"due",label:"Due",className:"w-24"}),A},[g,_,k,w,o,h]);function N(A){x(C=>{const T=new Set(C);return T.has(A)?T.delete(A):T.add(A),T})}if(n)return s.jsxs("div",{className:"m-4 flex items-start gap-2 rounded-md border border-outline-error bg-surface-errorSubtle p-3 text-sm text-text-error",children:[s.jsx(yt,{className:"h-4 w-4 mt-0.5 shrink-0"}),s.jsx("div",{children:n})]});if(t&&e.length===0)return s.jsx("div",{className:"p-8 text-center text-sm text-text-secondary",children:"Loading tasksâ¦"});if(e.length===0)return s.jsxs("div",{className:"p-12 text-center",children:[s.jsx(D2,{className:"mx-auto h-8 w-8 text-text-tertiary"}),s.jsx("div",{className:"mt-2 text-sm text-text-secondary",children:"No tasks match this view."})]});function E(A,C=!1){const T=r===A.id,S=y.has(A.id),O=qS(A.status),R=O?{text:A.due_date??"â",tone:"neutral"}:$$(A.due_date);return s.jsxs("tr",{onClick:()=>a(A),className:B("border-t border-outline-faint cursor-pointer",S?"bg-surface-brandSubtle/60":T?"bg-surface-infoSubtle/60":"hover:bg-surface-subtle/60"),children:[g&&s.jsx("td",{className:"px-3 py-2 align-top",children:s.jsx(Vk,{checked:S,onChange:()=>d(A.id),title:"Select task"})}
906),s.jsx("td",{className:"px-3 py-2 align-top",title:`Priority: ${A.priority}`,children:s.jsx(one,{className:B("h-6 w-6 -mx-1.5",uze[A.priority])})}),s.jsxs("td",{className:B("px-3 py-2 align-top",C&&"pl-8"),children:[s.jsx("div",{className:B("font-medium",O?"text-text-secondary line-through":"text-text-primary"),children:A.title}),A.type&&A.type!=="other"&&s.jsx("div",{className:"text-body-xs text-text-secondary mt-0.5 capitalize",children:A.type.replace(/_/g," ")})]}),s.jsx("td",{className:"px-3 py-2 align-top",children:s.jsx(yze,{task:A,onQuickStatus:i,onSelect:a})}),!o&&s.jsx("td",{className:"px-3 py-2 align-top text-text-body",children:A.seller_slug?(l==null?void 0:l[A.seller_slug])??A.seller_slug:s.jsx("span",{className:"text-text-tertiary",children:"â internal"})}),s.jsx("td",{className:B("px-3 py-2 align-top whitespace-nowrap",R.tone==="overdue"&&"text-text-error font-medium",R.tone==="soon"&&"text-text-warning",R.tone==="neutral"&&"text-text-secondary"),children:s.jsxs("span",{className:"inline-flex items-center gap-1",children:[R.tone==="overdue"?s.jsx(yt,{className:"h-3.5 w-3.5"}):A.due_date?s.jsx(Qp,{className:"h-3.5 w-3.5"}):null,R.text]})})]},A.id)}return s.jsx(dt,{rows:f,columns:j,getRowKey:A=>A.kind==="task"?A.task.id:A.key,persist:!1,paginate:!1,renderRow:A=>{if(A.kind==="task")return E(A.task);const C=m.has(A.key),T=A.tasks.filter(I=>!qS(I.status)&&$$(I.due_date).tone==="overdue").length,S=A.tasks.map(I=>I.id),O=S.every(I=>y.has(I)),R=S.some(I=>y.has(I));return s.jsxs(s.Fragment,{children:[s.jsxs("tr",{onClick:()=>N(A.key),className:"border-t border-outline-faint cursor-pointer bg-surface-subtle/40 hover:bg-surface-subtle/70",children:[g&&s.jsx("td",{className:"px-3 py-2",children:s.jsx(Vk,{checked:O,indeterminate:R&&!O,onChange:()=>h(S,!O),title:"Select group"})}),s.jsx("td",{className:"px-3 py-2 text-text-secondary",children:C?s.jsx(Pn,{className:"h-4 w-4"}):s.jsx(fr,{className:"h-4 w-4"})}),s.jsxs("td",{colSpan:v-(g?2:1),className:"px-3 py-2",children:[s.jsx("span",{className:"font-medium text-text-primary",children:mze(A.type)}),s.jsxs("span",{className:"text-text-secondary",children:[" · ",A.tasks.length," task",A.tasks.length===1?"":"s"]}),T>0&&s.jsxs("span",{className:"ml-2 inline-flex items-center gap-1 text-text-error font-medium",children:[s.jsx(yt,{className:"h-3.5 w-3.5"}),T," overdue"]})]})]}),C&&A.tasks.map(I=>E(I,!0))]})}})}function yze({task:e,onQuickStatus:t,onSelect:n}){return qS(e.status)||!t?s.jsx(_n,{tone:Aq[e.status],children:cu[e.status]}):s.jsxs("select",{value:e.status,onClick:r=>r.stopPropagation(),onChange:r=>{r.stopPropagation();const a=r.target.value;if(a==="__complete__"){n(e);return}t(e,a)},className:B("cursor-pointer focus:outline-none focus-visible:shadow-focus",M3[e.status]),title:"Change status",children:[hze.map(r=>s.jsx("option",{value:r,children:cu[r]},r)),s.jsx("option",{value:"__complete__",children:"Complete / closeâ¦"})]})}const ql={dot:"bg-outline-strong",text:"text-text-secondary",fill:"bg-outline-strong",tint:"bg-surface-sunken"},Fi={info:{dot:"bg-info-500",text:"text-text-info",fill:"bg-info-500",tint:"bg-surface-infoSubtle"},warning:{dot:"bg-warning-500",text:"text-text-warning",fill:"bg-warning-500",tint:"bg-surface-warningSubtle"},success:{dot:"bg-success-500",text:"text-text-success",fill:"bg-success-500",tint:"bg-surface-successSubtle"},error:{dot:"bg-error-500",text:"text-text-error",fill:"bg-error-500",tint:"bg-surface-errorSubtle"}};function Di(e){const t=Ve[e];return{dot:t.dot,text:t.text,fill:t.fill,tint:t.tint}}function Ly(e){return Di(mB(e))}const bze=["from-category-1 to-category-1-700","from-category-2 to-category-2-700","from-category-3 to-category-3-700","from-category-4 to-category-4-700","from-category-5 to-category-5-700","from-category-6 to-category-6-700"],vze={fire:"ð¥ Fire",replenishment:"Replenishment",promotion:"Promotion",listing_creation:"New listing",listing_upgrade:"Listing upgrade",dc_allocation:"DC allocation",stock_recon:"Stock recon",overview_report:"Morning Overview",customer_communication:"Customer comm",pricing_experiment:"Price experiment",billing:"Billing",bug:"Bug",feature:"Feature",meeting:"Meeting",reminder:"Reminder",internal:"Internal",management:"Management",other:"Other"},wze=[{key:"overview_report",name:"Morning Overview",accent:Di(3),types:["overview_report"]},{key:"promotion",name:"Promotions",accent:Di(1),types:["promotion"]},{key:"pricing_experiment",name:"Price experiments",accent:Di(1),types:["pricing_experiment"]},{key:"replenishment",name:"Replenishment",accent:Di(2),types:["replenishment"]},{key:"listing_upgrade",name:"Listing Upgrades",accent:Di(3),types:["listing_upgrade"]},{key:"listing_creation",name:"Listing Creations",accent:Di(4),t
906ypes:["listing_creation"]},{key:"ticket",name:"Ticket Centre",accent:Di(5),types:["customer_communication"]},{key:"dc_allocation",name:"DC Allocation",accent:Di(6),types:["dc_allocation"]},{key:"stock_recon",name:"Stock Recon",accent:Di(4),types:["stock_recon"]},{key:"billing",name:"Billing",accent:Di(5),types:["billing"]},{key:"internal",name:"Internal & Other",accent:ql,types:["fire","bug","feature","meeting","reminder","internal","management","other"]}],_ze=["not_started","scheduled","in_progress","monitoring_testing","waiting_for_signoff","done","customer_completed","customer_not_required","cancelled"],kze={not_started:ql,scheduled:Fi.info,in_progress:Fi.info,monitoring_testing:Fi.info,waiting_for_signoff:Fi.warning,done:Fi.success,customer_completed:Fi.success,customer_not_required:ql,cancelled:ql},jze=["high","medium","low"],Nze={high:Fi.error,medium:Fi.warning,low:ql},Sze={high:"text-error-500",medium:"text-warning-500",low:"text-text-tertiary"},Cze=["not_started","scheduled","in_progress","monitoring_testing","waiting_for_signoff"],Tq=["done","customer_completed","customer_not_required"],Eze=[...Tq,"cancelled"];function $l(e){return Eze.includes(e)}function Aze(e){return Tq.includes(e)}function Oq(e,t){if(!e)return{text:"â",tone:"neutral",icon:"none"};if(t)return{text:e,tone:"neutral",icon:"check"};const n=new Date;n.setHours(0,0,0,0);const r=new Date(`${e}T00:00:00`),a=Math.round((r.getTime()-n.getTime())/864e5);return a<0?{text:`${Math.abs(a)}d overdue`,tone:"overdue",icon:"alert"}:a===0?{text:"Today",tone:"soon",icon:"clock"}:a===1?{text:"Tomorrow",tone:"soon",icon:"clock"}:a<7?{text:`In ${a}d`,tone:"soon",icon:"clock"}:a<31?{text:`In ${a}d`,tone:"neutral",icon:"clock"}:{text:e,tone:"neutral",icon:"clock"}}function Iq(e){return Oq(e.due_date,$l(e.status)).tone==="overdue"}function Tze({tasks:e,groupBy:t,density:n,loading:r,error:a,selectedId:i,onSelect:o,onQuickStatus:l,selectable:c,selectedIds:u,onToggleSelect:d,onToggleSelectMany:h,sellerDisplay:f,assigneeDisplay:m,dateMode:x="due",emptyMessage:g}){const y=!!(c&&u&&d&&h),b=u??Oze,[v,w]=p.useState(new Set);p.useEffect(()=>{w(new Set)},[t]);const _=p.useMemo(()=>Rze(e,t,f,m),[e,t,f,m]);function k(A){w(C=>{const T=new Set(C);return T.has(A)?T.delete(A):T.add(A),T})}if(a)return s.jsxs("div",{className:"m-4 flex items-start gap-2 rounded-md border border-outline-error bg-surface-errorSubtle p-3 text-sm text-text-error",children:[s.jsx(yt,{className:"h-4 w-4 mt-0.5 shrink-0"}),s.jsx("div",{children:a})]});if(r&&e.length===0)return s.jsx("div",{className:"p-8 text-center text-sm text-text-secondary",children:"Loading tasksâ¦"});if(_.length===0)return s.jsxs("div",{className:"p-12 text-center",children:[s.jsx(D2,{className:"mx-auto h-8 w-8 text-text-tertiary"}),s.jsx("div",{className:"mt-2 text-sm text-text-secondary",children:g??"No tasks match this view."})]});const j=n==="compact"?"px-4 py-1.5":"px-4 py-2.5",N=n==="compact"?"h-5 w-5 text-[9px]":"h-6 w-6 text-[10px]";function E(A){const C=$l(A.status),T=b.has(A.id),S=i===A.id,O=x==="completed"?Dze(A.completed_at):Oq(A.due_date,C),R=x==="completed"?A.completed_by_user_id:A.assignee_user_id;let I=null;if(t!=="seller")if(A.seller_slug){const P=Ly(A.seller_slug);I=s.jsxs("span",{className:B("inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-body-xs font-medium",P.tint,P.text),children:[s.jsx("span",{className:B("h-1.5 w-1.5 rounded-full",P.dot)}),(f==null?void 0:f[A.seller_slug])??A.seller_slug]})}else I=s.jsx("span",{className:"text-body-xs font-medium text-text-tertiary",children:"â internal"});const $=Pze(R,m,N);return s.jsxs("div",{onClick:()=>o(A),className:B("group/row relative flex items-center gap-3 border-t border-outline-faint cursor-pointer transition-colors",j,T?"bg-surface-brandSubtle/60":S?"bg-surface-infoSubtle/50":"hover:bg-surface-subtle/60"),children:[y&&s.jsx("button",{type:"button",title:"Select task",onClick:P=>{P.stopPropagation(),d(A.id)},className:B("grid h-[17px] w-[17px] shrink-0 place-items-center rounded border transition-opacity",T?"border-brand-600 bg-intent-brand opacity-100":"border-outline-strong opacity-0 group-hover/row:opacity-100 focus:opacity-100"),children:T&&s.jsx(fn,{className:"h-3 w-3 text-text-inverse"})}),s.jsx(_ne,{className:B("h-3.5 w-3.5 shrink-0 fill-current",Sze[A.priority]),"aria-label":`Priority: ${A.priority}`}),s.jsxs("div",{className:B("min-w-0 flex-1",n==="compact"?"flex items-baseline gap-3":"flex flex-col gap-0.5"),children:[s.jsx("div",{className:B("flex min-w-0 items-center gap-2",n==="compact"&&"shrink"),
906children:s.jsx("span",{className:B("truncate text-body-md font-medium",C?"text-text-tertiary line-through":"text-text-primary"),children:A.title})}),s.jsxs("div",{className:B("flex items-center gap-1.5",n==="compact"&&"min-w-0 overflow-hidden"),children:[t!=="type"&&s.jsx("span",{className:"text-body-xs font-medium text-text-tertiary",children:vze[A.type]??A.type}),I,t!=="status"&&s.jsx(Ize,{task:A,onQuickStatus:l,onSelect:o})]})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[$,s.jsxs("span",{className:B("inline-flex min-w-[76px] items-center justify-end gap-1 whitespace-nowrap text-body-sm font-semibold",O.tone==="overdue"&&"text-text-error",O.tone==="soon"&&"text-text-warning",O.tone==="neutral"&&"text-text-tertiary"),children:[O.icon==="alert"?s.jsx(yt,{className:"h-3.5 w-3.5"}):O.icon==="check"?s.jsx(Xt,{className:"h-3.5 w-3.5"}):O.icon==="clock"?s.jsx(Qp,{className:"h-3.5 w-3.5"}):null,O.text]})]})]},A.id)}return s.jsx("div",{children:_.map(A=>{const C=A.accent,T=v.has(A.key),S=A.tasks.filter(F=>Aze(F.status)).length,O=A.tasks.length?Math.round(S/A.tasks.length*100):0,R=A.tasks.filter(Iq).length,I=A.tasks.map(F=>F.id),$=y&&I.length>0&&I.every(F=>b.has(F)),P=y&&I.some(F=>b.has(F));return s.jsxs("section",{className:"relative border-t border-outline-subtle first:border-t-0",children:[s.jsx("div",{className:B("absolute left-0 top-0 bottom-0 w-[3px]",C.fill),"aria-hidden":!0}),s.jsxs("div",{onClick:()=>k(A.key),className:B("group/head flex cursor-pointer select-none items-center gap-2.5 py-2.5 pl-4 pr-4",C.tint,"bg-opacity-40 hover:bg-opacity-70"),children:[y&&s.jsx("button",{type:"button",title:$?"Deselect group":"Select group",onClick:F=>{F.stopPropagation(),h(I,!$)},className:B("grid h-[17px] w-[17px] shrink-0 place-items-center rounded border transition-opacity",$?"border-brand-600 bg-intent-brand opacity-100":P?"border-brand-600 bg-intent-brand/30 opacity-100":"border-outline-strong opacity-0 group-hover/head:opacity-100"),children:$?s.jsx(fn,{className:"h-3 w-3 text-text-inverse"}):P?s.jsx(Hv,{className:"h-3 w-3 text-text-brand"}):null}),s.jsx(Pn,{className:B("h-4 w-4 shrink-0 text-text-tertiary transition-transform",T&&"-rotate-90")}),s.jsx("span",{className:B("h-2 w-2 shrink-0 rounded-full",C.dot)}),s.jsx("span",{className:B("text-xs font-bold uppercase tracking-wide",C.text),children:A.name}),s.jsx("span",{className:"rounded-full bg-surface-sunken px-2 py-0.5 text-body-xs font-semibold tabular-nums text-text-secondary",children:A.tasks.length}),R>0&&!A.key.startsWith("due:overdue")&&s.jsxs("span",{className:"inline-flex items-center gap-1 text-body-xs font-semibold text-text-error",children:[s.jsx(yt,{className:"h-3.5 w-3.5"}),R," overdue"]}),s.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[s.jsx("div",{className:"h-1.5 w-16 overflow-hidden rounded-full bg-surface-sunken",title:`${S} of ${A.tasks.length} done`,children:s.jsx("div",{className:B("h-full rounded-full transition-all",C.fill),style:{width:`${O}%`}})}),s.jsxs("span",{className:"w-9 text-right text-body-xs font-medium tabular-nums text-text-tertiary",children:[S,"/",A.tasks.length]})]})]}),!T&&s.jsx("div",{children:A.tasks.map(E)})]},A.key)})})}const Oze=new Set;function Ize({task:e,onQuickStatus:t,onSelect:n}){return $l(e.status)||!t?s.jsx(_n,{tone:Aq[e.status],children:cu[e.status]}):s.jsxs("select",{value:e.status,onClick:r=>r.stopPropagation(),onChange:r=>{r.stopPropagation();const a=r.target.value;if(a==="__complete__"){n(e);return}t(e,a)},className:B("cursor-pointer focus:outline-none focus-visible:shadow-focus",M3[e.status]),title:"Change status",children:[Cze.map(r=>s.jsx("option",{value:r,children:cu[r]},r)),s.jsx("option",{value:"__complete__",children:"Complete / closeâ¦"})]})}function Pze(e,t,n){if(e&&(t!=null&&t[e])){const r=bze[mB(e)-1];return s.jsx("div",{title:t[e].name,className:B("grid shrink-0 place-items-center rounded-full bg-gradient-to-br font-bold text-text-inverse ring-2 ring-surface",n,r),children:t[e].initials})}return s.jsx("div",{title:"Unassigned",className:B("grid shrink-0 place-items-center rounded-full bg-surface-sunken text-text-tertiary",n),children:s.jsx(f6,{className:"h-3 w-3"})})}function Rze(e,t,n,r){var l,c;if(t==="type")return wze.map(u=>({key:`type:${u.key}`,name:u.name,accent:u.accent,tasks:e.filter(d=>u.types.includes(d.type))})).filter(u=>u.tasks.length>0);if(t==="status")return _ze.map(u=>({key:`status:${u}`,name:cu[u],accent:kze[u],tasks:e.filter(d=>d.status===u)})).filter(u=>u.tasks.length>0);if(t==="priority")return jze.map(u=>({key:`priority:${u}`,name:`${u.charAt(0).toUpperCase()+u.slice(1)} priority`,accent:Nze[u],tasks:e.filter(d=>d.priority===u)})).filter(u=>u.tasks.length>0);if(t==="due")return[{key:"overdue",name:"Overdue",accent:Fi.error,test:d=>!$l(d.status)&&Iq(d)},{key:"today",name:"Today",accent:Fi.warning,test:d=>!$l(d.status)&&ty(d)===0},{key:"tomorrow",name:"Tomorrow",accent:Fi.info,test:d=>!$l(d.status)&&ty(d)===1},{key:"week",name:"This week",accent:Di(2),test:d=>{const h=ty(d);return!$l(d.status)&&h!==null&&h>1&&h<7}},{key:"later",name:"Later",accent:ql,test:d=>{const h=ty(d);return!$l(d.status)&&(h===null||h>=7)}},{key:"done",name:"Done",accent:Fi.success,test:d=>$l(d.status)}].map(d=>({key:`due:${d.key}`,name:d.name,accent:d.accent,tasks:e.filter(d.test)})).filter(d=>d.tasks.length>0);if(t==="assignee"){const u=new Map;for(const f of e){const m=f.assignee_user_id??"__unassigned__";(u.get(m)??u.set(m,[]).get(m)).push(f)}const d=[];for(const[f,m]of u)f!=="__unassigned__"&&d.push({key:`assignee:${f}`,name:((l=r==null?void 0:r[f])==null?void 0:l.name)??"Assignee",accent:Ly(f),tasks:m});d.sort((f,m)=>f.name.localeCompare(m.name));const h=u.get("__unassigned__");return h&&d.push({key:"assignee:__unassigned__",name:"Unassigned",accent:ql,tasks:h}),d}if(t==="closer"){const u=new Map;for(const f of e){const m=f.completed_by_user_id??"__unattributed__";(u.get(m)??u.set(m,[]).get(m)).push(f)}const d=[];for(const[f,m]of u)f!=="__unattributed__"&&d.push({key:`closer:${f}`,name:((c=r==null?void 0:r[f])==null?void 0:c.name)??"Closer",accent:Ly(f),tasks:m});d.sort((f,m)=>f.name.localeCompare(m.name));const h=u.get("__unattributed__");return h&&d.push({key:"closer:__unattributed__",name:"Unattributed",accent:ql,tasks:h}),d}const a=new Map;for(const u of e){const d=u.seller_slug??"__internal__";(a.get(d)??a.set(d,[]).get(d)).push(u)}const i=[];for(const[u,d]of a)u!=="__internal__"&&i.push({key:`seller:${u}`,name:(n==null?void 0:n[u])??u,accent:Ly(u),tasks:d});i.sort((u,d)=>u.name.localeCompare(d.name));const o=a.get("__internal__");return o&&i.push({key:"seller:__internal__",name:"Internal",accent:ql,tasks:o}),i}function Dze(e){return e?{text:new Intl.DateTimeFormat("en-ZA",{timeZone:"Africa/Johannesburg",day:"numeric",month:"short",hour:"2-digit",minute:"2-digit",hour12:!1}).format(new Date(e)),tone:"neutral",icon:"check"}:{text:"â",tone:"neutral",icon:"none"}}function ty(e){if(!e.due_date)return null;const t=new Date;t.setHours(0,0,0,0);const n=new Date(`${e.due_date}T00:00:00`);return Math.round((n.getTime()-t.getTime())/864e5)}const L$=[{value:"meeting",label:"Meeting"},{value:"internal",label:"Internal"},{value:"management",label:"Management"},{value:"bug",label:"Bug"},{value:"reminder",label:"Reminder"},{value:"fire",label:"ð¥ Fire"},{value:"billing",label:"Billing"},{value:"customer_communication",label:"Customer comm"},{value:"feature",label:"Feature"},{value:"replenishment",label:"Replenishment"},{value:"promotion",label:"Promotion"},{value:"listing_upgrade",label:"Listing upgrade"},{value:"listing_creation",label:"New listing"},{value:"dc_allocation",label:"DC allocation"},{value:"stock_recon",label:"Stock recon"},{value:"overview_report",label:"Morning Overview"},{value:"pricing_experiment",label:"Price experiment"},{value:"other",label:"Other"}],Mze=["done","customer_completed","customer_not_required"],F$=["listing_creation","listing_upgrade","promotion","stock_recon"],B$=["listing_creation","listing_upgrade","promotion"],$ze=["overview_report"],Lze=["not_started","scheduled","in_progress","monitoring_testing","waiting_for_signoff","done","customer_completed","customer_not_required","cancelled"],Fze=["low","medium","high"],Bze=["promotion","replenishment","listing_upgrade","listing_creation","dc_allocation","stock_recon","customer_communication"];function Pq(e){return Bze.includes(e)}function Uze(e){switch(e){case"replenishment":return{label:"Shipment / PO numbers",placeholder:"e.g. 8683534, 187103616",help:"The Takealot shipment ID or purchase-order number from the bulk replen. Those are 6+ digits â not a count of units.",summaryPlaceholder:"e.g. Booked bulk shipment to CPT."};case"promotion":return{label:"Promotion IDs",placeholder:"e.g. 12826",help:"The Takealot promotion ID from the seller portal.",summaryPlaceholder:"e.g. Applied 42 SKUs to September Clearance."};default:return{label:"Takealot submission IDs",placeholder:"e.g. 4614838, 4614885, 4614956",help:"The catalogue / edit submission IDs Takealot returned. Each is linked to its submission status as proof of the work.",summaryPlaceholder:"e.g. Upgraded 5 listings â titles, images, attributes."}}}const qk=[{label:"Never",rrule:null},{label:"Daily",rrule:"FREQ=DAILY"},{label:"Weekly (same day)",rrule:"FREQ=WEEKLY"},{label:"Every 2 weeks",rrule:"FREQ=WEEKLY;INTERVAL=2"},{label:"Monthly (same date)",rrule:"FREQ=MONTHLY"}];function U$(e,t,n="other"){return{title:"",description:"",type:n,status:"not_started",priority:"medium",due_date:"",seller_slug:e??"",assignee_user_id:t??"",recurrence_rule:"",completion_summary:"",submission_refs:"",visible_to_seller:Pq(n)}}function zze(e,t,n,r){var a;return t||(e?n.length===1?n[0].slug:r[0]??((a=n[0])==null?void 0:a.slug)??"":"")}function z$(e){const t=new Set;for(const n of e.split(/[\s,]+/)){if(!n)continue;const r=Number(n);Number.isInteger(r)&&r>0&&t.add(r)}return[...t]}async function Wze(e,t,n,r){var m;const i=Array.from(((m=e.clipboardData)==null?void 0:m.items)??[]).find(x=>x.kind==="file"&&x.type.startsWith("image/"));if(!i)return;e.preventDefault(),r(null);const o=i.getAsFile();if(!o)return;const l=await new Promise((x,g)=>{const y=new FileReader;y.onerror=()=>g(y.error),y.onload=()=>{const b=y.result;if(typeof b!="string")return g(new Error("FileReader returned non-string"));const v=b.indexOf(",");x(v>=0?b.slice(v+1):b)},y.readAsDataURL(o)}),u=e.currentTarget.selectionStart??t.description.length,d="![uploadingâ¦]()",h=t.description.slice(0,u),f=t.de
906scription.slice(u);n({...t,description:`${h}${d}${f}`});try{const x=await K.taskAttachmentUpload(o.type,l);n(g=>({...g,description:g.description.replace(d,``)}))}catch(x){n(g=>({...g,description:g.description.replace(d,"")})),r(`Couldn't upload pasted image: ${x instanceof Error?x.message:String(x)}`)}}function Kze(e){return{title:e.title,description:e.description??"",type:e.type,status:e.status,priority:e.priority,due_date:e.due_date??"",seller_slug:e.seller_slug??"",assignee_user_id:e.assignee_user_id??"",recurrence_rule:e.recurrence_rule??"",completion_summary:e.completion_summary??"",submission_refs:(e.submission_refs??[]).map(t=>t.takealot_submission_id).join(", "),visible_to_seller:e.visible_to_seller}}function Rq({open:e,mode:t,taskId:n,defaultSellerSlug:r,sellers:a,onSaved:i,onClose:o}){const l=Lt(),c=l.kind==="ready"?l.me.id:null,u=l.kind==="ready"&&l.me.role==="super_admin",d=l.kind==="ready"&&l.me.role==="seller_user",h=l.kind==="ready"?l.me.allowed_slugs??[]:[],f=zze(d,r,a,h),m=d?"reminder":"other",[x,g]=p.useState(()=>U$(f,c??void 0,m)),[y,b]=p.useState(null),[v,w]=p.useState([]),[_,k]=p.useState([]),[j,N]=p.useState(!1),[E,A]=p.useState(!1),[C,T]=p.useState(null),[S,O]=p.useState(""),[R,I]=p.useState(!1),[$,P]=p.useState(!1),[F,Z]=p.useState(null),[D,H]=p.useState(null),[Y,M]=p.useState(null),[z,G]=p.useState(!1);p.useEffect(()=>{e&&(T(null),O(""),P(!1),Z(null),G(!1),g(U$(f,c??void 0,m)),b(null),w([]),H(null))},[e]),p.useEffect(()=>{!e||t!=="create"||!f||g(J=>J.seller_slug?J:{...J,seller_slug:f})},[e,t,f]),p.useEffect(()=>{if(!e)return;let J=!0;return vr.roster().then(Ne=>{J&&k(Ne.users)}).catch(()=>{}),()=>{J=!1}},[e]),p.useEffect(()=>{if(!e||t!=="edit"||!n)return;let J=!0;return N(!0),vr.get(n).then(Ne=>{J&&(b(Ne.task),w(Ne.comments),g(Kze(Ne.task)))}).catch(Ne=>{J&&T(Ne.message)}).finally(()=>{J&&N(!1)}),()=>{J=!1}},[e,t,n]),p.useEffect(()=>{if(!e||!y||y.type!=="promotion"||!y.seller_slug){H(null);return}let J=!0;return K.promotionDrafts.list(y.seller_slug).then(Ne=>{J&&H(Ne.drafts.find(ve=>ve.task_id===y.id)??null)}).catch(()=>{J&&H(null)}),()=>{J=!1}},[e,y]),p.useEffect(()=>{if(!e||!y||y.type!=="pricing_experiment"||!y.seller_slug){M(null);return}let J=!0;return K.experiments.listApprovals(y.seller_slug).then(Ne=>{J&&M(Ne.approvals.find(ve=>ve.task_id===y.id)??null)}).catch(()=>{J&&M(null)}),()=>{J=!1}},[e,y]),p.useEffect(()=>{if(!e)return;function J(Ne){Ne.key==="Escape"&&o()}return window.addEventListener("keydown",J),()=>window.removeEventListener("keydown",J)},[e,o]),p.useEffect(()=>{if(!e)return;const J=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=J}},[e]);const te=x.status==="done"&&F$.includes(x.type)&&!(t==="edit"&&(y==null?void 0:y.status)==="done"),re=te&&B$.includes(x.type),L=Uze(x.type),q=p.useMemo(()=>_,[_]),me=p.useMemo(()=>[...a].sort((J,Ne)=>J.display_name.localeCompare(Ne.display_name)),[a]),ee=p.useMemo(()=>d?L$.filter(J=>QF.includes(J.value)):L$,[d]),ne=d&&t==="edit"&&!!y&&y.created_by_user_id!==c,X=E||j||ne;function he(J){g(Ne=>({...Ne,type:J,visible_to_seller:z?Ne.visible_to_seller:Pq(J)}))}async function ae(){var ve;if(!x.title.trim()){T("Title is required.");return}if(!(t==="edit"&&(y==null?void 0:y.status)==="done")&&x.status==="done"&&F$.includes(x.type)){const Me=x.type.replace(/_/g," ");if(!x.completion_summary.trim()){T(`A "${Me}" task needs a completion summary â what was done â before it can be marked done.`);return}if(B$.includes(x.type)&&z$(x.submission_refs).length===0){T(`A "${Me}" task needs at least one Takealot submission ID as proof before it can be marked done.`);return}}const Ne=d?x.seller_slug||f:x.seller_slug||null;if(d&&t==="create"&&!Ne){T("No store is attached to this account, so a task can't be created.");return}A(!0),T(null);try{const Me=d&&t==="edit"?ne?{status:x.status}:{title:x.title.trim(),description:x.description.trim()||null,type:x.type,status:x.status,priority:x.priority,due_date:x.due_date||null,completion_summary:x.completion_summary.trim()||null}:{title:x.title.trim(),description:x.description.trim()||null,type:x.type,status:x.status,priority:x.priority,due_date:x.due_date||null,seller_slug:Ne,assignee_user_id:x.assignee_user_id||null,recurrence_rule:x.recurrence_rule||null,completion_summary:x.completion_summary.trim()||null,submission_refs:z$(x.submission_refs),...d?{}:{visible_to_seller:x.visible_to_seller}};if(t==="create"){const Xe=await vr.create(Me);i(Xe.task)}else if(y){const Xe=await vr.update(y.id,Me);(ve=Xe.system_comments)!=null&&ve.length&&w(ze=>[...ze,...Xe.system_comments]),b(Xe.task),i(Xe.task)}}catch(Me){T(Me instanceof Error?Me.message:String(Me))}finally{A(!1)}}async function je(){if(!(!y||!S.trim())){I(!0),T(null);try{const J=y.type==="customer_communication"&&!!y.source_chat_id,Ne=await vr.addComment(y.id,S.trim(),J);
906w(ve=>[...ve,Ne.comment]),O("")}catch(J){T(J instanceof Error?J.message:String(J))}finally{I(!1)}}}async function $e(){if(y){if(!$){P(!0);return}A(!0),T(null);try{await vr.remove(y.id),i(null)}catch(J){T(J instanceof Error?J.message:String(J)),A(!1)}}}return s.jsx(Cr,{open:e,onOpenChange:J=>{J||o()},children:s.jsxs(mr,{side:"right",size:"lg",children:[s.jsxs(Er,{children:[s.jsx(xr,{children:t==="create"?"New task":"Edit task"}),s.jsx(Mr,{className:"sr-only",children:t==="create"?"Create a new task â set title, type, assignee, due date, and details.":"Edit this task's title, type, assignee, due date, status, and details."})]}),s.jsxs(pr,{className:"p-4 space-y-4",children:[C&&s.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-outline-error bg-surface-errorSubtle p-3 text-sm text-text-error",children:[s.jsx(yt,{className:"h-4 w-4 mt-0.5 shrink-0"}),s.jsx("div",{children:C})]}),j?s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Loadingâ¦"]}):s.jsxs(s.Fragment,{children:[ne&&s.jsx("div",{className:"rounded-md border border-outline-subtle bg-surface-subtle p-3 text-body-sm text-text-secondary",children:"Your account manager created this task. You can update its status; the other details are managed by them."}),Y?s.jsxs(st,{to:`/approvals/${y==null?void 0:y.seller_slug}/experiments/${Y.batch_id}`,onClick:o,className:"flex items-center gap-3 rounded-md border border-outline-brand bg-surface-brandSubtle/50 px-3 py-2.5 text-body-sm text-text-primary transition hover:bg-surface-brandSubtle",children:[s.jsx(cd,{className:"h-4 w-4 shrink-0 text-intent-brand"}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium",children:"Open price experiment for sign-off"}),s.jsxs("span",{className:"text-body-xs text-text-secondary",children:[Y.line_count!=null?`${Y.line_count} SKUs · `:"","approve or request changes"]})]})]}):null,D?s.jsxs(st,{to:`/approvals/${y==null?void 0:y.seller_slug}/${D.id}`,onClick:o,className:"flex items-center gap-3 rounded-md border border-outline-brand bg-surface-brandSubtle/50 px-3 py-2.5 text-body-sm text-text-primary transition hover:bg-surface-brandSubtle",children:[s.jsx(cd,{className:"h-4 w-4 shrink-0 text-intent-brand"}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block font-medium",children:D.status==="approved"?"Open approved promotion":D.status==="uploaded"?"Open submitted promotion":D.changes_requested_at?"Open promotion â seller replied":"Open promotion for sign-off"}),s.jsxs("span",{className:"text-body-xs text-text-secondary",children:[D.line_count!=null?`${D.line_count} SKUs · `:"","review prices, drop lines, approve or resend"]})]})]}):null,s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs font-medium text-text-secondary",children:"Title"}),s.jsx(Re,{type:"text",value:x.title,disabled:X,onChange:J=>g({...x,title:J.target.value}),placeholder:"What needs doing?",autoFocus:t==="create"})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs font-medium text-text-secondary",children:x.type==="overview_report"?"WhatsApp note (copy, send, then close this task)":"Description (markdown supported · paste screenshots to upload)"}),s.jsx(Ui,{value:x.description,disabled:X,onChange:J=>g({...x,description:J.target.value}),onPaste:J=>{Wze(J,x,g,Z)},rows:x.type==="overview_report"?16:4,placeholder:x.type==="overview_report"?"Overnight job writes the seller-facing note hereâ¦":"Context, links, what good looks like⦠(paste screenshots inline)"}),F&&s.jsx("div",{className:"mt-1 text-xs text-text-error",children:F})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs font-medium text-text-secondary",children:"Type"}),s.jsx(Tt,{value:x.type,disabled:X,onChange:J=>he(J.target.value),children:ee.map(J=>s.jsx("option",{value:J.value,children:J.label},J.value))})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs font-medium text-text-secondary",children:"Priority"}),s.jsx(Tt,{value:x.priority,disabled:X,onChange:J=>g({...x,priority:J.target.value}),children:Fze.map(J=>s.jsx("option",{value:J,children:J.charAt(0).toUpperCase()+J.slice(1)},J))})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs font-medium text-text-secondary",children:"Status"}),s.jsx(Tt,{value:x.status,disabled:E||j,onChange:J=>g({...x,status:J.target.value}),children:Lze.map(J=>s.jsx("option",{value:J,children:cu[J]},J))})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs font-medium text-text-secondary",children:"Due"}),s.jsx(Re,{type:"date",value:x.due_date,disabled:X,onChange:J=>g({...x,due_date:J.target.value})})]})]}
906),Mze.includes(x.status)&&!$ze.includes(x.type)&&s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface-successSubtle/40 p-3 space-y-3",children:[s.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wide text-text-secondary",children:["Completion",te&&s.jsxs("span",{className:"ml-1.5 normal-case font-medium text-text-error",children:["â required to mark this ",x.type.replace(/_/g," ")," done"]})]}),s.jsxs("label",{className:"block",children:[s.jsxs("span",{className:"text-xs font-medium text-text-secondary",children:["What was done",te&&s.jsx("span",{className:"text-text-error",children:" *"})]}),s.jsx(Ui,{value:x.completion_summary,disabled:E||j,onChange:J=>g({...x,completion_summary:J.target.value}),rows:2,placeholder:L.summaryPlaceholder})]}),!d&&s.jsxs("label",{className:"block",children:[s.jsxs("span",{className:"text-xs font-medium text-text-secondary",children:[L.label,re&&s.jsx("span",{className:"text-text-error",children:" *"})]}),s.jsx(Ui,{value:x.submission_refs,onChange:J=>g({...x,submission_refs:J.target.value}),rows:2,placeholder:L.placeholder}),s.jsx("p",{className:"text-body-xs text-text-secondary mt-1",children:L.help})]}),!d&&t==="edit"&&(y==null?void 0:y.submission_refs)&&y.submission_refs.length>0&&s.jsx("ul",{className:"flex flex-wrap gap-1.5",children:y.submission_refs.map(J=>{const Ne=J.resolved_kind==="shipment"?"Shipment":J.resolved_kind==="promotion"?"Promotion":null,ve=J.outcome==="good"?"bg-surface-successSubtle text-text-success ring-outline-success":J.outcome==="bad"?"bg-surface-errorSubtle text-text-error ring-outline-error":J.outcome==="pending"?"bg-surface-infoSubtle text-text-info ring-outline-info":"bg-surface-sunken text-text-body ring-outline-subtle",Me=[Ne,J.status_label,J.plid?`PLID ${J.plid}`:null,J.promo_title].filter(Boolean).join(" · ");return s.jsxs("li",{title:J.matched?Me:"Logged â not yet matched to a submission, shipment or promotion record",className:B("inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-body-xs ring-1",ve),children:[s.jsx("span",{className:"font-mono",children:J.takealot_submission_id}),J.status_label&&s.jsxs("span",{className:"opacity-70",children:["· ",Ne?`${Ne}: `:"",J.status_label]}),J.ambiguous&&s.jsx("span",{className:"opacity-70",title:"Matches more than one record",children:"â "})]},J.id)})})]}),!d&&s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs font-medium text-text-secondary",children:"Seller"}),s.jsxs(Tt,{value:x.seller_slug,disabled:X,onChange:J=>g({...x,seller_slug:J.target.value}),children:[s.jsx("option",{value:"",children:"â internal (no seller) â"}),me.map(J=>s.jsx("option",{value:J.slug,children:J.display_name},J.slug))]})]}),!d&&s.jsxs("label",{className:"flex items-start gap-2.5 rounded-md border border-outline-subtle bg-surface-subtle p-3",children:[s.jsx("input",{type:"checkbox",checked:x.visible_to_seller,disabled:X,onChange:J=>{G(!0),g({...x,visible_to_seller:J.target.checked})},className:"mt-0.5 h-4 w-4 cursor-pointer rounded border-outline accent-brand-600"}),s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block text-xs font-medium text-text-primary",children:"Visible to seller"}),s.jsx("span",{className:"block text-body-xs text-text-secondary",children:"Show this task in the seller's own Tasks view. Seller-facing types (promotions, replenishment, listing work, ticketsâ¦) default to visible."})]})]}),!d&&s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"text-xs font-medium text-text-secondary",children:"Assignee"}),s.jsxs(Tt,{value:x.assignee_user_id,disabled:X,onChange:J=>g({...x,assignee_user_id:J.target.value}),children:[s.jsx("option",{value:"",children:"â unassigned â"}),q.map(J=>s.jsxs("option",{value:J.id,children:[J.display_name||J.email,J.role==="super_admin"?" (admin)":""]},J.id))]})]}),!d&&s.jsxs("label",{className:"block",children:[s.jsxs("span",{className:"text-xs font-medium text-text-secondary flex items-center gap-1",children:[s.jsx(Pre,{className:"h-3.5 w-3.5"})," Repeat"]}),s.jsxs(Tt,{value:qk.some(J=>J.rrule===(x.recurrence_rule||null))?x.recurrence_rule||"":"__custom__",disabled:X,onChange:J=>{const Ne=J.target.value;Ne!=="__custom__"&&g({...x,recurrence_rule:Ne})},children:[qk.map(J=>s.jsx("option",{value:J.rrule??"",children:J.label},J.label)),s.jsx("option",{value:"__custom__",children:"Custom (RRULE)â¦"})]}),!qk.some(J=>J.rrule===(x.recurrence_rule||null))&&s.jsx(Re,{type:"text",value:x.recurrence_rule,disabled:X,onChange:J=>g({...x,recurrence_rule:J.target.value}),placeholder:"e.g. FREQ=WEEKLY;BYDAY=MO,WE"}),s.jsx("p",{className:"text-body-xs text-text-secondary mt-1",children:"Recurring tasks auto-spawn the next instance when this one is marked done."})]}),t==="edit"&&y&&s.jsxs("section",{className:"pt-4 border-t border-outline-subtle",children:[s.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-text-secondary mb-2",children:"Activity"}),s.jsxs("ul",{className:"space-y-2",children:[v.length===0&&s.jsx("li",{className:"text-xs text-text-tertiary",children:"No activity yet."}),v.map(J=>s.jsxs("li",{className:B("text-sm rounded-md px-3 py-2",J.is_system?"bg-surface-subtle text-text-secondary italic text-body-sm":"bg-surface border border-outline-subtle"),children:[J.is_system?s.jsx("div",{children:J.body}):s.jsx("div",{className:"prose prose-sm max-w-none",children:s.jsx(mx,{remarkPlugins:[px,d3,p3],components:{...GV,a:({node:Ne,...ve})=>s.jsx("a",{...ve,target:"_blank",rel:"noopener noreferrer"})},children:J.body})}),s.jsxs("div",{className:"text-body-xs text-text-tertiary mt-1 flex items-center gap-1.5",children:[s.jsx("span",{children:new Date(J.created_at).toLocaleStr
906ing()}),J.posted_to_chat&&s.jsxs("span",{className:"inline-flex items-center gap-0.5 text-text-success",children:[s.jsx(V2,{className:"h-2.5 w-2.5"})," sent to seller"]})]})]},J.id))]}),s.jsxs("div",{className:"mt-3 flex items-start gap-2",children:[s.jsx(Ui,{value:S,onChange:J=>O(J.target.value),rows:2,placeholder:y.type==="customer_communication"&&y.source_chat_id?"Reply to the seller⦠(will be posted to their chat)":"Add a commentâ¦",className:"flex-1 rounded-md border border-outline px-3 py-2 text-sm focus:outline-none focus:border-outline-brand focus-visible:shadow-focus"}),s.jsx(W,{type:"button",onClick:je,disabled:!S.trim()||R,intent:"brand",size:"md",children:R?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):"Post"})]})]})]})]}),s.jsxs(ml,{className:"justify-between",children:[s.jsx("div",{children:t==="edit"&&u&&s.jsxs(W,{type:"button",onClick:$e,intent:"destructive",variant:$?"solid":"ghost",size:"sm",children:[s.jsx(us,{className:"h-3.5 w-3.5"}),$?"Confirm delete":"Delete"]})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(W,{type:"button",onClick:o,intent:"neutral",variant:"ghost",size:"sm",children:"Cancel"}),s.jsx(W,{type:"button",onClick:ae,disabled:E||j,intent:"brand",size:"sm",children:E?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):t==="create"?"Create":"Save"})]})]})]})})}const Hze=[{key:"30d",label:"30 days"},{key:"90d",label:"90 days"},{key:"all",label:"All time"}];function Vze(e){return e==="30d"||e==="90d"||e==="all"}function Gk(e){var t;return((t=e.display_name)==null?void 0:t.trim())||e.email}function qze({refreshSignal:e=0,onSelectAm:t,bare:n=!1}){var j;const r=Lt(),a=r.kind==="ready"?r.me.id:null,[i,o]=it("amteam",""),l=n?!1:i==="1",[c,u]=it("amwin","all"),d=Vze(c)?c:"all",[h,f]=p.useState(null),[m,x]=p.useState(!0),[g,y]=p.useState(null);p.useEffect(()=>{let N=!0;return x(!0),y(null),vr.byAm(d).then(E=>{N&&f(E.rows)}).catch(E=>{N&&y(E.message)}).finally(()=>{N&&x(!1)}),()=>{N=!1}},[d,e]);const b=Id(h,N=>[N.display_name,N.email],{urlKey:"amq"}),v=p.useMemo(()=>(b.filtered??[]).reduce((E,A)=>({open:E.open+A.open,overdue:E.overdue+A.overdue,completed:E.completed+A.completed}),{open:0,overdue:0,completed:0}),[b.filtered]),w=d==="all"?"Cleared (all)":`Cleared (${d})`,_=[{key:"name",label:"Account manager",sortable:!0,sticky:!0,getValue:N=>Gk(N).toLowerCase(),render:N=>s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium",children:Gk(N)}),N.id===a&&s.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-text-brand border border-outline-brand rounded px-1 py-0.5",children:"You"}),N.role==="super_admin"&&s.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-text-tertiary border border-outline-subtle rounded px-1 py-0.5",children:"Admin"})]}),className:"whitespace-nowrap text-text-body"},{key:"open",label:"Open",sortable:!0,align:"right",render:N=>s.jsx("span",{className:"font-medium text-text-body",children:N.open.toLocaleString()})},{key:"overdue",label:"Overdue",sortable:!0,align:"right",render:N=>s.jsx("span",{className:N.overdue>0?"font-medium text-text-error":"text-text-tertiary",children:N.overdue.toLocaleString()})},{key:"completed",label:w,sortable:!0,align:"right",render:N=>s.jsx("span",{className:"text-text-tertiary",children:N.completed.toLocaleString()})}],k=s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-center gap-3 flex-wrap border-b border-outline-subtle px-3 py-2",children:[n?s.jsx("span",{className:"text-sm font-medium text-text-primary",children:"Team workload"}):s.jsxs("button",{type:"button",onClick:()=>o(l?"":"1"),className:"flex items-center gap-1.5 text-sm font-medium text-text-primary hover:text-text-secondary","aria-expanded":!l,children:[l?s.jsx(fr,{className:"h-4 w-4"}):s.jsx(Pn,{className:"h-4 w-4"}),"Team workload"]}),!l&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-center gap-1",children:Hze.map(N=>s.jsx("button",{type:"button",onClick:()=>u(N.key),className:B("px-2.5 py-1 rounded-md text-xs font-medium whitespace-nowrap transition",d===N.key?"bg-surface-inverse text-text-inverse":"text-text-secondary hover:bg-surface-sunken"),children:N.label},N.key))}),s.jsx(Ni,{value:b.q,onChange:b.setQ,placeholder:"Filter by nameâ¦",className:"ml-auto w-full sm:w-64"})]})]}),!l&&s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"px-4 pt-2.5 pb-1 text-body-xs text-text-tertiary",children:"Where work is piling up across the team â so it can be rebalanced, not ranked."}),g?s.jsx("p",{className:"py-6 text-center text-body-sm text-text-error",children:g}):s.jsx(dt,{rows:b.filtered,columns:_,getRowKey:N=>N.id,sortUrlKey:"amsort",defaultSort:{key:"open",direction:"desc"},paginate:!1,loading:m&&!h,empty:{title:"No account managers match."},onRowClick:t?N=>t({id:N.id,name:Gk(N)}):void 0,rowClassName:N=>N.id===a?"bg-surface-subtle":void 0,footer:(((j=b.filtered)==null?void 0:j.length)??0)>1?s.jsx("tfoot",{children:s.jsxs("tr",{className:"border-t border-outline-subtle bg-surface-subtle text-text-secondary",children:[s.jsx("td",{className:"py-2 pl-4 pr-3 text-xs uppercase tracking-wider",children:"Team total"}),s.jsx("td",{className:"py-2 px-3 text-right tabular-nums font-medium",children:v.open.toLocaleStr
906ing()}),s.jsx("td",{className:"py-2 px-3 text-right tabular-nums font-medium",children:v.overdue.toLocaleString()}),s.jsx("td",{className:"py-2 pr-4 pl-3 text-right tabular-nums font-medium text-text-tertiary",children:v.completed.toLocaleString()})]})}):null}),s.jsxs("p",{className:"px-4 py-2.5 text-body-xs text-text-tertiary border-t border-outline-faint",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Open"})," &"," ",s.jsx("span",{className:"font-medium text-text-secondary",children:"Overdue"})," are current load. ",s.jsx("span",{className:"font-medium text-text-secondary",children:"Cleared"})," ","counts the selected window and is attributed by the task's assignee â the system doesn't record who marked a task done, so read it as a rough health signal, not a score."]})]})]});return n?k:s.jsx(V,{className:"overflow-hidden",children:k})}function Gze(e){var t;return((t=e.display_name)==null?void 0:t.trim())||e.email}function Yze({isSuperAdmin:e,refreshSignal:t=0}){const n=Lt(),r=n.kind==="ready"?n.me.id:null,[a,i]=p.useState("today"),[o,l]=p.useState(null),[c,u]=p.useState(!0),[d,h]=p.useState(null),[f,m]=p.useState(""),[x,g]=p.useState(!1);p.useEffect(()=>{let k=!0;return u(!0),h(null),vr.today(a).then(j=>{k&&(l(j),m(String(j.floor)))}).catch(j=>{k&&h(j.message)}).finally(()=>{k&&u(!1)}),()=>{k=!1}},[a,t]);async function y(){const k=Number(f);if(!o||!Number.isInteger(k)||k<1||k>20||k===o.floor){o&&m(String(o.floor));return}g(!0);try{const j=await vr.setDailyFloor(k);l(N=>N&&{...N,floor:j.floor,rows:N.rows.map(E=>({...E,met_floor:E.role==="am"?E.done>=j.floor:null}))}),m(String(j.floor))}catch(j){h(j instanceof Error?j.message:String(j)),o&&m(String(o.floor))}finally{g(!1)}}const b=(o==null?void 0:o.rows)??[],v=p.useMemo(()=>b.filter(k=>k.role==="am"),[b]),w=p.useMemo(()=>v.filter(k=>k.met_floor===!1).length,[v]),_=a==="today"?"today":"yesterday";return s.jsxs("div",{className:"border-b border-outline-subtle",children:[s.jsxs("div",{className:"flex items-center gap-3 flex-wrap px-3 py-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Daily floor check"}),s.jsx("p",{className:"text-body-xs text-text-tertiary",children:o&&v.length>0?w===0?`All ${v.length} account manager${v.length===1?"":"s"} cleared the floor ${_}.`:`${w} of ${v.length} account managers below the floor ${_} â worth a nudge.`:"Tasks each account manager has closed today, against a daily minimum."})]}),s.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-body-xs text-text-secondary",children:[s.jsx("span",{children:"Floor"}),e?s.jsx(Re,{type:"number",min:1,max:20,value:f,disabled:x,onChange:k=>m(k.target.value),onBlur:y,onKeyDown:k=>{k.key==="Enter"&&k.target.blur()},className:"w-14 h-7 text-center tabular-nums",title:"Minimum tasks per AM per day"}):s.jsx("span",{className:"font-semibold tabular-nums text-text-primary",children:(o==null?void 0:o.floor)??"â"}),s.jsx("span",{children:"/day"})]}),s.jsxs(Pa,{value:a,onValueChange:k=>{(k==="today"||k==="yesterday")&&i(k)},children:[s.jsx(Ln,{value:"today",children:"Today"}),s.jsx(Ln,{value:"yesterday",children:"Yesterday"})]})]})]}),d?s.jsx("p",{className:"px-4 py-3 text-body-xs text-text-error",children:d}):s.jsx(dt,{rows:b,columns:[{key:"manager",label:"Account manager",render:k=>{const j=k.id===r;return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium",children:Gze(k)}),j&&s.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-text-brand border border-outline-brand rounded px-1 py-0.5",children:"You"}),k.role==="super_admin"&&s.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-text-tertiary border border-outline-subtle rounded px-1 py-0.5",children:"Admin"})]})},className:"text-text-body whitespace-nowrap"},{key:"done",label:`Done ${_}`,align:"right",render:k=>s.jsx("span",{className:B("tabular-nums font-medium",k.met_floor===!1?"text-text-warning":"text-text-body"),children:k.done.toLocaleStr
906ing()})},{key:"outstanding",label:"Outstanding",align:"right",render:k=>s.jsxs("span",{className:"tabular-nums text-text-secondary",children:[k.open.toLocaleString(),k.overdue>0&&s.jsxs("span",{className:"ml-1.5 text-text-error",title:`${k.overdue} overdue`,children:["(",k.overdue,")"]})]})},{key:"floor",label:"Floor",align:"right",render:k=>k.met_floor==null?s.jsx("span",{className:"text-text-tertiary",children:"â"}):k.met_floor?s.jsx("span",{className:"inline-flex items-center gap-1 text-text-success",title:"Met the daily floor",children:s.jsx(fn,{className:"h-3.5 w-3.5"})}):s.jsxs("span",{className:"inline-flex items-center gap-1 text-text-warning",title:"Below the daily floor",children:[s.jsx(zn,{className:"h-3.5 w-3.5"})," below"]})}],getRowKey:k=>k.id,paginate:!1,persist:!1,tableClassName:"text-body-sm",loading:c&&!o,empty:{title:"No account managers to show."},rowClassName:k=>B(k.met_floor===!1&&"bg-surface-warningSubtle/40",k.id===r&&k.met_floor!==!1&&"bg-surface-subtle")}),s.jsxs("p",{className:"px-4 py-2.5 text-body-xs text-text-tertiary",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Done"})," counts tasks each person actually ",s.jsx("span",{className:"font-medium text-text-secondary",children:"closed"})," ","that day (recorded from when this check shipped â earlier days read 0)."," ",s.jsx("span",{className:"font-medium text-text-secondary",children:"Outstanding"})," is their current open load (overdue in red). The floor applies to account managers only."]})]})}const W$={"30d":"last 30 days","90d":"last 90 days",all:"all time"};function Zze(e){return e==="30d"||e==="90d"||e==="all"}function Xze({isSuperAdmin:e,roster:t,refreshSignal:n=0}){const[r,a]=p.useState("30d"),[i,o]=p.useState(""),[l,c]=p.useState(null),[u,d]=p.useState(!0),[h,f]=p.useState(null);p.useEffect(()=>{let v=!0;return d(!0),f(null),vr.completionsByAccount(r,i||void 0).then(w=>{v&&c(w.rows)}).catch(w=>{v&&f(w.message)}).finally(()=>{v&&d(!1)}),()=>{v=!1}},[r,i,n]);const m=p.useMemo(()=>(l??[]).reduce((v,w)=>v+w.completed,0),[l]),x=p.useMemo(()=>(l??[]).filter(v=>v.seller_slug).length,[l]),g=p.useMemo(()=>(l??[]).reduce((v,w)=>Math.max(v,w.completed),0),[l]),y=i?t.find(v=>v.id===i):null,b=y?`${y.display_name||y.email} closed`:"You closed";return s.jsxs("div",{className:"border-b border-outline-subtle px-3 py-3 space-y-2.5",children:[s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Progress · by account"}),s.jsx("p",{className:"text-body-xs text-text-tertiary",children:"Completed work and the accounts it landed on â coverage, not a ranking."})]}),s.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[e&&t.length>0&&s.jsxs(Tt,{value:i,onChange:v=>o(v.target.value),className:"w-40 shrink-0",title:"Whose completions to show",children:[s.jsx("option",{value:"",children:"My progress"}),t.map(v=>s.jsxs("option",{value:v.id,children:[v.display_name||v.email,v.role==="super_admin"?" (admin)":""]},v.id))]}),s.jsxs(Pa,{value:r,onValueChange:v=>{Zze(v)&&a(v)},children:[s.jsx(Ln,{value:"30d",children:"30d"}),s.jsx(Ln,{value:"90d",children:"90d"}),s.jsx(Ln,{value:"all",children:"All"})]})]})]}),h?s.jsx("p",{className:"text-body-xs text-text-error",children:h}):u&&!l?s.jsx("p",{className:"text-body-xs text-text-tertiary",children:"Loadingâ¦"}):m===0?s.jsxs("p",{className:"text-body-xs text-text-tertiary",children:["No completions in ",W$[r],"."]}):s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"text-body-xs text-text-secondary",children:[s.jsxs("span",{className:"font-semibold text-text-primary",children:[b," ",m.toLocaleString()," task",m===1?"":"s"]})," ","across ",x.toLocaleString()," account",x===1?"":"s"," · ",W$[r],"."]}),s.jsx("div",{className:"max-h-56 overflow-y-auto pr-1 space-y-1",children:l.map(v=>{const w=v.seller_slug?v.display_name??v.seller_slug:"No account / internal",_=g>0?Math.round(v.completed/g*100):0;return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:B("w-44 shrink-0 truncate text-xs",v.seller_slug?"text-text-body":"text-text-tertiary italic"),title:w,children:w}),s.jsx(Nf,{className:"min-w-0 flex-1",value:_,valueLabel:v.completed.toLocaleStr
906ing()})]},v.seller_slug??"__none__")})})]})]})}function Jze({crumbs:e,items:t,title:n,subtitle:r,children:a}){return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:e}),s.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:[s.jsx(As,{items:t}),s.jsxs("div",{className:"w-full px-4 md:px-6 py-6 space-y-6",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-semibold text-text-primary",children:n}),r&&s.jsx("p",{className:"mt-1 text-sm text-text-secondary",children:r})]}),a]})]})]})}function Gn({label:e,hint:t,children:n}){return s.jsxs("div",{className:"p-4 flex items-start gap-4",children:[s.jsxs("div",{className:"w-40 shrink-0",children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-0.5",children:t})]}),s.jsx("div",{className:"flex-1 min-w-0 flex justify-end items-center",children:n})]})}function $n(){return s.jsx("div",{className:"border-t border-outline-faint"})}const Yk=["street","suburb","city","postal_code","country"],Qze={street:"Street",suburb:"Suburb",city:"City",postal_code:"Postal code",country:"Country"},Zk=[{field:"bank.account_holder",label:"Account holder",hint:""},{field:"bank.bank",label:"Bank",hint:""},{field:"bank.branch_code",label:"Branch code",hint:"6 digits"},{field:"bank.account_number",label:"Account number",hint:"6â12 digits"}];function Xa(e){const t=e==null?void 0:e.value;return typeof t=="string"?t:""}function Xk(e){const t=e==null?void 0:e.value;return t&&typeof t=="object"?t:{}}function Jk(e){const t=e.replace(/\D/g,"");return t.length>4?`â¢â¢â¢â¢${t.slice(-4)}`:"â¢â¢â¢â¢"}function Fy({state:e}){return!e||e.source==="missing"?s.jsx("span",{className:"text-xs text-text-warning whitespace-nowrap",children:"Not set"}):e.source==="override"?s.jsx("span",{className:"text-xs text-text-secondary whitespace-nowrap",children:"Your value"}):s.jsx("span",{className:"text-xs text-text-tertiary whitespace-nowrap",children:"From Takealot"})}function eWe({seller:e}){const t=e.slug,[n,r]=p.useState(null),[a,i]=p.useState(null),[o,l]=p.useState(!1),[c,u]=p.useState(null),d=p.useCallback(()=>{i(null),K.businessInfo.get(t).then(m=>r(m.business_info)).catch(m=>i(String((m==null?void 0:m.message)||m)))},[t]);p.useEffect(()=>{r(null),d()},[d]);async function h(){l(!0),i(null),u(null);try{const m=await K.businessInfo.refresh(t);r(m.business_info);const x=m.errors?Object.keys(m.errors):[];u(x.length?`Refreshed. Takealot didn't return: ${x.join(", ")} â fill those in below.`:"Refreshed from Takealot.")}catch(m){i(String((m==null?void 0:m.message)||m))}finally{l(!1)}}if(a&&!n)return s.jsx(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:a});if(!n)return s.jsx(V,{className:"p-4 text-sm text-text-secondary",children:"Loading detailsâ¦"});const f=n.missing_for_invoice??[];return s.jsxs("div",{className:"flex flex-col gap-4",children:[a&&s.jsx(V,{className:"p-3 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:a}),f.length>0&&s.jsx(V,{className:"p-3 bg-surface-warningSubtle border-outline-warning",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(zn,{className:"w-4 h-4 text-text-warning mt-0.5 shrink-0"}),s.jsxs("div",{className:"text-sm text-text-warning",children:[s.jsxs("span",{className:"font-medium",children:[f.length," field",f.length===1?"":"s"," still missing."]})," ","A Stock Loss Claim invoice generated now would print â[MISSING]â in place of ",f.length===1?"it":"them",", which Takealot will reject."]})]})}),c&&s.jsxs(V,{className:"p-3 text-sm text-text-secondary flex items-start gap-2",children:[s.jsx(lF,{className:"w-4 h-4 text-text-tertiary mt-0.5 shrink-0"}),s.jsx("span",{children:c})]}),s.jsx(tWe,{info:n,slug:t,onSaved:r}),s.jsx(nWe,{info:n,slug:t,onSaved:r}),s.jsx(rWe,{info:n,slug:t,onSaved:r}),s.jsxs("div",{className:"flex items-center justify-between gap-3 px-1",children:[s.jsxs("div",{className:"text-xs text-text-tertiary",children:[n.fetched_at?`Last pulled from Takealot ${new Date(n.fetched_at).toLocaleStr
906ing()}.`:"Never pulled from Takealot."," ","Values you save here are kept and always win."]}),s.jsxs(W,{onClick:h,disabled:o,intent:"neutral",size:"sm",children:[s.jsx(pa,{className:`w-3.5 h-3.5 ${o?"animate-spin":""}`}),o?"Refreshingâ¦":"Refresh from Takealot"]})]})]})}function tWe({info:e,slug:t,onSaved:n}){const[r,a]=p.useState(Xa(e.fields.trading_name)),[i,o]=p.useState(Xa(e.fields.contact_email)),[l,c]=p.useState(Xk(e.fields.billing_address)),[u,d]=p.useState(!1),[h,f]=p.useState(null),[m,x]=p.useState(null);p.useEffect(()=>{a(Xa(e.fields.trading_name)),o(Xa(e.fields.contact_email)),c(Xk(e.fields.billing_address))},[e]);const g=Xk(e.fields.billing_address),y=Yk.some(w=>(l[w]??"")!==(g[w]??"")),b=r!==Xa(e.fields.trading_name)||i!==Xa(e.fields.contact_email)||y;async function v(){d(!0),x(null);try{let w=e;const _=[];if(r!==Xa(e.fields.trading_name)&&_.push(["trading_name",r.trim()||null]),i!==Xa(e.fields.contact_email)&&_.push(["contact_email",i.trim()||null]),y){const k=Yk.some(j=>(l[j]??"").toString().trim());_.push(["billing_address",k?{street:(l.street??"").trim(),suburb:(l.suburb??"").trim()||void 0,city:(l.city??"").trim(),postal_code:(l.postal_code??"").trim(),country:(l.country??"").trim()||"South Africa"}:null])}for(const[k,j]of _){const N=await K.businessInfo.update(t,k,j);N.ok&&(w=N.business_info)}n(w),f(Date.now())}catch(w){x(String((w==null?void 0:w.message)||w))}finally{d(!1)}}return s.jsxs(V,{children:[s.jsx("div",{className:"px-4 pt-4 pb-1 text-sm font-medium text-text-primary",children:"Business details"}),s.jsx("div",{className:"px-4 pb-3 text-xs text-text-secondary",children:"Printed as the âBill Fromâ block on every claim invoice."}),s.jsx($n,{}),s.jsx(Gn,{label:"Trading name",children:s.jsxs("div",{className:"flex items-center gap-2 w-full",children:[s.jsx(Re,{type:"text",value:r,onChange:w=>a(w.target.value),disabled:u,inputSize:"sm",maxLength:120,placeholder:"Registered trading name",className:"flex-1"}),s.jsx(Fy,{state:e.fields.trading_name})]})}),s.jsx($n,{}),s.jsx(Gn,{label:"Contact email",children:s.jsxs("div",{className:"flex items-center gap-2 w-full",children:[s.jsx(Re,{type:"email",value:i,onChange:w=>o(w.target.value),disabled:u,inputSize:"sm",placeholder:"[email protected]",className:"flex-1"}),s.jsx(Fy,{state:e.fields.contact_email})]})}),s.jsx($n,{}),s.jsx(Gn,{label:"Billing address",hint:"Street, city and postal code required",children:s.jsxs("div",{className:"w-full flex flex-col gap-2",children:[s.jsx("div",{className:"flex items-center justify-end",children:s.jsx(Fy,{state:e.fields.billing_address})}),Yk.map(w=>s.jsx(Re,{type:"text",value:l[w]??"",onChange:_=>c({...l,[w]:_.target.value}),disabled:u,inputSize:"sm",placeholder:Qze[w]},w))]})}),s.jsx($n,{}),s.jsx(sWe,{dirty:b,saving:u,savedAt:h,err:m,onSave:v})]})}function nWe({info:e,slug:t,onSaved:n}){const[r,a]=p.useState(Xa(e.fields.vat_number)),[i,o]=p.useState(!1),[l,c]=p.useState(null),[u,d]=p.useState(null);p.useEffect(()=>a(Xa(e.fields.vat_number)),[e]);const h=r!==Xa(e.fields.vat_number),f=e.vat_status==="registered_no_number",m=e.vat_status==="unknown",x=e.vat_status_override==="not_registered";async function g(){o(!0),d(null);try{const v=await K.businessInfo.update(t,"vat_number",r.trim()||null);let w=v.ok?v.business_info:e;if(r.trim()&&x){const _=await K.businessInfo.update(t,"vat_status",null);_.ok&&(w=_.business_info)}n(w),c(Date.now())}catch(v){d(String((v==null?void 0:v.message)||v))}finally{o(!1)}}async function y(v){o(!0),d(null);try{const w=await K.businessInfo.update(t,"vat_status",v?"not_registered":null);w.ok&&n(w.business_info),c(Date.now())}catch(w){d(String((w==null?void 0:w.message)||w))}finally{o(!1)}}const b=e.vat_status==="registered_with_number"?"VAT registered â claims are issued as Tax Invoices":e.vat_status==="not_registered"?"Not VAT registered â claims are issued as plain Invoices":e.vat_status==="registered_no_number"?"Takealot lists you as VAT registered, but your VAT number is missing":"Unknown â no VAT information on file yet";return s.jsxs(V,{children:[s.jsx("div",{className:"px-4 pt-4 pb-1 text-sm font-medium text-text-primary",children:"VAT"}),s.jsx("div",{className:"px-4 pb-3 text-xs text-text-secondary",children:"Decides whether a claim is a Tax Invoice with VAT, or a plain invoice without."}),s.jsx($n,{}),s.jsx(Gn,{label:"Status",children:s.jsxs("div",{className:"flex items-start gap-2 w-full",children:[f||m?s.jsx(zn,{className:"w-4 h-4 text-text-warning mt-0.5 shrink-0"}):s.jsx(Xt,{className:"w-4 h-4 text-text-success mt-0.5 shrink-0"}),s.jsxs("div",{className:`text-sm ${f||m?"text-text-warning":"text-text-body"}`,children:[b,(f||m)&&s.jsx("div",{className:"text-xs mt-1 text-text-secondary",children:"Claim generation is paused until this is resolved â we wonât guess a VAT treatment. Add your SARS number below, or confirm you arenât registered."})]})]})}),s.jsx($n,{}),s.jsx(Gn,{label:"VAT number",hint:"10 digits, starts with 4",children:s.jsxs("div",{className:"flex items-center gap-2 w-full",children:[s.jsx(Re,{type:"text",value:r,onChange:v=>a(v.target.value),disabled:i||x,inputSize:"sm",maxLength:14,placeholder:x?"Not applicable":"4xxxxxxxxx",className:"flex-1"}),s.jsx(W,{onClick:g,disabled:!h||i||x,intent:"brand",size:"sm",children:i?"Savingâ¦":"Save"}),l!==null&&Date.now()-l<4e3&&s.jsx(Xt,{className:"w-4 h-4 text-text-success"})]})}),s.jsx($n,{}),s.jsx(Gn,{label:"Not registered",hint:"Only if you are not a VAT vendor",children:s.jsx("div",{className:"w-full",children:x?s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-sm text-text-body",children:"Marked as
906not VAT registered."}),s.jsx(W,{onClick:()=>y(!1),disabled:i,intent:"neutral",size:"sm",children:"Undo"})]}):s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(W,{onClick:()=>y(!0),disabled:i||!!r.trim(),intent:"neutral",size:"sm",children:"Iâm not VAT registered"}),!!r.trim()&&s.jsx("span",{className:"text-xs text-text-tertiary",children:"Clear the VAT number first."})]})})}),u&&s.jsxs(s.Fragment,{children:[s.jsx($n,{}),s.jsx("div",{className:"px-4 py-3 text-sm text-text-error",children:u})]})]})}function rWe({info:e,slug:t,onSaved:n}){const r=()=>Object.fromEntries(Zk.map(v=>[v.field,Xa(e.fields[v.field])])),[a,i]=p.useState(r),[o,l]=p.useState(!1),[c,u]=p.useState(!1),[d,h]=p.useState(!1),[f,m]=p.useState(null),[x,g]=p.useState(null);p.useEffect(()=>{i(r()),u(!1)},[e]);const y=Zk.filter(v=>a[v.field]!==Xa(e.fields[v.field]));async function b(){h(!0),g(null);try{let v=e;for(const w of y){const _=await K.businessInfo.update(t,w.field,a[w.field].trim()||null,!0);_.ok&&(v=_.business_info)}n(v),m(Date.now()),u(!1)}catch(v){g(String((v==null?void 0:v.message)||v))}finally{h(!1)}}return s.jsxs(V,{children:[s.jsxs("div",{className:"px-4 pt-4 pb-1 flex items-center gap-2 text-sm font-medium text-text-primary",children:[s.jsx(z2,{className:"w-4 h-4 text-text-tertiary"}),"Banking"]}),s.jsx("div",{className:"px-4 pb-3 text-xs text-text-secondary",children:"The account Takealot pays a stock loss claim into. Printed on the invoice."}),s.jsx($n,{}),Zk.map(v=>{const w=v.field==="bank.account_number",_=w&&!o;return s.jsxs("div",{children:[s.jsx(Gn,{label:v.label,hint:v.hint||void 0,children:s.jsxs("div",{className:"flex items-center gap-2 w-full",children:[s.jsx(Re,{type:"text",value:_&&a[v.field]?Jk(a[v.field]):a[v.field],onChange:k=>i({...a,[v.field]:k.target.value}),onFocus:()=>w&&l(!0),disabled:d,inputSize:"sm",className:"flex-1"}),w&&s.jsx("button",{type:"button",onClick:()=>l(k=>!k),className:"text-text-tertiary hover:text-text-primary","aria-label":o?"Hide account number":"Show account number",children:o?s.jsx(F2,{className:"w-4 h-4"}):s.jsx(al,{className:"w-4 h-4"})}),s.jsx(Fy,{state:e.fields[v.field]})]})}),s.jsx($n,{})]},v.field)}),c?s.jsxs("div",{className:"p-4 bg-surface-warningSubtle",children:[s.jsxs("div",{className:"flex items-start gap-2 mb-3",children:[s.jsx(zn,{className:"w-4 h-4 text-text-warning mt-0.5 shrink-0"}),s.jsxs("div",{className:"text-sm text-text-warning",children:[s.jsx("div",{className:"font-medium mb-1",children:"Confirm the change to your payout account"}),s.jsx("div",{className:"text-text-body",children:"Claims issued from now on will ask Takealot to pay into this account."})]})]}),s.jsx("div",{className:"flex flex-col gap-1 mb-3 pl-6",children:y.map(v=>{const w=v.field==="bank.account_number",_=Xa(e.fields[v.field]),k=a[v.field];return s.jsxs("div",{className:"text-sm text-text-body",children:[s.jsxs("span",{className:"text-text-secondary",children:[v.label,":"]})," ",s.jsx("span",{className:"line-through text-text-tertiary",children:_?w?Jk(_):_:"not set"})," ","â"," ",s.jsx("span",{className:"font-medium",children:k?w?Jk(k):k:"not set"})]},v.field)})}),s.jsxs("div",{className:"flex items-center gap-2 pl-6",children:[s.jsx(W,{onClick:b,disabled:d,intent:"brand",size:"sm",children:d?"Savingâ¦":"Yes, update banking"}),s.jsx(W,{onClick:()=>u(!1),disabled:d,intent:"neutral",size:"sm",children:"Cancel"})]})]}):s.jsxs("div",{className:"p-4 flex items-center gap-3",children:[s.jsx(W,{onClick:()=>u(!0),disabled:y.length===0||d,intent:"brand",size:"sm",children:"Save banking"}),f!==null&&Date.now()-f<4e3&&s.jsxs("span",{className:"inline-flex items-center gap-1 text-sm text-text-success",children:[s.jsx(Xt,{className:"w-4 h-4"})," Saved"]}),x&&s.jsx("span",{className:"text-sm text-text-error",children:x})]})]})}function sWe({dirty:e,saving:t,savedAt:n,err:r,onSave:a}){return s.jsxs("div",{className:"p-4 flex items-center gap-3",children:[s.jsx(W,{onClick:a,disabled:!e||t,intent:"brand",size:"sm",children:t?"Savingâ¦":"Save changes"}),n!==null&&Date.now()-n<4e3&&s.jsxs("span",{className:"inline-flex items-center gap-1 text-sm text-text-success",children:[s.jsx(Xt,{className:"w-4 h-4"})," Saved"]}),r&&s.jsx("span",{className:"text-sm text-text-error",children:r})]})}const aWe="[email protected]";function $3(e){const t=String(e??"").trim();return/^\d+$/.test(t)?`agent+${t}@${aWe.split("@")[1]}`:null}function Dq(e){const t=String(e||"").trim();return!t||/\s/.test(t)||t.includes("://")?!1:/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)}function L3(e){const t=String(e||"").trim();return!t||Dq(t)?!1:/^https?:\/\//i.test(t)||/^(www\.)?[\w.-]+\.[a-z]{2,}([/:].*)?$/i.test(t)}function uu(e){const t=String((e==null?void 0:e.username)||"").trim();if(t)return t;const n=String((e==null?void 0:e.url)||"").trim();return Dq(n)?n:""}function Bc(e){return String(e||"").trim().toLowerCase().replace(/[_-]+/g," ").replace(/\s+/g," ")}function iWe(e){return Bc(e).includes(",")}function F3(e,t){const n=$3(t);return!n||!e?!1:String(e).trim().toLowerCase()===n.toLowerCase()}const qx=Object.freeze([Object.freeze({key:"gadjet_agent",label:"Gadjet agent",url:"https://sellers.takealot.com",usernameMode:"agent_plus",hint:"Unattended Portal Actions. Locked to agent+{seller id}@gadjet.co.za; OTPs land in [email protected].",aliases:Object.freeze(["gadjet agent","portal actions","agent login"]),labelRe:/^(gadjet\s+)?agent$|^portal\s+actions$/,urlRe:null}),Object.freeze({key:"takealot_seller_portal",label:"Takealot Seller Portal",url:"https://sellers.takealot.com",usernameMode:null,hint:"Human AM login. Owner or marketplace email is fine.",aliases:Object.freeze(["ta seller portal","takealot seller portsl","takealot sellerportal"]),labelRe:/^(ta|takealot)\b.*\bseller\s*port/,urlRe:/sellers\.takealot\.com|seller\.takealot\.com|sellerportal\.takealot\.com/i}),Object.freeze({key:"takealot_ticket_centre",label:"Takealot Ticket Centre",url:"https://help.takealot.com",usernameMode:null,hint:"Seller Support tickets (help.takealot.com).",aliases:Object.freeze(["ticket centre","ticker centre","takealot ticket center","takealot seller support","takealot ticket centre"]),labelRe:/(ticket|ticker)\s*centr|seller\s*support/,urlRe:/help\.takealot\.com/i}),Object.freeze({key:"takealot_booking_portal",label:"Takealot Booking Portal",url:"https://takealot.za.adaptris.com/wbs/",usernameMode:null,hint:"Adaptris collection bookings for removal orders.",aliases:Object.freeze(["booking portal","adaptris"]),labelRe:/booking\s*portal|adaptris/,urlRe:/adaptris\.com/i}),Object.freeze({key:"amazon_seller_central",label:"Amazon Seller Central",url:"https://sellercentral.amazon.co.za",usernameMode:null,hint:"Manual AM login. SP-API connect stays under Integrations.",aliases:Object.freeze(["amazon seller portal","seller central"]),labelRe:/\bamazon\b.*\b(seller\s*(central|portal)|central)\b/,urlRe:/sellercentral\.amazon\./i}),Object.freeze({key:"two_ship",label:"2 Ship",url:null,usernameMode:null,hint:"Courier portal if this seller uses 2 Ship.",aliases:Object.freeze(["2ship","2-ship"]),labelRe:/^2\s*ship$/,urlRe:null})]);qx.find(e=>e.key==="gadjet_agent");qx.find(e=>e.key==="takealot_seller_portal");qx.find(e=>e.key==="takealot_ticket_centre");function Mq(e,t,n=null){if(!e||!t)return!1;if(t.usernameMode==="agent_plus"&&n&&F3(uu(e),n))return!0;const r=Bc(e.label);if(!r||iWe(r)&&r!==Bc(t.label))return!1;if(r===Bc(t.label)||(t.aliases||[]).some(i=>r===Bc(i))||t.labelRe&&t.labelRe.test(r))return!0;const a=String(e.url||"").trim();return!!(t.urlRe&&L3(a)&&t.urlRe.test(a))}function oWe(e,t=null){return e&&qx.find(n=>Mq(e,n,t))||null}function K$(e,t,n=null){var o;const r=Bc(e.label);let a=0;r===Bc(t.label)?a+=8:(t.aliases||[]).some(l=>r===Bc(l))?a+=4:(o=t.labelRe)!=null&&o.test(r)&&(a+=3),uu(e)&&(a+=2);const i=String(e.url||"").trim();return t.urlRe&&L3(i)&&t.urlRe.test(i)&&(a+=1),t.usernameMode==="agent_plus"&&F3(uu(e),n)&&(a+=5),a}function lWe(e,t=null,n=null){if(!e)return"empty";const r=uu(e);
906if((t==null?void 0:t.usernameMode)==="agent_plus"){const a=$3(n);return r?a&&!F3(r,n)?"wrong_login":"ready":"needs_username"}return r?"ready":"needs_username"}function cWe(e,t,n){if((e==null?void 0:e.usernameMode)==="agent_plus")return $3(n)||uu(t)||"";const r=uu(t);return r||""}function uWe(e,t){if(e!=null&&e.url)return e.url;const n=String((t==null?void 0:t.url)||"").trim();return L3(n)?n:""}function dWe(e,t={}){const n=t.sellerId??null,r=Array.isArray(e)?e:[],a=new Set,i=qx.map(l=>{const c=r.filter(d=>d&&!a.has(d.id)&&Mq(d,l,n));c.sort((d,h)=>{const f=x=>uu(x)?1:0,m=f(h)-f(d);return m||K$(h,l,n)-K$(d,l,n)});const u=c[0]||null;return u!=null&&u.id&&a.add(u.id),{key:l.key,template:l,credential:u,status:lWe(u,l,n),username:cWe(l,u,n),url:uWe(l,u),storedLogin:uu(u)||""}}),o=r.filter(l=>l&&!a.has(l.id));return{slots:i,extras:o}}function hWe(e,t){return dWe(e,{sellerId:t})}const fWe={empty:{label:"Waiting",className:"bg-surface-sunken text-text-secondary border-outline-subtle"},needs_username:{label:"Add login email",className:"bg-surface-warningSubtle text-text-warning border-outline-warning"},wrong_login:{label:"Wrong user",className:"bg-surface-warningSubtle text-text-warning border-outline-warning"},ready:{label:"Ready",className:"bg-surface-successSubtle text-text-success border-outline-success"}};function mWe({seller:e}){const[t,n]=p.useState(null),[r,a]=p.useState(null),i=p.useCallback(()=>{a(null),K.listCredentials(e.slug).then(n).catch(l=>a(String((l==null?void 0:l.message)||l)))},[e.slug]);p.useEffect(()=>{n(null),i()},[i]);const o=t?hWe(t,e.seller_id):null;return s.jsxs("div",{className:"space-y-3",children:[s.jsxs(V,{className:"p-4 flex items-start gap-3",children:[s.jsx("div",{className:"w-9 h-9 rounded-md bg-surface-sunken text-text-secondary flex items-center justify-center shrink-0",children:s.jsx(Bl,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-sm font-semibold text-text-primary flex items-center gap-2",children:["Portal credentials",s.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide text-text-secondary bg-surface-sunken border border-outline-subtle px-1.5 py-0.5 rounded",children:"Internal · admin only"})]}),s.jsxs("div",{className:"text-xs text-text-secondary mt-0.5",children:["Built-in logins for ",e.display_name,". Seller Portal is whoever AMs use by hand â owner email is fine. Gadjet agent is the unattended user; fill it when that Takealot login exists. Add another portal is only for extras not in this list. Encrypted at rest; never shown to the seller; never used by the AI. Revealing a password is audit-logged."]})]})]}),r&&s.jsx(V,{className:"p-3 text-xs text-text-error bg-surface-errorSubtle border-outline-error",children:r}),t===null?s.jsx("div",{className:"text-xs text-text-tertiary px-1",children:"Loadingâ¦"}):s.jsxs(s.Fragment,{children:[o.slots.map(l=>s.jsx(pWe,{slug:e.slug,slot:l,onChanged:i},l.key)),o.extras.length>0&&s.jsx("div",{className:"text-[11px] font-medium uppercase tracking-wide text-text-tertiary pt-2",children:"Other"}),o.extras.map(l=>s.jsx(xWe,{slug:e.slug,cred:l,onChanged:i},l.id)),s.jsx(gWe,{slug:e.slug,onSaved:i})]})]})}function pWe({slug:e,slot:t,onChanged:n}){var M,z,G,te;const r=t.template,[a,i]=p.useState(t.username),[o,l]=p.useState(t.url),[c,u]=p.useState(((M=t.credential)==null?void 0:M.notes)||""),[d,h]=p.useState(""),[f,m]=p.useState(!1),[x,g]=p.useState(!1),[y,b]=p.useState(null),[v,w]=p.useState(null),[_,k]=p.useState(!1),[j,N]=p.useState(!1);p.useEffect(()=>{var re;i(t.username),l(t.url),u(((re=t.credential)==null?void 0:re.notes)||""),h(""),m(!1),b(null),w(null)},[(z=t.credential)==null?void 0:z.id,t.username,t.url,(G=t.credential)==null?void 0:G.notes]),p.useEffect(()=>{if(v==null)return;const re=setTimeout(()=>w(null),6e4);return()=>clearTimeout(re)},[v]);const E=!!r.url,A=t.status==="wrong_login",C=!t.credential||f||A,T=a.trim()!==(t.username||""),S=!E&&o.trim()!==(t.url||""),O=c.trim()!==(((te=t.credential)==null?void 0:te.notes)||"").trim(),R=t.credential,I=R?R.label!==r.label||String(R.username||"").trim()!==a.trim()||E&&String(R.url||"").trim()!==String(r.url||"").trim():!1,$=C&&d.length>0||!C&&(T||S||O||I);async function P(){if(a)try{await navigator.clipboard.writeText(a),N(!0),setTimeout(()=>N(!1),2e3)}catch{}}async function F(){var re;g(!0),b(null);try{await K.saveCredential(e,{id:(re=t.credential)==null?void 0:re.id,label:r.label,username:(r.usernameMode==="agent_plus"&&t.username||a).trim()||void 0,url:(E?r.url:o.trim())||void 0,notes:c.trim()||void 0,secret:C?d:void 0}),h(""),m(!1),n()}catch(L){b(String((L==null?void 0:L.message)||L))}finally{g(!1)}}async function Z(){if(t.credential){g(!0),b(null);try{const re=await K.revealCredential(e,t.credential.id);w(re.secret)}catch(re){b(String((re==null?void 0:re.message)||re))}finally{g(!1)}}}async function D(){if(v!=null)try{await navigator.clipboard.writeText(v),k(!0),setTimeout(()=>k(!1),2e3)}catch{}}async function H(){if(t.credential){g(!0),b(null);try{await K.deleteCredential(e,t.credential.id),n()}catch(re){b(String((re==null?void 0:re.message)||re)),g(!1)}}}const Y=fWe[t.status];return s.jsx(V,{children:s.jsxs("div",{className:"p-4 space-y-3",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:r.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-0.5",children:r.hint})]}),s.jsx("span",{className:B("text-[10px] font-medium uppercase tracking-wide border px-1.5 py-0.5 rounded shrink-0",Y.className),children:Y.label})]}),s.jsx(ny,{label:"URL",children:E?s.jsxs("a",{href:r.url,target:"_blank",rel:"noreferrer",className:"text-xs text-text-brand inline-flex items-center gap-1 hover:underline break-all",children:[r.url,s.jsx(Qt,{className:"w-3 h-3 shrink-0"})]}):s.jsx(Re,{type:"text",value:o,onChange:re=>l(re.target.value),disabled:x,inputSize:"sm",placeholder:"Login URL"})}),s.jsx(ny,{label:"Username",children:r.usernameMode==="agent_plus"?s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("div",{className:"text-xs text-text-primary pt-1.5 break-all font-mono",children:a||"agent+{seller id}@gadjet.co.za"}),a?s.jsxs(W,{onClick:P,variant:"link",intent:"neutral",size:"sm",children:[s.jsx(bi,{className:"w-3.5 h-3.5"})," ",j?"Copied":"Copy"]}):null]}),A&&t.storedLogin?s.jsxs("div",{className:"text-xs text-text-warning",children:["This slot still has ",t.storedLogin,". It only accepts"," ",a,". Paste that userâs password to correct it."]}):null,t.status==="empty"&&r.usernameMode==="agent_plus"?s.jsx("div",{className:"text-xs text-text-secondary",children:"Create this user on Takealot, then paste its password here. Seller Portal can keep the owner login."}):null]}):s.jsx(Re,{type:"text",value:a,onChange:re=>i(re.target.value),disabled:x,inputSize:"sm",placeholder:"Username / email"})}),s.jsx(ny,{label:"Password",children:t.credential&&!f&&!A?s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"text-xs font-mono text-text-tertiary",children:v??`â¢â¢â¢â¢â¢â¢â¢â¢ (set · ${t.credential.secret_fingerprint})`}),v==null?s.jsxs(W,{onClick:Z,disabled:x,variant:"outline",intent:"neutral",size:"sm",children:[s.jsx(al,{className:"w-3.5 h-3.5"})," ",x?"â¦":"Reveal"]}):s.jsxs(s.Fragment,{children:[s.jsxs(W,{onClick:()=>w(null),variant:"outline",intent:"neutral",size:"sm",children:[s.jsx(F2,{className:"w-3.5 h-3.5"})," Hide"]}),s.jsxs(W,{onClick:D,variant:"link",intent:"neutral",size:"sm",children:[s.jsx(bi,{className:"w-3.5 h-3.5"})," ",_?"Copied":"Copy"]})]}),s.jsx(W,{onClick:()=>m(!0),variant:"link",intent:"neutral",size:"sm",children:"Replace"})]}):s.jsxs("div",{className:"space-y-1",children:[s.jsx(Re,{type:"password",value:d,onChange:re=>h(re.target.value),disabled:x,inputSize:"sm",placeholder:A?"Gadjet agent password":"Password",className:"font-mono"}),t.credential&&!A&&s.jsx(W,{onClick:()=>{m(!1),h("")},variant:"link",intent:"neutral",size:"sm",children:"Cancel replace"})]})}),s.jsx(ny,{label:"Notes",children:s.jsx(Ui,{value:c,onChange:re=>u(re.target.value),disabled:x,rows:2,inputSize:"sm",placeholder:"Handling quirks, 2FA owner â not the password"})}),y&&s.jsx("div",{className:"text-xs text-text-error bg-surface-errorSubtle border border-outline-error roun
906ded px-2 py-1",children:y}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(W,{onClick:F,disabled:x||!$,intent:"brand",size:"sm",children:x?"Savingâ¦":t.credential?"Save changes":"Save credential"}),t.credential&&s.jsxs(W,{onClick:H,disabled:x,variant:"link",intent:"destructive",size:"sm",children:[s.jsx(us,{className:"w-3.5 h-3.5"})," Clear"]})]})]})})}function ny({label:e,children:t}){return s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx("span",{className:"w-20 shrink-0 text-xs text-text-tertiary pt-1.5",children:e}),s.jsx("div",{className:"flex-1 min-w-0",children:t})]})}function xWe({slug:e,cred:t,onChanged:n}){const[r,a]=p.useState(null),[i,o]=p.useState(!1),[l,c]=p.useState(null),[u,d]=p.useState(!1),[h,f]=p.useState(!1);p.useEffect(()=>{if(r==null)return;const y=setTimeout(()=>a(null),6e4);return()=>clearTimeout(y)},[r]);async function m(){o(!0),c(null);try{const y=await K.revealCredential(e,t.id);a(y.secret)}catch(y){c(String((y==null?void 0:y.message)||y))}finally{o(!1)}}async function x(){if(r!=null)try{await navigator.clipboard.writeText(r),d(!0),setTimeout(()=>d(!1),2e3)}catch{}}async function g(){o(!0),c(null);try{await K.deleteCredential(e,t.id),n()}catch(y){c(String((y==null?void 0:y.message)||y)),o(!1)}}return s.jsxs(V,{children:[s.jsxs("div",{className:"p-4 flex items-start gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0 space-y-1.5",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:t.label}),t.username&&s.jsx(Qk,{label:"Username",value:t.username}),t.url&&s.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[s.jsx("span",{className:"w-20 shrink-0 text-text-tertiary",children:"URL"}),/^https?:\/\//i.test(t.url)?s.jsxs("a",{href:t.url,target:"_blank",rel:"noreferrer",className:"flex-1 break-all text-text-brand inline-flex items-center gap-1 hover:underline",children:[t.url,s.jsx(Qt,{className:"w-3 h-3 shrink-0"})]}):s.jsx("span",{className:"flex-1 break-all text-text-body",children:t.url})]}),s.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[s.jsx("span",{className:"w-20 shrink-0 text-text-tertiary",children:"Password"}),s.jsx("span",{className:"flex-1 break-all font-mono text-text-body",children:r??s.jsxs("span",{className:"text-text-tertiary",children:["â¢â¢â¢â¢â¢â¢â¢â¢ (set · ",t.secret_fingerprint,")"]})})]}),t.notes&&s.jsx(Qk,{label:"Notes",value:t.notes}),s.jsx(Qk,{label:"Updated",value:t.updated_at?Ca(t.updated_at):"â"})]}),s.jsxs("div",{className:"flex flex-col items-end gap-1.5 shrink-0",children:[r==null?s.jsxs(W,{onClick:m,disabled:i,variant:"outline",intent:"neutral",size:"sm",children:[s.jsx(al,{className:"w-3.5 h-3.5"})," ",i?"â¦":"Reveal"]}):s.jsxs(s.Fragment,{children:[s.jsxs(W,{onClick:()=>a(null),variant:"outline",intent:"neutral",size:"sm",children:[s.jsx(F2,{className:"w-3.5 h-3.5"})," Hide"]}),s.jsxs(W,{onClick:x,variant:"link",intent:"neutral",size:"sm",children:[s.jsx(bi,{className:"w-3.5 h-3.5"})," ",u?"Copied":"Copy"]})]}),h?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx(W,{onClick:g,disabled:i,intent:"destructive",size:"sm",children:i?"â¦":"Confirm"}),s.jsx(W,{onClick:()=>f(!1),variant:"link",intent:"neutral",size:"sm",children:"Cancel"})]}):s.jsxs(W,{onClick:()=>f(!0),disabled:i,variant:"link",intent:"destructive",size:"sm",children:[s.jsx(us,{className:"w-3.5 h-3.5"})," Delete"]})]})]}),l&&s.jsx("div",{className:"border-t border-outline-faint px-4 py-2 text-xs text-text-error bg-surface-errorSubtle",children:l})]})}function gWe({slug:e,onSaved:t}){const[n,r]=p.useState(!1),[a,i]=p.useState(""),[o,l]=p.useState(""),[c,u]=p.useState(""),[d,h]=p.useState(""),[f,m]=p.useState(""),[x,g]=p.useState(!1),[y,b]=p.useState(null);function v(){i(""),l(""),u(""),h(""),m(""),b(null)}async function w(){const _=oWe({label:a.trim(),username:o.trim(),url:c.trim()});if(_){b(`That's the built-in ${_.label} slot. Fill the card above instead of adding another.`);return}g(!0),b(null);try{await K.saveCredential(e,{label:a.trim(),username:o.trim()||void 0,url:c.trim()||void 0,notes:d.trim()||void 0,secret:f}),v(),r(!1),t()}catch(k){b(String((k==null?void 0:k.message)||k))}finally{g(!1)}}return n?s.jsxs(V,{className:"p-4 space-y-2",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Other portal"}),s.jsx("div",{className:"text-xs text-text-secondary",children:"For a supplier or courier that is not in the list above. Built-in names (Seller Portal, Gadjet agent, Ticket Centre, â¦) fill those cards â they cannot be added twice."}),s.jsx(Re,{type:"text",value:a,onChange:_=>i(_.target.value),disabled:x,inputSize:"sm",maxLength:120,placeholder:"Label"}),s.jsx(Re,{type:"text",value:o,onChange:_=>l(_.target.value),disabled:x,inputSize:"sm",placeholder:"Username / email"}),s.jsx(Re,{type:"text",value:c,onChange:_=>u(_.target.value),disabled:x,inputSize:"sm",placeholder:"Login URL"}),s.jsx(Re,{type:"password",value:f,onChange:_=>m(_.target.value),disabled:x,inputSize:"sm",placeholder:"Password /
906secret",className:"font-mono"}),s.jsx(Ui,{value:d,onChange:_=>h(_.target.value),disabled:x,rows:2,inputSize:"sm",placeholder:"Notes (optional)"}),y&&s.jsx("div",{className:"text-xs text-text-error bg-surface-errorSubtle border border-outline-error rounded px-2 py-1",children:y}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(W,{onClick:w,disabled:x||a.trim().length===0||f.length===0,intent:"brand",size:"sm",children:x?"Savingâ¦":"Save credential"}),s.jsx(W,{onClick:()=>{v(),r(!1)},variant:"link",intent:"neutral",size:"sm",children:"Cancel"})]})]}):s.jsxs(W,{onClick:()=>r(!0),variant:"outline",intent:"neutral",size:"sm",children:[s.jsx(In,{className:"w-3.5 h-3.5"})," Add another portal"]})}function Qk({label:e,value:t}){return s.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[s.jsx("span",{className:"w-20 shrink-0 text-text-tertiary",children:e}),s.jsx("span",{className:"flex-1 break-words text-text-body",children:t})]})}function yWe({slug:e}){const[t,n]=p.useState(null),[r,a]=p.useState(null),[i,o]=p.useState(!1),[l,c]=p.useState(""),[u,d]=p.useState(!1),[h,f]=p.useState(null);p.useEffect(()=>{let b=!0;return n(null),a(null),K.tcsConnection(e).then(v=>b&&n(v)).catch(v=>b&&a(String((v==null?void 0:v.message)||v))),()=>{b=!1}},[e]);const m=!!(t!=null&&t.connected);async function x(){d(!0),f(null);try{const b=await K.tcsConnect(e,l.trim());n(b),c(""),o(!1)}catch(b){f(String((b==null?void 0:b.message)||b))}finally{d(!1)}}async function g(){d(!0),f(null);try{n(await K.tcsDisconnect(e))}catch(b){f(String((b==null?void 0:b.message)||b))}finally{d(!1)}}const y=t==null&&!r?"Checkingâ¦":r?"Couldn't load Takealot Courier status â try refreshing.":m?`Connected${t.account_name?` · ${t.account_name}`:""} â book inbound and DC returns on this seller's TFS account.`:"Paste the seller's Takealot Courier API key to book collections from Gadjet. Charged on their TCS account, not the Gadjet courier wallet.";return s.jsxs(V,{children:[s.jsxs("div",{className:"p-4 flex items-center gap-3",children:[s.jsx("div",{className:B("w-9 h-9 rounded-md flex items-center justify-center shrink-0",m?"bg-surface-successSubtle text-text-success":"bg-surface-sunken text-text-secondary"),children:m?s.jsx(Xt,{className:"w-4 h-4"}):s.jsx(qi,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Takealot Courier (TFS)"}),s.jsx("div",{className:"text-xs text-text-secondary",children:y})]}),m?s.jsx("span",{className:"text-xs font-medium text-text-success bg-surface-successSubtle border border-outline-success px-2 py-0.5 rounded-full",children:"Connected"}):s.jsx(W,{onClick:()=>o(!0),disabled:t==null||!!r,intent:"brand",size:"sm",children:"Connect"})]}),(i||m)&&s.jsxs("div",{className:"border-t border-outline-faint px-4 py-3 bg-surface-subtle space-y-2",children:[i&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-xs text-text-body",children:["Generate a key in ",s.jsx("span",{className:"font-medium",children:"takealot.shiplogic.com â Settings â API Keys"}),". We validate it against the live TCS account and encrypt it at rest."]}),s.jsx(Ui,{value:l,onChange:b=>c(b.target.value),disabled:u,rows:2,placeholder:"Paste the Takealot Courier API keyâ¦",inputSize:"sm",className:"font-mono text-xs"})]}),h&&s.jsx("div",{className:"text-xs text-text-error bg-surface-errorSubtle border border-outline-error rounded px-2 py-1",children:h}),s.jsxs("div",{className:"flex items-center gap-2",children:[i&&s.jsxs(s.Fragment,{children:[s.jsx(W,{onClick:x,disabled:u||l.trim().length<16,intent:"brand",size:"sm",children:u?"Verifyingâ¦":"Save key"}),s.jsx(W,{onClick:()=>{o(!1),c(""),f(null)},variant:"link",intent:"neutral",size:"sm",children:"Cancel"})]}),m&&!i&&s.jsx(W,{onClick:g,disabled:u,variant:"link",intent:"neutral",size:"sm",children:"Disconnect"})]})]})]})}const bWe=5e3,vWe=120*1e3;function wWe({slug:e}){const[t,n]=p.useState(null),[r,a]=p.useState(!1),[i,o]=p.useState(null),[l,c]=p.useState(!1),[u,d]=p.useState(!1),[h,f]=p.useState(null),[m,x]=p.useState(!1);p.useEffect(()=>{let v=!0;return a(!1),n(null),o(null),K.makroConnectStatus(e).then(w=>
906{v&&(w.email&&w.status!=="absent"&&n({email:w.email,sellerSlug:w.seller_slug||"",makroSellerId:w.makro_seller_id||null,connected:w.status==="connected"}),a(!0))}).catch(w=>{v&&(o(w instanceof Error?w.message:"Could not load Makro."),a(!0))}),()=>{v=!1}},[e]),p.useEffect(()=>{if(!u)return;let v=!1;const w=Date.now()+vWe;async function _(){if(!v){try{const k=await K.makroConnectCheck(e);if(v)return;if(k.status==="connected"&&k.email){d(!1),n({email:k.email,sellerSlug:k.seller_slug||"",makroSellerId:k.makro_seller_id||null,connected:!0}),f(null);return}f(k.message||"Waiting for Makro to recognise the new user.")}catch(k){if(v)return;d(!1),f(k instanceof Error?k.message:"Makro connect failed.");return}if(Date.now()>=w){d(!1),f("Still waiting. Add the user on Makro if you have not yet, then check again.");return}window.setTimeout(_,bWe)}}return _(),()=>{v=!0}},[u,e]);async function g(){c(!0),o(null);try{const v=await K.makroConnectStart(e);n({email:v.email,sellerSlug:v.seller_slug,makroSellerId:v.makro_seller_id||null,connected:v.status==="connected"})}catch(v){o(v instanceof Error?v.message:"Could not start Makro connect.")}finally{c(!1)}}async function y(){t&&(await navigator.clipboard.writeText(t.email),x(!0),window.setTimeout(()=>x(!1),1500))}const b=!!(t!=null&&t.connected);return s.jsx(V,{children:s.jsxs("div",{className:"p-4 flex items-start gap-3",children:[s.jsx("div",{className:B("w-9 h-9 rounded-md flex items-center justify-center shrink-0",b?"bg-surface-successSubtle text-text-success":"bg-surface-sunken text-text-secondary"),children:b?s.jsx(Xt,{className:"w-4 h-4"}):s.jsx(sx,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0 space-y-2",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Makro"}),!r&&s.jsx("p",{className:"text-xs text-text-secondary",children:"Checkingâ¦"}),i&&s.jsx("p",{className:"text-xs text-text-error",children:i}),r&&!t&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-xs text-text-secondary",children:"Connect by adding a Gadjet admin user on the Makro Seller Portal. You do not share your Makro password."}),s.jsxs(W,{onClick:()=>void g(),disabled:l,intent:"brand",size:"sm",children:[l&&s.jsx(_e,{className:"mr-2 h-4 w-4 animate-spin"}),"Connect Makro"]})]}),t&&b&&s.jsxs("p",{className:"text-xs text-text-secondary",children:["Connected as ",t.email,t.makroSellerId?` · seller ${t.makroSellerId}`:"",". Orders, returns, and listings for this store are read from that portal session. Keep the Admin user on Makro."]}),t&&!b&&s.jsxs("div",{className:"space-y-2 text-xs text-text-secondary",children:[s.jsx("p",{children:"On seller.makro.co.za go to Manage Profile â Manage Users â Add New User. Role Admin. Name can be Gadjet."}),s.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-outline-subtle bg-surface px-2 py-1.5",children:[s.jsx("span",{className:"w-12 shrink-0 text-text-tertiary",children:"Email"}),s.jsx("code",{className:"min-w-0 flex-1 truncate text-text-primary",children:t.email}),s.jsxs("button",{type:"button",onClick:()=>void y(),className:"inline-flex items-center gap-1 text-text-brand",children:[m?s.jsx(Xt,{className:"h-3.5 w-3.5"}):s.jsx(bi,{className:"h-3.5 w-3.5"}),m?"Copied":"Copy"]})]}),s.jsx("p",{children:"Phone number is required. Enter the cellphone already on your Takealot account, as 10 digits starting with 0 and with no spaces. The sign-in code still arrives on the email above."}),h&&s.jsx("p",{className:"text-text-primary",children:h}),s.jsxs(W,{onClick:()=>d(!0),disabled:u,intent:"brand",size:"sm",children:[u&&s.jsx(_e,{className:"mr-2 h-4 w-4 animate-spin"}),u?"Checking Makroâ¦":"I've added the user"]})]})]})]})})}const H$=[{dow:1,label:"Mon"},{dow:2,label:"Tue"},{dow:3,label:"Wed"},{dow:4,label:"Thu"},{dow:5,label:"Fri"}],_We=[{key:"replenishment",label:"Replenishment Shipment",mode:"weekly"},{key:"listing_upgrade",label:"Listing Upgrade",mode:"weekly"},{key:"promotion",label:"Promotion",mode:"weekly"},{key:"listing_creation",label:"Listing Creation",mode:"weekly"},{key:"stock_recon",label:"Stock Recon",mode:"monthly_first_business_day"},{key:"overview_pdf",label:"Morning Overview",mode:"weekly"}];function kWe(e){return e.mode==="monthly_first_business_day"?"Monthly · 1st business day":e.mode==="biweekly"?"Every other week · Monday":null}function jWe(e){return e.startsWith("amazon")?s.jsxs(s.Fragment,{children:["Tick the days each Amazon routine should run for this store. A ticked cell creates a recurring task for the account's AM."," ",s.jsx("span",{className:"font-medium text-text-body",children:"FBA Replen"})," and"," ",s.jsx("span",{className:"font-medium text-text-body",children:"Listing Creation"})," are weekly;"," ",s.jsx("span",{className:"font-medium text-text-body",children:"Promotion Application"}
906)," ","is every other Monday; Stock Recon is monthly, on the 1st business day."]}):s.jsxs(s.Fragment,{children:["Tick the days each routine task should run. A ticked cell creates a"," ",s.jsx("span",{className:"font-medium text-text-body",children:"weekly-recurring"})," task of that type for the account's AM; untick to stop it. Stock Recon runs monthly, on the 1st business day."]})}function NWe({seller:e}){const[t,n]=p.useState(null),[r,a]=p.useState(_We),[i,o]=p.useState(e.marketplace||"takealot"),[l,c]=p.useState(null),[u,d]=p.useState(null),h=p.useCallback(()=>{c(null),K.managedAccountSchedule(e.slug).then(x=>{n(new Set(x.cells.map(g=>`${g.task_key}:${g.day_of_week}`))),x.catalogue.length&&a(x.catalogue),x.marketplace&&o(x.marketplace)}).catch(x=>c(String((x==null?void 0:x.message)||x)))},[e.slug]);p.useEffect(()=>{n(null),h()},[h]);async function f(x,g){if(!t)return;const y=`${x}:${g}`,b=!t.has(y),v=new Set(t);b?v.add(y):v.delete(y),n(v),d(y),c(null);try{await K.setScheduleCell(e.slug,{task_key:x,day_of_week:g,checked:b})}catch(w){c(String((w==null?void 0:w.message)||w)),h()}finally{d(null)}}const m=(x,g,y)=>{const b=`${x}:${g}`;return s.jsx("div",{className:"inline-flex items-center justify-center",children:s.jsx(ei,{checked:!!t&&t.has(b),disabled:u===b||t===null,onCheckedChange:()=>f(x,g),"aria-label":y})})};return s.jsxs("div",{className:"space-y-2",children:[s.jsx(V,{className:"p-3 text-xs text-text-secondary",children:jWe(i)}),l&&s.jsx(V,{className:"p-3 text-xs text-text-error bg-surface-errorSubtle border-outline-error",children:l}),s.jsx(V,{className:"overflow-hidden",children:s.jsxs("table",{className:"w-full text-sm",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"text-xs text-text-secondary bg-surface-subtle",children:[s.jsx("th",{className:"text-left font-medium px-4 py-2",children:"Task"}),H$.map(x=>s.jsx("th",{className:"font-medium px-2 py-2 text-center w-16",children:x.label},x.dow))]})}),s.jsx("tbody",{className:"divide-y divide-outline-faint",children:t===null?s.jsx("tr",{children:s.jsx("td",{colSpan:6,className:"px-4 py-6 text-center text-xs text-text-tertiary",children:"Loadingâ¦"})}):r.map(x=>{const g=kWe(x),y=x.mode==="weekly";return s.jsxs("tr",{children:[s.jsxs("td",{className:"px-4 py-2.5",children:[s.jsx("div",{className:"font-medium text-text-primary",children:x.label}),g&&s.jsx("div",{className:"text-xs text-text-tertiary",children:g})]}),y?H$.map(b=>s.jsx("td",{className:"px-2 py-2.5 text-center",children:m(x.key,b.dow,`${x.label} on ${b.label}`)},b.dow)):s.jsx("td",{colSpan:5,className:"px-2 py-2.5 text-center",children:m(x.key,0,`${x.label} ${g||"toggle"}`)})]},x.key)})})]})})]})}function SWe({seller:e,tab:t,onSellerChange:n,isAdminRole:r,isSuperAdmin:a}){return t==="integrations"?s.jsx(MWe,{seller:e,isAdminRole:r}):t==="billing"?s.jsx(eWe,{seller:e}):t==="managed"||t==="credentials"?r?s.jsx($q,{seller:e,onSellerChange:n,isSuperAdmin:a}):s.jsx(V,{className:"p-4 text-sm text-text-warning bg-surface-warningSubtle border-outline-warning",children:"The Managed Account page is restricted to the Gadjet account-management team."}):t==="danger"?s.jsx(UWe,{seller:e,isSuperAdmin:a,onSellerChange:n}):s.jsx(DWe,{seller:e,onSellerChange:n,isSuperAdmin:a})}function $q({seller:e,onSellerChange:t,isSuperAdmin:n,identityEditable:r=!1,hideIntro:a=!1}){const[i,o]=p.useState(null),[l,c]=p.useState(null),u=p.useCallback(()=>{c(null),K.managedAccountOverview(e.slug).then(o).catch(d=>c(String((d==null?void 0:d.message)||d)))},[e.slug]);return p.useEffect(()=>{o(null),u()},[u]),s.jsxs("div",{className:"space-y-4",children:[!a&&s.jsxs(V,{className:"p-4 flex items-start gap-3",children:[s.jsx("div",{className:"w-9 h-9 rounded-md bg-surface-sunken text-text-secondary flex items-center justify-center shrink-0",children:s.jsx(xf,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-sm font-semibold text-text-primary flex items-center gap-2",children:["Managed Account",s.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide text-text-secondary bg-surface-sunken border border-outline-subtle px-1.5 py-0.5 rounded",children:"Internal · admin only"})]}),s.jsxs("div",{className:"text-xs text-text-secondary mt-0.5",children:["Everything the Gadjet team needs to operate ",e.display_name,": account facts, contacts & billing, and the portal credentials you hold on their behalf."]})]})]}),s.jsxs("section",{children:[s.jsx(uh,{children:"Account"}),s.jsxs(V,{children:[r&&s.jsxs(s.Fragment,{children:[s.jsx(Gn,{label:"Name",children:s.jsx(CWe,{seller:e,onSellerChange:t})}),s.jsx($n,{})]}),s.jsx(Gn,{label:"Legal name",children:s.jsx("span",{className:"text-sm text-text-secondary",children:e.legal_name??"â"})}),s.jsx($n,{}),s.jsx(Gn,{label:"Slug",children:s.jsx("code",{className:"text-xs px-1.5 py-0.5 rounded bg-surface-sunken text-text-body font-mono",children:e.slug})}),s.jsx($n,{}),s.jsx(Gn,{label:"Status",children:r?s.jsx(Bq,{slug:e.slug,status:e.status,onChange:d=>t({...e,status:d})}):s.jsx(GS,{status:e.status})}),s.jsx($n,{}),s.jsx(Gn,{label:"Owner",hint:"The customer. A Gadjet AM is never the owner of a store.",children:s.jsx(Lq,{seller:e})}),s.jsx($n,{}),s.jsx(Gn,{label:"Account manager",hint:n?"Who the sidebar groups this store under. Reassigning updates the AM grant, the primary advisor, and this label together.":"Gadjet AM for this store.",children:n&&i?s.jsx(Fq,{seller:e,advisors:i.advisors,availableAms:i.available_ams,onSellerChange:t,onReloadOverview:u}):s.jsx("span",{className:"text-sm text-text-secondary",children:e.account_owner_label||e.account_owner||"â"})}),s.jsx($n,{}),s.jsx(Gn,{label:"Onboarded",hint:"When the store was first connected.",children:s.jsx("span",{className:"text-sm text-text-secondary",children:e.onboarded_at?cn(e.onboarded_at):"â"})}),s.jsx($n,{}),s.jsx(Gn,{label:"Start of management",hint:"When they came under Gadjet management. AM-editable.",children:s.jsx(AWe,{seller:e,onSellerChange:t})})]}),!r&&s.jsxs("p",{className:"text-xs text-text-tertiary mt-1 px-1",children:["Edit the name & status on the"," ",s.jsx("a",{className:"text-text-brand hover:underline",href:`/settings/stores/${e.slug}`,children:"Store"})," ","tab."]})]}),s.jsxs("section",{children:[s.jsx(uh,{children:"Contacts & billing"}),l?s.jsx(V,{className:"p-3 text-xs text-text-error bg-surface-errorSubtle border-outline-error",children:l}):i===null?s.jsx("div",{className:"text-xs text-text-tertiary px-1",children:"Loadingâ¦"}):s.jsxs(V,{children:[s.jsx(Gn,{label:"Subscription",children:i.account?s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(GS,{status:i.account.subscription_status}),s.jsx("span",{className:"text-xs text-text-tertiary capitalize",children:i.account.account_type.replace(/_/g," ")})]}):s.jsx("span",{className:"text-sm text-text-secondary",children:"No account linked"})}),s.jsx($n,{}),s.jsx(Gn,{label:"Account managers",hint:n?"Primary is set via Account manager above. Secondaries listed here.":"From the account's advisors.",children:s.jsx(V$,{people:i.advisors,empty:"No AM assigned"})}),s.jsx($n,{}),s.jsx(Gn,{label:"Seller team",hint:"Users with access to this account.",children:s.jsx(V$,{people:i.members,empty:"No seller-side users yet"})})]})]}),s.jsxs("section",{children:[s.jsx(uh,{children:"Standard tasks"}),s.jsx(NWe,{seller:e})]}),s.jsxs("section",{children:[s.jsx(uh,{children:"Team notes"}),s.jsx(OWe,{seller:e})]}),s.jsxs("section",{children:[s.jsx(uh,{children:"Credentials"}),s.jsx(mWe,{seller:e})]}),n&&e.is_managed&&s.jsxs("section",{children:[s.jsx(uh,{children:"Leave managed retainer"}),s.jsx(Uq,{seller:e,onSellerChange:t})]})]})}function CWe({seller:e,onSellerChange:t}
906){const[n,r]=p.useState(e.display_name),[a,i]=p.useState(!1),[o,l]=p.useState(null);p.useEffect(()=>{r(e.display_name)},[e.display_name]);const c=n.trim()!==e.display_name&&n.trim().length>0;async function u(){i(!0),l(null);try{const d=await K.patchSeller(e.slug,{display_name:n.trim()});t({...e,display_name:d.display_name})}catch(d){l(String((d==null?void 0:d.message)||d))}finally{i(!1)}}return s.jsxs("div",{className:"flex items-center gap-2 w-full justify-end flex-wrap",children:[s.jsx(Re,{type:"text",value:n,onChange:d=>r(d.target.value),disabled:a,inputSize:"sm",maxLength:120,className:"flex-1 min-w-[8rem]"}),s.jsx(W,{onClick:u,disabled:!c||a,intent:"brand",size:"sm",children:a?"Savingâ¦":"Save"}),o&&s.jsx("span",{className:"text-xs text-text-error",children:o})]})}function EWe(e){const t=new Date(`${e}T00:00:00`);if(Number.isNaN(t.getTime()))return null;const n=new Date;let r=(n.getFullYear()-t.getFullYear())*12+(n.getMonth()-t.getMonth());if(n.getDate()<t.getDate()&&(r-=1),r<0)return"starts in future";if(r<1)return"under 1 mo · managed";const a=Math.floor(r/12),i=r%12,o=[];return a&&o.push(`${a} yr`),i&&o.push(`${i} mo`),`${o.join(" ")} · managed`}function AWe({seller:e,onSellerChange:t}){const[n,r]=p.useState(e.management_started_at??""),[a,i]=p.useState(!1),[o,l]=p.useState(null);p.useEffect(()=>{r(e.management_started_at??"")},[e.management_started_at]);const c=(n||null)!==(e.management_started_at||null);async function u(){i(!0),l(null);try{const h=await K.setManagementStartDate(e.slug,n||null);t({...e,management_started_at:h.management_started_at})}catch(h){l(String((h==null?void 0:h.message)||h))}finally{i(!1)}}const d=e.management_started_at?EWe(e.management_started_at):null;return s.jsxs("div",{className:"flex items-center gap-2 justify-end flex-wrap",children:[d&&s.jsx("span",{className:"text-xs text-text-tertiary whitespace-nowrap",children:d}),s.jsx("input",{type:"date",value:n,onChange:h=>r(h.target.value),disabled:a,className:"text-sm px-2 py-1 rounded-md border border-outline-subtle bg-surface-subtle focus:bg-surface focus:outline-none focus:border-outline-brand focus-visible:shadow-focus"}),s.jsx(W,{onClick:u,disabled:!c||a,intent:"brand",size:"sm",children:a?"Savingâ¦":"Save"}),o&&s.jsx("span",{className:"text-xs text-text-error",children:o})]})}function TWe(e){return e.toLowerCase().trim().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"").replace(/^([0-9])/,"n$1").slice(0,64)}function OWe({seller:e}){const[t,n]=p.useState(null),[r,a]=p.useState(null),i=p.useCallback(()=>{a(null),K.managedAccountNotes(e.slug).then(n).catch(o=>a(String((o==null?void 0:o.message)||o)))},[e.slug]);return p.useEffect(()=>{n(null),i()},[i]),s.jsxs("div",{className:"space-y-3",children:[s.jsxs(V,{className:"p-3 text-xs text-text-secondary",children:["Visible to the Gadjet team and"," ",s.jsx("span",{className:"font-medium text-text-body",children:"fed to the AI"})," when you chat about ",e.display_name,` â never shown in the seller's own chat. Keep them short and factual (e.g. "ships stock Mondays only").`]}),r&&s.jsx(V,{className:"p-3 text-xs text-text-error bg-surface-errorSubtle border-outline-error",children:r}),t===null?s.jsx("div",{className:"text-xs text-text-tertiary px-1",children:"Loadingâ¦"}):t.length===0?s.jsx(V,{className:"p-4 text-sm text-text-secondary",children:"No team notes yet. Add the first one below."}):t.map(o=>s.jsx(IWe,{slug:e.slug,note:o,onChanged:i},o.key)),s.jsx(PWe,{slug:e.slug,onSaved:i})]})}function IWe({slug:e,note:t,onChanged:n}){const[r,a]=p.useState(!1),[i,o]=p.useState(!1),[l,c]=p.useState(null);async function u(){a(!0),c(null);try{await K.deleteTeamNote(e,t.key),n()}catch(d){c(String((d==null?void 0:d.message)||d)),a(!1)}}return s.jsxs(V,{className:"p-3",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-xs font-mono text-text-tertiary",children:t.key}),s.jsx("div",{className:"text-sm text-text-body mt-0.5 break-words whitespace-pre-wrap",children:t.value})]}),i?s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[s.jsx(W,{onClick:u,disabled:r,intent:"destructive",size:"sm",children:r?"â¦":"Delete"}),s.jsx(W,{onClick:()=>o(!1),variant:"link",intent:"neutral",size:"sm",children:"Cancel"})]}):s.jsx("button",{onClick:()=>o(!0),disabled:r,className:"shrink-0 p-1 rounded text-text-tertiary hover:text-text-error hover:bg-surface-sunken",title:"Delete note","aria-label":"Delete note",children:s.jsx(us,{className:"w-3.5 h-3.5"})})]}),l&&s.jsx("div",{className:"text-xs text-text-error mt-1",children:l})]})}function PWe({slug:e,onSaved:t}){const[n,r]=p.useState(""),[a,i]=p.useState(""),[o,l]=p.useState(!1),[c,u]=
906p.useState(null),d=TWe(n),h=d.length>0&&a.trim().length>0&&!o;async function f(){l(!0),u(null);try{await K.saveTeamNote(e,{key:d,value:a.trim()}),r(""),i(""),t()}catch(m){u(String((m==null?void 0:m.message)||m))}finally{l(!1)}}return s.jsxs(V,{className:"p-4 space-y-2",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Add a note"}),s.jsx(Re,{type:"text",value:n,onChange:m=>r(m.target.value),disabled:o,inputSize:"sm",maxLength:80,placeholder:"Short label â e.g. shipping cadence"}),n&&s.jsxs("div",{className:"text-[10px] font-mono text-text-tertiary",children:["key: ",d||"â (needs a letter)"]}),s.jsx(Ui,{value:a,onChange:m=>i(m.target.value),disabled:o,rows:2,inputSize:"sm",maxLength:1024,placeholder:"e.g. Ships stock Mondays only; won't join promos discounting >15%."}),c&&s.jsx("div",{className:"text-xs text-text-error bg-surface-errorSubtle border border-outline-error rounded px-2 py-1",children:c}),s.jsxs(W,{onClick:f,disabled:!h,intent:"brand",size:"sm",children:[s.jsx(In,{className:"w-3.5 h-3.5"})," Add note"]})]})}function Lq({seller:e}){return e.store_owner_label?s.jsxs("span",{className:"text-sm text-text-secondary",children:[e.store_owner_label,e.store_owner_email?s.jsx("span",{className:"ml-1.5 text-xs text-text-tertiary",children:e.store_owner_email}):null]}):s.jsx("span",{className:"text-sm text-text-tertiary",children:"No customer owner linked"})}function uh({children:e}){return s.jsx("div",{className:"text-xs font-semibold uppercase tracking-wider text-text-tertiary mb-1.5 px-1",children:e})}function V$({people:e,empty:t}){return e.length?s.jsx("div",{className:"flex flex-col items-end gap-1",children:e.map((n,r)=>s.jsxs("div",{className:"text-sm",children:[s.jsx("span",{className:"text-text-body",children:n.display_name||n.email}),s.jsx("span",{className:"ml-1.5 text-xs text-text-tertiary capitalize",children:n.role})]},`${n.email}-${r}`))}):s.jsx("span",{className:"text-sm text-text-tertiary",children:t})}function RWe(e,t){var r;const n=(e.account_owner||"").trim();return n&&n!=="unassigned"?n:((r=t.find(a=>a.role==="primary"))==null?void 0:r.display_name)??""}function Fq({seller:e,advisors:t,availableAms:n,onSellerChange:r,onReloadOverview:a}){const i=t.find(j=>j.role==="primary"),o=(i==null?void 0:i.display_name)??"",l=RWe(e,t),c=!!(l&&o&&l!==o),u=c?o:l,[d,h]=p.useState(u),[f,m]=p.useState(!1),[x,g]=p.useState(null),[y,b]=p.useState(null);p.useEffect(()=>{h(u),b(null),g(null)},[u]);const v=[...n],w=(j,N)=>{j&&!v.some(E=>E.display_name===j)&&v.unshift({display_name:j,email:N})};w(o,(i==null?void 0:i.email)??o),w(l,l);const _=d.length>0&&d!==l;async function k(){m(!0),g(null),b(null);try{const j=await K.reassignAm(e.slug,d);b(j.message),a();try{const N=await K.seller(e.slug);r(N)}catch{}}catch(j){g(String((j==null?void 0:j.message)||j))}finally{m(!1)}}return s.jsxs("div",{className:"flex flex-col items-end gap-1 w-full",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("select",{value:d,onChange:j=>h(j.target.value),disabled:f,"aria-label":"Account manager",className:"text-sm px-2 py-1 rounded-md border border-outline-subtle bg-surface-subtle focus:bg-surface focus:outline-none focus:border-outline-brand focus-visible:shadow-focus",children:[!l&&s.jsx("option",{value:"",children:"Unassigned"}),v.map(j=>s.jsx("option",{value:j.display_name??"",children:j.display_name},j.email||j.display_name||""))]}),s.jsx(W,{onClick:k,disabled:!_||f,intent:"brand",size:"sm",children:f?"â¦":c?"Repair":"Reassign"})]}),c&&!y&&s.jsxs("span",{className:"text-xs text-text-warning",children:["Sidebar still shows ",e.account_owner_label||l,", but the advisor list says ",o,". Reassign to sync them."]}),y&&s.jsx("span",{className:"text-xs text-text-success",children:y}),x&&s.jsx("span",{className:"text-xs text-text-error",children:x})]})}function DWe({seller:e,onSellerChange:t,isSuperAdmin:n}){var b,v;const r=((v=(b=e.display_name)==null?void 0:b[0])==null?void 0:v.toUpperCase())??"?",[a,i]=p.useState(e.display_name),[o,l]=p.useState(!1),[c,u]=p.useState(null),[d,h]=p.useState(null),[f,m]=p.useState(null),x=p.useCallback(()=>{n&&K.managedAccountOverview(e.slug).then(m).catch(()=>m(null))},[n,e.slug]);p.useEffect(()=>{i(e.display_name)},[e.display_name]),p.useEffect(()=>{m(null),x()},[x]);const g=a.trim()!==e.display_name&&a.trim().length>0;async function y(){l(!0),h(null);try{const w=await K.patchSeller(e.slug,{display_name:a.trim()});t({...e,display_name:w.display_name}),u(Date.now())}catch(w){h(String((w==null?void 0:w.message)||w))}finally{l(!1)}}return s.jsxs(V,{children:[s.jsx(Gn,{label:"Logo",children:s.jsx("div",{className:"w-9 h-9 rounded-md bg-surface-brandSubtle text-text-brand flex items-center justify-center text-sm font-semibold",children:r})}),s.jsx($n,{}),s.jsx(Gn,{label:"Name",children:s.jsxs("div",{className:"flex items-center gap-2 w-full",children:[s.jsx(Re,{type:"text",value:a,onChange:w=>i(w.target.value),disabled:o,inputSize:"sm",maxLength:120,className:"flex-1"}),s.jsx(W,{onClick:y,disabled:!g||o,intent:"brand",size:"sm",children:o?"Savingâ¦":"Save"}),c&&Date.now()-c<4e3&&s.jsx(Xt,{className:"w-4 h-4 text-text-success"})]})}),d&&s.jsx("div",{className:"px-4 py-2 text-xs text-text-error bg-surface-errorSubtle border-t border-outline-error",children:d}),s.jsx($n,{}),s.jsx(Gn,{label:"Legal name",children:s.jsx("span",{className:"text-sm text-text-secondary",children:e.legal_name??"â"})}),s.jsx($n,{}),s.jsx(Gn,{label:"Slug",hint:"Identifies the seller across the API, reports, and YAML registry. Read-only.",children:s.jsx("code",{className:"text-xs px-1.5 py-0.5 rounded bg-surface-sunken text-text-body font-mono",children:e.slug})}),s.jsx($n,{}),s.jsx(Gn,{label:"Status",children:s.jsx(Bq,{slug:e.slug,status:e.status,onChange:w=>t({...e,status:w})})}),s.jsx($n,{}),s.jsx(Gn,{label:"Owner",hint:"The customer. A Gadjet AM is never the owner of a store.",children:s.jsx(Lq,{seller:e})}),s.jsx($n,{}),s.jsx(Gn,{label:"Account manager",hint:n?"Who the sidebar groups this store under. Reassigning updates the AM grant, not just this label.":void 0,children:n&&f?s.jsx(Fq,{seller:e,advisors:f.advisors,availableAms:f.available_ams,onSellerChange:t,onReloadOverview:x}):s.jsx("span",{className:"text-sm text-text-secondary",children:e.account_owner_label||e.account_owner||"â"})}),s.jsx($n,{}),s.jsx(Gn,{label:"Onboarded",children:s.jsx("span",{className:"text-sm text-text-secondary",children:e.onboarded_at?cn(e.onboarded_at):"â"})})]})}function Bq({slug:e,status:t,onChange:n}){const[r,a]=p.useState(!1),[i,o]=p.useState(null);async function l(c){a(!0),o(null);try{const u=await K.patchSeller(e,{status:c});n(u.status)}catch(u){o(String((u==null?void 0:u.message)||u))}finally{a(!1)}}return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(GS,{status:t}),t==="active"&&s.jsx("button",{onClick:()=>l("paused"),disabled:r,className:"text-xs px-2 py-0.5 rounded border border-outline-warning bg-surface-warningSubtle text-text-warning disabled:opacity-50",children:"Pause"}),t==="paused"&&s.jsx(W,{onClick:()=>l("active"),disabled:r,intent:"success",variant:"outline",size:"sm",children:"Resume"}),i&&s.jsx("span",{className:"text-xs text-text-error",children:i})]})}function MWe({seller:e,isAdminRole:t}){const n=e.seller_id!=null;return s.jsxs("div",{className:"space-y-3",children:[s.jsxs(V,{children:[s.jsxs("div",{className:"p-4 flex items-center gap-3",children:[s.jsx("div",{className:B("w-9 h-9 rounded-md flex items-center justify-center shrink-0",n?"bg-surface-successSubtle text-text-success":"bg-surface-sunken text-text-secondary"),children:n?s.jsx(Xt,{className:"w-4 h-4"}):s.jsx(Q6,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Takealot"}),s.jsx("div",{className:"text-xs text-text-secondary",children:n?`Connected · Seller ID ${e.seller_id}`:"Not connected â onboard the seller to attach a Takealot API key."})]}),n&&s.jsx("span",{className:"text-xs font-medium text-text-success bg-surface-successSubtle border border-outline-success px-2 py-0.5 rounded-full",children:"Connected"})]}),n&&s.jsx(FWe,{slug:e.slug,sellerId:e.seller_id??null})]}),s.jsx(LWe,{seller:e}),s.jsx(wWe,{slug:e.slug}),s.jsx(yWe,{slug:e.slug}),t&&s.jsx(BWe,{slug:e.slug})]})}function $We(e){return e==="amazon_za"?"South Africa":e==="amazon_us"?"United States":e??""}function LWe({seller:e}){const[t,n]=p.useState(null),[r,a]=p.useState(null),[i,o]=p.useState(!1),[l,c]=p.useState(null);p.useEffect(()=>{let x=!0;return n(null),a(null),K.amazonConnection(e.slug).then(g=>x&&n(g)).catch(g=>x&&a(String((g==null?void 0:g.message)||g))),()=>{x=!1}},[e.slug]);const u=!!(t!=null&&t.connected),d=!!(t!=null&&t.needs_reconnect),h=u&&!d;async function f(){o(!0),c(null);try{const{consentUrl:x}=await K.amazonConnect("amazon_za",e.slug);window.location.href=x}catch(x){c(String((x==null?void 0:x.message)||x)),o(!1)}}let m="";return t==null&&!r?m="Checkingâ¦":r?m="Couldn't load Amazon status â try refreshing.":t!=null&&!u?m="Not connected â authorize Gadjet on Amazon Seller Central to sync this store.":d?m=(t==null?void 0:t.last_error)||"Amazon access was revoked. Reconnect on Seller Central to resume sync.":u&&(m=`Connected${t!=null&&t.marketplace?` · ${$We(t.marketplace)}`:""}${t!=null&&t.last_synced_at?` · last sync ${Ca(t.last_synced_at)}`:""}`),s.jsxs(V,{children:[s.jsxs("div",{className:"p-4 flex items-center gap-3",children:[s.jsx("div",{className:B("w-9 h-9 rounded-md flex items-center justify-center shrink-0",d?"bg-surface-warningSubtle text-text-warning":h?"bg-surface-successSubtle text-text-success":"bg-surface-sunken text-text-secondary"),children:d?s.jsx(zn,{className:"w-4 h-4"}):h?s.jsx(Xt,{className:"w-4 h-4"}):s.jsx(sN,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Amazon"}),s.jsx("div",{className:"text-xs text-text-secondary",children:m})]}),d?s.jsx(W,{onClick:f,disabled:i,intent:"brand",size:"sm",children:i?"Opening Amazonâ¦":"Reconnect"}):u?s.jsx("span",{className:B("text-xs font-medium px-2 py-0.5 rounded-full border",(t==null?void 0:t.status)==="pending"?"bg-surface-warningSubtle text-text-warning border-outline-warning":"bg-surface-successSubtle text-text-success border-outline-success"),children:(t==null?void 0:t.status)==="pending"?"Awaiting first sync":"Connected"}):s.jsx(W,{onClick:f,disabled:i||t==null||!!r,intent:"brand",size:"sm",children:i?"Opening Amazonâ¦":"Connect Amazon"})]}),l&&s.jsx("div",{className:"border-t border-outline-faint px-4 py-2 text-xs text-text-error bg-surface-errorSubtle",children:l})]})}function FWe({slug:e,sellerId:t}){const[n,r]=p.useState(!1),[a,i]=p.useState(""),[o,l]=p.useState(!1),[c,u]=
906p.useState(null),[d,h]=p.useState(null);async function f(){l(!0),h(null),u(null);try{const m=await K.rotateSellerKey(e,a.trim());u(m.message),i("")}catch(m){h(String((m==null?void 0:m.message)||m))}finally{l(!1)}}return s.jsx("div",{className:"border-t border-outline-faint px-4 py-3 bg-surface-subtle",children:n?s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"text-xs text-text-body",children:["Paste a new Takealot Marketplace API key for this seller",t?` (must belong to seller_id ${t})`:"",". The old key gets replaced â your existing data isn't touched."]}),s.jsx("div",{className:"text-body-xs text-text-secondary",children:"Key is encrypted at rest with AES-256-GCM. Never logged in plaintext. Never echoed back. Generate a fresh one in your Takealot Seller Portal â Integrations â API."}),s.jsx(Ui,{value:a,onChange:m=>i(m.target.value),disabled:o,rows:3,placeholder:"Paste the new keyâ¦",inputSize:"sm",className:"font-mono text-xs"}),d&&s.jsx("div",{className:"text-xs text-text-error bg-surface-errorSubtle border border-outline-error rounded px-2 py-1",children:d}),c&&s.jsx("div",{className:"text-xs text-text-success bg-surface-successSubtle border border-outline-success rounded px-2 py-1",children:c}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(W,{onClick:f,disabled:o||a.trim().length<20,intent:"brand",size:"sm",children:o?"Verifyingâ¦":"Rotate key"}),s.jsx(W,{onClick:()=>{r(!1),i(""),h(null),u(null)},variant:"link",intent:"neutral",size:"sm",children:"Cancel"})]})]}):s.jsx(W,{onClick:()=>r(!0),variant:"link",intent:"neutral",size:"sm",children:"Change Takealot API key"})})}function BWe({slug:e}){const[t,n]=p.useState(null),[r,a]=p.useState(null);p.useEffect(()=>{let o=!0;return n(null),a(null),K.jwtStatus(e).then(l=>o&&n(l)).catch(l=>o&&a(String((l==null?void 0:l.message)||l))),()=>{o=!1}},[e]);const i=t?t.has_jwt?t.is_stale?"stale":"active":"absent":"loading";return s.jsxs(V,{children:[s.jsxs("div",{className:"p-4 flex items-center gap-3",children:[s.jsx("div",{className:B("w-9 h-9 rounded-md flex items-center justify-center shrink-0",i==="active"?"bg-surface-successSubtle text-text-success":i==="stale"?"bg-surface-warningSubtle text-text-warning":"bg-surface-sunken text-text-secondary"),children:s.jsx(m6,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-sm font-semibold text-text-primary flex items-center gap-2",children:["Portal session token",s.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide text-text-secondary bg-surface-sunken border border-outline-subtle px-1.5 py-0.5 rounded",children:"Internal · admin only"})]}),s.jsxs("div",{className:"text-xs text-text-secondary",children:[i==="loading"&&"Loadingâ¦",i==="absent"&&"Not captured â refreshes when the seller next opens sellers.takealot.com with the Gadjet extension.",i==="stale"&&"Stale â the portal session ended before expiry. Needs re-capture via the extension.",i==="active"&&"Active â promotions data is syncing."]})]}),(t==null?void 0:t.has_jwt)&&s.jsx("span",{className:B("text-xs font-medium px-2 py-0.5 rounded-full border",t.is_stale?"bg-surface-warningSubtle text-text-warning border-outline-warning":"bg-surface-successSubtle text-text-success border-outline-success"),children:t.is_stale?"Stale":"Active"})]}),r&&s.jsx("div",{className:"border-t border-outline-faint px-4 py-2 text-xs text-text-error bg-surface-errorSubtle",children:r}),(t==null?void 0:t.has_jwt)&&s.jsxs("div",{className:"border-t border-outline-faint px-4 py-3 bg-surface-subtle space-y-1.5",children:[s.jsx(ry,{label:"Captured",value:t.captured_at?Ca(t.captured_at):"â"}),s.jsx(ry,{label:"Expires",value:t.expires_at?Ca(t.expires_at):"â"}),t.last_error&&s.jsx(ry,{label:"Last error",tone:"error",value:`${t.last_error}${t.last_error_at?` · ${Ca(t.last_error_at)}`:""}`}),t.last_attempt&&s.jsx(ry,{label:"Last sync",value:`${t.last_attempt.kind} · ${t.last_attempt.status}${t.last_attempt.error_kind?` (${t.last_attempt.error_kind})`:""}${t.last_attempt.finished_at?` · ${Ca(t.last_attempt.finished_at)}`:""}`})]})]})}function ry({label:e,value:t,tone:n}){return s.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[s.jsx("span",{className:"w-20 shrink-0 text-text-tertiary",children:e}),s.jsx("span",{className:B("flex-1 break-words",n==="error"?"text-text-error":"text-text-body"),children:t})]})}function UWe({seller:e,isSuperAdmin:t,onSellerChange:n}){const r=t&&!!e.is_managed;return s.jsxs("div",{className:"space-y-3",children:[!t&&s.jsx(V,{className:"p-4 text-sm text-text-warning bg-surface-warningSubtle border-outline-warning",children:"These actions are restricted to super-admins."}),t&&s.jsx(Uq,{seller:e,onSellerChange:n}),s.jsxs(V,{children:[s.jsx(ej,{label:"Pause syncs",hint:"Stop nightly syncs and skill runs. Rever
906sible. Use the pause-seller skill in chat."}),s.jsx($n,{}),s.jsx(ej,{label:"Offboard",hint:"Archive the seller and revoke the API key. Use the offboard-seller skill in chat."}),!r&&s.jsxs(s.Fragment,{children:[s.jsx($n,{}),s.jsx(ej,{label:"Change tier",hint:`Currently in the registry â use the convert_to_managed chat tool to move ${e.display_name} onto a managed retainer, or convert_from_managed if they are leaving one.`})]})]})]})}const zWe=["starter","business","empire"];function Uq({seller:e,onSellerChange:t}){const[n,r]=p.useState("starter"),[a,i]=p.useState(!1),[o,l]=p.useState(null),[c,u]=p.useState(null),d=fi[n],h=zc(d.monthlyGrantZar),f=zc(d.priceZar);if(!e.is_managed&&!c)return null;async function m(){const x=[`Convert ${e.display_name} off Gadjet management onto ${d.displayName}?`,"","This will:","⢠Drop the AM assignment so they leave the managed book","⢠Clear Start of Management",`⢠If they are on an Agency retainer, flip billing to ${d.displayName} (R${f}/mo) with R${h} trial credits â chat becomes metered`,"⢠Keep their login, catalogue, and API key","","This is not offboarding. To reverse, use convert_to_managed."];if(window.confirm(x.join(` 907`))){i(!0),l(null),u(null);
907try{const g=await K.convertFromManaged(e.slug,{plan:n,reason:"no longer a managed account"});u(g.message);try{const y=await K.seller(e.slug);t(y)}catch{t({...e,is_managed:!1,account_owner:"unassigned",management_started_at:null})}}catch(g){l(String((g==null?void 0:g.message)||g))}finally{i(!1)}}}return s.jsxs(V,{className:"p-4 space-y-3 border-outline-warning bg-surface-warningSubtle",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Convert to self-serve"}),s.jsx("div",{className:"text-xs text-text-secondary mt-0.5",children:c?`${e.display_name} is no longer on a managed retainer.`:`${e.display_name} is on a Gadjet-managed retainer. This drops the AM assignment, meters chat, and lands them on a paying plan. Super-admin only.`})]}),!c&&s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("select",{value:n,onChange:x=>r(x.target.value),disabled:a,"aria-label":"Self-serve plan",className:"text-sm px-2 py-1 rounded-md border border-outline-subtle bg-surface focus:bg-surface focus:outline-none focus:border-outline-brand focus-visible:shadow-focus",children:zWe.map(x=>s.jsxs("option",{value:x,children:[fi[x].displayName," â R",zc(fi[x].priceZar),"/mo"]},x))}),s.jsx(W,{onClick:m,disabled:a,intent:"warning",size:"sm",children:a?"Convertingâ¦":`Convert to ${d.displayName}`})]}),c&&s.jsx("div",{className:"text-xs text-text-success",children:c}),o&&s.jsx("div",{className:"text-xs text-text-error",children:o})]})}function ej({label:e,hint:t}){return s.jsx("div",{className:"p-4 flex items-start gap-4",children:s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:e}),s.jsx("div",{className:"text-xs text-text-secondary mt-0.5",children:t})]})})}function GS({status:e}){const t=e==="active"?"bg-surface-successSubtle text-text-success border-outline-success":e==="pending"?"bg-surface-warningSubtle text-text-warning border-outline-warning":e==="paused"?"bg-surface-subtle text-text-body border-outline-subtle":"bg-surface-subtle text-text-secondary border-outline-subtle";return s.jsx("span",{className:B("text-xs font-medium px-2 py-0.5 rounded-full border capitalize",t),children:e})}function WWe({slug:e,open:t,onOpenChange:n,isSuperAdmin:r,onSellerChange:a,onViewTasks:i}){const[o,l]=p.useState(null),[c,u]=p.useState(null),[d,h]=p.useState(!1);p.useEffect(()=>{if(!t||!e){l(null),u(null);return}let m=!0;return h(!0),u(null),K.seller(e).then(x=>{m&&l(x)}).catch(x=>{m&&(l(null),u(x.message||"Could not load this account."))}).finally(()=>{m&&h(!1)}),()=>{m=!1}},[t,e]);function f(m){l(m),a==null||a(m)}return s.jsx(Cr,{open:t,onOpenChange:n,children:s.jsxs(mr,{side:"right",size:"lg",children:[s.jsxs(Er,{children:[s.jsx(xr,{children:(o==null?void 0:o.display_name)??"Managed account"}),s.jsx(Mr,{children:"Account details, contacts, credentials â assigned AM and super-admins only."})]}),s.jsx(pr,{className:"px-4 py-4",children:d&&!o?s.jsx("p",{className:"text-body-sm text-text-tertiary",children:"Loadingâ¦"}):c?s.jsx("p",{className:"text-body-sm text-text-error",children:c}):o?s.jsx($q,{seller:o,onSellerChange:f,isSuperAdmin:r,identityEditable:!0,hideIntro:!0}):null}),o&&s.jsxs(ml,{className:"justify-between",children:[s.jsx(W,{type:"button",variant:"outline",intent:"neutral",size:"sm",asChild:!0,children:s.jsxs(st,{to:`/settings/stores/${encodeURIComponent(o.slug)}/managed`,children:[s.jsx(Qt,{className:"h-3.5 w-3.5"}),"Full settings"]})}),i&&s.jsxs(W,{type:"button",intent:"brand",size:"sm",onClick:()=>{i(o.slug),n(!1)},children:[s.jsx(yd,{className:"h-3.5 w-3.5"}),"Todayâs tasks"]})]})]})})}function sy({label:e,valueLabel:t,pct:n,intent:r="brand"}){const a=r==="success"?"bg-intent-success":r==="warning"?"bg-intent-warning":"bg-intent-brand",i=Math.max(0,Math.min(100,n));return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[s.jsx("span",{className:"text-[11px] text-text-tertiary",children:e}),s.jsx("span",{className:"tabular-nums text-xs font-medium text-text-body",children:t})]}),s.jsx("div",{role:"progressbar","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(i),"aria-valuetext":`${e} ${t}`,className:"mt-0.5 h-1.5 overflow-hidden rounded-full bg-surface-sunken",children:s.jsx("div",{className:B("h-full rounded-full transition-[width] duration-500 ease-out",a),style:{width:`${i}%`}})})]})}function KWe(e,t){if(!e)return t===1?"yesterday":"today";const[n,r,a]=e.split("-").map(Number);return!n||!r||!a?e:new Date(Date.UTC(n,r-1,a)).toLocaleDateString("en-ZA",{weekday:"short",day:"numeric",month:"short",timeZone:"UTC"})}function HWe({refreshSignal:e=0,assigneeId:t,search:n="",sellerFilter:r="",viewerUserId:a,isSuperAdmin:i=!1,onSelectAccount:o}){const[l,c]=p.useState("today"),[u,d]=p.useState(null),[h,f]=p.useState(null),[m,x]=p.useState(!0),[g,y]=p.useState(null),[b,v]=p.useState(null),[w,_]=p.useState({});p.useEffect(()=>{let S=!0;return x(!0),y(null),vr.progressByAccount(l,t).then(O=>{S&&(d(O.rows),f(O.day))}).catch(O=>{S&&y(O.message)}).finally(()=>{S&&x(!1)}),()=>{S=!1}},[l,t,e]);const k=n.trim().toLowerCase(),j=p.useMemo(()=>{let S=u??[];return r&&(S=S.filter(O=>O.seller_slug===r)),k&&(S=S.filter(O=>(w[O.seller_slug]??O.display_name??O.seller_slug).toLowerCase().includes(k)||O.seller_slug.toLowerCase().includes(k))),S},[u,r,k,w]);function N(S){return i?!0:a?(S.assigned_am_ids??[]).includes(a):!1}const E=p.useMemo(()=>j.reduce((S,O)=>Math.max(S,O.today_due),0),[j]),A=p.useMemo(()=>j.reduce((S,O)=>Math.max(S,O.today_closed),0),[j]),C=p.useMemo(()=>j.filter(S=>S.today_due>0&&S.today_pct<100).length,[j]),T=KWe(h,l==="yesterday"?1:0);return s.jsxs("div",{className:"px-3 py-3 space-y-3",children:[s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Progress · by account"}),s.jsxs("p",{className:"text-body-xs text-text-tertiary",children:[u&&u.length>0?C===0?`All ${j.length||u.length} account${(j.length||u.length)===1?"":"s"} clear for ${T}.`:`${C} account${C===1?"":"s"} still have work due ${T}.`:"Daily task progress for each managed account."," ","Click a card you manage to edit account details."]})]}),s.jsx("div",{className:"ml-auto",children:s.jsxs(Pa,{value:l,onValueChange:S=>{(S==="today"||S==="yesterday")&&c(S)},children:[s.jsx(Ln,{value:"today",children:"Today"}),s.jsx(Ln,{value:"yesterday",children:"Yesterday"})]})})]}),g?s.jsx("p",{className:"text-body-xs text-text-error",children:g}):m&&!u?s.jsx("p",{className:"text-body-xs text-text-tertiary",children:"Loadingâ¦"}):j.length===0?s.jsx("p",{className:"text-body-xs text-text-tertiary",children:k||r?"No managed accounts match this filter.":"No active managed accounts in this book."}):s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:j.map(S=>{const O=w[S.seller_slug]??S.display_name??S.seller_slug,R=N(S),I=S.today_due>0&&S.today_pct>=100?"success":S.overdue>0?"warning":"brand";return s.jsxs(V,{padding:"sm",interactive:R||!!o,className:B("flex flex-col gap-2.5",S.overdue>0&&"border-outline-warning"),onClick:()=>{R?v(S.seller_slug):o==null||o(S.seller_slug)},children:[s.jsxs("div",{className:"flex items-start gap-2 min-w-0",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-semibold text-text-primary underline decoration-outline-subtle underline-offset-2",title:O,children:O}),R&&s.jsx("button",{type:"button",onClick:$=>{$.stopPropagation(),v(S.seller_slug)},className:"shrink-0 text-text-tertiary hover:text-text-secondary",title:`Edit ${O}`,"aria-label":`Edit ${O}`,children:s.jsx(Qi,{className:"h-3.5 w-3.5"})}),s.jsx(st,{to:`/sellers/${encodeURIComponent(S.seller_slug)}/tasks`,onClick:$=>$.stopPropagation(),className:"shrink-0 text-text-tertiary hover:text-text-secondary",title:`Open ${O} tasks`,"aria-label":`Open ${O} tasks`,children:s.jsx(Qt,{className:"h-3.5 w-3.5"})})]}),s.jsx(sy,{label:"Today",valueLabel:`${S.today_pct}%`,pct:S.today_pct,intent:I}),s.jsx(sy,{label:"Done today",valueLabel:S.today_closed.toLocaleStr
907ing(),pct:A>0?Math.round(S.today_closed/A*100):0}),s.jsx(sy,{label:"This week",valueLabel:`${S.week_pct}%`,pct:S.week_pct,intent:S.week_due>0&&S.week_pct>=100?"success":"brand"}),s.jsx(sy,{label:"Due today",valueLabel:S.today_due.toLocaleString(),pct:E>0?Math.round(S.today_due/E*100):0}),(S.open>0||S.overdue>0)&&s.jsxs("p",{className:"text-[11px] text-text-tertiary",children:[S.open.toLocaleString()," open",S.overdue>0&&s.jsxs("span",{className:"ml-1.5 text-text-error",children:["· ",S.overdue.toLocaleString()," overdue"]})]})]},S.seller_slug)})}),s.jsx(WWe,{slug:b,open:!!b,onOpenChange:S=>{S||v(null)},isSuperAdmin:i,onSellerChange:S=>{_(O=>({...O,[S.slug]:S.display_name}))},onViewTasks:o})]})}function Hd({title:e,metric:t,hint:n,hintTone:r="default",windows:a,activeWindow:i,onWindowChange:o,askPrompt:l,slug:c,loading:u=!1,empty:d=!1,emptyLabel:h="No data",children:f,className:m}){const x=Rt(),[g,y]=p.useState(!1);async function b(){if(!(!l||g)){y(!0);try{const v=await K.createChat(c);sessionStorage.setItem(`gadjet:seed:${v.id}`,l),x(`/sellers/${c}/chats/${v.id}`)}catch(v){console.error("ChartCard: seeded chat creation failed",v),y(!1)}}}return s.jsxs(V,{padding:"md",className:m,children:[s.jsxs("header",{className:"flex items-start justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary",children:e}),t!=null&&s.jsx("div",{className:"mt-0.5 text-xl font-semibold tabular-nums text-text-primary truncate",children:t}),n!=null&&s.jsx("div",{className:B("text-xs mt-0.5",r==="success"&&"text-text-success",r==="warning"&&"text-text-warning",r==="default"&&"text-text-secondary"),children:n})]}),a&&a.length>0&&s.jsx(Pa,{value:String(i),onValueChange:v=>o==null?void 0:o(Number(v)),className:"shrink-0",children:a.map(v=>s.jsx(Ln,{value:String(v.value),className:"tabular-nums",children:v.label},v.value))})]}),s.jsx("div",{className:"relative",children:d&&!u?s.jsx("div",{className:"flex items-center justify-center text-xs text-text-tertiary h-32",children:h}):s.jsxs(s.Fragment,{children:[u&&s.jsx("div",{className:"absolute inset-0 flex items-center justify-center text-xs text-text-tertiary z-10",children:"Loadingâ¦"}),s.jsx("div",{className:u?"opacity-30":void 0,children:f})]})}),l&&s.jsx("footer",{"data-chart-ask-this":"true",className:"mt-3 pt-2 border-t border-outline-faint flex justify-end",children:s.jsxs("button",{type:"button",onClick:b,disabled:g,className:"text-xs text-text-secondary hover:text-text-primary inline-flex items-center gap-1 transition disabled:opacity-50",children:[s.jsx("span",{children:g?"Openingâ¦":"Ask about this"}),s.jsx("span",{"aria-hidden":!0,children:"â"})]})})]})}const _s={purple:et.primary,slate:et.neutral,red:et.danger,amber:et.warning,green:et.success,grid:Co},Tw={"30d":"last 30 days","90d":"last 90 days",all:"all time"},VWe={meeting:"Meeting",internal:"Internal",management:"Management",bug:"Bug",reminder:"Reminder",fire:"ð¥ Fire",billing:"Billing",customer_communication:"Customer comm",feature:"Feature",listing_upgrade:"Listing upgrade",overview_report:"Morning Overview",other:"Other",replenishment:"Replenishment",dc_allocation:"DC allocation",promotion:"Promotion",listing_creation:"New listing",stock_recon:"Stock recon",pricing_experiment:"Price experiment"};function qWe(e){return e==="30d"||e==="90d"||e==="all"}function Nv(e){const[t,n,r]=e.split("-").map(Number);return!t||!n||!r?e:`${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][n-1]} ${r}`}function zq(e){return e==null?"â":e<1?"<1h":e<48?`${Math.round(e)}h`:`${(e/24).toFixed(1)}d`}function GWe({refreshSignal:e=0}){const[t,n]=p.useState("90d"),[r,a]=p.useState(null),[i,o]=p.useState(!0),[l,c]=p.useState(null);return p.useEffect(()=>{let u=!0;return o(!0),c(null),vr.stats(t).then(d=>{u&&a(d)}).catch(d=>{u&&c(d.message)}).finally(()=>{u&&o(!1)}),()=>{u=!1}},[t,e]),l?s.jsx("div",{className:"p-4 text-body-xs text-text-error",children:l}):s.jsxs("div",{className:"p-3 md:p-4 space-y-4",children:[s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Task statistics"}),s.jsxs("p",{className:"text-body-xs text-text-tertiary",children:["Operational health and per-manager throughput · ",Tw[t],"."]})]}),s.jsxs(Pa,{value:t,onValueChange:u=>{qWe(u)&&n(u)},className:"ml-auto shrink-0",children:[s.jsx(Ln,{value:"30d",children:"30d"}),s.jsx(Ln,{value:"90d",children:"90d"}),s.jsx(Ln,{value:"all",children:"All"})]})]}),s.jsx(q$,{children:"Operational health"}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[s.jsx(YWe,{data:r,loading:i,win:t}),s.jsx(ZWe,{data:r,loading:i}),s.jsx(XWe,{data:r,loading:i}),s.jsx(JWe,{data:r,loading:i}),s.jsx(QWe,{data:r,loading:i,win:t}),s.jsx(eKe,{data:r,loading:i,win:t})]}),s.jsx(tKe,{data:r,loading:i}),s.jsx(q$,{children:"Per-manager"}),s.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-outline-subtle bg-surface-subtle px-3 py-2 text-body-xs text-text-tertiary",children:[s.jsx(lF,{className:"h-3.5 w-3.5 shrink-0 mt-0.5"}),s.jsxs("span",{children:["Completion is attributed by a task's"," ",s.jsx("span",{className:"font-medium text-text-secondary",children:"current assignee"})," â the system doesn't record who actually marked a task done. Read this section as a throughput & load health signal, not a precise per-person score."]})]}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[s.jsx(nKe,{data:r,loading:i}),s.jsx(rKe,{data:r,loading:i})]})]})}function q$({children:e}){return s.jsx("h2",{className:"text-xs font-semibold uppercase tracking-wider text-text-secondary pt-1",children:e})}function Gx({children:e}){return s.jsx("div",{className:"rounded-md border border-outline-subtle bg-surface px-2.5 py-1.5 text-xs shadow-sm",children:e})}function YWe({data:e,loading:t,win:n}){const r=(e==null?void 0:e.completions_over_time)??[],a=p.useMemo(()=>r.reduce((o,l)=>o+l.completed,0),[r]),i=!!e&&a===0;return s.jsx(Hd,{title:"Completions over time",metric:e?a.toLocaleStr
907ing():"â",hint:`tasks cleared · weekly · ${Tw[n]}`,slug:"",loading:t&&!e,empty:i,emptyLabel:"No completions in this window",children:s.jsx("div",{style:{height:200},children:s.jsx(li,{width:"100%",height:"100%",children:s.jsxs(zx,{data:r,margin:{top:6,right:8,bottom:0,left:0},children:[s.jsx(Ma,{strokeDasharray:"3 3",stroke:_s.grid,vertical:!1}),s.jsx($a,{dataKey:"week",tickFormatter:Nv,tick:{fontSize:10,fill:kr},interval:"preserveStartEnd",minTickGap:28}),s.jsx(zr,{hide:!0,domain:[0,"dataMax"],allowDecimals:!1}),s.jsx(Da,{cursor:{fill:Nu},content:({active:o,payload:l})=>{if(!o||!(l!=null&&l.length))return null;const c=l[0].payload;return s.jsxs(Gx,{children:[s.jsxs("div",{className:"text-text-secondary",children:["week of ",Nv(c.week)]}),s.jsxs("div",{className:"tabular-nums text-text-primary font-medium",children:[c.completed," completed"]})]})}}),s.jsx(vo,{dataKey:"completed",fill:_s.purple,radius:[2,2,0,0],isAnimationActive:!1})]})})})})}function ZWe({data:e,loading:t}){const n=(e==null?void 0:e.backlog_trend)??[],r=n[n.length-1],a=n[0],i=r&&a?r.open-a.open:null,o=!!e&&n.every(l=>l.open===0&&l.overdue===0);return s.jsx(Hd,{title:"Backlog & overdue",metric:r?r.open.toLocaleString():"â",hint:i==null?"open tasks, reconstructed per week":`${i>=0?"+":""}${i} open vs ${(e==null?void 0:e.weeks)??""}w ago`,hintTone:i!=null&&i>0?"warning":"default",slug:"",loading:t&&!e,empty:o,emptyLabel:"No backlog history",children:s.jsx("div",{style:{height:200},children:s.jsx(li,{width:"100%",height:"100%",children:s.jsxs(PH,{data:n,margin:{top:6,right:8,bottom:0,left:0},children:[s.jsx(Ma,{strokeDasharray:"3 3",stroke:_s.grid,vertical:!1}),s.jsx($a,{dataKey:"week",tickFormatter:Nv,tick:{fontSize:10,fill:kr},interval:"preserveStartEnd",minTickGap:28}),s.jsx(zr,{hide:!0,domain:[0,"dataMax"],allowDecimals:!1}),s.jsx(Da,{cursor:{stroke:_s.slate,strokeDasharray:"2 2"},content:({active:l,payload:c})=>{if(!l||!(c!=null&&c.length))return null;const u=c[0].payload;return s.jsxs(Gx,{children:[s.jsxs("div",{className:"text-text-secondary",children:["week of ",Nv(u.week)]}),s.jsxs("div",{className:"tabular-nums",children:[s.jsx("span",{className:"text-text-secondary",children:"Open:"})," ",s.jsx("span",{className:"font-medium text-text-primary",children:u.open})]}),s.jsxs("div",{className:"tabular-nums text-text-error",children:[s.jsx("span",{children:"Overdue:"})," ",u.overdue]})]})}}),s.jsx(Vi,{type:"monotone",dataKey:"open",stroke:_s.purple,strokeWidth:2,dot:!1,isAnimationActive:!1}),s.jsx(Vi,{type:"monotone",dataKey:"overdue",stroke:_s.red,strokeWidth:2,dot:!1,isAnimationActive:!1})]})})})})}function XWe({data:e,loading:t}){const n=p.useMemo(()=>((e==null?void 0:e.type_mix)??[]).map(o=>({...o,label:VWe[o.type]??o.type})),[e]),r=p.useMemo(()=>n.reduce((o,l)=>o+l.completed,0),[n]),a=!!e&&r===0,i=Math.max(160,n.length*26+12);return s.jsx(Hd,{title:"Task-type mix",metric:e?`${n.length} types`:"â",hint:"completed work, by type",slug:"",loading:t&&!e,empty:a,emptyLabel:"No completions in this window",children:s.jsx("div",{style:{height:Math.min(i,260)},children:s.jsx(li,{width:"100%",height:"100%",children:s.jsxs(zx,{data:n,layout:"vertical",margin:{top:0,right:12,bottom:0,left:0},children:[s.jsx(Ma,{strokeDasharray:"3 3",stroke:_s.grid,horizontal:!1}),s.jsx($a,{type:"number",hide:!0,allowDecimals:!1}),s.jsx(zr,{type:"category",dataKey:"label",width:110,tick:{fontSize:11,fill:vw}}),s.jsx(Da,{cursor:{fill:Nu},content:({active:o,payload:l})=>{if(!o||!(l!=null&&l.length))return null;const c=l[0].payload;return s.jsxs(Gx,{children:[s.jsxs("span",{className:"text-text-secondary",children:[c.label,": "]}),s.jsx("span",{className:"font-medium text-text-primary tabular-nums",children:c.completed})]})}}),s.jsx(vo,{dataKey:"completed",fill:_s.purple,radius:[0,2,2,0],isAnimationActive:!1})]})})})})}function JWe({data:e,loading:t}){const n=(e==null?void 0:e.aging.open)??[],r=(e==null?void 0:e.aging.overdue)??[],a=p.useMemo(()=>n.reduce((o,l)=>o+l.n,0),[n]),i=!!e&&a===0;return s.jsxs(Hd,{title:"Aging · open tasks",metric:e?a.toLocaleString():"â",hint:"how long open tasks have been sitting",slug:"",loading:t&&!e,empty:i,emptyLabel:"No open tasks",children:[s.jsx("div",{style:{height:150},children:s.jsx(li,{width:"100%",height:"100%",children:s.jsxs(zx,{data:n,margin:{top:6,right:8,bottom:0,left:0},children:[s.jsx(Ma,{strokeDasharray:"3 3",stroke:_s.grid,vertical:!1}),s.jsx($a,{dataKey:"bucket",tick:{fontSize:10,fill:kr}}),s.jsx(zr,{hide:!0,domain:[0,"dataMax"],allowDecimals:!1}),s.jsx(Da,{cursor:{fill:Nu},content:({active:o,payload:l})=>
907{if(!o||!(l!=null&&l.length))return null;const c=l[0].payload;return s.jsxs(Gx,{children:[s.jsxs("span",{className:"text-text-secondary",children:[c.bucket," old: "]}),s.jsx("span",{className:"font-medium text-text-primary tabular-nums",children:c.n})]})}}),s.jsx(vo,{dataKey:"n",radius:[2,2,0,0],isAnimationActive:!1,children:n.map((o,l)=>s.jsx(zd,{fill:l>=4?_s.red:l>=3?_s.amber:_s.purple},o.bucket))})]})})}),s.jsxs("div",{className:"mt-3 pt-2 border-t border-outline-faint flex items-center gap-2 flex-wrap text-body-xs",children:[s.jsx("span",{className:"text-text-tertiary",children:"Overdue by:"}),r.map(o=>s.jsxs("span",{className:B("inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 tabular-nums",o.n>0?"bg-surface-errorSubtle text-text-error":"bg-surface-sunken text-text-tertiary"),children:[o.bucket," ",s.jsx("span",{className:"font-semibold",children:o.n})]},o.bucket))]})]})}function QWe({data:e,loading:t,win:n}){const r=e==null?void 0:e.ref_outcomes,a=(r==null?void 0:r.total)??0,i=!!e&&a===0,o=r?[{key:"good",label:"Landed",n:r.good,color:_s.green},{key:"pending",label:"Pending",n:r.pending,color:_s.amber},{key:"bad",label:"Failed",n:r.bad,color:_s.red},{key:"unmatched",label:"Unresolved",n:r.unmatched,color:_s.slate}].filter(l=>l.n>0):[];return s.jsx(Hd,{title:"Proof-of-work outcomes",metric:r?`${r.bad} failed`:"â",hint:`logged Takealot refs on tasks cleared · ${Tw[n]}`,hintTone:r&&r.bad>0?"warning":"default",slug:"",loading:t&&!e,empty:i,emptyLabel:"No submission refs logged in this window",children:r&&a>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex h-2.5 w-full overflow-hidden rounded-full bg-surface-sunken",children:o.map(l=>s.jsx("div",{style:{width:`${l.n/a*100}%`,backgroundColor:l.color},title:`${l.label}: ${l.n}`},l.key))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-x-3 gap-y-1 text-body-xs",children:o.map(l=>s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-text-secondary",children:[s.jsx("span",{className:"h-2 w-2 rounded-sm",style:{backgroundColor:l.color}}),l.label," ",s.jsx("span",{className:"font-semibold tabular-nums text-text-primary",children:l.n})]},l.key))}),r.bad_samples.length>0&&s.jsxs("div",{className:"mt-3 pt-2 border-t border-outline-faint space-y-1.5",children:[s.jsxs("p",{className:"flex items-center gap-1.5 text-body-xs font-medium text-text-error",children:[s.jsx(zn,{className:"h-3.5 w-3.5"})," Work that didn't land"]}),s.jsx("div",{className:"max-h-32 overflow-y-auto pr-1 space-y-1",children:r.bad_samples.map(l=>s.jsxs("div",{className:"flex items-center gap-2 text-body-xs",children:[s.jsx("span",{className:"flex-1 truncate text-text-body",title:l.title??"",children:l.title??"Untitled task"}),s.jsx("span",{className:"shrink-0 text-text-tertiary",children:l.seller_slug}),s.jsx("span",{className:"shrink-0 rounded bg-surface-errorSubtle px-1 text-text-error",children:l.status_label??"failed"})]},l.task_id))})]})]})})}function eKe({data:e,loading:t,win:n}){const r=e==null?void 0:e.coverage,a=!!e&&((r==null?void 0:r.managed)??0)===0;return s.jsx(Hd,{title:"Account-coverage gap",metric:r?`${r.neglected} untouched`:"â",hint:r?`of ${r.managed} managed accounts · no completed task ${Tw[n]}`:"managed accounts with no attention",hintTone:r&&r.neglected>0?"warning":"success",slug:"",loading:t&&!e,empty:a,emptyLabel:"No managed accounts",children:r&&r.neglected_accounts.length>0?s.jsx("div",{className:"max-h-48 overflow-y-auto pr-1 space-y-1",children:r.neglected_accounts.map(i=>s.jsxs("div",{className:"flex items-center gap-2 text-body-xs",children:[s.jsx("span",{className:"flex-1 truncate text-text-body",title:i.display_name??i.seller_slug,children:i.display_name??i.seller_slug}),i.open>0&&s.jsxs("span",{className:"shrink-0 rounded bg-surface-sunken px-1 tabular-nums text-text-secondary",children:[i.open," open"]}),s.jsx("span",{className:"shrink-0 text-text-tertiary tabular-nums",children:i.last_completed_at?`last ${i.last_completed_at}`:"never"})]},i.seller_slug))}):r&&s.jsx("div",{className:"flex h-24 items-center justify-center text-center text-body-xs text-text-success",children:"Every managed account got attention this window."})})}function tKe({data:e,loading:t}){const n=(e==null?void 0:e.recurrence)??[];return s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-3 py-2 border-b border-outline-subtle",children:[s.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Recurring series"}),s.jsx("p",{className:"text-body-xs text-text-tertiary",children:"How standing recurring tasks are keeping up â completion & on-time rates per series."})]}),t&&!e?s.jsx("p",{className:"py-6 text-center text-body-xs text-text-tertiary",children:"Loadingâ¦"}):s.jsx("div",{className:"max-h-72 overflow-auto",children:s.jsx(dt,{rows:n,columns:[{key:"series",label:"Series",render:r=>s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"truncate block max-w-[22rem]",title:r.title??"",children:r.title??"Untitled series"}),r.seller_slug&&s.jsx("span",{className:"text-body-xs text-text-tertiary",children:r.seller_slug})]}),className:"text-text-body"},{key:"instances",label:"Instances",align:"right",render:r=>s.jsx("span",{className:"tabular-nums text-text-body",children:r.instances})},{key:"completed",label:"Completed",align:"right",render:r=>s.jsx("span",{className:"tabular-nums text-text-secondary",children:r.completed})},{key:"onTime",label:"On-time",align:"right",render:r=>{const a=r.completed>0?Math.round(r.on_time/r.completed*100):null;return a==null?s.jsx("span",{className:"text-text-tertiary",children:"â"}):s.jsxs("span",{className:B("tabular-nums",a>=80?"text-text-success":a>=50?"text-text-warning":"text-text-error"),children:[a,"%"]})}},{key:"overdue",label:"Overdue now",align:"right",render:r=>s.jsx("span",{className:B("tabular-nums",r.overdue_open>0?"text-text-error font-medium":"text-text-tertiary"),children:r.overdue_open})}],getRowKey:r=>r.root_id,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No recurring task series yet."}})})]})}function Wq(e){var t;return((t=e.display_name)==null?void 0:t.trim())||e.email}function nKe({data:e,loading:t}){const n=p.useMemo(()=>((e==null?void 0:e.per_am)??[]).map(o=>({...o,label:Wq(o)})).slice(0,12),[e]),r=p.useMemo(()=>n.reduce((o,l)=>o+l.completed,0),[n]),a=!!e&&r===0,i=Math.max(160,n.length*28+12);return s.jsx(Hd,{title:"Completions by manager",metric:e?r.toLocaleStr
907ing():"â",hint:"tasks cleared in the window, by current assignee",slug:"",loading:t&&!e,empty:a,emptyLabel:"No completions in this window",children:s.jsx("div",{style:{height:Math.min(i,320)},children:s.jsx(li,{width:"100%",height:"100%",children:s.jsxs(zx,{data:n,layout:"vertical",margin:{top:0,right:12,bottom:0,left:0},children:[s.jsx(Ma,{strokeDasharray:"3 3",stroke:_s.grid,horizontal:!1}),s.jsx($a,{type:"number",hide:!0,allowDecimals:!1}),s.jsx(zr,{type:"category",dataKey:"label",width:110,tick:{fontSize:11,fill:vw}}),s.jsx(Da,{cursor:{fill:Nu},content:({active:o,payload:l})=>{if(!o||!(l!=null&&l.length))return null;const c=l[0].payload;return s.jsxs(Gx,{children:[s.jsx("div",{className:"font-medium text-text-primary",children:c.label}),s.jsxs("div",{className:"tabular-nums text-text-secondary",children:[c.completed," cleared"]}),s.jsxs("div",{className:"tabular-nums text-text-tertiary",children:["median ",zq(c.median_hours)," to close"]})]})}}),s.jsx(vo,{dataKey:"completed",fill:_s.purple,radius:[0,2,2,0],isAnimationActive:!1})]})})})})}function rKe({data:e,loading:t}){const n=(e==null?void 0:e.per_am)??[];return s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-3 py-2 border-b border-outline-subtle",children:[s.jsx("h3",{className:"text-sm font-medium text-text-primary",children:"Manager leaderboard"}),s.jsx("p",{className:"text-body-xs text-text-tertiary",children:"Throughput, speed, and current load side by side â a health read, not a verdict."})]}),t&&!e?s.jsx("p",{className:"py-6 text-center text-body-xs text-text-tertiary",children:"Loadingâ¦"}):s.jsx("div",{className:"max-h-72 overflow-auto",children:s.jsx(dt,{rows:n,columns:[{key:"rank",label:"#",render:r=>s.jsx("span",{className:"tabular-nums text-text-tertiary",children:n.indexOf(r)+1})},{key:"manager",label:"Manager",render:r=>s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium",children:Wq(r)}),r.role==="super_admin"&&s.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-text-tertiary border border-outline-subtle rounded px-1 py-0.5",children:"Admin"})]}),className:"text-text-body"},{key:"cleared",label:"Cleared",align:"right",render:r=>s.jsx("span",{className:"tabular-nums font-medium text-text-body",children:r.completed.toLocaleString()})},{key:"median",label:"Median",align:"right",render:r=>s.jsx("span",{className:"tabular-nums text-text-tertiary",children:zq(r.median_hours)})},{key:"open",label:"Open",align:"right",render:r=>s.jsx("span",{className:"tabular-nums text-text-secondary",children:r.open})},{key:"overdue",label:"Overdue",align:"right",render:r=>s.jsx("span",{className:B("tabular-nums",r.overdue>0?"text-text-error font-medium":"text-text-tertiary"),children:r.overdue})}],getRowKey:r=>r.id,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No managers to show."}})})]})}const sKe="Africa/Johannesburg",B3=[{key:"yesterday",label:"Yesterday"},{key:"today",label:"Today"},{key:"week",label:"This week"},{key:"7d",label:"Last 7 days"},{key:"14d",label:"Last 14 days"}];function Yx(e=new Date){return new Intl.DateTimeFormat("en-CA",{timeZone:sKe,year:"numeric",month:"2-digit",day:"2-digit"}).format(e)}function By(e,t){const n=new Date(`${e}T12:00:00Z`);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)}function aKe(e){const n=new Date(`${e}T12:00:00Z`).getUTCDay(),r=n===0?6:n-1;return By(e,-r)}function U3(e,t=Yx()){switch(e){case"yesterday":{const n=By(t,-1);return{from:n,to:n}}case"today":return{from:t,to:t};case"week":return{from:aKe(t),to:t};case"7d":return{from:By(t,-6),to:t};case"14d":return{from:By(t,-13),to:t}}}function Kq(e,t,n=Yx()){for(const{key:r}of B3){const a=U3(r,n);if(a.from===e&&a.to===t)return r}return"custom"}function tj(e){const[t,n,r]=e.split("-").map(Number);return!t||!n||!r?e:`${r} ${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][n-1]} ${t}`}function iKe(e,t,n=Yx()){var a;const r=Kq(e,t,n);return r!=="custom"?((a=B3.find(i=>i.key===r))==null?void 0:a.label)??"Custom":e===t?tj(e):`${tj(e)} â ${tj(t)}`}function ay(e=Yx()){return U3("yesterday",e)}function oKe({from:e,to:t,onPreset:n,onCustom:r,className:a}){const[i,o]=p.useState(!1),l=Yx(),c=Kq(e,t,l),[u,d]=p.useState(e),[h,f]=p.useState(t);p.useEffect(()=>
907{i&&(d(e),f(t))},[i,e,t]);function m(){!u||!h||u>h||(r(u,h),o(!1))}return s.jsxs(Tf,{open:i,onOpenChange:o,children:[s.jsx(Of,{asChild:!0,children:s.jsxs("button",{type:"button",title:"Completed on (SAST calendar days)",className:B("inline-flex items-center gap-1.5 rounded-md border border-outline-subtle bg-surface px-2.5 py-1.5 text-xs font-medium text-text-primary","hover:bg-surface-subtle transition-colors",a),children:[s.jsx(yd,{className:"h-3.5 w-3.5 text-text-tertiary"}),iKe(e,t,l),s.jsx(Pn,{className:"h-3 w-3 text-text-tertiary"})]})}),s.jsxs($d,{align:"start",className:"w-72 p-2",children:[s.jsx("div",{className:"space-y-0.5",children:B3.map(x=>{const g=c===x.key;return s.jsxs("button",{type:"button",onClick:()=>{n(x.key),o(!1)},className:B("w-full flex items-center justify-between px-3 py-1.5 text-xs rounded transition",g?"bg-surface-brandSubtle text-text-brand font-medium":"text-text-body hover:bg-surface-subtle"),children:[s.jsx("span",{children:x.label}),g&&s.jsx(fn,{className:"h-3.5 w-3.5"})]},x.key)})}),s.jsx("div",{className:"my-2 border-t border-outline-faint"}),s.jsxs("div",{className:"px-2 pb-1",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("div",{className:"text-xs font-medium text-text-secondary",children:"Custom range"}),c==="custom"&&s.jsx("span",{className:"text-[10px] text-text-brand font-medium uppercase tracking-wider",children:"Active"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"block text-[10px] text-text-tertiary uppercase tracking-wider mb-0.5",children:"From"}),s.jsx("input",{type:"date",value:u,max:h||l,onChange:x=>d(x.target.value),className:"block w-full text-xs px-2 py-1 rounded border border-outline bg-surface focus:outline-none focus:border-outline-brand focus-visible:shadow-focus"})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"block text-[10px] text-text-tertiary uppercase tracking-wider mb-0.5",children:"To"}),s.jsx("input",{type:"date",value:h,min:u||void 0,max:l,onChange:x=>f(x.target.value),className:"block w-full text-xs px-2 py-1 rounded border border-outline bg-surface focus:outline-none focus:border-outline-brand focus-visible:shadow-focus"})]})]}),s.jsx(W,{onClick:m,disabled:!u||!h||u>h,size:"sm",className:"w-full mt-2",children:"Apply"})]})]})]})}const Hq=["not_started","scheduled","in_progress","monitoring_testing","waiting_for_signoff"],lKe=[...Hq,"done"],cKe=[{value:"type",label:"Task type"},{value:"status",label:"Status"},{value:"due",label:"Due date"},{value:"assignee",label:"Assignee"},{value:"closer",label:"Who closed"},{value:"seller",label:"Seller"},{value:"priority",label:"Priority"}],nj=2e3;function rj(e){const t=new Date;return t.setHours(0,0,0,0),t.setDate(t.getDate()+e),`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`}function uKe(e){const t=e.trim();if(!t)return"?";const n=t.split(/\s+/);return n.length>=2?(n[0][0]+n[1][0]).toUpperCase():t.slice(0,2).toUpperCase()}const sj=[{key:"mine",label:"Mine",filters:{assignee:"me",status:"open"}},{key:"all",label:"All my book",filters:{status:"open"}},{key:"team",label:"Team",filters:{status:"open"}},{key:"closed",label:"Closed",filters:{status:"closed"}},{key:"recent",label:"Done recently",filters:{}},{key:"stats",label:"Stats",filters:{status:"open"}}],iy=["mine","all"];function G$(e,t="neutral"){if(!(e<=0))return s.jsx("span",{className:B("ml-1.5 inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full px-1 text-body-xs font-semibold tabular-nums",t==="danger"?"bg-surface-errorSubtle text-text-error":"bg-surface-sunken text-text-secondary"),children:e})}const dKe=[{value:"",label:"All types"},{value:"replenishment",label:"Replenishment"},{value:"promotion",label:"Promotion"},{value:"listing_creation",label:"New listing"},{value:"listing_upgrade",label:"Listing upgrade"},{value:"dc_allocation",label:"DC allocation"},{value:"stock_recon",label:"Stock recon"},{value:"overview_report",label:"Morning Overview"},{value:"pricing_experiment",label:"Price experiment"},{value:"customer_communication",label:"Customer comm"},{value:"billing",label:"Billing"},{value:"fire",label:"ð¥ Fire"},{value:"bug",label:"Bug"},{value:"feature",label:"Feature"},{value:"meeting",label:"Meeting"},{value:"reminder",label:"Reminder"},{value:"internal",label:"Internal"},{value:"management",label:"Management"},{value:"other",label:"Other"}];function hKe({count:e,roster:t,busy:n,onPatch:r,onClear:a}){const[i,o]=p.useState(!1);return s.jsxs("div",{className:"border-b border-outline-subtle bg-surface-brandSubtle/50 px-3 py-2 flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-xs font-semibold text-text-primary whitespace-nowrap",children:[e," selected"]}),s.jsxs("div",{className:"inline-flex items-center gap-1",children:[s.jsx(Xp,{className:"h-3.5 w-3.5 text-text-tertiary"}),s.jsxs(Tt,{value:"",disabled:n,onChange:l=>{const c=l.target.value;if(c)if(c==="__unassign__")r({assignee_user_id:null},"Unassigned");else{const u=t.find(d=>d.id===c);r({assignee_user_id:c},`Reassigned to ${(u==null?void 0:u.display_name)||(u==null?void 0:u.email)||"user"}`)}},className:"w-40",children:[s.jsx("option",{value:"",children:"Reassign toâ¦"}),s.jsx("option",{value:"__unassign__",children:"â Unassign â"}),t.map(l=>s.jsxs("option",{value:l.id,children:[l.display_name||l.email,l.role==="super_admin"?" (admin)":""]},l.id))]})]}),s.jsxs("div",{className:"inline-flex items-center gap-1",children:[s.jsx(Qp,{className:"h-3.5 w-3.5 text-text-tertiary"}),s.jsx(W,{type:"button",size:"sm",variant:"outline",intent:"neutral",disabled:n,onClick:()=>r({due_date:rj(1)},"Rescheduled to tomorrow"),children:"Tomorrow"}),s.jsx(W,{type:"button",size:"sm",variant:"outline",intent:"neutral",disabled:n,onClick:()=>r({due_date:rj(3)},"Rescheduled +3 days"),children:"+3d"}),s.jsx(W,{type:"button",size:"sm",variant:"outline",intent:"neutral",disabled:n,onClick:()=>r({due_date:rj(7)},"Rescheduled +1 week"),children:"Next week"}),s.jsx(Re,{type:"date",disabled:n,onChange:l=>{l.target.value&&r({due_date:l.target.value},"Rescheduled")},className:"w-36",title:"Reschedule to a specific date"})]}),s.jsxs(Tt,{value:"",disabled:n,onChange:l=>{l.target.value&&r({status:l.target.value},"Status updated")},className:"w-36",children:[s.jsx("option",{value:"",children:"Set statusâ¦"}),Hq.map(l=>s.jsx("option",{value:l,children:cu[l]},l))]}),s.jsxs(W,{type:"button",size:"sm",variant:i?"solid":"outline",intent:"destructive",disabled:n,onClick:()=>
907{if(!i){o(!0);return}o(!1),r({status:"cancelled"},"Cancelled")},onBlur:()=>o(!1),children:[s.jsx(dte,{className:"h-3.5 w-3.5"}),i?"Confirm cancel":"Cancel tasks"]}),n&&s.jsx(_e,{className:"h-4 w-4 animate-spin text-text-tertiary"}),s.jsx(W,{type:"button",size:"sm",variant:"ghost",intent:"neutral",disabled:n,onClick:a,className:"ml-auto",children:"Clear"})]})}function fKe(e){if(!e)return{text:"â",tone:"neutral"};const t=new Date;t.setHours(0,0,0,0);const n=new Date(`${e}T00:00:00`),r=Math.round((n.getTime()-t.getTime())/864e5);return r<0?{text:`${Math.abs(r)}d overdue`,tone:"overdue"}:r===0?{text:"Today",tone:"soon"}:r===1?{text:"Tomorrow",tone:"soon"}:r<7?{text:`In ${r}d`,tone:"soon"}:{text:e,tone:"neutral"}}function mKe({tasks:e,sellerDisplay:t,onSelect:n}){return s.jsx("div",{className:"flex gap-3 overflow-x-auto p-3",children:lKe.map(r=>{const a=e.filter(i=>i.status===r);return s.jsxs("div",{className:"flex w-64 shrink-0 flex-col rounded-lg bg-surface-subtle p-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5",children:[s.jsx("span",{className:B("inline-flex items-center rounded px-1.5 py-0.5 text-body-xs font-medium ring-1 ring-inset",M3[r]),children:cu[r]}),s.jsx("span",{className:"text-body-xs font-semibold tabular-nums text-text-tertiary",children:a.length})]}),s.jsx("div",{className:"flex flex-col gap-2 p-1",children:a.length===0?s.jsx("div",{className:"py-3 text-center text-body-xs text-text-tertiary",children:"â"}):a.map(i=>{const o=fKe(i.due_date);return s.jsxs("button",{type:"button",onClick:()=>n(i),className:"rounded-lg border border-outline-subtle bg-surface p-2.5 text-left shadow-xs transition hover:border-outline-strong",children:[s.jsx("div",{className:"text-body-sm font-medium text-text-primary",children:i.title}),s.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[i.seller_slug?s.jsx("span",{className:"truncate text-body-xs text-text-secondary",children:t[i.seller_slug]??i.seller_slug}):s.jsx("span",{className:"text-body-xs text-text-tertiary",children:"â internal"}),s.jsx("span",{className:B("ml-auto whitespace-nowrap text-body-xs font-medium",o.tone==="overdue"&&"text-text-error",o.tone==="soon"&&"text-text-warning",o.tone==="neutral"&&"text-text-tertiary"),children:o.text})]})]},i.id)})})]},r)})})}function pKe(e,t){const n=new Date(e);return n.setHours(0,0,0,0),n.setDate(n.getDate()+t),`${n.getFullYear()}-${String(n.getMonth()+1).padStart(2,"0")}-${String(n.getDate()).padStart(2,"0")}`}function Vq(e){return new Date(`${e}T12:00:00Z`)}function Y$(e,t){const n=Vq(e);return n.setUTCDate(n.getUTCDate()+t),n.toISOString().slice(0,10)}function xKe(){return new Intl.DateTimeFormat("en-CA",{timeZone:"Africa/Johannesburg",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date)}const gKe=["January","February","March","April","May","June","July","August","September","October","November","December"],yKe=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],bKe=new Set(["done","customer_completed","customer_not_required","cancelled"]);function Z$({task:e,draggable:t,onSelect:n,onDragStart:r,onDragEnd:a}){const i=bKe.has(e.status),o=i?`${Ve[4].tint} ${Ve[4].text} border ${Ve[4].border}`:`${Ve[5].tint} ${Ve[5].text} border ${Ve[5].border}`;return s.jsxs("button",{type:"button",draggable:t,title:e.title,onClick:l=>{l.stopPropagation(),n(e)},onDragStart:l=>{l.dataTransfer.setData("text/plain",e.id),l.dataTransfer.effectAllowed="move",r(e)},onDragEnd:a,className:B("w-full flex items-center gap-1 rounded-sm border px-1 py-px text-[10px] leading-tight truncate text-left",o,t&&"cursor-grab active:cursor-grabbing",i&&"line-through opacity-80"),children:[e.priority==="high"&&s.jsx("span",{className:"w-1 h-1 rounded-full bg-error-500 shrink-0"}),s.jsx("span",{className:"truncate",children:e.title})]})}function vKe({tasks:e,density:t,onSelect:n,onReschedule:r}){const a=p.useMemo(()=>xKe(),[]),[i,o]=p.useState(()=>{const[k,j]=a.split("-");return{year:Number(k),month:Number(j)-1}}),[l,c]=p.useState(null),[u,d]=p.useState(null),h=t==="compact",f=h?2:3,m=p.useMemo(()=>{const[k,j]=a.split("-");return i.year===Number(k)&&i.month===Number(j)-1},[i,a]),x=p.useMemo(()=>{const k=`${i.year}-${String(i.month+1).padStart(2,"0")}-01`,j=(Vq(k).getUTCDay()+6)%7,N=Y$(k,-j),E=[];for(let A=0;A<42;A++)E.push(Y$(N,A));return E},[i]),g=p.useMemo(()=>{const k=new Map;for(const j of e){if(!j.due_date)continue;const N=k.get(j.due_date)??[];N.push(j),k.set(j.due_date,N)}return k},[e]),y=p.useMemo(()=>e.filter(k=>!k.due_date),[e]);function b(k){o(j=>{const N=j.month+k;return{year:j.year+Math.floor(N/12),month:(N%12+12)%12}})}function v(){const[k,j]=a.split("-");o({year:Number(k),month:Number(j)-1})}function w(k){const j=l;d(null),c(null),j&&r(j,k)}const _={onDragStart:c,onDragEnd:()=>{c(null),d(null)}};return s.jsxs("div",{className:"p-3 md:p-4",children:[s.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[s.jsx(W,{type:"button",size:"sm",variant:"outline",intent:"neutral",disabled:m,onClick:v,children:"Today"}),s.jsx(W,{type:"button",size:"sm",variant:"ghost",intent:"neutral","aria-label":"Previous month",onClick:()=>b(-1),children:s.jsx(ud,{className:"h-4 w-4"})}),s.jsxs("div",{className:"min-w-[9rem] text-center text-body-md font-semibold text-text-primary",children:[gKe[i.month]," ",i.year]}),s.jsx(W,{type:"button",size:"sm",variant:"ghost",intent:"neutral","aria-label":"Next month",onClick:()=>b(1),children:s.jsx(fr,{className:"h-4 w-4"})})]}),s.jsxs(V,{className:"p-0 overflow-hidden",children:[s.jsx("div",{className:"grid grid-cols-7 border-b border-outline-subtle",children:yKe.map(k=>s.jsx("div",{className:"px-2 py-1.5 text-center text-body-xs font-medium text-text-tertiary",children:k},k))}),s.jsx("div",{className:"grid grid-cols-7",children:x.map(k=>{const j=Number(k.slice(5,7))-1===i.month,N=k===a,E=g.get(k)??[],A=E.slice(0,f),C=E.length-A.length,T=u===k&&!!l;return s.jsxs("div",{onDragOver:S=>{S.preventDefault(),S.dataTransfer.dropEffect="move",u!==k&&d(k)},onDragLeave:S=>{S.currentTarget.contains(S.relatedTarget)||d(O=>O===k?null:O)},onDrop:()=>w(k),className:B(h?"min-h-[3.5rem]":"min-h-[4.25rem]","flex flex-col gap-px border-b border-r border-outline-subtle p-1",!j&&"bg-surface-subtle/50",T&&"bg-intent-brand/5 ring-1 ring-inset ring-brand-600"),children:[s.jsx("div",{className:"flex items-center justify-between px-0.5",children:s.jsx("span",{className:B("text-[10px] leading-none",N?"inline-flex h-4 w-4 items-center justify-center rounded-full bg-intent-brand font-semibold text-text-inverse":j?"text-text-secondary":"text-text-tertiary"),children:Number(k.slice(8,10))})}),A.map(S=>s.jsx(Z$,{task:S,draggable:!0,onSelect:n,onDragStart:_.onDragStart,onDragEnd:_.onDragEnd},S.id)),C>0&&s.jsxs("button",{type:"button",onClick:()=>n(E[f]),className:"w-full rounded-sm px-1 py-px text-left text-[10px] leading-tight text-text-tertiary hover:text-text-secondary",children:["+",C," more"]})]},k)})})]}),s.jsxs("div",{onDragOver:k=>{k.preventDefault(),k.dataTransfer.dropEffect="move",u!=="__unsched__"&&d("__unsched__")},onDragLeave:k=>{k.currentTarget.contains(k.relatedTarget)||d(j=>j==="__unsched__"?null:j)},onDrop:()=>w(null),className:B("mt-3 rounded-lg border px-3 py-2 transition-colors",u==="__unsched__"&&l?"border-brand-600 bg-intent-brand/5":"border-outline-subtle"),children:[s.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5 text-text-secondary",children:[s.jsx(oF,{className:"h-4 w-4"}),s.jsx("span",{className:"text-body-sm font-semibold",children:"Unscheduled"}),s.jsx("span",{className:"text-body-xs font-semibold tabular-nums",children:y.length}),s.jsx("span",{className:"text-body-xs text-text-tertiary",children:"· drop here to clear a date"})]}),y.length?s.jsx("div",{className:"flex flex-wrap gap-1.5",children:y.map(k=>s.jsx("div",{className:"w-56 max-w-full",children:s.jsx(Z$,{task:k,draggable:!0,onSelect:n,onDragStart:_.onDragStart,onDragEnd:_.onDragEnd})}
907,k.id))}):s.jsx("div",{className:"text-body-xs text-text-tertiary",children:"No unscheduled tasks."})]}),s.jsx("p",{className:"mt-3 text-center text-body-xs text-text-tertiary",children:"Drag a task to another day to reschedule it â or onto Unscheduled to clear its date."})]})}function wKe(){var Ge;const e=Lt(),t=e.kind==="ready"&&e.me.role==="super_admin",n=e.kind==="ready"&&e.me.role==="seller_user",[r,a]=it("tab","mine"),i=mc(),[o]=it("cfrom",""),[l]=it("cto",""),[c,u]=it("closer",""),h=sj.filter(ye=>ye.key!=="stats"||t).map(ye=>ye.key).includes(r)?r:"mine",[f,m]=p.useState("list"),[x,g]=p.useState("type"),[y,b]=p.useState("comfortable"),[v,w]=p.useState(""),[_,k]=p.useState(""),[j,N]=p.useState(""),[E,A]=p.useState(!1),C=E&&(n||iy.includes(h)),[T,S]=p.useState(!1),O=T&&(n||iy.includes(h)),R=p.useMemo(()=>o&&l?{from:o,to:l}:o?{from:o,to:o}:l?{from:l,to:l}:ay(),[o,l]);function I(ye){const ie=U3(ye),pe=ay();ie.from===pe.from&&ie.to===pe.to?i({cfrom:"",cto:""}):i({cfrom:ie.from,cto:ie.to})}function $(ye,ie){const pe=ay();ye===pe.from&&ie===pe.to?i({cfrom:"",cto:""}):i({cfrom:ye,cto:ie})}const[P,F]=p.useState(null),Z=!n&&h==="recent"&&!P,[D,H]=p.useState([]),[Y,M]=p.useState([]),[z,G]=p.useState([]),[te,re]=p.useState({mine:0,book:0,overdue:0}
907),[L,q]=p.useState(!0),[me,ee]=p.useState(null),[ne,X]=p.useState(null),[he,ae]=p.useState(new Set),[je,$e]=p.useState(!1),[J,Ne]=p.useState(null),[ve,Me]=p.useState("edit"),[Xe,ze]=p.useState(!1),[Fe,tt]=p.useState(0),fe=p.useCallback(()=>tt(ye=>ye+1),[]);p.useEffect(()=>{h==="recent"?(g("closer"),m("list")):g(ye=>ye==="closer"?"type":ye)},[h]);const U=p.useCallback(async(ye,ie)=>{H(pe=>pe.map(xe=>xe.id===ye.id?{...xe,status:ie}:xe));try{await vr.update(ye.id,{status:ie})}catch(pe){ee(pe instanceof Error?pe.message:String(pe)),tt(xe=>xe+1)}},[]),ce=p.useCallback(async(ye,ie)=>{if((ye.due_date??null)!==(ie??null)){H(pe=>pe.map(xe=>xe.id===ye.id?{...xe,due_date:ie}:xe));try{await vr.update(ye.id,{due_date:ie})}catch(pe){ee(pe instanceof Error?pe.message:String(pe)),tt(xe=>xe+1)}}},[]),ue=p.useCallback(ye=>{ae(ie=>{const pe=new Set(ie);return pe.has(ye)?pe.delete(ye):pe.add(ye),pe})},[]),Ee=p.useCallback((ye,ie)=>{ae(pe=>{const xe=new Set(pe);for(const Ke of ye)ie?xe.add(Ke):xe.delete(Ke);return xe})},[]),bt=p.useCallback(async(ye,ie)=>{const pe=[...he];if(pe.length!==0){$e(!0),X(null);try{const xe=await vr.bulkUpdate(pe,ye),Ke=xe.results.filter(St=>!St.ok);Ke.length?X(`â ${ie}: ${xe.updated} of ${xe.total} updated · ${Ke.length} failed (${Ke[0].error}).`):X(`${ie}: ${xe.updated} task${xe.updated===1?"":"s"}.`),ae(new Set),tt(St=>St+1)}catch(xe){X(`â ${xe instanceof Error?xe.message:String(xe)}`)}finally{$e(!1)}}},[he]),Ze=p.useMemo(()=>{var ie;if(n)return{status:"open",...E?{overdue:!0}:{},...v?{type:v}:{}};const ye=P?{assignee:P.id,status:"open"}:((ie=sj.find(pe=>pe.key===h))==null?void 0:ie.filters)??{};return h==="recent"&&!P?{completed_from:R.from,completed_to:R.to,...c?{completed_by:c}:{},...v?{type:v}:{},..._?{seller_slug:_}:{},limit:nj}:{...ye,...C&&!P?{overdue:!0}:{},...v?{type:v}:{},..._?{seller_slug:_}:{}}},[n,h,P,C,E,v,_,R,c]);p.useEffect(()=>{ae(new Set)},[Ze,f]),p.useEffect(()=>{let ye=!0;return q(!0),ee(null),vr.list(Ze).then(ie=>{ye&&H(ie.tasks)}).catch(ie=>{ye&&ee(ie.message)}).finally(()=>{ye&&q(!1)}),()=>{ye=!1}},[Ze,Fe]),p.useEffect(()=>{let ye=!0;return K.sellers().then(ie=>{ye&&M(ie)}).catch(()=>{}),()=>{ye=!1}},[]),p.useEffect(()=>{if(n)return;let ye=!0;return vr.roster().then(ie=>{ye&&G(ie.users)}).catch(()=>{}),()=>{ye=!1}},[n]),p.useEffect(()=>{if(e.kind!=="ready"||n)return;let ye=!0;return vr.counts().then(ie=>{ye&&re(ie)}).catch(()=>{}),()=>{ye=!1}},[e.kind,n,Fe]),p.useEffect(()=>{if(e.kind!=="ready")return;let ye=null;const ie=xn.channel("tasks-changes").on("postgres_changes",{event:"*",schema:"public",table:"tasks"},()=>{ye&&clearTimeout(ye),ye=setTimeout(()=>{fe(),ye=null},400)}).subscribe();return()=>{ye&&clearTimeout(ye),xn.removeChannel(ie)}},[e.kind,fe]);const vt=p.useMemo(()=>{const ye={};for(const ie of Y)ye[ie.slug]=ie.display_name;return ye},[Y]),Ot=p.useMemo(()=>{const ye={};for(const ie of z){const pe=ie.display_name||ie.email;ye[ie.id]={name:pe,initials:uKe(pe)}}return ye},[z]),It=p.useMemo(()=>{const ye=j.trim().toLowerCase(),ie=O?pKe(new Date,0):null;let pe=D;return ie&&(pe=pe.filter(xe=>xe.due_date===ie)),ye&&(pe=pe.filter(xe=>{const Ke=xe.seller_slug?vt[xe.seller_slug]??xe.seller_slug:"";return xe.title.toLowerCase().includes(ye)||Ke.toLowerCase().includes(ye)})),pe},[D,j,vt,O]),Ut=p.useMemo(()=>{const ye=new Set;for(const ie of D)ie.seller_slug&&ye.add(ie.seller_slug);return _&&ye.add(_),[...ye].map(ie=>({slug:ie,name:vt[ie]??ie})).sort((ie,pe)=>ie.name.localeCompare(pe.name))},[D,vt,_]);function Lr(){Ne(null),Me("create"),ze(!0)}function en(ye){Ne(ye.id),Me("edit"),ze(!0)}function Hs(){ze(!1),Ne(null)}function Os(ye){fe(),ye==null&&Hs()}const gr=n||h!=="team"&&h!=="stats",Vs=ay(),Xn=Z&&(c||R.from!==Vs.from||R.to!==Vs.to),le=v||_||j||C||O||Xn,De=s.jsxs(s.Fragment,{children:[!Z&&s.jsx("div",{className:"flex items-center gap-1 border-b border-outline-subtle px-2 pt-1",children:[{key:"list",label:"List",Icon:Xne},{key:"board",label:"Board",Icon:$2},{key:"calendar",label:"Calendar",Icon:yd},...n?[]:[{key:"gallery",label:"Gallery",Icon:gf}]].map(({key:ye,label:ie,Icon:pe})=>s.jsxs("button",{type:"button",onClick:()=>m(ye),className:B("-mb-px inline-flex items-center gap-1.5 border-b-2 px-3 py-2 text-sm font-medium transition-colors",f===ye?"border-outline-brand text-text-primary":"border-transparent text-text-secondary hover:text-text-primary"),children:[s.jsx(pe,{className:"h-3.5 w-3.5"}),ie]},ye))}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-outline-subtle px-3 py-2",children:[s.jsxs("div",{className:B("inline-flex items-center gap-1.5",f!=="list"&&"opacity-40"),children:[s.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-text-tertiary",children:"Group"}
907),s.jsx(Tt,{value:x,disabled:f!=="list",onChange:ye=>g(ye.target.value),className:"w-36",children:cKe.filter(ye=>Z?ye.value!=="due":ye.value!=="closer").map(ye=>s.jsx("option",{value:ye.value,children:ye.label},ye.value))})]}),s.jsxs("div",{className:B("inline-flex items-center gap-1.5",f!=="list"&&"opacity-40"),children:[s.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-text-tertiary",children:"Density"}),s.jsx("div",{className:"inline-flex rounded-md bg-surface-sunken p-0.5",children:["comfortable","compact"].map(ye=>s.jsx("button",{type:"button",disabled:f!=="list",onClick:()=>b(ye),className:B("rounded px-2 py-1 text-body-xs font-medium capitalize transition-colors",y===ye?"bg-surface text-text-brand shadow-xs":"text-text-tertiary hover:text-text-secondary"),children:ye},ye))})]}),t&&z.length>0&&Z&&s.jsxs(Tt,{value:c,onChange:ye=>u(ye.target.value),className:"w-44",title:"Who closed these tasks",children:[s.jsx("option",{value:"",children:"Who closed⦠(all)"}),z.map(ye=>s.jsxs("option",{value:ye.id,children:[ye.display_name||ye.email,ye.role==="super_admin"?" (admin)":""]},ye.id))]}),t&&z.length>0&&!Z&&s.jsxs(Tt,{value:(P==null?void 0:P.id)??"",onChange:ye=>{const ie=ye.target.value;if(!ie){F(null);return}const pe=z.find(xe=>xe.id===ie);F({id:ie,name:(pe==null?void 0:pe.display_name)||(pe==null?void 0:pe.email)||"AM"}),X(null)},className:"w-44",title:"View an AM's open book",children:[s.jsx("option",{value:"",children:"Whose book⦠(all)"}),z.map(ye=>s.jsxs("option",{value:ye.id,children:[ye.display_name||ye.email,ye.role==="super_admin"?" (admin)":""]},ye.id))]}),Z&&s.jsx(oKe,{from:R.from,to:R.to,onPreset:I,onCustom:$}),(n||iy.includes(h))&&s.jsxs("button",{type:"button",onClick:()=>{S(ye=>!ye),A(!1)},"aria-pressed":O,title:"Show only tasks due today â applies to List, Board and Calendar",className:B("inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs font-medium whitespace-nowrap transition-colors",O?"border-outline-brand bg-surface-brandSubtle text-text-brand":"border-outline-subtle text-text-secondary hover:text-text-primary"),children:[s.jsx(yd,{className:"h-3.5 w-3.5"}),"Today"]}),(n||iy.includes(h))&&s.jsxs("button",{type:"button",onClick:()=>{A(ye=>!ye),S(!1)},"aria-pressed":C,title:"Show only overdue tasks in this view",className:B("inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs font-medium whitespace-nowrap transition-colors",C?"border-outline-error bg-surface-errorSubtle text-text-error":"border-outline-subtle text-text-secondary hover:text-text-primary"),children:[s.jsx(Qp,{className:"h-3.5 w-3.5"}),"Overdue",!n&&te.overdue>0&&s.jsx("span",{className:"tabular-nums",children:te.overdue})]}),s.jsx(Tt,{value:v,onChange:ye=>w(ye.target.value),className:"w-40",children:dKe.map(ye=>s.jsx("option",{value:ye.value,children:ye.label},ye.value||"all"))}),!n&&s.jsxs(Tt,{value:_,onChange:ye=>k(ye.target.value),className:"w-44",children:[s.jsx("option",{value:"",children:"All sellers"}),Ut.map(ye=>s.jsx("option",{value:ye.slug,children:ye.name},ye.slug))]}),le&&s.jsx(W,{type:"button",intent:"neutral",variant:"ghost",size:"sm",onClick:()=>{w(""),k(""),N(""),A(!1),S(!1),Z&&i({closer:"",cfrom:"",cto:""})},children:"Clear"}),s.jsx(pc,{fieldClassName:"ml-auto min-w-[12rem] flex-1 sm:flex-none",type:"text",value:j,onChange:ye=>N(ye.target.value),placeholder:"Search title or sellerâ¦",reserveEnd:!0,end:j?s.jsx("button",{type:"button",onClick:()=>N(""),className:"absolute right-2 top-1/2 z-[1] -translate-y-1/2 text-text-tertiary hover:text-text-secondary","aria-label":"Clear search",children:s.jsx(Bn,{className:"h-3.5 w-3.5"})}):null})]})]}),Ie=s.jsxs(s.Fragment,{children:[!n&&h==="closed"&&!P&&f!=="gallery"&&s.jsx(Xze,{isSuperAdmin:t,roster:z,refreshSignal:Fe}),De,Z&&D.length>=nj&&s.jsxs("div",{className:"border-b border-outline-subtle bg-surface-warningSubtle/50 px-3 py-2 text-body-xs text-text-secondary",children:["Showing the first ",nj," completions in this window â narrow the date range or pick one closer."]}),!n&&he.size>0&&s.jsx(hKe,{count:he.size,roster:z,busy:je,onPatch:bt,onClear:()=>ae(new Set)}),f==="gallery"&&!n?s.jsx(HWe,{refreshSignal:Fe,assigneeId:P==null?void 0:P.id,search:j,sellerFilter:_,viewerUserId:e.kind==="ready"?e.me.id:null,isSuperAdmin:t,onSelectAccount:ye=>{k(ye),S(!0),A(!1),a("all"),m("list")}}):f==="board"?s.jsx(mKe,{tasks:It,sellerDisplay:vt,onSelect:en}):f==="calendar"?s.jsx(vKe,{tasks:It,density:y,onSelect:en,onReschedule:ce}):s.jsx(Tze,{tasks:It,groupBy:x,density:y,loading:L,error:me,selectedId:J,onSelect:en,onQuickStatus:U,selectable:!n,selectedIds:he,onToggleSelect:ue,onToggleSelectMany:Ee,sellerDisplay:vt,assigneeDisplay:Ot,dateMode:Z?"completed":"due",emptyMessage:Z?"No tasks completed in this window.":void 0})]});return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Tasks"}],actions:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(W,{type:"button",onClick:fe,intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(vi,{className:"h-3.5 w-3.5"})," Refresh"]}),s.jsxs(W,{type:"button",onClick:Lr,intent:"brand",size:"sm",children:[s.jsx(In,{className:"h-3.5 w-3.5"})," New task"]})]})}),!n&&(P?s.jsx("div",{className:"border-b border-outline-subtle bg-surface-warningSubtle/40 px-4 md:px-6",children:s.jsxs("div",{className:"w-full flex items-center gap-2 py-2",children:[s.jsxs(W,{type:"button",size:"sm",variant:"ghost",intent:"neutral",onClick:()=>F(null),children:[s.jsx(ff,{className:"h-3.5 w-3.5"})," Back"]}),s.jsxs("span",{className:"text-sm text-text-body",children:["Lightening ",s.jsx("span",{className:"font-semibold",children:P.name}),"âs load â their open tasks. Select a batch and reassign to rebalance."]}),s.jsxs("span",{className:"ml-auto text-body-xs text-text-secondary shrink-0",children:[It.length,It.length!==D.length?` of ${D.length}`:""," task",D.length===1?"":"s"]})]})}):s.jsx(As,{items:sj.filter(ye=>ye.key!=="stats"||t).map(ye=>({key:ye.key,label:ye.label,active:h===ye.key,onClick:()=>a(ye.key),trailing:ye.key==="mine"?G$(te.mine):ye.key==="all"?G$(te.book):void 0})),actions:h!=="team"&&h!=="stats"?s.jsxs("span",{className:"text-body-xs text-text-secondary",children:[It.length,It.length!==D.length?` of ${D.length}`:""," task",D.length===1?"":"s"]}):void 0})),s.jsx("div",{className:"flex-1 overflow-auto",children:!n&&h==="stats"&&t&&!P?s.jsx("div",{className:"w-full",children:s.jsx(GWe,{refreshSignal:Fe})}):s.jsx("div",{className:"w-full p-4 md:p-6 space-y-4",children:s.jsxs(V,{className:"overflow-hidden",children:[ne&&s.jsxs("div",{className:"border-b border-outline-subtle bg-surface-subtle px-3 py-2 flex items-center gap-2 text-body-xs text-text-secondary",children:[s.jsx("span",{children:ne}),s.jsx("button",{type:"button",onClick:()=>X(null),className:"ml-auto text-text-tertiary hover:text-text-secondary","aria-label":"Dismiss",children:s.jsx(Bn,{className:"h-3.5 w-3.5"})})]}),!n&&h==="team"&&!P?s.jsxs(s.Fragment,{children:[s.jsx(Yze,{isSuperAdmin:t,refreshSignal:Fe}),s.jsx(qze,{bare:!0,refreshSignal:Fe,onSelectAm:t?ye=>{F(ye),X(null)}:void 0})]}):gr&&Ie]})})}),s.jsx(Rq,{open:Xe,mode:ve,taskId:J,defaultSellerSlug:n?((Ge=Y[0])==null?void 0:Ge.slug)||(e.kind==="ready"?e.me.allowed_slugs[0]:void 0):void 0,sellers:Y,onSaved:Os,onClose:Hs})]})}const _Ke=[{key:"open",label:"Open"},{key:"closed",label:"Closed"}];function kKe(){const{slug:e=""}=jn(),t=Lt(),[n,r]=p.useState("open"),[a,i]=p.useState([]),[o,l]=
907p.useState([]),[c,u]=p.useState(null),[d,h]=p.useState(!0),[f,m]=p.useState(null),[x,g]=p.useState(null),[y,b]=p.useState("edit"),[v,w]=p.useState(!1),[_,k]=p.useState(0),j=p.useCallback(()=>k(S=>S+1),[]);p.useEffect(()=>{let S=!0;return h(!0),m(null),vr.list({seller_slug:e,status:n}).then(O=>{S&&i(O.tasks)}).catch(O=>{S&&m(O.message)}).finally(()=>{S&&h(!1)}),()=>{S=!1}},[e,n,_]),p.useEffect(()=>{let S=!0;return K.sellers().then(O=>{S&&(l(O),u(O.find(R=>R.slug===e)??null))}).catch(()=>{}),()=>{S=!1}},[e]),p.useEffect(()=>{if(t.kind!=="ready")return;let S=null;const O=xn.channel(`tasks-changes-${e}`).on("postgres_changes",{event:"*",schema:"public",table:"tasks"},()=>{S&&clearTimeout(S),S=setTimeout(()=>{j(),S=null},400)}).subscribe();return()=>{S&&clearTimeout(S),xn.removeChannel(O)}},[t.kind,j,e]);const N=p.useMemo(()=>{const S={};for(const O of o)S[O.slug]=O.display_name;return S},[o]);function E(){g(null),b("create"),w(!0)}function A(S){g(S.id),b("edit"),w(!0)}function C(){w(!1),g(null)}function T(S){j(),S==null&&C()}return t.kind==="ready"&&t.me.role==="seller_user"?s.jsx(Yt,{to:"/",replace:!0}):s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:(c==null?void 0:c.display_name)??e,to:`/sellers/${e}`},{label:"Tasks"}],actions:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(W,{type:"button",onClick:j,intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(vi,{className:"h-3.5 w-3.5"})," Refresh"]}),s.jsxs(W,{type:"button",onClick:E,intent:"brand",size:"sm",children:[s.jsx(In,{className:"h-3.5 w-3.5"})," New task"]})]})}),s.jsx("div",{className:"flex-1 overflow-auto p-4 md:p-6",children:s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"border-b border-outline-subtle px-3 py-2 flex items-center gap-1 overflow-x-auto",children:[_Ke.map(S=>s.jsx("button",{type:"button",onClick:()=>r(S.key),className:B("px-3 py-1.5 rounded-md text-xs font-medium whitespace-nowrap",n===S.key?"bg-surface-inverse text-text-inverse":"text-text-secondary hover:bg-surface-sunken"),children:S.label},S.key)),s.jsxs("span",{className:"ml-auto text-body-xs text-text-secondary shrink-0",children:[a.length," task",a.length===1?"":"s"]})]}),s.jsx(gze,{tasks:a,loading:d,error:f,selectedId:x,onSelect:A,hideSellerColumn:!0,sellerDisplay:N})]})}),s.jsx(Rq,{open:v,mode:y,taskId:x,defaultSellerSlug:e,sellers:o,onSaved:T,onClose:C})]})}const jKe=[{key:"replenishment",label:"Replenishment Shipment",mode:"weekly"},{key:"listing_upgrade",label:"Listing Upgrade",mode:"weekly"},{key:"promotion",label:"Promotion",mode:"weekly"},{key:"listing_creation",label:"Listing Creation",mode:"weekly"},{key:"stock_recon",label:"Stock Recon",mode:"monthly_first_business_day"},{key:"overview_pdf",label:"Morning Overview",mode:"weekly"}],X$=[{dow:1,label:"Mon"},{dow:2,label:"Tue"},{dow:3,label:"Wed"},{dow:4,label:"Thu"},{dow:5,label:"Fri"}];function J$(){return new Set(["overview_pdf:1","overview_pdf:2","overview_pdf:3","overview_pdf:4","overview_pdf:5","stock_recon:0"])}function Q$(){return new Date().toLocaleDateString("en-CA",{timeZone:"Africa/Johannesburg"})}function oy(){return{street:"",suburb:"",city:"",postal_code:"",country:"South Africa"}}async function NKe(e,t){const n=await new Promise((a,i)=>{const o=new FileReader;o.onload=()=>a(String(o.result||"")),o.onerror=()=>i(o.error),o.readAsDataURL(e)}),r=n.includes(",")?n.slice(n.indexOf(",")+1):n;return{kind:t,filename:e.name,mime_type:e.type||"application/pdf",base64:r}}function wn({label:e,hint:t,children:n}){return s.jsxs("label",{className:"block min-w-0",children:[s.jsx("span",{className:"mb-1 block text-body-xs font-medium text-text-secondary",children:e}),n,t&&s.jsx("span",{className:"mt-1 block text-[11px] text-text-tertiary",children:t})]})}function jl({title:e,description:t,children:n}){return s.jsxs("section",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:e}),t&&s.jsx("p",{className:"text-body-xs text-text-tertiary mt-0.5",children:t})]}),n]})}function eL({value:e,onChange:t,disabled:n}){const r=a=>i=>t({...e,[a]:i.target.value});return s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[s.jsx(wn,{label:"Street",children:s.jsx(Re,{value:e.street,onChange:r("street"),disabled:n,inputSize:"sm"})}),s.jsx(wn,{label:"Suburb",children:s.jsx(Re,{value:e.suburb,onChange:r("suburb"),disabled:n,inputSize:"sm"})}),s.jsx(wn,{label:"City",children:s.jsx(Re,{value:e.city,onChange:r("city"),disabled:n,inputSize:"sm"})}),s.jsx(wn,{label:"Postal code",children:s.jsx(Re,{value:e.postal_code,onChange:r("postal_code"),disabled:n,inputSize:"sm"})}),s.jsx(wn,{label:"Country",children:s.jsx(Re,{value:e.country,onChange:r("country"),disabled:n,inputSize:"sm"})})]})}function SKe({open:e,onOpenChange:t,onOnboarded:n,prefill:r}){var bc;const a=Rt(),[i,o]=p.useState([]),[l,c]=p.useState(""),[u,d]=p.useState(null),[h,f]=p.useState(!1),[m,x]=p.useState(!1),[g,y]=p.useState(""),[b,v]=p.useState(""),[w,_]=p.useState(""),[k,j]=p.useState(Q$()),[N,E]=p.useState(!0),[A,C]=p.useState(""),[T,S]=p.useState(""),[O,R
907]=p.useState(""),[I,$]=p.useState(""),[P,F]=p.useState(""),[Z,D]=p.useState(""),[H,Y]=p.useState(""),[M,z]=p.useState(""),[G,te]=p.useState(""),[re,L]=p.useState(oy()),[q,me]=p.useState(!1),[ee,ne]=p.useState(oy()),[X,he]=p.useState(""),[ae,je]=p.useState(""),[$e,J]=p.useState(""),[Ne,ve]=p.useState(""),[Me,Xe]=p.useState(""),[ze,Fe]=p.useState(""),[tt,fe]=p.useState(""),[U,ce]=p.useState(""),[ue,Ee]=p.useState(J$),[bt,Ze]=p.useState(""),[vt,Ot]=p.useState(""),[It,Ut]=p.useState("whatsapp"),[Lr,en]=p.useState(""),[Hs,Os]=p.useState(""),[gr,Vs]=p.useState([]),[Xn,le]=p.useState(!1),[De,Ie]=p.useState(null),[Ge,ye]=p.useState(null);p.useEffect(()=>{e&&(ie(r),K.onboardManagedAms().then(o).catch(()=>o([])))},[e,r]);function ie(Ce){c(""),d(null),x(!1),y((Ce==null?void 0:Ce.displayName)??""),v((Ce==null?void 0:Ce.displayName)??""),_(""),j(Q$()),E(!0),C((Ce==null?void 0:Ce.ownerEmail)??""),S((Ce==null?void 0:Ce.ownerName)??""),R(""),$(""),F(""),D(""),Y(""),z(""),te((Ce==null?void 0:Ce.billingName)??""),L(oy()),me(!1),ne(oy()),he(""),je(""),J(Ce!=null&&Ce.vatNumber?"yes":""),ve((Ce==null?void 0:Ce.vatNumber)??""),Xe(""),Fe(""),fe(""),ce(""),Ee(J$()),Ze(""),Ot(""),Ut((Ce==null?void 0:Ce.channel)??"whatsapp"),en((Ce==null?void 0:Ce.whoContact)??""),Os((Ce==null?void 0:Ce.notes)??""),Vs([]),le(!1),Ie(null),ye(null)}function pe(Ce){Xn||(t(Ce),Ce||ie())}const xe=p.useMemo(()=>!(u!=null&&u.display_name)||!g.trim()?!1:u.display_name.trim().toLowerCase()!==g.trim().toLowerCase(),[u,g]);async function Ke(){f(!0),Ie(null),d(null),x(!1);try{const Ce=await K.previewManagedKey(l);d(Ce),Ce.already_attached&&Ie(`This Takealot store is already in Gadjet as ${Ce.attached_slug}. Reassign that record instead of onboarding again.`)}catch(Ce){Ie(Ce instanceof Error?Ce.message:String(Ce))}finally{f(!1)}}function St(Ce,yr){const Ua=`${Ce}:${yr}`,Ci=new Set(ue);Ci.has(Ua)?Ci.delete(Ua):Ci.add(Ua),Ee(Ci)}async function Jt(Ce,yr){if(yr)try{const Ua=await NKe(yr,Ce);Vs(Ci=>[...Ci.filter(or=>or.kind!==Ce||Ce==="other"),Ua])}catch(Ua){Ae.error(Ua instanceof Error?Ua.message:"Could not read that file.")}}async function yn(){if(!(!u||u.already_attached)){le(!0),Ie(null);try{const Ce={api_key:l,am_short_name:w,display_name_override:b.trim()||null,expected_display_name:g.trim()||u.display_name,confirm_store:m||!xe,create_login:N,owner_email:A.trim()||null,owner_name:T.trim()||null,management_started_at:k,portal_password:O,two_fa_holder:I.trim()||null,ticket_centre_username:P.trim()||null,ticket_centre_password:Z||null,adaptris_username:H.trim()||null,adaptris_password:M||null,billing_company_name:G.trim()||null,billing_address:re.street?re:null,warehouse_same_as_billing:q,warehouse_address:q?null:ee.street?ee:null,warehouse_contact_person:X.trim()||null,warehouse_contact_phone:ae.trim()||null,vat_registered:$e==="yes"?!0:$e==="no"?!1:null,vat_number:Ne.trim()||null,bank_account_holder:Me.trim()||null,bank_name:ze.trim()||null,bank_branch_code:tt.trim()||null,bank_account_number:U.trim()||null,schedule:[...ue].map(Ua=>{const[Ci,or]=Ua.split(":");return{task_key:Ci,day_of_week:Number(or)}}),shipment_cadence:bt.trim()||null,promo_appetite:vt.trim()||null,preferred_channel:It||null,who_to_contact:Lr.trim()||null,extra_notes:Hs.trim()||null,documents:gr},yr=await K.onboardManagedAccount(Ce);ye(yr),n==null||n({slug:yr.slug,display_name:yr.display_name}),Ae.success(`Onboarded ${yr.display_name}`,{description:yr.agent_plus_email?`Ask them to add ${yr.agent_plus_email} on the Seller Portal.`:void 0})}catch(Ce){Ie(Ce instanceof Error?Ce.message:String(Ce))}finally{le(!1)}}}const no=!!u&&!u.already_attached&&!!w&&!!O&&(!N||!!A.trim())&&!!P.trim()&&!!Z&&(q||!!ee.street)&&!(xe&&!m)&&!Xn;return s.jsx(js,{open:e,onOpenChange:pe,children:s.jsxs(Ns,{size:"full",hideCloseButton:Xn,className:"max-h-[92vh] flex flex-col overflow-hidden",onPointerDownOutside:Ce=>{Xn&&Ce.preventDefault()},onEscapeKeyDown:Ce=>{Xn&&Ce.preventDefault()},children:[s.jsxs(La,{children:[s.jsx(ma,{children:Ge?"Managed account created":"Onboard a managed account"}),s.jsx(hc,{children:Ge?"The store is on the books. Copy the secondary portal user for the client, then open the account.":"One form for the SOP â bootstrap, vault, billing, the standard-task grid, notes, and invites."})]}),Ge?s.jsxs(Oa,{className:"overflow-y-auto space-y-4 pb-4",children:[s.jsxs("div",{className:"rounded-lg border border-outline-success bg-surface-successSubtle p-4 space-y-2",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-success",children:[s.jsx(Xt,{className:"h-4 w-4"}),Ge.display_name," (",Ge.slug,")"]}),s.jsxs("p",{className:"text-body-sm text-text-secondary",children:["Seller ID ",Ge.seller_id," · AM ",Ge.am_short_name," · Start of management ",Ge.management_started_at]})]}),Ge.agent_plus_email&&s.jsx(tL,{label:"Secondary Seller Portal user",value:Ge.agent_plus_email,hint:"Give this to the client to add as a
907secondary user on sellers.takealot.com. OTP lands in [email protected]."}),((bc=Ge.owner_invite)==null?void 0:bc.invite_link)&&s.jsx(tL,{label:"Client Gadjet invite",value:Ge.owner_invite.invite_link,hint:Ge.owner_invite.invite_email_sent?`Emailed to ${Ge.owner_invite.owner_email}.`:`Invite created for ${Ge.owner_invite.owner_email} â email did not send (${Ge.owner_invite.invite_email_skip_reason||Ge.owner_invite.error||"unknown"}). Forward the link.`}),Ge.webhook_error&&s.jsxs("p",{className:"text-body-sm text-text-warning",children:["Webhook did not provision: ",Ge.webhook_error,". The account is live; real-time events need a follow-up."]}),Ge.warnings.length>0&&s.jsxs("div",{className:"text-body-sm text-text-warning space-y-1",children:[s.jsx("div",{className:"font-medium",children:"Saved with follow-ups"}),s.jsx("ul",{className:"list-disc pl-5 space-y-0.5",children:Ge.warnings.map(Ce=>s.jsxs("li",{children:[Ce.step,": ",Ce.message]},Ce.step))})]})]}):s.jsxs(Oa,{className:"overflow-y-auto space-y-8 pb-4",children:[s.jsxs(jl,{title:"Store",description:"Look the key up against Takealot before anything else. A wrong paste is the usual failure.",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[s.jsx(wn,{label:"Takealot Marketplace API key",hint:"Never pasted back into chat or Slack. Stored encrypted.",children:s.jsx(Re,{type:"password",autoComplete:"off",value:l,onChange:Ce=>{c(Ce.target.value),d(null)},inputSize:"sm"})}),s.jsx("div",{className:"flex items-end",children:s.jsxs(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",disabled:l.trim().length<20||h,onClick:Ke,children:[h?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):null,"Look up store"]})}),s.jsx(wn,{label:"Name we were told",hint:"Optional. If this differs from Takealot's live name you'll need to confirm.",children:s.jsx(Re,{value:g,onChange:Ce=>y(Ce.target.value),inputSize:"sm"})}),s.jsx(wn,{label:"Gadjet display name",hint:"Leave blank to use Takealot's name.",children:s.jsx(Re,{value:b,onChange:Ce=>v(Ce.target.value),inputSize:"sm"})}),s.jsx(wn,{label:"Assigned AM",children:s.jsxs(Tt,{value:w,onChange:Ce=>_(Ce.target.value),inputSize:"sm",children:[s.jsx("option",{value:"",children:"Selectâ¦"}),i.map(Ce=>s.jsxs("option",{value:Ce.display_name,children:[Ce.display_name,Ce.role==="am"?"":` (${Ce.role})`]},Ce.email||Ce.display_name))]})}),s.jsx(wn,{label:"Start of management",hint:"Defaults to today. Separate from the onboarded-at timestamp.",children:s.jsx(Re,{type:"date",value:k,onChange:Ce=>j(Ce.target.value),inputSize:"sm"})})]}),u&&!u.already_attached&&s.jsxs("div",{className:"rounded-md border border-outline-subtle bg-surface-subtle px-3 py-2 text-body-sm space-y-1",children:[s.jsxs("div",{children:["Live Takealot name:"," ",s.jsx("span",{className:"font-medium text-text-primary",children:u.display_name||"â"})]}),s.jsxs("div",{className:"text-text-secondary",children:["Seller ID ",u.seller_id??"â",u.legal_name?` · ${u.legal_name}`:"",u.agent_plus_email?` · secondary user ${u.agent_plus_email}`:""]}),xe&&s.jsxs("label",{className:"flex items-start gap-2 pt-1 text-text-warning",children:[s.jsx(ei,{checked:m,onCheckedChange:Ce=>x(Ce===!0)}),s.jsx("span",{children:"Confirm this is the right store (live name doesnât match what we were told)."})]})]})]}),s.jsxs(jl,{title:"Client Gadjet login",description:"We create the account for them and email a 14-day owner invite.",children:[s.jsxs(vv,{value:N?"yes":"no",onValueChange:Ce=>E(Ce==="yes"),className:"flex flex-row gap-6",children:[s.jsx(Vg,{value:"yes",label:"Yes â create it for them"}),s.jsx(Vg,{value:"no",label:"No â Gadjet-run only"})]}),N&&s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[s.jsx(wn,{label:"Owner email",children:s.jsx(Re,{type:"email",value:A,onChange:Ce=>C(Ce.target.value),inputSize:"sm"})}),s.jsx(wn,{label:"Owner name",hint:"Optional.",children:s.jsx(Re,{value:T,onChange:Ce=>S(Ce.target.value),inputSize:"sm"})})]})]}),s.jsx(jl,{title:"Portal logins",description:"Passwords go into the vault only â never team notes. Seller Portal is the owner (or whoever AMs use by hand). Fill Gadjet agent later, once that Takealot user exists.",children:s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[s.jsx(wn,{label:"Seller Portal password",children:s.jsx(Re,{type:"password",autoComplete:"new-password",value:O,onChange:Ce=>R(Ce.target.value),inputSize:"sm"})}),s.jsx(wn,{label:"Who holds 2FA",hint:"Name only â not the password.",children:s.jsx(Re,{value:I,onChange:Ce=>$(Ce.target.value),inputSize:"sm"})}),s.jsx(wn,{label:"Ticket Centre username",hint:"Hard requirement â needed to perform tasks.",children:s.jsx(Re,{value:P,onChange:Ce=>F(Ce.target.value),inputSize:"sm"})}),s.jsx(wn,{label:"Ticket Centre password",children:s.jsx(Re,{type:"password",autoComplete:"new-password",value:Z,onChange:Ce=>D(Ce.target.value),inputSize:"sm"})}),s.jsx(wn,{label:"Adaptris username",hint:"Optional shipping add-on.",children:s.jsx(Re,{value:H,onChange:Ce=>Y(Ce.target.value),inputSize:"sm"})}),s.jsx(wn,{label:"Adaptris password",children:s.jsx(Re,{type:"password",autoComplete:"new-password",value:M,onChange:Ce=>z(Ce.target.value),inputSize:"sm"})})]})}),s.jsxs(jl,{title:"Billing",children:[s.jsx(wn,{label:"Company name (invoicing)",children:s.jsx(Re,{value:G,onChange:Ce=>te(Ce.target.value),inputSize:"sm"})}),s.jsx(eL,{value:re,onChange:L})]}),s.jsxs(jl,{title:"Warehouse",description:"Couriers use this address. If it's the same as billing, say so explicitly.",children:[s.jsxs("label",{className:"flex items-center gap-2 text-body-sm",children:[s.jsx(ei,{checked:q,onCheckedChange:Ce=>me(Ce===!0)}),"Same as billing, confirmed"]}),!q&&s.jsx(eL,{value:ee,onChange:ne}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[s.jsx(wn,{label:"Warehouse contact person",children:s.jsx(Re,{value:X,onChange:Ce=>he(Ce.target.value),inputSize:"sm"})}),s.jsx(wn,{label:"Contact phone",children:s.jsx(Re,{value:ae,onChange:Ce=>je(Ce.target.value),inputSize:"sm"})})]})]}),s.jsxs(jl,{title:"VAT and bank",description:"Needed for stock-loss claims and the monthly invoice.",children:[s.jsxs(vv,{value:$e,onValueChange:Ce=>J(Ce),className:"flex flex-row gap-6",children:[s.jsx(Vg,{value:"yes",label:"VAT-registered"}),s.jsx(Vg,{value:"no",label:"Not a VAT vendor"})]}),$e==="yes"&&s.jsx(wn,{label:"VAT number",hint:"10 digits starting with 4.",children:s.jsx(Re,{value:Ne,onChange:Ce=>ve(Ce.target.value),inputSize:"sm"})}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[s.jsx(wn,{label:"Account holder",children:s.jsx(Re,{value:Me,onChange:Ce=>Xe(Ce.target.value),inputSize:"sm"})}),s.jsx(wn,{label:"Bank",children:s.jsx(Re,{value:ze,onChange:Ce=>Fe(Ce.target.value),inputSize:"sm"})}),s.jsx(wn,{label:"Branch code",hint:"6 digits.",children:s.jsx(Re,{value:tt,onCh
907ange:Ce=>fe(Ce.target.value),inputSize:"sm"})}),s.jsx(wn,{label:"Account number",hint:"6â12 digits.",children:s.jsx(Re,{type:"password",autoComplete:"off",value:U,onChange:Ce=>ce(Ce.target.value),inputSize:"sm"})})]})]}),s.jsx(jl,{title:"Standard tasks",description:"Same matrix as the Managed Account panel. Morning Overview weekdays and monthly Stock Recon are ticked by default.",children:s.jsx("div",{className:"overflow-hidden rounded-lg border border-outline-subtle",children:s.jsxs("table",{className:"w-full text-sm",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"text-xs text-text-secondary bg-surface-subtle",children:[s.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Task"}),X$.map(Ce=>s.jsx("th",{className:"font-medium px-2 py-2 text-center w-14",children:Ce.label},Ce.dow))]})}),s.jsx("tbody",{className:"divide-y divide-outline-faint",children:jKe.map(Ce=>s.jsxs("tr",{children:[s.jsxs("td",{className:"px-3 py-2",children:[s.jsx("div",{className:"font-medium text-text-primary",children:Ce.label}),Ce.mode==="monthly_first_business_day"&&s.jsx("div",{className:"text-xs text-text-tertiary",children:"Monthly · 1st business day"})]}),Ce.mode==="weekly"?X$.map(yr=>s.jsx("td",{className:"px-2 py-2 text-center",children:s.jsx("div",{className:"inline-flex items-center justify-center",children:s.jsx(ei,{checked:ue.has(`${Ce.key}:${yr.dow}`),onCheckedChange:()=>St(Ce.key,yr.dow),"aria-label":`${Ce.label} on ${yr.label}`})})},yr.dow)):s.jsx("td",{colSpan:5,className:"px-2 py-2 text-center",children:s.jsx("div",{className:"inline-flex items-center justify-center",children:s.jsx(ei,{checked:ue.has(`${Ce.key}:0`),onCheckedChange:()=>St(Ce.key,0),"aria-label":`${Ce.label} monthly`})})})]},Ce.key))})]})})}),s.jsxs(jl,{title:"Handling notes",description:"These become team-only memories â staff chat can see them, the seller cannot.",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[s.jsx(wn,{label:"Shipment rhythm",children:s.jsx(Re,{value:bt,onChange:Ce=>Ze(Ce.target.value),placeholder:"e.g. Ships Mondays only",inputSize:"sm"})}),s.jsx(wn,{label:"Promo appetite",children:s.jsx(Re,{value:vt,onChange:Ce=>Ot(Ce.target.value),placeholder:"e.g. Won't discount over 15%",inputSize:"sm"})}),s.jsx(wn,{label:"Preferred channel",children:s.jsxs(Tt,{value:It,onChange:Ce=>Ut(Ce.target.value),inputSize:"sm",children:[s.jsx("option",{value:"whatsapp",children:"WhatsApp"}),s.jsx("option",{value:"email",children:"Email"}),s.jsx("option",{value:"phone",children:"Phone"})]})}),s.jsx(wn,{label:"Who to contact",children:s.jsx(Re,{value:Lr,onChange:Ce=>en(Ce.target.value),inputSize:"sm"})})]}),s.jsx(wn,{label:"Anything else",children:s.jsx(Ui,{value:Hs,onChange:Ce=>Os(Ce.target.value),rows:3,inputSize:"sm"})})]}),s.jsx(jl,{title:"Documents",description:"Optional. Retainer, VAT certificate, bank confirmation â stored on the seller, not in chat.",children:s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[s.jsx(ly,{label:"Signed retainer",kind:"signed_retainer",docs:gr,onFile:Jt}),s.jsx(ly,{label:"VAT certificate",kind:"vat_certificate",docs:gr,onFile:Jt}),s.jsx(ly,{label:"Bank confirmation",kind:"bank_confirmation",docs:gr,onFile:Jt}),s.jsx(ly,{label:"Other",kind:"other",docs:gr,onFile:Jt})]})}),De&&s.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-outline-error bg-surface-errorSubtle px-3 py-2 text-body-sm text-text-error",children:[s.jsx(yt,{className:"h-4 w-4 mt-0.5 shrink-0"}),s.jsx("span",{children:De})]})]}),s.jsx(da,{children:Ge?s.jsxs(s.Fragment,{children:[s.jsx(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",onClick:()=>pe(!1),children:"Close"}),s.jsx(W,{type:"button",intent:"brand",size:"sm",onClick:()=>{const Ce=Ge.slug;pe(!1),a(`/settings/stores/${encodeURIComponent(Ce)}/managed`)},children:"Open Managed Account"})]}):s.jsxs(s.Fragment,{children:[s.jsx(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",disabled:Xn,onClick:()=>pe(!1),children:"Cancel"}),s.jsxs(W,{type:"button",intent:"brand",size:"sm",disabled:!no,onClick:yn,children:[Xn?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):null,Xn?"Onboardingâ¦":"Create managed account"]})]})})]})})}function tL({label:e,value:t,hint:n}){return s.jsxs("div",{className:"space-y-1",children:[s.jsx(Fs,{children:e}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"flex-1 text-xs px-2 py-1.5 rounded bg-surface-sunken font-mono break-all",children:t}),s.jsx(W,{type:"button",size:"sm",intent:"neutral",variant:"outline",onClick:()=>{navigator.clipboard.writeText(t),Ae.success("Copied")},children:s.jsx(bi,{className:"h-3.5 w-3.5"})})]}),n&&s.jsx("p",{className:"text-[11px] text-text-tertiary",children:n})]})}function ly({label:e,kind:t,docs:n,onFile:r}){const a=n.filter(i=>i.kind===t);return s.jsxs("label",{className:"block rounded-md border border-dashed border-outline-subtle px-3 py-2 cursor-pointer hover:border-outline-brand",children:[s.jsxs("span",{className:"flex items-center gap-2 text-body-xs font-medium text-text-secondary",children:[s.jsx(ti,{className:"h-3.5 w-3.5"}),e]}),s.jsx("input",{type:"file",className:"sr-only",accept:".pdf,.png,.jpg,.jpeg,.webp,.docx,application/pdf,image/*",onChange:i=>{var o;r(t,((o=i.target.files)==null?void 0:o[0])??null),i.target.value=""}}),s.jsx("span",{className:B("mt-1 block text-[11px]",a.length?"text-text-primary":"text-text-tertiary"),children:a.length?a.map(i=>i.filename).join(", "):"PDF, image, or DOCX"})]})}const qq=p.createContext(null);function CKe({children:e}){const[t,n]=p.useState(!1),[r,a]=p.useState(),i=p.useCallback(l=>{a(l),n(!0)},[]),o=p.useMemo(()=>({openOnboardManagedAccount:i}),[i]);return s.jsxs(qq.Provider,{value:o,children:[e,s.jsx(SKe,{open:t,prefill:r,onOpenChange:n,onOnboarded:()=>ai()})]})}function Gq(){return p.useContext(qq)??{openOnboardManagedAccount:()=>{}}}const z3={};function Yq(e,t){const n={};return e!=="all"&&(n.view=e),t.search&&t.search.trim()&&(n.search=t.search.trim()),t.stages&&t.stages.length&&(n.stages=t.stages.join(",")),t.sources&&t.sources.length&&(n.sources=t.sources.join(",")),t.ownerId&&(n.owner_id=t.ownerId),t.nextAction&&(n.next_action=t.nextAction),t.staleDays&&t.staleDays>0&&(n.stale_days=t.staleDays),t.estRevMin!=null&&(n.est_rev_min=t.estRevMin),t.estRevMax!=null&&(n.est_rev_max=t.estRevMax),t.linked&&(n.linked=t.linked),t.region&&t.region.trim()&&(n.region=t.region.trim()),t.lastActivityDays&&t.lastActivityDays>0&&(n.last_activity_days=t.lastActivityDays),t.hasDemoScheduled!=null&&(n.has_demo_scheduled=t.hasDemoScheduled),n}function Zq(e){return{view:e.view??"all",filters:{search:e.search??null,stages:e.stages?e.stages.split(","):null,sources:e.sources?e.sources.split(","):null,ownerId:e.owner_id??null,
907nextAction:e.next_action??null,staleDays:e.stale_days??null,estRevMin:e.est_rev_min??null,estRevMax:e.est_rev_max??null,linked:e.linked??null,region:e.region??null,lastActivityDays:e.last_activity_days??null,hasDemoScheduled:e.has_demo_scheduled??null}}}function Xq(e,t,n){return JSON.stringify({f:Yq(e,t),sv:n??null})}function EKe(e){try{const t=JSON.parse(e),{view:n,filters:r}=Zq(t.f??{});return{view:n,filters:r,activeViewId:t.sv??null}}catch{return null}}const AKe=Xq("today",z3,null);function aj(e){const t=e.get("s");return(t?EKe(t):null)??{view:"today",filters:z3,activeViewId:null}}const TKe=[{key:"today",label:"Today"},{key:"pipeline",label:"Pipeline"},{key:"all",label:"All companies"}],Zc=["new","contacted","demo","negotiation","customer","upgrading","lost"],lf={new:"New",contacted:"Contacted",demo:"Demo",negotiation:"Negotiation",customer:"Customer",upgrading:"Upgrading",lost:"Lost"},OKe={new:`${Ve[1].tint} ${Ve[1].text}`,contacted:`${Ve[2].tint} ${Ve[2].text}`,demo:`${Ve[3].tint} ${Ve[3].text}`,negotiation:`${Ve[4].tint} ${Ve[4].text}`,customer:"bg-surface-successSubtle text-text-success",upgrading:`${Ve[5].tint} ${Ve[5].text}`,lost:"bg-surface-errorSubtle text-text-error"},IKe={new:{category:1},contacted:{category:2},demo:{category:3},negotiation:{category:4},customer:{tone:"success"},upgrading:{category:5},lost:{tone:"error"}},PKe={new:Ve[1].text,contacted:Ve[2].text,demo:Ve[3].text,negotiation:Ve[4].text,customer:"text-text-success",upgrading:Ve[5].text,lost:"text-text-error"},Jq=[{value:"referral",label:"Referral"},{value:"cold_outreach",label:"Cold Outreach"},{value:"inbound",label:"Inbound"},{value:"partner",label:"Partner"},{value:"other",label:"Other"}],Qq={referral:"Referral",cold_outreach:"Cold outreach",inbound:"Inbound",partner:"Partner",other:"Other"};function nL(e,t){if(!t)return"â";const n=e.find(r=>r.id===t);return(n==null?void 0:n.display_name)||(n==null?void 0:n.email)||"â"}function ij(e){return`R${e.toLocaleString("en-ZA",{maximumFractionDigits:0})}`}const RKe=10;function eG(e){return e.updated_at?Date.now()-new Date(e.updated_at).getTime()>RKe*24*60*60*1e3:!1}function YS(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString("en-ZA",{day:"2-digit",month:"short"})}function DKe(){const e=Lt(),t=Rt(),n=Ba(),[r,a]=ki(),{openOnboardManagedAccount:i}=Gq(),o=p.useCallback(J=>t(`/crm/${J}`,{state:{from:`/crm${n.search}`}}),[t,n.search]),[l,c]=p.useState(()=>aj(r).view),[u,d]=p.useState(()=>aj(r).filters),[h,f]=p.useState([]),[m,x]=p.useState(!0),[g,y]=p.useState(null),[b,v]=p.useState(0),[w,_]=p.useState(!1),[k,j]=p.useState(!1),[N,E]=p.useState(!1),[A,C]=p.useState(!1),[T,S]=p.useState([]),[O,R]=p.useState(()=>aj(r).activeViewId),[I,$]=p.useState(0),[P,F]=p.useState([]),[Z,D]=p.useState(()=>new Set),[H,Y]=p.useState(!1),M=p.useCallback(()=>{D(new Set),Y(!1)},[]),z=p.useCallback(()=>v(J=>J+1),[]),G=eB(u),te=JSON.stringify(u),re=p.useCallback(J=>{d(J),R(null)},[]);p.useEffect(()=>{let J=!0;return x(!0),y(null),Rr.listCompanies(l,u).then(Ne=>{J&&f(Array.isArray(Ne==null?void 0:Ne.companies)?Ne.companies:[])}).catch(Ne=>{J&&y(Ne.message)}).finally(()=>{J&&x(!1)}),()=>{J=!1}},[l,te,b]),p.useEffect(()=>{const J=()=>{document.visibilityState==="visible"&&v(Me=>Me+1)};document.addEventListener("visibilitychange",J);let Ne=new Date().getDate();const ve=window.setInterval(()=>{const Me=new Date().getDate();Me!==Ne&&(Ne=Me,v(Xe=>Xe+1))},6e4);return()=>{document.removeEventListener("visibilitychange",J),window.clearInterval(ve)}},[]),p.useEffect(()=>{M()},[l,te,b,M]),p.useEffect(()=>{let J=!0;return Rr.listSavedViews().then(Ne=>{J&&S(Array.isArray(Ne==null?void 0:Ne.views)?Ne.views:[])}).catch(()=>{}),()=>{J=!1}},[I]),p.useEffect(()=>{let J=!0;return vr.roster().then(Ne=>{J&&F(Array.isArray(Ne==null?void 0:Ne.users)?Ne.users:[])}).catch(()=>{}),()=>{J=!1}},[]),p.useEffect(()=>{const J=Xq(l,u,O),Ne=J===AKe?null:J;(r.get("s")??null)!==(Ne??null)&&a(ve=>{const Me=new URLSearchParams(ve);return Ne==null?Me.delete("s"):Me.set("s",Ne),Me},{replace:!0})},[l,te,O]);const L=p.useCallback(J=>{const{view:Ne,filters:ve}=Zq(J.filters_json);c(Ne),d(ve),R(J.id),E(!0)},[]),q=p.useCallback(J=>{C(!1),R(J.id),$(Ne=>Ne+1)},[]),me=p.useCallback(async J=>{try{await Rr.deleteSavedView(J),O===J&&R(null),$(Ne=>Ne+1)}catch(Ne){y(Ne instanceof Error?Ne.message:String(Ne))}},[O]),ee=p.useCallback(async(J,Ne)=>{try{await Rr.updateCompany(J,{stage:Ne}),z()}catch(ve){y(ve instanceof Error?ve.message:String(ve))}},[z]),ne=p.useCallback(J=>{Y(!1),D(Ne=>{const ve=new Set(Ne);return ve.has(J)?ve.delete(J):ve.add(J),ve})},[]),X=h.length>0&&Z.size===h.length,he=p.useCallback(()=>{Y(!1),D(J=>J.size===h.length?new Set:new Set(h.map(Ne=>Ne.id)))},[h]),ae=p.useCallback(async(J,Ne)=>{try{const ve=H?{filter:u,view:l}:{ids:[...Z]},Me=await Rr.bulkAction(J,ve,Ne);return M(),z(),y(null),Me.updated}catch(ve){return y(ve instanceof Error?ve.message:String(ve)),null}},[H,u,l,Z,M,z]),je=H?h.length:Z.size,$e=H||Z.size>0;return e.kind==="ready"&&e.me.role!=="super_admin"?s.jsx(Yt,{to:"/",replace:!0}):s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"CRM"}],actions:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(W,{type:"button",onClick:z,intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(vi,{className:"h-3.5 w-3.5"})," Refresh"]}),s.jsxs(W,{type:"button",onClick:()=>j(!0),intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(ti,{className:"h-3.5 w-3.5"})," Import"]}),s.jsxs(W,{type:"button",onClick:()=>i(),intent:"brand",size:"sm",children:[s.jsx(q2,{className:"h-3.5 w-3.5"})," Onboard managed account"]}),s.jsxs(W,{type:"button",onClick:()=>_(!0),intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(In,{className:"h-3.5 w-3.5"})," New company"]})]})}),s.jsx("div",{className:"flex-1 overflow-auto p-4 md:p-6",children:s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"border-b border-outline-subtle px-3 py-2 flex items-center gap-1 flex-wrap",children:[TKe.map(J=>s.jsx("button",{type:"button",onClick:()=>{c(J.key),R(null)},className:B("px-3 py-1.5 rounded-md text-xs font-medium whitespace-nowrap",l===J.key&&O===null?"bg-surface-inverse text-text-inverse":"text-text-secondary hover:bg-surface-sunken"),children:J.label},J.key)),s.jsx("div",{className:"w-px h-5 bg-outline-subtle mx-1 shrink-0"}),s.jsx(MKe,{views:T,activeViewId:O,onSelect:L,onDelete:me}),s.jsxs("span",{className:"ml-auto text-body-xs text-text-secondary shrink-0",children:[h.length,h.length===1e3?"+":""," ",h.length===1?"company":"companies"]})]}),s.jsxs("div",{className:"border-b border-outline-subtle px-3 py-2 flex items-center gap-2 flex-wrap",children:[s.jsxs("button",{type:"button",onClick:()=>E(J=>!J),className:B("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium",G?"bg-surface-brandSubtle text-text-brand":"bg-surface-sunken text-text-secondary hover:bg-surface-subtle"),children:[s.jsx(qre,{className:"h-3.5 w-3.5"}),"Filters",G&&s.jsx("span",{className:"ml-0.5 px-1.5 py-0.5 rounded-full bg-intent-brand text-text-inverse text-body-xs leading-none",children:"on"}),s.jsx(Pn,{className:B("h-3 w-3 transition-transform",N&&"rotate-180")}
907)]}),s.jsxs("div",{className:"relative",children:[s.jsx(Fa,{className:b2}),s.jsx("input",{type:"text",value:u.search??"",onChange:J=>re({...u,search:J.target.value||null}),placeholder:"Search companiesâ¦",className:`w-44 rounded-md bg-surface-sunken py-1.5 pr-2 text-xs outline-none focus:border-outline-brand focus-visible:shadow-focus ${v2}`})]}),G&&s.jsxs("button",{type:"button",onClick:()=>re(z3),className:"inline-flex items-center gap-1 text-xs text-text-secondary hover:text-text-primary",children:[s.jsx(Bn,{className:"h-3.5 w-3.5"})," Clear filters"]}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsxs(W,{type:"button",onClick:()=>C(!0),intent:"neutral",variant:"outline",size:"sm",disabled:!G&&l==="all",title:!G&&l==="all"?"Apply a filter first to save a view":"Save this filter as a named view",children:[s.jsx(e0,{className:"h-3.5 w-3.5"})," Save view"]})})]}),N&&s.jsx(LKe,{filters:u,onChange:re,roster:P}),$e&&s.jsx(FKe,{count:je,allMatching:H,loadedCount:h.length,canSelectAllMatching:X&&h.length>=1e3,onSelectAllMatching:()=>Y(!0),onClear:M,onRun:ae,roster:P}),g&&s.jsx("div",{className:"px-4 py-3 text-sm text-text-error bg-surface-errorSubtle border-b border-outline-error",children:g}),m?s.jsx("div",{className:"px-4 py-12 text-center text-sm text-text-tertiary",children:"Loadingâ¦"}):h.length===0?s.jsx(UKe,{view:l,onCreate:()=>_(!0)}):l==="pipeline"?s.jsx(WKe,{companies:h,onCardClick:o,onStageChange:ee}):s.jsx(zKe,{companies:h,view:l,selectedIds:Z,allMatching:H,onToggleRow:ne,onTogglePage:he,allLoadedSelected:X,onRowClick:o,onStageChange:ee,roster:P})]})}),w&&s.jsx(HKe,{onClose:()=>_(!1),onCreated:J=>{_(!1),o(J)}}),k&&s.jsx(GKe,{onClose:()=>j(!1),onImported:()=>{j(!1),z()}}),A&&s.jsx(BKe,{filtersJson:Yq(l,u),onClose:()=>C(!1),onSaved:q})]})}function MKe({views:e,activeViewId:t,onSelect:n,onDelete:r}){const[a,i]=p.useState(!1),o=e.find(l=>l.id===t)??null;return s.jsxs("div",{className:"relative shrink-0",children:[s.jsxs("button",{type:"button",onClick:()=>i(l=>!l),className:B("inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium whitespace-nowrap",o?"bg-surface-inverse text-text-inverse":"text-text-secondary hover:bg-surface-sunken"),children:[s.jsx(e0,{className:"h-3.5 w-3.5"}),o?o.name:"Views",s.jsx(Pn,{className:"h-3 w-3"})]}),a&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-10",onClick:()=>i(!1)}),s.jsx("div",{className:"absolute left-0 mt-1 z-20 w-60 bg-surface rounded-md shadow-lg border border-outline-subtle py-1 max-h-80 overflow-y-auto",children:e.length===0?s.jsx("div",{className:"px-3 py-2 text-xs text-text-tertiary",children:"No saved views yet. Apply filters and âSave viewâ."}):e.map(l=>s.jsxs("div",{className:B("group flex items-center gap-1 px-2 py-1.5 text-xs hover:bg-surface-sunken cursor-pointer",l.id===t&&"bg-surface-brandSubtle"),onClick:()=>{n(l),i(!1)},children:[s.jsx("span",{className:"flex-1 truncate text-text-primary",children:l.name}),s.jsx("button",{type:"button","aria-label":`Delete view ${l.name}`,onClick:c=>{c.stopPropagation(),r(l.id)},className:"opacity-0 group-hover:opacity-100 text-text-tertiary hover:text-text-error p-0.5",children:s.jsx(us,{className:"h-3.5 w-3.5"})})]},l.id))})]})]})}function rL({label:e,active:t,onClick:n,className:r}){return s.jsx("button",{type:"button",onClick:n,className:B("px-2 py-1 rounded-full text-[11px] font-medium border transition-colors",t?"border-outline-brand bg-surface-brandSubtle text-text-brand":"border-outline-subtle bg-surface-sunken text-text-secondary hover:border-outline-strong",r),children:e})}const $Ke=[{value:"account",label:"Signed up"},{value:"seller",label:"Has Takealot seller"},{value:"none",label:"Not linked"}];function LKe({filters:e,onChange:t,roster:n}){const r=i=>{const o=new Set(e.stages??[]);o.has(i)?o.delete(i):o.add(i),t({...e,stages:o.size?[...o]:null})},a=i=>{const o=new Set(e.sources??[]);o.has(i)?o.delete(i):o.add(i),t({...e,sources:o.size?[...o]:null})};return s.jsxs("div",{className:"border-b border-outline-subtle px-4 py-3 bg-surface-sunken/40 space-y-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-body-xs font-semibold uppercase tracking-wide text-text-tertiary mb-1.5",children:"Stage"}),s.jsx("div",{className:"flex flex-wrap gap-1.5",children:Zc.map(i=>s.jsx(rL,{label:lf[i],active:(e.stages??[]).includes(i),onClick:()=>r(i)},i))})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-body-xs font-semibold uppercase tracking-wide text-text-tertiary mb-1.5",children:"Source"}),s.jsx("div",{className:"flex flex-wrap gap-1.5",children:Jq.map(i=>s.jsx(rL,{label:i.label,active:(e.sources??[]).includes(i.value),onClick:()=>a(i.value)},i.value))})]}),s.jsxs("div",{className:"flex flex-wrap gap-4",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"block text-body-xs font-semibold uppercase tracking-wide text-text-tertiary mb-1",children:"Owner"}),s.jsxs("select",{value:e.ownerId??"",onChange:i=>t({...e,ownerId:i.target.value||null}),className:"py-1.5 px-2 rounded-md text-xs bg-surface border border-outline-subtle outline-none focus:border-outline-brand focus-visible:shadow-focus",children:[s.jsx("option",{value:"",children:"Any"}),n.map(i=>s.jsx("option",{value:i.id,children:i.display_name||i.email},i.id))]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"block text-body-xs font-semibold uppercase tracking-wide text-text-tertiary mb-1",children:"Next action"}),s.jsxs("select",{value:e.nextAction??"",onChange:i=>t({...e,nextAction:i.target.value||null}),className:"py-1.5 px-2 rounded-md text-xs bg-surface border border-outline-subtle outline-none focus:border-outline-brand focus-visible:shadow-focus",children:[s.jsx("option",{value:"",children:"Any"}),s.jsx("option",{value:"overdue",children:"Overdue / due"}),s.jsx("option",{value:"none",children:"None set"}),s.jsx("option",{value:"upcoming",children:"Upcoming"})]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"block text-body-xs font-semibold uppercase tracking-wide text-text-tertiary mb-1",children:"App linkage"}),s.jsxs("select",{value:e.linked??"",onChange:i=>t({...e,linked:i.target.value||null}),className:"py-1.5 px-2 rounded-md text-xs bg-surface border border-outline-subtle outline-none focus:border-outline-brand focus-visible:shadow-focus",children:[s.jsx("option",{value:"",children:"Any"}),$Ke.map(i=>s.jsx("option",{value:i.value,children:i.label},i.value))]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"block text-body-xs font-semibold uppercase tracking-wide text-text-tertiary mb-1",children:"Last activity"}),s.jsxs("select",{value:e.lastActivityDays??"",onChange:i=>t({...e,lastActivityDays:i.target.value?Number(i.target.value):null}),className:"py-1.5 px-2 rounded-md text-xs bg-surface border border-outline-subtle outline-none focus:border-outline-brand focus-visible:shadow-focus",title:"No logged activity in at least N days (or never)",children:[s.jsx("option",{value:"",children:"Any"}),s.jsx("option",{value:"14",children:"No touch 14+ days"}),s.jsx("option",{value:"30",children:"No touch 30+ days"}),s.jsx("option",{value:"60",children:"No touch 60+ days"}),s.jsx("option",{value:"90",children:"No touch 90+ days"})]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"block text-body-xs font-semibold uppercase tracking-wide text-text-tertiary mb-1",children:"Last update"}),s.jsxs("select",{value:e.staleDays??"",onChange:i=>t({...e,staleDays:i.target.value?Number(i.target.value):null}),className:"py-1.5 px-2 rounded-md text-xs bg-surface border border-outline-subtle outline-none focus:border-outline-brand focus-visible:shadow-focus",title:"Record not updated in at least N days",children:[s.jsx("option",{value:"",children:"Any"}),s.jsx("option",{value:"7",children:"Not in 7+ days"}),s.jsx("option",{value:"14",children:"Not in 14+ days"}),s.jsx("option",{value:"30",children:"Not in 30+ days"}),s.jsx("option",{value:"60",children:"Not in 60+ days"})]})]}),s.jsxs("div",{className:"block",children:[s.jsx("span",{className:"block text-body-xs font-semibold uppercase tracking-wide text-text-tertiary mb-1",children:"Est. revenue (ZAR)"}),s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"number",min:0,value:e.estRevMin??"",onChange:i=>t({...e,estRevMin:i.target.value?Number(i.target.value):null}),placeholder:"min",className:"w-24 py-1.5 px-2 rounded-md text-xs bg-surface border border-outline-subtle outline-none focus:border-outline-brand focus-visible:shadow-focus"}),s.jsx("span",{className:"text-text-tertiary text-xs",children:"â"}),s.jsx("input",{type:"number",min:0,value:e.estRevMax??"",onChange:i=>t({...e,estRevMax:i.target.value?Number(i.target.value):null}),placeholder:"max",className:"w-24 py-1.5 px-2 rounded-md text-xs bg-surface border border-outline-subtle outline-none focus:border-outline-brand focus-visible:shadow-focus"})]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"block text-body-xs font-semibold uppercase tracking-wide text-text-tertiary mb-1",children:"Region"}),s.jsx("input",{type:"text",value:e.region??"",onChange:i=>t({...e,region:i.target.value||null}),placeholder:"e.g. Cape Town",className:"w-36 py-1.5 px-2 rounded-md text-xs bg-surface border border-outline-subtle outline-none focus:border-outline-brand focus-visible:shadow-focus"})]})]})]})}function FKe({count:e,allMatching:t,loadedCount:n,canSelectAllMatching:r,onSelectAllMatching:a,onClear:i,onRun:o,roster:l}
907){const[c,u]=p.useState(""),[d,h]=p.useState(!1),[f,m]=p.useState(null),x=async(g,y)=>{h(!0),m(null);const b=await o(g,y);h(!1),b!=null&&(m(`Updated ${b}`),u(""))};return s.jsxs("div",{className:"border-b border-outline-brand bg-surface-brandSubtle px-4 py-2.5 flex items-center gap-3 flex-wrap text-xs",children:[s.jsxs("span",{className:"font-semibold text-text-brand",children:[t?"All matching filter":`${e} selected`,!t&&n>0?` of ${n}`:""]}),r&&!t&&s.jsx("button",{type:"button",onClick:a,className:"text-text-brand underline",children:"Select all matching filter"}),s.jsx("div",{className:"w-px h-5 bg-brand-200"}),s.jsxs("div",{className:"inline-flex items-center gap-1.5",children:[s.jsx(Qp,{className:"h-3.5 w-3.5 text-text-brand"}),s.jsx("input",{type:"date",value:c,onChange:g=>u(g.target.value),className:"py-1 px-1.5 rounded border border-brand-300 bg-surface outline-none focus:border-outline-brand focus-visible:shadow-focus"}),s.jsx(W,{type:"button",size:"sm",intent:"brand",disabled:d||!c,onClick:()=>x("set_next_action",{next_action_at:c}),children:"Set next action"})]}),s.jsxs("select",{defaultValue:"",disabled:d,onChange:g=>{const y=g.target.value;y&&x("set_stage",{stage:y}),g.target.value=""},className:"py-1.5 px-2 rounded-md bg-surface border border-brand-300 outline-none focus:border-outline-brand focus-visible:shadow-focus",title:"Move the block to a stage",children:[s.jsx("option",{value:"",children:"Move to stageâ¦"}),Zc.map(g=>s.jsx("option",{value:g,children:lf[g]},g))]}),s.jsxs("select",{defaultValue:"",disabled:d||l.length===0,onChange:g=>{const y=g.target.value;y&&x("assign_owner",{owner_id:y}),g.target.value=""},className:"py-1.5 px-2 rounded-md bg-surface border border-brand-300 outline-none focus:border-outline-brand focus-visible:shadow-focus",title:"Assign an owner to the selection",children:[s.jsx("option",{value:"",children:"Assign ownerâ¦"}),l.map(g=>s.jsx("option",{value:g.id,children:g.display_name||g.email},g.id))]}),s.jsx("button",{type:"button",disabled:d,onClick:()=>x("clear_next_action",{}),className:"text-text-secondary hover:text-text-primary underline disabled:opacity-50",children:"Clear next action"}),f&&s.jsx("span",{className:"text-text-success font-medium",children:f}),s.jsxs("button",{type:"button",onClick:i,className:"ml-auto inline-flex items-center gap-1 text-text-secondary hover:text-text-primary",children:[s.jsx(Bn,{className:"h-3.5 w-3.5"})," Clear selection"]})]})}function BKe({filtersJson:e,onClose:t,onSaved:n}){const[r,a]=p.useState(""),[i,o]=p.useState(!1),[l,c]=p.useState(null),u=async d=>{if(d.preventDefault(),!!r.trim()){o(!0),c(null);try{const h=await Rr.createSavedView({name:r.trim(),filters_json:e});n(h.view)}catch(h){c(h instanceof Error?h.message:String(h))}finally{o(!1)}}};return s.jsx("div",{className:"fixed inset-0 z-modal bg-black/30 flex items-center justify-center p-4",onClick:t,children:s.jsxs("div",{className:"bg-surface rounded-lg shadow-xl w-full max-w-sm p-6",onClick:d=>d.stopPropagation(),children:[s.jsx("h2",{className:"text-lg font-semibold mb-1",children:"Save view"}),s.jsx("p",{className:"text-xs text-text-secondary mb-4",children:"Saves the current filters as a named view, shared with the team. Re-using a name overwrites it."}),s.jsxs("form",{onSubmit:u,className:"space-y-3",children:[s.jsx("input",{autoFocus:!0,value:r,onChange:d=>a(d.target.value),placeholder:"e.g. Negotiations â no next action",maxLength:80,className:"w-full rounded-md border border-outline-subtle px-2.5 py-1.5 text-sm outline-none focus:border-outline-brand focus-visible:shadow-focus"}),l&&s.jsx("div",{className:"text-xs text-text-error",children:l}),s.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[s.jsx(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",onClick:t,children:"Cancel"}),s.jsx(W,{type:"submit",intent:"brand",size:"sm",disabled:i||!r.trim(),children:i?"Savingâ¦":"Save"})]})]})]})})}function UKe({view:e,onCreate:t}){const n=e==="today"?"Nothing due today. Set a next-action on a company to surface it here.":e==="pipeline"?"Pipeline is empty. Add a company to get started.":"No companies yet. Sign-ups auto-populate the list; add leads manually with the button below.";return s.jsxs("div",{className:"px-6 py-16 text-center",children:[s.jsx(xf,{className:"mx-auto h-8 w-8 text-text-tertiary mb-3"}),s.jsx("p",{className:"text-sm text-text-secondary mb-4 max-w-md mx-auto",children:n}),s.jsxs(W,{type:"button",onClick:t,intent:"brand",size:"sm",children:[s.jsx(In,{className:"h-3.5 w-3.5"})," New company"]})]})}function zKe({companies:e,view:t,selectedIds:n,allMatching:r,allLoadedSelected:a,onToggleRow:i,onTogglePage:o,onRowClick:l,onStageChange:c,roster:u}){const d=[{key:"name",label:"Company",sortable:!0,sticky:!0,getValue:h=>h.name,headerPrefix:s.jsx("input",{type:"checkbox","aria-label":"Select page",checked:r||a,ref:h=>{h&&(h.indeterminate=!r&&!a&&n.size>0)},onChange:o,className:"align-middle accent-brand-600 cursor-pointer"}),render:h=>s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("input",{type:"checkbox","aria-label":`Select ${h.name}`,checked:r||n.has(h.id),onChange:()=>i(h.id),onClick:f=>f.stopPropagation(),className:"align-middle accent-brand-600 cursor-pointer shrink-0"}),s.jsx("span",{className:"truncate",children:h.name}),eG(h)&&s.jsx(_n,{tone:"error",className:"shrink-0",children:"STALE"}),(h.account_id||h.seller_slug)&&s.jsx(_n,{tone:"success",className:"shrink-0",children:h.account_id?"Signed up":"Seller"})]})},{key:"stage",label:"Stage",sortable:!0,getValue:h=>h.stage?Zc.indexOf(h.stage):null,render:h=>s.jsx(KKe,{stage:h.stage,onChange:f=>c(h.id,f)})},{key:"source",label:"Source",sortable:!1,getValue:h=>h.source,render:h=>s.jsx("span",{className:"text-text-secondary",children:h.source?Qq[h.source]:"â"})},{key:"due",label:t==="today"?"Due":"Next action",sortable:!0,getValue:h=>h.next_action_at,render:h=>s.jsx("span",{className:"text-text-secondary",children:YS(h.next_action_at)||"â"})},{key:"owner",label:"Owner",sortable:!1,getValue:h=>nL(u,h.owner_id),render:h=>s.jsx("span",{className:"text-text-secondary",children:nL(u,h.owner_id)})},{key:"updated",label:"Last update",sortable:!0,getValue:h=>h.updated_at,render:h=>s.jsx("span",{className:"text-text-secondary",children:YS(h.updated_at)})}
907,{key:"revenue",label:"Est. revenue",sortable:!0,align:"right",getValue:h=>h.estimated_revenue!=null?Number(h.estimated_revenue):null,render:h=>s.jsx("span",{className:"text-text-secondary tabular-nums",children:h.estimated_revenue!=null?`R${Number(h.estimated_revenue).toLocaleString()}`:""})}];return s.jsx(dt,{rows:e,columns:d,getRowKey:h=>h.id,empty:{title:"No companies match."},onRowClick:h=>l(h.id),rowClassName:h=>r||n.has(h.id)?"bg-surface-brandSubtle/50":void 0})}function WKe({companies:e,onCardClick:t,onStageChange:n}){const[r,a]=p.useState(null),[i,o]=p.useState(null),l=p.useMemo(()=>{var h;const d=new Map;for(const f of Zc)d.set(f,[]);for(const f of e)f.stage&&((h=d.get(f.stage))==null||h.push(f));return d},[e]),c=p.useMemo(()=>Zc.map(d=>{const h=l.get(d)??[],f=h.reduce((m,x)=>m+(x.estimated_revenue!=null?Number(x.estimated_revenue):0),0);return{stage:d,count:h.length,revenue:f}}),[l]),u=(d,h)=>{h.preventDefault();const f=h.dataTransfer.getData("text/plain")||r;if(a(null),o(null),!f)return;const m=e.find(x=>x.id===f);!m||m.stage===d||n(f,d)};return s.jsxs("div",{children:[s.jsx("div",{className:"flex gap-2 px-3 pt-3 overflow-x-auto",children:c.map(d=>s.jsxs("div",{className:"shrink-0 px-2 py-1 rounded-md bg-surface-sunken text-[11px] text-text-secondary",children:[s.jsx("span",{className:B("font-medium",PKe[d.stage]),children:lf[d.stage]})," · ",d.count,d.revenue>0&&s.jsxs(s.Fragment,{children:[" · ",ij(d.revenue)]})]},d.stage))}),s.jsx("div",{className:"overflow-x-auto",children:s.jsx("div",{className:"flex gap-3 p-3 min-h-[60vh]",children:Zc.map(d=>{const h=l.get(d)??[],f=h.reduce((m,x)=>m+(x.estimated_revenue!=null?Number(x.estimated_revenue):0),0);return s.jsxs("div",{className:B("w-64 shrink-0 bg-surface-sunken rounded-lg p-2 transition-colors",i===d&&"ring-2 ring-brand-400 bg-surface-brandSubtle/40"),onDragOver:m=>{m.preventDefault(),m.dataTransfer.dropEffect="move",i!==d&&o(d)},onDragLeave:m=>{m.currentTarget.contains(m.relatedTarget)||i===d&&o(null)},onDrop:m=>u(d,m),children:[s.jsxs("div",{className:"flex items-center justify-between px-2 py-1.5 mb-2 gap-2",children:[s.jsx(_n,{...IKe[d],children:lf[d]}),s.jsxs("span",{className:"text-xs text-text-tertiary tabular-nums text-right",children:[h.length,f>0&&s.jsx("span",{className:"block text-body-xs",children:ij(f)})]})]}),s.jsx("div",{className:"space-y-2 min-h-[4rem]",children:h.map(m=>s.jsxs("div",{draggable:!0,onDragStart:x=>{x.dataTransfer.setData("text/plain",m.id),x.dataTransfer.effectAllowed="move",a(m.id)},onDragEnd:()=>{a(null),o(null)},onClick:()=>t(m.id),className:B("w-full text-left bg-surface rounded-md border border-outline-subtle p-2.5 hover:border-outline-strong cursor-grab active:cursor-grabbing",r===m.id&&"opacity-50"),children:[s.jsx("div",{className:"text-sm font-medium text-text-primary truncate",children:m.name}),s.jsxs("div",{className:"flex items-center gap-1.5 mt-1 flex-wrap",children:[m.source&&s.jsx("span",{className:"text-body-xs text-text-tertiary",children:Qq[m.source]}),eG(m)&&s.jsx(_n,{tone:"error",children:"STALE"})]}),m.estimated_revenue!=null&&s.jsx("div",{className:"text-xs text-text-tertiary tabular-nums mt-1",children:ij(Number(m.estimated_revenue))}),m.next_action_at&&s.jsxs("div",{className:"text-xs text-text-secondary mt-1",children:["Due ",YS(m.next_action_at)]})]},m.id))})]},d)})})})]})}function KKe({stage:e,onChange:t}){return s.jsxs("select",{value:e??"",onClick:n=>n.stopPropagation(),onChange:n=>t(n.target.value||null),className:B("text-xs rounded px-1.5 py-1 border-0 outline-none focus:border-outline-brand focus-visible:shadow-focus",e?OKe[e]:"bg-surface-sunken text-text-secondary"),children:[s.jsx("option",{value:"",children:"â"}),Zc.map(n=>s.jsx("option",{value:n,children:lf[n]},n))]})}function HKe({onClose:e,onCreated:t}){const[n,r]=p.useState(""),[a,i]=p.useState("cold_outreach"),[o,l]=p.useState("new"),[c,u]=p.useState(""),[d,h]=p.useState(""),[f,m]=p.useState(!1),[x,g]=p.useState(null),y=async b=>{if(b.preventDefault(),!!n.trim()){m(!0),g(null);try{const v=await Rr.createCompany({name:n.trim(),source:a,stage:o,estimated_revenue:c?Number(c):null,takealot_seller_url:d.trim()||null});t(v.company.id)}catch(v){g(v instanceof Error?v.message:String(v))}finally{m(!1)}}};return s.jsx("div",{className:"fixed inset-0 z-modal bg-black/30 flex items-center justify-center p-4",onClick:e,children:s.jsxs("div",{className:"bg-surface rounded-lg shadow-xl w-full max-w-md p-6",onClick:b=>b.stopPropagation(),children:[s.jsx("h2",{className:"text-lg font-semibold mb-4",children:"New company"}),s.jsxs("form",{onSubmit:y,className:"space-y-3",children:[s.jsx(km,{label:"Company name",children:s.jsx("input",{autoFocus:!0,value:n,onChange:b=>r(b.target.value),className:"w-full rounded-md border border-outline-subtle px-2.5 py-1.5 text-sm outline-none focus:border-outline-brand focus-visible:shadow-focus",required:!0,maxLength:200})}),s.jsx(km,{label:"Source",children:s.jsx("select",{value:a,onChange:b=>i(b.target.value),className:"w-full rounded-md border border-outline-subtle px-2.5 py-1.5 text-sm outline-none focus:border-outline-brand focus-visible:shadow-focus",children:Jq.map(b=>s.jsx("option",{value:b.value,children:b.label},b.value))})}),s.jsx(km,{label:"Stage",children:s.jsx("select",{value:o,onChange:b=>l(b.target.value),className:"w-full rounded-md border border-outline-subtle px-2.5 py-1.5 text-sm outline-none focus:border-outline-brand focus-visible:shadow-focus",children:Zc.map(b=>s.jsx("option",{value:b,children:lf[b]},b))})}),s.jsx(km,{label:"Est. monthly revenue (ZAR)",children:s.jsx("input",{type:"number",value:c,onChange:b=>u(b.target.value),className:"w-full rounded-md border border-outline-subtle px-2.5 py-1.5 text-sm outline-none focus:border-outline-brand focus-visible:shadow-focus",min:0})}),s.jsx(km,{label:"Takealot store URL (optional)",children:s.jsx("input",{type:"url",value:d,onChange:b=>h(b.target.value),placeholder:"https://www.takealot.com/all?sellers=â¦",className:"w-full rounded-md border border-outline-subtle px-2.5 py-1.5 text-sm outline-none focus:border-outline-brand focus-visible:shadow-focus"})}),x&&s.jsx("div",{className:"text-xs text-text-error",children:x}),s.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[s.jsx(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",onClick:e,children:"Cancel"}),s.jsx(W,{type:"submit",intent:"brand",size:"sm",disabled:f||!n.trim(),children:f?"Creatingâ¦":"Create"})]})]})]})})}function km({label:e,children:t}){return s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"block text-xs font-medium text-text-secondary mb-1",children:e}),t]})}const VKe=[{key:"name",label:"Name",render:e=>
907e.name??""},{key:"stage",label:"Stage",render:e=>s.jsx("span",{className:"text-text-secondary",children:e.stage??""})},{key:"source",label:"Source",render:e=>s.jsx("span",{className:"text-text-secondary",children:e.source??""})},{key:"revenue",label:"Est. revenue",align:"right",getValue:e=>e.estimated_revenue!=null?Number(e.estimated_revenue):null,render:e=>s.jsx("span",{className:"text-text-secondary tabular-nums",children:e.estimated_revenue!=null?`R${Number(e.estimated_revenue).toLocaleString()}`:""})}],tG=["name","legal_name","source","stage","estimated_revenue","website","takealot_seller_url","notes"];function qKe(e){const t=e.split(/\r?\n/).map(a=>a.trim()).filter(a=>a.length>0);if(t.length<2)return[];const n=t[0].split(" ").map(a=>a.trim().toLowerCase().replace(/ /g,"_")),r=[];for(let a=1;a<t.length;a++){const i=t[a].split(" "),o={};n.forEach((l,c)=>{if(!tG.includes(l))return;const u=(i[c]??"").trim();if(u)if(l==="estimated_revenue"){const d=Number(u.replace(/[^0-9.\-]/g,""));o[l]=Number.isFinite(d)?d:null}else o[l]=u}),o.name&&r.push(o)}return r}function GKe({onClose:e,onImported:t}){const[n,r]=p.useState(""),[a,i]=p.useState(!1),[o,l]=p.useState(null),[c,u]=p.useState(null),d=p.useMemo(()=>qKe(n),[n]),h=async f=>{if(f.preventDefault(),d.length!==0){i(!0),l(null),u(null);try{const m=await Rr.bulkImport(d);u(m)}catch(m){l(m instanceof Error?m.message:String(m))}finally{i(!1)}}};return s.jsx("div",{className:"fixed inset-0 z-modal bg-black/30 flex items-center justify-center p-4",onClick:e,children:s.jsxs("div",{className:"bg-surface rounded-lg shadow-xl w-full max-w-2xl p-6 max-h-[90vh] overflow-y-auto",onClick:f=>f.stopPropagation(),children:[s.jsx("h2",{className:"text-lg font-semibold mb-1",children:"Bulk import"}),s.jsxs("p",{className:"text-xs text-text-secondary mb-4",children:["Paste TSV (copy a range from Google Sheets / Excel). First row = headers. Recognised columns:"," ",s.jsx("code",{className:"text-[11px]",children:tG.join(", ")}),". Duplicates by name are skipped."]}),!c&&s.jsxs("form",{onSubmit:h,className:"space-y-3",children:[s.jsx("textarea",{value:n,onChange:f=>r(f.target.value),rows:10,placeholder:`name source stage estimated_revenue 908Acme referral new 250000 909Bravo cold_outreach contacted 800000`,className:"w-full font-mono text-xs rounded-md border border-outline-subtle px-2.5 py-1.5 outline-none focus:border-outline-brand focus-visible:shadow-focus"}),s.jsx("div",{className:"text-xs text-text-secondary",children:d.length===0?"Paste data to preview.":`Parsed ${d.length} row${d.length===1?"":"s"}.`}),d.length>0&&s.jsx("div",{className:"border border-outline-subtle rounded-md overflow-hidden max-h-48 overflow-y-auto",children:s.jsx(dt,{rows:d.slice(0,20),columns:VKe,getRowKey:(f,m)=>`${f.name??""}-${m}`,paginate:!1,persist:!1,tableClassName:"text-xs",empty:{title:"Paste data to preview."},footer:d.length>20?s.jsx("tfoot",{children:s.jsx("tr",{children:s.jsxs("td",{colSpan:4,className:"py-2 text-center text-text-tertiary",children:["â¦",d.length-20," more"]})})}):void 0})}),o&&s.jsx("div",{className:"text-xs text-text-error",children:o}),s.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[s.jsx(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",onClick:e,children:"Cancel"}),s.jsx(W,{type:"submit",intent:"brand",size:"sm",disabled:a||d.length===0,children:a?"Importingâ¦":`Import ${d.length}`})]})]}),c&&s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[s.jsxs("div",{className:"p-3 rounded-md bg-surface-successSubtle",children:[s.jsx("div",{className:"text-xl font-semibold text-text-success",children:c.created}),s.jsx("div",{className:"text-xs text-text-success",children:"created"})]}),s.jsxs("div",{className:"p-3 rounded-md bg-surface-warningSubtle",children:[s.jsx("div",{className:"text-xl font-semibold text-text-warning",children:c.skipped}),s.jsx("div",{className:"text-xs text-text-warning",children:"skipped (duplicate)"})]}),s.jsxs("div",{className:"p-3 rounded-md bg-surface-errorSubtle",children:[s.jsx("div",{className:"text-xl font-semibold text-text-error",children:c.errors.length}),s.jsx("div",{className:"text-xs text-text-error",children:"errors"})]})]}),c.errors.length>
9090&&s.jsx("div",{className:"border border-outline-error rounded-md max-h-40 overflow-y-auto p-2",children:c.errors.map((f,m)=>s.jsxs("div",{className:"text-xs text-text-error",children:["Row ",f.row+1," ",f.name?`(${f.name})`:"",": ",f.error]},m))}),s.jsx("div",{className:"flex justify-end",children:s.jsx(W,{type:"button",intent:"brand",size:"sm",onClick:t,children:"Done"})})]})]})})}const YKe=["new","contacted","demo","negotiation","customer","upgrading","lost"],ZKe={new:"New",contacted:"Contacted",demo:"Demo",negotiation:"Negotiation",customer:"Customer",upgrading:"Upgrading",lost:"Lost"},nG=[{value:"call",label:"Call",icon:dF},{value:"email",label:"Email",icon:p6},{value:"whatsapp",label:"WhatsApp",icon:rre},{value:"demo",label:"Demo",icon:fse},{value:"note",label:"Note",icon:pF}],ZS=[{value:"no_answer",label:"No answer"},{value:"spoke",label:"Spoke to contact"},{value:"info_sent",label:"Info sent"},{value:"demo_booked",label:"Demo booked"},{value:"follow_up",label:"Follow up later"},{value:"wrong_contact",label:"Wrong contact"},{value:"not_interested",label:"Not interested"},{value:"converted",label:"Converted"},{value:"other",label:"Other"}],Sa="rounded-md border border-outline-subtle px-2 py-1 text-xs outline-none focus:border-outline-brand focus-visible:shadow-focus";function XKe(e){if(!e)return"â";const t=new Date(e);return Number.isNaN(t.getTime())?"â":t.toLocaleDateString("en-ZA",{day:"2-digit",month:"short",year:"numeric"})}function JKe(e){if(!e)return"â";const t=new Date(e);return Number.isNaN(t.getTime())?"â":t.toLocaleString("en-ZA",{day:"2-digit",month:"short",hour:"2-digit",minute:"2-digit"})}function Sv(e){if(!e)return"";const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const n=Date.now()-t.getTime(),r=Math.round(n/1e3);if(Math.abs(r)<60)return"just now";const a=Math.round(r/60);if(Math.abs(a)<60)return`${a}m ago`;const i=Math.round(a/60);return Math.abs(i)<24?`${i}h ago`:`${Math.round(i/24)}d ago`}function QKe(e,t){if(!t)return"Unassigned";const n=e.find(r=>r.id===t);return(n==null?void 0:n.display_name)||(n==null?void 0:n.email)||"Unassigned"}function eHe(e){let t=e.replace(/\D/g,"");return t.startsWith("00")&&(t=t.slice(2)),t.startsWith("0")&&(t="27"+t.slice(1)),`https://wa.me/${t}`}function tHe(e){return/^https?:\/\//i.test(e)?e:`https://${e}`}function nHe(e,t){const n=t.find(r=>r.is_primary)??t[0];return{displayName:e.name||void 0,billingName:e.legal_name||void 0,vatNumber:e.vat_number||void 0,notes:e.notes||void 0,ownerEmail:(n==null?void 0:n.email)||void 0,ownerName:(n==null?void 0:n.name)||void 0,whoContact:(n==null?void 0:n.name)||void 0,channel:n!=null&&n.whatsapp_number?"whatsapp":void 0}}function rHe(){var C,T;const e=Lt(),t=Rt(),n=Ba(),{id:r}=jn(),{openOnboardManagedAccount:a}=Gq(),i=((C=n.state)==null?void 0:C.from)??"/crm",[o,l]=p.useState(null),[c,u]=p.useState(null),[d,h]=p.useState([]),[f,m]=p.useState([]),[x,g]=p.useState([]),[y,b]=p.useState(!0),[v,w]=p.useState(null),[_,k]=p.useState(0),j=p.useCallback(()=>k(S=>S+1),[]);p.useEffect(()=>{let S=!0;return vr.roster().then(O=>{S&&g(Array.isArray(O==null?void 0:O.users)?O.users:[])}).catch(()=>{}),()=>{S=!1}},[]),p.useEffect(()=>{if(!r)return;let S=!0;return b(!0),w(null),Promise.all([Rr.getCompany(r),Rr.getAppProfile(r),Rr.listActivities(r),Rr.listContacts(r)]).then(([O,R,I,$])=>{S&&(l((O==null?void 0:O.company)??null),u((R==null?void 0:R.profile)??null),h(Array.isArray(I==null?void 0:I.activities)?I.activities:[]),m(Array.isArray($==null?void 0:$.contacts)?$.contacts:[]))}).catch(O=>{S&&w(O.message)}).finally(()=>{S&&b(!1)}),()=>{S=!1}},[r,_]);const N=p.useCallback(async S=>{if(r)try{const O=await Rr.updateCompany(r,S);l(O.company)}catch(O){w(O instanceof Error?O.message:String(O))}},[r]),E=p.useCallback(async()=>{if(!(!r||!o)&&confirm(`Delete ${o.name}? This removes contacts and activities too.`))try{await Rr.deleteCompany(r),t("/crm")}catch(S){w(S instanceof Error?S.message:String(S))}},[r,o,t]);if(e.kind==="ready"&&e.me.role!=="super_admin")return s.jsx(Yt,{to:"/",replace:!0});if(!r)return s.jsx(Yt,{to:"/crm",replace:!0});const A=!!(o!=null&&o.seller_slug)||(((T=c==null?void 0:c.sellers)==null?void 0:T.length)??0)>0;return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"CRM",to:i},{label:(o==null?void 0:o.name)??"â¦"}],actions:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(W,{type:"button",onClick:j,intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(vi,{className:"h-3.5 w-3.5"})," Refresh"]}),!A&&s.jsxs(W,{type:"button",onClick:()=>o&&a(nHe(o,f)),intent:"brand",size:"sm",disabled:!o,children:[s.jsx(q2,{className:"h-3.5 w-3.5"})," Onboard managed account"]}),s.jsxs(W,{type:"button",onClick:E,intent:"destructive",variant:"outline",size:"sm",disabled:!o,children:[s.jsx(us,{className:"h-3.5 w-3.5"}),"Delete"]})]})}),s.jsxs("div",{className:"flex-1 overflow-auto p-4 md:p-6 space-y-4",children:[s.jsxs(st,{to:i,className:"inline-flex items-center gap-1 text-xs text-text-secondary hover:text-text-primary",children:[s.jsx(ff,{className:"h-3.5 w-3.5"})," Back to CRM"]}),v&&s.jsx("div",{className:"px-4 py-3 text-sm text-text-error bg-surface-errorSubtle border border-outline-error roun
909ded-md",children:v}),y&&!o?s.jsx(V,{className:"px-4 py-12 text-center text-sm text-text-tertiary",children:"Loadingâ¦"}):o?s.jsxs(s.Fragment,{children:[s.jsx(sHe,{company:o,roster:x,onPatch:N}),c&&s.jsx(aHe,{profile:c}),s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[s.jsx("div",{className:"lg:col-span-2 space-y-4",children:s.jsx(iHe,{companyId:r,activities:d,contacts:f,onLogged:j})}),s.jsxs("div",{className:"space-y-4",children:[s.jsx(cHe,{companyId:r,contacts:f,onChanged:j}),s.jsx(uHe,{company:o,onPatch:N})]})]})]}):s.jsx(V,{className:"px-4 py-12 text-center text-sm text-text-tertiary",children:"Company not found."})]})]})}function sHe({company:e,roster:t,onPatch:n}){const[r,a]=p.useState(!1),[i,o]=p.useState(e.name),l=e.next_action_at?new Date(e.next_action_at).toISOString().slice(0,16):"";p.useEffect(()=>{o(e.name)},[e.name]);const c=()=>{a(!1);const u=i.trim();if(!u){o(e.name);return}u!==e.name&&n({name:u})};return s.jsx(V,{className:"p-4",children:s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[r?s.jsx("input",{autoFocus:!0,value:i,onChange:u=>o(u.target.value),onBlur:c,onKeyDown:u=>{u.key==="Enter"&&c(),u.key==="Escape"&&(o(e.name),a(!1))},className:"text-xl font-semibold text-text-primary mr-auto rounded-md border border-outline-subtle px-2 py-0.5 outline-none focus:border-outline-brand focus-visible:shadow-focus min-w-[12rem] flex-1",maxLength:200}):s.jsxs("button",{type:"button",onClick:()=>a(!0),className:"group inline-flex items-center gap-1.5 text-xl font-semibold text-text-primary mr-auto text-left hover:text-text-brand",title:"Rename",children:[e.name,s.jsx(Qi,{className:"h-3.5 w-3.5 text-text-tertiary opacity-0 group-hover:opacity-100"})]}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary",children:["Owner:",s.jsxs("select",{value:e.owner_id??"",onChange:u=>n({owner_id:u.target.value||null}),className:Sa,children:[s.jsx("option",{value:"",children:"Unassigned"}),t.map(u=>s.jsx("option",{value:u.id,children:u.display_name||u.email},u.id)),e.owner_id&&!t.some(u=>u.id===e.owner_id)&&s.jsx("option",{value:e.owner_id,children:QKe(t,e.owner_id)})]})]}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary",children:["Stage:",s.jsxs("select",{value:e.stage??"",onChange:u=>n({stage:u.target.value||null}),className:Sa,children:[s.jsx("option",{value:"",children:"â"}),YKe.map(u=>s.jsx("option",{value:u,children:ZKe[u]},u))]})]}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary",children:["Next action:",s.jsx("input",{type:"datetime-local",value:l,onChange:u=>n({next_action_at:u.target.value?new Date(u.target.value).toISOString():null}),className:Sa})]})]})})}function aHe({profile:e}){var c,u,d,h,f,m;const t=!!(e!=null&&e.account),n=Array.isArray(e==null?void 0:e.sellers)?e.sellers:[],r=n.length>0,a=((c=e==null?void 0:e.gmv)==null?void 0:c.last_30d_zar)??0,i=((u=e==null?void 0:e.gmv)==null?void 0:u.sale_count_30d)??0,o=((d=e==null?void 0:e.chat)==null?void 0:d.chats_7d)??0,l=((h=e==null?void 0:e.chat)==null?void 0:h.last_chat_at)??null;return s.jsxs(V,{className:"p-4",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary mb-3",children:"App Profile"}),!t&&!r?s.jsx("p",{className:"text-sm text-text-tertiary",children:"Not yet linked to an account or seller. Once they sign up, plan and GMV signals appear here automatically."}):s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[t&&s.jsxs(s.Fragment,{children:[s.jsx(Cc,{label:"Plan",value:e.account.account_type}),s.jsx(Cc,{label:"Credits",value:`R${Number(e.account.credits_zar).toLocaleString()}`}),s.jsx(Cc,{label:"Subscription",value:e.account.subscription_status}),s.jsx(Cc,{label:"AM",value:((f=e.am)==null?void 0:f.display_name)??((m=e.am)==null?void 0:m.email)??"Unassigned"})]}),s.jsx(Cc,{label:"Sellers",value:n.length===0?"â":`${n.length}`}),s.jsx(Cc,{label:"GMV (30d)",value:a>0?`R${a.toLocaleString(void 0,{maximumFractionDigits:0})}`:"â"}),s.jsx(Cc,{label:"Sales (30d)",value:i>0?`${i}`:"â"}),s.jsx(Cc,{label:"Chats (7d)",value:o>0?`${o}${l?` · ${Sv(l)}`:""}`:"â"})]}),r&&s.jsxs("div",{className:"mt-4 pt-3 border-t border-outline-subtle",children:[s.jsx("p",{className:"text-xs text-text-secondary mb-2",children:"Connected sellers"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(x=>s.jsxs(st,{to:`/sellers/${encodeURIComponent(x.slug)}`,className:"inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-xs bg-surface-sunken hover:bg-surface-subtle",children:[s.jsx("span",{className:"font-medium",children:x.name}),s.jsxs("span",{className:"text-text-tertiary",children:["· last sync ",Sv(x.last_sync_at)||"â"]}
909),s.jsx(Qt,{className:"h-3 w-3 text-text-tertiary"})]},x.slug))})]})]})}function Cc({label:e,value:t}){return s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-tertiary",children:e}),s.jsx("div",{className:"text-sm font-semibold text-text-primary truncate",children:t})]})}function iHe({companyId:e,activities:t,contacts:n,onLogged:r}){const[a,i]=p.useState("call"),[o,l]=p.useState(""),[c,u]=p.useState(""),[d,h]=p.useState(""),[f,m]=p.useState(""),[x,g]=p.useState(""),[y,b]=p.useState(!1),[v,w]=p.useState(null),_=async k=>{k.preventDefault(),b(!0),w(null);try{await Rr.createActivity(e,{type:a,outcome:o||null,body:c.trim()||null,contact_id:d||null,scheduled_at:a==="demo"&&f?new Date(f).toISOString():null,next_action_at:x?new Date(x).toISOString():null}),u(""),l(""),g(""),m(""),r()}catch(j){w(j instanceof Error?j.message:String(j))}finally{b(!1)}};return s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("form",{onSubmit:_,className:"p-4 border-b border-outline-subtle space-y-2",children:[s.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:nG.map(k=>{const j=k.icon;return s.jsxs("button",{type:"button",onClick:()=>i(k.value),className:B("inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-xs font-medium",a===k.value?"bg-surface-inverse text-text-inverse":"text-text-secondary hover:bg-surface-sunken"),children:[s.jsx(j,{className:"h-3.5 w-3.5"})," ",k.label]},k.value)})}),s.jsx("textarea",{value:c,onChange:k=>u(k.target.value),rows:2,placeholder:a==="note"?"Noteâ¦":`What happened on this ${a}?`,className:"w-full rounded-md border border-outline-subtle px-2.5 py-1.5 text-sm outline-none focus:border-outline-brand focus-visible:shadow-focus"}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-2",children:[a!=="note"&&s.jsxs("select",{value:o,onChange:k=>l(k.target.value),className:Sa,children:[s.jsx("option",{value:"",children:"Outcomeâ¦"}),ZS.map(k=>s.jsx("option",{value:k.value,children:k.label},k.value))]}),n.length>0&&s.jsxs("select",{value:d,onChange:k=>h(k.target.value),className:Sa,children:[s.jsx("option",{value:"",children:"Contactâ¦"}),n.map(k=>s.jsx("option",{value:k.id,children:k.name},k.id))]}),a==="demo"&&s.jsxs("label",{className:"flex items-center gap-1 text-xs text-text-secondary",children:["Scheduled:",s.jsx("input",{type:"datetime-local",value:f,onChange:k=>m(k.target.value),className:B("flex-1",Sa)})]}),s.jsxs("label",{className:"flex items-center gap-1 text-xs text-text-secondary",children:["Follow up:",s.jsx("input",{type:"datetime-local",value:x,onChange:k=>g(k.target.value),className:B("flex-1",Sa)})]})]}),v&&s.jsx("div",{className:"text-xs text-text-error",children:v}),s.jsx("div",{className:"flex justify-end",children:s.jsxs(W,{type:"submit",intent:"brand",size:"sm",disabled:y,children:[s.jsx(In,{className:"h-3.5 w-3.5"}),y?"Loggingâ¦":"Log activity"]})})]}),s.jsx("div",{className:"divide-y divide-outline-subtle max-h-[60vh] overflow-y-auto",children:t.length===0?s.jsx("div",{className:"px-4 py-8 text-center text-sm text-text-tertiary",children:"No activities yet. Log a call, email, or note above."}):t.map(k=>s.jsx(oHe,{activity:k,contacts:n,onChanged:r},k.id))})]})}function oHe({activity:e,contacts:t,onChanged:n}){var w;const r=nG.find(_=>_.value===e.type),a=(r==null?void 0:r.icon)??pF,i=e.contact_id?t.find(_=>_.id===e.contact_id):null,o=e.type==="demo"&&e.scheduled_at&&new Date(e.scheduled_at)>new Date&&!e.outcome,[l,c]=p.useState(!1),[u,d]=p.useState(e.body??""),[h,f]=p.useState(e.outcome??""),[m,x]=p.useState(!1),[g,y]=p.useState(null);p.useEffect(()=>{d(e.body??""),f(e.outcome??"")},[e.body,e.outcome]);const b=async()=>{x(!0),y(null);try{await Rr.updateActivity(e.id,{body:u.trim()||null,outcome:h||null}),c(!1),n()}catch(_){y(_ instanceof Error?_.message:String(_))}finally{x(!1)}},v=async()=>{if(confirm("Delete this activity?")){x(!0),y(null);try{await Rr.deleteActivity(e.id),n()}catch(_){y(_ instanceof Error?_.message:String(_)),x(!1)}}};return s.jsxs("div",{className:"px-4 py-3 flex items-start gap-3 group",children:[s.jsx("div",{className:"mt-0.5 p-1.5 rounded-md bg-surface-sunken text-text-secondary",children:s.jsx(a,{className:"h-3.5 w-3.5"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-secondary flex-wrap",children:[s.jsx("span",{className:"font-medium text-text-primary capitalize",children:e.type}),!l&&e.outcome&&s.jsx("span",{className:"px-1.5 py-0.5 rounded bg-surface-sunken",children:((w=ZS.find(_=>_.value===e.outcome))==null?void 0:w.label)??e.outcome}),i&&s.jsxs("span",{children:["· ",i.name]}),s.jsx("span",{className:"ml-auto",children:Sv(e.scheduled_at||e.logged_at)}),s.jsx("button",{type:"button",onClick:()=>c(_=>!_),className:"text-text-tertiary hover:text-text-primary opacity-0 group-hover:opacity-100",title:l?"Cancel":"Edit",children:l?"Cancel":"Edit"}),s.jsx("button",{type:"button",onClick:v,disabled:m,className:"text-text-tertiary hover:text-text-error opacity-0 group-hover:opacity-100 disabled:opacity-50",title:"Delete",children:"Delete"})]}),l?s.jsxs("div",{className:"mt-2 space-y-2",children:[e.type!=="note"&&s.jsxs("select",{value:h,onChange:_=>f(_.target.value),className:Sa,children:[s.jsx("option",{value:"",children:"Outcomeâ¦"}),ZS.map(_=>s.jsx("option",{value:_.value,children:_.label},_.value))]}),s.jsx("textarea",{value:u,onChange:_=>d(_.target.value),rows:3,className:"w-full rounded-md border border-outline-subtle px-2.5 py-1.5 text-sm outline-none focus:border-outline-brand focus-visible:shadow-focus"}),g&&s.jsx("div",{className:"text-xs text-text-error",children:g}),s.jsx("div",{className:"flex justify-end",children:s.jsx(W,{type:"button",intent:"brand",size:"sm",disabled:m,onClick:b,children:m?"Savingâ¦":"Save"})})]}):s.jsxs(s.Fragment,{children:[e.body&&s.jsx("p",{className:"mt-1 text-sm text-text-primary whitespace-pre-wrap",children:e.body}),e.scheduled_at&&s.jsxs("p",{className:"mt-1 text-xs text-text-secondary",children:[o?"Scheduled for":"Was scheduled for"," ",JKe(e.scheduled_at)]})]})]})]})}
909const oj={name:"",email:"",phone:"",whatsapp:"",role:""};function lHe(e){return{name:e.name,email:e.email??"",phone:e.phone??"",whatsapp:e.whatsapp_number??"",role:e.role??""}}function cHe({companyId:e,contacts:t,onChanged:n}){const[r,a]=p.useState(!1),[i,o]=p.useState(null),[l,c]=p.useState(oj),[u,d]=p.useState(!1),[h,f]=p.useState(null),m=()=>{c(oj),f(null),a(!1),o(null)},x=_=>{a(!1),o(_.id),c(lHe(_)),f(null)},g=()=>({name:l.name.trim(),email:l.email.trim()||null,phone:l.phone.trim()||null,whatsapp_number:l.whatsapp.trim()||null,role:l.role.trim()||null}),y=async _=>{if(_.preventDefault(),!!l.name.trim()){d(!0),f(null);try{await Rr.createContact(e,{...g(),is_primary:t.length===0}),m(),n()}catch(k){f(k instanceof Error?k.message:String(k))}finally{d(!1)}}},b=async _=>{if(_.preventDefault(),!(!i||!l.name.trim())){d(!0),f(null);try{await Rr.updateContact(i,g()),m(),n()}catch(k){f(k instanceof Error?k.message:String(k))}finally{d(!1)}}},v=async _=>{d(!0),f(null);try{await Rr.updateContact(_,{is_primary:!0}),n()}catch(k){f(k instanceof Error?k.message:String(k))}finally{d(!1)}},w=async _=>{if(confirm(`Remove ${_.name} from this company?`)){d(!0),f(null);try{await Rr.deleteContact(_.id),i===_.id&&m(),n()}catch(k){f(k instanceof Error?k.message:String(k))}finally{d(!1)}}};return s.jsxs(V,{className:"p-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Contacts"}),s.jsx("button",{type:"button",onClick:()=>{o(null),c(oj),f(null),a(_=>!_)},className:"text-xs text-text-brand hover:underline",children:r?"Cancel":"+ Add"})]}),r&&s.jsx(sL,{draft:l,onChange:c,onSubmit:y,onCancel:m,busy:u,err:h,submitLabel:u?"Addingâ¦":"Add"}),t.length===0&&!r?s.jsx("p",{className:"text-xs text-text-tertiary",children:"No contacts yet."}):s.jsx("div",{className:"space-y-3",children:t.map(_=>i===_.id?s.jsx(sL,{draft:l,onChange:c,onSubmit:b,onCancel:m,busy:u,err:h,submitLabel:u?"Savingâ¦":"Save"},_.id):s.jsxs("div",{className:"text-xs group",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"font-medium text-text-primary",children:_.name}),_.is_primary?s.jsx(_n,{tone:"success",children:"PRIMARY"}):s.jsx("button",{type:"button",onClick:()=>v(_.id),disabled:u,className:"text-body-xs text-text-tertiary hover:text-text-brand opacity-0 group-hover:opacity-100",children:"Set primary"}),_.role&&s.jsxs("span",{className:"text-text-tertiary",children:["· ",_.role]}),s.jsxs("span",{className:"ml-auto flex items-center gap-2 opacity-0 group-hover:opacity-100",children:[s.jsx("button",{type:"button",onClick:()=>x(_),className:"text-text-tertiary hover:text-text-primary",children:"Edit"}),s.jsx("button",{type:"button",onClick:()=>w(_),disabled:u,className:"text-text-tertiary hover:text-text-error",children:"Delete"})]})]}),_.email&&s.jsx("div",{children:s.jsx("a",{href:`mailto:${_.email}`,className:"text-text-brand hover:underline",children:_.email})}),s.jsxs("div",{className:"text-text-secondary flex flex-wrap gap-x-2",children:[_.phone&&s.jsx("a",{href:`tel:${_.phone}`,className:"hover:text-text-brand hover:underline",children:_.phone}),_.whatsapp_number&&s.jsxs("a",{href:eHe(_.whatsapp_number),target:"_blank",rel:"noreferrer",className:"hover:text-text-brand hover:underline",children:["WA ",_.whatsapp_number]})]})]},_.id))})]})}function sL({draft:e,onChange:t,onSubmit:n,onCancel:r,busy:a,err:i,submitLabel:o}){const l=(c,u)=>t({...e,[c]:u});return s.jsxs("form",{onSubmit:n,className:"space-y-2 mb-3 p-2 rounded-md bg-surface-sunken",children:[s.jsx("input",{placeholder:"Name",value:e.name,onChange:c=>l("name",c.target.value),className:B("w-full",Sa),required:!0}),s.jsx("input",{placeholder:"Email",type:"email",value:e.email,onChange:c=>l("email",c.target.value),className:B("w-full",Sa)}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsx("input",{placeholder:"Phone",value:e.phone,onChange:c=>l("phone",c.target.value),className:Sa}),s.jsx("input",{placeholder:"WhatsApp",value:e.whatsapp,onChange:c=>l("whatsapp",c.target.value),className:Sa})]}),s.jsx("input",{placeholder:"Role",value:e.role,onChange:c=>l("role",c.target.value),className:B("w-full",Sa)}),i&&s.jsx("div",{className:"text-xs text-text-error",children:i}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",onClick:r,children:"Cancel"}),s.jsx(W,{type:"submit",intent:"brand",size:"sm",disabled:a||!e.name.trim(),children:o})]})]})}function uHe({company:e,onPatch:t}){var n;return s.jsxs(V,{className:"p-4",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary mb-3",children:"Details"}),s.jsxs("div",{className:"space-y-2",children:[s.jsx(dHe,{value:e.notes,onPatch:t}),s.jsx(ba,{label:"Source",value:e.source,field:"source",onPatch:t,type:"select",options:["referral","cold_outreach","inbou
909nd","partner","other"]}),s.jsx(ba,{label:"Legal name",value:e.legal_name,field:"legal_name",onPatch:t}),s.jsx(ba,{label:"Est. revenue",value:((n=e.estimated_revenue)==null?void 0:n.toString())??null,field:"estimated_revenue",onPatch:t,type:"number"}),s.jsx(ba,{label:"Website",value:e.website,field:"website",onPatch:t,type:"url"}),s.jsx(ba,{label:"Takealot URL",value:e.takealot_seller_url,field:"takealot_seller_url",onPatch:t,type:"url"}),s.jsx(ba,{label:"Shopify URL",value:e.shopify_store_url,field:"shopify_store_url",onPatch:t,type:"url"}),s.jsx(ba,{label:"Amazon URL",value:e.amazon_store_url,field:"amazon_store_url",onPatch:t,type:"url"}),s.jsx(ba,{label:"LinkedIn",value:e.linkedin_url,field:"linkedin_url",onPatch:t,type:"url"}),s.jsx(ba,{label:"Facebook",value:e.facebook_url,field:"facebook_url",onPatch:t,type:"url"}),s.jsx(ba,{label:"Instagram",value:e.instagram_url,field:"instagram_url",onPatch:t,type:"url"}),s.jsx(ba,{label:"VAT #",value:e.vat_number,field:"vat_number",onPatch:t}),s.jsx(ba,{label:"Tax #",value:e.tax_number,field:"tax_number",onPatch:t}),s.jsx(ba,{label:"Billing address",value:e.billing_address,field:"billing_address",onPatch:t}),s.jsx(ba,{label:"Region",value:e.primary_region,field:"primary_region",onPatch:t}),s.jsx(ba,{label:"Brands",value:e.brands_product_lines,field:"brands_product_lines",onPatch:t}),s.jsxs("div",{className:"pt-2 border-t border-outline-subtle text-xs text-text-tertiary",children:["Created ",XKe(e.created_at)," · updated ",Sv(e.updated_at)]})]})]})}function dHe({value:e,onPatch:t}){const[n,r]=p.useState(e??"");p.useEffect(()=>{r(e??"")},[e]);const a=()=>{const i=n.trim()===""?null:n;i!==(e??null)&&t({notes:i})};return s.jsxs("div",{className:"text-xs",children:[s.jsx("div",{className:"text-text-tertiary mb-1",children:"Notes"}),s.jsx("textarea",{value:n,onChange:i=>r(i.target.value),onBlur:a,rows:3,placeholder:"Working notes on this companyâ¦",className:"w-full rounded-md border border-outline-subtle px-2 py-1.5 text-xs outline-none focus:border-outline-brand focus-visible:shadow-focus"})]})}function ba({label:e,value:t,field:n,onPatch:r,type:a="text",options:i}){const[o,l]=p.useState(!1),[c,u]=p.useState(t??"");p.useEffect(()=>{u(t??"")},[t]);const d=()=>{l(!1);const h=c.trim(),f=h===""?null:h;f!==(t??null)&&r(a==="number"?{[n]:f===null?null:Number(f)}:{[n]:f})};return s.jsxs("div",{className:"text-xs",children:[s.jsx("div",{className:"text-text-tertiary",children:e}),o?a==="select"?s.jsxs("select",{autoFocus:!0,value:c,onChange:h=>u(h.target.value),onBlur:d,className:B("w-full",Sa),children:[s.jsx("option",{value:"",children:"â"}),i==null?void 0:i.map(h=>s.jsx("option",{value:h,children:h.replace(/_/g," ")},h))]}
909):s.jsx("input",{autoFocus:!0,type:a==="number"?"number":"text",value:c,onChange:h=>u(h.target.value),onBlur:d,onKeyDown:h=>{h.key==="Enter"&&d(),h.key==="Escape"&&(u(t??""),l(!1))},className:B("w-full",Sa)}):a==="url"&&t?s.jsxs("div",{className:"flex items-center gap-1 min-h-[1.25rem]",children:[s.jsxs("a",{href:tHe(t),target:"_blank",rel:"noreferrer",className:"text-text-brand hover:underline inline-flex items-center gap-1 truncate",children:[t,s.jsx(Qt,{className:"h-3 w-3 shrink-0"})]}),s.jsx("button",{type:"button",onClick:()=>l(!0),className:"text-text-tertiary hover:text-text-primary p-0.5",title:`Edit ${e}`,children:s.jsx(Qi,{className:"h-3 w-3"})})]}):s.jsx("button",{type:"button",onClick:()=>l(!0),className:"w-full text-left text-text-primary hover:bg-surface-sunken rounded px-1.5 py-0.5 -mx-1.5 min-h-[1.25rem]",children:t?a==="number"?`R${Number(t).toLocaleString()}`:t:s.jsx("span",{className:"text-text-tertiary",children:"â"})})]})}const Nl=e=>`R${Number(e||0).toLocaleString("en-ZA",{maximumFractionDigits:2})}`;function cy(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString("en-ZA",{day:"2-digit",month:"short"})}const aL={below_minimum:"That's below the minimum withdrawal amount.",no_bank_account:"Add your bank details in Settings â Payouts first.",holdback_not_met:"Cash withdrawals unlock once your account is a little older.",insufficient_withdrawable:"That's more than your available-to-withdraw balance.",insufficient_earnings:"That's more than your balance.",bad_amount:"Enter a valid amount."},lj={active:"bg-surface-successSubtle text-text-success",pending:"bg-surface-warningSubtle text-text-warning",inactive:"bg-surface-sunken text-text-secondary"},hHe={paid:"bg-surface-successSubtle text-text-success",pending:"bg-surface-warningSubtle text-text-warning",approved:"bg-surface-warningSubtle text-text-warning",pending_transfer:"bg-surface-warningSubtle text-text-warning",failed:"bg-surface-errorSubtle text-text-error",rejected:"bg-surface-errorSubtle text-text-error",cancelled:"bg-surface-sunken text-text-secondary"};function iL({label:e,tone:t}){return s.jsx("span",{className:B("inline-flex rounded px-1.5 py-0.5 text-body-xs font-medium capitalize",t),children:e.replace(/_/g," ")})}function fHe({overview:e,onChanged:t}){const{wallet:n,referrals:r,earnings:a}=e,[i,o]=p.useState(null),[l,c]=p.useState([]),[u,d]=p.useState(0),h=p.useCallback(()=>d(C=>C+1),[]),[f,m]=p.useState(""),[x,g]=p.useState(null),[y,b]=p.useState(null),[v,w]=p.useState(null);p.useEffect(()=>{let C=!0;return Promise.all([Us.bankAccount(),Us.myWithdrawals()]).then(([T,S])=>{C&&(o(T.bankAccount),c(Array.isArray(S==null?void 0:S.withdrawals)?S.withdrawals:[]))}).catch(()=>{}),()=>{C=!1}},[u]);async function _(){g("sweep"),b(null),w(null);try{const C=await Us.sweep(n.balanceZar);w(`Moved ${Nl(C.sweptZar)} to your chat credit.`),t()}catch(C){const T=C instanceof Error?C.message:String(C);b(aL[T]??T)}finally{g(null)}}async function k(){const C=Number(f);g("withdraw"),b(null),w(null);try{await Us.withdraw(C),w(`Withdrawal of ${Nl(C)} requested â we'll review and pay it to your bank.`),m(""),t(),h()}catch(T){const S=T instanceof Error?T.message:String(T);b(aL[S]??S)}finally{g(null)}}async function j(C){b(null);try{await Us.cancelWithdrawal(C),t(),h()}catch(T){b(T instanceof Error?T.message:String(T))}}const N=!!(i!=null&&i.payout_ready)&&n.matured&&n.withdrawableZar>0,E=Number(f),A=Number.isFinite(E)&&E>0&&E<=n.withdrawableZar;return s.jsxs(s.Fragment,{children:[s.jsxs(V,{padding:"lg",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(s0,{className:"h-4 w-4 text-text-secondary"}),s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Affiliate earnings"})]}),s.jsx("div",{className:"mt-3",children:s.jsxs(dr,{cols:3,children:[s.jsx(Ye,{label:"Available",value:Nl(n.balanceZar),tone:"success"}),s.jsx(Ye,{label:"Ready to withdraw",value:Nl(n.withdrawableZar)}),s.jsx(Ye,{label:"Earned all-time",value:Nl(n.lifetimeEarnedZar)})]})}),v&&s.jsx("p",{className:"mt-3 text-body-xs text-text-success",children:v}),y&&s.jsx("p",{className:"mt-3 text-body-xs text-text-error",children:y}),s.jsx("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:s.jsxs(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",disabled:n.balanceZar<=0||x!==null,onClick:_,children:[x==="sweep"?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):s.jsx(ite,{className:"h-3.5 w-3.5"}),"Move ",Nl(n.balanceZar)," to credit"]})}),s.jsxs("div",{className:"mt-4 rounded-md border border-outline-subtle bg-surface-subtle p-3",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-text-primary",children:[s.jsx(P2,{className:"h-4 w-4 text-text-secondary"})," Withdraw to your bank"]}),i!=null&&i.payout_ready?n.matured?s.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"text-sm text-text-secondary",children:"R"}),s.jsx("input",{type:"text",inputMode:"decimal",value:f,onChange:C=>m(C.target.value.replace(/[^\d.]/g,"")),placeholder:"Amount",className:"w-28 rounded border border-outline-subtle bg-surface px-2 py-1.5 text-sm"})]}),s.jsxs(W,{type:"button",intent:"brand",size:"sm",disabled:!N||!A||x!==null,onClick:k,children:[x==="withdraw"?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):null,"Withdraw"]}),s.jsxs("span",{className:"text-body-xs text-text-tertiary",children:["up to ",Nl(n.withdrawableZar)," to ",i.bank_name," ···· ",i.account_number_last4]})]}):s.jsx("p",{className:"mt-1 text-body-xs text-text-secondary",children:"Cash withdrawals unlock once your account is a little older. You can still move earnings to chat credit any time."}):s.jsxs("p",{className:"mt-1 text-body-xs text-text-secondary",children:["Add your bank details in"," ",s.jsx(st,{to:"/settings/workspace/payouts",className:"text-text-brand hover:underline",children:"Settings â Payouts"})," ","to withdraw as cash."]})]}),l.length>0&&s.jsx("ul",{className:"mt-4 divide-y divide-outline-faint",children:l.map(C=>s.jsxs("li",{className:"flex items-center justify-between gap-3 py-2 first:pt-0 last:pb-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm text-text-primary tabular-nums",children:Nl(C.amount_zar)}),C.failure_reason&&C.status==="failed"&&s.jsx("div",{className:"text-body-xs text-text-error",children:C.failure_reason})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[s.jsx(iL,{label:C.status,tone:hHe[C.status]}),s.jsx("span",{className:"text-body-xs text-text-tertiary",children:cy(C.created_at)}),C.status==="pending"&&s.jsx("button",{type:"button",onClick:()=>j(C.id),className:"text-body-xs text-text-tertiary hover:text-text-error hover:underline",children:"cancel"})]})]},C.id))})]}),r.length>0&&s.jsxs(V,{padding:"lg",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Your referrals"}),s.jsx("ul",{className:"mt-3 divide-y divide-outline-faint",children:r.map(C=>s.jsxs("li",{className:"flex items-center justify-between gap-3 py-2 first:pt-0 last:pb-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"truncate text-sm text-text-primary",children:C.label}),s.jsxs("div",{className:"text-body-xs text-text-tertiary",children:["joined ",cy(C.created_at),C.activated_at?` · paying since ${cy(C.activated_at)}`:""]})]}),s.jsx(iL,{label:C.active_paying?"paying":C.status,tone:C.active_paying?lj.active:lj[C.status]??lj.inactive})]},C.id))})]}),a.length>0&&s.jsxs(V,{padding:"lg",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Earnings history"}),s.jsx("ul",{className:"mt-3 divide-y divide-outline-faint",children:a.map(C=>s.jsxs("li",{className:"flex items-center justify-between gap-3 py-2 first:pt-0 last:pb-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"truncate text-sm text-text-primary capitalize",children:C.reason.replace(/_/g," ")}),C.note&&s.jsx("div",{className:"truncate text-body-xs text-text-tertiary",children:C.note})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[s.jsxs("span",{className:B("text-body-xs tabular-nums",C.delta_zar>=0?"text-text-success":"text-text-secondary"),children:[C.delta_zar>=0?"+":"â",Nl(Math.abs(C.delta_zar))]}),s.jsx("span",{className:"text-body-xs text-text-tertiary",children:cy(C.created_at)})]})]},C.id))})]})]})}const mHe=["pending","approved","pending_transfer","paid","failed","all"],pHe=e=>
909`R${Number(e||0).toLocaleString("en-ZA",{maximumFractionDigits:2})}`;function xHe(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString("en-ZA",{day:"2-digit",month:"short"})}const gHe={paid:"bg-surface-successSubtle text-text-success",pending:"bg-surface-warningSubtle text-text-warning",approved:"bg-surface-warningSubtle text-text-warning",pending_transfer:"bg-surface-warningSubtle text-text-warning",failed:"bg-surface-errorSubtle text-text-error",rejected:"bg-surface-errorSubtle text-text-error",cancelled:"bg-surface-sunken text-text-secondary"};function yHe(){const[e,t]=p.useState([]),[n,r]=p.useState(!1),[a,i]=p.useState(null),[o,l]=p.useState("pending"),[c,u]=p.useState(0),[d,h]=p.useState(null),[f,m]=p.useState(null),[x,g]=p.useState("");p.useEffect(()=>{let b=!0;return r(!0),i(null),Us.withdrawalQueue(o).then(v=>b&&t(Array.isArray(v==null?void 0:v.withdrawals)?v.withdrawals:[])).catch(v=>b&&i(v.message)).finally(()=>b&&r(!1)),()=>{b=!1}},[o,c]);async function y(b,v,w){h(b),i(null);try{const _=await Us.reviewWithdrawal(b,v,w);_!=null&&_.error&&i(`Transfer not sent: ${_.error}`),m(null),g(""),u(k=>k+1)}catch(_){i(_ instanceof Error?_.message:String(_))}finally{h(null)}}return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-wrap items-center gap-1",children:mHe.map(b=>s.jsx("button",{type:"button",onClick:()=>l(b),className:B("rounded-md px-2.5 py-1 text-sm capitalize",o===b?"bg-surface-sunken font-medium text-text-primary":"text-text-secondary hover:bg-surface-subtle"),children:b.replace(/_/g," ")},b))}),n&&s.jsx("p",{className:"text-sm text-text-secondary",children:"Loading queueâ¦"}),a&&s.jsx("p",{className:"text-sm text-text-error",children:a}),!n&&!a&&e.length===0&&s.jsx(V,{padding:"lg",children:s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-secondary",children:[s.jsx(qv,{className:"h-4 w-4"})," Nothing ",o==="all"?"":o.replace(/_/g," ")," to show."]})}),e.length>0&&s.jsx(V,{padding:"none",className:"overflow-hidden",children:s.jsx("ul",{className:"divide-y divide-outline-subtle",children:e.map(b=>s.jsxs("li",{className:"p-4",children:[s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"text-sm font-medium text-text-primary",children:[b.business_name??b.account_id," · ",pHe(b.amount_zar)]}),s.jsxs("div",{className:"text-body-xs text-text-tertiary",children:[b.account_holder??"â"," · ",b.bank_name??"â"," ···· ",b.account_number_last4??"----"," ·"," ",xHe(b.created_at)]}),b.failure_reason&&s.jsx("p",{className:"mt-1 text-body-xs text-text-error",children:b.failure_reason}),b.review_note&&s.jsxs("p",{className:"mt-1 text-body-xs text-text-tertiary",children:["Note: ",b.review_note]})]}),s.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-2",children:[s.jsx("span",{className:B("inline-flex rounded px-1.5 py-0.5 text-body-xs font-medium capitalize",gHe[b.status]),children:b.status.replace(/_/g," ")}),(b.status==="pending"||b.status==="approved")&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(W,{type:"button",intent:"brand",size:"sm",disabled:d===b.id,onClick:()=>y(b.id,"approve"),children:b.status==="approved"?"Retry transfer":"Approve & pay"}),s.jsx(W,{type:"button",intent:"destructive",variant:"outline",size:"sm",disabled:d===b.id,onClick:()=>{m(f===b.id?null:b.id),g("")},children:"Reject"})]})]})]}),f===b.id&&s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("input",{type:"text",value:x,onChange:v=>g(v.target.value),placeholder:"Reason (optional)",className:"flex-1 rounded border border-outline-subtle bg-surface px-2 py-1.5 text-sm"}),s.jsx(W,{type:"button",intent:"destructive",size:"sm",disabled:d===b.id,onClick:()=>y(b.id,"reject",x),children:"Confirm reject"})]})]},b.id))})})]})}const bHe=["earn"],vHe=["earn","review","withdrawals"],wHe={already_pending:"You already have a pending submission for this.",already_earned:"You've already earned this one.",too_soon:"You've earned this one recently â try again later.",proof_url_required:"Please paste a link as proof.",no_account:"Submitting is available on seller accounts."};function oL(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleDateString("en-ZA",{day:"2-digit",month:"short"})}const _He={google_review:"Google review",takealot_ssn_review:"Takealot SSN review",social_post:"Social post"},kHe=e=>_He[e]??e.replace(/_/g," ");function lL({status:e}){const t=e==="approved"?"bg-surface-successSubtle text-text-success":e==="rejected"?"bg-surface-errorSubtle text-text-error":"bg-surface-warningSubtle text-text-warning";return s.jsx("span",{className:B("inline-flex rounded px-1.5 py-0.5 text-body-xs font-medium capitalize",t),children:e})}function jHe(){const e=Lt(),t=e.kind==="ready"&&e.me.role==="super_admin",[n,r]=it("tab","earn"),i=(t?vHe:bHe).includes(n)?n:"earn",[o,l]=p.useState(null),[c,u]=p.useState(!0),[d,h]=p.useState(null),[f,m]=p.useState(!1),[x,g]=p.useState(0),y=p.useCallback(()=>g(X=>
909X+1),[]),[b,v]=p.useState(null),[w,_]=p.useState(""),[k,j]=p.useState(null),[N,E]=p.useState(!1),[A,C]=p.useState(null),[T,S]=p.useState([]),[O,R]=p.useState(!1),[I,$]=p.useState(null),[P,F]=p.useState("pending"),[Z,D]=p.useState(0),[H,Y]=p.useState(null),[M,z]=p.useState(""),[G,te]=p.useState(null);p.useEffect(()=>{let X=!0;return u(!0),h(null),Us.overview().then(he=>X&&l(he)).catch(he=>X&&h(he.message)).finally(()=>X&&u(!1)),()=>{X=!1}},[x]),p.useEffect(()=>{if(i!=="review")return;let X=!0;return R(!0),$(null),Us.reviewQueue(P).then(he=>X&&S(Array.isArray(he==null?void 0:he.submissions)?he.submissions:[])).catch(he=>X&&$(he.message)).finally(()=>X&&R(!1)),()=>{X=!1}},[i,P,Z]);const re=!!(o!=null&&o.referralCode),L=o!=null&&o.referralCode?`https://gadjet.ai/?ref=${o.referralCode}`:"",q=new Set(((o==null?void 0:o.submissions)??[]).filter(X=>X.status==="approved").map(X=>X.activity_key));async function me(X){E(!0),C(null);try{let he=null;k&&(he=await Us.uploadProofScreenshot(k)),await Us.submit({activityKey:X,proofUrl:w.trim(),proofScreenshotPath:he}),v(null),_(""),j(null),y()}catch(he){const ae=he instanceof Error?he.message:String(he);C(wHe[ae]??ae)}finally{E(!1)}}async function ee(X,he,ae){te(X);try{await Us.review(X,he,ae),Y(null),z(""),D(je=>je+1),y()}catch(je){$(je instanceof Error?je.message:String(je))}finally{te(null)}}const ne=[{key:"earn",label:"Earn",active:i==="earn",onClick:()=>r("earn")}];return t&&(ne.push({key:"review",label:"Review queue",active:i==="review",onClick:()=>r("review"),trailing:o&&o.pendingReviewCount>0?s.jsx("span",{className:"ml-1.5 inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-intent-info px-1 text-body-xs font-semibold text-text-inverse",children:o.pendingReviewCount}):void 0}),ne.push({key:"withdrawals",label:"Withdrawals",active:i==="withdrawals",onClick:()=>r("withdrawals")})),s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Earn"}]}),s.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:[s.jsx(As,{items:ne}),s.jsxs("div",{className:"w-full px-4 md:px-6 py-6 space-y-6",children:[c&&s.jsx("p",{className:"text-sm text-text-secondary",children:"Loadingâ¦"}),d&&s.jsx(V,{padding:"md",variant:"sunken",children:s.jsxs("p",{className:"text-sm text-text-warning",children:["Couldn't load Earn (",d,")."]})}),i==="earn"&&o&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("div",{className:"mt-0.5 rounded-md bg-surface-sunken p-2 text-intent-brand",children:s.jsx(B2,{className:"h-5 w-5"})}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:"Earn with Gadjet"}),s.jsx("p",{className:"text-sm text-text-secondary",children:"Share Gadjet, refer sellers, and earn credits â and get your plan covered as your referrals grow."})]})]}),s.jsxs(dr,{cols:3,children:[s.jsx(Ye,{label:"Active paying",value:o.counts.activePaying,tone:"success"}),s.jsx(Ye,{label:"Pending",value:o.counts.pending}),s.jsx(Ye,{label:"Total referred",value:o.counts.total})]}),s.jsxs(V,{padding:"lg",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Your referral link"}),o.referralCode?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"mt-1 text-sm text-text-secondary",children:"Share this link. Sellers who sign up on it count toward your rewards."}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("code",{className:"flex-1 break-all rounded border border-outline-subtle bg-surface px-2 py-1.5 font-mono text-body-xs",children:L}),s.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(L),m(!0),setTimeout(()=>m(!1),2e3)},className:"flex items-center gap-1 rounded border border-outline-subtle px-2 py-1 text-xs text-text-secondary hover:bg-surface-sunken hover:text-text-body",children:[f?s.jsx(fn,{className:"h-3 w-3"}):s.jsx(bi,{className:"h-3 w-3"}),f?"Copied":"Copy"]})]}),s.jsxs("p",{className:"mt-2 text-body-xs text-text-tertiary",children:["Code: ",s.jsx("span",{className:"font-mono",children:o.referralCode})]})]}):s.jsx("p",{className:"mt-1 text-sm text-text-secondary",children:"Your referral link appears once you're on a seller account. No code is issued for admin/staff accounts â this is a preview of what sellers will see."})]}),re&&s.jsx(fHe,{overview:o,onChanged:y}),s.jsxs(V,{padding:"lg",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Xp,{className:"h-4 w-4 text-text-secondary"}),s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Referral rewards"})]}),s.jsx("ul",{className:"mt-3 space-y-3",children:o.ladder.map(X=>{const he=o.counts.activePaying>=X.threshold,ae=Math.max(0,X.threshold-o.counts.activePaying);return s.jsxs("li",{className:"flex items-start gap-3",children:[s.jsx("span",{className:B("inline-flex h-8 min-w-[2rem]
909shrink-0 items-center justify-center rounded-md px-2 text-sm font-semibold tabular-nums",he?"bg-surface-successSubtle text-text-success":"bg-surface-sunken text-text-primary"),children:X.threshold}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 text-sm font-medium text-text-primary",children:[X.reward,he?s.jsxs("span",{className:"inline-flex items-center gap-0.5 text-body-xs font-normal text-text-success",children:[s.jsx(fn,{className:"h-3 w-3"})," unlocked"]}):s.jsxs("span",{className:"text-body-xs font-normal text-text-tertiary",children:[ae," more to go"]})]}),s.jsx("div",{className:"text-sm text-text-secondary",children:X.detail})]})]},X.threshold)})})]}),s.jsxs(V,{padding:"lg",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Ways to earn"}),s.jsx("ul",{className:"mt-3 divide-y divide-outline-faint",children:o.activities.map(X=>s.jsxs("li",{className:"py-3 first:pt-0 last:pb-0",children:[s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:X.title}),s.jsx("div",{className:"text-sm text-text-secondary",children:X.detail})]}),s.jsxs("div",{className:"shrink-0 text-right",children:[s.jsxs("div",{className:"text-sm font-medium text-text-primary tabular-nums",children:["R",X.topup_zar," ",s.jsx("span",{className:"font-normal text-text-secondary",children:"credits"})]}),X.me_credits>0&&s.jsxs("div",{className:"text-body-xs text-text-secondary",children:["+ ",X.me_credits," Market Explorer searches"]}),s.jsx("div",{className:"text-body-xs text-text-tertiary",children:X.cadence==="once"?"one-off":`every ${X.period_days??7} days`})]})]}),re?X.cadence==="once"&&q.has(X.key)?s.jsxs("p",{className:"mt-2 inline-flex items-center gap-1 text-body-xs font-medium text-text-success",children:[s.jsx(fn,{className:"h-3.5 w-3.5"})," Earned"]}):b===X.key?s.jsxs("div",{className:"mt-3 space-y-2 rounded-md border border-outline-subtle bg-surface-subtle p-3",children:[X.requires_url&&s.jsx("input",{type:"url",value:w,onChange:he=>_(he.target.value),placeholder:"Link to your review / post",className:"w-full rounded border border-outline-subtle bg-surface px-2 py-1.5 text-sm"}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary",children:[s.jsx(ti,{className:"h-3.5 w-3.5"}),s.jsx("input",{type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",onChange:he=>{var ae;return j(((ae=he.target.files)==null?void 0:ae[0])??null)},className:"text-xs"}),s.jsx("span",{className:"text-text-tertiary",children:X.requires_screenshot?"(screenshot required)":"(screenshot optional)"})]}),A&&s.jsx("p",{className:"text-body-xs text-text-error",children:A}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(W,{type:"button",intent:"brand",size:"sm",disabled:N||X.requires_url&&!w.trim()||X.requires_screenshot&&!k,onClick:()=>me(X.key),children:[N?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):null,"Submit for review"]}),s.jsx(W,{type:"button",intent:"neutral",variant:"ghost",size:"sm",disabled:N,onClick:()=>{v(null),_(""),j(null),C(null)},children:"Cancel"})]})]}):s.jsx(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",className:"mt-2",onClick:()=>{v(X.key),_(""),j(null),C(null)},children:"Submit proof"}):s.jsx("p",{className:"mt-2 text-body-xs text-text-tertiary",children:"Seller accounts only"})]},X.key))})]}),o.submissions.length>0&&s.jsxs(V,{padding:"lg",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Your submissions"}),s.jsx("ul",{className:"mt-3 divide-y divide-outline-faint",children:o.submissions.map(X=>s.jsxs("li",{className:"flex items-center justify-between gap-4 py-2.5 first:pt-0 last:pb-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"truncate text-sm text-text-primary",children:kHe(X.activity_key)}),X.proof_url&&s.jsxs("a",{href:X.proof_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-body-xs text-text-brand hover:underline",children:["proof ",s.jsx(Qt,{className:"h-3 w-3"})]})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-3",children:[X.status==="approved"&&X.granted_zar!=null&&s.jsxs("span",{className:"text-body-xs tabular-nums text-text-success",title:"Chat credits + Market Explorer searches",children:["+R",X.granted_zar,X.granted_me_credits?` + ${X.granted_me_credits} searches`:""]}),s.jsx(lL,{status:X.status}),s.jsx("span",{className:"text-body-xs text-text-tertiary",children:oL(X.created_at)})]})]},X.id))})]})]}),i==="review"&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-center gap-1",children:["pending","approved","rejected","all"].map(X=>s.jsx("button",{type:"button",onClick:()=>F(X),className:B("rounded-md px-2.5 py-1 text-sm capitalize",P===X?"bg-surface-sunken font-medium text-text-primary":"text-text-secondary hover:bg-surface-subtle"),children:X},X))}),O&&s.jsx("p",{className:"text-sm text-text-secondary",children:"Loading queueâ¦"}),I&&s.jsx("p",{className:"text-sm text-text-error",children:I}),!O&&!I&&T.length===0&&s.jsx(V,{padding:"lg",children:s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-secondary",children:[s.jsx(qv,{className:"h-4 w-4"})," Nothing ",P==="all"?"":P," to show."]})}),T.length>0&&s.jsx(V,{padding:"none",className:"overflow-hidden",children:s.jsx("ul",{className:"divide-y divide-outline-subtle",children:T.map(X=>s.jsxs("li",{className:"p-4",children:[s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:X.business_name??X.account_id}),s.jsxs("div",{className:"text-body-xs text-text-tertiary",children:[X.activity_key," · ",X.submitter_email??"â"," · ",oL(X.created_at)]}),s.jsxs("div",{className:"mt-1.5 flex items-center gap-3",children:[X.proof_url&&s.jsxs("a",{href:X.proof_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-body-xs text-text-brand hover:underline",children:["proof link ",s.jsx(Qt,{className:"h-3 w-3"})]}),X.proof_screenshot_url&&s.jsx("a",{href:X.proof_screenshot_url,target:"_blank",rel:"noreferrer",children:s.jsx("img",{src:X.proof_screenshot_url,alt:"proof",className:"h-12 w-12 rounded border border-outline-subtle object-cover"})})]}),X.review_note&&s.jsxs("p",{className:"mt-1 text-body-xs text-text-tertiary",children:["Note: ",X.review_note]})]}),s.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[X.status==="approved"&&X.granted_zar!=null&&s.jsxs("span",{className:"text-body-xs tabular-nums text-text-success",children:["+R",X.granted_zar,X.granted_me_credits?` +${X.granted_me_credits} ME`:""]}),s.jsx(lL,{status:X.status})]}),X.status==="pending"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(W,{type:"button",intent:"brand",size:"sm",disabled:G===X.id,onClick:()=>ee(X.id,"approve"),children:"Approve"}),s.jsx(W,{type:"button",intent:"destructive",variant:"outline",size:"sm",disabled:G===X.id,onClick:()=>{Y(H===X.id?null:X.id),z("")},children:"Reject"})]})]})]}),H===X.id&&s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("input",{type:"text",value:M,onChange:he=>z(he.target.value),placeholder:"Reason (optional)",className:"flex-1 rounded border border-outline-subtle bg-surface px-2 py-1.5 text-sm"}),s.jsx(W,{type:"button",intent:"destructive",size:"sm",disabled:G===X.id,onClick:()=>ee(X.id,"reject",M),children:"Confirm reject"})]})]},X.id))})})]}),i==="withdrawals"&&t&&s.jsx(yHe,{})]})]})]})}const NHe=["pulse","board","calendar","backlog","performance"],ip=["backlog","scripting","recording","editing","ready","published","atomising","done"],qp={backlog:"Backlog",scripting:"Scripting",recording:"Recording",editing:"Editing",ready:"Ready",published:"Published",atomising:"Atomising",done:"Done"},SHe={backlog:"bg-outline-strong",scripting:"bg-brand-400",recording:"bg-intent-brand",editing:"bg-warning-500",ready:"bg-success-500",published:"bg-intent-success",atomising:"bg-brand-500",done:"bg-gray-500"},CHe=["proprietary-data","capability-menu","seller-education","social-proof","seasonal"],rG={"proprietary-data":"Proprietary data","capability-menu":"Capability","seller-education":"Seller education","social-proof":"Social proof",seasonal:"Seasonal"},Zn={youtube_long:"YouTube",youtube_short:"Short",blog:"Blog",linkedin:"LinkedIn",facebook:"Facebook",instagram:"Instagram",email:"Email"},cf=["youtube_long","youtube_short","blog","linkedin","facebook","instagram","email"],EHe=["linkedin","facebook","instagram"],sG=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],AHe={youtube_long:1,youtube_short:2,blog:1,email:1,linkedin:7,facebook:7,instagram:7},Cv={youtube_long:5e3,youtube_short:100,blog:0,linkedin:3e3,facebook:0,instagram:2200,email:0},cj=3,cr="rounded-md border border-outline bg-surface px-2 py-1 text-sm text-text-primary focus:outline-none focus:border-outline-brand focus-visible:shadow-focus";function Br(e){return e.toISOString().slice(0,10)}function Zo(e){const t=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),n=(t.getUTCDay()+6)%7;return t.setUTCDate(t.getUTCDate()-n),t}function Gl(e,t){const n=new Date(e);return n.setUTCDate(n.getUTCDate()+t),n}function Bs(e){if(!e)return"â";const t=new Date(`${e.slice(0,10)}T00:00:00Z`);return Number.isNaN(t.getTime())?"â":t.toLocaleDateString("en-ZA",{day:"2-digit",month:"short",timeZone:"UTC"})}function THe(e){const t=Zo(e),n=new Date(Date.UTC(t.getUTCFullYear(),0,4)),r=Zo(n);return 1+Math.round((t.getTime()-r.getTime())/(168*3600*1e3))}function Ro({label:e="Loadingâ¦"}){return s.jsxs("div",{className:"flex items-center gap-2 py-12 text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," ",e]})}function Zi({msg:e}){return s.jsx("div",{className:"rounded-lg border border-outline-error bg-surface-errorSubtle px-3 py-2 text-sm text-text-error",children:e})}function Xc({children:e}){return s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:e})}
909function Jc({children:e,className:t}){return s.jsx("div",{className:B("w-full space-y-4 px-4 py-4 md:space-y-6 md:px-6 md:py-6",t),children:e})}function W3({text:e,className:t}){const[n,r]=p.useState(!1);return s.jsx("button",{type:"button",className:B("text-text-tertiary hover:text-text-primary",t),title:"Copy",onClick:async a=>{a.stopPropagation();try{await navigator.clipboard.writeText(e),r(!0),setTimeout(()=>r(!1),1200)}catch{}},children:n?s.jsx(fn,{className:"h-3.5 w-3.5 text-text-success"}):s.jsx(bi,{className:"h-3.5 w-3.5"})})}function wo({children:e,caption:t,className:n}){return s.jsxs("div",{className:B("flex min-h-11 shrink-0 items-center justify-between gap-3 border-b border-outline-subtle px-4 py-2",n),children:[s.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:e}),t!=null&&s.jsx("span",{className:"text-xs text-text-secondary",children:t})]})}function Ow({cells:e}){return s.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5",children:e.map(t=>s.jsxs(V,{padding:"md",children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:t.label}),s.jsxs("div",{className:B("mt-1 text-2xl font-semibold leading-none tracking-tight tabular-nums md:text-[28px]",t.tone==="success"&&"text-text-success",t.tone==="warning"&&"text-text-warning",t.tone==="error"&&"text-text-error",(!t.tone||t.tone==="default")&&"text-text-primary"),children:[t.value,t.delta!=null&&s.jsx("span",{className:"ml-2 align-middle text-xs font-medium text-text-success",children:t.delta})]}),t.hint!=null&&s.jsx("div",{className:"mt-1.5 text-xs text-text-secondary",children:t.hint})]},t.label))})}const OHe={live:"bg-surface-successSubtle text-text-success",scheduled:"bg-surface-brandSubtle text-text-brand",draft:"bg-surface-sunken text-text-body",overdue:"bg-surface-errorSubtle text-text-error",warning:"bg-surface-warningSubtle text-text-warning",review:"bg-surface-brandSubtle text-text-brand",approved:"bg-surface-successSubtle text-text-success"};function dl({tone:e,children:t,className:n}){return s.jsx("span",{className:B("inline-flex items-center rounded-[10px] px-2 py-0.5 text-[11px] font-semibold",OHe[e],n),children:t})}function Ev(e,t){return e==="published"?"live":e==="scheduled"?"scheduled":t&&t<new Date().toISOString().slice(0,10)?"overdue":"draft"}function Iw({value:e,provenance:t,action:n}){return s.jsx("div",{className:"rounded-lg border border-outline-brand bg-surface-brandSubtle px-3 py-2.5",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-brand",children:"Data hook"}),s.jsx("div",{className:"mt-0.5 text-sm font-medium text-text-primary",children:e}),t!=null&&s.jsx("div",{className:"mt-0.5 font-mono text-[11px] text-text-secondary",children:t})]}),n]})})}function IHe({onOpenBacklog:e}){var T;const t=Rt(),[n,r]=p.useState(null),[a,i]=p.useState(null),[o,l]=p.useState(null),[c,u]=p.useState(0),[d,h]=p.useState(null),f=p.useMemo(()=>Zo(new Date),[]),m=p.useMemo(()=>Gl(f,6),[f]),x=Br(new Date);p.useEffect(()=>{let S=!0;return Promise.all([At.pulse(),At.listAssets(Br(f),Br(m))]).then(([O,R])=>{S&&(r(O.pulse),i(R.assets))}).catch(O=>S&&l(O.message)),()=>{S=!1}},[c,f,m]);const g=async S=>{i(O=>(O==null?void 0:O.map(R=>R.id===S.id?{...R,status:"published"}:R))??O);try{await At.updateAsset(S.id,{status:"published"})}catch{u(O=>O+1)}},y=async(S,O)=>{if(O.trim()){h(null);try{await At.updateAsset(S.id,{url:O.trim(),status:S.status==="draft"?"scheduled":S.status}),u(R=>R+1)}catch{u(R=>R+1)}}};if(o)return s.jsx(Zi,{msg:o});if(!n||!a)return s.jsx(Ro,{});const b=n.academy,v=(b==null?void 0:b.unfilmed)??[],w=((b==null?void 0:b.seller_skills)??0)-v.length,k=(n.this_week_pillars??[])[0]??null,j=Array.from({length:7},(S,O)=>Gl(f,O)),N=THe(f),E=a.filter(S=>S.scheduled_date===x),A=a.filter(S=>S.status!=="published"&&S.scheduled_date&&S.scheduled_date<x),C=A.length+E.filter(S=>S.status!=="published").length+(n.runway_red?1:0);return s.jsxs("div",{className:"space-y-4 md:space-y-6",children:[s.jsx(Ow,{cells:[{label:"Runway",value:`${n.runway}`,hint:n.runway_red?"Promote from Backlog to stay 2â3 ahead":"Ideas plus pillars in flight",tone:n.runway_red?"warning":"success"},{label:"Published 7d",value:n.published_last_7d,hint:"Across 7 channels"},{label:"Ideas in backlog",value:n.idea_count??n.backlog_count,hint:"Ranked intake waiting to promote"},{label:"Overdue",value:n.overdue.length,hint:n.overdue.length?"Waiting on a URL or a status move":"Nothing overdue",tone:n.overdue.length?"error":"default"},{label:"Academy filmed",value:`${w}/${(b==null?void 0:b.seller_skills)??0}`,hint:`${v.length} seller skills unfilmed`,delta:b!=null&&b.filmed_last_7d?`+${b.filmed_last_7d}`:void 0}]}),s.jsxs("div",{className:"flex flex-col gap-4 xl:flex-row xl:items-start",children:[s.jsxs("div",{className:"min-w-0 flex-1 space-y-4",children:[s.jsxs(V,{children:[s.jsx(wo,{caption:`Week ${N}
909 · ${Bs(Br(f))}â${Bs(Br(m))}`,children:"This weekâs pillar"}),s.jsx("div",{className:"p-4 md:p-5",children:k?s.jsxs("div",{children:[s.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{className:"text-lg font-semibold leading-tight tracking-tight text-text-primary md:text-[22px]",children:k.title}),s.jsxs("p",{className:"mt-1 text-[13px] text-text-secondary",children:["Publishes ",Bs(k.target_publish_week),typeof k.asset_count=="number"&&` · ${k.asset_count} assets scaffolded`,` · ${qp[k.status]}`]})]}),s.jsx(W,{intent:"brand",variant:"outline",size:"sm",className:"shrink-0",onClick:()=>t(`/content/pillars/${k.id}`),children:"Open workbench"})]}),s.jsx(PHe,{current:k.status}),((T=k.data_hook)==null?void 0:T.captured_value)&&s.jsx("div",{className:"mt-4",children:s.jsx(Iw,{value:k.data_hook.captured_value,provenance:s.jsxs(s.Fragment,{children:[k.data_hook.skill,k.data_hook.captured_at?` · captured ${Bs(k.data_hook.captured_at.slice(0,10))}`:null]})})})]}):s.jsxs("div",{children:[s.jsx("p",{className:"text-sm text-text-secondary",children:"Nothing scheduled this week. Promote an idea from Backlog to start."}),s.jsx(W,{intent:"brand",variant:"solid",size:"sm",className:"mt-3",onClick:e,children:"Open Backlog"})]})})]}),s.jsxs(V,{children:[s.jsx(wo,{caption:"Click a chip to open the pillar",children:"Publish lanes"}),s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("div",{className:"grid min-w-[640px]",style:{gridTemplateColumns:"88px repeat(7, minmax(0, 1fr))"},children:[s.jsx("div",{className:"border-b border-r border-outline-subtle bg-surface-subtle px-3 py-2 text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:"Channel"}),j.map((S,O)=>s.jsxs("div",{className:B("border-b border-outline-subtle bg-surface-subtle px-2 py-2 text-[11px] font-medium text-text-secondary",O<6&&"border-r",Br(S)===x&&"text-text-brand"),children:[sG[O]," ",S.getUTCDate()]},O)),cf.map(S=>s.jsx(RHe,{channel:S,days:j,assets:a.filter(O=>O.channel===S),onOpen:O=>t(`/content/pillars/${O}`)},S))]})})]})]}),s.jsxs(V,{className:"xl:w-[360px] xl:shrink-0",children:[s.jsx(wo,{caption:s.jsx("span",{className:"inline-flex h-5 min-w-[20px] items-center justify-center rounded-full bg-surface-errorSubtle px-1.5 text-[11px] font-semibold text-text-error",children:C}),children:"Needs you today"}),s.jsxs("div",{className:"flex gap-2 border-b border-outline-subtle px-4 py-3 lg:hidden",children:[s.jsx(DHe,{pillar:k}),s.jsx(MHe,{assets:E.filter(S=>!S.url),onPaste:y})]}),s.jsxs("div",{children:[A.map(S=>s.jsx(jm,{kind:"Overdue",tone:"overdue",title:S.pillar_title??Zn[S.channel],meta:`${Zn[S.channel]} · ${Bs(S.scheduled_date)}`,action:S.url?s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",onClick:()=>g(S),children:"Mark published"}):d===S.id?s.jsx("input",{autoFocus:!0,className:B(cr,"w-28 text-xs"),placeholder:"paste URL",onBlur:O=>y(S,O.target.value),onKeyDown:O=>O.key==="Enter"&&y(S,O.target.value)}):s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",onClick:()=>h(S.id),children:"Paste URL"})},`o-${S.id}`)),E.filter(S=>S.status!=="published").map(S=>s.jsx(jm,{kind:"Publishes today",tone:"scheduled",title:S.pillar_title??S.format??Zn[S.channel],meta:Zn[S.channel],extra:S.cta_url?s.jsx(W3,{text:S.cta_url}):null,action:s.jsx(W,{intent:"brand",variant:"outline",size:"sm",onClick:()=>g(S),children:"Mark published"})},`d-${S.id}`)),n.runway_red&&s.jsx(jm,{kind:"Runway",tone:"warning",title:"Nothing promoted far enough ahead",meta:"Stay 2â3 pillars in front of the week",action:s.jsx(W,{intent:"warning",variant:"outline",size:"sm",onClick:e,children:"Open backlog"})}),n.upcoming.slice(0,3).map(S=>s.jsx(jm,{kind:"Upcoming",tone:"draft",title:S.title,meta:`${qp[S.status]} · ${Bs(S.target_publish_week)}`,action:s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",onClick:()=>t(`/content/pillars/${S.id}`),children:"Open"})},`u-${S.id}`)),v.slice(0,2).map(S=>s.jsx(jm,{kind:"Film",tone:"warning",title:`/${S.name}`,meta:S.description,action:s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",onClick:()=>t("/content/film-queue"),children:"Open queue"})},S.name)),C===0&&n.upcoming.length===0&&v.length===0&&s.jsx("div",{className:"px-4 py-6 text-sm text-text-tertiary",children:"Nothing waiting."})]})]})]})]})}function PHe({current:e}){const t=ip.indexOf(e);return s.jsxs("div",{className:"mt-4",children:[s.jsx("div",{className:"flex gap-[3px]",children:ip.map((n,r)=>s.jsx("div",{className:B("h-1 flex-1 rounded-[2px]",r<t?"bg-intent-brand":r===t?"bg-brand-400":"bg-outline-subtle")},n))}),s.jsx("div",{className:"mt-1.5 hidden sm:flex",children:ip.map(n=>s.jsx("div",{className:"min-w-0 flex-1 truncate text-[11px] text-text-tertiary",children:qp[n]},n))})]})}function RHe({channel:e,days:t,assets:n,onOpen:r}){return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex min-h-[46px] items-center border-b border-r border-outline-subtle px-3 text-[12.5px] font-medium text-text-primary",children:Zn[e]}),t.map((a,i)=>{const o=n.filter(l=>l.scheduled_date===Br(a));return s.jsx("div",{className:B("flex min-h-[46px] flex-col justify-center gap-1 border-b border-outline-subtle px-1.5 py-1",i<6&&"border-r"),children:o.map(l
909=>s.jsx("button",{type:"button",onClick:()=>r(l.pillar_id),className:"truncate text-left",children:s.jsx(dl,{tone:Ev(l.status,l.scheduled_date),className:"max-w-full truncate",children:l.format??l.pillar_title??Zn[e]})},l.id))},i)})]})}function jm({kind:e,tone:t,title:n,meta:r,action:a,extra:i}){const o={overdue:"bg-intent-error",scheduled:"bg-brand-500",warning:"bg-warning-500",draft:"bg-outline-strong"}[t],l={overdue:"text-text-error",scheduled:"text-text-brand",warning:"text-text-warning",draft:"text-text-secondary"}[t];return s.jsxs("div",{className:"flex flex-col gap-2 border-b border-outline-subtle px-4 py-3 sm:flex-row sm:items-start sm:gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:B("flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.08em]",l),children:[s.jsx("span",{className:B("h-1.5 w-1.5 rounded-full",o)}),e]}),s.jsx("div",{className:"mt-0.5 text-[13.5px] font-medium text-text-primary",children:n}),r&&s.jsx("div",{className:"mt-0.5 text-xs text-text-secondary",children:r})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[i,a]})]})}function DHe({pillar:e}){var l;const[t,n]=p.useState(!1),r=p.useRef(null),a=p.useRef(null),i=async()=>{n(!0);try{const c=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment"},audio:!1});a.current=c,r.current&&(r.current.srcObject=c)}catch{}},o=()=>{var c;(c=a.current)==null||c.getTracks().forEach(u=>u.stop()),a.current=null,n(!1)};return s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",onClick:i,className:"flex h-10 flex-1 items-center justify-center gap-2 rounded-lg border border-outline-subtle bg-surface text-sm font-medium text-text-primary",children:[s.jsx(up,{className:"h-4 w-4"})," Capture"]}),t&&s.jsxs("div",{className:"fixed inset-0 z-modal overflow-auto bg-surface-subtle p-4",children:[s.jsx("button",{type:"button",className:"text-sm text-text-brand",onClick:o,children:"â Today"}),s.jsxs("div",{className:"mx-auto mt-3 max-w-md space-y-3",children:[s.jsx("div",{className:"overflow-hidden rounded-2xl bg-gray-900",children:s.jsx("video",{ref:r,autoPlay:!0,playsInline:!0,muted:!0,className:"h-[300px] w-full object-cover"})}),s.jsxs(V,{padding:"md",children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:"Current shot"}),s.jsx("div",{className:"mt-1 text-[15px] font-medium text-text-primary",children:"Talking-head open · the data hook"}),s.jsx("div",{className:"mt-1 font-mono text-xs text-text-brand",children:"target 0:18"})]}),s.jsxs(V,{padding:"md",children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:"Teleprompter"}),s.jsx("p",{className:"mt-2 text-[15px] leading-[23px] text-text-body",children:((l=e==null?void 0:e.data_hook)==null?void 0:l.captured_value)??"Name the pain in one sentence. End on the one-line fix."})]}),s.jsx("button",{type:"button",className:"mx-auto flex h-16 w-16 items-center justify-center rounded-full bg-intent-error text-text-inverse","aria-label":"Close capture",onClick:o,children:s.jsx(up,{className:"h-6 w-6"})})]})]})]})}function MHe({assets:e,onPaste:t}){const[n,r]=p.useState(!1),a=e[0];return s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",onClick:()=>r(!0),className:"flex h-10 flex-1 items-center justify-center gap-2 rounded-lg border border-outline-subtle bg-surface text-sm font-medium text-text-primary",children:[s.jsx(Qt,{className:"h-4 w-4"})," Paste URL"]}),n&&s.jsx("div",{className:"fixed inset-0 z-modal flex items-end bg-black/40 p-4",onClick:()=>r(!1),children:s.jsxs("div",{className:"w-full rounded-2xl bg-surface p-4",onClick:i=>i.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Paste a published URL"}),a?s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"mt-1 text-xs text-text-secondary",children:[Zn[a.channel]," · ",a.pillar_title]}),s.jsx("input",{autoFocus:!0,className:B(cr,"mt-3 w-full"),placeholder:"https://â¦",onKeyDown:i=>{i.key==="Enter"&&(t(a,i.target.value),r(!1))},onBlur:i=>{i.target.value&&(t(a,i.target.value),r(!1))}})]}):s.jsx("p",{className:"mt-2 text-sm text-text-secondary",children:"Nothing waiting on a URL today."}),s.jsx(W,{intent:"neutral",variant:"ghost",size:"sm",className:"mt-3",onClick:()=>r(!1),children:"Close"})]})})]})}const cL="gadjet:content-wip";function $He({onOpenBacklog:e}){const t=Rt(),[n,r]=p.useState(null),[a,i]=p.useState(null),[o,l]=p.useState(0),[c,u]=
909p.useState(null),[d,h]=p.useState(null),[f,m]=p.useState(()=>{try{return localStorage.getItem(cL)!=="0"}catch{return!0}}),x=p.useCallback(()=>l(b=>b+1),[]);p.useEffect(()=>{let b=!0;return At.listPillars().then(v=>b&&r(v.pillars)).catch(v=>b&&i(v.message)),()=>{b=!1}},[o]);const g=async(b,v)=>{if(b.status!==v){r(w=>(w==null?void 0:w.map(_=>_.id===b.id?{..._,status:v}:_))??w);try{await At.updatePillar(b.id,{status:v})}catch{x()}}},y=()=>{m(b=>{const v=!b;try{localStorage.setItem(cL,v?"1":"0")}catch{}return v})};return a?s.jsx(Zi,{msg:a}):n?n.length===0?s.jsx(V,{padding:"lg",className:"max-w-xl",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx(M2,{className:"mt-0.5 h-5 w-5 text-text-brand"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"No pillars in production yet"}),s.jsx("p",{className:"mt-1 text-sm text-text-secondary",children:"Promote an idea from Backlog to start this weekâs pillar."}),s.jsx(W,{intent:"brand",variant:"solid",size:"sm",className:"mt-3",onClick:e,children:"Open Backlog"})]})]})}):s.jsxs(V,{children:[s.jsxs("div",{className:"flex min-h-11 items-center gap-3 border-b border-outline-subtle bg-surface-subtle px-4 py-2",children:[s.jsxs("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:[n.length," pillars"]}),s.jsxs("label",{className:"ml-auto flex cursor-pointer items-center gap-2 text-xs text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:f,onChange:y}),"WIP limit of ",cj]})]}),s.jsx("div",{className:"flex overflow-x-auto",children:ip.map(b=>{const v=n.filter(_=>_.status===b),w=f&&v.length>cj;return s.jsxs("div",{className:B("flex min-h-[420px] w-[198px] shrink-0 flex-col border-r border-outline-subtle last:border-r-0 md:min-w-[198px] md:flex-1",d===b&&"bg-surface-brandSubtle/40"),onDragOver:_=>{_.preventDefault(),h(b)},onDragLeave:()=>h(_=>_===b?null:_),onDrop:_=>{_.preventDefault(),h(null);const k=Number(_.dataTransfer.getData("text/plain")),j=n.find(N=>N.id===k);j&&g(j,b),u(null)},children:[s.jsxs("div",{className:"sticky top-0 z-10 flex h-10 shrink-0 items-center gap-2 border-b border-outline-subtle bg-surface px-3",children:[s.jsx("span",{className:B("h-1.5 w-1.5 rounded-full",SHe[b])}),s.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:qp[b]}),s.jsx("span",{className:B("ml-auto rounded-full px-1.5 py-0.5 text-[11px] tabular-nums",w?"bg-surface-warningSubtle text-text-warning":"bg-surface-sunken text-text-body"),children:v.length})]}),w&&s.jsxs("div",{className:"border-b border-outline-warning bg-surface-warningSubtle px-3 py-1 text-[11px] text-text-warning",children:["Over WIP limit of ",cj]}),s.jsxs("div",{className:"flex flex-col gap-2 p-2",children:[v.map(_=>{var k;return s.jsxs("article",{draggable:!0,onDragStart:j=>{j.dataTransfer.setData("text/plain",String(_.id)),j.dataTransfer.effectAllowed="move",u(_.id)},onDragEnd:()=>{u(null),h(null)},onClick:()=>t(`/content/pillars/${_.id}`),className:B("cursor-grab rounded-lg border border-outline-subtle bg-surface p-2.5 shadow-xs transition hover:shadow-md active:cursor-grabbing",c===_.id&&"opacity-50"),children:[s.jsx("div",{className:"text-[13px] font-semibold text-text-primary",children:_.title}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[_.target_publish_week&&s.jsx("span",{className:"rounded bg-surface-sunken px-1.5 py-0.5 font-mono text-[11px] text-text-body",children:Bs(_.target_publish_week)}),((k=_.data_hook)==null?void 0:k.captured_value)&&s.jsxs("span",{className:"inline-flex items-center gap-0.5 rounded bg-surface-brandSubtle px-1.5 py-0.5 text-[11px] font-semibold text-text-brand",children:[s.jsx(Ht,{className:"h-2.5 w-2.5"})," HOOK"]})]}),typeof _.asset_count=="number"&&_.asset_count>0&&s.jsxs("div",{className:"mt-2",children:[s.jsx("div",{className:"h-[3px] overflow-hidden rounded-full bg-outline-subtle",children:s.jsx("div",{className:"h-full bg-intent-brand",style:{width:`${Math.round((_.published_count??0)/_.asset_count*100)}%`}})}),s.jsxs("div",{className:"mt-1 flex items-center justify-between text-[11px] text-text-secondary",children:[s.jsxs("span",{className:"tabular-nums",children:[_.published_count??0,"/",_.asset_count," live"]}),s.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-surface-brandSubtle text-[10px] font-semibold text-text-brand",children:"·"})]})]})]},_.id)}),v.length===0&&s.jsx("div",{className:"rounded-lg border border-dashed border-outline px-2 py-6 text-center text-xs text-text-tertiary",children:"Drop here"})]})]},b)})})]}):s.jsx(Ro,{})}function LHe(){const e=Rt(),[t,n]=p.useState(()=>{const j=new Date;return new Date(Date.UTC(j.getUTCFullYear(),j.getUTCMonth(),1))}),[r,a]=p.useState("month"),[i,o]=p.useState(null),[l,c]=p.useState([]),[u,d]=p.useState(null),[h,f]=p.useState(null),m=t,x=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth()+1,0)),g=Zo(m),y=Gl(Zo(x),6);p.useEffect(()=>{let j=!0;return Promise.all([At.listAssets(Br(g),Br(y)),At.listAssets(void 0,void 0,{undated:!0})]).then(([N,E])=>{j&&(o(N.assets),c(E.assets.filter(A=>!A.scheduled_date)))}).catch(N=>j&&d(N.message)),()=>{j=!1}},[g.getTime(),y.getTime()]);const b=p.useMemo(()=>{const j=[];for(let N=new Date(g);N<=y;N=Gl(N,1))j.push(new Date(N));return j},[g.getTime(),y.getTime()]),v=Zo(new Date),w=j=>(i??[]).filter(N=>N.channel===j&&N.scheduled_date&&N.scheduled_date>=Br(v)&&N.scheduled_date<=Br(Gl(v,6))).length,_=async(j,N)=>{const E=[...i??[],...l].find(C=>C.id===N);if(!E)return;const A=Br(j);o(C=>[...(C??[]).filter(S=>S.id!==N),{...E,scheduled_date:A,status:E.status==="draft"?"scheduled":E.status}]),c(C=>C.filter(T=>T.id!==N));try{await At.updateAsset(N,{scheduled_date:A,status:E.status==="draft"?"scheduled":E.status})}catch{}},k=t.toLocaleDateString("en-ZA",{month:"long",year:"numeric",timeZone:"UTC"});return u?s.jsx(Zi,{msg:u}):i?s.jsx(V,{children:s.jsxs("div",{className:"flex flex-col lg:flex-row",children:[s.jsxs("aside",{className:"border-b border-outline-subtle bg-surface-subtle lg:w-[248px] lg:shrink-0 lg:border-b-0 lg:border-r",children:[s.jsx(wo,{children:"Cadence this week"}),s.jsx("div",{className:"grid grid-cols-2 gap-1.5 p-3 lg:grid-cols-1",children:cf.map(j=>{const N=w(j),E=AHe[j],A=N>=E;return s.jsxs("div",{className:B("flex items-center justify-between rounded-md px-2.5 py-1.5 text-[12.5px]",A?"bg-surface-successSubtle":"bg-surface-warningSubtle"),children:[s.jsx("span",{className:"font-medium text-text-primary",children:Zn[j]}),s.jsxs("span",{className:"tabular-nums text-text-secondary",children:[N," of ",E]})]},j)})}),s.jsx(wo,{children:"Unscheduled"}),s.jsxs("div",{className:"flex flex-wrap gap-1.5 p-3 lg:flex-col",children:[l.length===0&&s.jsx("div",{className:"text-xs text-text-tertiary",children:"All dated."}),l.map(j=>s.jsxs("div",{draggable:!0,onDragStart:N=>{N.dataTransfer.setData("text/plain",String(j.id)),f(j.id)},onDragEnd:()=>f(null),className:B("cursor-grab rounded-md border border-outline-subtle bg-surface px-2 py-1.5 text-[12px] shadow-xs",h===j.id&&"opacity-50"),children:[s.jsx("div",{className:"font-medium text-text-brand",children:Zn[j.channel]}),s.jsx("div",{className:"truncate text-text-secondary",children:j.format??j.pillar_title})]},j.id))]})]}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex h-11 shrink-0 items-center gap-2 border-b border-outline-subtle px-3 md:px-4",children:[s.jsx(W,{intent:"neutral",variant:"ghost",size:"sm",onClick:()=>n(new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth()-1,1))),children:s.jsx(ud,{className:"h-4 w-4"})}),s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:k}),s.jsx(W,{intent:"neutral",variant:"ghost",size:"sm",onClick:()=>
909n(new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth()+1,1))),children:s.jsx(fr,{className:"h-4 w-4"})}),s.jsxs("div",{className:"ml-auto flex rounded-md border border-outline-subtle text-xs",children:[s.jsx("button",{type:"button",className:B("px-2.5 py-1",r==="month"&&"bg-surface-subtle font-medium"),onClick:()=>a("month"),children:"Month"}),s.jsx("button",{type:"button",className:B("px-2.5 py-1",r==="week"&&"bg-surface-subtle font-medium"),onClick:()=>a("week"),children:"Week"})]})]}),s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("div",{className:"min-w-[560px]",children:[s.jsx("div",{className:"grid shrink-0 grid-cols-7 border-b border-outline-subtle",children:sG.map(j=>s.jsx("div",{className:"h-10 border-r border-outline-subtle px-2 py-2 text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary last:border-r-0",children:j},j))}),s.jsx("div",{className:"grid min-h-[420px] grid-cols-7 grid-rows-5",children:b.map(j=>{const N=Br(j),E=j.getUTCMonth()===t.getUTCMonth(),A=N===Br(new Date),C=i.filter(S=>S.scheduled_date===N),T=r==="week"?N>=Br(Zo(new Date))&&N<=Br(Gl(Zo(new Date),6)):!0;return r==="week"&&!T?s.jsx("div",{className:"border-b border-r border-outline-subtle bg-surface-subtle"},N):s.jsxs("div",{onDragOver:S=>S.preventDefault(),onDrop:S=>{S.preventDefault();const O=Number(S.dataTransfer.getData("text/plain"));O&&_(j,O)},className:"flex flex-col overflow-hidden border-b border-r border-outline-subtle p-1.5 last:border-r-0",children:[s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("span",{className:B("font-mono text-xs tabular-nums",E?"text-text-primary":"text-text-tertiary"),children:j.getUTCDate()}),A&&s.jsx("span",{className:"h-[5px] w-[5px] rounded-full bg-brand-500"})]}),s.jsxs("div",{className:"mt-1 min-h-0 flex-1 space-y-0.5 overflow-auto",children:[C.map(S=>s.jsx("button",{type:"button",draggable:!0,onDragStart:O=>{O.dataTransfer.setData("text/plain",String(S.id)),f(S.id)},onClick:()=>e(`/content/pillars/${S.pillar_id}`),className:"block w-full truncate text-left",children:s.jsxs(dl,{tone:Ev(S.status,S.scheduled_date),className:"max-w-full truncate",children:[Zn[S.channel]," ",S.format??""]})},S.id)),C.length===0&&E&&j.getUTCDay()!==0&&j.getUTCDay()!==6&&s.jsx("div",{className:"rounded border border-dashed border-outline-subtle px-1 py-0.5 text-[10px] text-text-tertiary",children:"gap"})]})]},N)})})]})})]})]})}):s.jsx(Ro,{})}const FHe=["inbox","ranked","dismissed"];function BHe(){var I;const e=Rt(),[t,n]=it("queue","inbox"),r=FHe.includes(t)?t:"inbox",[a,i]=p.useState(null),[o,l]=p.useState(null),[c,u]=p.useState(null),[d,h]=p.useState(null),[f,m]=p.useState(0),x=p.useCallback(()=>m($=>$+1),[]),[g,y]=p.useState(""),[b,v]=p.useState("capability-menu"),[w,_]=p.useState(!1),[k,j]=p.useState(""),[N,E]=p.useState("light"),[A,C]=p.useState(!1);p.useEffect(()=>{let $=!0;return Promise.all([At.listIdeas("idea"),At.listProposals()]).then(([P,F])=>{$&&(i(P.ideas),l(F.proposals),u(Z=>F.proposals.find(H=>H.id===(Z==null?void 0:Z.id))??F.proposals.find(H=>H.state===r)??F.proposals[0]??null))}).catch(P=>$&&h(P.message)),()=>{$=!1}},[f]);const T=async()=>{if(g.trim()){_(!0);try{const $=a&&a.length?a[0].priority_rank:1e3;await At.createIdea({title:g.trim(),source_tag:b,priority_rank:$-10}),y(""),x()}catch($){h($.message)}finally{_(!1)}}},S=(o??[]).filter($=>$.state===r),O=(o??[]).filter($=>$.state==="inbox").length,R=async $=>{C(!0);try{const P=await At.promoteProposal($.id,{target_publish_week:k||void 0,scaffold:N});e(`/content/pillars/${P.pillar.id}`)}catch(P){h(P.message),C(!1)}};return s.jsxs(V,{children:[s.jsx(As,{tone:"subtle",items:[{key:"inbox",label:"Inbox",active:r==="inbox",onClick:()=>n("inbox"),trailing:O?s.jsx("span",{className:"ml-1 rounded-full bg-surface-brandSubtle px-1.5 text-[11px] font-semibold text-text-brand",children:O}):void 0},{key:"ranked",label:"Ranked",active:r==="ranked",onClick:()=>n("ranked")},{key:"dismissed",label:"Dismissed",active:r==="dismissed",onClick:()=>n("dismissed")}]}),d&&s.jsx(Zi,{msg:d}),(!a||!o)&&!d&&s.jsx(Ro,{}),o&&s.jsxs("div",{className:"flex flex-col lg:flex-row",children:[s.jsxs("div",{className:"min-w-0 flex-1 p-3.5",children:[s.jsxs("div",{className:"mb-3 flex flex-col gap-2 sm:flex-row sm:items-center",children:[s.jsx("input",{className:B(cr,"min-w-0 flex-1 text-xs"),placeholder:"Add an idea",value:g,onChange:$=>y($.target.value),onKeyDown:$=>$.key==="Enter"&&T()}),s.jsx("select",{className:B(cr,"text-xs sm:w-40"),value:b,onChange:$=>v($.target.value),children:CHe.map($=>s.jsx("option",{value:$,children:rG[$]},$))}),s.jsxs(W,{intent:"brand",variant:"solid",size:"sm",onClick:T,disabled:w||!g.trim(),children:[s.jsx(In,{className:"h-4 w-4"})," Add"]})]}),s.jsxs("div",{className:"flex flex-col gap-2.5",children:[S.length===0&&s.jsxs("div",{className:"rounded-lg border border-dashed border-outline px-4 py-8 text-center text-sm text-text-tertiary",children:["Nothing in ",r,". Add an idea or wait for the next proposal sweep."]}),S.map($=>s.jsxs("button",{type:"button",onClick:()=>u($),className:B("rounded-[10px] border p-3.5 text-left",(c==null?void 0:c.id)===$.id?"border-outline-brand bg-surface-brandSubtle":"border-outline-subtle bg-surface hover:border-outline"),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[$.skill&&s.jsxs("span",{className:"rounded bg-surface-sunken px-1.5 py-0.5 font-mono text-[11px] text-text-body",children:["/",$.skill]}),s.jsx(dl,{tone:$.confidence==="high"?"live":$.confidence==="low"?"draft":"warning",children:$.confidence}),s.jsx("span",{className:"ml-auto text-xs text-text-tertiary",children:Bs($.created_at.slice(0,10))})]}),s.jsx("div",{className:"mt-1.5 text-base font-semibold text-text-primary",children:$.title}),$.resolved_stat&&s.jsxs("div",{className:"mt-1 text-[12px] text-text-secondary",children:[s.jsx("span",{className:"font-semibold text-text-brand",children:"HOOK "}),$.resolved_stat]})]},$.id))]})]}),s.jsx("aside",{className:"border-t border-outline-subtle lg:w-[400px] lg:shrink-0 lg:border-l lg:border-t-0 xl:w-[472px]",children:c?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"p-4 md:p-5",children:[s.jsx("h2",{className:"text-[19px] font-semibold text-text-primary",children:c.title}),c.resolved_stat&&s.jsx("div",{className:"mt-3",children:s.jsx(Iw,{value:c.resolved_stat,provenance:c.skill})}),c.why_now&&s.jsx("p",{className:"mt-4 text-[13.5px] leading-relaxed text-text-body",children:c.why_now}),((I=c.angles)==null?void 0:I.length)>0&&s.jsxs("div",{className:"mt-4 space-y-1.5",children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:"Suggested angles"}),c.angles.map(($,P)=>s.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-outline-subtle px-3 py-2",children:[s.jsx("span",{className:"w-[66px] text-[12px] font-medium text-text-secondary",children:$.channel}),s.jsx("span",{className:"text-[13px] text-text-primary",children:$.angle})]},P))]}),a&&a.length>0&&r==="inbox"&&s.jsx(UHe,{ideas:a,onPromote:async $=>{C(!0);try{const P=await At.promoteIdea($.id,{target_publish_week:k||void 0,scaffold:N});e(`/content/pillars/${P.pillar.id}`)}catch(P){h(P.message),C(!1)}},onDelete:async $=>{i(P=>(P==null?void 0:P.filter(F=>F.id!==$.id))??P);try{await At.deleteIdea($.id)}catch{x()}}})]}),s.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-2 border-t border-outline-subtle bg-surface-subtle px-4 py-3",children:[s.jsx("input",{type:"date",className:B(cr,"text-xs"),value:k,onChange:$=>j($.target.value),title:"Target week"}),s.jsxs("label",{className:"text-xs text-text-secondary",children:[s.jsx("input",{type:"radio",checked:N==="light",onCh
909ange:()=>E("light")})," light"]}),s.jsxs("label",{className:"text-xs text-text-secondary",children:[s.jsx("input",{type:"radio",checked:N==="full",onChange:()=>E("full")})," full"]}),s.jsx(W,{intent:"brand",variant:"solid",size:"sm",onClick:()=>void R(c),disabled:A,children:A?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):"Promote as pillar"}),c.state==="inbox"&&s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",onClick:()=>At.updateProposal(c.id,{state:"ranked"}).then(x),children:"Send to ranked"}),s.jsx(W,{intent:"neutral",variant:"ghost",size:"sm",onClick:()=>At.updateProposal(c.id,{state:"dismissed"}).then(x),children:"Dismiss"})]})]}):s.jsx("div",{className:"p-6 text-sm text-text-tertiary",children:"Select a proposal."})})]})]})}function UHe({ideas:e,onPromote:t,onDelete:n}){return s.jsxs("div",{className:"mt-6",children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:"Hand-typed ideas"}),s.jsx("div",{className:"mt-2 space-y-1",children:e.slice(0,8).map((r,a)=>s.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-outline-subtle px-2 py-1.5",children:[s.jsxs("div",{className:"flex flex-col text-text-tertiary",children:[s.jsx(t0,{className:"h-3 w-3"}),s.jsx(Pn,{className:"h-3 w-3"})]}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"truncate text-[13px] font-medium",children:r.title}),s.jsx("div",{className:"text-[11px] text-text-secondary",children:rG[r.source_tag]})]}),s.jsx(W,{intent:"brand",variant:"ghost",size:"sm",onClick:()=>t(r),children:"Promote"}),s.jsx("button",{type:"button",className:"text-text-tertiary hover:text-text-error",onClick:()=>n(r),children:s.jsx(us,{className:"h-3.5 w-3.5"})}),s.jsx("span",{className:"hidden",children:a})]},r.id))})]})}const zHe={...Zn,google_ads:"Google Ads"};function Av(e){return zHe[e]??e}function Gp(e){return e==null||Number.isNaN(Number(e))?"â":`R${Math.round(e).toLocaleString("en-ZA")}`}function WHe(e){const t=e.ads;if(!(t!=null&&t.connected))return t!=null&&t.reason?`Ads not connected â ${t.reason}`:"Media spend not connected";const n=Gp(t.spend_zar);return t.cost_per_trial_zar==null?`${n} spend · ${t.trials} Ads trials · ILSâZAR ${t.fx.ils_per_zar} (${t.fx.as_of})`:`${n} spend / ${t.trials} Ads trials · ILSâZAR ${t.fx.ils_per_zar}`}function KHe(){var u,d,h;const[e,t]=p.useState(null),[n,r]=p.useState(null),[a,i]=p.useState(null),[o,l]=p.useState(30);if(p.useEffect(()=>{let f=!0;return At.performance({days:o}).then(m=>f&&t(m.performance)).catch(m=>f&&r(m.message)),()=>{f=!1}},[o]),n)return s.jsx(Zi,{msg:n});if(!e)return s.jsx(Ro,{});const c=Math.max(1,...e.reach_series.map(f=>f.value));return s.jsxs("div",{className:"space-y-4 md:space-y-6",children:[s.jsxs("div",{className:"flex items-center justify-end gap-2",children:[s.jsx("span",{className:"text-xs text-text-secondary",children:"Range"}),[7,30,90].map(f=>s.jsxs("button",{type:"button",onClick:()=>l(f),className:B("rounded-md px-2 py-1 text-xs",o===f?"bg-surface font-medium":"text-text-secondary"),children:[f,"d"]},f))]}),s.jsx(Ow,{cells:[{label:"Reach 30d",value:ta(e.reach),hint:"Blog pageviews + email unique opens"},{label:"Engagement rate",value:e.engagement_rate==null?"â":`${e.engagement_rate}%`,hint:"Email unique-open rate when captured"},{label:"Clicks to site",value:ta(e.clicks),hint:"Email clicks + blog GSC clicks + Google Ads clicks"},{label:"Trials attributed",value:ta(e.trials),hint:"Pillar slug or Ads campaign id (first-touch UTM)",tone:"success"},{label:"Cost per trial",value:Gp(e.cost_per_trial),hint:WHe(e)}]}),s.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row",children:[s.jsxs(V,{padding:"md",className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:"Reach"}),s.jsx("div",{className:"mt-3 flex h-[136px] items-end gap-[3px]",children:e.reach_series.map((f,m)=>s.jsx("div",{className:B("flex-1 rounded-t-[2px]",m>=e.reach_series.length-7?"bg-intent-brand":"bg-info-200"),style:{height:`${Math.max(4,f.value/c*100)}%`},title:`${f.date}: ${f.value}`},m))})]}
909),s.jsxs(V,{padding:"md",className:"lg:w-[360px] lg:shrink-0",children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:"Channel mix"}),s.jsx("div",{className:"mt-3 space-y-2.5",children:cf.map(f=>{const m=e.channels.find(b=>b.channel===f),x=(m==null?void 0:m.connected)??(f==="blog"||f==="email"),g=(m==null?void 0:m.reach)??0,y=Math.max(1,...e.channels.map(b=>b.reach));return s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 text-[12.5px]",children:[s.jsx("span",{className:"font-medium",children:Zn[f]}),x?s.jsxs("span",{className:"tabular-nums text-text-secondary",children:[ta(g),(m==null?void 0:m.engagement_rate)!=null?` · ${m.engagement_rate}%`:""]}):s.jsx(dl,{tone:"draft",children:"Not connected"})]}),s.jsx("div",{className:"h-1.5 overflow-hidden rounded-full bg-surface-sunken",children:s.jsx("div",{className:"h-full bg-brand-500",style:{width:`${x?g/y*100:0}%`}})})]},f)})})]})]}),s.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start",children:[s.jsxs(V,{className:"min-w-0 flex-1 overflow-hidden",children:[s.jsx(wo,{children:"Post leaderboard"}),s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("div",{className:"min-w-[720px]",children:[s.jsx("div",{className:"grid border-b border-outline-subtle bg-surface-subtle px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",style:{gridTemplateColumns:"96px 1fr 96px 72px 62px 62px 62px 54px 72px"},children:["Channel","Title","Date","Reach","Eng %","Clicks","Trials","Î",""].map(f=>s.jsx("span",{children:f},f))}),e.posts.map(f=>s.jsxs("button",{type:"button",onClick:()=>i(f),className:"grid w-full items-center border-b border-outline-subtle px-4 py-2.5 text-left text-[12.5px] hover:bg-surface-subtle",style:{gridTemplateColumns:"96px 1fr 96px 72px 62px 62px 62px 54px 72px"},children:[s.jsx("span",{children:Av(f.channel)}),s.jsx("span",{className:"truncate font-medium text-text-primary",children:f.title}),s.jsx("span",{className:"font-mono text-text-secondary",children:f.date??"â"}),s.jsx("span",{className:"tabular-nums",children:ta(f.reach)}),s.jsx("span",{className:"tabular-nums",children:f.engagement_rate==null?"â":`${f.engagement_rate}%`}),s.jsx("span",{className:"tabular-nums",children:ta(f.clicks)}),s.jsx("span",{className:"tabular-nums font-semibold text-text-success",children:ta(f.trials)}),s.jsx("span",{className:B("tabular-nums",(f.delta??0)>=0?"text-text-success":"text-text-error"),children:f.delta==null?"â":`${f.delta>0?"+":""}${f.delta}%`}),s.jsx("span",{className:"flex h-1.5 overflow-hidden rounded-full bg-surface-sunken",children:s.jsx("span",{className:"bg-brand-400",style:{width:`${Math.min(100,f.reach_share??0)}%`}})})]},f.id))]})})]}),s.jsxs(V,{className:"lg:w-[360px] lg:shrink-0",children:[s.jsx(wo,{children:"Pillars by reach"}),s.jsx("div",{className:"space-y-2 p-4",children:e.pillars.map(f=>s.jsxs("a",{href:`/content/pillars/${f.id}?tab=performance`,className:"block",children:[s.jsxs("div",{className:"flex items-center justify-between text-[13px]",children:[s.jsx("span",{className:"truncate font-medium",children:f.title}),s.jsx("span",{className:"tabular-nums text-text-secondary",children:ta(f.reach)})]}),s.jsx("div",{className:"mt-1 h-1.5 overflow-hidden rounded-full bg-surface-sunken",children:s.jsx("div",{className:"h-full bg-intent-brand",style:{width:`${Math.min(100,f.share??0)}%`}})}),s.jsxs("div",{className:"mt-0.5 text-[11px] text-text-tertiary",children:[f.assets," assets · ",f.trials," trials"]})]},f.id))}),s.jsx(wo,{children:"Connections"}),s.jsxs("div",{className:"space-y-2 p-4",children:[s.jsx(uL,{label:"Google Ads",connected:!!((u=e.ads)!=null&&u.connected),detail:(d=e.ads)!=null&&d.connected?`${e.ads.customer_id??""} · ${Gp(e.ads.spend_zar)}`:((h=e.ads)==null?void 0:h.reason)??"Not connected"}),cf.map(f=>{const m=f==="blog"||f==="email";return s.jsx(uL,{label:Zn[f],connected:m},f)})]})]})]}),a&&s.jsx(VHe,{post:a,onClose:()=>i(null)})]})}function HHe({pillarId:e,pillar:t}){var l;const[n,r]=p.useState(null),[a,i]=p.useState(null);if(p.useEffect(()=>{let c=!0;return At.performance({days:30,pillar_id:e}).then(u=>c&&r(u.performance)).catch(u=>c&&i(u.message)),()=>{c=!1}},[e]),a)return s.jsx(Zi,{msg:a});if(!n)return s.jsx(Ro,{});const o=n.posts[0];return s.jsxs("div",{className:"space-y-4 md:space-y-6",children:[s.jsx(Ow,{cells:[{label:"Pillar reach",value:ta(n.reach),hint:"vs other pillars this window"}
909,{label:"Clicks to site",value:ta(n.clicks)},{label:"Trials attributed",value:ta(n.trials),tone:"success"},{label:"Best derivative",value:o?Av(o.channel):"â"}]}),s.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start",children:[s.jsxs(V,{padding:"md",className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:"Contribution"}),s.jsx("div",{className:"mt-3 space-y-2",children:n.posts.map(c=>s.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-lg bg-surface-subtle px-3 py-2",children:[s.jsx("span",{className:"w-20 text-[12.5px] font-medium",children:Av(c.channel)}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[12.5px] text-text-secondary",children:c.title}),s.jsx("div",{className:"h-[22px] w-full overflow-hidden rounded-full bg-surface-sunken sm:w-auto sm:flex-1",children:s.jsx("div",{className:"h-full bg-brand-500",style:{width:`${Math.min(100,c.reach_share??0)}%`}})}),s.jsx("span",{className:"w-16 text-right tabular-nums",children:ta(c.reach)}),s.jsx("span",{className:"w-12 text-right font-semibold tabular-nums text-text-success",children:ta(c.tri
909als)})]},c.id))})]}),s.jsxs("div",{className:"space-y-3 lg:w-[360px] lg:shrink-0",children:[s.jsx(uj,{tone:"brand",title:"What held up",body:((l=t.data_hook)==null?void 0:l.captured_value)??"The pinned hook is the through-line."}),s.jsx(uj,{tone:"warning",title:"Weak channel",body:"Social is not connected â LinkedIn / Facebook / Instagram / YouTube show as empty, not zero."}),s.jsx(uj,{tone:"success",title:"Above its reach",body:"Email, blog, and Google Ads are the channels with a real denominator. Social is still empty, not zero."})]})]})]})}function VHe({post:e,onClose:t}){const n=Rt();return s.jsx(Cr,{open:!0,onOpenChange:r=>{r||t()},children:s.jsxs(mr,{side:"right",size:"lg",className:"md:w-[600px]",hideCloseButton:!1,children:[s.jsx(Er,{children:s.jsxs(xr,{children:[s.jsx("span",{className:"mr-2 text-xs font-semibold uppercase text-text-secondary",children:Av(e.channel)}),e.title]})}),s.jsxs(pr,{className:"space-y-4 p-5",children:[s.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row",children:[s.jsx("div",{className:"h-[160px] w-full shrink-0 rounded-lg border border-outline-subtle sm:h-[200px] sm:w-[200px]",style:{background:"repeating-linear-gradient(45deg,#F2F4F7,#F2F4F7 8px,#EAECF0 8px,#EAECF0 16px)"}}),s.jsxs("div",{className:"space-y-3",children:[s.jsx(Nm,{label:"Reach",value:ta(e.reach)}),s.jsx(Nm,{label:"Engagement rate",value:e.engagement_rate==null?"â":`${e.engagement_rate}%`}),s.jsx(Nm,{label:"Trials",value:ta(e.trials),success:!0}),e.spend_zar!=null&&s.jsx(Nm,{label:"Spend",value:Gp(e.spend_zar)}),e.ads_clicks!=null&&e.ads_clicks>0&&s.jsx(Nm,{label:"Ads clicks",value:ta(e.ads_clicks)})]})]}),s.jsxs("p",{className:"text-xs text-text-secondary",children:[e.date??"this window"," · utm_campaign=",e.campaign??"â",e.channel==="google_ads"?" · reach is Ads impressions":"",e.ads_spend_zar!=null&&e.ads_spend_zar>0?` · ${Gp(e.ads_spend_zar)} paid`:""]}),s.jsxs("div",{className:"flex gap-2",children:[e.url&&s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",onClick:()=>window.open(e.url,"_blank","noopener,noreferrer"),children:"View on channel"}),e.pillar_id&&s.jsx(W,{intent:"brand",variant:"outline",size:"sm",onClick:()=>n(`/content/pillars/${e.pillar_id}`),children:"Make a variant"})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:"14-day"}),s.jsx("div",{className:"mt-2 flex h-24 items-end gap-1",children:(e.series??[]).map((r,a)=>s.jsx("div",{className:"flex-1 rounded-t bg-brand-500",style:{height:`${Math.max(4,r)}%`}},a))})]})]})]})})}function uL({label:e,connected:t,detail:n}){return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between text-[13px]",children:[s.jsx("div",{className:"flex items-center gap-2",children:s.jsx(x6,{tone:t?"success":"neutral",children:e})}),s.jsx(dl,{tone:t?"live":"draft",children:t?"Connected":"Not connected"})]}),n?s.jsx("div",{className:"mt-0.5 pl-3.5 text-[11px] text-text-tertiary truncate",children:n}):null]})}function Nm({label:e,value:t,success:n}){return s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] uppercase text-text-secondary",children:e}),s.jsx("div",{className:B("text-[28px] font-semibold tabular-nums",n&&"text-text-success"),children:t})]})}function uj({tone:e,title:t,body:n}){const r={brand:"bg-surface-brandSubtle border-outline-brand",warning:"bg-surface-warningSubtle border-outline-warning",success:"bg-surface-successSubtle border-outline-success"}[e];return s.jsxs("div",{className:B("rounded-lg border p-3",r),children:[s.jsx("div",{className:"text-[13px] font-semibold text-text-primary",children:t}),s.jsx("p",{className:"mt-1 text-[12.5px] text-text-body",children:n})]})}function ta(e){return e==null?"â":Math.round(e).toLocaleString("en-ZA")}const qHe=["Shorter","Punchier hook","Add the data hook","Softer CTA","More specific"];function GHe({asset:e,pillar:t,onClose:n,onUse:r}){var b;const[a,i]=p.useState("write"),[o,l]=p.useState([]),[c,u]=p.useState(""),[d,h]=p.useState(!1),[f,m]=p.useState(null),x=Cv[e.channel],g=[...o].reverse().find(v=>v.role==="model");p.useEffect(()=>{let v=!0;return At.getThread(e.id).then(w=>
909{var _;v&&((_=w.turns)!=null&&_.length)&&l(w.turns)}).catch(()=>{}),()=>{v=!1}},[e.id]);const y=async v=>{const w=v.trim();if(!(!w||d)){h(!0),m(null),l(_=>[..._,{role:"user",text:w}]),u("");try{const k=(await At.generate({pillar_id:t.id,asset_id:e.id,channel:e.channel,prompt:w,shape:"chat"})).text??"";l(j=>{const N=[...j,{role:"model",text:k}];return At.saveThread(e.id,N).catch(()=>{}),N})}catch(_){m(_.message)}finally{h(!1)}}};return s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"fixed inset-0 z-drawer bg-black/40 md:hidden","aria-label":"Close composer",onClick:n}),s.jsxs("aside",{className:"fixed inset-0 z-drawer-content flex flex-col bg-surface md:absolute md:inset-y-0 md:left-auto md:right-0 md:w-[440px] md:border-l md:border-outline-subtle",style:{boxShadow:"-12px 0 24px -12px rgb(16 24 40 / 0.10)"},children:[s.jsxs("div",{className:"shrink-0 border-b border-outline-subtle px-4 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("span",{className:"rounded bg-surface-brandSubtle px-1.5 py-0.5 text-[11px] font-semibold uppercase tracking-[0.08em] text-text-brand",children:"Composer"}),s.jsxs("div",{className:"mt-1 text-sm font-semibold text-text-primary",children:[Zn[e.channel]," · ",e.scheduled_date??"undated"]})]}),s.jsx("button",{type:"button",onClick:n,className:"rounded p-1 text-text-tertiary hover:bg-surface-subtle","aria-label":"Close",children:s.jsx(Bn,{className:"h-4 w-4"})})]}),s.jsx(As,{tone:"subtle",className:"mt-2 border-0 px-0",items:[{key:"write",label:"Write",active:a==="write",onClick:()=>i("write")},{key:"refine",label:"Refine",active:a==="refine",onClick:()=>i("refine")},{key:"variants",label:"Variants",active:a==="variants",onClick:()=>i("variants")}]})]}),((b=t.data_hook)==null?void 0:b.captured_value)&&s.jsxs("div",{className:"mx-4 mt-3 rounded-lg border border-outline-brand bg-surface-brandSubtle px-3 py-2",children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-brand",children:"Grounded in"}),s.jsx("div",{className:"mt-0.5 text-[12.5px] text-text-primary",children:t.data_hook.captured_value})]}),s.jsxs("div",{className:"min-h-0 flex-1 space-y-3 overflow-auto px-4 py-3",children:[o.map((v,w)=>s.jsxs("div",{className:B("flex flex-col",v.role==="user"?"items-end":"items-start"),children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-tertiary",children:v.role==="user"?"You":"Model"}),s.jsx("div",{className:B("mt-1 max-w-[340px] whitespace-pre-line rounded-lg border px-3 py-2 text-[13px]",v.role==="user"?"border-outline-subtle bg-surface-subtle":"border-outline-brand bg-surface"),children:v.text})]},w)),g&&s.jsx("div",{className:"rounded-lg border border-outline-subtle",children:s.jsxs("div",{className:"flex items-center gap-2 bg-surface-subtle px-3 py-2",children:[s.jsx(W,{intent:"brand",variant:"solid",size:"sm",onClick:()=>r(g.text),children:"Use this"}),s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",onClick:()=>navigator.clipboard.writeText(g.text),children:"Copy"}),s.jsxs("span",{className:B("ml-auto font-mono text-[11px]",x&&g.text.length>x?"text-text-error":"text-text-tertiary"),children:[g.text.length,x?`/${x}`:""]})]})}),f&&s.jsx("div",{className:"text-xs text-text-error",children:f})]}),s.jsxs("div",{className:"shrink-0 border-t border-outline-subtle bg-surface-subtle p-3",children:[a==="refine"&&s.jsx("div",{className:"mb-2 flex flex-wrap gap-1.5",children:qHe.map(v=>s.jsx("button",{type:"button",onClick:()=>void y(v),className:"h-[26px] rounded-full border border-outline px-2.5 text-[12px] text-text-secondary hover:border-brand-400 hover:text-text-brand",children:v},v))}),s.jsxs("div",{className:"flex items-end gap-2",children:[s.jsx("textarea",{className:B(cr,"min-h-[40px] flex-1"),rows:2,placeholder:"Ask for a draft, or a rewriteâ¦",value:c,onChange:v=>u(v.target.value),onKeyDown:v=>{v.key==="Enter"&&!v.shiftKey&&(v.preventDefault(),y(c))}}),s.jsx(W,{intent:"brand",variant:"solid",size:"sm",onClick:()=>void y(c),disabled:d||!c.trim(),children:d?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):"Generate"})]}),s.jsx("div",{className:"mt-1 font-mono text-[11px] text-text-tertiary",children:"chat.default · content surface"})]})]})]})}function YHe({asset:e,pillar:t,onClose:n,onSave:r}){var N,E;const a=p.useMemo(()=>g6().slice(0,8),[]),[i,o]=p.useState(()=>{var A;return(A=t.data_hook)!=null&&A.captured_value?["data_hook"]:[]}),[l,c]=p.useState(`Write a ${Zn[e.channel].toLowerCase()} for â${t.title}
909â. Senior-analyst register, specific, benefit-led, grounded in the pinned data hook.`),[u,d]=p.useState(e.copy??""),[h,f]=p.useState(!1),[m,x]=p.useState(null),[g,y]=p.useState(null),b=u!==(e.copy??""),v=A=>{o(C=>C.includes(A)?C.filter(T=>T!==A):[...C,A])},w=async()=>{f(!0),x(null);try{const A=await At.generate({pillar_id:t.id,asset_id:e.id,channel:e.channel,prompt:l,sources:i,shape:"longform"});d(A.text??"")}catch(A){x(A.message)}finally{f(!1)}},_=()=>{r(u),y(new Date().toISOString())},k=()=>{b&&!window.confirm("Discard unsaved draft?")||n()},j=u.split(/\n(?=##\s)/).filter(Boolean);return s.jsx(js,{open:!0,onOpenChange:A=>{A||k()},children:s.jsxs(Ns,{size:"full",hideCloseButton:!0,className:"mx-2 flex h-[min(760px,calc(100dvh-1.5rem))] max-w-[1288px] flex-col overflow-hidden p-0 sm:mx-4",children:[s.jsxs("header",{className:"flex min-h-[52px] shrink-0 flex-wrap items-center gap-2 border-b border-outline-subtle px-4 py-2 md:h-[60px] md:flex-nowrap md:gap-3 md:px-5",children:[s.jsx("span",{className:"rounded bg-surface-brandSubtle px-1.5 py-0.5 text-[11px] font-semibold uppercase tracking-[0.08em] text-text-brand",children:"Generate"}),s.jsx("div",{className:"min-w-0 truncate text-base font-semibold text-text-primary",children:t.title}),s.jsx("span",{className:"rounded bg-surface-sunken px-1.5 py-0.5 font-mono text-[11px] text-text-body",children:Zn[e.channel]}),g&&s.jsxs("span",{className:"font-mono text-[11px] text-text-tertiary",children:["saved ",Bs(g.slice(0,10))]}),s.jsx("button",{type:"button",className:"ml-auto rounded p-1 text-text-tertiary hover:bg-surface-subtle",onClick:k,"aria-label":"Close",children:s.jsx(Bn,{className:"h-4 w-4"})})]}),s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto md:flex-row md:overflow-hidden",children:[s.jsxs("aside",{className:"shrink-0 border-b border-outline-subtle bg-surface-subtle p-4 md:w-[288px] md:overflow-auto md:border-b-0 md:border-r",children:[((N=t.data_hook)==null?void 0:N.captured_value)&&s.jsx(Iw,{value:t.data_hook.captured_value,provenance:t.data_hook.skill}),s.jsx("div",{className:"mt-4 space-y-1.5",children:[["Model","chat.default"],["Audience","Takealot sellers"],["Tone","Senior analyst"],["Length","Long-form"]].map(([A,C])=>s.jsxs("div",{className:"flex items-center justify-between rounded-md bg-surface px-2.5 py-2 text-[13px]",children:[s.jsx("span",{className:"text-text-secondary",children:A}),s.jsx("span",{className:"font-medium text-text-primary",children:C})]},A))}),s.jsx("div",{className:"mt-4 text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:"Sources"}),s.jsxs("label",{className:"mt-2 flex items-start gap-2 text-[13px]",children:[s.jsx("input",{type:"checkbox",checked:i.includes("data_hook"),onChange:()=>v("data_hook")}),s.jsxs("span",{children:[s.jsx("span",{className:"block",children:"Pinned data hook"}),s.jsx("span",{className:"font-mono text-[11.5px] text-text-tertiary",children:((E=t.data_hook)==null?void 0:E.skill)??"none"})]})]}),a.map(A=>s.jsxs("label",{className:"mt-1.5 flex items-start gap-2 text-[13px]",children:[s.jsx("input",{type:"checkbox",checked:i.includes(`blog:${A.slug}`),onChange:()=>v(`blog:${A.slug}`)}),s.jsxs("span",{children:[s.jsxs("span",{className:"block font-mono text-[11.5px]",children:[A.slug,".md"]}),s.jsx("span",{className:"text-[11px] text-text-tertiary",children:"blog"})]})]},A.slug))]}),s.jsxs("div",{className:"min-w-0 flex-1 p-4 md:overflow-auto md:p-5",children:[s.jsxs("div",{className:"rounded-lg border border-outline-subtle p-3",children:[s.jsx("textarea",{className:"w-full resize-none bg-transparent text-sm text-text-primary focus:outline-none",rows:3,value:l,onChange:A=>c(A.target.value)}),s.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[s.jsxs("span",{className:"text-xs text-text-tertiary",children:[l.split(/\s+/).filter(Boolean).length," words"]}),s.jsx(W,{intent:"brand",variant:"solid",size:"sm",onClick:()=>void w(),disabled:h,children:h?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):"Regenerate"})]})]}),m&&s.jsx("div",{className:"mt-3 text-sm text-text-error",children:m}),s.jsxs("article",{className:"mx-auto mt-6 max-w-[640px]",children:[h&&!u&&s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Generatingâ¦"]}),j.map((A,C)=>
909{const T=A.match(/^##\s+(.+)/),S=A.split(/\s+/).filter(Boolean).length;return s.jsxs("section",{className:"mb-5",children:[T&&s.jsxs("div",{className:"mb-1 flex items-baseline justify-between",children:[s.jsx("h3",{className:"text-[19px] font-semibold text-text-primary",children:T[1]}),s.jsxs("button",{type:"button",className:"text-xs text-text-brand hover:underline",onClick:()=>void w(),children:["Rewrite section · ",S,"w"]})]}),s.jsx("div",{className:"whitespace-pre-wrap text-[15px] leading-[25px] text-text-body",children:T?A.replace(/^##\s+.+\n?/,""):A})]},C)}),h&&u&&s.jsxs("div",{className:"mt-4 flex items-center gap-2 text-xs text-text-tertiary",children:[s.jsx("span",{className:"inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-brand-500"}),"streaming"]})]})]}),s.jsxs("aside",{className:"shrink-0 border-t border-outline-subtle bg-surface-subtle p-4 md:w-[264px] md:overflow-auto md:border-l md:border-t-0",children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:"Variants"}),s.jsxs("div",{className:B("mt-2 rounded-lg border p-3","border-outline-brand bg-surface-brandSubtle"),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"h-3 w-3 rounded-sm bg-intent-brand"}),s.jsx("span",{className:"text-[13px] font-medium",children:"Current draft"})]}),s.jsx("p",{className:"mt-1 line-clamp-4 text-xs text-text-secondary",children:u.slice(0,180)||"Empty"})]}),s.jsx("button",{type:"button",onClick:()=>void w(),className:"mt-2 w-full rounded-lg border border-dashed border-outline px-3 py-4 text-xs text-text-tertiary hover:border-brand-400",children:"Generate a fourth"})]})]}),s.jsxs("footer",{className:"flex min-h-[60px] shrink-0 flex-wrap items-center justify-end gap-2 border-t border-outline-subtle bg-surface-subtle px-4 py-3 sm:justify-between md:h-[60px] md:px-5 md:py-0",children:[s.jsx("span",{className:"hidden font-mono text-[11px] text-text-tertiary sm:inline",children:"chat.default · content · no seller tools"}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",onClick:()=>navigator.clipboard.writeText(u),disabled:!u,children:"Copy markdown"}),s.jsxs(W,{intent:"brand",variant:"solid",size:"sm",onClick:_,disabled:!u,children:["Save to ",Zn[e.channel].toLowerCase()," asset"]})]})]})]})})}const dL=["Stat card","Carousel cover","Quote card","How-to step","End slide"],ZHe=["1:1","4:5","9:16","16:9"],XHe=[{name:"Cover",caption:""},{name:"The number",caption:""},{name:"Why it matters",caption:""},{name:"What to do",caption:""},{name:"End / CTA",caption:""}];function JHe({asset:e,pillar:t,onClose:n,onAttach:r}){var T;const a=e.media??[],[i,o]=p.useState(`${t.title} â ${((T=t.data_hook)==null?void 0:T.captured_value)??"a specific Takealot seller proof point"}`),[l,c]=p.useState(dL[0]),[u,d]=p.useState("4:5"),[h,f]=p.useState(!0),[m,x]=p.useState(0),[g,y]=p.useState(XHe.map((S,O)=>{var R,I,$;return{...S,caption:((R=a[O])==null?void 0:R.caption)??S.caption,url:((I=a[O])==null?void 0:I.url)??null,storage_path:(($=a[O])==null?void 0:$.storage_path)??null}})),[b,v]=p.useState([]),[w,_]=p.useState(!1),[k,j]=p.useState(null),N=g[m],E=async()=>{_(!0),j(null);
909try{const S=await At.generateImage({prompt:i,preset:l,ratio:u,brand_lock:h,slide_index:m,pillar_title:t.title});v(S.candidates??[])}catch(S){j(S.message)}finally{_(!1)}},A=S=>{y(R=>R.map((I,$)=>$===m?{...I,url:S.url,storage_path:S.storage_path}:I));const O=g.findIndex((R,I)=>I!==m&&!R.url);O>=0&&x(O)},C=g.filter(S=>S.url).map((S,O)=>({url:S.url,storage_path:S.storage_path,caption:S.caption,slide_index:O,name:S.name}));return s.jsx(js,{open:!0,onOpenChange:S=>{S||n()},children:s.jsxs(Ns,{size:"full",hideCloseButton:!0,className:"mx-2 flex h-[min(760px,calc(100dvh-1.5rem))] max-w-[1288px] flex-col overflow-hidden p-0 sm:mx-4",children:[s.jsxs("header",{className:"flex min-h-[52px] shrink-0 items-center gap-3 border-b border-outline-subtle px-4 py-2 md:h-[60px] md:px-5",children:[s.jsx("span",{className:"rounded bg-surface-brandSubtle px-1.5 py-0.5 text-[11px] font-semibold uppercase tracking-[0.08em] text-text-brand",children:"Studio"}),s.jsxs("div",{className:"min-w-0 truncate text-base font-semibold text-text-primary",children:[Zn[e.channel]," carousel"]}),s.jsx("button",{type:"button",className:"ml-auto rounded p-1 text-text-tertiary hover:bg-surface-subtle",onClick:n,"aria-label":"Close",children:s.jsx(Bn,{className:"h-4 w-4"})})]}),s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto md:flex-row md:overflow-hidden",children:[s.jsxs("aside",{className:"shrink-0 border-b border-outline-subtle bg-surface-subtle p-4 md:w-[272px] md:overflow-auto md:border-b-0 md:border-r",children:[s.jsxs("label",{className:"text-xs text-text-secondary",children:["Prompt",s.jsx("textarea",{className:B(cr,"mt-1 w-full"),rows:5,value:i,onChange:S=>o(S.target.value)})]}),s.jsx("div",{className:"mt-3 flex flex-wrap gap-1.5",children:dL.map(S=>s.jsx("button",{type:"button",onClick:()=>c(S),className:B("rounded-full border px-2.5 py-1 text-[12px]",l===S?"border-outline-brand bg-surface-brandSubtle text-text-brand":"border-outline text-text-secondary"),children:S},S))}),s.jsx("div",{className:"mt-3 grid grid-cols-4 gap-1",children:ZHe.map(S=>s.jsx("button",{type:"button",onClick:()=>d(S),className:B("rounded-md border py-1.5 font-mono text-[11px]",u===S?"border-outline-brand bg-surface-brandSubtle":"border-outline"),children:S},S))}),s.jsxs("label",{className:"mt-4 flex items-center justify-between text-[13px]",children:[s.jsx("span",{children:"Brand palette lock"}),s.jsx("button",{type:"button",role:"switch","aria-checked":h,onClick:()=>f(S=>!S),className:B("relative h-5 w-[34px] rounded-full",h?"bg-intent-brand":"bg-outline"),children:s.jsx("span",{className:B("absolute top-0.5 h-4 w-4 rounded-full bg-surface transition",h?"left-[14px]":"left-0.5")})})]}),s.jsx(W,{intent:"brand",variant:"solid",size:"sm",className:"mt-4 w-full",onClick:()=>void E(),disabled:w,children:w?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):"Generate 4 options"}),k&&s.jsx("div",{className:"mt-2 text-xs text-text-error",children:k})]}),s.jsxs("div",{className:"min-w-0 flex-1 bg-surface-sunken p-4 md:overflow-auto md:p-5",children:[s.jsxs("div",{className:"mb-3 flex items-baseline justify-between",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:N.name}),s.jsx("div",{className:"font-mono text-[11px] text-text-tertiary",children:N.url?"assigned":"empty"})]}),s.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2",style:{gridAutoRows:"min-content"},children:(b.length?b:[null,null,null,null]).map((S,O)=>s.jsxs("button",{type:"button",disabled:!S,onClick:()=>S&&A(S),className:B("overflow-hidden rounded-lg border bg-surface text-left",S&&N.storage_path===S.storage_path?"border-2 border-outline-brand":"border-outline-subtle"),children:[S!=null&&S.url?s.jsx("img",{src:S.url,alt:"",className:"h-[180px] w-full object-cover sm:h-[250px]"}):s.jsx("div",{className:"flex h-[180px] items-center justify-center font-mono text-[11px] text-text-tertiary sm:h-[250px]",style:{background:"repeating-linear-gradient(45deg,#F2F4F7,#F2F4F7 8px,#EAECF0 8px,#EAECF0 16px)"},children:w?"generatingâ¦":"placeholder"}),s.jsxs("div",{className:"flex h-[33px] items-center justify-between px-2 text-[11px] text-text-secondary",children:[s.jsx("span",{children:S?"Ready":"â"}),S&&s.jsx("span",{children:"Select"})]})]},O))})]}),s.jsxs("aside",{className:"flex shrink-0 flex-col border-t border-outline-subtle md:w-[296px] md:border-l md:border-t-0",children:[s.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-3",children:g.map((S,O)=>s.jsxs("button",{type:"button",onClick:()=>x(O),className:B("mb-2 flex w-full items-center gap-2 rounded-md border p-1.5 text-left",O===m?"border-outline-brand bg-surface-brandSubtle":"border-outline-subtle"),children:[S.url?s.jsx("img",{src:S.url,alt:"",className:"h-[55px] w-11 rounded object-cover"}):s.jsx("div",{className:"h-[55px] w-11 rounded bg-surface-sunken"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"truncate text-[12.5px] font-medium",children:S.name}),s.jsx("div",{className:B("text-[11px]",S.url?"text-text-success":"text-text-tertiary"),children:S.url?"Assigned":"Empty"})]})]},S.name))}),s.jsxs("div",{className:"border-t border-outline-subtle bg-surface-subtle p-3",children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:"Caption"}),s.jsx("textarea",{className:B(cr,"mt-1 w-full"),rows:3,value:N.caption,onChange:S=>{const O=S.target.value;y(R=>R.map((I,$)=>$===m?{...I,caption:O}:I))}})]})]})]}
909),s.jsxs("footer",{className:"flex min-h-[60px] shrink-0 flex-wrap items-center justify-end gap-2 border-t border-outline-subtle px-4 py-3 md:h-[60px] md:px-5 md:py-0",children:[s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",disabled:!C.length,onClick:()=>C[0]&&window.open(C[0].url,"_blank","noopener,noreferrer"),children:"Download set"}),s.jsxs(W,{intent:"brand",variant:"solid",size:"sm",disabled:!C.length,onClick:()=>r(C),children:["Attach ",C.length," slides to asset"]})]})]})})}function QHe({pillarId:e}){const[t,n]=it("tab","workbench"),r=t==="performance"?"performance":"workbench",[a,i]=p.useState(null),[o,l]=p.useState(null),[c,u]=p.useState(null),[d,h]=p.useState(0),f=p.useCallback(()=>h(L=>L+1),[]),[m,x]=p.useState(null),[g,y]=p.useState(!1),[b,v]=p.useState("linkedin"),[w,_]=p.useState(""),[k,j]=p.useState(!1),[N,E]=p.useState(!1),[A,C]=p.useState(!1),[T,S]=p.useState(!1);p.useEffect(()=>{let L=!0;return At.getPillar(e).then(q=>L&&i(q.pillar)).catch(q=>L&&l(q.message)),()=>{L=!1}},[e,d]);const O=async L=>{if(a){i({...a,...L});try{await At.updatePillar(e,L)}catch{f()}}},R=async(L,q)=>{i(me=>{var ee;return me&&{...me,assets:(ee=me.assets)==null?void 0:ee.map(ne=>ne.id===L.id?{...ne,...q}:ne)}});try{await At.updateAsset(L.id,q)}catch{f()}},I=async()=>{y(!0),u(null);try{await At.createAsset({pillar_id:e,channel:b,scheduled_date:w||null,status:w?"scheduled":"draft"}),_(""),f()}catch(L){u(L.message)}finally{y(!1)}},$=async L=>{i(q=>{var me;return q&&{...q,assets:(me=q.assets)==null?void 0:me.filter(ee=>ee.id!==L.id)}});try{await At.deleteAsset(L.id)}catch{f()}},P=async()=>{j(!0),u(null);try{i((await At.atomisePillar(e)).pillar)}catch(L){u(L.message)}finally{j(!1)}};if(o)return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Content",to:"/content"},{label:"Pillar"}]}),s.jsx(Xc,{children:s.jsx(Jc,{children:s.jsx(Zi,{msg:o})})})]});if(!a)return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Content",to:"/content"},{label:"Pillar"}]}),s.jsx(Xc,{children:s.jsx(Jc,{children:s.jsx(Ro,{})})})]});const F=a.assets??[],Z=F.find(L=>L.id===m)??F[0]??null,D=F.filter(L=>L.status==="published").length,H=F.some(L=>EHe.includes(L.channel)),Y=F.find(L=>L.channel==="youtube_long"),M=F.find(L=>L.channel==="blog"),z=F.find(L=>L.channel==="email"),G=[{done:!!(a.video_url||Y!=null&&Y.url||(Y==null?void 0:Y.status)==="published"),label:"Record the flagship video"},{done:!!(a.blog_url||M!=null&&M.url||(M==null?void 0:M.status)==="published"),label:"Write the blog"},{done:!!(z!=null&&z.copy||(z==null?void 0:z.status)==="published"||z!=null&&z.url),label:"Write the email"},{done:H,label:"Atomise into daily social"},{done:F.some(L=>L.status==="published"),label:"Engage as it lands"}],te=cf.map(L=>({ch:L,rows:F.filter(q=>q.channel===L)})).filter(L=>L.rows.length>0),re=[{key:"workbench",label:"Workbench",active:r==="workbench",onClick:()=>n("workbench")},{key:"performance",label:"Performance",active:r==="performance",onClick:()=>n("performance")}];return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Content",to:"/content"},{label:a.title}],actions:s.jsxs("div",{className:"flex items-center gap-2",children:[!H&&s.jsxs(W,{intent:"brand",variant:"outline",size:"sm",onClick:P,disabled:k,children:[k?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):s.jsx(Ht,{className:"h-4 w-4"}),s.jsx("span",{className:"hidden sm:inline",children:"Atomise"})]}),s.jsx(W,{intent:"brand",variant:"solid",size:"sm",onClick:()=>{const L=F.find(q=>q.status!=="published");L&&(x(L.id),R(L,{status:"published",review_state:"approved"}))},children:"Publish next"})]})}),s.jsxs(Xc,{children:[s.jsx(As,{items:re}),s.jsx(Jc,{children:r==="performance"?s.jsx(HHe,{pillarId:e,pillar:a}):s.jsxs("div",{className:"relative flex flex-col gap-4 xl:flex-row xl:items-start",children:[s.jsx(V,{className:"xl:w-[308px] xl:shrink-0",children:s.jsxs("div",{className:"p-5",children:[s.jsx("input",{className:B(cr,"w-full border-0 px-0 text-[19px] font-semibold tracking-[-0.02em] shadow-none focus-visible:shadow-none"),value:a.title,onChange:L=>i({...a,title:L.target.value}),onBlur:L=>O({title:L.target.value})}),s.jsxs("dl",{className:"mt-4 space-y-2",children:[s.jsx(uy,{label:"Status",children:s.jsx("select",{className:B(cr,"w-full text-xs"),value:a.status,onChange:L=>O({status:L.target.value}),children:ip.map(L=>s.jsx("option",{value:L,children:qp[L]},L))})}),s.jsx(uy,{label:"Week",children:s.jsx("input",{type:"date",className:B(cr,"w-full text-xs"),value:a.target_publish_week??"",onChange:L=>O({target_publish_week:L.target.value||null})})}),s.jsx(uy,{label:"Video",children:s.jsx("input",{className:B(cr,"w-full text-xs"),value:a.video_url??"",placeholder:"URL",onChange:L=>i({...a,video_url:L.target.value}),onBlur:L=>O({video_url:L.target.value||null})})}),s.jsx(uy,{label:"Blog",children:s.jsx("input",{className:B(cr,"w-full text-xs"),value:a.blog_url??"",placeholder:"URL",onChange:L=>i({...a,blog_url:L.target.value}),onBlur:L=>O({blog_url:L.target.value||null})})})]}),s.jsxs("div",{className:"mt-6",children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:"Production order"}),s.jsx("ol",{className:"mt-3",children:G.map((L,q)=>s.jsxs("li",{className:"flex gap-3",children:[s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:B("flex h-4 w-4 items-center justify-center rounded-full ring-2",L.done?"bg-intent-success ring-success-700 text-text-inverse":"bg-surface ring-outline-subtle"),children:L.done?s.jsx(Xt,{className:"h-3 w-3"}):s.jsx(D2,{className:"h-2.5 w-2.5 text-transparent"})}),q<G.length-1&&s.jsx("span",{className:B("h-[26px] w-0.5",L.done?"bg-success-200":"bg-outline-subtle")})]}),s.jsx("span",{className:B("pb-3 text-[13px]",L.done?"text-text-secondary line-through":"text-text-primary"),children:L.label})]},L.label))})]}),s.jsx("div",{className:"mt-4",children:s.jsx(tVe,{pillar:a,setPillar:i,patch:O})})]})}),s.jsxs(V,{className:"min-w-0 flex-1 overflow-hidden",children:[s.jsxs("div",{className:"hidden items-center border-b border-outline-subtle bg-surface-subtle px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary md:grid md:px-6",style:{gridTemplateColumns:"130px 1fr 92px 104px 74px"},children:[s.jsx("span",{children:"Channel"}),s.jsx("span",{children:"Angle / copy"}),s.jsx("span",{children:"Date"}),s.jsx("span",{children:"Status"}),s.jsx("span",{})]}),s.jsxs("div",{children:[c&&s.jsx("div",{className:"px-4 pt-3",children:s.jsx(Zi,{msg:c}
909)}),te.map(L=>s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between bg-surface-sunken px-6 py-1.5",children:[s.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:Zn[L.ch]}),s.jsxs("span",{className:"text-[11px] tabular-nums text-text-tertiary",children:[L.rows.filter(q=>q.status==="published").length,"/",L.rows.length]})]}),L.rows.map(q=>s.jsxs("button",{type:"button",onClick:()=>{x(q.id),E(!1)},className:B("w-full border-b border-outline-subtle px-4 py-2.5 text-left hover:bg-surface-subtle md:grid md:items-center md:px-6",(Z==null?void 0:Z.id)===q.id&&"bg-surface-subtle"),style:{gridTemplateColumns:"130px 1fr 92px 104px 74px"},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 md:contents",children:[s.jsx("span",{className:"text-[12.5px] font-medium text-text-primary",children:Zn[q.channel]}),s.jsx(dl,{className:"md:hidden",tone:Ev(q.status,q.scheduled_date),children:q.status})]}),s.jsxs("span",{className:"mt-0.5 block truncate text-[12.5px] text-text-secondary md:mt-0",children:[q.format??q.angle??(q.copy?q.copy.slice(0,60):"â"),s.jsxs("span",{className:"md:hidden",children:[" · ",Bs(q.scheduled_date)]})]}),s.jsx("span",{className:"hidden font-mono text-[12px] text-text-secondary md:block",children:Bs(q.scheduled_date)}),s.jsx("span",{className:"hidden md:block",children:s.jsx(dl,{tone:Ev(q.status,q.scheduled_date),children:q.status})}),s.jsxs("span",{className:"mt-1 flex justify-end gap-1 md:mt-0",children:[q.cta_url&&s.jsx(W3,{text:q.cta_url}),q.url&&s.jsx("a",{href:q.url,target:"_blank",rel:"noreferrer",onClick:me=>me.stopPropagation(),className:"text-text-brand",children:s.jsx(Qt,{className:"h-3.5 w-3.5"})})]})]},q.id))]},L.ch)),s.jsxs("div",{className:"flex flex-col gap-2 px-4 py-3 sm:flex-row sm:items-center md:px-6",children:[s.jsx("select",{className:B(cr,"text-xs"),value:b,onChange:L=>v(L.target.value),children:cf.map(L=>s.jsx("option",{value:L,children:Zn[L]},L))}),s.jsx("input",{type:"date",className:B(cr,"text-xs"),value:w,onChange:L=>_(L.target.value)}),s.jsxs(W,{intent:"brand",variant:"outline",size:"sm",onClick:I,disabled:g,children:[g?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):s.jsx(In,{className:"h-4 w-4"}),"Add asset"]}),s.jsxs("span",{className:"ml-auto text-xs text-text-tertiary",children:[D,"/",F.length," live"]})]})]})]}),s.jsx(V,{className:"xl:w-[364px] xl:shrink-0",children:Z?s.jsx(eVe,{asset:Z,pillar:a,onPatch:L=>R(Z,L),onDelete:()=>$(Z),onOpenComposer:()=>E(!0),onOpenGenerate:()=>C(!0),onOpenStudio:()=>S(!0)}):s.jsx("div",{className:"p-6 text-sm text-text-tertiary",children:"Select a derivative."})}),N&&Z&&s.jsx(GHe,{asset:Z,pillar:a,onClose:()=>E(!1),onUse:L=>{R(Z,{copy:L,status:"draft"}),E(!1)}})]})})]}),A&&Z&&s.jsx(YHe,{asset:Z,pillar:a,onClose:()=>C(!1),onSave:L=>{R(Z,{copy:L}),C(!1)}}),T&&Z&&s.jsx(JHe,{asset:Z,pillar:a,onClose:()=>S(!1),onAttach:L=>{R(Z,{media:L}),S(!1)}})]})}function uy({label:e,children:t}){return s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("dt",{className:"shrink-0 text-[12.5px] text-text-secondary",children:e}),s.jsx("dd",{className:"min-w-0 flex-1 text-right text-[12.5px] font-medium",children:t})]})}function eVe({asset:e,pillar:t,onPatch:n,onDelete:r,onOpenComposer:a,onOpenGenerate:i,onOpenStudio:o}){const[l,c]=p.useState(e.copy??""),[u,d]=p.useState(null);p.useEffect(()=>{c(e.copy??"")},[e.id,e.copy]),p.useEffect(()=>{if(e.channel!=="email"||e.url){d(null);return}let g=!0;return At.suggestedLink(e.id).then(y=>{g&&d(y.suggestion)}).catch(()=>{g&&d(null)}),()=>{g=!1}},[e.id,e.channel,e.url]);const h=Cv[e.channel],f=h>0&&l.length>h,x=p.useMemo(()=>g6(),[]).find(g=>g.title.toLowerCase().includes(t.title.slice(0,18).toLowerCase())||t.title.toLowerCase().includes(g.title.slice(0,18).toLowerCase()));return s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[s.jsx(wo,{caption:Zn[e.channel],children:"Derivative"}),s.jsxs("div",{className:"min-h-0 flex-1 space-y-3 overflow-auto p-4",children:[s.jsxs("label",{className:"block text-xs",children:[s.jsx("span",{className:"text-text-secondary",children:"Angle"}),s.jsx("input",{className:B(cr,"mt-1 w-full"),value:e.format??e.angle??"",onBlur:g=>n({format:g.target.value||null}),onChange:()=>{},defaultValue:e.format??e.angle??""},`fmt-${e.id}`)]}),s.jsxs("label",{className:"block text-xs",children:[s.jsxs("span",{className:"flex items-center justify-between text-text-secondary",children:["Copy",s.jsxs("span",{className:B("font-mono",f?"text-text-error":"text-text-tertiary"),children:[l.length,h?`/${h}`:""]})]}),s.jsx("textarea",{className:B(cr,"mt-1 w-full"),rows:8,value:l,onCh
909ange:g=>c(g.target.value),onBlur:()=>{l!==(e.copy??"")&&n({copy:l||null})}})]}),s.jsxs("label",{className:"block text-xs",children:[s.jsx("span",{className:"text-text-secondary",children:"CTA link"}),s.jsxs("div",{className:"mt-1 flex items-center gap-1",children:[s.jsx("input",{className:B(cr,"w-full"),defaultValue:e.cta_url??"",onBlur:g=>n({cta_url:g.target.value||null})},`cta-${e.id}`),e.cta_url&&s.jsx(W3,{text:e.cta_url})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[s.jsxs("label",{className:"text-xs",children:[s.jsx("span",{className:"text-text-secondary",children:"Date"}),s.jsx("input",{type:"date",className:B(cr,"mt-1 w-full"),value:e.scheduled_date??"",onChange:g=>n({scheduled_date:g.target.value||null,status:g.target.value?"scheduled":e.status})})]}),s.jsxs("label",{className:"text-xs",children:[s.jsx("span",{className:"text-text-secondary",children:"Status"}),s.jsxs("select",{className:B(cr,"mt-1 w-full"),value:e.status,onChange:g=>n({status:g.target.value}),children:[s.jsx("option",{value:"draft",children:"Draft"}),s.jsx("option",{value:"scheduled",children:"Scheduled"}),s.jsx("option",{value:"published",children:"Published"})]})]})]}),e.channel==="blog"&&!e.url&&x&&s.jsxs(W,{intent:"brand",variant:"outline",size:"sm",className:"w-full",onClick:()=>n({url:`https://gadjet.ai/blog/${x.slug}`}),children:["Link published post · ",x.title]}),e.channel==="email"&&!e.url&&u&&s.jsxs(W,{intent:"brand",variant:"outline",size:"sm",className:"w-full",onClick:()=>n({url:u.url}),children:["Link this send · ",u.label]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(W,{intent:"brand",variant:"outline",size:"sm",onClick:a,children:"Refine"}),s.jsx(W,{intent:"brand",variant:"outline",size:"sm",onClick:i,children:"Generate"}),s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",onClick:o,children:"Studio"})]})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-outline-subtle bg-surface-subtle px-4 py-3",children:[s.jsx(W,{intent:"success",variant:"solid",size:"sm",onClick:()=>n({status:"published",review_state:"approved"}),children:"Mark published"}),e.copy&&s.jsxs(W,{intent:"neutral",variant:"outline",size:"sm",onClick:()=>navigator.clipboard.writeText(e.copy??""),children:[s.jsx(bi,{className:"h-3.5 w-3.5"})," Copy"]}),s.jsx("button",{type:"button",className:"ml-auto text-text-tertiary hover:text-text-error",onClick:r,"aria-label":"Delete",children:s.jsx(us,{className:"h-4 w-4"})})]})]})}function tVe({pillar:e,setPillar:t,patch:n}){var y;const[r,a]=p.useState([]),[i,o]=p.useState(((y=e.data_hook)==null?void 0:y.skill)??""),[l,c]=p.useState(()=>{var b;return((b=e.data_hook)==null?void 0:b.args)??{}}),[u,d]=p.useState(!1),[h,f]=p.useState(null);p.useEffect(()=>{let b=!0;return At.hookSources().then(v=>b&&a(v.sources)).catch(()=>{}),()=>{b=!1}},[]);const m=r.find(b=>b.skill===i),x=e.data_hook,g=async()=>{if(i){d(!0),f(null);try{const b=await At.resolveHook(e.id,{skill:i,args:l});t(b.pillar)}catch(b){f(b.message)}finally{d(!1)}}};return s.jsxs("div",{children:[x!=null&&x.captured_value?s.jsx(Iw,{value:x.captured_value,provenance:s.jsxs(s.Fragment,{children:[x.skill,x.captured_at?` · ${Bs(x.captured_at.slice(0,10))}`:""]}),action:s.jsx(W,{intent:"brand",variant:"ghost",size:"sm",onClick:g,disabled:u||!i,children:"Re-resolve"})}):s.jsx("div",{className:"text-xs text-text-tertiary",children:"No data hook pinned yet."}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsxs("select",{className:B(cr,"w-full text-xs"),value:i,onChange:b=>o(b.target.value),children:[s.jsx("option",{value:"",children:"â Market Map stat â"}),r.map(b=>s.jsx("option",{value:b.skill,children:b.label},b.skill))]}),m==null?void 0:m.args.map(b=>{const v=b.replace(/\?$/,"");return s.jsx("input",{className:B(cr,"w-full text-xs"),placeholder:v,value:l[v]??"",onChange:w=>c(_=>({..._,[v]:w.target.value}))},v)}),i&&s.jsxs(W,{intent:"brand",variant:"solid",size:"sm",onClick:g,disabled:u,children:[u?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):s.jsx(Ht,{className:"h-4 w-4"}),"Resolve"]}),h&&s.jsx("div",{className:"text-xs text-text-error",children:h}),s.jsx("input",{className:B(cr,"w-full text-xs"),placeholder:"Or pin a stat manually",defaultValue:(x==null?void 0:x.captured_value)??"",onBlur:b=>n({data_hook:{skill:(x==null?void 0:x.skill)??null,args:(x==null?void 0:x.args)??null,captured_at:(x==null?void 0:x.captured_at)??null,captured_value:b.target.value||null}})},(x==null?void 0:x.captured_value)??"empty")]})]})}function nVe(){const[e,t]=p.useState(null),[n,r]=p.useState(null),[a,i]=p.useState([]),[o,l]=
909p.useState(null),[c,u]=p.useState(""),[d,h]=p.useState(null),f=()=>{At.listReviewQueue().then(v=>{t(v.assets),r(w=>v.assets.find(_=>_.id===(w==null?void 0:w.id))??v.assets[0]??null)}).catch(v=>l(v.message))};p.useEffect(()=>{f()},[]),p.useEffect(()=>{if(!n){i([]);return}At.listComments(n.id).then(v=>i(v.comments)).catch(()=>i([]))},[n==null?void 0:n.id]);const m=a.filter(v=>!v.resolved).length,x=async()=>{n&&(m&&!window.confirm(`${m} open thread(s). Approve anyway?`)||(await At.updateAsset(n.id,{review_state:"approved",status:"scheduled"}),f()))},g=async()=>{n&&(await At.updateAsset(n.id,{review_state:"changes_requested",status:"draft"}),f())},y=async()=>{if(!n||!c.trim())return;await At.addComment(n.id,{body:c.trim(),range_start:(d==null?void 0:d.start)??null,range_end:(d==null?void 0:d.end)??null,quote:(d==null?void 0:d.quote)??null}),u(""),h(null);const v=await At.listComments(n.id);i(v.comments)},b=()=>{const v=window.getSelection();if(!v||v.isCollapsed||!(n!=null&&n.copy))return;const w=v.toString(),_=n.copy.indexOf(w);_>=0&&h({start:_,end:_+w.length,quote:w})};return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Content",to:"/content"},{label:"Review"}],actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",className:"hidden sm:inline-flex",onClick:()=>void g(),disabled:!n,children:"Request changes"}),s.jsx(W,{intent:"success",variant:"solid",size:"sm",onClick:()=>void x(),disabled:!n,children:"Approve"})]})}),s.jsx(Xc,{children:s.jsxs(Jc,{children:[o&&s.jsx(Zi,{msg:o}),!e&&!o&&s.jsx(Ro,{}),e&&s.jsxs("div",{className:"flex flex-col gap-4 xl:flex-row xl:items-start",children:[s.jsx(V,{className:"xl:w-[280px] xl:shrink-0",children:s.jsxs("div",{className:"p-3",children:[e.length===0&&s.jsx("div",{className:"p-3 text-sm text-text-tertiary",children:"Queue is clear."}),e.map(v=>{var w;return s.jsxs("button",{type:"button",onClick:()=>r(v),className:B("mb-2 w-full rounded-lg border p-3 text-left last:mb-0",(n==null?void 0:n.id)===v.id?"border-brand-300 bg-surface-subtle":"border-outline-subtle bg-surface"),children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[12px] text-text-secondary",children:Zn[v.channel]}),s.jsx(dl,{tone:v.review_state==="approved"?"approved":v.review_state==="changes_requested"?"overdue":v.review_state==="in_review"?"review":"draft",children:v.review_state==="in_review"?"In review":((w=v.review_state)==null?void 0:w.replace("_"," "))??"Draft"})]}),s.jsx("div",{className:"mt-1 text-[13px] font-medium text-text-primary",children:v.pillar_title??v.format}),s.jsx("div",{className:"mt-0.5 text-[11px] text-text-tertiary",children:Bs(v.scheduled_date)})]},v.id)})]})}),s.jsx(V,{className:"min-w-0 flex-1",children:n?s.jsxs("article",{className:"px-4 py-5 sm:px-8 sm:py-7",children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:Zn[n.channel]}),s.jsx("h2",{className:"mt-1 text-lg font-semibold",children:n.pillar_title}),s.jsx("div",{className:"mt-4 whitespace-pre-wrap text-[15.5px] leading-[26px] text-text-body",onMouseUp:b,children:rVe(n.copy??"No copy yet.",a)}),s.jsxs("div",{className:"mt-6 flex flex-wrap items-center gap-x-4 gap-y-1 border-t border-outline-subtle pt-3 text-xs text-text-secondary",children:[s.jsxs("span",{className:"font-mono",children:[(n.copy??"").length,Cv[n.channel]?`/${Cv[n.channel]}`:""]}),s.jsx("span",{children:Bs(n.scheduled_date)}),s.jsxs("span",{children:[m," open comments"]})]})]}):s.jsx("div",{className:"p-6 text-sm text-text-tertiary",children:"Nothing to review."})}),s.jsxs(V,{className:"xl:w-[360px] xl:shrink-0",children:[s.jsxs("div",{className:"space-y-3 p-4",children:[a.map(v=>s.jsxs("div",{className:"rounded-lg border border-outline-subtle p-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"flex h-[22px] w-[22px] items-center justify-center rounded-full bg-surface-brandSubtle text-[10px] font-semibold text-text-brand",children:(v.author_name??"?").slice(0,2).toUpperCase()}),s.jsx("span",{className:"text-[13px] font-medium",children:v.author_name??"Someone"}),s.jsx("span",{className:"text-[11px] text-text-tertiary",children:Bs(v.created_at.slice(0,10))}),s.jsx(dl,{tone:v.resolved?"approved":"warning",className:"ml-auto",children:v.resolved?"Resolved":"Open"})]}),v.quote&&s.jsx("div",{className:"mt-2 border-l-2 border-warning-400 bg-surface-warningSubtle px-2 py-1 text-xs",children:v.quote}),s.jsx("p",{className:"mt-2 text-[13px] text-text-body",children:v.body}),!v.resolved&&n&&s.jsx("button",{type:"button",className:"mt-2 text-xs text-text-brand",onClick:()=>
909At.resolveComment(n.id,v.id).then(()=>At.listComments(n.id).then(w=>i(w.comments))),children:"Resolve"})]},v.id)),a.length===0&&s.jsx("div",{className:"text-sm text-text-tertiary",children:"No comments yet. Select copy to quote a range."})]}),s.jsxs("div",{className:"border-t border-outline-subtle bg-surface-subtle p-3",children:[d&&s.jsxs("div",{className:"mb-2 truncate rounded bg-surface-warningSubtle px-2 py-1 text-[11px] text-text-warning",children:["â",d.quote,"â"]}),s.jsx("textarea",{className:B(cr,"w-full"),rows:3,placeholder:"Comment on the copyâ¦",value:c,onChange:v=>u(v.target.value)}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[s.jsx(W,{intent:"brand",variant:"solid",size:"sm",onClick:()=>void y(),children:"Comment"}),s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",className:"sm:hidden",onClick:()=>void g(),disabled:!n,children:"Request changes"})]})]})]})]})]})})]})}function rVe(e,t){let n=[e];return t.forEach(r=>{if(r.range_start==null||r.range_end==null)return;const a=[];n.forEach(i=>{if(typeof i!="string"){a.push(i);return}const o=e.slice(r.range_start,r.range_end),l=i.indexOf(o);if(l<0){a.push(i);return}a.push(i.slice(0,l)),a.push(s.jsx("mark",{className:B("rounded-sm",r.resolved?"bg-surface-brandSubtle underline decoration-brand-400":"bg-surface-warningSubtle underline decoration-warning-400"),children:o},r.id)),a.push(i.slice(l+o.length))}),n=a}),n}function sVe(){const e=Rt(),[t,n]=p.useState(null),[r,a]=p.useState(null),[i,o]=p.useState(null);p.useEffect(()=>{let c=!0;return At.repurpose().then(u=>c&&n(u.repurpose)).catch(u=>c&&a(u.message)),()=>{c=!1}},[]);const l=async c=>{var u;o(c);try{const d=await At.draftRepurpose(c);(u=d.asset)!=null&&u.pillar_id&&e(`/content/pillars/${d.asset.pillar_id}`)}catch(d){a(d.message)}finally{o(null)}};return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Content",to:"/content"},{label:"Repurpose"}]}),s.jsx(Xc,{children:s.jsxs(Jc,{children:[r&&s.jsx(Zi,{msg:r}),!t&&!r&&s.jsx(Ro,{}),t&&s.jsxs(s.Fragment,{children:[s.jsx(Ow,{cells:[{label:"Re-cut candidates",value:t.recuts.length,hint:"Winners with a silent channel"},{label:"Evergreen still converting",value:t.evergreen.length,hint:"Older than 90d, clicks not falling"},{label:"Runway if accepted",value:t.runway_if_accepted,hint:"Adds draft assets in review",tone:"success"}]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsx(wo,{children:"Re-cut the winners"}),s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("div",{className:"min-w-[860px]",children:[s.jsxs("div",{className:"grid border-b border-outline-subtle bg-surface-subtle px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",style:{gridTemplateColumns:"220px 190px 180px 1fr 110px 108px"},children:[s.jsx("span",{children:"Original"}),s.jsx("span",{children:"How it did"}),s.jsx("span",{children:"Target"}),s.jsx("span",{children:"Why"}),s.jsx("span",{children:"Expected"}),s.jsx("span",{})]}),t.recuts.length===0&&s.jsx("div",{className:"px-4 py-6 text-sm text-text-tertiary",children:"No recuts yet â need email or blog winners."}),t.recuts.map(c=>s.jsxs("div",{className:"grid items-center border-b border-outline-subtle px-4 py-2.5 text-[13px]",style:{gridTemplateColumns:"220px 190px 180px 1fr 110px 108px"},children:[s.jsx("span",{className:"truncate font-medium",children:c.title}),s.jsx("span",{className:"text-text-secondary",children:c.how}),s.jsx("span",{className:"font-medium text-text-brand",children:Zn[c.target_channel]??c.target_channel}),s.jsx("span",{className:"text-text-secondary",children:c.why}),s.jsx("span",{className:"tabular-nums",children:c.expected_reach??"â"}),s.jsx(W,{intent:"brand",variant:"outline",size:"sm",className:"bg-surface-brandSubtle",disabled:i===c.id,onClick:()=>void l(c.id),children:"Draft it"})]},c.id))]})})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsx(wo,{children:"Evergreen still converting"}),s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("div",{className:"min-w-[720px]",children:[s.jsxs("div",{className:"grid border-b border-outline-subtle bg-surface-subtle px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",style:{gridTemplateColumns:"280px 110px 110px 1fr 108px"},children:[s.jsx("span",{children:"Post"}),s.jsx("span",{children:"Age"}),s.jsx("span",{children:"Clicks 30d"}),s.jsx("span",{children:"Evidence"}),s.jsx("span",{})]}),t.evergreen.length===0&&s.jsx("div",{className:"px-4 py-6 text-sm text-text-tertiary",children:"No evergreen candidates yet."}),t.evergreen.map(c=>s.jsxs("div",{className:"grid items-center border-b border-outline-subtle px-4 py-2.5 text-[13px]",style:{gridTemplateColumns:"280px 110px 110px 1fr 108px"},children:[s.jsx("span",{className:"truncate font-medium",children:c.title}),s.jsx("span",{className:"text-text-secondary",children:c.age}),s.jsx("span",{className:"tabular-nums",children:c.clicks_30d??"â"}),s.jsx("span",{className:"font-medium text-text-success",children:c.evidence}),s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",disabled:i===c.id,onClick:()=>void l(c.id),children:c.verb??"Resurface"})]},c.id))]})})]}),t.recuts.length>0&&s.jsx("div",{className:"flex justify-end",children:s.jsx(W,{intent:"brand",variant:"solid",size:"sm",onClick:async()=>{for(const c of t.recuts)await At.draftRepurpose(c.id);e("/content/review")},children:"Draft everything into review"})})]})]})})]})}function aVe(){var m,x;const e=Rt(),[t,n]=p.useState(null),[r,a]=p.useState(null),[i,o]=p.useState(null),[l,c]=p.useState(!1),u=()=>{At.filmQueue().then(g=>{n(g.items),a(y=>g.items.find(b=>b.skill_name===(y==null?void 0:y.skill_name))??g.items[0]??null)}
909).catch(g=>o(g.message))};p.useEffect(()=>{u()},[]);const d=async()=>{if(r){c(!0);try{const g=await At.generateFilmScript(r.skill_name);a(g.item),n(y=>(y==null?void 0:y.map(b=>b.skill_name===g.item.skill_name?g.item:b))??y)}catch(g){o(g.message)}finally{c(!1)}}},h=(t==null?void 0:t.filter(g=>g.state==="filmed").length)??0,f=(t==null?void 0:t.length)??0;return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Content",to:"/content"},{label:"Film queue"}],actions:s.jsxs("span",{className:"text-sm text-text-secondary",children:[h," of ",f," filmed"]})}),s.jsx(Xc,{children:s.jsxs(Jc,{children:[i&&s.jsx(Zi,{msg:i}),s.jsxs("p",{className:"mb-3 text-[13px] leading-relaxed text-text-secondary",children:["For a 30â60s Takealot clip on the curated Demo Store, use"," ",s.jsx("span",{className:"font-medium text-text-primary",children:"Enter demo view"})," ","in the account menu (bottom of the left nav). Eight-hour seller POV; no real customer data. Exit the same place when you are done."]}),!t&&!i&&s.jsx(Ro,{}),t&&s.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start",children:[s.jsx(V,{className:"min-w-0 flex-1 overflow-hidden",children:s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("div",{className:"min-w-[640px]",children:[s.jsxs("div",{className:"grid border-b border-outline-subtle bg-surface-subtle px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary md:px-6",style:{gridTemplateColumns:"200px 1fr 96px 78px 104px"},children:[s.jsx("span",{children:"Skill"}),s.jsx("span",{children:"Description"}),s.jsx("span",{children:"Script"}),s.jsx("span",{children:"Shots"}),s.jsx("span",{children:"State"})]}),t.map(g=>{var y;return s.jsxs("button",{type:"button",onClick:()=>a(g),className:B("grid w-full items-center border-b border-outline-subtle px-4 py-2.5 text-left hover:bg-surface-subtle md:px-6",(r==null?void 0:r.skill_name)===g.skill_name&&"bg-surface-subtle"),style:{gridTemplateColumns:"200px 1fr 96px 78px 104px"},children:[s.jsxs("span",{className:"truncate font-mono text-[13px] text-text-brand",children:["/",g.skill_name]}),s.jsx("span",{className:"truncate text-[13px] text-text-secondary",children:g.description}),s.jsx("span",{className:"text-[12px] text-text-secondary",children:g.script?"Yes":"â"}),s.jsx("span",{className:"tabular-nums",children:((y=g.shots)==null?void 0:y.length)??0}),s.jsx(dl,{tone:g.state==="filmed"?"live":g.state==="scripted"?"scheduled":g.state==="drafting"?"warning":"draft",children:g.state})]},g.skill_name)})]})})}),s.jsx(V,{className:"lg:w-[400px] lg:shrink-0 xl:w-[440px]",children:r?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"p-4 md:p-5",children:[s.jsxs("div",{className:"font-mono text-sm font-medium text-text-brand",children:["/",r.skill_name]}),s.jsx("h2",{className:"mt-1 text-[18px] font-semibold text-text-primary",children:r.title??r.skill_name}),s.jsxs("p",{className:"mt-1 text-[13px] text-text-secondary",children:[((m=r.shots)==null?void 0:m.length)??0," shots",r.est_duration?` · ${r.est_duration}`:""]}),s.jsxs("div",{className:"mt-4 space-y-2",children:[(r.shots??[]).map((g,y)=>s.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-outline-subtle p-2.5",children:[s.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded bg-surface-sunken font-mono text-[11px]",children:y+1}),s.jsx("div",{className:"min-w-0 flex-1 text-[13px] text-text-primary",children:g.description}),s.jsx("span",{className:"font-mono text-[11px] text-text-tertiary",children:g.duration})]},y)),!((x=r.shots)!=null&&x.length)&&s.jsx("p",{className:"text-sm text-text-tertiary",children:"No shot list yet. Generate a script."})]}),r.script&&s.jsx("pre",{className:"mt-4 whitespace-pre-wrap rounded-lg bg-surface-subtle p-3 text-[12.5px] leading-relaxed text-text-body",children:r.script})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 border-t border-outline-subtle bg-surface-subtle px-4 py-3",children:[s.jsx(W,{intent:"success",variant:"solid",size:"sm",onClick:()=>At.updateFilmScript(r.skill_name,{state:"filmed"}).then(u),children:"Mark filmed"}),s.jsx(W,{intent:"brand",variant:"outline",size:"sm",onClick:()=>void d(),disabled:l,children:l?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):"Regenerate script"}),s.jsx(W,{intent:"neutral",variant:"ghost",size:"sm",onClick:async()=>{const g=await At.createIdea({title:`Academy: ${r.title??r.skill_name}`,source_tag:"capability-menu"}),y=await At.promoteIdea(g.idea.id,{scaffold:"light"});e(`/content/pillars/${y.pillar.id}`)},children:"Promote to pillar"})]})]}):s.jsx("div",{className:"p-6 text-sm text-text-tertiary",children:"Queue is clear."})})]})]})})]})}function iVe(){const e=Rt(),{week:t}=jn(),n=t&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:Br(Zo(new Date)),[r,a]=p.useState(null),[i,o]=p.useState(null),[l,c]=p.useState(!1),u=()=>{At.getDigest(n).then(m=>a(m.digest)).catch(m=>o(m.message))};p.useEffect(()=>{u()},[n]);const d=Br(Gl(new Date(`${n}T00:00:00Z`),-7)),h=Br(Gl(new Date(`${n}T00:00:00Z`),7)),f=Br(Gl(new Date(`${n}T00:00:00Z`),6));return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Content",to:"/content"},{label:"Monday digest"}],actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",className:"hidden sm:inline-flex",onClick:()=>window.print(),children:"PDF"}),s.jsx(W,{intent:"brand",variant:"solid",size:"sm",disabled:l,onClick:async()=>{c(!0);try{await At.emailDigest(n)}catch(m){o(m.message)}finally{c(!1)}},children:"Email to team"})]})}),s.jsx(Xc,{children:s.jsxs(Jc,{children:[i&&s.jsx(Zi,{msg:i}),!r&&!i&&s.jsx(Ro,{}),r&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-center justify-between text-xs text-text-secondary print:hidden",children:[s.jsx("button",{type:"button",onClick:()=>e(`/content/digest/${d}`),children:"â previous week"}),s.jsx("button",{type:"button",onClick:()=>e(`/content/digest/${h}`),children:"next week â"})]}),s.jsx(V,{children:s.jsxs("article",{className:"px-4 py-6 sm:px-8 sm:py-8 md:px-12 md:py-10",children:[s.jsxs("div",{className:"font-mono text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:["Week of ",Bs(n)," â ",Bs(f)]}),s.jsx("h1",{className:"mt-2 text-[22px] font-semibold leading-tight tracking-[-0.02em] text-text-primary sm:text-[28px]",children:r.headline}),s.jsx("p",{className:"mt-3 text-[15px] leading-relaxed text-text-body",children:r.standfirst}),s.jsx("div",{className:"mt-8 grid grid-cols-1 border-y border-outline-subtle sm:grid-cols-3",children:[{k:"Reach",v:r.reach},{k:"Trials",v:r.trials},{k:"Runway",v:r.runway,warn:r.runway_short}].map((m,x)=>s.jsxs("div",{className:B("px-4 py-4",x<2&&"border-b border-outline-subtle sm:border-b-0 sm:border-r"),children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:m.k}),s.jsx("div",{className:B("mt-1 text-[30px] font-semibold tabular-nums",m.warn&&"text-text-warning"),children:m.v??"â"})]},m.k))}),s.jsx("h2",{className:"mt-8 text-[13px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:"What shipped"}),s.jsxs("div",{className:"mt-3 divide-y divide-outline-subtle",children:[r.shipped.length===0&&s.jsx("p",{className:"py-3 text-sm text-text-tertiary",children:"Nothing published this week."}),r.shipped.map((m,x)=>s.jsxs("div",{className:"flex items-center gap-3 py-2",children:[s.jsx("span",{className:"w-[78px] text-[13px] font-medium text-text-secondary",children:Zn[m.channel]??m.channel}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-[14px] text-text-primary",children:m.title}),s.jsx("span",{className:"text-[13px] tabular-nums text-text-secondary",children:m.metric??""})]},x))]}),s.jsx("h2",{className:"mt-8 text-[13px] font-semibold uppercase tracking-[0.08em] text-text-secondary",children:"Do this week"}),s.jsx("div",{className:"mt-3 space-y-3",children:r.actions.map(m=>s.jsxs("label",{className:"flex items-start gap-3",children:[s.jsx("input",{type:"checkbox",className:"mt-0.5 h-4 w-4",checked:m.done,onChange:async x=>{await At.updateDigestItem(m.id,{done:x.target.checked}),u()}}),s.jsxs("span",{children:[s.jsx("span",{className:"block text-[14.5px] text-text-primary",children:m.body}),m.reason&&s.jsx("span",{className:"block text-[13px] text-text-secondary",children:m.reason})]})]},m.id))})]})})]})]})})]})}function dh(){const e=Lt(),t=Ba(),{id:n}=jn(),r=Rt(),[a,i]=it("tab","pulse"),o=NHe.includes(a)?a:"pulse";if(e.kind==="ready"&&!Kc(e.me.nav_visibility,"content"))return s.jsx(Yt,{to:"/",replace:!0});if(t.pathname.startsWith("/content/review"))return s.jsx(nVe,{});if(t.pathname.startsWith("/content/repurpose"))return s.jsx(sVe,{});if(t.pathname.startsWith("/content/film-queue"))return s.jsx(aVe,{});if(t.pathname.startsWith("/content/digest"))return s.jsx(iVe,{});if(n)return s.jsx(QHe,{pillarId:Number(n)});const l=[{key:"pulse",label:"Today",active:o==="pulse",onClick:()=>i("pulse")},{key:"board",label:"Board",active:o==="board",onClick:()=>i("board")},{key:"calendar",label:"Calendar",active:o==="calendar",onClick:()=>i("calendar")},{key:"backlog",label:"Backlog",active:o==="backlog",onClick:()=>i("backlog")},{key:"performance",label:"Performance",active:o==="performance",onClick:()=>i("performance")}],c=Br(Zo(new Date));return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Content"}],actions:s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",className:"hidden lg:inline-flex",onClick:()=>r(`/content/digest/${c}`),children:"Monday digest"}),s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",onClick:()=>r("/content/review"),children:"Review"}),s.jsx(W,{intent:"neutral",variant:"ghost",size:"sm",className:"hidden lg:inline-flex",onClick:()=>r("/content/film-queue"),children:"Film queue"}),s.jsx(W,{intent:"brand",variant:"solid",size:"sm",onClick:()=>i("backlog"),children:"Promote idea"})]})}),s.jsxs(Xc,{children:[s.jsx(As,{items:l,actions:s.jsx("button",{type:"button",className:"hidden text-xs text-text-secondary hover:text-text-primary sm:inline",onClick:()=>r("/content/repurpose"),children:"Repurpose"})}),s.jsxs("div",{className:"flex flex-wrap gap-2 px-4 pt-3 lg:hidden",children:[s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",onClick:()=>r(`/content/digest/${c}`),children:"Monday digest"}),s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",onClick:()=>r("/content/film-queue"),children:"Film queue"}),s.jsx(W,{intent:"neutral",variant:"ghost",size:"sm",onClick:()=>r("/content/repurpose"),children:"Repurpose"})]}),s.jsxs(Jc,{children:[o==="pulse"&&s.jsx(IHe,{onOpenBacklog:()=>i("backlog")}),o==="board"&&s.jsx($He,{onOpenBacklog:()=>i("backlog")}
909),o==="calendar"&&s.jsx(LHe,{}),o==="backlog"&&s.jsx(BHe,{}),o==="performance"&&s.jsx(KHe,{})]})]})]})}function Eo(e){return new Date(`${e}T12:00:00Z`)}function oVe(e){return e.toISOString().slice(0,10)}function ea(e,t){const n=Eo(e);return n.setUTCDate(n.getUTCDate()+t),oVe(n)}function Bm(e){const t=Eo(e).getUTCDay(),n=t===0?6:t-1;return ea(e,-n)}function XS(e){const t=Eo(e).getUTCDay();return t===0||t===6}function lVe(e){const t=Eo(e).getUTCDay(),n=t===6?1:t===0?2:0;return n?ea(e,-n):e}function cVe(e){const t=ea(e,-1),n=Bm(e);return n<t?n:t}function aG(e){return!!e&&e.kind==="promo_deadline"&&e.shape==="span"}function dj(e,t){if(!aG(e)||!t)return!1;const n=e.start,r=e.end||e.date;return!!(n&&r&&n<=t&&t<=r)}function uVe(e,t,{hideWeekends:n=!1,gridAnchor:r=null}={}){if(aG(e))return dj(e,t)?!0:n&&Eo(t).getUTCDay()===5?dj(e,ea(t,1))||dj(e,ea(t,2)):!1;if(typeof r!="function")return!1;let a=r(e);return a&&n&&XS(a)&&(a=lVe(a)),a===t}function dVe(e){const t=ea(e,6),n=["January","February","March","April","May","June","July","August","September","October","November","December"],r=Eo(e),a=Eo(t),i=o=>n[o.getUTCMonth()].slice(0,3);return r.getUTCFullYear()!==a.getUTCFullYear()?`${r.getUTCDate()} ${i(r)} ${r.getUTCFullYear()} â ${a.getUTCDate()} ${i(a)} ${a.getUTCFullYear()}`:r.getUTCMonth()===a.getUTCMonth()?`${r.getUTCDate()}â${a.getUTCDate()} ${i(a)} ${a.getUTCFullYear()}`:`${r.getUTCDate()} ${i(r)} â ${a.getUTCDate()} ${i(a)} ${a.getUTCFullYear()}`}const hVe=/^(Apply by|Apply|Applied|Closed|Done|Action):\s*/i;function K3(e){return String(e||"").replace(hVe,"").trim()}function fVe({title:e,applied:t=!1,done:n=!1,closed:r=!1,needsAction:a=!1}={}){const i=K3(e);return a?`Action: ${i}`:n?`Done: ${i}`:t?`Applied: ${i}`:r?`Closed: ${i}`:`Apply: ${i}`}function mVe({applied:e=!1,done:t=!1,closed:n=!1,participation:r=null,categories:a=null}={}){const i=Number((r==null?void 0:r.submitted)||0),o=Number((r==null?void 0:r.action_required)||0);return o>0?e?`${o} need action · ${i} submitted`:`${o} need action`:t?e?`Done · ${i} submitted`:"Done":e?`${i}
909 submitted`:n?"Applications closed":(Array.isArray(a)?a.filter(Boolean).slice(0,2).join(", "):"")||"Applications open"}function Zx(e){var t;return((t=e==null?void 0:e.meta)==null?void 0:t.closed)===!0}function iG(e){var t,n,r;return((t=e==null?void 0:e.meta)==null?void 0:t.applied)===!0?!0:Number(((r=(n=e==null?void 0:e.meta)==null?void 0:n.participation)==null?void 0:r.submitted)||0)>0}function oG(e){var t;return((t=e==null?void 0:e.meta)==null?void 0:t.done)===!0}function lG(e){return iG(e)||oG(e)}function Pw(e){return(e==null?void 0:e.kind)==="promo_action"}function pVe(e){var t,n,r;return Number(((n=(t=e==null?void 0:e.meta)==null?void 0:t.participation)==null?void 0:n.action_required)||((r=e==null?void 0:e.meta)==null?void 0:r.action_required)||0)}function H3(e){var t;return e?Pw(e)||((t=e==null?void 0:e.meta)==null?void 0:t.needs_action)===!0?!0:pVe(e)>0:!1}function xVe(e,t){if(!e||e.kind!=="promo_deadline"||Zx(e)||!t)return!1;const n=e.start,r=e.end||e.date;return!!(n&&r&&n<=t&&r>=t)}function cG(e,t){return!e||e.kind!=="promo_deadline"||!t?!1:(e.end||e.date)===t}function gVe(e,{hideApplied:t=!1}={}){return!t||!e||Pw(e)||e.kind!=="promo_deadline"?!1:lG(e)}function hL(e,t,n){var c;const r=Number((c=e==null?void 0:e.meta)==null?void 0:c.promotion_id);if(!e||!Number.isFinite(r)||r!==Number(t))return e;const a={...e.meta||{},done:!!n};if(e.kind!=="promo_deadline")return{...e,meta:a};const i=iG({...e,meta:a}),o=Zx({...e,meta:a}),l=H3({...e,meta:a});return{...e,meta:a,title:fVe({title:e.title,applied:i,done:!!n,closed:o,needsAction:l}
909),subtitle:mVe({applied:i,done:!!n,closed:o,participation:a.participation,categories:a.categories}),actionRequired:l||!i&&!o&&!n}}function yVe({slug:e,title:t,promotionId:n,actionCount:r=0,skus:a=[]}={}){const i=K3(t),o=(Array.isArray(a)?a:[]).map(c=>typeof c=="string"?c:c==null?void 0:c.sku).filter(Boolean).slice(0,8).join(", "),l=Number(r)||0;return`Takealot requested action on ${e}'s "${i}" promotion (promotion_id ${n}). ${l} product${l===1?"":"s"} need action`+(o?` â e.g. ${o}`:"")+". Use list_seller_promotion_history to load rejection reasons. Help me fix what can be fixed (price, quantity, eligibility) or drop SKUs that were applied to the wrong promotion. Do not start a fresh apply sheet unless we decide to re-submit."}function bVe(e){const t=typeof e=="number"?e:Number(e);return!Number.isFinite(t)||t<=0||!Number.isInteger(t)?null:t}const uG=["January","February","March","April","May","June","July","August","September","October","November","December"],fL=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],V3=["promotions","shipments","payouts","tasks","system"],vVe=["promotions","shipments","payouts","tasks"],mL="calendar.hideWeekends",pL="calendar.hideApplied",xL="calendar.view",hj=4,uf={promotions:{label:"Promotions",short:"promos",icon:s.jsx(Gv,{className:"w-3.5 h-3.5"}),dot:Ve[1].dot,chip:`${Ve[1].tint} ${Ve[1].text} border ${Ve[1].border}`},shipments:{label:"Shipments",short:"shipments",icon:s.jsx(qi,{className:"w-3.5 h-3.5"}),dot:Ve[2].dot,chip:`${Ve[2].tint} ${Ve[2].text} border ${Ve[2].border}`},payouts:{label:"Payouts",short:"payouts",icon:s.jsx(P2,{className:"w-3.5 h-3.5"}),dot:Ve[3].dot,chip:`${Ve[3].tint} ${Ve[3].text} border ${Ve[3].border}`},tasks:{label:"Tasks",short:"tasks",icon:s.jsx(Uh,{className:"w-3.5 h-3.5"}),dot:Ve[4].dot,chip:`${Ve[4].tint} ${Ve[4].text} border ${Ve[4].border}`},system:{label:"System",short:"events",icon:s.jsx(Kh,{className:"w-3.5 h-3.5"}),dot:Ve[6].dot,chip:`${Ve[6].tint} ${Ve[6].text} border ${Ve[6].border}`}};function fj(){return new Intl.DateTimeFormat("en-CA",{timeZone:"Africa/Johannesburg",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date)}function wVe(e,t){if(e===t)return"Today";const n=Math.round((Eo(e).getTime()-Eo(t).getTime())/864e5);return n===1?"Tomorrow":n===-1?"Yesterday":n<0?Za(e):n<7?`In ${n} days`:n<14?"Next week":`In ${Math.round(n/7)} weeks`}function Za(e){if(!e)return"";const t=Eo(e);return`${["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][t.getUTCDay()]} ${t.getUTCDate()} ${uG[t.getUTCMonth()].slice(0,3)}`}function dG(e){var n;const t=((n=e.meta)==null?void 0:n.milestones)??null;return(t==null?void 0:t.expected)||(t==null?void 0:t.received)||e.end||e.start||e.date||null}function _Ve(e){return e.kind==="promo_running"||e.kind==="promo_deadline"?null:e.layer==="shipments"?dG(e):e.shape==="point"?e.date??null:e.start??null}function kVe(e,t){return e.layer==="shipments"?dG(e):e.kind==="promo_deadline"?e.date??e.end??null:e.shape==="point"?e.date??null:e.start&&e.start>=t?e.start:e.end??e.start??null}const jVe={dot:Ve[5].dot,chip:`${Ve[5].tint} ${Ve[5].text} border ${Ve[5].border}`,short:"due"};function JS(e){const t=[];for(const n of V3){const r=e.filter(i=>i.layer===n);if(!r.length)continue;const a=uf[n];if(n==="tasks"){const i=r.filter(l=>l.kind==="task_done"),o=r.filter(l=>l.kind!=="task_done");i.length&&t.push({key:"tasks_done",layer:n,items:i,dot:a.dot,chip:a.chip,short:"done"}),o.length&&t.push({key:"tasks_due",layer:n,items:o,...jVe})}else t.push({key:n,layer:n,items:r,dot:a.dot,chip:a.chip,short:a.short})}return t}function NVe(e,t){if(!t)return JS(e);const n=e.filter(o=>o.layer==="promotions").sort((o,l)=>(l.actionRequired?1:0)-(o.actionRequired?1:0)),r=e.filter(o=>o.layer!=="promotions"),a=[],i=uf.promotions;for(const o of n.slice(0,hj))a.push({key:o.id,layer:"promotions",items:[o],dot:i.dot,chip:i.chip,short:i.short});return n.length>hj&&a.push({key:"promos_more",layer:"promotions",items:n.slice(hj),dot:i.dot,chip:i.chip,short:"more"}),a.push(...JS(r)),a}function gL(e,t){try{const n=localStorage.getItem(e);return n===null?t:n==="1"}catch{return t}}function yL(e,t){try{localStorage.setItem(e,t?"1":"0")}catch{}}function SVe(e,{today:t,lookbackFrom:n,fetchTo:r}){const a=e.filter(u=>xVe(u,t)&&!lG(u)).sort((u,d)=>(u.date||u.end||"").localeCompare(d.date||d.end||"")),i=e.filter(u=>Pw(u)).sort((u,d)=>(u.title||"").localeCompare(d.title||"")),o=new Set([...a,...i].map(u=>u.id)),l=new Map;for(const u of e){const d=kVe(u,t);!d||d<n||d>r||o.has(u.id)&&d>=t||(l.has(d)||l.set(d,[]),l.get(d).push(u))}const c=[...l.entries()].sort((u,d)=>u[0]<d[0]?-1:1).map(([u,d])=>({date:u,groups:JS(d)}));return{openNow:a,needsAction:i,agenda:c}}function Tv({item:e,onToggle:t,className:n}){var i;if(e.kind!=="promo_deadline")return null;const r=bVe((i=e.meta)==null?void 0:i.promotion_id);if(!r)return null;const a=oG(e);return s.jsx("span",{className:B("inline-flex shrink-0 items-center justify-center min-h-11 min-w-11 md:min-
909h-0 md:min-w-0",n),onClick:o=>o.stopPropagation(),onPointerDown:o=>o.stopPropagation(),children:s.jsx(ei,{checked:a,onCheckedChange:o=>t(r,o===!0),"aria-label":a?"Mark promotion as not done":"Mark promotion as done",className:"h-3.5 w-3.5"})})}function CVe({lookbackFrom:e,fetchTo:t,openNow:n,needsAction:r,agenda:a,loading:i,today:o,onSelect:l,onToggleDone:c}){const u=a.length===0&&n.length===0&&r.length===0;return s.jsxs(V,{className:"p-3 h-fit",children:[s.jsx("div",{className:"text-body-sm font-semibold text-text-primary",children:"Upcoming"}),s.jsxs("div",{className:"text-body-xs text-text-tertiary mb-3",children:[Za(e)," â ",Za(t)]}),r.length>0&&s.jsxs("div",{className:"mb-4",children:[s.jsx("div",{className:"text-body-xs font-semibold text-text-error mb-1",children:"Needs action"}),s.jsx("ul",{className:"flex flex-col gap-0.5",children:r.map(d=>s.jsx("li",{className:"flex items-start gap-1",children:s.jsxs("button",{type:"button",onClick:()=>l(d.date||o,[d]),className:"min-w-0 flex-1 flex items-start gap-2 py-1 text-left hover:bg-surface-subtle/60 rounded px-1 -mx-1",children:[s.jsx("span",{className:B("mt-1 w-2 h-2 rounded-full shrink-0",uf.promotions.dot)}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"text-body-sm text-text-primary truncate",children:d.title}),s.jsx(yt,{className:"w-3.5 h-3.5 text-text-error shrink-0"})]}),d.subtitle&&s.jsx("span",{className:"text-body-xs text-text-tertiary truncate block",children:d.subtitle})]})]})},d.id))})]}),n.length>0&&s.jsxs("div",{className:"mb-4",children:[s.jsx("div",{className:"text-body-xs font-semibold text-text-primary mb-1",children:"Open to apply"}),s.jsx("ul",{className:"flex flex-col gap-0.5",children:n.map(d=>s.jsxs("li",{className:"flex items-start gap-1",children:[s.jsxs("button",{type:"button",onClick:()=>l(d.date||d.end||o,[d]),className:"min-w-0 flex-1 flex items-start gap-2 py-1 text-left hover:bg-surface-subtle/60 rounded px-1 -mx-1",children:[s.jsx("span",{className:B("mt-1 w-2 h-2 rounded-full shrink-0",uf.promotions.dot)}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"text-body-sm text-text-primary truncate",children:d.title}),d.actionRequired&&s.jsx(yt,{className:"w-3.5 h-3.5 text-text-error shrink-0"})]}),s.jsx("span",{className:"text-body-xs text-text-tertiary truncate block",children:cG(d,o)?"Expires today":`Closes ${Za(d.date||d.end||"")}`})]})]}),s.jsx(Tv,{item:d,onToggle:c})]},d.id))})]}),i&&u?s.jsx("div",{className:"text-body-sm text-text-tertiary py-6 text-center",children:"Loadingâ¦"}):u?s.jsx("div",{className:"text-body-sm text-text-tertiary py-6 text-center",children:"Nothing upcoming in this window."}):a.length===0?null:s.jsxs("div",{className:"relative flex flex-col gap-4 pl-5",children:[s.jsx("span",{className:"absolute left-[5px] top-2 bottom-2 w-px bg-outline-subtle","aria-hidden":!0}),a.map(({date:d,groups:h})=>s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:B("absolute -left-[19px] top-1 w-2.5 h-2.5 rounded-full ring-2 ring-surface",d===o?"bg-intent-brand":d<o?"bg-outline-subtle":"bg-outline-strong/40"),"aria-hidden":!0}),s.jsxs("div",{className:"flex items-baseline gap-2 mb-1",children:[s.jsx("span",{className:"text-body-xs font-semibold text-text-primary",children:wVe(d,o)}),d!==o&&s.jsx("span",{className:"text-body-xs text-text-tertiary",children:Za(d)})]}),s.jsx("ul",{className:"flex flex-col gap-0.5",children:h.map(f=>{const m=f.items.length===1?f.items[0]:null,x=f.items.some(y=>y.actionRequired),g=m?m.title:`${f.items.length} ${f.short}`;return s.jsxs("li",{className:"flex items-start gap-1",children:[s.jsxs("button",{type:"button",onClick:()=>l(d,f.items),className:"min-w-0 flex-1 flex items-start gap-2 py-1 text-left hover:bg-surface-subtle/60 rounded px-1 -mx-1",children:[s.jsx("span",{className:B("mt-1 w-2 h-2 rounded-full shrink-0",f.dot,(m==null?void 0:m.confidence)==="projected"&&"opacity-50 ring-1 ring-success-400")}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"text-body-sm text-text-primary truncate",children:g}),x&&s.jsx(yt,{className:"w-3.5 h-3.5 text-text-error shrink-0"})]}),(m==null?void 0:m.subtitle)&&s.jsx("span",{className:"text-body-xs text-text-tertiary truncate block",children:m.subtitle})]})]}),(m==null?void 0:m.kind)==="promo_deadline"&&s.jsx(Tv,{item:m,onToggle:c})]},f.key)})})]},d))]})]})}function EVe({selected:e,onClose:t,onOpenInChat:n,onOpenShipment:r,onOpenTasks:a,onToggleDone:i}
909){const[o,l]=p.useState(e);p.useEffect(()=>{e&&l(e)},[e]);const c=e??o;return s.jsx(Cr,{open:!!e,onOpenChange:u=>{u||t()},children:s.jsxs(mr,{side:"right",size:"md",children:[s.jsx(Er,{children:s.jsx(xr,{children:c?Za(c.day):""})}),s.jsx(pr,{className:"p-4 flex flex-col gap-3",children:c==null?void 0:c.items.map(u=>{const d=uf[u.layer],h=u.meta??{},f=typeof h.assumption=="string"?h.assumption:null,m=u.layer==="shipments"&&Number(h.shipment_id)?Number(h.shipment_id):null,x=h.participation,g=h.milestones,y=Array.isArray(h.action_skus)?h.action_skus:[],b=typeof h.portal_url=="string"?h.portal_url:null,v=Pw(u)||H3(u);return s.jsxs("div",{className:"rounded-md border border-outline-subtle p-3",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[s.jsx("span",{className:B("w-2 h-2 rounded-full",d.dot)}),s.jsx("span",{className:"text-body-xs text-text-tertiary",children:d.label}),u.confidence==="projected"&&s.jsx("span",{className:"text-body-xs text-text-success bg-success-500/10 rounded px-1",children:"forecast"}),u.kind==="promo_deadline"&&Zx(u)&&s.jsx("span",{className:"text-body-xs text-text-tertiary bg-surface-subtle rounded px-1",children:"closed"}),u.kind==="promo_deadline"&&s.jsxs("span",{className:"ml-auto inline-flex items-center gap-1.5 text-body-xs text-text-secondary",children:[s.jsx(Tv,{item:u,onToggle:i}),"Done"]}),u.actionRequired&&u.kind!=="promo_deadline"&&s.jsxs("span",{className:"ml-auto inline-flex items-center gap-1 text-body-xs text-text-error",children:[s.jsx(yt,{className:"w-3.5 h-3.5"})," Action"]}),u.actionRequired&&u.kind==="promo_deadline"&&s.jsxs("span",{className:"inline-flex items-center gap-1 text-body-xs text-text-error",children:[s.jsx(yt,{className:"w-3.5 h-3.5"})," Action"]})]}),m?s.jsx("button",{onClick:()=>r(m),className:"text-body-sm font-medium text-text-brand hover:underline text-left",children:u.title}):s.jsx("div",{className:"text-body-sm font-medium text-text-primary",children:u.title}),u.subtitle&&s.jsx("div",{className:"text-body-xs text-text-secondary mt-0.5",children:u.subtitle}),u.shape==="point"&&u.date&&s.jsx("div",{className:"text-body-xs text-text-tertiary mt-1",children:Za(u.date)}),u.shape==="span"&&u.start&&u.end&&s.jsx("div",{className:"text-body-xs text-text-tertiary mt-1",children:u.kind==="promo_deadline"?`Open ${Za(u.start)} â closes ${Za(u.end)}`:`${Za(u.start)} â ${Za(u.end)}`}),g&&s.jsxs("div",{className:"text-body-xs text-text-tertiary mt-1 flex flex-wrap gap-x-3",children:[g.dispatched&&s.jsxs("span",{children:["Dispatched ",Za(g.dispatched)]}),g.expected&&s.jsxs("span",{children:["Expected ",Za(g.expected)]}),g.received&&s.jsxs("span",{children:["Received ",Za(g.received)]})]}),x&&s.jsxs("div",{className:"text-body-xs text-text-secondary mt-1",children:[x.submitted," submitted · ",x.accepted," accepted",x.rejected?` · ${x.rejected} rejected`:"",x.action_required?` · ${x.action_required} need action`:""]}),y.length>0&&s.jsx("ul",{className:"mt-2 flex flex-col gap-1.5",children:y.map((w,_)=>{var k;return s.jsxs("li",{className:"rounded border border-outline-subtle bg-surface-subtle/60 px-2 py-1.5",children:[s.jsxs("div",{className:"text-body-xs font-medium text-text-primary truncate",children:[w.sku||"SKU",w.title?` · ${w.title}`:""]}),s.jsxs("div",{className:"text-body-xs text-text-tertiary",children:[w.status_name||"Rejected",(k=w.reasons)!=null&&k.length?` â ${w.reasons.join("; ")}`:""]})]},`${w.sku||_}`)})}),f&&s.jsx("div",{className:"text-body-xs text-text-tertiary mt-1 italic",children:f}),m?s.jsxs("button",{onClick:()=>r(m),className:"mt-2 inline-flex items-center gap-1.5 text-body-sm text-text-brand hover:underline",children:[s.jsx(qi,{className:"w-3.5 h-3.5"}),"Open in Shipments"]}):u.layer==="tasks"?s.jsxs("button",{onClick:a,className:"mt-2 inline-flex items-center gap-1.5 text-body-sm text-text-brand hover:underline",children:[s.jsx(Uh,{className:"w-3.5 h-3.5"}),"Open in Tasks"]}):u.deepLinkSkill?s.jsxs("button",{onClick:()=>n(u),className:"mt-2 inline-flex items-center gap-1.5 text-body-sm text-text-brand hover:underline",children:[s.jsx(Rd,{className:"w-3.5 h-3.5"}),v?"Manage in chat":"Do this in chat"]}):null,b&&s.jsxs("a",{href:b,target:"_blank",rel:"noreferrer",className:"mt-1.5 inline-flex items-center gap-1.5 text-body-sm text-text-secondary hover:underline",children:[s.jsx(Qt,{className:"w-3.5 h-3.5"}),"Open on Takealot"]})]},u.id)})})]})})}function AVe({view:e,hideWeekends:t,visibleDays:n,items:r,today:a,anchorMonth:i,onSelect:o,onToggleDone:l}){const c=t?fL.slice(0,5):fL;return s.jsx(V,{className:"min-w-0 p-0 overflow-hidden",children:s.jsx("div",{className:"overflow-x-auto",children:s.jsxs("div",{className:B(e==="week"&&"min-w-[560px]"),children:[s.jsx("div",{className:B("grid border-b border-outline-subtle",t?"grid-cols-5":"grid-cols-7"),children:c.map(u=>s.jsx("div",{className:"min-w-0 px-1 py-1.5 text-body-xs font-medium text-text-tertiary text-center md:px-2",children:u},u))}),s.jsx("div",{className:B("grid",t?"grid-cols-5":"grid-cols-7",e==="week"&&"min-h-[28rem]"),children:n.map(u=>{const d=Number(u.slice(5,7))-1===i,h=u===a,f=r.filter(g=>uVe(g,u,{hideWeekends:t,gridAnchor:y=>_Ve(y)})),m=f.some(g=>g.kind==="promo_deadline"&&!Zx(g)),x=NVe(f,e==="week");return s.jsxs("div",{className:B("min-w-0 overflow-hidden border-b border-r border-outline-subtle p-1 flex flex-col gap-px",e==="week"?"min-h-[28rem]":"min-h-[4.25rem]",!d&&e==="month"&&"bg-surface-subtle/50",m&&"bg-category-1-50/40"),children:[s.jsx("div",{className:"flex items-center justify-between px-0.5",children:s.jsx("span",{className:B("text-[10px] leading-none",h?"inline-flex items-center justify-center w-4 h-4 rounded-full bg-intent-brand text-text-inverse font-semibold":d?"text-text-secondary":"text-text-tertiary"),children:Number(u.slice(8,10))})}),x.map(g=>s.jsx(TVe,{group:g,today:a,onClick:()=>o(u,g.items),onToggleDone:l},g.key))]},u)})})]})})})}function TVe({group:e,today:t,onClick:n,onToggleDone:r}){const{items:a}=e,i=a.length===1?a[0]:null,o=a.some(h=>h.actionRequired),l=!!i&&i.confidence==="projected",c=!!i&&Zx(i),u=!!i&&cG(i,t),d=i?i.title:`${a.length} ${e.short}`;
909return s.jsxs("div",{className:B("min-w-0 w-full flex items-center gap-0.5 rounded-sm border px-1 py-px text-[10px] leading-tight",e.chip,l&&"border-dashed opacity-80",c&&"opacity-60"),children:[(i==null?void 0:i.kind)==="promo_deadline"&&s.jsx(Tv,{item:i,onToggle:r,className:"min-h-0 min-w-0 -ml-0.5"}),s.jsxs("button",{type:"button",onClick:n,className:"min-w-0 flex-1 flex items-center gap-1 truncate text-left",title:d,children:[o&&s.jsx("span",{className:"w-1 h-1 rounded-full bg-error-500 shrink-0"}),s.jsx("span",{className:"truncate min-w-0 flex-1",children:d}),u&&!c&&s.jsx("span",{className:"shrink-0 text-[9px] font-medium opacity-80",children:"today"})]})]})}function OVe({layers:e,onToggleLayer:t,showAllPromos:n,onShowAllPromos:r,hideApplied:a,onHideApplied:i,hideWeekends:o,onHideWeekends:l,view:c,onView:u,onToday:d,todayDisabled:h,onPrev:f,onNext:m,heading:x}){return s.jsxs("div",{className:"mb-4 flex min-w-0 flex-col gap-3",children:[s.jsx("div",{className:"flex min-w-0 flex-wrap items-center gap-x-1 gap-y-1",children:V3.map(g=>{const y=e.has(g),b=uf[g];return s.jsxs("button",{onClick:()=>t(g),className:B("inline-flex items-center gap-1.5 rounded px-2 py-2 text-body-sm md:px-1.5 md:py-1 md:text-body-xs","min-h-11 md:min-h-0 transition-colors hover:bg-surface-subtle",y?"text-text-secondary":"text-text-tertiary/60"),title:y?`Hide ${b.label}`:`Show ${b.label}`,"aria-pressed":y,children:[s.jsx("span",{className:B("w-2 h-2 rounded-full shrink-0 transition-colors",y?b.dot:"bg-outline-strong/30")}),s.jsx("span",{className:B(!y&&"line-through decoration-from-font"),children:b.label})]},g)})}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2",children:[e.has("promotions")&&s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"inline-flex min-h-11 md:min-h-0 items-center gap-1.5 text-body-sm text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:n,onChange:g=>r(g.target.checked),className:"rounded border-outline"}),"All promos"]}),s.jsxs("label",{className:"inline-flex min-h-11 md:min-h-0 items-center gap-1.5 text-body-sm text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:a,onChange:g=>i(g.target.checked),className:"rounded border-outline"}),"Hide applied"]})]}),s.jsxs("label",{className:"inline-flex min-h-11 md:min-h-0 items-center gap-1.5 text-body-sm text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:o,onChange:g=>l(g.target.checked),className:"rounded border-outline"}),"Weekdays only"]})]}),s.jsxs("div",{className:"flex min-w-0 w-full flex-wrap items-center gap-2 sm:ml-auto sm:w-auto",children:[s.jsxs(Pa,{value:c,onValueChange:g=>{(g==="month"||g==="week")&&u(g)},variant:"neutral",size:"sm",className:"shrink-0","aria-label":"Calendar view",children:[s.jsx(Ln,{value:"month",children:"Month"}),s.jsx(Ln,{value:"week",children:"Week"})]}),s.jsx(W,{intent:"neutral",variant:"outline",size:"sm",onClick:d,disabled:h,children:"Today"}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center justify-center gap-1 sm:flex-none",children:[s.jsx(W,{variant:"ghost",size:"sm",onClick:f,"aria-label":c==="week"?"Previous week":"Previous month",children:s.jsx(ud,{className:"w-4 h-4"})}),s.jsx("div",{className:"min-w-0 flex-1 truncate text-center text-body-md font-semibold text-text-primary sm:min-w-[9rem] sm:flex-none",children:x}),s.jsx(W,{variant:"ghost",size:"sm",onClick:m,"aria-label":c==="week"?"Next week":"Next month",children:s.jsx(fr,{className:"w-4 h-4"})})]})]})]})]})}function IVe(){const e=Lt(),t=Rt(),[n,r]=ki(),[a,i]=p.useState([]),[o,l]=p.useState(()=>n.get("seller")||""),[c,u]=p.useState(new Set(vVe)),[d,h]=p.useState(!1),[f,m]=p.useState(()=>gL(mL,!1)),[x,g]=p.useState(()=>gL(pL,!0)),[y,b]=p.useState(()=>{try{return localStorage.getItem(xL)==="week"?"week":"month"}catch{return"month"}}),[v,w]=p.useState(()=>{const ve=fj();return{year:Number(ve.slice(0,4)),month:Number(ve.slice(5,7))-1}}),[_,k]=p.useState(()=>Bm(fj())),[j,N]=p.useState(null),[E,A]=p.useState(!1),[C,T]=p.useState(null),[S,O]=p.useState(null),R=fj(),I=cVe(R),$=v.year===Number(R.slice(0,4))&&v.month===Number(R.slice(5,7))-1,P=_===Bm(R),F=y==="week"?P:$;p.useEffect(()=>{yL(mL,f)},[f]),p.useEffect(()=>{yL(pL,x)},[x]),p.useEffect(()=>{try{localStorage.setItem(xL,y)}catch{}},[y]);function Z(ve){l(ve),r(Me=>{const Xe=new URLSearchParams(Me);return Xe.set("seller",ve),Xe},{replace:!0})}p.useEffect(()=>{K.sellers().then(ve=>{var Xe;i(ve);const Me=[n.get("seller"),o].find(ze=>ze&&ve.some(Fe=>Fe.slug===ze))||((Xe=ve[0])==null?void 0:Xe.slug)||"";Me&&Z(Me)}).catch(()=>i([]))},[]),p.useEffect(()=>{const ve=n.get("seller");ve&&ve!==o&&a.some(Me=>Me.slug===ve)&&l(ve)},[n,a,o]);const D=p.useMemo(()=>{const ve=`${v.year}-${String(v.month+1).padStart(2,"0")}-01`,Me=(Eo(ve).getUTCDay()+6)%7,Xe=ea(ve,-Me),ze=[];for(let Fe=0;Fe<42;Fe++)ze.push(ea(Xe,Fe));return{days:ze,gridStart:Xe,gridEnd:ze[41]}},[v]),H=p.useMemo(()=>{const ve=[];for(let Me=0;Me<7;Me++)ve.push(ea(_,Me));return f?ve.filter(Me=>!XS(Me)):ve},[_,f]),Y=p.useMemo(()=>y==="week"?H:f?D.days.filter(ve=>
909!XS(ve)):D.days,[y,H,D.days,f]),M=p.useMemo(()=>{const ve=y==="week"?_:D.gridStart,Me=y==="week"?ea(_,6):D.gridEnd,Xe=ve<ea(R,-14)?ve:ea(R,-14),ze=Me>ea(R,42)?Me:ea(R,42);return{from:Xe,to:ze}},[y,_,D,R]),z=p.useMemo(()=>V3.filter(ve=>c.has(ve)),[c]);p.useEffect(()=>{if(!o||z.length===0){N(null);return}let ve=!1;return A(!0),T(null),kN.get({seller:o,from:M.from,to:M.to,layers:z,showAllPromos:d}).then(Me=>{ve||N(Me)}).catch(Me=>{ve||T(String((Me==null?void 0:Me.message)||Me))}).finally(()=>{ve||A(!1)}),()=>{ve=!0}},[o,M.from,M.to,z,d]);const G=p.useMemo(()=>((j==null?void 0:j.items)??[]).filter(ve=>!gVe(ve,{hideApplied:x})),[j==null?void 0:j.items,x]),{openNow:te,needsAction:re,agenda:L}=p.useMemo(()=>SVe(G,{today:R,lookbackFrom:I,fetchTo:M.to}),[G,R,I,M.to]);function q(ve){u(Me=>{const Xe=new Set(Me);return Xe.has(ve)?Xe.delete(ve):Xe.add(ve),Xe})}function me(ve){w(Me=>{const Xe=Me.month+ve,ze=Me.year+Math.floor(Xe/12),Fe=(Xe%12+12)%12;return{year:ze,month:Fe}})}function ee(){w({year:Number(R.slice(0,4)),month:Number(R.slice(5,7))-1}),k(Bm(R))}function ne(ve){k(Me=>ea(Me,ve*7))}function X(ve){if(ve!==y){if(ve==="week"){const Me=$?R:`${v.year}-${String(v.month+1).padStart(2,"0")}-01`;k(Bm(Me))}else{const Me=ea(_,3);w({year:Number(Me.slice(0,4)),month:Number(Me.slice(5,7))-1})}b(ve)}}function he(ve,Me){N(Xe=>Xe&&{...Xe,items:Xe.items.map(ze=>hL(ze,ve,Me))}),O(Xe=>Xe&&{...Xe,items:Xe.items.map(ze=>hL(ze,ve,Me))})}async function ae(ve,Me){if(o){he(ve,Me);try{await kN.setPromoDone({seller:o,promotionId:ve,done:Me})}catch(Xe){he(ve,!Me),T(String((Xe==null?void 0:Xe.message)||Xe))}}}function je(ve){var Xe,ze,Fe,tt;if(!o)return;const Me=(Xe=ve.meta)==null?void 0:Xe.promotion_id;if((ve.kind==="promo_action"||H3(ve))&&(typeof Me=="number"||typeof Me=="string")){const U=(Array.isArray((ze=ve.meta)==null?void 0:ze.action_skus)?ve.meta.action_skus:[]).map(Ee=>Ee==null?void 0:Ee.sku).filter(Ee=>!!Ee),ce=(Fe=ve.meta)==null?void 0:Fe.participation,ue=yVe({slug:o,title:ve.title,promotionId:Me,actionCount:Number(((tt=ve.meta)==null?void 0:tt.action_required)||(ce==null?void 0:ce.action_required)||0),skus:U});t(`${Zl()}?prompt=${encodeURIComponent(ue)}&seller=${encodeURIComponent(o)}`);return}if(ve.kind==="promo_deadline"&&(typeof Me=="number"||typeof Me=="string")){const fe=K3(ve.title),U=`Build a Takealot promotion application for ${o} for the "${fe}" promotion (promotion_id ${Me}). Help me choose which products to include and produce the upload-ready sheet.`;t(`${Zl()}?prompt=${encodeURIComponent(U)}&seller=${encodeURIComponent(o)}`);return}ve.deepLinkSkill&&t(`${Zl()}?skill=${encodeURIComponent(ve.deepLinkSkill)}&seller=${encodeURIComponent(o)}`)}function $e(ve){!o||!ve||t(`/sellers/${encodeURIComponent(o)}/shipments?open=${ve}`)}function J(){o&&t(`/sellers/${encodeURIComponent(o)}/tasks`)}if(e.kind==="ready"&&e.me.is_demo_mode)return s.jsx(Yt,{to:"/",replace:!0});const Ne=y==="week"?dVe(_):`${uG[v.month]} ${v.year}`;return s.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[s.jsx(Pt,{crumbs:[{label:"Calendar"}]}),s.jsxs("div",{className:"flex-1 min-h-0 min-w-0 overflow-y-auto overflow-x-hidden px-4 md:px-6 py-4",children:[s.jsx(OVe,{layers:c,onToggleLayer:q,showAllPromos:d,onShowAllPromos:h,hideApplied:x,onHideApplied:g,hideWeekends:f,onHideWeekends:m,view:y,onView:X,onToday:ee,todayDisabled:F,onPrev:()=>y==="week"?ne(-1):me(-1),onNext:()=>y==="week"?ne(1):me(1),heading:Ne}),C&&s.jsx(V,{className:"mb-4 border-outline-error bg-surface-errorSubtle p-3 text-body-sm text-text-error",children:C}),(j==null?void 0:j.notes)&&j.notes.length>0&&s.jsxs(V,{className:"mb-4 border-warning/30 bg-warning/5 p-3 text-body-sm text-text-secondary",children:["Some layers couldnât load: ",j.notes.map(ve=>ve.layer).join(", "),"."]}),s.jsxs("div",{className:"grid min-w-0 grid-cols-1 lg:grid-cols-[minmax(0,1fr)_20rem] gap-4",children:[s.jsx(AVe,{view:y,hideWeekends:f,visibleDays:Y,items:G,today:R,anchorMonth:v.month,onSelect:(ve,Me)=>O({day:ve,items:Me}),onToggleDone:ae}),s.jsx(CVe,{lookbackFrom:I,fetchTo:M.to,openNow:te,needsAction:re,agenda:L,loading:E,today:R,onSelect:(ve,Me)=>
909O({day:ve,items:Me}),onToggleDone:ae})]})]}),s.jsx(EVe,{selected:S,onClose:()=>O(null),onOpenInChat:je,onOpenShipment:$e,onOpenTasks:J,onToggleDone:ae})]})}const PVe=new Set(["Sales pulse","Returns snapshot","Catalogue & operations"]),RVe=[{title:"Money",titles:["Sales Pulse","Profitability","Payout Bridge"]},{title:"Stock",titles:["Stock Health"]},{title:"Quality",titles:["Returns Watch","Listing Quality"]},{title:"Competition",titles:["Competitive Intelligence","Repricer"]}];function DVe(){const e=Lt(),t=e.kind==="ready"&&e.me.is_demo_mode,n=e.kind==="ready"?e.me.allowed_slugs??[]:[],[r,a]=p.useState(null),[i,o]=p.useState({}),[l,c]=p.useState(null),[u,d]=p.useState(null),[h,f]=p.useState(""),[m,x]=p.useState(null),g=m??n[0]??null;async function y(){try{a(await K.listDashboards())}catch(E){d(String((E==null?void 0:E.message)||E))}}p.useEffect(()=>{y()},[]),p.useEffect(()=>{if(!g){o({}),c(null);return}let E=!1;return K.dashboardHeadlines({seller:g}).then(A=>{E||(o(A.headlines||{}),c(A.resolved_at))}).catch(A=>{console.error("dashboard headlines failed",A)}),()=>{E=!0}},[g]);const b=p.useMemo(()=>{if(!r)return null;const E=r.filter(C=>!PVe.has(C.title)),A=h.toLowerCase().trim();return A?E.filter(C=>C.title.toLowerCase().includes(A)||(C.description??"").toLowerCase().includes(A)||C.sellers.some(T=>T.toLowerCase().includes(A))):E},[r,h]),v=p.useMemo(()=>(b==null?void 0:b.filter(E=>E.is_favorite))??[],[b]),w=p.useMemo(()=>(b==null?void 0:b.filter(E=>E.is_system&&!E.is_favorite))??[],[b]),_=p.useMemo(()=>(b==null?void 0:b.filter(E=>!E.is_system&&!E.is_favorite))??[],[b]),k=p.useMemo(()=>{const E=new Set,A=RVe.map(T=>{const S=T.titles.map(O=>w.find(R=>R.title===O)).filter(O=>!!O);for(const O of S)E.add(O.id);return{title:T.title,items:S}}).filter(T=>T.items.length>0),C=w.filter(T=>!E.has(T.id));return C.length>0&&A.push({title:"Built-in reports",items:C}),A},[w]);async function j(E,A){a(C=>C&&C.map(T=>T.id===E?{...T,is_favorite:A}:T));try{await K.favoriteDashboard(E,A)}catch(C){console.error("favorite toggle failed",C),y()}}const N=g?`?seller=${encodeURIComponent(g)}`:"";return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Reports"}],actions:t?null:s.jsxs(st,{to:"/dashboards/new",className:"text-xs text-text-body hover:text-text-primary flex items-center gap-1 px-2 py-1 rounded-md border border-outline-subtle hover:bg-surface-subtle",children:[s.jsx(In,{className:"w-3 h-3"})," New report"]})}),s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full p-4 md:p-8 space-y-6 md:space-y-8",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-text-primary",children:"Reports"}),s.jsx("p",{className:"mt-1 text-sm text-text-secondary max-w-2xl",children:"Ask the agent to build you a report wrapping your seller data â pin it here, come back to it any time, and the data refreshes every time you open it."})]}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx(pc,{fieldClassName:"max-w-md flex-1 min-w-[200px]",type:"search",value:h,onChange:E=>f(E.target.value),placeholder:"Search reportsâ¦"}),n.length>1&&s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary",children:["Store",s.jsx(Tt,{value:g??n[0],onChange:E=>x(E.target.value),inputSize:"sm",className:"w-auto",children:n.map(E=>s.jsx("option",{value:E,children:E},E))})]})]}),u&&s.jsxs(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error flex items-start gap-2",children:[s.jsx(yt,{className:"w-4 h-4 shrink-0 mt-0.5"}),s.jsx("div",{children:u})]}),r===null&&!u&&s.jsx("div",{className:"text-xs text-text-tertiary",children:"Loadingâ¦"}),(r==null?void 0:r.length)===0&&s.jsxs(V,{className:"p-8 text-center",children:[s.jsx(rx,{className:"w-8 h-8 mx-auto text-text-tertiary mb-3"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"No reports yet."}),!t&&s.jsxs(st,{to:"/dashboards/new",className:"mt-3 inline-flex items-center gap-1 text-xs text-text-brand hover:text-text-brand",children:[s.jsx(In,{className:"w-3 h-3"})," Build your first report"]})]}),r&&r.length>0&&(b==null?void 0:b.length)===0&&s.jsxs("div",{className:"text-sm text-text-secondary",children:['No reports match "',h,'".']}),v.length>0&&s.jsx(mj,{title:"Favorites",count:v.length,children:v.map(E=>
909s.jsx(pj,{dashboard:E,headline:i[E.id],freshness:E.is_system?l:null,href:`/dashboards/${E.id}${E.is_system?N:""}`,onToggleFavorite:j},E.id))}),k.map(E=>s.jsx(mj,{title:E.title,count:E.items.length,children:E.items.map(A=>s.jsx(pj,{dashboard:A,headline:i[A.id],freshness:l,href:`/dashboards/${A.id}${N}`,onToggleFavorite:j},A.id))},E.title)),_.length>0&&s.jsx(mj,{title:v.length>0||k.length>0?"Your reports":"",count:v.length>0||k.length>0?_.length:void 0,children:_.map(E=>s.jsx(pj,{dashboard:E,href:`/dashboards/${E.id}`,onToggleFavorite:j},E.id))})]})})]})}function mj({title:e,count:t,children:n}){return s.jsxs("div",{children:[e&&s.jsxs("div",{className:"mb-3 flex items-baseline gap-2",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:e}),t!=null&&s.jsx("span",{className:"text-xs text-text-tertiary",children:t})]}),s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:n})]})}function pj({dashboard:e,headline:t,freshness:n,href:r,onToggleFavorite:a}){const i=(t==null?void 0:t.delta_pct)==null?null:t.delta_pct>0?"text-text-success":t.delta_pct<0?"text-text-error":"text-text-tertiary";return s.jsxs("div",{className:"group relative",children:[s.jsxs(st,{to:r,className:"block rounded-xl border border-outline-subtle bg-surface p-4 hover:border-outline-strong hover:shadow-sm transition",children:[s.jsxs("div",{className:"flex items-start gap-2 pr-7",children:[s.jsx("div",{className:"font-semibold text-text-primary text-sm flex-1",children:e.title}),e.is_system&&s.jsx("span",{title:"Built-in report provided by Gadjet â view-only.",className:"shrink-0 mt-0.5 px-1.5 py-0.5 rounded bg-surface-brandSubtle border border-outline-brand text-text-brand text-body-xs font-semibold uppercase tracking-wider",children:"Gadjet"})]}),t?s.jsxs("div",{className:"mt-2",children:[s.jsxs("div",{className:"text-lg font-semibold tabular-nums text-text-primary tracking-tight",children:[t.formatted,t.delta_formatted&&s.jsx("span",{className:B("ml-2 text-xs font-medium",i),children:t.delta_formatted})]}),s.jsx("div",{className:"text-body-xs text-text-tertiary",children:t.label})]}):e.description&&s.jsx("p",{className:"mt-1 text-xs text-text-secondary line-clamp-2 min-h-[2.4em]",children:e.description}),s.jsxs("div",{className:"mt-3 flex items-center gap-2 flex-wrap text-body-xs",children:[!e.is_system&&s.jsx("span",{className:"px-1.5 py-0.5 rounded bg-surface-subtle border border-outline-subtle text-text-secondary uppercase tracking-wider",children:e.scope==="cross_seller"?"cross-seller":"seller"}),!e.is_system&&e.sellers.slice(0,3).map(o=>s.jsx("span",{className:"px-1.5 py-0.5 rounded bg-surface-subtle border border-outline-subtle text-text-secondary font-mono",children:o},o)),!e.is_system&&e.sellers.length>3&&s.jsxs("span",{className:"text-text-tertiary",children:["+",e.sellers.length-3]})]}),s.jsx("div",{className:"mt-2 text-body-xs text-text-tertiary",children:n?`numbers from ${new Date(n).toLocaleTimeString("en-ZA",{hour:"2-digit",minute:"2-digit"})}`:"Refreshes when you open it"})]}),s.jsx("button",{onClick:o=>{o.preventDefault(),o.stopPropagation(),a(e.id,!e.is_favorite)},"aria-label":e.is_favorite?"Unstar":"Star",title:e.is_favorite?"Unstar":"Star",className:B("absolute top-3 right-3 p-1 rounded",e.is_favorite?"text-warning-500 hover:text-text-warning":"text-text-tertiary hover:text-warning-500 opacity-0 group-hover:opacity-100 focus:opacity-100"),children:s.jsx(Jre,{className:B("w-4 h-4",e.is_favorite?"fill-warning-400":"")})})]})}const bL=400;function MVe({html:e}){const t=p.useRef(null),[n,r]=p.useState(bL);return p.useEffect(()=>{var u;const a=t.current;if(!a)return;let i=null,o=null;function l(){var d;try{const h=(d=a==null?void 0:a.contentDocument)==null?void 0:d.body;if(!h)return;const f=Math.max(h.scrollHeight,bL);r(f)}catch{}}function c(){var h;l(),o=setTimeout(l,100);const d=(h=a==null?void 0:a.contentDocument)==null?void 0:h.body;d&&typeof ResizeObserver<"u"&&(i=new ResizeObserver(()=>l()),i.observe(d))}return a.addEventListener("load",c),((u=a.contentDocument)==null?void 0:u.readyState)==="complete"&&c(),()=>{a.removeEventListener("load",c),i&&i.disconnect(),o&&clearTimeout(o)}},[e]),s.jsx("iframe",{ref:t,sandbox:"allow-same-origin allow-top-navigation-by-user-activation",srcDoc:e,title:"Report",style:{width:"100%",height:`${n}px`,border:"none",display:"block"}})}const hG=[{window:{kind:"default"},label:"Default"},{window:{kind:"days",days:7},label:"7d"},{window:{kind:"days",days:30},label:"30d"},{window:{kind:"days",days:90},label:"90d"},{window:{kind:"relative",relative:"current_month"},label:"This month"},{window:{kind:"relative",relative:"last_month"},label:"Last month"}];function $Ve(e,t){if(t==="current_month"||t==="last_month")return{kind:"relative",relative:t};if(e){const n=Number(e);if(n===7||n===30||n===90)return{kind:"days",days:n}}return{kind:"default"}}function LVe(e){if(e.kind==="default")return null;const t=hG.find(n=>fG(n.window,e));return(t==null?void 0:t.label)??null}function fG(e,t){return e.kind!==t.kind?!1:e.kind==="days"&&t.kind==="days"?e.days===t.days:e.kind==="relative"&&t.kind==="relative"?e.relative===t.relative:!0}function FVe(e){return e.kind==="days"?{days:e.days}:e.kind==="relative"?{relative:e.relative}:{}}
909function BVe({value:e,onChange:t}){return s.jsx("div",{role:"group","aria-label":"Report time window",className:"inline-flex items-center gap-0.5 p-0.5 rounded-md border border-outline-subtle bg-surface",children:hG.map(n=>{const r=fG(n.window,e);return s.jsx("button",{type:"button",onClick:()=>t(n.window),className:B("px-2 py-1 text-[11px] font-medium rounded transition",r?"bg-surface-brandSubtle text-text-brand":"text-text-secondary hover:text-text-primary hover:bg-surface-subtle"),children:n.label},n.label)})})}function UVe(){const{id:e}=jn(),t=Rt(),[n,r]=ki(),a=Lt(),[i,o]=p.useState(null),[l,c]=p.useState(null),[u,d]=p.useState(null),[h,f]=p.useState(!1),[m,x]=p.useState(!1),[g,y]=p.useState(!1),b=p.useMemo(()=>a.kind!=="ready"?[]:a.me.allowed_slugs??[],[a]),v=n.get("seller"),w=n.get("days"),_=n.get("relative"),k=p.useMemo(()=>$Ve(w,_),[w,_]),j=p.useMemo(()=>({...v?{seller:v}:{},...FVe(k)}),[v,w,_,k]),N=p.useCallback(I=>{const $=new URLSearchParams(n);for(const[P,F]of Object.entries(I))F==null||F===""?$.delete(P):$.set(P,F);r($,{replace:!0})},[n,r]),E=p.useCallback(async()=>{if(e){d(null);try{const[I,$]=await Promise.all([K.getDashboard(e),K.renderDashboard(e,j)]);o(I),c($)}catch(I){d(String((I==null?void 0:I.message)||I))}}},[e,j]);p.useEffect(()=>{o(null),c(null),E()},[e,E]);async function A(){if(e){f(!0),d(null);try{c(await K.renderDashboard(e,j))}catch(I){d(String((I==null?void 0:I.message)||I))}finally{f(!1)}}}async function C(){if(!(!e||m)){x(!0),d(null);try{const{blob:I,filename:$}=await K.renderDashboardPdf(e,j),P=URL.createObjectURL(I),F=document.createElement("a");F.href=P,F.download=$,document.body.appendChild(F),F.click(),F.remove(),setTimeout(()=>URL.revokeObjectURL(P),1500)}catch(I){d(String((I==null?void 0:I.message)||I))}finally{x(!1)}}}async function T(){if(!(!e||!i||g)){y(!0),d(null);try{const I=await K.duplicateDashboard(e);t(`/dashboards/${I.id}/edit`)}catch(I){d(String((I==null?void 0:I.message)||I))}finally{y(!1)}}}async function S(){if(!(!e||!i)&&zVe(i.title))try{await K.deleteDashboard(e),t("/dashboards")}catch(I){d(String((I==null?void 0:I.message)||I))}}function O(I){I.kind==="default"?N({days:null,relative:null}):I.kind==="days"?N({days:String(I.days),relative:null}):N({relative:I.relative,days:null})}const R=LVe(k);return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Reports",to:"/dashboards"},{label:(i==null?void 0:i.title)||"Loadingâ¦"}],actions:s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs(W,{onClick:A,disabled:!i||h,intent:"neutral",variant:"outline",size:"sm",title:"Re-run the report's queries against current data",children:[s.jsx(pa,{className:h?"w-3.5 h-3.5 animate-spin":"w-3.5 h-3.5"}),s.jsx("span",{className:"hidden sm:inline",children:"Refresh"})]}),s.jsxs(W,{onClick:C,disabled:!i||m,"aria-label":"Download PDF",intent:"neutral",variant:"outline",size:"sm",title:"Download this report as a PDF (uses current data)",children:[s.jsx(Dr,{className:m?"w-3.5 h-3.5 animate-pulse":"w-3.5 h-3.5"}),s.jsx("span",{className:"hidden md:inline",children:m?"Renderingâ¦":"PDF"})]}),s.jsxs(W,{onClick:T,disabled:!i||g,"aria-label":"Duplicate",intent:"neutral",variant:"outline",size:"sm",title:"Clone this report as a starting point â opens the new copy's edit chat",children:[s.jsx(bi,{className:g?"w-3.5 h-3.5 animate-pulse":"w-3.5 h-3.5"}),s.jsx("span",{className:"hidden md:inline",children:g?"Cloningâ¦":"Duplicate"})]}),(i==null?void 0:i.can_edit)&&s.jsxs(s.Fragment,{children:[s.jsxs(W,{onClick:()=>e&&t(`/dashboards/${e}/edit`),disabled:!i,"aria-label":"Edit",intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(Qi,{className:"w-3.5 h-3.5"}),s.jsx("span",{className:"hidden md:inline",children:"Edit"})]}),s.jsxs(W,{onClick:S,disabled:!i,"aria-label":"Delete",intent:"destructive",variant:"outline",size:"sm",children:[s.jsx(us,{className:"w-3.5 h-3.5"}),s.jsx("span",{className:"hidden md:inline",children:"Delete"})]})]})]})}),s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full p-4 md:p-6 space-y-4",children:[u&&s.jsxs(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error flex items-start gap-2",children:[s.jsx(yt,{className:"w-4 h-4 shrink-0 mt-0.5"}),s.jsx("div",{children:u})]}),i&&s.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[s.jsxs("div",{children:[i.description&&s.jsx("p",{className:"text-sm text-text-secondary",children:i.description}),s.jsxs("div",{className:"mt-1 flex items-center gap-2 text-body-xs text-text-tertiary flex-wrap",children:[i.is_system?s.jsx("span",{className:"px-1.5 py-0.5 rounded bg-surface-brandSubtle border border-outline-brand text-text-brand text-body-xs font-semibold uppercase tracking-wider",children:"Gadjet"}):s.jsx(WVe,{scope:i.scope}),!i.is_system&&s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"·"}),s.jsx("span",{children:i.sellers.join(", ")||"no sellers"})]}),(l==null?void 0:l.resolved_at)&&s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"·"}),s.jsxs("span",{children:["numbers from"," ",new Date(l.resolved_at).toLocaleTimeString("en-ZA",{hour:"2-digit",minute:"2-digit"})]})]}),R&&s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"·"}),s.jsx("span",{children:R})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx(BVe,{value:k,onChange:O}),i.is_system&&b.length>1&&s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary",children:["Store",s.jsx(Tt,{value:v??b[0],onChange:I=>N({seller:I.target.value}),inputSize:"sm",className:"w-auto",children:b.map(I=>s.jsx("option",{value:I,children:I},I))})]})]})]}),l&&l.errors.length>0&&s.jsxs(V,{className:"p-3 text-xs text-text-warning bg-surface-warningSubtle border-outline-warning",children:[s.jsxs("div",{className:"flex items-center gap-2 font-medium mb-1",children:[s.jsx(yt,{className:"w-3.5 h-3.5"}),l.errors.length," token",l.errors.length===1?"":"s"," failed to resolve"]}),s.jsx("ul",{className:"ml-5 list-disc space-y-0.5",children:l.errors.map(I=>s.jsxs("li",{children:[s.jsx("span",{className:"font-mono",children:I.token}),": ",I.message]},I.token))})]}),l?s.jsx(V,{className:"overflow-hidden p-0",children:s.jsx(MVe,{html:l.html})}):!u&&s.jsx("div",{className:"text-xs text-text-tertiary py-12 text-center",children:"Loading reportâ¦"})]})})]})}function zVe(e){return window.confirm(`Delete dashboard "${e}
909"? This can't be undone.`)}function WVe({scope:e}){return s.jsx("span",{className:"px-1.5 py-0.5 rounded bg-surface-sunken text-text-secondary text-body-xs uppercase tracking-wider",children:e==="cross_seller"?"cross-seller":"single-seller"})}function vL(){const{id:e}=jn(),t=Rt(),n=e?"edit":"create",[r,a]=p.useState(null),[i,o]=p.useState(null),[l,c]=p.useState(null),[u,d]=p.useState(null),h=p.useRef(!1);p.useEffect(()=>{if(c(null),a(null),o(null),h.current=!1,n==="create"){K.createDashboardChat().then(a).catch(g=>c(String((g==null?void 0:g.message)||g)));return}e&&K.getDashboard(e).then(async g=>{if(o(g),g.chat_id)try{const y=await K.getDashboardChat(g.chat_id);a(y)}catch{const y=await K.createDashboardChat();a(y)}else{const y=await K.createDashboardChat();a(y)}}).catch(g=>c(String((g==null?void 0:g.message)||g)))},[n,e]);const f=p.useCallback(async g=>{r&&await K.saveDashboardChat(r.id,{messages:Hp(g)})},[r]),m=p.useCallback(g=>{if(g.name!=="save_dashboard"||g.is_error)return;const y=g.summary||{};if(!(!y.ok||!y.dashboard_id))if(n==="create"){if(h.current)return;h.current=!0,t(`/dashboards/${y.dashboard_id}`)}else d(Date.now())},[n,t]),x=n==="edit"&&e?{chat_id:r==null?void 0:r.id,dashboard_id:e}:{chat_id:r==null?void 0:r.id};return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Reports",to:"/dashboards"},n==="edit"?{label:(i==null?void 0:i.title)||"Loadingâ¦",to:e?`/dashboards/${e}`:void 0}:{label:"New"},...n==="edit"?[{label:"Edit"}]:[]],actions:n==="edit"&&e?s.jsxs(W,{onClick:()=>t(`/dashboards/${e}`),intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(al,{className:"w-3 h-3"})," View report"]}):null}),s.jsx(D3,{error:l,loading:!l&&!r}),!l&&r&&s.jsxs(s.Fragment,{children:[n==="edit"&&u&&s.jsx(KVe,{timestamp:u}),s.jsx(of,{chatId:r.id,initialMessages:Aw(r.messages),extraRequestBody:x,onConversationChange:f,onToolResult:m,endpoint:"/api/dashboards/chat",placeholder:n==="create"?"Describe the report you wantâ¦":"Ask for a change â add a chart, change the window, drop a sectionâ¦",welcome:({pickExample:g})=>s.jsx(HVe,{onPick:g,mode:n})},r.id)]})]})}function KVe({timestamp:e}){const[t,n]=p.useState(!0);return p.useEffect(()=>{n(!0);const r=setTimeout(()=>n(!1),3e3);return()=>clearTimeout(r)},[e]),t?s.jsx("div",{className:"px-6 pt-3",children:s.jsxs("div",{className:"inline-flex items-center gap-2 text-xs text-text-success bg-surface-successSubtle border border-outline-success px-3 py-1.5 rounded-full",children:[s.jsx(Xt,{className:"w-3.5 h-3.5"}),'Report saved â click "View report" to see it.']})}):null}function HVe({onPick:e,mode:t}){const n=t==="create"?[{text:"Weekly pulse â GMV vs last week, top 10 SKUs",prompt:"Weekly pulse for my store â GMV this week vs last week, plus the top 10 SKUs by revenue."},{text:"Returns â rate, region, top SKUs",prompt:"30-day return rate, returns by region, and the top 5 returning SKUs."},{text:"90-day GMV with stock and transactions",prompt:"90-day GMV trend with current stock levels and recent transactions."},{text:"High traffic, low conversion",prompt:"Top offers by traffic with their 30-day conversion â find the listings worth fixing."}]:[{text:"Add 30-day units sold",prompt:"Add a card showing 30-day units sold."},{text:"Switch to last month",prompt:"Change the time window to last month."},{text:"Add a returns section",prompt:"Add a returns section underneath the sales section."}];return s.jsx(Vp,{heading:t==="create"?"What do you want to see?":"What do you want to change?",examples:n,onPick:e,gridMaxWidth:"2xl"})}function q3({value:e,onChange:t,onPick:n,placeholder:r,disabled:a,variant:i="field",className:o}){const l=i==="search",c=p.useRef(null),[u,d]=p.useState(e),[h,f]=p.useState([]),[m,x]=p.useState(!1),[g,y]=p.useState(!1);p.useEffect(()=>{if(!l)return;function _(k){var E,A;if(k.key!=="/"||k.ctrlKey||k.metaKey||k.altKey)return;const j=k.target;if(!j)return;const N=j.tagName;N==="INPUT"||N==="TEXTAREA"||j.isContentEditable||(k.preventDefault(),(E=c.current)==null||E.focus(),(A=c.current)==null||A.select())}return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[l]),p.useEffect(()=>{d(e)},[e]),p.useEffect(()=>{const _=u.trim();if(_.length<2){f([]);return}const k=window.setTimeout(()=>{$t.searchCategories(_).then(j=>f(j.matches)).catch(()=>f([]))},250);return()=>window.clearTimeout(k)},[u]);function b(_){d(_.target.value),t(_.target.value),x(!0)}function v(){y(!0),x(!0)}function w(){y(!1),window.setTimeout(()=>x(!1),150)}return s.jsxs("div",{className:B("relative min-w-0",l?"w-[300px] max-w-full shrink-0":"flex-1",o),children:[l?s.jsx(pc,{ref:c,value:u,disabled:a,placeholder:r,reserveEnd:!0,onChange:b,onFocus:v,onBlur:w,end:!u&&!g?s.jsx("kbd",{className:"pointer-events-none absolute right-2 top-1/2 z-[1] hidden h-5 min-w-[1.25rem] -translate-y-1/2 items-center justify-center rounded border border-outline-subtle bg-surface-subtle px-1 font-mono text-[10px] text-text-tertiary md:inline-flex",children:"/"}):null}):s.jsx(Re,{ref:c,value:u,disabled:a,placeholder:r,onChange:b,onFocus:v,onBlur:w}),m&&h.length>0&&s.jsx("ul",{className:"absolute z-20 mt-1 w-full max-h-48 overflow-y-auto rounded-md border border-outline-subtle bg-surface shadow-md",children:h.map(_=>s.jsx("li",{children:s.jsxs("button",{type:"button",className:B("w-full text-left px-3 py-2 text-sm hover:bg-surface-subtle",e===_.browse_path&&"bg-surface-subtle"),onMouseDown:k=>k.preventDefault(),onClick:()=>{d(n?_.display_name:_.browse_path),t(_.browse_path),n==null||n(_),x(!1)},children:[s.jsx("div",{className:"font-medium text-text-primary",children:_.display_name}),s.jsx("div",{className:"text-xs text-text-tertiary",children:_.browse_path})]})},_.category_id))})]})}function VVe({onRun:e,running:t,compact:n=!1}){const[r,a]=p.useState(""),[i,o]=p.useState(""),[l,c]=p.useState(""),[u,d]=p.useState(""),[h,f]=p.useState(""),[m,x]=p.useState(!1);function g(){e({min_price_zar:r?Number(r):void 0,max_price_zar:i?Number(i):void 0,max_reviews:l?Number(l):void 0,min_rating:u?Number(u):void 0,max_days_since_first_seen:h?Number(h):void 0,in_stock_only:m||void 0,limit:36})}const y=s.jsxs("div",{className:n?"grid grid-cols-2 gap-2 md:grid-cols-6":"grid grid-cols-2 md:grid-cols-3 gap-3",children:[s.jsx(Sm,{label:"Min price (R)",value:r,onChange:a}),s.jsx(Sm,{label:"Max price (R)",value:i,onChange:o}
909),s.jsx(Sm,{label:"Max reviews",value:l,onChange:c}),s.jsx(Sm,{label:"Min rating",value:u,onChange:d}),s.jsx(Sm,{label:"First seen ⤠days",value:h,onChange:f}),s.jsxs("label",{className:"flex items-end gap-2 pb-2 text-sm text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:m,onChange:b=>x(b.target.checked)}),"In stock only"]})]});return n?s.jsxs("div",{className:"border-t border-outline-subtle bg-surface px-4 py-2.5 md:px-6",children:[y,s.jsx("div",{className:"mt-2",children:s.jsx(W,{onClick:g,disabled:t,size:"sm",children:t?"Searchingâ¦":"Find products"})})]}):s.jsxs(V,{className:"p-4 space-y-3",children:[s.jsx("p",{className:"text-sm text-text-secondary",children:"Filter the Phase B snapshot catalogue â find listings by price, reviews, rating, stock, and age."}),y,s.jsx(W,{onClick:g,disabled:t,children:t?"Searchingâ¦":"Find products"})]})}function Sm({label:e,value:t,onChange:n}){return s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs font-medium text-text-secondary mb-1",children:e}),s.jsx(Re,{value:t,onChange:r=>n(r.target.value)})]})}const mG=p.createContext(null);function qVe({children:e}){const[t,n]=p.useState([]),[r,a]=p.useState(!0),[i,o]=p.useState("detail"),[l,c]=p.useState(0),u=p.useCallback(()=>{o("shortlist"),c(w=>w+1)},[]),d=p.useCallback(async()=>{try{const{items:w}=await $t.listShortlist();n(w)}catch(w){console.warn("[market-explorer] shortlist load failed:",w)}finally{a(!1)}},[]);p.useEffect(()=>{d()},[d]);const h=p.useCallback(async(w,_)=>{const k=w.filter(j=>j.plid!=null).map(j=>({item_kind:"plid",external_id:String(j.plid),meta:{title:j.title??void 0,brand:j.brand??void 0,opportunity_score:j.opportunity_score??null,price:j.selling_price??null,from_search_id:_??null}}));if(!k.length){Ae("warning","No listings with a PLID in that selection.");return}try{const{items:j}=await $t.addShortlistItems(k);n(N=>wL(N,j)),o("shortlist"),Ae("success",`Added ${k.length} to shortlist`)}catch(j){Ae("error",j instanceof Error?j.message:String(j))}},[]),f=p.useCallback(async w=>{const _=w.map(k=>k.keyword.trim()).filter(Boolean).map((k,j)=>{var N,E;return{item_kind:"keyword",keyword:k,meta:{title:k,volume:((N=w[j])==null?void 0:N.volume)??null,competition:((E=w[j])==null?void 0:E.competition)??null}}});if(_.length)try{const{items:k}=await $t.addShortlistItems(_);n(j=>wL(j,k)),o("shortlist"),Ae("success",`Added ${_.length} to shortlist`)}catch(k){Ae("error",k instanceof Error?k.message:String(k))}},[]),m=p.useCallback(async w=>{try{await $t.removeShortlistItem(w),n(_=>_.filter(k=>k.id!==w))}catch(_){Ae("error",_ instanceof Error?_.message:String(_))}},[]),x=p.useCallback(async()=>{try{await $t.clearShortlist(),n([])}catch(w){Ae("error",w instanceof Error?w.message:String(w))}},[]),g=p.useCallback(async(w,_)=>{try{const{item:k}=await $t.patchShortlistItem(w,{playbook_run_id:_});n(j=>j.map(N=>N.id===k.id?k:N))}catch(k){Ae("error",k instanceof Error?k.message:String(k))}},[]),y=p.useCallback(w=>{if(w==null)return!1;const _=`plid:${String(w)}`;return t.some(k=>k.item_key===_)},[t]),b=p.useCallback(w=>{const _=`kw:${w.trim().toLowerCase()}`;return t.some(k=>k.item_key===_)},[t]),v=p.useMemo(()=>({items:t,loading:r,rightTab:i,setRightTab:o,validateNonce:l,requestValidate:u,reload:d,addRows:h,addKeywords:f,remove:m,clear:x,attachRun:g,hasPlid:y,hasKeyword:b}),[t,r,i,l,u,d,h,f,m,x,g,y,b]);return s.jsx(mG.Provider,{value:v,children:e})}function Rw(){const e=p.useContext(mG);if(!e)throw new Error("useShortlist must be used inside ShortlistProvider");return e}function wL(e,t){const n=new Map(e.map(r=>[r.id,r]));for(const r of t)n.set(r.id,r);return[...n.values()].sort((r,a)=>r.sort_order-a.sort_order||r.created_at.localeCompare(a.created_at))}function Dw({queryBar:e,leftRail:t,canvas:n,rightPanel:r,leftRailOpen:a=!0,onCloseLeftRail:i,rightPanelFilled:o=!1,bare:l=!1}){const c=Rw(),[u,d]=p.useState(!1),h=c.items.length,f=o||h>0;return l?s.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden bg-surface-subtle/30 px-4 py-4 md:px-6 md:py-6",children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border border-outline-subtle bg-surface",children:[s.jsx("div",{className:"shrink-0 border-b border-outline-subtle bg-surface",children:e}),s.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:n})]})}):(p.useEffect(()=>{f||d(!1)},[f]),s.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden bg-surface-subtle/30 px-4 py-4 md:px-6 md:py-6",children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border border-outline-subtle bg-surface",children:[s.jsx("div",{className:"shrink-0 border-b border-outline-subtle bg-surface",children:e}),s.jsxs("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[a&&s.jsx("button",{type:"button","aria-label":"Close saved rail",onClick:i,className:"fixed inset-0 z-drawer bg-surface-inverse/40 lg:hidden"}),s.jsx("aside",{className:B("flex w-[212px] shrink-0 flex-col overflow-hidden border-r border-outline-subtle bg-surface","max-lg:fixed max-lg:inset-y-0 max-lg:left-0 max-lg:z-drawer-content max-lg:shadow-lg",!a&&"max-lg:hidden"),children:t}),s.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden",children:n}),u?s.jsxs("aside",{className:"relative hidden w-[352px] shrink-0 flex-col overflow-hidden border-l border-outline-subtle bg-surface md:flex",children:[s.jsx("button",{type:"button",onClick:()=>d(!1),"aria-label":"Hide inspector",title:"Hide inspector",className:"absolute right-2 top-2 z-10 inline-flex h-7 w-7 items-center justify-center rounded-md text-text-secondary hover:bg-surface-subtle hover:text-text-primary",children:s.jsx(fr,{className:"h-4 w-4"})}),r]}):f&&s.jsx(GVe,{filled:o,count:h,onOpen:()=>d(!0)})]})]})}))}function GVe({filled:e,count:t,onOpen:n}){const r=[e?"selection ready":null,t>0?`${t}
909 on shortlist`:null].filter(Boolean),a=r.length?`Show inspector: ${r.join(", ")}`:"Show inspector";return s.jsx("aside",{className:"hidden w-10 shrink-0 flex-col items-center border-l border-outline-subtle bg-surface md:flex",children:s.jsxs("button",{type:"button",onClick:n,"aria-label":a,title:a,className:"relative mt-2.5 inline-flex h-8 w-8 items-center justify-center rounded-md text-text-secondary hover:bg-surface-subtle hover:text-text-primary",children:[s.jsx(xre,{className:B("h-4 w-4",e&&"text-intent-brand")}),t>0?s.jsx("span",{className:"absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full bg-intent-brand px-1 text-[9px] font-semibold leading-none text-text-inverse",children:t}):e&&s.jsx("span",{className:"absolute right-1 top-1 h-2 w-2 rounded-full bg-intent-brand"})]})})}function G3({children:e,quota:t,running:n,runDisabled:r,onRun:a,runLabel:i="Run"}){return s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5 px-4 py-2.5 md:px-6",children:[e,a&&s.jsx(W,{onClick:a,disabled:r||n,size:"sm",children:n?"Runningâ¦":i}),t&&s.jsx("span",{className:"whitespace-nowrap text-[11px] leading-4 text-text-tertiary",children:t.max_searches==null?`${t.used_searches} used`:`${t.used_searches}/${t.max_searches}`})]})}function pG({options:e,value:t,onChange:n}){return s.jsx("div",{className:"inline-flex rounded-md bg-surface-subtle p-0.5",children:e.map(r=>s.jsxs("button",{type:"button",onClick:()=>n(r.key),className:B("inline-flex items-center gap-1 rounded-md px-2.5 py-1 text-sm font-medium",t===r.key?"bg-surface text-text-primary shadow-xs":"text-text-secondary hover:text-text-primary"),children:[r.icon,r.label]},r.key))})}function YVe({pages:e,onChange:t}){return s.jsxs("label",{className:"inline-flex cursor-pointer items-center gap-1.5 whitespace-nowrap rounded-md border border-outline-subtle bg-surface px-2.5 py-1.5 text-sm text-text-secondary",children:[s.jsx(j2,{className:"h-3.5 w-3.5"}),s.jsxs("select",{value:e,onChange:n=>t(Number(n.target.value)),className:"bg-transparent text-sm text-text-primary outline-none",children:[s.jsx("option",{value:1,children:"1 page"}),s.jsx("option",{value:2,children:"2 pages"}),s.jsx("option",{value:3,children:"3 pages"})]}),s.jsx(Pn,{className:"h-3 w-3 text-text-tertiary"})]})}function QS({value:e,onChange:t,placeholder:n,onSubmit:r,disabled:a}){return s.jsx("div",{className:"min-w-[160px] flex-1",children:s.jsx(Re,{value:e,onChange:i=>t(i.target.value),placeholder:n,disabled:a,onKeyDown:i=>{i.key==="Enter"&&r&&r()}})})}function ZVe({onClick:e}){return s.jsxs("button",{type:"button",onClick:e,className:"inline-flex items-center gap-1.5 whitespace-nowrap rounded-md border border-outline-brand bg-surface px-2.5 py-1.5 text-sm text-intent-brand hover:bg-surface-brandSubtle",children:[s.jsx(Ht,{className:"h-3.5 w-3.5"}),"Ask instead"]})}function Y3({onClick:e}){return s.jsx("button",{type:"button",onClick:e,className:"inline-flex items-center justify-center rounded-md border border-outline-subtle p-1.5 text-text-secondary hover:text-text-primary lg:hidden","aria-label":"Open saved rail",children:s.jsx(uF,{className:"h-4 w-4"})})}function XVe(e){const t=[];e.preset_key==="biggest_sellers"?t.push("Marketplace bestsellers"):e.keyword&&t.push(`Keyword: "${e.keyword}"`),e.min_price_zar!=null&&e.max_price_zar!=null?t.push(`R${e.min_price_zar}âR${e.max_price_zar}`):e.max_price_zar!=null?t.push(`under R${e.max_price_zar}`):e.min_price_zar!=null&&t.push(`over R${e.min_price_zar}`);const n=e.page_count??1;return t.push(`${n} page${n>1?"s":""}`),t.join(" · ")}function JVe({disabled:e,onRunSpec:t}){const[n,r]=p.useState(""),[a,i]=p.useState(!1),[o,l]=p.useState(null),c=p.useCallback(async()=>{const u=n.trim();if(!(!u||a)){i(!0),l(null);try{const d=await $t.parseQuery(u);l(d)}catch(d){Ae("error",d instanceof Error?d.message:String(d))}finally{i(!1)}}},[n,a]);return s.jsxs("div",{className:"min-w-[160px] flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Re,{value:n,onChange:u=>{r(u.target.value),l(null)},placeholder:'e.g. "top 100 fish oil listings under R200"',disabled:e,onKeyDown:u=>{u.key==="Enter"&&c()}}),s.jsxs(W,{onClick:()=>void c(),disabled:e||!n.trim()||a,size:"sm",variant:"outline",children:[a?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):s.jsx(Ht,{className:"h-3.5 w-3.5"}),a?"Readingâ¦":"Interpret"]})]}),o&&s.jsxs("div",{className:"mt-2 rounded-md border border-outline-subtle bg-surface-subtle/60 p-2.5",children:[s.jsx("p",{className:"text-sm text-text-primary",children:o.interpretation}),s.jsx("p",{className:"mt-0.5 text-[11px] text-text-tertiary",children:XVe(o.spec)}),s.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[s.jsxs(W,{onClick:()=>t(o.spec),disabled:e,size:"sm",children:[s.jsx(bd,{className:"h-3.5 w-3.5"}
909),"Run this search"]}),s.jsx("button",{type:"button",onClick:()=>l(null),className:"text-xs text-text-tertiary hover:text-text-primary",children:"Start over"})]})]}),s.jsx("p",{className:"mt-1 text-[11px] leading-4 text-text-tertiary",children:"Parsing is free â only running a search counts against your quota."})]})}function Z3({children:e}){return s.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto px-2.5 py-3.5",children:e})}function pd({label:e,trailing:t,children:n}){return s.jsxs("div",{className:"mb-1",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between px-1.5",children:[s.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-text-tertiary",children:e}),t]}),n]})}function Yp({active:e,onClick:t,icon:n,title:r,meta:a,trailing:i}){return s.jsxs("button",{type:"button",onClick:t,className:B("flex w-full items-center gap-2 rounded-md px-1.5 py-1.5 text-left",e?"bg-surface-brandSubtle":"hover:bg-surface-subtle"),children:[n,s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"truncate text-sm font-medium text-text-primary",children:r}),a&&s.jsx("div",{className:"truncate text-[11px] leading-4 text-text-tertiary",children:a})]}),i]})}function QVe({folders:e,activeFolderId:t,quota:n,onOpen:r,onRefresh:a,onRename:i,onDelete:o}){return s.jsxs(pd,{label:"Saved",trailing:s.jsx("span",{className:"text-[11px] text-text-tertiary",children:(n==null?void 0:n.max_folders)==null?`${(n==null?void 0:n.folder_count)??e.length}`:`${(n==null?void 0:n.folder_count)??e.length}/${n.max_folders}`}),children:[e.length===0&&s.jsx("p",{className:"px-1.5 text-[11px] leading-4 text-text-tertiary",children:"Save a search to pin it here."}),e.map(l=>s.jsx(eqe,{folder:l,active:t===l.id,onOpen:()=>r(l),onRefresh:()=>a(l),onRename:c=>i(l,c),onDelete:()=>o(l)},l.id))]})}function eqe({folder:e,active:t,onOpen:n,onRefresh:r,onRename:a,onDelete:i}){const[o,l]=p.useState(!1),[c,u]=p.useState(e.name),d=e.last_result_count!=null?`${e.last_result_count} rows${e.last_completed_at?` · ${_L(e.last_completed_at)}`:""}`:_L(e.updated_at),h=()=>{const f=c.trim();f&&f!==e.name&&a(f),l(!1)};return o?s.jsxs("div",{className:"flex items-center gap-1 px-1.5 py-1",children:[s.jsx("input",{value:c,onChange:f=>u(f.target.value),onKeyDown:f=>{f.key==="Enter"&&h(),f.key==="Escape"&&(u(e.name),l(!1))},autoFocus:!0,className:"min-w-0 flex-1 bg-transparent text-sm outline-none"}),s.jsx("button",{type:"button",onClick:h,className:"text-intent-success",children:s.jsx(fn,{className:"h-3.5 w-3.5"})})]}):s.jsxs("div",{className:B("group flex items-center rounded-md",t&&"bg-surface-brandSubtle"),children:[s.jsxs("button",{type:"button",onClick:n,className:"flex min-w-0 flex-1 items-center gap-2 px-1.5 py-1.5 text-left",children:[s.jsx(sF,{className:B("h-3.5 w-3.5 shrink-0",t?"text-intent-brand":"text-text-tertiary")}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"truncate text-sm font-medium text-text-primary",children:e.name}),s.jsx("div",{className:"truncate text-[11px] leading-4 text-text-tertiary",children:d})]})]}),s.jsx("button",{type:"button",onClick:r,title:"Refresh",className:"px-1 text-text-tertiary opacity-0 hover:text-text-primary group-hover:opacity-100",children:s.jsx(pa,{className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:()=>{u(e.name),l(!0)},title:"Rename",className:"px-1 text-text-tertiary opacity-0 hover:text-text-primary group-hover:opacity-100",children:s.jsx(Qi,{className:"h-3 w-3"})}),s.jsx("button",{type:"button",onClick:i,title:"Delete",className:"px-1 text-text-tertiary opacity-0 hover:text-intent-error group-hover:opacity-100",children:s.jsx(Bn,{className:"h-3.5 w-3.5"})})]})}function _L(e){const t=Date.now()-new Date(e).getTime();if(!Number.isFinite(t)||t<0)return"just now";const n=Math.floor(t/864e5);return n<1?"today":n===1?"1 day ago":n<30?`${n} days ago`:new Date(e).toLocaleDateString()}function X3({items:e,onRemove:t,onClear:n,onValidate:r,validateDisabled:a}){return s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[s.jsxs("div",{className:"min-h-0 flex-1 space-y-2 overflow-y-auto overflow-x-hidden px-3 py-2.5",children:[e.length===0&&s.jsx("p",{className:"px-1 py-6 text-center text-sm text-text-tertiary",children:"Tick rows in Catalogue or Keywords, then add them here. Validate reads this list."}),e.map(i=>{var o;return s.jsxs("div",{className:"shrink-0 overflow-hidden rounded-[10px] border border-outline-subtle p-2.5",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[i.item_kind==="keyword"?s.jsx(Fa,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-text-tertiary"}):s.jsx(Si,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-text-tertiary"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"truncate text-[13px] font-medium leading-[17px] text-text-primary",children:((o=i.meta)==null?void 0:o.title)||i.keyword||(i.external_id?`PLID ${i.external_id}`:"Item")}),s.jsx("div",{className:"mt-0.5 text-[11px] leading-4 text-text-tertiary",children:tqe(i)})]}),s.jsx("button",{type:"button",onClick:()=>t(i.id),className:"text-text-tertiary hover:text-text-primary","aria-label":"Remove from shortlist",children:s.jsx(Bn,{className:"h-3.5 w-3.5"})})]}),s.jsx("div",{className:"mt-1.5",children:s.jsx("span",{className:rqe(i),children:nqe(i)})})]},i.id)})]}),s.jsxs("div",{className:"border-t border-outline-subtle p-4",children:[n&&e.length>0&&s.jsx("button",{type:"button",onClick:n,className:"mb-2 w-full text-center text-xs text-text-tertiary hover:text-text-primary",children:"Clear all"}),s.jsxs(W,{className:"w-full justify-center",onClick:r,disabled:a||e.length===0,children:[s.jsx(qv,{className:"h-4 w-4"}),"Validate shortlist"]}),s.jsx("p",{className:"mt-2 text-center text-[11px] leading-4 text-text-tertiary",children:e.length===0?"Add listings or phrases first.":`Sends ${e.length===1?"this item":`all ${e.length}`} into Validate.`})]})]})}function tqe(e){var n,r,a;if(e.item_kind==="keyword"){const i=typeof((n=e.meta)==null?void 0:n.volume)=="number"?`${e.meta.volume.toLocaleStr
909ing()}/mo`:null,o=typeof((r=e.meta)==null?void 0:r.competition)=="string"?String(e.meta.competition).toLowerCase():null;return[i,o?`${o} competition`:null].filter(Boolean).join(" · ")||"Keyword"}return[e.external_id?`PLID ${e.external_id}`:null,((a=e.meta)==null?void 0:a.opportunity_score)!=null?`opp ${e.meta.opportunity_score}`:null].filter(Boolean).join(" · ")}function nqe(e){return e.playbook_run_id?"QUEUED":e.item_kind==="keyword"?"KEYWORD":"LISTING"}function rqe(e){const t=e.playbook_run_id?"bg-surface-brandSubtle text-intent-brand":e.item_kind==="keyword"?"bg-surface-subtle text-text-tertiary":"bg-intent-success/10 text-intent-success";return B("rounded px-1.5 py-0.5 text-[10px] font-semibold tracking-wide",t)}function sqe({count:e,onAdd:t,onClear:n}){return e===0?null:s.jsxs("div",{className:"flex shrink-0 items-center gap-3 border-b border-outline-subtle bg-surface-brandSubtle/40 px-5 py-2 text-sm",children:[s.jsxs("span",{className:"text-text-primary",children:[e," ",e===1?"phrase":"phrases"," selected"]}),s.jsx("button",{type:"button",onClick:t,className:"font-medium text-intent-brand hover:text-intent-brandHover",children:"Add to shortlist"}),n&&s.jsx("button",{type:"button",onClick:n,className:"text-xs text-text-tertiary hover:text-text-primary",children:"Clear"})]})}function J3({tabs:e,value:t,onChange:n}){return s.jsx("div",{className:"flex shrink-0 gap-1 border-b border-outline-subtle pl-3.5 pr-10",children:e.map(r=>s.jsxs("button",{type:"button",onClick:()=>n(r.key),className:B("flex items-center gap-1.5 px-2.5 py-2.5 text-sm",t===r.key?"-mb-px border-b-2 border-outline-brand font-medium text-text-primary":"text-text-secondary hover:text-text-primary"),children:[r.label,r.badge!=null&&r.badge!==""&&s.jsx("span",{className:"rounded-full bg-surface-brandSubtle px-1.5 py-0.5 text-[10px] font-semibold text-text-brand",children:r.badge})]},r.key))})}function aqe(e){const t=Date.now()-new Date(e).getTime();if(!Number.isFinite(t)||t<0)return"just now";const n=Math.floor(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.floor(n/60);return r<48?`${r}h ago`:`${Math.floor(r/24)}d ago`}function kL(e){const t=e.status_display||e.status;return t==="completed"&&e.recommendation?String(e.recommendation).toUpperCase():t==="in_progress"?"In progress":t==="expired"?"Expired":t==="abandoned"?"Abandoned":t}function Ov(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t:String((t==null?void 0:t.query)||"")).filter(Boolean):[]}function iqe(e){return[{key:"keyword",label:"Keyword",getValue:t=>String(t.keyword||""),render:t=>{const n=String(t.keyword||""),r=e.includes(n);return s.jsxs("span",{className:"text-text-primary",children:[n,r?s.jsx("span",{className:"ml-1 text-intent-danger",children:"fading"}):null]})}},{key:"vol",label:"Vol",getValue:t=>t.avg_monthly_searches!=null?Number(t.avg_monthly_searches):null,render:t=>s.jsx("span",{className:"text-text-secondary",children:t.avg_monthly_searches!=null?String(t.avg_monthly_searches):"â"})},{key:"trend",label:"3mo",getValue:t=>t.trend_3mo!=null?String(t.trend_3mo):null,render:t=>s.jsx("span",{className:"text-text-secondary",children:t.trend_3mo!=null?String(t.trend_3mo):"â"})}]}function oqe({findings:e,selectedKeywords:t,onToggleKeyword:n}){const r=e.data||{},a=Ov(r.suggested_shortlist||r.suggestions||r.suggested_keepers),i=Array.isArray(r.metrics)?r.metrics:[],o=Array.isArray(r.results)?r.results:[],l=Ov(r.declining);return s.jsxs("div",{className:"space-y-3",children:[s.jsx("p",{className:B("text-sm",e.ok?"text-text-primary":"text-intent-danger"),children:e.summary}),a.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:a.map(c=>{const u=t.includes(c);return s.jsxs("button",{type:"button",onClick:()=>n(c),className:B("rounded-md border px-2 py-1 text-xs",u?"border-intent-brand bg-intent-brand/10 text-text-primary":"border-border-subtle text-text-secondary"),children:[u?"â ":"",c]},c)})}),i.length>0&&s.jsx("div",{className:"overflow-hidden rounded-md border border-border-subtle",children:s.jsx(dt,{rows:i.slice(0,12),columns:iqe(l),getRowKey:(c,u)=>`${String(c.keyword??"")}-${u}`,paginate:!1,persist:!1,tableClassName:"text-xs",empty:{title:"No keyword metrics."}})}),o.length>0&&s.jsx("ul",{className:"space-y-1.5 text-xs text-text-secondary",children:o.slice(0,8).map((c,u)=>s.jsxs("li",{className:"flex gap-2",children:[s.jsxs("span",{className:"w-5 shrink-0 text-text-tertiary",children:["#",String(c.position??u+1)]}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-text-primary",children:String(c.title||"â")}),s.jsxs("span",{className:"shrink-0",children:[typeof c.selling_price=="number"?`R${c.selling_price}`:"",typeof c.star_rating=="number"?` · ${c.star_rating}â
`:"",typeof c.reviews=="number"?` (${c.reviews})`:""]})]},String(c.plid||u)))})]})}function lqe(e){const t=e.seed_keyword||"this product",n=e.target_asp_zar!=null?` Target selling price around R${e.target_asp_zar}.`:"",r=Array.isArray(e.top_keywords)&&e.top_keywords.length?` Optimise the title and search terms for: ${e.top_keywords.join(", ")}.`:"";return`Help me create a Takealot listing for "${t}".${n}${r} Use the create-takealot-listing / listing creation flow and ask me for anything missing.`}function cqe(e){const t=e.seed_keyword||"this product",n=e.target_asp_zar!=null?` Page-1 typical price is ~R${e.target_asp_zar}.`:"",r=Array.isArray(e.top_keywords)&&e.top_keywords.length?` Keywords under consideration: ${e.top_keywords.join(", ")}.`:"";return`I ran New Product Validation for "${t}" and got CAUTION.${n}${r} Help me decide go/no-go: check landed margin at that ASP, differentiation vs weak incumbents, and what would need to be true before I list.`}function jL({brief:e,onOpenMe:t,onRestart:n}){var h,f;const r=Rt(),a=jf(),i=Lt(),o=(e.recommendation||"caution").toLowerCase(),l=e.seed_keyword||((h=e.top_keywords)==null?void 0:h[0])||"",c=i.kind==="ready"?((f=i.me.allowed_slugs)==null?void 0:f[0])??null:null;function u(){const m=new URLSearchParams({tab:"procedures",sop:"listing-creation"});c&&m.set("seller",c),r(`/sops?${m.toString()}`)}function d(m="keyword"){if(!l)return;const x=new URLSearchParams({tab:"catalogue",preset:m,q:l});t(`/market-explorer?${x.toString()}`)}return s.jsxs(V,{className:"space-y-4 p-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Xt,{className:"h-5 w-5 text-intent-success"}),s.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:"Launch Decision Brief"})]}),s.jsxs("p",{className:"text-sm text-text-primary",children:["Recommendation:"," ",s.jsx("span",{className:B("font-semibold uppercase",o==="go"&&"text-intent-success",o==="no-go"&&"text-intent-danger",o==="caution"&&"text-text-primary"),children:o}),e.seed_keyword?` for â${e.seed_keyword}â`:""]}),e.target_asp_zar!=null&&s.jsxs("p",{className:"text-sm text-text-secondary",children:["Target ASP ~R",e.target_asp_zar]}),Array.isArray(e.top_keywords)&&e.top_keywords.length>0&&s.jsxs("p",{className:"text-sm text-text-secondary",children:["Top keywords: ",e.top_keywords.join(", ")
909]}),Array.isArray(e.rationale)&&e.rationale.length>0&&s.jsx("ul",{className:"list-disc space-y-1 pl-5 text-sm text-text-secondary",children:e.rationale.map(m=>s.jsx("li",{children:m},m))}),s.jsxs("div",{className:"border-t border-border-subtle pt-4 space-y-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"What to do next"}),s.jsxs("p",{className:"mt-1 text-sm text-text-secondary",children:[o==="go"&&"The research supports listing. Create the listing now, or draft it in Chat with the briefâs ASP and keywords.",o==="caution"&&"Signals are mixed â donât commit stock yet. Stress-test margin and differentiation, or re-check the shelf.",o==="no-go"&&"This idea looks crowded with no clear opening. Park it, or validate a different seed keyword.",o!=="go"&&o!=="caution"&&o!=="no-go"&&"Use the brief to decide whether to list, dig deeper, or move on."]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[o==="go"&&s.jsxs(s.Fragment,{children:[s.jsx(W,{onClick:u,children:"Create listing"}),s.jsx(W,{variant:"outline",onClick:()=>a(lqe(e)),children:"Draft listing in Chat"}),l&&s.jsxs(W,{variant:"outline",onClick:()=>d("keyword"),children:[s.jsx(Qt,{className:"mr-1 h-3.5 w-3.5"}),"Open shelf in Catalogue"]})]}),o==="caution"&&s.jsxs(s.Fragment,{children:[s.jsx(W,{onClick:()=>a(cqe(e)),children:"Stress-test in Chat"}),l&&s.jsxs(W,{variant:"outline",onClick:()=>d("weak_incumbents"),children:[s.jsx(Qt,{className:"mr-1 h-3.5 w-3.5"}),"Re-check weak incumbents"]}),s.jsx(W,{variant:"outline",onClick:n,children:"Validate a different idea"})]}),o==="no-go"&&s.jsxs(s.Fragment,{children:[s.jsx(W,{onClick:n,children:"Validate a different idea"}),l&&s.jsxs(W,{variant:"outline",onClick:()=>d("keyword"),children:[s.jsx(Qt,{className:"mr-1 h-3.5 w-3.5"}),"Browse related shelf"]})]}),o!=="go"&&o!=="caution"&&o!=="no-go"&&s.jsx(W,{variant:"outline",onClick:n,children:"Start another validation"})]})]})]})}function NL(e){var n,r;if((n=e.keyword)!=null&&n.trim())return e.keyword.trim();const t=typeof((r=e.meta)==null?void 0:r.title)=="string"?e.meta.title.trim():"";return t?t.slice(0,80):e.external_id?`PLID ${e.external_id}`:""}function uqe({onOpenMe:e,initialRunId:t=null}){var ne,X,he;const[n,r]=p.useState(""),[a,i]=p.useState(""),[o,l]=p.useState(null),[c,u]=p.useState([]),[d,h]=p.useState(!1),[f,m]=p.useState(null),[x,g]=p.useState([]),[y,b]=p.useState(0),[v,w]=p.useState(!1),[_,k]=p.useState(!1),[j,N]=p.useState(null),E=Rw(),A=p.useRef(0),C=((ne=o==null?void 0:o.steps)==null?void 0:ne.length)||6,T=o==null?void 0:o.current_step_def,S=o==null?void 0:o.findings,O=p.useMemo(()=>{const ae=(S==null?void 0:S.data)||{};return Ov(ae.suggested_shortlist||ae.suggested_keepers||ae.suggestions)},[S]);function R(ae){var J;const je=((J=ae.findings)==null?void 0:J.data)||{},$e=Ov(je.suggested_shortlist||je.suggested_keepers||je.suggestions);g($e.slice(0,8))}function I(ae){g(je=>je.includes(ae)?je.filter($e=>$e!==ae):[...je,ae])}function $(){b(ae=>ae+1)}async function P(){try{const ae=await oe("/api/playbooks/runs?playbook_slug=new-product-validation&limit=50");if(!ae.ok)return;const je=await ae.json();u(je.runs||[])}catch{}}async function F(ae){var je,$e;m(null),h(!0);try{const J=await oe(`/api/playbooks/runs/${ae}`);if(!J.ok){const ve=await J.json().catch(()=>({}));throw new Error(ve.message||"Failed to open run")}const Ne=await J.json();l(Ne.run),Ne.run.status==="completed"&&Ne.run.deliverable&&N(Ne.run),Ne.run.status==="in_progress"&&R(Ne.run),(je=Ne.run.inputs)!=null&&je.keyword&&r(Ne.run.inputs.keyword),($e=Ne.run.inputs)!=null&&$e.category_slug&&i(Ne.run.inputs.category_slug)}catch(J){m(J instanceof Error?J.message:"Failed to open run")}finally{h(!1)}}function Z(ae){var je,$e;r(((je=ae.inputs)==null?void 0:je.keyword)||""),i((($e=ae.inputs)==null?void 0:$e.category_slug)||""),l(null),g([]),m(null),w(!0)}p.useEffect(()=>{P()},[y]),p.useEffect(()=>{t&&F(t)},[t]),p.useEffect(()=>{E.validateNonce===0||E.validateNonce===A.current||(A.current=E.validateNonce,Y())},[E.validateNonce]);async function D(){if(m(null),!n.trim()){m("Enter a seed keyword to start.");return}h(!0);try{const ae=await oe("/api/playbooks/runs",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({playbook_slug:"new-product-validation",inputs:{keyword:n.trim(),category_slug:a.trim()||void 0}})});if(!ae.ok){const $e=await ae.json().catch(()=>({}));throw new Error($e.message||"Failed to start validation")}const je=await ae.json();l(je.run),w(!1),R(je.run),$()}catch(ae){m(ae instanceof Error?ae.message:"Failed to start validation")}finally{h(!1)}}async function H(ae,je){const $e=await oe("/api/playbooks/runs",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({playbook_slug:"new-product-validation",inputs:{keyword:ae,category_slug:void 0}})});if(!$e.ok){const Ne=await $e.json().catch(()=>({}));throw new Error(Ne.message||"Failed to start validation")}return(await $e.json()).run}async function Y(){m(null),w(!1),h(!0);try{let ae=c;try{const $e=await oe("/api/playbooks/runs?playbook_slug=new-product-validation&limit=50");$e.ok&&(ae=(await $e.json()).runs||[],u(ae))}catch{}let je=null;for(const $e of E.items){if($e.playbook_run_id){const ve=ae.find(Xe=>Xe.id===$e.playbook_run_id);if(!ve||ve.status==="in_progress"||ve.status_display==="in_progress"||ve.status==="completed"){je||(await F($e.playbook_run_id),je={id:$e.playbook_run_id});continue}}const J=NL($e);if(!J)continue;const Ne=await H(J);await E.attachRun($e.id,Ne.id),je||(l(Ne),R(Ne),je=Ne)}$(),E.setRightTab("brief")}catch(ae){m(ae instanceof Error?ae.message:"Failed to validate shortlist")}finally{h(!1)}}async function M(ae){if(o){m(null),h(!0);try{const je={};(ae==="approve"||ae==="redo")&&x.length&&(je.selected_keywords=x);const $e=await oe(`/api/playbooks/runs/${o.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:ae,payload:je})});if(!$e.ok){const Ne=await $e.json().catch(()=>({}));throw new Error(Ne.message||`Failed to ${ae}`)}const J=await $e.json();if(ae==="abandon"){l(null),g([]),$();return}J.run&&(l(J.run),J.status==="in_progress"&&R(J.run),J.status==="completed"&&($(),J.run.deliverable&&(N(J.run),E.setRightTab("brief"))))}catch(je){m(je instanceof Error?je.message:`Failed to ${ae}`)}finally{h(!1)}}}function z(ae){ae&&ae.startsWith("/market-explorer")&&e(ae)}function G(){l(null),g([]),w(!1),$()}const te=(S==null?void 0:S.me_deep_link)||(T==null?void 0:T.me_deep_link),re=O.length>0,L=(j==null?void 0:j.deliverable)||((o==null?void 0:o.status)==="completed"?o.deliverable:null),q=E.rightTab==="detail"?"brief":E.rightTab,me=s.jsxs(V,{className:"space-y-4 p-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:"Validate something else"}),s.jsx("p",{className:"mt-1 text-sm text-text-secondary",children:"We walk
909you through demand, competition, and pricing â one step at a time â and end with a Launch Decision Brief."})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Seed keyword"}),s.jsx(Re,{value:n,onChange:ae=>r(ae.target.value),placeholder:"e.g. fish oil",disabled:d,onKeyDown:ae=>{ae.key==="Enter"&&D()}})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("label",{className:"text-xs font-medium text-text-secondary",children:"Category (optional â improves TAM)"}),s.jsx(q3,{value:a,onChange:i,placeholder:"Search categoriesâ¦",disabled:d})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(W,{onClick:()=>void D(),disabled:d||!n.trim(),children:d?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):"Start validation"}),E.items.length>0&&s.jsx(W,{variant:"outline",onClick:()=>w(!1),children:"Cancel"})]}),f&&s.jsx("p",{className:"text-sm text-intent-danger",children:f})]});let ee;return v&&!o?ee=s.jsx("div",{className:"overflow-auto p-4",children:me}):(o==null?void 0:o.status)==="completed"&&o.deliverable?ee=s.jsxs("div",{className:"overflow-auto p-4",children:[s.jsx("div",{className:"mb-3 flex justify-end",children:s.jsx(W,{variant:"outline",size:"sm",onClick:G,children:"Back to rail"})}),s.jsx(jL,{brief:o.deliverable,onOpenMe:e,onRestart:()=>w(!0)})]}):o?ee=s.jsxs("div",{className:"overflow-auto p-4 space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsxs("p",{className:"text-xs font-medium uppercase tracking-wide text-text-tertiary",children:["Step ",(o.current_step??0)+1," of ",C,(X=o.inputs)!=null&&X.keyword?` · ${o.inputs.keyword}`:""]}),s.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:(T==null?void 0:T.title)||"Workingâ¦"})]}),s.jsx(W,{variant:"outline",size:"sm",disabled:d,onClick:()=>void M("abandon"),children:"Abort"})]}),o.stale&&s.jsx("p",{className:"rounded-md border border-border-subtle bg-surface-subtle px-3 py-2 text-sm text-text-secondary",children:"This run is past its freshness window â findings may be stale. Prefer Redo this step before approving."}),s.jsxs(V,{className:"space-y-4 p-4",children:[s.jsx("p",{className:"text-sm text-text-secondary",children:T==null?void 0:T.body}),d&&!S?s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"}),"Running researchâ¦"]}):S?s.jsx(oqe,{findings:S,selectedKeywords:x,onToggleKeyword:I}):s.jsx("p",{className:"text-sm text-text-secondary",children:"Waiting for findingsâ¦"}),S&&s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"text-sm font-medium text-text-primary",children:(T==null?void 0:T.checkpoint_prompt)||"Review the findings, then continue."}),re&&s.jsx("p",{className:"text-xs text-text-tertiary",children:"Tap chips to adjust the shortlist we carry into the next step."}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(W,{disabled:d,onClick:()=>void M("approve"),children:d?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):"Approve & continue"}),s.jsx(W,{variant:"outline",disabled:d,onClick:()=>void M("redo"),children:"Redo this step"}),s.jsx(W,{variant:"outline",disabled:d,onClick:()=>void M("skip"),children:"Skip"}),te&&s.jsxs(W,{variant:"outline",disabled:d,onClick:()=>z(te),children:[s.jsx(Qt,{className:"mr-1 h-3.5 w-3.5"}),"View in Market Explorer"]})]})]}),f&&s.jsx("p",{className:"text-sm text-intent-danger",children:f})]})]}):E.items.length===0?ee=s.jsx("div",{className:"overflow-auto p-4",children:s.jsxs(V,{className:"p-6 text-center",children:[s.jsx("p",{className:"text-sm text-text-primary",children:"Nothing on the shortlist yet"}),s.jsx("p",{className:"mt-1 text-xs text-text-secondary",children:"Add listings from Catalogue or phrases from Keywords, then Validate shortlist. Or start an ad-hoc idea."}),s.jsx(W,{className:"mt-4",onClick:()=>w(!0),children:"Validate something else"})]})}):ee=s.jsx("div",{className:"overflow-auto p-4",children:s.jsxs(V,{className:"p-6 text-center",children:[s.jsxs("p",{className:"text-sm text-text-primary",children:[E.items.length," ",E.items.length===1?"item":"items"," ready to validate"]}),s.jsx("p",{className:"mt-1 text-xs text-text-secondary",children:"Starts one New Product Validation run per item that doesnât already have a live run."}),s.jsxs("div",{className:"mt-4 flex flex-wrap justify-center gap-2",children:[s.jsx(W,{onClick:()=>void Y(),disabled:d,children:d?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):"Validate shortlist"}),s.jsx(W,{variant:"outline",onClick:()=>w(!0),children:"Validate something else"})]}),f&&s.jsx("p",{className:"mt-3 text-sm text-intent-danger",children:f})]})}
909),s.jsx(Dw,{leftRailOpen:_,onCloseLeftRail:()=>k(!1),rightPanelFilled:!!L,queryBar:s.jsxs(G3,{children:[s.jsx(Y3,{onClick:()=>k(!0)}),s.jsx("span",{className:"text-sm font-medium text-text-primary",children:"New Product Validation"}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-text-secondary",children:(he=o==null?void 0:o.inputs)!=null&&he.keyword?`This run: ${o.inputs.keyword}`:"Shortlist-driven â or validate something else"}),s.jsx(W,{variant:"outline",size:"sm",onClick:()=>{l(null),w(!0)},children:"Validate something else"})]}),leftRail:s.jsxs(Z3,{children:[s.jsxs(pd,{label:"This run",children:[E.items.length===0&&s.jsx("p",{className:"px-1.5 text-[11px] leading-4 text-text-tertiary",children:"Add items from Catalogue or Keywords."}),E.items.map(ae=>{var Ne;const je=((Ne=ae.meta)==null?void 0:Ne.title)||ae.keyword||(ae.external_id?`PLID ${ae.external_id}`:"Item"),$e=ae.playbook_run_id?c.find(ve=>ve.id===ae.playbook_run_id):void 0,J=$e?kL($e):ae.playbook_run_id?"Queued":"Not started";return s.jsx(Yp,{title:String(je),meta:J,active:!!ae.playbook_run_id&&(o==null?void 0:o.id)===ae.playbook_run_id,onClick:()=>{if(ae.playbook_run_id)F(ae.playbook_run_id);else{const ve=NL(ae);ve&&(r(ve),w(!0))}}},ae.id)})]}),s.jsxs(pd,{label:"Past runs",children:[c.length===0&&s.jsx("p",{className:"px-1.5 text-[11px] leading-4 text-text-tertiary",children:"No previous validations."}),c.slice(0,12).map(ae=>{var je;return s.jsx(Yp,{title:((je=ae.inputs)==null?void 0:je.keyword)||"Untitled",meta:`${kL(ae)}${ae.updated_at?` · ${aqe(ae.updated_at)}`:""}`,active:(o==null?void 0:o.id)===ae.id,onClick:()=>{(ae.status_display||ae.status)==="abandoned"?Z(ae):F(ae.id)}},ae.id)})]})]}),canvas:ee,rightPanel:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[s.jsx(J3,{tabs:[{key:"brief",label:"Brief"},{key:"shortlist",label:"Shortlist",badge:E.items.length||void 0}],value:q==="shortlist"?"shortlist":"brief",onChange:ae=>E.setRightTab(ae)}),q==="shortlist"?s.jsx(X3,{items:E.items,onRemove:ae=>void E.remove(ae),onClear:()=>void E.clear(),onValidate:()=>void Y()}):L?s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-3",children:s.jsx(jL,{brief:L,onOpenMe:e,onRestart:()=>w(!0)})}):s.jsx("div",{className:"flex flex-1 items-center justify-center p-6 text-center text-sm text-text-tertiary",children:"The Launch Decision Brief lands here when a run completes â you can keep another item in-step on the canvas."})]})})}const Uy=[{key:"keyword",label:"Keyword",hint:"a search phrase",group:"scope",Icon:Fa,inputKind:"text",inputLabel:"Search keyword",inputPlaceholder:"e.g. fish oil, gaming chair, air fryer"},{key:"by_category",label:"By Category",hint:"a Takealot category",group:"scope",Icon:Nne,inputKind:"category",input
909Label:"Category",inputPlaceholder:"Start typing a category nameâ¦"},{key:"by_brand",label:"By Brand",hint:"everything one brand sells",group:"scope",Icon:Gv,inputKind:"text",inputLabel:"Brand name",inputPlaceholder:"e.g. Solgar, Hisense"},{key:"biggest_sellers",label:"Biggest Sellers",hint:"marketplace bestsellers",group:"scope",Icon:ose,inputKind:"none",inputLabel:"",inputPlaceholder:"",blurb:"Marketplace bestsellers â top sellers across all of Takealot, default rank."},{key:"weak_incumbents",label:"Weak Incumbents",hint:"demand behind thin reviews",group:"lens",Icon:h6,inputKind:"text",inputLabel:"Keyword or category",inputPlaceholder:"e.g. fish oil or health/supplements/fish-oil",blurb:"High-demand listings with thin reviews or mediocre ratings â beatable targets."},{key:"underpriced_outliers",label:"Underpriced Outliers",hint:"priced below the shelf",group:"lens",Icon:Fte,inputKind:"category",inputLabel:"Category",inputPlaceholder:"Start typing a category nameâ¦"},{key:"premium_price_band",label:"Premium Price Band",hint:"the top of a category",group:"lens",Icon:Ute,inputKind:"category",input
909Label:"Category",inputPlaceholder:"Start typing a category nameâ¦"},{key:"fastest_growing",label:"Fastest Growing",hint:"categories adding listings",group:"lens",Icon:Xi,inputKind:"window",inputLabel:"Growth window",inputPlaceholder:"",blurb:"Top listings from the Takealot categories expanding fastest, by listing-count growth."},{key:"new_arrivals",label:"New Arrivals",hint:"first seen recently",group:"lens",Icon:Ht,inputKind:"days",inputLabel:"Listed within",inputPlaceholder:"",blurb:"Listings first seen on Takealot recently (from our snapshot history)."},{key:"product_finder",label:"Product Finder",hint:"filter the whole catalogue",group:"lens",Icon:Si,inputKind:"product_finder",inputLabel:"",inputPlaceholder:"",blurb:"Filter the entire snapshot catalogue by price, reviews, rating, stock, and age."}];function dqe({preset:e,onSelect:t,open:n,onToggle:r}){const a=Uy.find(o=>o.key===e),i=a.Icon;return s.jsxs("div",{className:"relative",children:[s.jsxs("button",{type:"button",onClick:r,className:B("inline-flex items-center gap-1.5 whitespace-nowrap rounded-md border bg-surface px-2.5 py-1.5 text-sm font-medium text-text-primary",n?"border-intent-brand shadow-[0_0_0_4px_rgba(133,84,237,0.16)]":"border-outline-subtle hover:border-outline"),children:[s.jsx(i,{className:"h-3.5 w-3.5 text-intent-brand"}),a.label,n?s.jsx(t0,{className:"h-3.5 w-3.5 text-text-tertiary"}):s.jsx(Pn,{className:"h-3.5 w-3.5 text-text-tertiary"})]}),n&&s.jsxs("div",{className:"absolute left-0 top-[42px] z-20 w-[286px] rounded-xl border border-outline-subtle bg-surface p-1.5 shadow-lg",children:[s.jsx("div",{className:"px-2 pb-1 pt-2 text-[10px] font-semibold uppercase tracking-wider text-text-tertiary",children:"Scopes â what to look at"}),Uy.filter(o=>o.group==="scope").map(o=>s.jsx(SL,{preset:o,active:o.key===e,onSelect:t},o.key)),s.jsx("div",{className:"px-2 pb-1 pt-2.5 text-[10px] font-semibold uppercase tracking-wider text-text-tertiary",children:"Lenses â how to look at it"}),Uy.filter(o=>o.group==="lens").map(o=>s.jsx(SL,{preset:o,active:o.key===e,onSelect:t},o.key))]})]})}function SL({preset:e,active:t,onSelect:n}){const r=e.Icon;return s.jsxs("button",{type:"button",onClick:()=>n(e.key),className:B("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left",t?"bg-surface-brandSubtle":"hover:bg-surface-subtle"),children:[s.jsx(r,{className:B("h-3.5 w-3.5 shrink-0",t?"text-intent-brand":"text-text-tertiary")}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:B("text-sm text-text-primary",t?"font-semibold":"font-medium"),children:e.label}),s.jsx("div",{className:"text-[11px] leading-4 text-text-tertiary",children:e.hint})]}),t&&s.jsx(fn,{className:"h-3.5 w-3.5 shrink-0 text-intent-brand"})]})}function hqe({rollup:e,estLocked:t,onFilter:n,onColumns:r,onExport:a,onSave:i,saveDisabled:o,extra:l}){var u,d,h;const c=e?[["Listings",String(e.total_listings)],["Median price",e.price.median!=null?ge(e.price.median):"â"],["In stock",e.in_stock_pct!=null?`${Math.round(e.in_stock_pct)}%`:"â"],["Best",((u=e.opportunity)==null?void 0:u.max)!=null?String(e.opportunity.max):"â"],["Est rev 30d",t?"â":e.total_est_revenue_rand_30d!=null?ge(e.total_est_revenue_rand_30d):"â"],["Volume",((d=e.keyword_volume)==null?void 0:d.avg_monthly_searches)!=null?`${e.keyword_volume.avg_monthly_searches.toLocaleString()}/mo`:"â"],["Wishlist 30d",((h=e.wishlist)==null?void 0:h.median_30d)!=null?`~${e.wishlist.median_30d.toLocaleString()}`:"â"]]:[];return s.jsxs("div",{className:"flex shrink-0 items-center gap-5 border-b border-outline-subtle bg-surface px-5 py-3",children:[c.map(([f,m])=>s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[11px] leading-4 text-text-tertiary",children:f}),s.jsx("div",{className:"mt-px whitespace-nowrap text-[15px] font-semibold text-text-primary",children:m})]},f)),s.jsx("div",{className:"flex-1"}),l,s.jsxs("div",{className:"flex shrink-0 gap-3.5 text-xs font-medium text-text-secondary",children:[n&&s.jsxs("button",{type:"button",onClick:n,className:"inline-flex items-center gap-1 hover:text-text-primary",children:[s.jsx(aF,{className:"h-3.5 w-3.5"})," Filter"]}),r&&s.jsxs("button",{type:"button",onClick:r,className:"inline-flex items-center gap-1 hover:text-text-primary",children:[s.jsx($2,{className:"h-3.5 w-3.5"})," Columns"]}),a&&s.jsxs("button",{type:"button",onClick:a,className:"inline-flex items-center gap-1 hover:text-text-primary",children:[s.jsx(Dr,{className:"h-3.5 w-3.5"})," Export"]}),i&&s.jsxs("button",{type:"button",onClick:i,disabled:o,className:B("inline-flex items-center gap-1",o?"cursor-not-allowed text-text-tertiary":"text-intent-brand hover:text-intent-brandHover"),children:[s.jsx(ko,{className:"h-3.5 w-3.5"})," Save"]})]})]})}function fqe(e){const t=e.trim().toLowerCase(),n={},r=t.match(/(?:min|at least|over|â¥|>=)\s*(\d+)\s*reviews?/),a=t.match(/(?:drop|under|below|<|â¤|<=)\s*(\d+)\s*reviews?/),i=t.match(/(?:rating|stars?).*?(?:â¥|>=|at least|over)\s*([0-9.]+)/),o=/\bin[- ]?stock\b/.test(t),l=/sort.*est\s*rev/.test(t),c=/sort.*opportunit/.test(t),u=/sort.*price/.test(t),d=t.match(/top\s*(\d+)/);a&&(n.filters={...n.filters,min_reviews:Number(a[1])+1}),r&&(n.filters={...n.filters,min_reviews:Number(r[1])}),i&&(n.filters={...n.filters,min_rating:Number(i[1])}),o&&(n.filters={...n.filters,in_stock_only:!0}),l?n.sort={by:"est_revenue_rand_30d",dir:"desc"}:c?n.sort={by:"opportunity_score",dir:"desc"}:u&&(n.sort={by:"selling_price",dir:t.includes("high")?"desc":"asc"}),d&&(n.limit=Number(d[1]));const h=t.match(/drop.*under\s*(\d+)\s*reviews?/);return h&&(n.filters={...n.filters,min_reviews:Number(h[1])}),n}const mqe=["drop under 50 reviews","sort by est revenue","only in stock"];function pqe({searchId:e,disabled:t,onRefined:n,onHideMyCatalogue:r,hideMyCatalogue:a}){const[i,o]=p.useState(""),[l,c]=p.useState(!1),[u,d]=p.useState(!1);async function h(f){if(!(!e||!f.trim())){c(!0);try{const m=fqe(f),x=await $t.deriveSearch(e,m);n(x),o(""),d(!1)}catch(m){console.warn("[market-explorer] refine failed",m)}finally{c(!1)}}}return s.jsxs("div",{className:"flex shrink-0 flex-wrap items-center gap-2 border-b border-outline-subtle bg-surface-subtle/70 px-5 py-2",children:[s.jsx("span",{className:"whitespace-nowrap text-[11px] leading-4 text-text-tertiary",children:"Refine â free"}),mqe.map(f=>s.jsx("button",{type:"button",disabled:t||!e||l,onClick:()=>void h(f),className:"rounded-md border border-outline-brand bg-surface px-2 py-0.5 text-xs text-intent-brand hover:bg-surface-brandSubtle disabled:opacity-50",children:f},f)),r&&s.jsx("button",{type:"button",onClick:r,className:B("rounded-md border bg-surface px-2 py-0.5 text-xs",a?"border-intent-brand bg-surface-brandSubtle text-intent-brand":"border-outline-brand text-intent-brand hover:bg-surface-brandSubtle"),children:"hide brands I stock"}),u?s.jsxs("form",{className:"flex min-w-[180px] flex-1 items-center gap-1",onSubmit:f=>{f.preventDefault(),h(i)},children:[s.jsx("input",{autoFocus:!0,value:i,onChange:f=>o(f.target.value),placeholder:"Type a refinementâ¦",disabled:t||!e||l,className:"h-7 min-w-0 flex-1 rounded-md border border-outline-subtle bg-surface px-2 text-xs text-text-primary outline-none focus:border-outline-brand focus-visible:shadow-focus"}),s.jsx("button",{type:"submit",disabled:t||!e||l||!i.trim(),className:"text-xs font-medium text-intent-brand disabled:opacity-50",children:l?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):"Apply"})]}):s.jsxs("button",{type:"button",onClick:()=>d(!0),className:"inline-flex items-center gap-1 rounded-md border border-outline-subtle bg-surface px-2 py-0.5 text-xs text-text-secondary hover:text-text-primary",children:[s.jsx(Ht,{className:"h-3 w-3"}),"Type a refinementâ¦"]})]})}function xqe({plid:e,title:t,suggestedPrice:n,suggestedRrp:r,open:a,onClose:i}
909){const[o,l]=p.useState([]),[c,u]=p.useState(""),[d,h]=p.useState(""),[f,m]=p.useState(""),[x,g]=p.useState(""),[y,b]=p.useState("1"),[v,w]=p.useState(""),[_,k]=p.useState("5"),[j,N]=p.useState(!1),[E,A]=p.useState(null),[C,T]=p.useState(null),[S,O]=p.useState("syncing"),[R,I]=p.useState("basic"),[$,P]=p.useState("compete"),[F,Z]=p.useState(""),[D,H]=p.useState(""),[Y,M]=p.useState(""),[z,G]=p.useState(""),[te,re]=p.useState(!1),[L,q]=p.useState(null);p.useEffect(()=>{a&&(A(null),T(null),N(!1),O("syncing"),q(null),H(""),M(""),G(""),h(""),m(n!=null?String(n):""),g(r!=null?String(r):""),b("1"),k("5"),K.marketSellerOptions().then(X=>{const he=X.sellers??[];l(he),u(ae=>{var je;return ae||(((je=he[0])==null?void 0:je.slug)??"")})}).catch(()=>l([])))},[a,n,r]),p.useEffect(()=>{const X=o.find(he=>he.slug===c);X&&X.primary_warehouse_id!=null&&w(String(X.primary_warehouse_id))},[c,o]),p.useEffect(()=>{if(!C||S!=="syncing")return;const X=d.trim().toLowerCase();let he=!0,ae=0;const je=async()=>{if(he){ae+=1;try{if(((await K.enrollableOffers(C,{search:d.trim(),limit:20})).offers??[]).some(ve=>(ve.sku??"").toLowerCase()===X)&&he){Z(f||""),O("ready");return}}catch{}if(he){if(ae>=10){O("timeout");return}$e=setTimeout(je,4e3)}}};let $e=setTimeout(je,3e3);return()=>{he=!1,clearTimeout($e)}},[C,S,d,f]);async function me(){var he;if(!C||te)return;const X=Number(F);if(!Number.isFinite(X)||X<=0){q("Enter a floor price (whole rand).");return}re(!0),q(null);try{const ae=await K.enrolSubscription(C,{seller_sku:d.trim(),tier:R,mode:$,min_price:Math.round(X),preferred_price:D.trim()===""?null:Math.round(Number(D))}),je=Y.trim()===""?null:Number(Y),$e=z.trim()===""?null:Number(z);ae.subscription_id&&(je!=null||$e!=null)&&await K.updateSubscription(C,ae.subscription_id,{min_margin_pct:je,min_roi_pct:$e}),O("enrolled")}catch(ae){const je=ae;q(((he=je.body)==null?void 0:he.message)||je.message||"Couldn't enrol â you may be out of repricer slots on this tier.")}finally{re(!1)}}const ee=!!e&&!!c&&d.trim()!==""&&Number(f)>0&&Number(x)>0&&Number.isInteger(Number(y))&&Number(y)>=0&&Number(v)>0&&!j;async function ne(){if(ee){N(!0),A(null);try{await K.addOfferFromPlid({plid:String(e),seller_slug:c,sku:d.trim(),selling_price:Number(f),rrp:Number(x),stock_qty:Number(y),warehouse_id:Number(v),leadtime_days:Number(_)}),T(c)}catch(X){const he=X;A(he.code==="barcode_unresolved"?"This product has no barcode (EAN) on its Takealot page, so an offer can't be matched to it. Try another product.":he.code==="validation_error"?"Some fields are invalid â check price, RRP, stock and warehouse.":he.message||"Couldn't add the offer.")}finally{N(!1)}}}return s.jsx(Cr,{open:a,onOpenChange:X=>!X&&i(),children:s.jsxs(mr,{side:"right",size:"md",children:[s.jsxs(Er,{children:[s.jsx(xr,{children:"Add offer"}),t&&s.jsx(Mr,{className:"truncate",title:t,children:t})]}),s.jsx(pr,{className:"p-4 space-y-4",children:C?s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"rounded border border-success-border bg-success-bg p-3 text-sm text-success-text",children:"Offer created on Takealot."}),S==="syncing"&&s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"}),"Syncing the offer so you can protect it with the repricerâ¦"]}),S==="timeout"&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-sm text-text-secondary",children:"Still syncing â it can take a moment. You can enrol it in the repricer from Automations once it appears."}),s.jsx(st,{to:`/sellers/${C}/automations`,className:"inline-flex items-center gap-2 text-sm font-medium text-text-brand hover:underline",children:"Open Automations â"})]}),S==="enrolled"&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-sm text-success-text",children:"Enrolled in the repricer â it'll keep your price competitive within your floor."}),s.jsx(st,{to:`/sellers/${C}/automations`,className:"inline-flex items-center gap-2 text-sm font-medium text-text-brand hover:underline",children:"View in Automations â"})]}),S==="ready"&&s.jsxs("div",{className:"space-y-3",children:[s.jsx("div",{className:"text-xs font-medium uppercase tracking-wider text-text-secondary",children:"Protect it with the repricer"}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-medium text-text-secondary",children:"Tier"}),s.jsxs(Tt,{value:R,onChange:X=>I(X.target.value),children:[s.jsx("option",{value:"basic",children:"Basic (60 min)"}),s.jsx("option",{value:"standard",children:"Standard (25 min)"}),s.jsx("option",{value:"boosted",children:"Boosted (15 min)"}),s.jsx("option",{value:"super_boosted",children:"Super Boosted (10 min)"})]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-medium text-text-secondary",children:"Mode"}),s.jsxs(Tt,{value:$,onChange:X=>P(X.target.value),children:[s.jsx("option",{value:"compete",children:"Compete (undercut R1)"}),s.jsx("option",{value:"share",children:"Share (match)"})]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-medium text-text-secondary",children:"Floor (R)"}),s.jsx(Re,{type:"number",min:"1",step:"1",value:F,onChange:X=>Z(X.target.value)})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-medium text-text-secondary",children:"Preferred (R)"}),s.jsx(Re,{type:"number",min:"1",step:"1",value:D,onChange:X=>H(X.target.value),placeholder:"optional"})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-medium text-text-secondary",children:"Min margin %"}),s.jsx(Re,{type:"number",min:"0",max:"99",step:"0.5",value:Y,onChange:X=>M(X.target.value),placeholder:"optional"})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-medium text-text-secondary",children:"Min ROI %"}),s.jsx(Re,{type:"number",min:"0",step:"1",value:z,onChange:X=>G(X.target.value),placeholder:"optional"})]})]}),L&&s.jsx("div",{className:"rounded border border-error-border bg-error-bg p-2 text-sm text-error-text",children:L}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(W,{type:"button",onClick:me,disabled:te,children:te?"Enrollingâ¦":"Enrol in repricer"}),s.jsx(st,{to:`/sellers/${C}/automations`,className:"text-sm text-text-secondary hover:underline",children:"Skip"})]})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-medium text-text-secondary",children:"Seller"}),s.jsxs(Tt,{value:c,onChange:X=>u(X.target.value),children:[o.length===0&&s.jsx("option",{value:"",children:"No sellers available"}),o.map(X=>s.jsx("option",{value:X.slug,children:X.display_name},X.slug))]})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-medium text-text-secondary",children:"Your SKU"}),s.jsx(Re,{value:d,onChange:X=>h(X.target.value),placeholder:"e.g. ABC-001"})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-medium text-text-secondary",children:"Selling price (R)"}),s.jsx(Re,{type:"number",min:"0",step:"0.01",value:f,onChange:X=>m(X.target.value)})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-medium text-text-secondary",children:"RRP (R)"}),s.jsx(Re,{type:"number",min:"0",step:"0.01",value:x,onChange:X=>g(X.target.value)})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-medium text-text-secondary",children:"Stock qty"}),s.jsx(Re,{type:"number",min:"0",step:"1",value:y,onChange:X=>b(X.target.value)})]}),s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-medium text-text-secondary",children:"Lead time (days)"}
909),s.jsx(Re,{type:"number",min:"0",step:"1",value:_,onChange:X=>k(X.target.value)})]}),s.jsxs("label",{className:"col-span-2 block",children:[s.jsx("span",{className:"mb-1 block text-xs font-medium text-text-secondary",children:"Warehouse ID"}),s.jsx(Re,{type:"number",min:"1",step:"1",value:v,onChange:X=>w(X.target.value),placeholder:"auto from seller"})]})]}),s.jsx("p",{className:"text-[11px] leading-snug text-text-tertiary",children:"This creates a real offer on Takealot against this product (it must have a matchable barcode). Double-check the price before adding."}),E&&s.jsx("div",{className:"rounded border border-error-border bg-error-bg p-2 text-sm text-error-text",children:E})]})}),s.jsxs(ml,{children:[s.jsx(W,{type:"button",variant:"outline",onClick:i,children:C?"Done":"Cancel"}),!C&&s.jsx(W,{type:"button",onClick:ne,disabled:!ee,children:j?"Addingâ¦":"Add offer"})]})]})})}function xG({plid:e,title:t,suggestedPrice:n,suggestedRrp:r}){const[a,i]=p.useState(!1);return e==null?null:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",title:"Add this product as your offer",onClick:o=>{o.stopPropagation(),i(!0)},className:"inline-flex items-center justify-center rounded p-1 text-text-tertiary transition-colors hover:bg-surface-brandSubtle hover:text-text-brand",children:s.jsx(Wte,{className:"h-4 w-4"})}),s.jsx("span",{style:{display:"contents"},onClick:o=>o.stopPropagation(),children:s.jsx(xqe,{plid:e,title:t,suggestedPrice:n,suggestedRrp:r,open:a,onClose:()=>i(!1)})})]})}function gqe({row:e,estLocked:t,onAddToShortlist:n,alreadyShortlisted:r}){if(!e)return s.jsx("div",{className:"flex flex-1 items-center justify-center p-6 text-center text-sm text-text-tertiary",children:"Click a row to inspect opportunity, price history, and actions."});const a=e.opportunity_factors,i=[["Demand",(a==null?void 0:a.demand)??null,"brand"],["Beatability",(a==null?void 0:a.beatability)??null,"success"],["Margin",(a==null?void 0:a.margin_headroom)??null,"warning"]],o=e.price_history||[],l=o[0],c=o[o.length-1],u=l&&c&&l>0?Math.round((c-l)/l*100):null,d=o.length?Math.max(...o):0,h=o.length?Math.min(...o):0,f=e.plid?`https://www.takealot.com/${e.slug||"x"}/PLID${e.plid}`:null,m=e.opportunity_score!=null&&e.opportunity_score>=67?"Best in this result":"Opportunity",x=[["Price",e.selling_price!=null?ge(e.selling_price):"â"],["Rating",e.star_rating!=null?`${e.star_rating.toFixed(1)} â
`:"â"],["Reviews",e.reviews!=null?e.reviews.toLocaleString():"â"],["Est sales",t?"â":e.est_units_30d!=null?`${e.est_units_30d.toLocaleString()}/mo`:"â"],["Est rev 30d",t?"â":e.est_revenue_rand_30d!=null?ge(e.est_revenue_rand_30d):"â"],["Wishlist 30d",e.wishlist_30_days!=null?e.wishlist_30_days.toLocaleString():"â"],["Search volume",e.avg_monthly_searches!=null?`${e.avg_monthly_searches.toLocaleString()}/mo${e.primary_keyword?` · ${e.primary_keyword}`:""}`:e.primary_keyword?e.primary_keyword:"â"],["PLID",e.plid!=null?String(e.plid):"â"]];return s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[s.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-4",children:[s.jsxs("div",{className:"flex items-start gap-2.5",children:[e.image_url?s.jsx("img",{src:e.image_url,alt:"",className:"h-[46px] w-[46px] rounded object-contain bg-surface-subtle"}):s.jsx("div",{className:"grid h-[46px] w-[46px] place-items-center rounded bg-surface-subtle text-text-tertiary",children:s.jsx(nx,{className:"h-3.5 w-3.5"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-sm font-semibold leading-5 text-text-primary",children:e.title||"â"}),s.jsx("div",{className:"mt-0.5 text-[11px] leading-4 text-text-tertiary",children:[e.brand,e.plid!=null?`PLID ${e.plid}`:null].filter(Boolean).join(" · ")})]})]}),s.jsxs("div",{className:"mt-3.5 flex items-baseline gap-2.5",children:[s.jsx("span",{className:B("text-[28px] font-semibold",e.opportunity_score!=null&&e.opportunity_score>=67?"text-intent-success":"text-text-primary"),children:e.opportunity_score??"â"}),s.jsx("span",{className:"whitespace-nowrap text-xs text-text-secondary",children:m})]}),s.jsx("div",{className:"mt-2.5 flex flex-col gap-2",children:i.map(([g,y,b])=>s.jsxs("div",{children:[s.jsx("div",{className:"whitespace-nowrap text-xs text-text-secondary",children:g}),s.jsx(Nf,{className:"mt-1",value:Math.round((y??0)*100),valueLabel:y!=null?`${Math.round(y*100)}%`:"â",intent:b})]},g))}),s.jsx("div",{className:"mt-4 grid grid-cols-2 gap-x-3.5 gap-y-3 border-t border-outline-subtle pt-3.5",children:x.map(([g,y])=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] leading-4 text-text-tertiary",children:g}),s.jsx("div",{className:"mt-px whitespace-nowrap text-sm font-semibold text-text-primary",children:y})]},g))}),e.wishlist_30_days!=null&&s.jsx("p",{className:"mt-2 text-[11px] leading-4 text-text-tertiary",children:"Wishlist is product-level â every seller on this PLID sees the same count."}),o.length>=2&&s.jsxs("div",{className:"mt-4 border-t border-outline-subtle pt-3.5",children:[s.jsxs("div",{className:"mb-1.5 text-[11px] leading-4 text-text-tertiary",children:["Price, last ",o.length," snapshots"]}),s.jsx("div",{className:"flex h-10 items-end gap-1",children:o.map((g,y)=>{const b=Math.max(1,d-h),v=Math.round((g-h)/b*100);return s.jsx("div",{className:"flex-1 rounded-t bg-brand-500/75",style:{height:`${Math.max(12,v)}%`},title:`R ${g}`},y)})}),s.jsxs("div",{className:"mt-1 text-[11px] leading-4 text-text-tertiary",children:[ge(l)," â ",ge(c),u!=null?` · ${u>0?"up":"down"} ${Math.abs(u)}%`:""]})]})]}),s.jsxs("div",{className:"flex flex-col gap-2 border-t border-outline-subtle p-4",children:[n&&s.jsxs(W,{onClick:n,disabled:r,className:"w-full justify-center",children:[s.jsx(vte,{className:"h-4 w-4"}),r?"On shortlist":"Add to shortlist"]}),s.jsxs("div",{className:"flex gap-2",children:[e.plid!=null&&s.jsx(Kd,{plid:e.plid,sellPrice:e.selling_price,title:e.title}),s.jsx(xG,{plid:e.plid,title:e.title,suggestedPrice:e.selling_price}),f&&s.jsx("a",{href:f,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center justify-center rounded-md border border-outline px-2.5 py-1.5 text-text-secondary hover:text-intent-brand",title:"Open on Takealot",children:s.jsx(Qt,{className:"h-3.5 w-3.5"})})]})]})]})}const yqe=["yoga mat","air fryer","fish oil","gazebo","baby monitor"],bqe=["browse","search","expand","saved"],Iv=[{key:"hot",label:"Hot",blurb:"Growing product phrases, diversified by department â fad risk labelled, not buried"},{key:"emerging",label:"Emerging",blurb:"Near-zero history, now real volume â early demand signals"}
909,{key:"new",label:"New",blurb:"First seen in our cache in the last 14 days"},{key:"seasonal",label:"Seasonal",blurb:"Peak month is now or soon â time ads and stock ahead of the spike"},{key:"volume",label:"Highest volume",blurb:"Biggest browseable phrases (incl. 1-word Takealot-ads heads) â widest net when taxonomy filters feel tight"},{key:"opportunities",label:"Opportunities",blurb:"Volume ⥠500, top-quartile demand per listing in the department, soft page 1, price that can carry fees â ranked by opportunity score"}],gG=Iv.map(e=>e.key),yG={LOW:1,MEDIUM:2,HIGH:3};function vqe(e){if(!e)return null;const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleDateString("en-ZA",{day:"numeric",month:"short"})}function wqe(e,t){var n;return(n=e==null?void 0:e.shelf)!=null&&n.category_id?e.shelf:t!=null&&t.category_id?{category_id:t.category_id,category_name:t.category_name,category_slug:null,department_slug:t.department_slug,listings:t.shelf_listings,captured_at:t.shelf_captured_at,history:[]}:null}function bG({shelf:e,compact:t}){if(!(e!=null&&e.category_id))return null;const n=o=>o.toLocaleString("en-ZA"),r=vqe(e.captured_at),a=(e.history||[]).map(o=>o.listings),i=e.category_name||"this category";return s.jsxs("div",{className:t?"":"rounded-lg border border-outline-subtle bg-surface-subtle/40 px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-text-tertiary",children:"Takealot shelf"}),s.jsxs("div",{className:"mt-0.5 text-body-sm font-medium text-text-primary",children:[e.listings!=null?`${n(e.listings)} listings`:"No snapshot yet",e.listings!=null&&s.jsxs("span",{className:"font-normal text-text-secondary",children:[" in ",i]})]}),s.jsxs("div",{className:"mt-0.5 text-body-xs text-text-tertiary",children:["Category shelf, not this search results page",r?` · ${r}`:""]}),!t&&a.length>=2&&s.jsx("div",{className:"mt-2",children:s.jsx(Ws,{data:a,width:220,height:28,className:"text-text-secondary"})})]})}function _qe({item:e}){if(e.shelf_listings==null)return s.jsx("span",{className:"text-text-tertiary",children:"â"});const t=e.volume!=null&&e.shelf_listings>0?Math.round(e.volume/e.shelf_listings):null;return s.jsxs("span",{className:"text-text-secondary",title:t!=null?`~${t.toLocaleString("en-ZA")} searches per listing in ${e.category_name||"this category"} (category shelf, not this SERP)`:"Category listing count â not this search results page",children:[e.shelf_listings.toLocaleString("en-ZA"),e.category_name&&s.jsx("span",{className:"block text-[10px] font-normal text-text-tertiary",children:e.category_name})]})}function kqe(){return{key:"shelf",label:"Shelf",sortable:!0,align:"right",hideBelow:"lg",getValue:e=>e.shelf_listings,render:e=>s.jsx(_qe,{item:e})}}function jqe({data:e}){const t=i=>i.toLocaleString("en-ZA");if(e==null||e==="loading")return s.jsxs("div",{className:"flex items-center gap-2 text-body-xs text-text-secondary",children:[s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"})," Loading historyâ¦"]});const n=e.volume_series,r=e.rank_series,a=n.length?n.reduce((i,o)=>o.value>i.value?o:i):null;return s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"mb-1 text-body-xs text-text-tertiary",children:["Search volume â ",n.length," months"]}),n.length>=2?s.jsxs(s.Fragment,{children:[s.jsx(Ws,{data:n.map(i=>i.value),width:240,height:44,className:"text-intent-brand"}),s.jsxs("div",{className:"mt-1 text-body-xs text-text-secondary",children:["now ",t(n[n.length-1].value),a&&` · peak ${t(a.value)} (${a.label})`]})]}):s.jsx("div",{className:"text-body-xs text-text-secondary",children:"No volume history."})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"mb-1 text-body-xs text-text-tertiary",children:["Competition (listings tracked) â ",r.length," snapshots"]}),r.length>=2?s.jsxs(s.Fragment,{children:[s.jsx(Ws,{data:r.map(i=>i.listings),width:240,height:44,className:"text-text-secondary"}),s.jsxs("div",{className:"mt-1 text-body-xs text-text-secondary",children:[r[0].listings," â ",r[r.length-1].listings," listings · best rank #",Math.min(...r.map(i=>i.best_rank))+1]})]}):s.jsx("div",{className:"text-body-xs text-text-secondary",children:"No rank history yet â run a Catalogue search for this keyword to start tracking who ranks."})]})]})}function Mw({saved:e,onClick:t,compact:n}){const r=e?yte:e0;return s.jsx("button",{type:"button",onClick:t,title:e?"Saved â click to remove":"Save to watchlist",className:`rounded p-1 transition hover:bg-surface-subtle ${e?"text-intent-brand":"text-text-tertiary hover:text-text-primary"} ${n?"":"border border-outline-subtle"}`,children:s.jsx(r,{className:n?"h-3.5 w-3.5":"h-4 w-4"})})}function e2(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}function dy({label:e,value:t,sub:n}){return s.jsxs(V,{className:"p-3",children:[s.jsx("div",{className:"text-body-xs text-text-tertiary",children:e}),s.jsx("div",{className:"mt-0.5 text-title-sm font-semibold text-text-primary",children:t}),n!=null&&s.jsx("div",{className:"mt-0.5 text-body-xs text-text-secondary",children:n})]})}function Nqe({item:e}){if(!e||e.demand_supply==null&&e.page1_median_reviews==null&&e.opportunity_score==null&&e.est_units_30d_top36==null)return null;const t=e.takealot_results!=null?`${e.takealot_results.toLocaleStr
909ing("en-ZA")} Takealot results`:void 0;return s.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-3",children:[e.opportunity_score!=null&&s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface-subtle/40 px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-text-tertiary",children:"Opportunity"}),s.jsx("div",{className:"mt-0.5 text-body-sm font-medium text-text-primary",children:e.opportunity_score})]}),e.est_units_30d_top36!=null&&s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface-subtle/40 px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-text-tertiary",children:"Page-1 est. sales"}),s.jsxs("div",{className:"mt-0.5 text-body-sm font-medium text-text-primary",children:[Math.round(e.est_units_30d_top36).toLocaleString("en-ZA"),"/mo"]})]}),s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface-subtle/40 px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-text-tertiary",children:"Demand / listing"}),s.jsx("div",{className:"mt-0.5 text-body-sm font-medium text-text-primary",title:e.demand_supply_source==="shelf"?"Using category shelf size â keyword SERP not captured yet":t,children:e.demand_supply==null?"â":e.demand_supply.toFixed(2)})]}),s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface-subtle/40 px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-text-tertiary",children:"Page 1"}),s.jsxs("div",{className:"mt-0.5 text-body-sm font-medium text-text-primary",children:[e.page1_median_reviews==null?"â":`${Math.round(e.page1_median_reviews).toLocaleString("en-ZA")} reviews`,e.page1_depth?s.jsx("span",{className:"ml-1 text-body-xs font-normal text-text-tertiary",children:e.page1_depth}):null]})]})]})}function $w({level:e}){if(!e)return s.jsx("span",{className:"text-text-tertiary",children:"â"});const t=e.toUpperCase(),n=t==="HIGH"?"border-outline-warning bg-surface-warningSubtle text-text-primary":t==="LOW"?"border-outline-success bg-surface-successSubtle text-text-success":"border-outline-subtle bg-surface-subtle text-text-secondary";return s.jsx("span",{className:`inline-block rounded-full border px-2 py-0.5 text-body-xs font-medium ${n}`,children:t[0]+t.slice(1).toLowerCase()})}const Sqe={down:0,flat:1,up:2};function Cqe(e){const t=r=>r==null?"â":r.toLocaleString("en-ZA"),n=[];if(e.onTogglePick){const r=e.onTogglePick;n.push({key:"select",label:"",className:"w-8",stopRowClick:!0,render:a=>{var i;return s.jsx("input",{type:"checkbox",checked:((i=e.picked)==null?void 0:i.has(a.keyword.toLowerCase()))??!1,onChange:()=>r({keyword:a.keyword,volume:a.volume,competition:a.competition}),"aria-label":`Select ${a.keyword}`})}})}return n.push({key:"keyword",label:"Keyword",sortable:!0,getValue:r=>r.keyword.toLowerCase(),render:r=>s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{className:"text-left text-text-primary",children:r.keyword}),r.is_emerging&&s.jsx("span",{className:"rounded-full bg-surface-brandSubtle/60 px-1.5 py-0.5 text-[10px] font-medium text-intent-brand",children:"emerging"}),r.is_spike&&s.jsx("span",{className:"rounded-full border border-outline-warning bg-surface-warningSubtle px-1.5 py-0.5 text-[10px] font-medium text-text-primary",title:"Latest month is a spike vs recent history â fad risk",children:"fad risk"}),r.in_corpus&&s.jsx("span",{className:"rounded-full border border-outline-subtle px-1.5 py-0.5 text-[10px] text-text-tertiary",title:"Seen in Takealot ads keyword suggestions",children:"ads"}),r.in_autocomplete===!0&&s.jsx("span",{className:"rounded-full border border-outline-subtle px-1.5 py-0.5 text-[10px] text-text-tertiary",title:"Takealot autocomplete has returned this phrase â shoppers type it",children:"typed"}),r.in_autocomplete===!1&&s.jsx("span",{className:"rounded-full bg-surface-subtle px-1.5 py-0.5 text-[10px] text-text-tertiary",title:"Checked Takealot autocomplete â not seen there yet",children:"not typed"}),r.intent&&r.intent!=="product"&&s.jsx("span",{className:"rounded-full bg-surface-subtle px-1.5 py-0.5 text-[10px] text-text-tertiary",children:r.intent})]})},{key:"trend",label:"Trend",sortable:!0,hideBelow:"sm",className:"text-center",getValue:r=>r.trend_3mo?Sqe[r.trend_3mo]??null:null,render:r=>s.jsx(Ws,{data:r.sparkline,width:72,height:18,className:"text-intent-brand mx-auto"})},{key:"volume",label:"Searches/mo",sortable:!0,align:"right",getValue:r=>r.volume,render:r=>s.jsx("span",{className:"text-text-secondary",children:t(r.volume)})},{key:"yoy",label:"YoY",sortable:!0,align:"right",hideBelow:"md",getValue:r=>r.yoy_change_pct,render:r=>s.jsx("span",{className:(r.yoy_change_pct??0)>5?"text-text-success":(r.yoy_change_pct??0)<-5?"text-text-error":"text-text-tertiary",children:r.yoy_change_pct==null?"â":`${r.yoy_change_pct>0?"+":""}${r.yoy_change_pct}%`})},{key:"competition",label:"Ad competition",sortable:!0,hideBelow:"lg",className:"text-center",title:"Advertiser competition on search in South Africa â not how many Takealot listings compete",getValue:r=>r.competition?yG[r.competition.toUpperCase()]??null:null,render:r=>s.jsx($w,{level:r.competition})},{key:"score",label:"Score",sortable:!0,align:"right",title:"Demand (search volume, Takealot est-sales, autocomplete) à beatability à margin room à ads-fit. Blank when we have no Takealot results count.",getValue:r=>r.opportunity_score,render:r=>s.jsx("span",{className:"text-text-primary font-medium",children:r.opportunity_score==null?"â":r.opportunity_score})},{key:"demand",label:"Demand / listing",sortable:!0,hideBelow:"md",align:"right",title:"Monthly searches divided by Takealot results. Falls back to the Market Map shelf when we have no keyword SERP yet.",getValue:r=>r.demand_supply,render:r=>s.jsx("span",{className:"text-text-secondary",title:r.demand_supply==null?"No Takealot supply signal yet":r.demand_supply_source==="shelf"?`Using category shelf (${t(r.shelf_listings)} listings) â keyword SERP not captured`:`${t(r.takealot_results)} Takealot results`,children:r.demand_supply==null?"â":r.demand_supply.toFixed(2)})},{key:"page1",label:"Page 1",sortable:!0,hideBelow:"lg",className:"text-center",title:"Median reviews of the current top 36. Under 50 is soft; 150+ is entrenched.",getValue:r=>r.page1_median_reviews,render:r=>r.page1_median_reviews==null?s.jsx("span",{className:"text-text-tertiary",children:"â"}):s.jsxs("span",{className:r.page1_depth==="soft"?"text-text-success":r.page1_depth==="entrenched"?"text-text-tertiary":"text-text-secondary",title:r.page1_median_price!=null?`Median page-1 price R${Math.round(r.page1_median_price).toLocaleStr
909ing("en-ZA")}`:void 0,children:[t(Math.round(r.page1_median_reviews)),r.page1_depth?s.jsx("span",{className:"ml-1 text-[10px] text-text-tertiary",children:r.page1_depth}):null]})},kqe(),{key:"actions",label:"",align:"right",className:"whitespace-nowrap",stopRowClick:!0,render:r=>s.jsxs(s.Fragment,{children:[s.jsx(Mw,{saved:e.saved.has(r.keyword.toLowerCase()),onClick:()=>e.onToggleSave(r.keyword),compact:!0}),s.jsx("button",{type:"button",onClick:()=>e.onOpenInCatalogue(r.keyword),className:"ml-1 rounded px-2 py-1 text-body-xs text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary",title:"Open in Catalogue",children:s.jsx(gf,{className:"h-3.5 w-3.5"})})]})}),n}function CL(e){const t=[],n=new Set;for(const r of String(e||"").split(",")){const a=r.trim();!a||n.has(a)||(n.add(a),t.push(a))}return t}function xj(e){return e.length?e.join(","):""}function EL({label:e,allLabel:t,options:n,selected:r,onChange:a,disabled:i}){var u;const o=p.useMemo(()=>new Set(r),[r]),l=r.length===0?t:r.length===1?((u=n.find(d=>d.value===r[0]))==null?void 0:u.label)||r[0]:`${r.length} selected`,c=d=>{o.has(d)?a(r.filter(h=>h!==d)):a([...r,d])};return s.jsxs("details",{className:B("relative",i&&"pointer-events-none opacity-50"),children:[s.jsxs("summary",{className:B("list-none inline-flex cursor-pointer items-center gap-1 rounded-md border border-outline-subtle bg-surface px-2 py-1 text-body-xs text-text-secondary",r.length>0&&"border-outline text-text-primary"),title:e,children:[s.jsxs("span",{className:"max-w-[11rem] truncate",children:[s.jsxs("span",{className:"text-text-tertiary",children:[e,": "]}),l]}),s.jsx(Pn,{className:"h-3 w-3 shrink-0 text-text-tertiary"})]}),s.jsxs("div",{className:"absolute left-0 z-30 mt-1 max-h-64 w-64 overflow-y-auto rounded-md border border-outline-subtle bg-surface p-2 shadow-md",children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2 px-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-tertiary",children:e}),r.length>0&&s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary",onClick:()=>a([]),children:"Clear"})]}),n.length===0?s.jsx("p",{className:"px-1 py-2 text-body-xs text-text-tertiary",children:"No options yet"}):n.map(d=>s.jsxs("label",{className:"flex cursor-pointer items-center gap-2 rounded px-1 py-1 text-body-xs text-text-secondary hover:bg-surface-subtle hover:text-text-primary",children:[s.jsx("input",{type:"checkbox",className:"rounded border-outline",checked:o.has(d.value),onChange:()=>c(d.value)}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:d.label}),d.count!=null&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-tertiary",children:d.count.toLocaleString("en-ZA")})]},d.value))]})]})}function Eqe(e){if(!e||e.length<2)return"text-text-tertiary";const t=e[e.length-1]-e[0];return t>0?"text-text-warning":t<0?"text-intent-success":"text-text-secondary"}function Aqe(e){if(!e||e.length<2)return"No price history yet";const t=e[0],n=e[e.length-1],r=t>0?Math.round((n-t)/t*100):0;return`Price ${n>t?"up":n<t?"down":"flat"} ${r>0?"+":""}${r}% over ${e.length} snapshots (R${t} â R${n})`}function Tqe({score:e,factors:t}){if(e==null)return s.jsx("span",{className:"text-text-tertiary tabular-nums",children:"â"});const n=e>=67?"bg-intent-success/10 text-intent-success":e>=34?"bg-surface-brandSubtle text-text-brand":"bg-surface-subtle text-text-tertiary",r=t?`demand ${Math.round(t.demand*100)}% · beatability ${Math.round(t.beatability*100)}%${t.margin_headroom!=null?` · margin ${Math.round(t.margin_headroom*100)}%`:""}`:void 0;return s.jsx("span",{title:r,className:B("inline-block min-w-[2.25rem] rounded px-1.5 py-0.5 text-xs font-semibold tabular-nums",n),children:e})}function Pv(){return s.jsx("span",{className:"cursor-help text-xs text-text-tertiary",title:"Estimated sales aren't reliable for this category yet â there isn't enough comparable data to model rank â sales here.",children:"low data"})}function nc({compact:e=!1}){const t=jf();return s.jsx("button",{type:"button",onClick:()=>t("sign me up now!"),className:B("text-intent-brand hover:text-intent-brandHover underline decoration-dotted underline-offset-2",e?"text-xs":"text-sm font-medium"),title:"Connect your Takealot store to unlock Est Sales & Revenue",children:"Sign up to use"})}const Oqe={JANUARY:0,FEBRUARY:1,MARCH:2,APRIL:3,MAY:4,JUNE:5,JULY:6,AUGUST:7,SEPTEMBER:8,OCTOBER:9,NOVEMBER:10,DECEMBER:11};function Iqe(e,t){const n=Oqe[e.toUpperCase()];
909return(n==null?new Date(t,0,1):new Date(t,n,1)).toLocaleString("en-ZA",{month:"short",year:"2-digit"})}function Pqe(e,t){if(t!=null&&t.length)return t.map(a=>({month:Iqe(a.month,a.year),searches:a.searches}));if(!e.length)return[];const n=new Date,r=new Date(n.getFullYear(),n.getMonth()-1,1);return e.map((a,i)=>({month:new Date(r.getFullYear(),r.getMonth()-(e.length-1-i),1).toLocaleString("en-ZA",{month:"short",year:"2-digit"}),searches:a}))}function Rqe(e,t){const n=r=>r==null?"â":r.toLocaleString("en-ZA");return[{key:"rank",label:"#",className:"w-10",align:"right",getValue:r=>r.rank,render:r=>s.jsx("span",{className:"text-text-tertiary tabular-nums",children:r.rank})},{key:"image",label:"",className:"w-12",header:s.jsx("span",{className:"sr-only",children:"Image"}),render:r=>r.image_url?s.jsx("img",{src:r.image_url,alt:"",className:"h-10 w-10 rounded object-contain bg-surface-subtle"}):s.jsx("div",{className:"grid h-10 w-10 place-items-center rounded bg-surface-subtle text-text-tertiary",children:s.jsx(nx,{className:"h-3.5 w-3.5"})})},{key:"title",label:"Listing",getValue:r=>r.title,render:r=>s.jsx("span",{className:"line-clamp-2 text-text-primary",children:r.title||`PLID ${r.plid}`})},{key:"brand",label:"Brand",hideBelow:"sm",getValue:r=>r.brand,render:r=>s.jsx("span",{className:"text-text-secondary",children:r.brand||"â"})},{key:"price",label:"Price",align:"right",hideBelow:"md",getValue:r=>r.price,render:r=>s.jsx("span",{className:"text-text-secondary",children:r.price!=null?ge(r.price):"â"})},{key:"rating",label:"â
",align:"right",hideBelow:"lg",getValue:r=>r.rating,render:r=>s.jsxs("span",{className:"text-text-secondary",children:[r.rating!=null?r.rating.toFixed(1):"â",r.reviews!=null&&s.jsxs("span",{className:"text-text-tertiary",children:[" (",n(r.reviews),")"]})]})},{key:"est_units_30d",label:"Est Sales",align:"right",getValue:r=>r.est_units_30d,render:r=>s.jsx("span",{className:"tabular-nums text-text-secondary",children:e?s.jsx(nc,{compact:!0}):r.est_units_30d!=null?`${r.est_units_30d.toLocaleString("en-ZA")}/mo`:(t==null?void 0:t.available)===!1&&t.reason!=="demo_locked"?"â":s.jsx(Pv,{})})},{key:"est_revenue_rand_30d",label:"Est Rev",align:"right",className:"hidden xl:table-cell",getValue:r=>r.est_revenue_rand_30d,render:r=>s.jsx("span",{className:"tabular-nums text-text-secondary",children:e?s.jsx(nc,{compact:!0}):r.est_revenue_rand_30d!=null?ge(r.est_revenue_rand_30d):"â"})},{key:"pdp",label:"",className:"w-8",align:"right",stopRowClick:!0,header:s.jsx("span",{className:"sr-only",children:"PDP"}),render:r=>r.plid?s.jsx("a",{href:`https://www.takealot.com/x/PLID${r.plid}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex text-text-tertiary hover:text-intent-brand",title:"Open on Takealot",children:s.jsx(Qt,{className:"h-3.5 w-3.5"})}):null}]}function Dqe({item:e,open:t,onOpenChange:n,saved:r,onToggleSave:a,onResearch:i,onOpenInCatalogue:o}){var I,$,P,F,Z,D,H,Y;const[l,c]=p.useState(null),[u,d]=p.useState([]),[h,f]=p.useState(null),[m,x]=p.useState(null),[g,y]=p.useState(!1),[b,v]=p.useState(!1),[w,_]=p.useState(null),k=(e==null?void 0:e.keyword)??"",j=(m==null?void 0:m.reason)==="demo_locked",N=p.useCallback(async M=>{var z;v(!0),_(null);try{const G=await $t.runSearch({marketplace:"takealot",keyword:M,page_count:1}),te=(G.rows??[]).slice(0,10).map((re,L)=>({rank:re.position??L+1,plid:re.plid!=null?String(re.plid):"",title:re.title,brand:re.brand,image_url:re.image_url??null,price:re.selling_price,rating:re.star_rating,reviews:re.reviews,est_units_30d:re.est_units_30d??null,est_revenue_rand_30d:re.est_revenue_rand_30d??null,source:"live"}));d(te),f("live"),x(((z=G.rollup)==null?void 0:z.est_sales_meta)??null)}catch(G){_(G instanceof Error?G.message:String(G))}finally{v(!1)}},[]);p.useEffect(()=>{if(!t||!e){c(null),d([]),f(null),x(null),_(null),y(!1),v(!1);return}let M=!1;return y(!0),_(null),d([]),f(null),x(null),$t.keyword(e.keyword).then(z=>{if(M)return;c(z),x(z.est_sales_meta??null);const G=(z.rankings??[]).slice().sort((te,re)=>te.rank-re.rank).slice(0,10).map(te=>({rank:te.rank+1,plid:String(te.plid),title:te.title,brand:te.brand,image_url:te.image_url??null,price:te.selling_price??null,rating:te.star_rating??null,reviews:te.reviews??null,est_units_30d:te.est_units_30d??null,est_revenue_rand_30d:te.est_revenue_rand_30d??null,source:"cached"}));G.length>0&&(d(G),f("cached"))}).catch(z=>{M||_(z instanceof Error?z.message:String(z))}).finally(()=>{M||y(!1)}),()=>{M=!0}},[t,e]);const E=($=(I=l==null?void 0:l.headline)==null?void 0:I.monthly_volumes)!=null&&$.length?l.headline.monthly_volumes:(e==null?void 0:e.sparkline)??[],A=((P=l==null?void 0:l.headline)==null?void 0:P.monthly_volume_series)??null,C=p.useMemo(()=>Pqe(E,A),[E,A]),T=M=>
909M==null?"â":M.toLocaleString("en-ZA"),S=((F=l==null?void 0:l.headline)==null?void 0:F.cpc_low_rands)!=null?l.headline:(e==null?void 0:e.cpc_low_rands)!=null?{cpc_low_rands:e.cpc_low_rands,cpc_high_rands:e.cpc_high_rands}:null,O=(l==null?void 0:l.related)??[],R=wqe(l,e);return s.jsx(js,{open:t,onOpenChange:n,children:s.jsxs(Ns,{size:"xl",className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[s.jsx(La,{children:s.jsxs("div",{className:"flex items-start justify-between gap-3 pr-8",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx(ma,{className:"truncate",children:k}),s.jsxs("p",{className:"mt-1 text-body-xs text-text-secondary",children:[(e==null?void 0:e.volume)!=null?`${T(e.volume)} searches/mo`:"Volume unknown",(e==null?void 0:e.yoy_change_pct)!=null&&s.jsxs("span",{className:e.yoy_change_pct>5?"text-text-success":e.yoy_change_pct<-5?"text-text-error":"text-text-tertiary",children:[" ","· ",e.yoy_change_pct>0?"+":"",e.yoy_change_pct,"% YoY"]}),(e==null?void 0:e.is_spike)&&s.jsx("span",{className:"ml-2 rounded-full border border-outline-warning bg-surface-warningSubtle px-1.5 py-0.5 text-[10px] font-medium text-text-primary",title:"Latest month is a spike vs recent history â fad risk",children:"fad risk"}),(e==null?void 0:e.competition)&&s.jsx("span",{className:"ml-2 inline-flex align-middle",title:"Advertiser competition on search in South Africa â not Takealot listing count",children:s.jsx($w,{level:e.competition})})]}),((e==null?void 0:e.department_name)||(e==null?void 0:e.category_name))&&s.jsx("p",{className:"mt-0.5 text-body-xs text-text-tertiary",children:[e.department_name,e.category_name].filter(Boolean).join(" · ")})]}),k&&s.jsx(Mw,{saved:r.has(k.toLowerCase()),onClick:()=>a(k)})]})}),s.jsxs(Oa,{className:"space-y-5 pb-4",children:[s.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:[s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface-subtle/40 px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-text-tertiary",children:"Est. CPC"}),s.jsx("div",{className:"mt-0.5 text-body-sm font-medium text-text-primary",children:(S==null?void 0:S.cpc_low_rands)!=null?`R${S.cpc_low_rands.toFixed(2)}${S.cpc_high_rands!=null?`â${S.cpc_high_rands.toFixed(2)}`:""}`:"â"})]}),s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface-subtle/40 px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-text-tertiary",children:"Takealot CPC"}),s.jsx("div",{className:"mt-0.5 text-body-sm font-medium text-text-primary",children:(l==null?void 0:l.cpc.floor_rands)!=null?`R${l.cpc.floor_rands.toFixed(2)}+`:"â"})]}),s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface-subtle/40 px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-text-tertiary",children:"Peak month"}),s.jsx("div",{className:"mt-0.5 text-body-sm font-medium text-text-primary",children:e!=null&&e.peak_month?e2(e.peak_month):(Z=l==null?void 0:l.headline)!=null&&Z.peak_month?e2(l.headline.peak_month):"â"})]}),s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface-subtle/40 px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-text-tertiary",children:"Trend"}),s.jsx("div",{className:"mt-0.5 text-body-sm font-medium text-text-primary",children:((e==null?void 0:e.trend_3mo)??((D=l==null?void 0:l.headline)==null?void 0:D.trend))==="up"?"â Rising":((e==null?void 0:e.trend_3mo)??((H=l==null?void 0:l.headline)==null?void 0:H.trend))==="down"?"â Falling":((e==null?void 0:e.trend_3mo)??((Y=l==null?void 0:l.headline)==null?void 0:Y.trend))==="flat"?"â Steady":"â"})]})]}),s.jsx(Nqe,{item:e}),R&&s.jsx(bG,{shelf:R}),s.jsxs("div",{children:[s.jsxs("div",{className:"mb-2 text-body-xs font-medium uppercase tracking-wide text-text-tertiary",children:["Search volume trend",g&&s.jsx(_e,{className:"ml-1.5 inline h-3 w-3 animate-spin text-text-tertiary"})]}),C.length>=2?s.jsx("div",{className:"h-56 w-full rounded-lg border border-outline-subtle bg-surface-subtle/30 p-3",children:s.jsx(li,{width:"100%",height:"100%",children:s.jsxs(DH,{data:C,margin:{top:8,right:8,bottom:0,left:0},children:[s.jsx("defs",{children:s.jsxs("linearGradient",{id:"browse-vol-grad",x1:"0",y1:"0",x2:"0",y2:"1",children:[s.jsx("stop",{offset:"0%",stopColor:et.primary,stopOpacity:.28}),s.jsx("stop",{offset:"100%",stopColor:et.primary,stopOpacity:0})]})}),s.jsx(Ma,{strokeDasharray:"3 3",stroke:Co,vertical:!1}),s.jsx($a,{dataKey:"month",tick:{fontSize:11,fill:kr},minTickGap:20}),s.jsx(zr,{tick:{fontSize:11,fill:kr},tickFormatter:M=>
909Number(M).toLocaleString("en-ZA"),width:52}),s.jsx(Da,{contentStyle:{background:"rgb(var(--color-surface))",border:"1px solid rgb(var(--color-outline-subtle))",borderRadius:8,fontSize:12},formatter:M=>[Number(M).toLocaleString("en-ZA"),"Searches"]}),s.jsx(xw,{type:"monotone",dataKey:"searches",stroke:et.primary,strokeWidth:2,fill:"url(#browse-vol-grad)"})]})})}):s.jsx("p",{className:"text-body-sm text-text-secondary",children:"Not enough monthly volume history to chart this phrase yet."})]}),O.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"mb-2 text-body-xs font-medium uppercase tracking-wide text-text-tertiary",children:"Related keywords"}),s.jsx("div",{className:"flex flex-wrap gap-1.5",children:O.slice(0,12).map(M=>s.jsxs("button",{type:"button",onClick:()=>{i(M.keyword),n(!1)},className:"inline-flex items-center gap-1.5 rounded-full border border-outline-subtle bg-surface px-2.5 py-1 text-body-xs text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary",title:M.volume!=null?`${T(M.volume)} searches/mo`:void 0,children:[M.keyword,M.volume!=null&&s.jsx("span",{className:"text-text-tertiary",children:T(M.volume)})]},M.keyword))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[s.jsxs("div",{className:"text-body-xs font-medium uppercase tracking-wide text-text-tertiary",children:["Top 10 on Takealot",h==="cached"&&s.jsx("span",{className:"ml-1.5 font-normal normal-case tracking-normal text-text-tertiary",children:"· from prior Catalogue scans"}),h==="live"&&s.jsx("span",{className:"ml-1.5 font-normal normal-case tracking-normal text-text-tertiary",children:"· live SERP (1 search used)"})]}),h==="cached"&&!b&&s.jsx("button",{type:"button",onClick:()=>N(k),className:"text-body-xs text-text-secondary hover:text-text-primary hover:underline",children:"Refresh live"})]}),b&&s.jsxs("div",{className:"flex items-center gap-2 py-6 text-body-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"}),"Scanning Takealot for â",k,"ââ¦"]}),!b&&w&&s.jsxs(V,{className:"border-outline-error bg-surface-errorSubtle p-3 text-body-sm text-text-error",children:[w,s.jsx("button",{type:"button",onClick:()=>o(k),className:"mt-2 block text-body-xs text-intent-brand hover:underline",children:"Open in Catalogue instead"})]}),!b&&!w&&u.length===0&&!g&&s.jsxs(V,{className:"border-outline-subtle bg-surface-subtle/40 p-4",children:[s.jsx("p",{className:"text-body-sm text-text-primary",children:"No stored Takealot rankings for this phrase yet."}),s.jsx("p",{className:"mt-1 text-body-xs text-text-secondary",children:"Run a live 1-page Catalogue scan to see who ranks (uses 1 search credit)."}),s.jsxs("button",{type:"button",onClick:()=>N(k),className:"mt-3 inline-flex items-center gap-1.5 rounded-md bg-intent-brand px-3 py-1.5 text-body-xs font-medium text-text-inverse shadow-xs hover:bg-intent-brandHover",children:[s.jsx(Fa,{className:"h-3.5 w-3.5"}),"Load top 10 on Takealot"]})]}),!b&&u.length>0&&s.jsx(V,{className:"overflow-hidden p-0",children:s.jsx(dt,{rows:u,columns:Rqe(j,m),getRowKey:M=>`${M.plid}-${M.rank}`,paginate:!1,persist:!1,tableClassName:"w-full text-body-sm",empty:{title:"No listings."}})})]})]}),s.jsxs(da,{className:"justify-between sm:justify-between",children:[s.jsx("button",{type:"button",onClick:()=>{i(k),n(!1)},className:"text-body-xs text-text-secondary hover:text-text-primary hover:underline",children:"Open in Keywords â Search"}),s.jsxs(W,{type:"button",onClick:()=>{o(k),n(!1)},children:[s.jsx(gf,{className:"mr-1.5 h-3.5 w-3.5"}),"Open in Catalogue"]})]})]})})}function AL(e){const t=[];return e.seed_taxonomy&&t.push(`${e.seed_taxonomy} taxonomy`),e.seed_extension&&t.push(`${e.seed_extension} extension`),e.seed_osmos&&t.push(`${e.seed_osmos} ads corpus`),e.seed_other&&t.push(`${e.seed_other} other`),t.join(" · ")}function Mqe({onPickDepartment:e}){const[t,n]=p.useState(null),[r,a]=p.useState(!1);if(p.useEffect(()=>{let l=!1;return $t.keywordBrowseCoverage().then(c=>{l||n(c)}).catch(()=>{l||n(null)}),()=>{l=!0}},[]),!(t!=null&&t.summary)||t.summary.departments===0)return null;const{summary:i}=t,o=t.departments.filter(l=>l.band!=="ok");return s.jsxs("div",{className:"rounded-md border border-outline-subtle bg-surface-subtle/40 px-3 py-2",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[s.jsxs("p",{className:"text-body-xs text-text-secondary",children:["Coverage · ",i.departments," departments · ",i.ok," mapped ·"," ",i.thin," thin · ",i.empty," empty",i.unmapped?` · ${i.unmapped.toLocaleStr
909ing("en-ZA")} unmapped`:""]}),o.length>0&&s.jsx("button",{type:"button",onClick:()=>a(l=>!l),className:"text-body-xs text-text-tertiary hover:text-text-secondary",children:r?"Hide thin departments":"Show thin departments"})]}),r&&o.length>0&&s.jsx("ul",{className:"mt-2 max-h-48 space-y-1 overflow-auto",children:o.map(l=>s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>e==null?void 0:e(l.department_slug),className:"flex w-full items-baseline justify-between gap-3 rounded px-1 py-0.5 text-left text-body-xs hover:bg-surface-subtle",children:[s.jsxs("span",{className:"text-text-primary",children:[l.display_name,s.jsx("span",{className:"ml-1.5 text-text-tertiary",children:l.band==="empty"?"empty":"thin"})]}),s.jsxs("span",{className:"shrink-0 text-text-tertiary",children:[l.keyword_count.toLocaleString("en-ZA"),AL(l)?` · ${AL(l)}`:""]})]})},l.department_slug))})]})}function $qe({onResearch:e,onOpenInCatalogue:t,saved:n,onToggleSave:r,hideRails:a=!1,picked:i,onTogglePick:o}){var ce;const l=mc(),[c,u]=it("rail","hot"),d=gG.includes(c)?c:"hot",[h,f]=it("hide_local","1"),m=h!=="0",[x,g]=it("volume",""),[y,b]=it("trend",""),[v,w]=it("yoy",""),[_,k]=it("words",""),[j,N]=it("competition",""),[E,A]=it("spike",""),[C,T]=it("cpc",""),[S,O]=it("in_corpus",""),R=S==="1",[I,$]=it("contains",""),[P,F]=p.useState(I),[Z,D]=it("exclude",""),[H,Y]=p.useState(Z),[M]=it("dept",""),[z]=it("cat",""),G=p.useMemo(()=>CL(M),[M]),te=p.useMemo(()=>CL(z),[z]),[re,L]=p.useState([]),[q,me]=p.useState([]),[ee,ne]=p.useState(null),[X,he]=p.useState(!0),[ae,je]=p.useState(null),[$e,J]=p.useState(0),[Ne,ve]=p.useState(null),Me=p.useMemo(()=>C==="lt1"?{cpc_min:void 0,cpc_max:1}:C==="lt5"?{cpc_min:void 0,cpc_max:5}:C==="5plus"?{cpc_min:5,cpc_max:void 0}:{cpc_min:void 0,cpc_max:void 0},[C]),Xe=G.join(","),ze=te.join(",");p.useEffect(()=>{F(I)},[I]),p.useEffect(()=>{Y(Z)},[Z]),p.useEffect(()=>{let ue=!1;return $t.keywordBrowseTaxonomyOptions().then(Ee=>{ue||L(Ee.departments||[])}).catch(()=>{ue||L([])}),()=>{ue=!0}},[]),p.useEffect(()=>{let ue=!1;if(!G.length){me([]),te.length&&l({cat:""});return}return $t.keywordBrowseTaxonomyOptions(Xe).then(Ee=>{if(ue)return;const bt=Ee.categories||[];me(bt);const Ze=new Set(bt.map(Ot=>Ot.category_id)),vt=te.filter(Ot=>Ze.has(Ot));vt.length!==te.length&&l({cat:xj(vt)})}).catch(()=>{ue||me([])}),()=>{ue=!0}},[Xe]),p.useEffect(()=>{let ue=!1;return he(!0),je(null),$t.keywordBrowse({rail:d,hide_local:m,volume:x||void 0,trend:y||void 0,yoy:v||void 0,words:_||void 0,competition:j||void 0,spike:E||void 0,in_corpus:R||void 0,contains:I||void 0,exclude:Z||void 0,department_slug:Xe||void 0,category_id:ze||void 0,cpc_min:Me.cpc_min,cpc_max:Me.cpc_max,offset:$e,limit:50}).then(Ee=>{ue||ne(Ee)}).catch(Ee=>{ue||(je(Ee instanceof Error?Ee.message:String(Ee)),ne(null))}).finally(()=>{ue||he(!1)}),()=>{ue=!0}},[d,m,x,y,v,_,j,E,R,I,Z,Xe,ze,Me.cpc_min,Me.cpc_max,$e]),p.useEffect(()=>{J(0)},[d,m,x,y,v,_,j,E,R,I,Z,Xe,ze,C]);const Fe=ue=>{l({dept:xj(ue),cat:""}),J(0)},tt=ue=>{l({cat:xj(ue)}),J(0)},fe=(ce=Iv.find(ue=>ue.key===d))==null?void 0:ce.blurb,U=G.length>0||te.length>0;return s.jsxs("div",{className:"space-y-3",children:[!a&&s.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:Iv.map(ue=>s.jsx("button",{type:"button",onClick:()=>{u(ue.key),J(0)},className:`rounded-full border px-2.5 py-1 text-body-xs transition ${d===ue.key?"border-outline bg-surface-subtle font-medium text-text-primary":"border-outline-subtle text-text-secondary hover:bg-surface-subtle"}`,children:ue.label},ue.key))}),!a&&fe&&s.jsx("p",{className:"text-body-xs text-text-tertiary",children:fe}),a&&fe&&s.jsx("p",{className:"text-body-xs text-text-tertiary",children:fe}),!a&&s.jsx(Mqe,{onPickDepartment:ue=>{Fe([ue])}}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(EL,{label:"Departments",allLabel:"All departments",options:re.map(ue=>({value:ue.department_slug,label:ue.display_name,count:ue.keyword_count})),selected:G,onChange:Fe}),s.jsx(EL,{label:"Categories",allLabel:G.length?"All categories":"Pick a department first",options:q.map(ue=>({value:ue.category_id,label:ue.display_name,count:ue.keyword_count})),selected:te,onChange:tt,disabled:!G.length}),s.jsxs("form",{className:"flex items-center gap-1",onSubmit:ue=>{ue.preventDefault(),$(P.trim()),J(0)},children:[s.jsx("input",{value:P,onChange:ue=>F(ue.target.value),placeholder:"Containsâ¦",title:"Show phrases that contain this text",className:"w-32 rounded-md border border-outline-subtle bg-surface px-2 py-1 text-body-xs text-text-primary"}),s.jsx("button",{type:"submit",className:"rounded-md border border-outline-subtle px-2 py-1 text-body-xs text-text-secondary hover:bg-surface-subtle",children:"Include"})]}),s.jsxs("form",{className:"flex items-center gap-1",onSubmit:ue=>{ue.preventDefault(),D(H.trim()),J(0)},children:[s.jsx("input",{value:H,onChange:ue=>Y(ue.target.value),placeholder:"Exclude⦠(comma-separated)",title:"Hide phrases containing any of these tokens",className:"w-44 rounded-md border border-outline-subtle bg-surface px-2 py-1 text-body-xs text-text-primary"}),s.jsx("button",{type:"submit",className:"rounded-md border border-outline-subtle px-2 py-1 text-body-xs text-text-secondary hover:bg-surface-subtle",children:"Exclude"})]}),s.jsxs("select",{value:x,onChange:ue=>{g(ue.target.value),J(0)},className:"rounded-md border border-outline-subtle bg-surface px-2 py-1 text-body-xs text-text-secondary",children:[s.jsx("option",{value:"",children:"Any volume"}),s.jsx("option",{value:"lt100",children:"<100 /mo"}),s.jsx("option",{value:"100-800",children:"100â800 /mo"}),s.jsx("option",{value:"800-10k",children:"800â10k /mo"}),s.jsx("option",{value:"10k+",children:"10k+ /mo"})]}),s.jsxs("select",{value:y,onChange:ue=>{b(ue.target.value),J(0)},className:"rounded-md border border-outline-subtle bg-surface px-2 py-1 text-body-xs text-text-secondary",children:[s.jsx("option",{value:"",children:"Any trend"}),s.jsx("option",{value:"up",children:"Rising"}),s.jsx("option",{value:"flat",children:"Steady"}),s.jsx("option",{value:"down",children:"Falling"})]}
909),s.jsxs("select",{value:v,onChange:ue=>{w(ue.target.value),J(0)},className:"rounded-md border border-outline-subtle bg-surface px-2 py-1 text-body-xs text-text-secondary",children:[s.jsx("option",{value:"",children:"Any YoY"}),s.jsx("option",{value:"growing",children:"Growing YoY"}),s.jsx("option",{value:"flat",children:"Flat YoY"}),s.jsx("option",{value:"shrinking",children:"Shrinking YoY"})]}),s.jsxs("select",{value:_,onChange:ue=>{k(ue.target.value),J(0)},className:"rounded-md border border-outline-subtle bg-surface px-2 py-1 text-body-xs text-text-secondary",children:[s.jsx("option",{value:"",children:"Any length"}),s.jsx("option",{value:"1",children:"1 word"}),s.jsx("option",{value:"2",children:"2 words"}),s.jsx("option",{value:"3",children:"3 words"}),s.jsx("option",{value:"4+",children:"4+ words"})]}),s.jsxs("select",{value:j,onChange:ue=>{N(ue.target.value),J(0)},className:"rounded-md border border-outline-subtle bg-surface px-2 py-1 text-body-xs text-text-secondary",children:[s.jsx("option",{value:"",children:"Any ad competition"}),s.jsx("option",{value:"LOW",children:"Low ad competition"}),s.jsx("option",{value:"MEDIUM",children:"Medium ad competition"}),s.jsx("option",{value:"HIGH",children:"High ad competition"})]}),s.jsxs("select",{value:E,onChange:ue=>{A(ue.target.value),J(0)},title:"Fad risk is a latest-month spike vs recent history â hide it or look at it",className:"rounded-md border border-outline-subtle bg-surface px-2 py-1 text-body-xs text-text-secondary",children:[s.jsx("option",{value:"",children:"Any fad risk"}),s.jsx("option",{value:"hide",children:"Hide fad risk"}),s.jsx("option",{value:"only",children:"Fad risk only"})]}),s.jsxs("select",{value:C,onChange:ue=>{T(ue.target.value),J(0)},className:"rounded-md border border-outline-subtle bg-surface px-2 py-1 text-body-xs text-text-secondary",children:[s.jsx("option",{value:"",children:"Any CPC"}),s.jsx("option",{value:"lt1",children:"CPC under R1"}),s.jsx("option",{value:"lt5",children:"CPC under R5"}),s.jsx("option",{value:"5plus",children:"CPC R5+"})]}),s.jsxs("label",{className:"inline-flex items-center gap-1.5 text-body-xs text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:m,onChange:ue=>{f(ue.target.checked?"1":"0"),J(0)},className:"rounded border-outline"}),"Hide local intent"]}),s.jsxs("label",{className:"inline-flex items-center gap-1.5 text-body-xs text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:R,onChange:ue=>{O(ue.target.checked?"1":""),J(0)},className:"rounded border-outline"}),"On Takealot ads"]})]}),X&&s.jsxs("div",{className:"flex items-center gap-2 px-1 py-4 text-body-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Loading browse railâ¦"]}),ae&&s.jsx(V,{className:"border-outline-error bg-surface-errorSubtle p-3 text-body-sm text-text-error",children:ae}),!X&&!ae&&ee&&ee.keywords.length===0&&s.jsxs(V,{className:"p-6 text-center",children:[s.jsx(Xi,{className:"mx-auto mb-2 h-6 w-6 text-text-tertiary"}),s.jsx("p",{className:"text-body-sm text-text-primary",children:"No keywords on this rail yet"}),s.jsx("p",{className:"mt-1 text-body-xs text-text-secondary",children:d==="opportunities"?"Opportunities needs a Takealot page 1 we already captured â soft reviews, a price that can carry fees, and a mapped department. Weâre still filling those stats from rankings we hold; try Highest volume in the meantime.":U?"Showing keywords weâve mapped to this Takealot area. Try other departments, clear categories or exclude phrases, or switch to Highest volume.":"These filters may be too tight, or taxonomy mapping is still catching up. Try Highest volume, loosen Exclude / competition, or turn off âHide local intentâ."})]}),!X&&ee&&ee.keywords.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-body-xs text-text-secondary",children:["Showing ",ee.keywords.length,ee.has_more?"+":""," phrases"]}),s.jsx(V,{className:"overflow-hidden p-0",children:s.jsx(dt,{rows:ee.keywords,columns:Cqe({picked:i,onTogglePick:o,saved:n,onToggleSave:r,onOpenInCatalogue:t}),getRowKey:ue=>ue.keyword,paginate:!1,persist:!1,tableClassName:"w-full text-body-sm",empty:{title:"No keywords on this rail yet"},onRowClick:ue=>ve(ue)},`${d}:${$e}:${m}:${x}:${y}:${v}:${_}:${j}:${E}:${R}:${I}:${Z}:${Xe}:${ze}:${C}`)}),s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("button",{type:"button",disabled:$e===0||X,onClick:()=>J(ue=>Math.max(0,ue-50)),className:"rounded-md border border-outline-subtle px-3 py-1.5 text-body-xs text-text-secondary disabled:opacity-40",children:"Previous"}),s.jsx("button",{type:"button",disabled:!ee.has_more||X,onClick:()=>J(ue=>ue+50),className:"rounded-md border border-outline-subtle px-3 py-1.5 text-body-xs text-text-secondary disabled:opacity-40",children:"Next"})]})]}),s.jsx(Dqe,{item:Ne,open:Ne!=null,onOpenChange:ue=>{ue||ve(null)},saved:n,onToggleSave:r,onResearch:e,onOpenInCatalogue:t})]})}function Lqe({data:e,onSearch:t,onOpenInCatalogue:n,saved:r,onToggleSave:a,picked:i,onTogglePick:o}){var h;const l=e.headline,c=(l==null?void 0:l.monthly_volumes)??[],u=(()=>
909{if(c.length<2)return null;const f=c[c.length-1],m=c.length>=13?c[c.length-13]:c[0];return m?Math.round((f-m)/m*100):null})(),d=f=>f==null?"â":f.toLocaleString("en-ZA");return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("h2",{className:"text-title-sm font-semibold text-text-primary",children:e.term}),s.jsx(Mw,{saved:r.has(e.term.toLowerCase()),onClick:()=>a(e.term)})]}),!l&&s.jsxs(V,{className:"border-outline-subtle bg-surface-subtle/40 p-3 text-body-xs text-text-secondary",children:["No search-volume data for â",e.term,"â yet â showing whatever Takealot CPC, related keywords and rankings we hold."]}),s.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4",children:[s.jsx(dy,{label:"Monthly searches",value:(l==null?void 0:l.avg_monthly_searches)!=null?d(l.avg_monthly_searches):"â",sub:u==null?void 0:s.jsxs("span",{className:u>=0?"text-text-success":"text-text-error",children:[s.jsx(Xi,{className:"mr-0.5 inline h-3 w-3"}),u>=0?"+":"",u,"% YoY"]})}),s.jsx(dy,{label:"Competition",value:s.jsx($w,{level:(l==null?void 0:l.competition)??null})}),s.jsx(dy,{label:"Est. CPC",value:(l==null?void 0:l.cpc_low_rands)!=null?`R${l.cpc_low_rands.toFixed(2)}â${(l.cpc_high_rands??l.cpc_low_rands).toFixed(2)}`:"â",sub:"top-of-page bid"}),s.jsx(dy,{label:"Takealot CPC floor",value:e.cpc.floor_rands!=null?`R${e.cpc.floor_rands.toFixed(2)}`:"â",sub:e.cpc.categories>0?`${e.cpc.categories} categor${e.cpc.categories===1?"y":"ies"}`:"no corpus data"})]}),((h=e.shelf)==null?void 0:h.category_id)&&s.jsx(bG,{shelf:e.shelf}),c.length>=2&&s.jsxs(V,{className:"flex items-center justify-between gap-4 p-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 text-body-xs text-text-tertiary",children:["Search volume â last ",c.length," months",(l==null?void 0:l.trend)&&s.jsx("span",{className:l.trend==="up"?"text-text-success":l.trend==="down"?"text-text-error":"text-text-tertiary",children:l.trend==="up"?"â rising":l.trend==="down"?"â falling":"â steady"})]}),s.jsxs("div",{className:"text-body-sm text-text-secondary",children:["Peak ",d(Math.max(...c))," · current ",d(c[c.length-1]),(l==null?void 0:l.peak_month)&&s.jsxs("span",{className:"text-text-tertiary",children:[" ","· busiest in ",e2(l.peak_month)]})]})]}),s.jsx(Ws,{data:c,width:200,height:40,className:"text-intent-brand"})]}),e.related.length>0&&s.jsxs(V,{className:"p-4",children:[s.jsxs("div",{className:"mb-2 flex items-center gap-1.5 text-body-xs text-text-tertiary",children:[s.jsx(Gv,{className:"h-3.5 w-3.5"})," Related keywords"]}),s.jsx("div",{className:"flex flex-wrap gap-1.5",children:e.related.map(f=>s.jsxs("span",{className:"inline-flex items-center gap-1",children:[o&&s.jsx("input",{type:"checkbox",checked:(i==null?void 0:i.has(f.keyword.toLowerCase()))??!1,onChange:()=>o({keyword:f.keyword,volume:f.volume}),"aria-label":`Select ${f.keyword}`}),s.jsxs("button",{type:"button",onClick:()=>t(f.keyword),className:"inline-flex items-center gap-1.5 rounded-full border border-outline-subtle bg-surface px-2.5 py-1 text-body-xs text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary",title:`${d(f.volume)} monthly searches`,children:[f.keyword,f.volume!=null&&s.jsx("span",{className:"text-text-tertiary",children:d(f.volume)})]})]},f.keyword))})]}),s.jsxs(V,{className:"p-4",children:[s.jsxs("div",{className:"mb-2 text-body-xs text-text-tertiary",children:["Who ranks for â",e.term,"â"]}),e.rankings.length===0?s.jsx("p",{className:"text-body-xs text-text-secondary",children:"No tracked rankings yet â run a Catalogue search for this keyword to start capturing who ranks."}):s.jsx("div",{className:"flex flex-col divide-y divide-outline-subtle",children:e.rankings.map(f=>{var m;return s.jsxs("a",{href:`https://www.takealot.com/x/PLID${f.plid}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-3 py-1.5 text-body-sm transition hover:bg-surface-subtle",children:[s.jsxs("span",{className:"w-7 shrink-0 text-right font-medium text-text-tertiary",children:["#",f.rank+1]}),f.image_url?s.jsx("img",{src:f.image_url,alt:"",className:"h-8 w-8 shrink-0 rounded object-contain bg-surface-subtle"}):s.jsx("div",{className:"grid h-8 w-8 shrink-0 place-items-center rounded bg-surface-subtle text-text-tertiary",children:s.jsx(nx,{className:"h-3 w-3"})}),s.jsxs("span",{className:"min-w-0 flex-1 truncate text-text-primary",children:[f.title||`PLID ${f.plid}`,f.brand&&s.jsx("span",{className:"ml-1.5 text-text-tertiary",children:f.brand})]}),s.jsx("span",{className:"shrink-0 tabular-nums text-body-xs text-text-secondary",children:((m=e.est_sales_meta)==null?void 0:m.reason)==="demo_locked"?s.jsx(nc,{compact:!0}
909):f.est_units_30d!=null?`${f.est_units_30d.toLocaleString("en-ZA")}/mo`:"â"}),s.jsx(Qt,{className:"h-3.5 w-3.5 shrink-0 text-text-tertiary"})]},f.plid)})})]}),s.jsxs("button",{type:"button",onClick:()=>n(e.term),className:"flex w-full items-center justify-between gap-3 rounded-md border border-outline-subtle bg-surface-brandSubtle/40 px-4 py-3 text-left transition hover:bg-surface-brandSubtle/70",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-body-sm font-medium text-text-primary",children:["See who's selling â",e.term,"â live"]}),s.jsx("div",{className:"text-body-xs text-text-secondary",children:"Run a full Catalogue search â prices, ratings, Est Sales & Opportunity per listing."})]}),s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 rounded-md bg-intent-brand px-3 py-1.5 text-body-sm font-medium text-text-inverse shadow-xs",children:[s.jsx(gf,{className:"h-3.5 w-3.5"})," Open in Catalogue"]})]})]})}function Fqe(e){const t=r=>r==null?"â":r.toLocaleString("en-ZA"),n=[];if(e.onTogglePick){const r=e.onTogglePick;n.push({key:"select",label:"",className:"w-8",stopRowClick:!0,render:a=>{var i;return s.jsx("input",{type:"checkbox",checked:((i=e.picked)==null?void 0:i.has(a.keyword.toLowerCase()))??!1,onChange:()=>r({keyword:a.keyword,volume:a.volume,competition:a.competition}),"aria-label":`Select ${a.keyword}`})}})}return n.push({key:"keyword",label:"Keyword",getValue:r=>r.keyword,render:r=>s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{className:"text-text-primary",children:r.keyword}),r.sources.includes("autocomplete")&&s.jsx("span",{className:"rounded-full bg-surface-brandSubtle/60 px-1.5 py-0.5 text-[10px] font-medium text-intent-brand",title:"Suggested by Takealot's search bar â a proven shopper query",children:"shopper"}),r.opportunity&&s.jsx("span",{className:"rounded-full border border-outline-success bg-surface-successSubtle px-1.5 py-0.5 text-[10px] font-medium text-text-success",title:"Long-tail sweet spot â real demand, but off the saturated head term so more winnable",children:"long-tail"})]})},{key:"volume",label:"Searches/mo",sortable:!0,align:"right",getValue:r=>r.volume,render:r=>s.jsx("span",{className:"text-text-secondary",children:t(r.volume)})},{key:"competition",label:"Competition",hideBelow:"sm",className:"text-center",getValue:r=>r.competition?yG[r.competition.toUpperCase()]??null:null,render:r=>s.jsx($w,{level:r.competition})},{key:"cpc_low_rands",label:"Est. CPC",align:"right",hideBelow:"sm",getValue:r=>r.cpc_low_rands,render:r=>s.jsx("span",{className:"text-text-secondary",children:r.cpc_low_rands!=null?`R${r.cpc_low_rands.toFixed(2)}`:"â"})},{key:"actions",label:"",align:"right",className:"whitespace-nowrap",stopRowClick:!0,render:r=>s.jsxs(s.Fragment,{children:[s.jsx(Mw,{saved:e.saved.has(r.keyword.toLowerCase()),onClick:()=>e.onToggleSave(r.keyword),compact:!0}),s.jsx("button",{type:"button",onClick:()=>e.onResearch(r.keyword),className:"rounded px-2 py-1 text-body-xs text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary",title:"Full keyword research",children:"Details"}),s.jsx("button",{type:"button",onClick:()=>e.onOpenInCatalogue(r.keyword),className:"rounded px-2 py-1 text-body-xs text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary",title:"See who's selling this live",children:"Live"})]})}),n}function Bqe({data:e,onResearch:t,onOpenInCatalogue:n,saved:r,onToggleSave:a,picked:i,onTogglePick:o}){const[l,c]=p.useState("all");if(e.candidates.length===0)return s.jsxs(V,{className:"p-6 text-center text-body-sm text-text-secondary",children:["No expansions found for â",e.term,"â. Try a broader seed."]});const d=e.candidates.filter(m=>l==="all"?!0:l==="shopper"?m.sources.includes("autocomplete"):m.opportunity),h=()=>{var m;(m=navigator.clipboard)==null||m.writeText(d.map(x=>x.keyword).join(` 910`)).then(()=>Ae("success",`Copied ${d.length} keywords`)).catch(()=>{})},f=()=>{$t.exportResults({columns:[{key:"keyword",label:"Keyword"},{key:"volume",label:"Monthly searches"},{key:"competition",label:"Competition"},{key:"cpc_low_rands",label:"Est. CPC (low)"},{key:"long_tail",label:"Long-tail"}],rows:d.map(m=>({keyword:m.keyword,volume:m.volume,competition:m.competition,cpc_low_rands:m.cpc_low_rands,long_tail:m.opportunity?"yes":""})),format:"csv",filename:`keywords-${e.term.replace(/[^a-z0-9]+/gi,"-")}.csv`}).catch(m=>Ae("error",m instanceof Error?m.message:String(m)))};return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 px-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-body-xs text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:e.counts.total})," ideas around â",e.term,"â",s.jsx("span",{className:"text-text-tertiary",children:"·"}),s.jsxs("span",{children:[e.counts.opportunities," long-tail"]}),s.jsx("span",{className:"text-text-tertiary",children:"·"}),s.jsxs("span",{children:[e.counts.autocomplete," from Takealot autocomplete"]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("button",{type:"button",onClick:h,className:"inline-flex items-center gap-1 rounded-md border border-outline-subtle px-2 py-1 text-body-xs text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary",children:[s.jsx(bi,{className:"h-3.5 w-3.5"})," Copy"]}),s.jsxs("button",{type:"button",onClick:f,className:"inline-flex items-center gap-1 rounded-md border border-outline-subtle px-2 py-1 text-body-xs text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary",children:[s.jsx(Dr,{className:"h-3.5 w-3.5"})," CSV"]})]})]}),s.jsx("div",{className:"flex flex-wrap items-center gap-1.5 px-1",children:[["all","All",e.candidates.length],["shopper","Shopper",e.counts.autocomplete],["long-tail","Long-tail",e.counts.opportunities]].map(([m,x,g])=>s.jsxs("button",{type:"button",onClick:()=>c(m),className:`rounded-full border px-2.5 py-1 text-body-xs transition ${l===m?"border-outline bg-surface-subtle font-medium text-text-primary":"border-outline-subtle text-text-secondary hover:bg-surface-subtle"}`,children:[x," ",s.jsx("span",{className:"text-text-tertiary",children:g})]},m))}),s.jsx(V,{className:"overflow-hidden p-0",children:s.jsx(dt,{rows:d,columns:Fqe({picked:i,onTogglePick:o,saved:r,onToggleSave:a,onResearch:t,onOpenInCatalogue:n}),getRowKey:m=>m.keyword,paginate:!1,persist:!1,defaultSort:{key:"volume",direction:"desc"},tableClassName:"w-full text-body-sm",empty:{title:"No expansions match this filter."}})}),s.jsx("p",{className:"px-1 text-body-xs text-text-tertiary",children:"Want the gaps vs your own catalogue, or the words your reviews use? Ask the whitespace-keywords or customer-language-miner skills in chat."})]})}function Uqe({onResearch:e,onOpenInCatalogue:t,onRemove:n,picked:r,onTogglePick:a}){const[i,o]=p.useState(null),[l,c]=p.useState(null),[u,d]=p.useState({});p.useEffect(()=>{$t.watchlist().then(f=>o(f.keywords)).catch(()=>o([]))},[]);const h=f=>{if(l===f.id){c(null);return}c(f.id),u[f.keyword]||(d(m=>({...m,[f.keyword]:"loading"})),$t.keywordTrack(f.keyword).then(m=>d(x=>({...x,[f.keyword]:m}))).catch(()=>d(m=>({...m,[f.keyword]:{keyword:f.keyword,marketplace:"takealot",volume_series:[],rank_series:[]}}))))};return i==null?s.jsxs("div",{className:"flex items-center gap-2 px-1 py-4 text-body-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Loading saved keywordsâ¦"]}):i.length===0?s.jsxs(V,{className:"p-6 text-center",children:[s.jsx(e0,{className:"mx-auto mb-2 h-6 w-6 text-text-tertiary"}),s.jsx("p",{className:"text-body-sm text-text-primary",children:"No saved keywords yet"}),s.jsx("p",{className:"mt-1 text-body-xs text-text-secondary",children:"Bookmark keywords from Search or Expand to build a wat
910chlist here, then track their demand and rank over time."})]}):s.jsx(V,{className:"overflow-hidden p-0",children:s.jsx(zqe,{items:i,openId:l,track:u,picked:r,onTogglePick:a,onToggleTrack:h,onResearch:e,onOpenInCatalogue:t,onRemove:f=>{n(f.keyword),o(m=>m&&m.filter(x=>x.id!==f.id))}})})}function zqe({items:e,openId:t,track:n,picked:r,onTogglePick:a,onToggleTrack:i,onResearch:o,onOpenInCatalogue:l,onRemove:c}){const u=f=>f==null?"â":f.toLocaleString("en-ZA"),d=[];a&&d.push({key:"select",label:"",className:"w-8",stopRowClick:!0,render:f=>s.jsx("input",{type:"checkbox",checked:(r==null?void 0:r.has(f.keyword.toLowerCase()))??!1,onChange:()=>a({keyword:f.keyword,volume:f.volume}),"aria-label":`Select ${f.keyword}`})}),d.push({key:"keyword",label:"Keyword",getValue:f=>f.keyword,render:f=>s.jsx("span",{className:"text-text-primary",children:f.keyword})},{key:"trend",label:"Trend",hideBelow:"sm",className:"text-center",render:f=>s.jsx(Ws,{data:f.trend_series,width:72,height:18,className:"text-intent-brand mx-auto"})},{key:"volume",label:"Searches/mo",align:"right",getValue:f=>f.volume,render:f=>s.jsx("span",{className:"text-text-secondary",children:u(f.volume)})},{key:"actions",label:"",align:"right",className:"whitespace-nowrap",stopRowClick:!0,render:f=>s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>i(f),className:`rounded px-2 py-1 text-body-xs transition hover:bg-surface-subtle ${t===f.id?"text-intent-brand":"text-text-secondary hover:text-text-primary"}`,children:"Track"}),s.jsx("button",{type:"button",onClick:()=>o(f.keyword),className:"rounded px-2 py-1 text-body-xs text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary",children:"Details"}),s.jsx("button",{type:"button",onClick:()=>l(f.keyword),className:"rounded px-2 py-1 text-body-xs text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary",children:"Live"}),s.jsx("button",{type:"button",onClick:()=>c(f),className:"rounded px-2 py-1 text-body-xs text-text-tertiary transition hover:bg-surface-subtle hover:text-text-error",title:"Remove from watchlist",children:"Remove"})]})});const h=d.length;return s.jsx(dt,{rows:e,columns:d,getRowKey:f=>f.id,paginate:!1,persist:!1,tableClassName:"w-full text-body-sm",empty:{title:"No saved keywords yet"},renderRow:f=>s.jsxs(s.Fragment,{children:[s.jsx("tr",{className:"border-b border-outline-faint last:border-0 bg-surface hover:bg-surface-subtle/50",children:d.map((m,x)=>s.jsx("td",{className:B("py-2",x===0?"pl-4 pr-3":x===h-1?"pr-4 pl-0":"pr-3",m.align==="right"&&"text-right",m.hideBelow==="sm"&&"hidden sm:table-cell",m.className),onClick:m.stopRowClick?g=>g.stopPropagation():void 0,children:m.render?m.render(f):null},m.key))}),t===f.id&&s.jsx("tr",{children:s.jsx("td",{colSpan:h,className:"bg-surface-subtle/40 px-3 py-3",children:s.jsx(jqe,{data:n[f.keyword]})})})]})})}function Wqe({onOpenInCatalogue:e,onGoValidate:t}){const n=Rw(),[r,a]=p.useState(!1),[i,o]=p.useState(()=>new Map),l=p.useCallback(L=>{const q=L.keyword.trim().toLowerCase();q&&o(me=>{const ee=new Map(me);return ee.has(q)?ee.delete(q):ee.set(q,{...L,keyword:L.keyword.trim()}),ee})},[]),c=mc(),[u,d]=it("mode","browse"),h=bqe.includes(u)?u:"browse",[f]=it("q",""),[m,x]=it("rail","hot"),g=gG.includes(m)?m:"hot",[y,b]=p.useState(f),[v,w]=p.useState(""),[_,k]=p.useState(!1),[j,N]=p.useState(()=>(h==="search"||h==="expand")&&f.trim()?f.trim():null),[E,A]=p.useState(null),[C,T]=p.useState(null),[S,O]=p.useState(!1),[R,I]=p.useState(null),[$,P]=p.useState(new Set),[F,Z]=p.useState([]);p.useEffect(()=>{$t.watchlist().then(L=>P(new Set(L.keywords.map(q=>q.keyword.toLowerCase())))).catch(()=>{}),$t.keywordDiscover().then(L=>Z(L.keywords)).catch(()=>{})},[]);const D=p.useCallback(async L=>{const q=L.trim().toLowerCase();if(!q)return;const me=$.has(q);P(ee=>{const ne=new Set(ee);return me?ne.delete(q):ne.add(q),ne});try{me?await $t.watchlistRemove(L):await $t.watchlistAdd(L)}catch{P(ee=>{const ne=new Set(ee);return me?ne.add(q):ne.delete(q),ne})}},[$]),H=p.useCallback(async(L,q)=>{const me=L.trim();if(me){N(me),b(me),c({mode:q,q:me}),O(!0),I(null);
910try{q==="search"?A(await $t.keyword(me)):T(await $t.keywordExpand(me))}catch(ee){I(ee instanceof Error?ee.message:String(ee)),q==="search"?A(null):T(null)}finally{O(!1)}}},[c]),Y=p.useRef(!1);p.useEffect(()=>{Y.current||(Y.current=!0,(h==="search"||h==="expand")&&f.trim()&&H(f,h))},[]);const M=p.useCallback(async L=>{const q=L.split(/[\n,]/).map(me=>me.trim()).filter(Boolean);if(q.length){N(`${q.length} keywords`),c({mode:"expand",q:null}),O(!0),I(null);try{T(await $t.keywordEnrich(q))}catch(me){I(me instanceof Error?me.message:String(me)),T(null)}finally{O(!1)}}},[c]),z=L=>{L==="browse"?c({mode:null}):L==="saved"?c({mode:"saved"}):(d(L),j&&!_&&H(j,L))},G=p.useCallback(L=>H(L,"search"),[H]),te=h==="search"||h==="expand",re=t;return s.jsx(Dw,{leftRailOpen:r,onCloseLeftRail:()=>a(!1),queryBar:s.jsxs(G3,{running:S,runLabel:h==="expand"?"Expand":"Search",runDisabled:S||te&&!_&&!y.trim()||_&&!v.trim(),onRun:te?()=>{h==="expand"&&_?M(v):(h==="search"||h==="expand")&&H(y,h)}:void 0,children:[s.jsx(Y3,{onClick:()=>a(!0)}),s.jsx(pG,{options:[{key:"browse",label:"Browse"},{key:"search",label:"Search"},{key:"expand",label:"Expand"},{key:"saved",label:$.size?`Saved (${$.size})`:"Saved"}],value:h,onChange:L=>
910z(L)}),h==="search"&&s.jsx(QS,{value:y,onChange:b,placeholder:"Research a keyword â e.g. yoga mat",onSubmit:()=>void H(y,"search"),disabled:S}),h==="expand"&&!_&&s.jsx(QS,{value:y,onChange:b,placeholder:"Expand a seed â e.g. air fryer",onSubmit:()=>void H(y,"expand"),disabled:S}),h==="expand"&&_&&s.jsx("textarea",{value:v,onChange:L=>w(L.target.value),rows:1,placeholder:"Paste keywords â one per line or comma-separated",className:"min-w-[160px] flex-1 rounded-md border border-outline-subtle bg-surface px-2 py-1.5 text-sm"}),h==="expand"&&s.jsx("button",{type:"button",onClick:()=>k(L=>!L),className:"whitespace-nowrap text-xs text-text-secondary underline-offset-2 hover:underline",children:_?"â single seed":"paste a list"})]}),leftRail:s.jsxs(Z3,{children:[h==="browse"&&s.jsx(pd,{label:"Rails",children:Iv.map(L=>s.jsx(Yp,{title:L.label,meta:L.blurb,active:g===L.key,onClick:()=>x(L.key)},L.key))}),h==="saved"&&s.jsx(pd,{label:"Watchlist",children:s.jsx("p",{className:"px-1.5 text-[11px] leading-4 text-text-tertiary",children:$.size?`${$.size} saved phrases`:"Bookmark phrases from Search or Expand."})}),(h==="search"||h==="expand")&&s.jsx(pd,{label:"Recently explored",children:(F.length?F:yqe.map(L=>({keyword:L,volume:null}))).map(L=>s.jsx(Yp,{title:L.keyword,meta:L.volume!=null?`${L.volume.toLocaleString()}/mo`:void 0,onClick:()=>void H(L.keyword,h)},L.keyword))})]}),canvas:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:[s.jsx(sqe,{count:i.size,onAdd:()=>void n.addKeywords([...i.values()]),onClear:()=>o(new Map)}),s.jsx("div",{className:"min-h-0 flex-1 overflow-auto p-4",children:h==="browse"?s.jsx($qe,{hideRails:!0,onResearch:G,onOpenInCatalogue:e,saved:$,onToggleSave:D,picked:i,onTogglePick:l}):h==="saved"?s.jsx(Uqe,{onResearch:G,onOpenInCatalogue:e,onRemove:L=>D(L),picked:i,onTogglePick:l},`saved-${$.size}`):s.jsxs(s.Fragment,{children:[!j&&!S&&s.jsxs(V,{className:"p-6 text-center",children:[s.jsx(Fa,{className:"mx-auto mb-2 h-6 w-6 text-text-tertiary"}),s.jsx("p",{className:"text-body-sm text-text-primary",children:h==="search"?"Research any keyword":"Expand a seed into keyword ideas"}),s.jsx("p",{className:"mx-auto mt-1 max-w-md text-body-xs text-text-secondary",children:h==="search"?"Search volume & trend, competition, estimated CPC, Takealot CPC floor, related keywords, and who currently ranks â all from data we already hold.":"Pull the phrases shoppers actually type (Takealot autocomplete) plus the long-tail around your seed, each scored with real search demand."})]}),R&&s.jsx(V,{className:"border-outline-error bg-surface-errorSubtle p-3 text-body-sm text-text-error",children:R}),S&&j&&s.jsxs("div",{className:"flex items-center gap-2 px-1 py-4 text-body-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Researching â",j,"ââ¦"]}),!S&&h==="search"&&E&&s.jsx(Lqe,{data:E,onSearch:G,onOpenInCatalogue:e,saved:$,onToggleSave:D,picked:i,onTogglePick:l}),!S&&h==="expand"&&C&&s.jsx(Bqe,{data:C,onResearch:G,onOpenInCatalogue:e,saved:$,onToggleSave:D,picked:i,onTogglePick:l})]})})]}),rightPanel:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[s.jsx(J3,{tabs:[{key:"detail",label:"Detail"},{key:"shortlist",label:"Shortlist",badge:n.items.length||void 0}],value:n.rightTab==="brief"?"shortlist":n.rightTab,onChange:L=>n.setRightTab(L)}),n.rightTab==="detail"?s.jsx("div",{className:"flex flex-1 items-center justify-center p-6 text-center text-sm text-text-tertiary",children:"Tick phrases, then add them to the shortlist. Open in Catalogue from a row to inspect listings."}):s.jsx(X3,{items:n.items,onRemove:L=>void n.remove(L),onClear:()=>void n.clear(),onValidate:re})]})})}function vG(e){const t=[""];for(const n of e||[]){if(n.kind==="leaf")break;t.push(n.id)}return t}function Kqe(e){const t=e||[],r=vG(t).map((o,l)=>{var c;return{reactKey:`${l}:${o}`,listKey:o,level:l,title:l===0?"Department":((c=t[l-1])==null?void 0:c.name)??"",shelf:!1,placeholder:null}}),a=t[t.length-1];if((a==null?void 0:a.kind)==="leaf"&&r.length<3){const o=r[r.length-1];r.push({...o,reactKey:`sib:${o.listKey}`,shelf:!0})}r.length>=3&&(r[r.length-1]={...r[r.length-1],shelf:!0});const i=r.slice(Math.max(0,r.length-3));for(;i.length<3;){const o=i.length;i.push({reactKey:`empty-${o}`,listKey:"",level:-1,title:"",shelf:!1,placeholder:o===1?"department":"category"})}return i}const Hqe="Opens this shelf · uses 1 Est Sales lookup";function Vqe({path:e,lists:t,onPick:n,onCrumb:r,collapsed:a,onExpand:i,onCollapse:o}){const l=Kqe(e),c=p.useRef([]),u=e.filter(f=>f.kind==="branch").length>2,d=e.map(f=>f.name).join(" ⺠"),h=e.some(f=>f.kind==="leaf");return a?s.jsxs("div",{className:"hidden shrink-0 items-center gap-3 border-b border-outline-subtle px-3.5 py-1.5 lg:flex",children:[s.jsxs("button",{type:"button",onClick:i,className:"flex min-w-0 flex-1 items-center gap-1.5 text-left text-[13px] text-text-secondary hover:text-text-primary",children:[s.jsx(fr,{className:"h-3.5 w-3.5 shrink-0 text-text-tertiary"}),s.jsx("span",{className:"truncate",children:d||"Categories"})]}),s.jsx("button",{type:"button",onClick:i,className:"shrink-0 text-xs font-medium text-intent-brand",children:"Change shelf"})]}):s.jsxs("div",{className:"hidden shrink-0 flex-col border-b border-outline-subtle lg:flex",children:[u||h?s.jsxs("div",{className:"flex items-center gap-2 px-3.5 pt-2 text-[11px] text-text-tertiary",children:[s.jsx("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1",children:e.map((f,m)=>s.jsxs("span",{className:"inline-flex items-center gap-1",children:[m>0?s.jsx("span",{children:"âº"}):null,f.kind==="leaf"||m===e.length-1?s.jsx("span",{className:"text-text-secondary",children:f.name}):s.jsx("button",{type:"button",className:"hover:text-text-primary hover:underline",onClick:()=>r(m),children:f.name})]},f.id))}),h?s.jsx("button",{type:"button",onClick:o,className:"shrink-0 text-xs text-text-tertiary hover:text-text-primary",children:"Hide categories"}):null]}
910):null,s.jsx("div",{className:"grid h-[228px] grid-cols-[1fr_1fr_1.25fr]",children:l.map((f,m)=>{var x,g,y,b;return s.jsx(qqe,{pane:f,rows:f.placeholder?null:((x=t[f.listKey])==null?void 0:x.rows)??null,loading:f.placeholder?!1:((g=t[f.listKey])==null?void 0:g.loading)??!1,error:f.placeholder?null:((y=t[f.listKey])==null?void 0:y.error)??null,selectedId:f.level>=0?((b=e[f.level])==null?void 0:b.id)??null:null,showReadingCaption:m===2&&!f.placeholder,paneRef:v=>{c.current[m]=v},onPick:v=>n(f.level,v),onMove:v=>{var w;return(w=c.current[m+v])==null?void 0:w.focus()}},f.reactKey)})})]})}function qqe({pane:e,rows:t,loading:n,error:r,selectedId:a,showReadingCaption:i,paneRef:o,onPick:l,onMove:c}){const[u,d]=p.useState(0);p.useEffect(()=>{if(!(t!=null&&t.length))return;const f=t.findIndex(m=>m.id===a);d(f>=0?f:0)},[t,a]);function h(f){if(t!=null&&t.length)if(f.key==="ArrowDown"||f.key==="ArrowUp")f.preventDefault(),d(m=>f.key==="ArrowDown"?Math.min(t.length-1,m+1):Math.max(0,m-1));else if(f.key==="Enter"){f.preventDefault();const m=t[u];m&&l(m)}else f.key==="ArrowRight"?(f.preventDefault(),c(1)):f.key==="ArrowLeft"&&(f.preventDefault(),c(-1))}return s.jsxs("div",{ref:o,tabIndex:e.placeholder?-1:0,onKeyDown:h,className:"flex min-w-0 flex-col overflow-hidden border-r border-outline-subtle outline-none last:border-r-0 focus-visible:bg-surface-subtle/40",children:[s.jsxs("div",{className:"flex items-baseline justify-between gap-2 px-3.5 pb-[5px] pt-[9px]",children:[s.jsx("div",{className:"truncate text-[10.5px] font-semibold uppercase tracking-[0.06em] text-text-tertiary",children:e.title}),i?s.jsx("div",{className:"shrink-0 text-[10.5px] font-semibold uppercase tracking-[0.06em] text-text-tertiary",children:"Reading"}):null]}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:e.placeholder?s.jsx("div",{className:"flex h-full items-center justify-center px-3 text-[13px] text-text-tertiary",children:e.placeholder==="department"?"Pick a department":"Pick a category"}):n&&!t?s.jsx("div",{className:"flex h-full items-center justify-center text-text-tertiary",children:s.jsx(_e,{className:"h-4 w-4 animate-spin"})}):r?s.jsx("p",{className:"px-3.5 py-3 text-[13px] text-text-secondary",children:r}):t==null?void 0:t.map((f,m)=>{const x=f.id===a,g=f.kind==="leaf",y=e.shelf&&g;return s.jsxs("button",{type:"button",title:g?Hqe:void 0,onClick:()=>l(f),className:B("flex w-full items-center gap-2 whitespace-nowrap px-3.5 py-[5px] text-left text-[13px]",x?"bg-surface-brandSubtle font-medium text-text-primary":"text-text-body hover:bg-surface-subtle",!x&&u===m&&"bg-surface-subtle"),children:[y?s.jsx("span",{className:B("h-1.5 w-1.5 shrink-0 rounded-full",f.has_reading?"bg-success-500":"bg-outline")}):null,s.jsx("span",{className:"min-w-0 flex-1 truncate",children:f.name}),y?s.jsx("span",{className:B("shrink-0 text-xs tabular-nums",f.has_reading?"text-text-secondary":"text-text-tertiary"),children:f.has_reading?"Has a reading":"No reading"}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"shrink-0 text-[11px] tabular-nums text-text-tertiary",children:de(f.leaf_count)}),s.jsx(fr,{className:"h-[13px] w-[13px] shrink-0 text-outline"})]})]},f.id)})})]})}function wG(e){return(e||[]).filter(t=>t&&Number.isFinite(Number(t.pace_per_day)))}function Gqe(e){const t=wG(e).map(a=>Number(a.pace_per_day)).sort((a,i)=>a-i);if(!t.length)return null;const n=Math.floor(t.length/2),r=t.length%2?t[n]:(t[n-1]+t[n])/2;return r<10?Math.max(.1,Math.round(r*10)/10):Math.round(r)}function Yqe(e,t){const n=wG(e),r=Number(t);if(!n.length||!Number.isFinite(r)||r<=0)return{kind:"none"};let a=n[0],i=n[0];for(const l of n)Number(l.pace_per_day)>Number(a.pace_per_day)&&(a=l),Number(l.pace_per_day)<Number(i.pace_per_day)&&(i=l);if(r>Number(a.pace_per_day))return{kind:"faster",rankMin:a.rank}
910;if(r<Number(i.pace_per_day))return{kind:"slower",rankMax:i.rank};let o=null;for(const l of n)Number(l.pace_per_day)>=r&&(o==null||l.rank>o.rank)&&(o=l);return o?{kind:"rank",rank:o.rank,revenue:o.revenue_rand_30d??null}:{kind:"none"}}function Rv(e){return e<10?String(e):de(e)}function Zqe(e){if(e.reason==="quota"&&e.cap!=null){const t=e.upgrade_to?` Upgrade to ${e.upgrade_to} for a higher monthly cap.`:"";return`You've used ${e.used??e.cap} of ${e.cap} Est Sales lookups this month.${t} Rank lookups share that pool.`}return"Estimated sales aren't available on this plan."}function Q3({row:e}){return e.pace_per_day!=null?s.jsxs("span",{className:"tabular-nums text-text-primary",children:[Rv(e.pace_per_day),"/day"]}):e.pace_reason==="demo"?s.jsx(nc,{compact:!0}):e.pace_reason==="gated"?s.jsx("span",{className:"text-xs text-text-tertiary",children:"Upgrade"}):e.pace_reason==="out_of_range"?s.jsx("span",{className:"cursor-help text-xs text-text-tertiary",title:"Pace is only shown for ranks this reading was fitted on.",children:"outside range"}):s.jsx(Pv,{})}function Dv({row:e,value:t}){return t!=null?s.jsx("span",{className:"tabular-nums text-text-primary",children:t}):e.pace_per_day!=null?s.jsx("span",{className:"text-text-tertiary",children:"â"}):s.jsx(Q3,{row:e})}function Xqe(e){if(e.pace_per_day==null)return"That rank is outside the measured span.";const t=`${Rv(e.pace_per_day)}/day`;return e.gap_per_day==null?`about ${t}.`:e.gap_per_day===0?`matching the best measured pace (${t}).`:`${Rv(e.gap_per_day)}/day behind the best measured rank.`}function Jqe(e){return e?e.min_rand===e.max_rand?ge(e.min_rand):`${ge(e.min_rand)} â ${ge(e.max_rand)}`:"â"}function Qqe(e){let t=null;for(const n of e)n.pace_per_day!=null&&(t==null||n.pace_per_day>t)&&(t=n.pace_per_day);return t}function _G({title:e,hint:t}){return s.jsxs("div",{className:"py-10 text-center",children:[s.jsx("div",{className:"text-body-sm font-medium text-text-primary",children:e}),t?s.jsx("div",{className:"mt-1 text-body-sm text-text-tertiary",children:t}):null]})}function eGe({rows:e,onOpen:t}){return!e||e.length===0?s.jsx(_G,{title:"Nothing matches.",hint:"Try another name, or clear Measured."}):s.jsx("ul",{className:"divide-y divide-outline-faint overflow-hidden rounded-md border border-outline-subtle bg-surface",children:e.map(n=>s.jsx("li",{children:s.jsxs("button",{type:"button",onClick:()=>t(n),className:"w-full px-3 py-3 text-left",children:[s.jsx("div",{className:"font-medium text-text-primary",children:n.name}),s.jsx("div",{className:"mt-0.5 break-words text-xs text-text-tertiary",children:n.path}),s.jsx("div",{className:"mt-1 text-sm text-text-secondary",children:n.kind==="leaf"?n.has_reading?"Has a reading":"No reading":`${de(n.leaf_count)} shelves · ${de(n.readable_leaves)} with a reading`}),n.best_leaf_name?s.jsxs("div",{className:"mt-1 break-words text-sm text-text-primary",children:["Strongest reading: ",n.best_leaf_name]}):null]})},n.id))})}function tGe(e){const t=[];return e.star_rating!=null&&t.push(`${e.star_rating.toFixed(1)}â
`),e.review_count!=null&&t.push(`${de(e.review_count)} reviews`),e.is_buyable!=null&&t.push(e.is_buyable?"Buyable":"Not buyable"),t.join(" · ")}function nGe({rows:e,youRank:t,targetRank:n}){return!e||e.length===0?s.jsx(_G,{title:"No ranks match.",hint:"Clear the filter to see the full page."}):s.jsx("ul",{className:"divide-y divide-outline-faint overflow-hidden rounded-md border border-outline-subtle bg-surface",children:e.map(r=>{const a=tGe(r),i=t!=null&&r.rank===t,o=n!=null&&r.rank===n;return s.jsx("li",{className:i?"bg-surface-brandSubtle/40":void 0,style:o?{boxShadow:"inset 0 -2px 0 rgb(var(--color-success-500))"}:void 0,children:s.jsxs("div",{className:"px-3 py-3",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"text-xs font-medium text-text-tertiary",children:["#",r.rank,r.brand?` · ${r.brand}`:""]}),s.jsx("div",{className:"mt-0.5 break-words text-sm text-text-primary",children:r.plid?s.jsx("a",{href:`https://www.takealot.com/x/PLID${r.plid}`,target:"_blank",rel:"noopener noreferrer",className:"hover:underline",children:r.title||`PLID ${r.plid}`}):"â"}),i?s.jsx("span",{className:"mt-1 inline-block rounded bg-intent-success/10 px-1.5 py-0.5 text-[10px] text-intent-success",children:"You sell this"}):null]}),s.jsxs("div",{className:"flex shrink-0 flex-col items-end gap-1",children:[s.jsx("div",{className:"text-sm font-semibold tabular-nums text-text-primary",children:r.price_rand!=null?ge(r.price_rand):"â"}),r.plid?s.jsx(Kd,{plid:r.plid,sellPrice:r.price_rand,title:r.title}):null]})]}),s.jsxs("div",{className:"mt-2 flex flex-wrap items-baseline gap-x-3 gap-y-1 text-sm text-text-secondary",children:[s.jsxs("span",{children:["Pace ",s.jsx(Q3,{row:r})]}),s.jsxs("span",{children:["30d ",s.jsx(Dv,{row:r,value:r.units_30d!=null?de(r.units_30d):null})]}),s.jsxs("span",{children:["Rev ",s.jsx(Dv,{row:r,value:r.revenue_rand_30d!=null?ge(r.revenue_rand_30d):null})]})]}),a?s.jsx("div",{className:"mt-1 text-xs text-text-tertiary",children:a}):null]})},r.rank)})})}function rGe(e){return[{key:"rank",label:"Rank",sticky:!0,sortable:!0,align:"right",getValue:t=>t.rank,render:t=>s.jsxs("span",{className:"tabular-nums font-medium text-text-primary",children:["#",t.rank]})},{key:"title",label:"Listing",sortable:!0,getValue:t=>t.title,render:t=>s.jsxs("div",{className:"min-w-0 max-w-md",children:[s.jsx("div",{className:"truncate text-text-primary",title:t.title||"",children:t.plid?s.jsx("a",{href:`https://www.takealot.com/x/PLID${t.plid}`,target:"_blank",rel:"noopener noreferrer",onClick:n=>n.stopPropagation(),className:"hover:underline",children:t.title||`PLID ${t.pl
910id}`}):"â"}),e!=null&&t.rank===e&&s.jsx("span",{className:"mt-1 inline-block rounded bg-intent-success/10 px-1.5 py-0.5 text-[10px] text-intent-success",children:"You sell this"})]})},{key:"brand",label:"Brand",sortable:!0,hideBelow:"md",getValue:t=>t.brand,render:t=>s.jsx("span",{className:"text-text-secondary",children:t.brand||"â"})},{key:"price_rand",label:"Price",align:"right",sortable:!0,getValue:t=>t.price_rand,render:t=>s.jsx("span",{className:"tabular-nums text-text-primary",children:t.price_rand!=null?ge(t.price_rand):"â"})},{key:"star_rating",label:"â
",align:"right",sortable:!0,hideBelow:"xl",getValue:t=>t.star_rating,render:t=>s.jsx("span",{className:"tabular-nums text-text-secondary",children:t.star_rating!=null?t.star_rating.toFixed(1):"â"})},{key:"review_count",label:"Reviews",align:"right",sortable:!0,hideBelow:"xl",getValue:t=>t.review_count,render:t=>s.jsx("span",{className:"tabular-nums text-text-tertiary",children:t.review_count!=null?de(t.review_count):"â"})},{key:"is_buyable",label:"Buyable",hideBelow:"xl",getValue:t=>t.is_buyable==null?null:t.is_buyable?1:0,render:t=>s.jsx("span",{className:"text-text-secondary",children:t.is_buyable==null?"â":t.is_buyable?"Yes":"No"})},{key:"pace_per_day",label:"Pace",align:"right",sortable:!0,title:"Units per day at this rank. Matching the pace does not place a listing here.",getValue:t=>t.pace_per_day,render:t=>s.jsx(Q3,{row:t})},{key:"units_30d",label:"Units / 30d",align:"right",sortable:!0,hideBelow:"md",getValue:t=>t.units_30d,render:t=>s.jsx(Dv,{row:t,value:t.units_30d!=null?de(t.units_30d):null})},{key:"revenue_rand_30d",label:"Est. revenue",align:"right",sortable:!0,getValue:t=>t.revenue_rand_30d,render:t=>s.jsx(Dv,{row:t,value:t.revenue_rand_30d!=null?ge(t.revenue_rand_30d):null})},{key:"profit",label:"",stopRowClick:!0,render:t=>t.plid?s.jsx(Kd,{plid:t.plid,sellPrice:t.price_rand,title:t.title}):null}]}function sGe({rows:e,youRank:t,targetRank:n}){return s.jsx(dt,{rows:e,columns:rGe(t),getRowKey:r=>r.rank,density:"compact",persist:!1,paginate:!1,defaultSort:{key:"rank",direction:"asc"},rowClassName:r=>{const a=t!=null&&r.rank===t,i=n!=null&&r.rank===n;return[a?"bg-surface-brandSubtle/40":"",i?"shadow-[inset_0_-2px_0_rgb(var(--color-success-500))]":""].filter(Boolean).join(" ")},empty:{title:"No ranks match.",hint:"Clear the filter to see the full page."}})}const aGe=[{key:"pace",label:"Has a pace",predicate:e=>e.pace_per_day!=null}];function iGe({leaf:e,rows:t,filter:n,onFilter:r,activeChips:a,onToggleChip:i,onClearChips:o,targetRaw:l,onTarget:c,onOpenKeyword:u,onCrumb:d}){var _,k,j,N,E;const h=Gqe(e.rows),f=l===""?h:Number(l),m=Yqe(e.rows,f),x=m.kind==="rank"?m.rank:null,g=((_=e.est_sales_meta)==null?void 0:_.reason)==="demo_locked"||e.rows.some(A=>A.pace_reason==="demo"),y=h!=null,b=Qqe(e.rows),v=(k=e.est_sales_meta)==null?void 0:k.gate,w=e.crumbs.slice(0,-1);return s.jsxs("div",{className:"lg:flex lg:min-h-0 lg:flex-1 lg:flex-col lg:overflow-hidden",children:[s.jsxs("div",{className:"grid gap-4 border-b border-outline-subtle px-4 py-3.5 lg:shrink-0 lg:grid-cols-[minmax(0,1fr)_300px_290px] lg:gap-[22px] lg:px-[18px]",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{className:"truncate text-[17px] font-semibold text-text-primary",children:e.display_name}),s.jsxs("div",{className:"mt-0.5 truncate text-[11px] text-text-tertiary",children:[w.map((A,C)=>s.jsxs("span",{children:[C>0?" ⺠":"",s.jsx("button",{type:"button",className:"hover:text-text-primary hover:underline",onClick:()=>d(C),children:A.name})]},A.id)),e.age_label?s.jsxs("span",{children:[w.length?" · ":"","snapshot ",e.age_label]}):null]}),s.jsxs("div",{className:"mt-3 flex flex-wrap items-end justify-between gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-x-[22px] gap-y-2",children:[s.jsx(hy,{label:"Listings",value:e.num_docs!=null?de(e.num_docs):"â"}),s.jsx(hy,{label:"Page-1 price",value:Jqe(e.price_band)}),s.jsx(hy,{label:"Top pace",value:b!=null?`${Rv(b)}/day`:"â"}),s.jsx(hy,{label:"Fitted ranks",value:e.rank_min!=null&&e.rank_max!=null?`${e.rank_min}â${e.rank_max}`:"â"})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(hu,{chips:aGe,activeChips:a,onToggle:i,onClear:o}),s.jsx(Ni,{value:n,onChange:r,placeholder:"Filter these ranks",hotkey:!1,className:"w-44"})]})]}),e.you?s.jsxs("p",{className:"mt-2.5 text-[13px] text-text-primary",children:["You're at rank ",s.jsxs("span",{className:"font-semibold",children:["#",e.you.rank]}),", ",Xqe(e.you),e.keyword?s.jsxs("button",{type:"button",onClick:()=>u(e.keyword.term),className:"ml-1.5 font-medium text-intent-brandHover hover:underline",children:[e.keyword.term,e.keyword.avg_monthly_searches!=null?` · ${de(e.keyword.avg_monthly_searches)} searches/mo`:""]}):null]}):null,e.note?s.jsx("p",{className:"mt-1 text-[13px] text-text-secondary",children:e.note}):null,v?s.jsx("p",{className:"mt-1 text-[13px] text-text-secondary",children:Zqe(v)}):null]}),s.jsx(cGe,{leaf:e,target:y?f:null,youRank:((j=e.you)==null?void 0:j.rank)??null}),g?s.jsx("div",{className:"flex items-center",children:s.jsx(nc,{})}):y?s.jsx(oGe,{hit:m,shown:l===""&&h!=null?String(h):l,onTarget:c}):s.jsx("div",{})]}),s.jsxs("div",{className:"px-4 py-3 lg:min-h-0 lg:flex-1 lg:overflow-auto lg:px-0 lg:py-0",children:[s.jsx("div",{className:"lg:hidden",children:s.jsx(nGe,{rows:t,youRank:((N=e.you)==null?void 0:N.rank)??null,targetRank:x})}),s.jsx("div",{className:"hidden lg:block",children:s.jsx(sGe,{rows:t,youRank:((E=e.you)==null?void 0:E.rank)??null,targetRank:x})})]})]})}function hy({label:e,value:t}){return s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[11px] leading-4 text-text-tertiary",children:e}),s.jsx("div",{className:"mt-px text-[15px] font-semibold tabular-nums text-text-primary",children:t})]})}function oGe({hit:e,shown:t,onTarget:n}){return s.jsxs("div",{className:"rounded-[10px] border border-outline-subtle bg-surface-subtle px-3.5 py-3",children:[s.jsx("div",{className:"text-[11px] text-text-tertiary",children:"Listings selling"}),s.jsxs("div",{className:"mt-1 flex items-center gap-2 text-[13px] text-text-body",children:[s.jsx(Re,{inputSize:"sm",type:"number",min:.1,step:"any",value:t,onChange:r=>n(r.target.value),"aria-label":"Units a day",className:"w-[62px] text-center font-semibold tabular-nums"}),"units a day"]}),s.jsx("div",{className:"mt-2 text-[13px] text-text-body",children:"sit at rank"}),s.jsx(lGe,{hit:e})]})}function lGe({hit:e}){if(e.kind==="faster")return s.jsxs("p",{className:"mt-0.5 text-[11px] text-text-tertiary",children:[s.jsxs("span",{className:"text-[15px] font-semibold",children:["above #",e.rankMin]})," · faster than any measured rank"]});if(e.kind==="slower")return s.jsxs("p",{className:"mt-0.5 text-[11px] text-text-tertiary",children:[s.jsxs("span",{className:"text-[15px] font-semibold",children:["below #",e.rankMax]})," · outside the measured span"]});if(e.kind!=="rank")return s.jsx("p",{className:"mt-0.5 text-[11px] text-text-tertiary",children:"#â"});const t=e.revenue!=null?` · â ${ge(e.revenue)} / 30d`:"";return s.jsxs("p",{className:"mt-0.5 text-[11px] text-text-tertiary",children:[s.jsxs("span",{className:"text-[26px] font-semibold leading-none text-intent-success",children:["#",e.rank]}),` and above${t}`]})}function cGe({leaf:e,target:t,youRank:n}){const r=p.useMemo(()=>e.rows.filter(i=>i.pace_per_day!=null&&i.rank>=(e.rank_min??i.rank)&&i.rank<=(e.rank_max??i.rank)).map(i=>({rank:i.rank,pace:i.pace_per_day})).sort((i,o)=>i.rank-o.rank),[e]),a=e.rank_min!=null&&e.rank_max!=null?`Pace by rank · fitted #${e.rank_min}â${e.rank_max}`:"Pace by rank";return s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[11px] text-text-tertiary",children:a}),r.length?s.jsx(uGe,{points:r,target:t,youRank:n}):null]})}function uGe({points:e,target:t,youRank:n}){const h=e[0].rank,f=e[e.length-1].rank,m=Math.max(...e.map(j=>j.pace),1e-4),x=j=>8+(f===h?284/2:(j-h)/(f-h)*284),g=j=>8+(1-j/m)*78,y=e.map(j=>`${x(j.rank)},${g(j.pace)}`).join(" "),b=`M ${x(e[0].rank)} ${g(e[0].pace)} ${e.slice(1).map(j=>`L ${x(j.rank)} ${g(j.pace)}`).join(" ")} L ${x(e[e.length-1].rank)}
910 86 L ${x(e[0].rank)} 86 Z`,v=t!=null?dGe(e,t):null,w=n!=null?e.find(j=>j.rank===n):null,_=Math.round((h+f)/2),k=h===f?[h]:[h,_,f];return s.jsxs("svg",{viewBox:"0 0 300 104",className:"mt-1 h-[104px] w-full max-w-[300px]",role:"img","aria-label":"Pace by rank",children:[s.jsx("path",{d:b,className:"fill-brand-500/10"}),s.jsx("polyline",{points:y,fill:"none",className:"stroke-brand-500",strokeWidth:2}),v?s.jsx("line",{x1:8,x2:292,y1:g(v.pace),y2:g(v.pace),className:"stroke-success-500",strokeWidth:1,strokeDasharray:"3 3"}):null,v?s.jsx("circle",{cx:x(v.rank),cy:g(v.pace),r:3.5,className:"fill-success-500"}):null,w?s.jsx("circle",{cx:x(w.rank),cy:g(w.pace),r:4,className:"fill-surface stroke-intent-brand",strokeWidth:2}):null,k.map(j=>s.jsxs("text",{x:x(j),y:102,textAnchor:j===h?"start":j===f?"end":"middle",className:"fill-text-tertiary text-[11px]",children:["#",j]},j))]})}function dGe(e,t){const n=Math.max(...e.map(i=>i.pace)),r=Math.min(...e.map(i=>i.pace));if(t>n||t<r)return null;for(let i=0;i<e.length-1;i++){const o=e[i],l=e[i+1],c=Math.max(o.pace,l.pace),u=Math.min(o.pace,l.pace);if(t<u||t>c||o.pace===l.pace)continue;const d=(o.pace-t)/(o.pace-l.pace);return{rank:o.rank+d*(l.rank-o.rank),pace:t}}const a=e.find(i=>i.pace===t);return a?{rank:a.rank,pace:a.pace}:null}function hGe({collapsed:e,pathLabel:t,onExpand:n,showBack:r,backLabel:a,onBack:i,filter:o,onFilter:l,chips:c,activeChips:u,onToggleChip:d,onClearChips:h,loading:f,error:m,rows:x,onOpen:g}){return e?s.jsxs("div",{className:"sticky top-0 z-10 flex items-center gap-3 border-b border-outline-subtle bg-surface px-3.5 py-2 lg:hidden",children:[s.jsxs("button",{type:"button",onClick:n,className:"flex min-w-0 flex-1 items-center gap-1.5 text-left text-[13px] text-text-secondary",children:[s.jsx(fr,{className:"h-3.5 w-3.5 shrink-0 text-text-tertiary"}),s.jsx("span",{className:"truncate",children:t||"Categories"})]}),s.jsx("button",{type:"button",onClick:n,className:"shrink-0 text-xs font-medium text-intent-brand",children:"Change shelf"})]}):s.jsxs("div",{className:"border-b border-outline-subtle px-4 py-3 lg:hidden",children:[r?s.jsxs("button",{type:"button",className:"mb-3 text-[13px] text-text-secondary hover:text-text-primary hover:underline",onClick:i,children:["â¹ ",a]}):null,s.jsx(Ni,{value:o,onChange:l,placeholder:"Filter this list",hotkey:!1,className:"mb-3"}),s.jsx(hu,{chips:c,activeChips:u,onToggle:d,onClear:h,className:"mb-3"}),f?s.jsxs("div",{className:"flex items-center gap-2 py-8 text-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Loading ranksâ¦"]}):m?s.jsx("p",{className:"py-6 text-sm text-text-secondary",children:m}):s.jsx(eGe,{rows:x,onOpen:g})]})}const kG="me.ranks.recent",jG=5;function NG(){try{const e=JSON.parse(localStorage.getItem(kG)||"[]");return Array.isArray(e)?e.filter(t=>t&&typeof t.id=="string"&&typeof t.name=="string").slice(0,jG):[]}catch{return[]}}function fGe(e,t){const n=[{id:e,name:t},...NG().filter(r=>r.id!==e)].slice(0,jG);try{localStorage.setItem(kG,JSON.stringify(n))}catch{}return n}const TL=[{key:"measured",label:"Measured",predicate:e=>e.has_reading}],mGe=[{key:"pace",label:"Has a pace",predicate:e=>e.pace_per_day!=null}],gj=new Map;function pGe(e){return e.crumbs.map((t,n)=>({id:t.id,name:t.name,kind:n===e.crumbs.length-1?"leaf":"branch"}))}function xGe({onOpenKeyword:e}){var re,L,q,me,ee,ne;const[t,n]=it("rank",""),[r,a]=it("target",""),[i,o]=p.useState(""),[l,c]=p.useState(""),[u,d]=p.useState(""),[h,f]=p.useState([]),[m,x]=p.useState({}),[g,y]=p.useState(null),[b,v]=p.useState(!1),[w,_]=p.useState(null),[k,j]=p.useState(()=>NG()),[N,E]=p.useState(null),[A,C]=p.useState(!1),T=p.useRef(0),S=p.useRef(null),O=vG(h).join("\0");p.useEffect(()=>{c("")},[t]),p.useEffect(()=>{if(!t){y(null),_(null),v(!1);return}let X=!1;return y(null),v(!0),_(null),$t.ranksLeaf(t).then(he=>{var ae;X||(y(he),f(pGe(he)),j(fGe(he.category_id,he.display_name)),C(!1),(ae=he.est_sales_meta)!=null&&ae.usage&&E(he.est_sales_meta.usage))}).catch(he=>{X||_(he instanceof Error?he.message:"Couldn't load ranks")}).finally(()=>{X||v(!1)}),()=>{X=!0}},[t]),p.useEffect(()=>{let X=!1;const he=O.split("\0");for(const ae of he){const je=gj.get(ae);if(je){x($e=>{var J;return((J=$e[ae])==null?void 0:J.rows)===je?$e:{...$e,[ae]:{rows:je,loading:!1,error:null}}});continue}x($e=>{var J;
910return{...$e,[ae]:{rows:((J=$e[ae])==null?void 0:J.rows)??null,loading:!0,error:null}}}),$t.ranksTree(ae||void 0).then($e=>{gj.set(ae,$e.rows),!X&&x(J=>({...J,[ae]:{rows:$e.rows,loading:!1,error:null}}))}).catch($e=>{if(X)return;const J=$e instanceof Error?$e.message:"Couldn't load ranks";x(Ne=>({...Ne,[ae]:{rows:null,loading:!1,error:J}}))})}return()=>{X=!0}},[O]);function R(X,he){T.current+=1;const ae=h.slice(0,X).concat({id:he.id,name:he.name,kind:he.kind==="leaf"?"leaf":"branch"});f(ae),C(he.kind!=="leaf"),n(he.kind==="leaf"?he.id:"")}function I(){const X=h.filter(he=>he.kind==="branch");if(X.length<=1){T.current+=1,C(!0),f([]),n("");return}$(X.length-2)}function $(X){T.current+=1;const he=h[X];!he||he.kind==="leaf"||(C(!0),f(h.slice(0,X+1)),n(""))}async function P(X){var ae;const he=++T.current;o("");try{const je=await $t.ranksTree(X);if(he!==T.current)return;if(gj.set(X,je.rows),((ae=je.parent)==null?void 0:ae.kind)==="leaf"){n(X);return}je.parent&&(n(""),f(je.parent.crumbs.map($e=>({id:$e.id,name:$e.name,kind:"branch"}))))}catch(je){_(je instanceof Error?je.message:"Couldn't load ranks")}}const F=p.useMemo(()=>{if(!g)return null;const X=l.trim().toLowerCase();return X?g.rows.filter(he=>`${he.title??""} ${he.brand??""} ${he.plid??""}`.toLowerCase().includes(X)):g.rows},[g,l]),Z=tu(F,mGe,{urlKey:"rankPace"}),D=((re=[...h].reverse().find(X=>X.kind==="branch"))==null?void 0:re.id)??"",H=h.filter(X=>X.kind==="branch").length,Y=((L=m[D])==null?void 0:L.rows)??null,M=p.useMemo(()=>{if(!Y)return null;const X=u.trim().toLowerCase();return X?Y.filter(he=>`${he.name} ${he.path} ${he.best_leaf_name??""}`.toLowerCase().includes(X)):Y},[Y,u]),z=tu(M,TL,{urlKey:"rankChips"});p.useEffect(()=>{d("")},[D]),p.useEffect(()=>{var X;(!g||A)&&((X=S.current)==null||X.scrollTo({top:0}))},[A,D,g]);const G=g?((q=g.est_sales_meta)==null?void 0:q.usage)??null:N,te=G?G.remaining:null;return s.jsx(Dw,{bare:!0,queryBar:s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5 px-4 py-2.5",children:[s.jsx(q3,{variant:"search",value:i,onChange:o,onPick:X=>void P(X.category_id),placeholder:"Jump to any shelfâ¦"}),k.length>0?s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 overflow-x-auto",children:[s.jsx("span",{className:"shrink-0 text-[10.5px] font-semibold uppercase tracking-[0.06em] text-text-tertiary",children:"Recent"}),k.map(X=>{const he=X.id===t;return s.jsxs("button",{type:"button",title:"Opens this shelf · uses 1 Est Sales lookup",onClick:()=>{T.current+=1,n(X.id)},className:B("inline-flex shrink-0 items-center gap-1 rounded-full border px-2.5 py-[3px] text-xs",he?"border-outline-brand bg-surface-brandSubtle font-medium text-intent-brandHover":"border-outline-subtle bg-surface text-text-secondary hover:bg-surface-subtle"),children:[s.jsx(r0,{className:"h-3 w-3"}),X.name]},X.id)})]}):s.jsx("div",{className:"flex-1"}),te!=null?s.jsxs("div",{className:"shrink-0 text-[11px] text-text-tertiary",children:[te," Est Sales lookups left"]}):null]}),leftRail:null,rightPanel:null,canvas:s.jsxs("div",{ref:S,className:"min-h-0 flex-1 overflow-y-auto overscroll-y-contain lg:flex lg:flex-col lg:overflow-hidden",children:[s.jsx(Vqe,{path:h,lists:m,onPick:R,onCrumb:$,collapsed:!!g&&!A,onExpand:()=>C(!0),onCollapse:()=>C(!1)}),s.jsx(hGe,{collapsed:!!g&&!A,pathLabel:h.map(X=>X.name).join(" ⺠"),onExpand:()=>C(!0),showBack:h.some(X=>X.kind==="branch"),backLabel:((me=h.filter(X=>X.kind==="branch").slice(-1)[0])==null?void 0:me.name)??"Back",onBack:I,filter:u,onFilter:d,chips:TL,activeChips:z.activeChips,onToggleChip:z.toggleChip,onClearChips:z.clearChips,loading:!!((ee=m[D])!=null&&ee.loading)&&!Y,error:((ne=m[D])==null?void 0:ne.error)??null,rows:z.filtered,onOpen:X=>R(H,X)}),g?s.jsx(iGe,{leaf:g,rows:Z.filtered,filter:l,onFilter:c,activeChips:Z.activeChips,onToggleChip:Z.toggleChip,onClearChips:Z.clearChips,targetRaw:r,onTarget:a,onOpenKeyword:e,onCrumb:$}):s.jsx("div",{className:"lg:min-h-0 lg:flex-1 lg:overflow-auto",children:b?s.jsxs("div",{className:"flex items-center gap-2 px-4 py-8 text-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Loading ranksâ¦"]}):w?s.jsx("p",{className:"px-4 py-6 text-sm text-text-secondary",children:w}):s.jsx("p",{className:"hidden px-4 py-6 text-[13px] text-text-secondary lg:block",children:"Pick a shelf to see its ranks. Opening a shelf uses one Est Sales lookup."})})]})})}function Zp(e){return e.plid!=null?`plid:${e.plid}`:`pos:${e.position}`}const gGe=[25,50,100],t2={inStockOnly:!1,priceMin:null,priceMax:null,brands:new Set,minRating:null,hideMyCatalogue:!1};function yGe(e,t){return e.filter(n=>{var r;return!(t.inStockOnly&&n.in_stock!==!0||t.priceMin!=null&&(n.selling_price==null||n.selling_price<t.priceMin)||t.priceMax!=null&&(n.selling_price==null||n.selling_price>t.priceMax)||t.brands.size>0&&(!n.brand||!t.brands.has(n.brand))||t.minRating!=null&&(n.star_rating==null||n.star_rating<t.minRating)||t.hideMyCatalogue&&((r=n.seller_badges)!=null&&r.includes("my_catalogue")))})}function bGe(e){const t=e.map(a=>a.opportunity_score).filter(a=>typeof a=="number").sort((a,i)=>a-i);if(t.length===0)return{max:null,median:null,scored_count:0};const n=Math.floor(t.length/2),r=t.length%2===1?t[n]:Math.round((t[n-1]+t[n])/2);return{max:t[t.length-1],median:r,scored_count:t.length}}function vGe(e){const t=e.map(a=>a.wishlist_30_days).filter(a=>typeof a=="number").sort((a,i)=>a-i);if(t.length===0)return{known_count:0,median_30d:null};const n=Math.floor(t.length/2),r=t.length%2===1?t[n]:Math.round((t[n-1]+t[n])/2);return{known_count:t.length,median_30d:r}}function wGe(e,t){if(e.length===0)return{...t,total_listings:0,price:{min:null,median:null,max:null,currency:t.price.currency},top_brands:[],in_stock_pct:null,total_est_revenue_rand_30d:null,est_sales_enriched_count:0,opportunity:{max:null,median:null,scored_count:0},wishlist:{known_count:0,median_30d:null}};const n=e.map(u=>u.selling_price).filter(u=>typeof u=="number").sort((u,d)=>u-d),r=n.length===0?null:n.length%2===1?n[(n.length-1)/2]:(n[n.length/2-1]+n[n.length/2])/2,a=new Map;for(const u of e)u.brand&&a.set(u.brand,(a.get(u.brand)||0)+1);const i=[...a.entries()].sort((u,d)=>d[1]-u[1]).slice(0,3).map(([u,d])=>({brand:u,count:d,share:Number((d/e.length).toFixed(3))})),o=e.filter(u=>u.in_stock===!0).length,l=e.map(u=>u.est_revenue_rand_30d).filter(u=>typeof u=="number"),c=l.length===0?null:Math.round(l.reduce((u,d)=>u+d,0));return{...t,total_listings:e.length,price:{min:n[0]??null,median:r,max:n[n.length-1]??null,currency:t.price.currency},top_brands:i,in_stock_pct:Number((o/e.length*100).toFixed(1)),total_est_revenue_rand_30d:c,est_sales_enriched_count:l.length,opportunity:bGe(e),wishlist:vGe(e)}}function _Ge(e){const t=new Map;for(const n of e)n.brand&&t.set(n.brand,(t.get(n.brand)||0)+1);return[...t.entries()].map(([n,r])=>({brand:n,count:r})).sort((n,r)=>r.count-n.count)}const kGe=[{key:"opportunity_score",label:"Opportunity"},{key:"brand",label:"Brand"},{key:"star_rating",label:"Rating"},{key:"reviews",label:"Reviews"},{key:"est_units_30d",label:"Est Sales"},{key:"est_revenue_rand_30d",label:"Est Rev"},{key:"wishlist_30_days",label:"Wishlist 30d"},{key:"price_trend",label:"Price trend"},{key:"rank_trend",label:"Rank trend"},{key:"stock",label:"Stock"}],jGe=new Set(["opportunity_score","reviews","est_revenue_rand_30d","wishlist_30_days"]);function NGe(e){const t=[{key:"position",label:"Rank"},{key:"title",label:"Title"}];return e.has("opportunity_score")&&t.push({key:"opportunity_score",label:"Opportunity (0â100)"}),e.has("brand")&&t.push({key:"brand",label:"Brand"}),t.push({key:"selling_price",label:"Price (ZAR)"}),e.has("star_rating")&&t.push({key:"star_rating",label:"Rating"}),e.has("reviews")&&t.push({key:"reviews",label:"Reviews"}),e.has("est_units_30d")&&t.push({key:"est_units_30d",label:"Est Sales (30d units)"}),e.has("est_revenue_rand_30d")&&t.push({key:"est_revenue_rand_30d",label:"Est Revenue (30d ZAR)"}),e.has("wishlist_30_days")&&t.push({key:"wishlist_30_days",label:"Wishlist (30d)"}),e.has("stock")&&t.push({key:"in_stock",label:"In stock"}),t.push({key:"plid",label:"PLID"}),t}function SGe(e){return e.map(t=>({position:t.position+1,title:t.title??"",opportunity_score:t.opportunity_score??"",brand:t.brand??"",selling_price:t.selling_price??"",star_rating:t.star_rating??"",reviews:t.reviews??"",est_units_30d:t.est_units_30d??"",est_revenue_rand_30d:t.est_revenue_rand_30d??"",wishlist_30_days:t.wishlist_30_days??"",in_stock:t.in_stock===!0?"Yes":t.in_stock===!1?"No":"",plid:t.plid??""}))}function SG({visibleCols:e,onToggleCol:t,onExport:n,exportDisabled:r}){return s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("details",{className:"relative",children:[s.jsxs("summary",{className:"list-none inline-flex items-center gap-1 cursor-pointer text-xs font-medium text-text-secondary hover:text-text-primary",children:[s.jsx($2,{className:"w-3.5 h-3.5"})," Columns"]}),s.jsx("div",{className:"absolute right-0 z-20 mt-1 w-44 rounded-md border border-outline-subtle bg-surface shadow-md p-2 space-y-0.5",children:kGe.map(a=>s.jsxs("label",{className:"flex items-center gap-2 px-1 py-0.5 text-xs text-text-secondary cursor-pointer hover:text-text-primary",children:[s.jsx("input",{type:"checkbox",checked:e.has(a.key),onChange:()=>t(a.key)}),a.label]},a.key))})]}),s.jsxs("details",{className:"relative",children:[s.jsxs("summary",{className:B("list-none inline-flex items-center gap-1 cursor-pointer text-xs font-medium",r?"text-text-tertiary cursor-not-allowed":"text-text-secondary hover:text-text-primary"),children:[s.jsx(Dr,{className:"w-3.5 h-3.5"})," Export"]}),s.jsxs("div",{className:"absolute right-0 z-20 mt-1 w-32 rounded-md border border-outline-subtle bg-surface shadow-md p-1",children:[s.jsx("button",{disabled:r,onClick:()=>n("xlsx"),className:"block w-full text-left text-xs px-2 py-1 rounded text-text-secondary hover:bg-surface-subtle disabled:opacity-50",children:"Excel (.xlsx)"}),s.jsx("button",{disabled:r,onClick:()=>n("csv"),className:"block w-full text-left text-xs px-2 py-1 rounded text-text-secondary hover:bg-surface-subtle disabled:opacity-50",children:"CSV (.csv)"})]})]})]})}function CGe(e){const{estLocked:t,visibleCols:n,selectedKeys:r,allRowKeys:a,onToggleRow:i,onToggleAll:o}=e,l=!!(a!=null&&a.length)&&!!r&&a.every(u=>r.has(u)),c=[];return i&&c.push({key:"select",label:"",className:"w-8",stopRowClick:!0,headerPrefix:s.jsx("input",{type:"checkbox",checked:l,onChange:()=>o==null?void 0:o(a||[],!l),"aria-label":"Select all listings"}),render:u=>s.jsx("input",{type:"checkbox",checked:(r==null?void 0:r.has(Zp(u)))??!1,onChange:()=>i(Zp(u)),"aria-label":"Select listing"})}),c.push({key:"position",label:"#",sortable:!0,className:"w-10",align:"right",getValue:u=>u.position,render:u=>s.jsx("span",{className:"text-text-tertiary tabular-nums",children:u.position+1})},{key:"image",label:"Img",className:"w-14",render:u=>u.image_url?s.jsx("img",{src:u.image_url,alt:"",className:"w-10 h-10 rounded object-contain bg-surface-subtle"}):s.jsx("div",{className:"w-10 h-10 rounded bg-surface-subtle grid place-items-center text-text-tertiary",children:s.jsx(nx,{className:"w-3 h-3"})})},{key:"title",label:"Title",sortable:!0,className:"max-w-md",getValue:u=>u.title,render:u=>s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"truncate text-text-primary",title:u.title||"",children:u.title||"â"}),u.seller_badges&&u.seller_badges.length>0&&s.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[u.seller_badges.includes("my_catalogue")&&s.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-intent-success/10 text-intent-success",children:"You sell this"}),u.seller_badges.includes("adjacent")&&s.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-surface-brandSubtle text-text-brand",children:"Near your range"}),u.seller_badges.includes("in_folders")&&s.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-surface-subtle text-text-tertiary",children:"In a saved folder"})]})]})}),n.has("opportunity_score")&&c.push({key:"opportunity_score",label:"Opp",sortable:!0,align:"right",title:"Opportunity = demand à beatability (thin reviews / weak rating) à margin headroom (room left after Takealot's standard fees). 0â100.",getValue:u=>u.opportunity_score,render:u=>t?s.jsx(nc,{compact:!0}):s.jsx(Tqe,{score:u.opportunity_score??null,factors:u.opportunity_factors})}),n.has("brand")&&c.push({key:"brand",label:"Brand",sortable:!0,getValue:u=>u.brand,render:u=>s.jsx("span",{className:"text-text-secondary",children:u.brand||"â"})}),c.push({key:"selling_price",label:"Price",sortable:!0,align:"right",getValue:u=>u.selling_price,render:u=>s.jsx("span",{className:"text-text-primary tabular-nums",children:u.selling_price!=null?ge(u.selling_price):"â"})}),n.has("price_trend")&&c.push({key:"price_trend",label:"Price",align:"right",title:"Price history from prior snapshots (current price last). Fills in as history deepens.",render:u=>s.jsxs("span",{className:B("inline-flex justify-end",Eqe(u.price_history)),title:Aqe(u.price_history),children:[u.price_trend_dir==="up"&&s.jsx("span",{className:"mr-1 text-xs",children:"â"}),u.price_trend_dir==="down"&&s.jsx("span",{className:"mr-1 text-xs",children:"â"}),u.price_trend_dir==="flat"&&s.jsx("span",{className:"mr-1 text-xs",children:"â"}),s.jsx(Ws,{data:u.price_history})]})}),n.has("rank_trend")&&c.push({key:"rank_trend",label:"Rank",align:"right",title:"Keyword rank history from prior Market Explorer searches.",render:u=>s.jsx("span",{className:"inline-flex justify-end text-text-secondary",children:s.jsx(Ws,{data:u.rank_history})})}),n.has("star_rating")&&c.push({key:"star_rating",label:"â
",sortable:!0,align:"right",getValue:u=>u.star_rating,render:u=>s.jsx("span",{className:"text-text-secondary tabular-nums",children:u.star_rating!=null?u.star_rating.toFixed(1):"â"})}),n.has("reviews")&&c.push({key:"reviews",label:"Reviews",sortable:!0,align:"right",getValue:u=>u.reviews,render:u=>s.jsx("span",{className:"text-text-tertiary tabular-nums",children:u.reviews!=null?u.reviews.toLocaleStr
910ing():"â"})}),n.has("est_units_30d")&&c.push({key:"est_units_30d",label:"Est Sales",sortable:!0,align:"right",getValue:u=>u.est_units_30d,render:u=>s.jsx("span",{className:"text-text-secondary tabular-nums",children:t?s.jsx(nc,{compact:!0}):u.est_units_30d!=null?`${u.est_units_30d.toLocaleString()}/mo`:s.jsx(Pv,{})})}),n.has("est_revenue_rand_30d")&&c.push({key:"est_revenue_rand_30d",label:"Est Rev",sortable:!0,align:"right",getValue:u=>u.est_revenue_rand_30d,render:u=>s.jsx("span",{className:"text-text-primary tabular-nums",children:t?s.jsx(nc,{compact:!0}):u.est_revenue_rand_30d!=null?ge(u.est_revenue_rand_30d):s.jsx(Pv,{})})}),n.has("wishlist_30_days")&&c.push({key:"wishlist_30_days",label:"Wishlist 30d",sortable:!0,align:"right",title:"Takealot wishlist adds in the last 30 days. Product-level â every seller on this PLID sees the same count. A dash means no Gadjet seller lists this product, so we have no offer to read the number from.",getValue:u=>u.wishlist_30_days,render:u=>{const d=[u.wishlist_30_days!=null?`${u.wishlist_30_days.toLocaleString()} wishlist adds in 30 days (shared across every seller on this PLID)`:"No Gadjet seller lists this PLID â wishlist is only on offers we sync",u.primary_keyword&&u.avg_monthly_searches!=null?`Primary keyword â${u.primary_keyword}â · ${u.avg_monthly_searches.toLocaleString()}/mo ZA searches`:u.primary_keyword?`Primary keyword â${u.primary_keyword}â`:null].filter(Boolean).join(". ");return s.jsx("span",{className:"text-text-secondary tabular-nums",title:d,children:u.wishlist_30_days!=null?u.wishlist_30_days.toLocaleString():"â"})}}),n.has("stock")&&c.push({key:"stock",label:"Stock",className:"text-center",getValue:u=>u.in_stock===!0?1:u.in_stock===!1?0:null,render:u=>s.jsx("span",{className:B("text-xs px-1.5 py-0.5 rounded",u.in_stock===!0?"bg-intent-success/10 text-intent-success":"bg-surface-subtle text-text-tertiary"),children:u.in_stock===!0?"Yes":u.in_stock===!1?"OOS":"â"})}),c.push({key:"pdp",label:"",className:"w-8 text-center",stopRowClick:!0,header:s.jsx("span",{className:"sr-only",children:"PDP"}),render:u=>{const d=u.plid?`https://www.takealot.com/${u.slug||"x"}/PLID${u.plid}`:null;return s.jsxs("div",{className:"inline-flex items-center gap-1",children:[u.plid!=null&&s.jsx(Kd,{plid:u.plid,sellPrice:u.selling_price,title:u.title}),s.jsx(xG,{plid:u.plid,title:u.title,suggestedPrice:u.selling_price}),d&&s.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",className:"text-text-tertiary hover:text-intent-brand inline-flex",title:"Open on Takealot",children:s.jsx(Qt,{className:"w-3.5 h-3.5"})})]})}}),c}function EGe({rows:e,searchId:t,activeFolderId:n,quota:r,onSaveClick:a,estLocked:i=!1,visibleCols:o,onToggleCol:l,onExport:c,compact:u=!1,selectedKeys:d,allRowKeys:h,onToggleRow:f,onToggleAll:m,onRowClick:x}){const g=(r==null?void 0:r.max_folders)!==null&&(r==null?void 0:r.max_folders)!==void 0&&r.folder_count>=r.max_folders,y=CGe({estLocked:i,visibleCols:o,selectedKeys:d,allRowKeys:h,onToggleRow:f,onToggleAll:m});return s.jsxs(V,{className:"overflow-hidden rounded-none border-0 shadow-none",children:[!u&&s.jsxs("div",{className:"px-4 py-2.5 flex items-center justify-between border-b border-outline-subtle text-xs text-text-tertiary",children:[s.jsxs("span",{children:[e.length>0?`${e.length.toLocaleString()} listings`:"0 listings",t&&s.jsxs("span",{className:"ml-2 font-mono opacity-50",children:["search_id: ",t.slice(0,8)]})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(SG,{visibleCols:o,onToggleCol:l,onExport:c,exportDisabled:e.length===0}),!n&&t&&s.jsxs("button",{onClick:a,disabled:g,title:g?"Folder cap reached â delete one to save another, or upgrade your plan.":"Save this query as a folder",className:B("inline-flex items-center gap-1 text-xs font-medium",g?"text-text-tertiary cursor-not-allowed":"text-intent-brand hover:text-intent-brandHover"),children:[s.jsx(ko,{className:"w-3.5 h-3.5"}),"Save as folder"]}),n&&s.jsxs("span",{className:"text-text-tertiary inline-flex items-center gap-1",children:[s.jsx(sF,{className:"w-3 h-3"})," showing folder · use the Refresh icon to re-run"]})]})]}),s.jsx(dt,{rows:e,columns:y,getRowKey:b=>`${b.plid??b.position}-${b.position}`,persist:!0,pageKey:"page",sizeKey:"size",sortUrlKey:"sort",defaultSort:{key:"position",direction:"asc"},pageSizes:gGe,defaultPageSize:25,tableClassName:"w-full text-sm",empty:{title:"No rows match the current filters.",hint:"Clear a filter to see results."},onRowClick:x,rowClassName:b=>d!=null&&d.has(Zp(b))?"bg-surface-brandSubtle/40":void 0})]})}function AGe({filters:e,setFilters:t,availableBrands:n,filteredCount:r,totalCount:a,onAction:i,embedded:o=!1}){const l=e.inStockOnly||e.priceMin!=null||e.priceMax!=null||e.brands.size>0||e.minRating!=null||e.hideMyCatalogue,c=d=>{const h=new Set(e.brands);
910h.has(d)?h.delete(d):h.add(d),t({...e,brands:h}),i("filter_brand",{brand:d,selected:h.has(d),total_selected:h.size})},u=s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:[!o&&s.jsxs("span",{className:"text-xs text-text-tertiary inline-flex items-center gap-1",children:[s.jsx(aF,{className:"w-3.5 h-3.5"})," Filter"]}),s.jsxs("label",{className:"inline-flex items-center gap-1.5 cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:e.inStockOnly,onChange:d=>{t({...e,inStockOnly:d.target.checked}),i("filter_in_stock",{value:d.target.checked})},className:"rounded border-outline-subtle"}),s.jsx("span",{className:"text-text-secondary",children:"In stock only"})]}),s.jsxs("div",{className:"inline-flex items-center gap-1.5",children:[s.jsx("span",{className:"text-text-secondary text-xs",children:"R"}),s.jsx("input",{type:"number",value:e.priceMin??"",onChange:d=>t({...e,priceMin:d.target.value===""?null:Number(d.target.value)}),onBlur:()=>i("filter_price",{which:"min",value:e.priceMin}),placeholder:"min",className:"w-20 h-8 px-2 rounded border border-outline-subtle bg-surface text-sm text-text-primary"}),s.jsx("span",{className:"text-text-tertiary",children:"â"}),s.jsx("input",{type:"number",value:e.priceMax??"",onChange:d=>t({...e,priceMax:d.target.value===""?null:Number(d.target.value)}),onBlur:()=>i("filter_price",{which:"max",value:e.priceMax}),placeholder:"max",className:"w-20 h-8 px-2 rounded border border-outline-subtle bg-surface text-sm text-text-primary"})]}),s.jsxs("div",{className:"inline-flex items-center gap-1.5",children:[s.jsx("span",{className:"text-text-secondary",children:"â
â¥"}),s.jsxs("select",{value:e.minRating??"",onChange:d=>{const h=d.target.value===""?null:Number(d.target.value);t({...e,minRating:h}),i("filter_rating",{value:h})},className:"h-8 px-2 rounded border border-outline-subtle bg-surface text-sm text-text-primary",children:[s.jsx("option",{value:"",children:"Any"}),s.jsx("option",{value:"3",children:"3.0"}),s.jsx("option",{value:"4",children:"4.0"}),s.jsx("option",{value:"4.5",children:"4.5"}),s.jsx("option",{value:"4.8",children:"4.8"})]})]}),l&&s.jsxs("button",{onClick:()=>{t(t2),i("filter_clear")},className:"ml-auto text-xs text-text-tertiary hover:text-text-primary inline-flex items-center gap-1",children:[s.jsx(Bn,{className:"w-3 h-3"})," Clear all"]})]}),n.length>0&&s.jsxs("div",{className:"mt-3 pt-3 border-t border-outline-subtle",children:[s.jsx("div",{className:"text-xs text-text-tertiary mb-1.5",children:"Brands (click to filter):"}),s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[n.slice(0,20).map(d=>{const h=e.brands.has(d.brand);return s.jsxs("button",{onClick:()=>c(d.brand),className:B("text-xs px-2 py-0.5 rounded-md border transition-colors",h?"bg-intent-brand text-text-inverse border-intent-brand":"bg-surface text-text-secondary border-outline-subtle hover:border-outline"),children:[d.brand,s.jsx("span",{className:"ml-1 opacity-60",children:d.count})]},d.brand)}),n.length>20&&s.jsxs("span",{className:"text-xs text-text-tertiary px-2 py-0.5",children:["+",n.length-20," more"]})]})]}),l&&r<a&&s.jsxs("div",{className:"mt-2 text-xs text-text-tertiary",children:[r," of ",a," rows match"]})]});return o?u:s.jsx(V,{className:"p-3",children:u})}function TGe({error:e}){const t=/no_account_context|403/i.test(e),n=/demo_daily_limit/i.test(e),r=!n&&/quota_exceeded|429/i.test(e),a=/\b401\b|auth_required/i.test(e),i=t||r||a||n;return s.jsx(V,{className:B("p-4",i?"border-outline-subtle bg-surface-subtle/40":"border-intent-error/40 bg-intent-error/5"),children:s.jsxs("div",{className:B("flex items-start gap-2 text-sm",i?"text-text-primary":"text-intent-error"),children:[s.jsx(zn,{className:B("w-4 h-4 shrink-0 mt-0.5",i?"text-text-tertiary":"text-intent-error")}),s.jsx("div",{children:t?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"font-medium",children:"Connect a store to use Market Explorer"}),s.jsx("div",{className:"text-text-secondary mt-1",children:"Market Explorer runs against your account's quota. Once you've connected your Takealot store the search will run normally â until then this
910surface is read-only."})]}):n?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"font-medium",children:"Demo daily limit reached"}),s.jsx("div",{className:"text-text-secondary mt-1",children:"You've used your 3 demo searches for today. Connect your Takealot store to keep using Market Explorer (no per-day cap, plus full Est Sales & Revenue)."}),s.jsx("div",{className:"mt-2",children:s.jsx(nc,{})})]}):r?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"font-medium",children:"Monthly search limit reached"}),s.jsx("div",{className:"text-text-secondary mt-1",children:"You've used your plan's Market Explorer quota for this period. Upgrade for more searches, or wait until the counter resets next month."})]}):a?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"font-medium",children:"Sign in to continue"}),s.jsx("div",{className:"text-text-secondary mt-1",children:"Your session expired or you're not signed in."})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"font-medium",children:"Search failed"}),s.jsx("div",{className:"text-text-secondary mt-1",children:e})]})})]})})}function OGe(){return s.jsxs(V,{className:"p-8 text-center",children:[s.jsx(Fa,{className:"w-8 h-8 mx-auto text-text-tertiary mb-3"}),s.jsx("div",{className:"text-text-primary font-medium",children:"Start a market scan"}),s.jsx("div",{className:"text-sm text-text-secondary mt-1 max-w-md mx-auto",children:"Pick a preset above (Keyword / Biggest Sellers / By Category / By Brand) and run a search. Save results as folders to revisit them later. This scan reads Takealot's public catalogue. A connected Amazon store is a separate seller in Gadjet. Makro catalogue search is on the roadmap."})]})}function IGe({spec:e}){const t=(e==null?void 0:e.preset_key)==="fastest_growing",n=(e==null?void 0:e.window_days)??7;return s.jsxs(V,{className:"p-8 text-center",children:[s.jsx(Fa,{className:"w-8 h-8 mx-auto text-text-tertiary mb-3"}),s.jsx("div",{className:"text-text-primary font-medium",children:"No listings for this search"}),s.jsx("div",{className:"text-sm text-text-secondary mt-1 max-w-md mx-auto",children:t&&n>7?s.jsxs(s.Fragment,{children:["No category has enough Market Map history yet for a ",n,"-day comparison. Try the ",s.jsx("span",{className:"font-medium",children:"7-day"})," window â longer windows fill in as the crawler accumulates more snapshots."]}):t?s.jsx(s.Fragment,{children:"No fast-growing categories surfaced for this window right now. Try again later as fresh snapshots land."}):s.jsx(s.Fragment,{children:"Nothing matched. Widen the price range, try a different keyword/category, or clear filters and re-run."})})]})}function PGe(e){return e?e.preset_key==="biggest_sellers"?"Biggest Sellers":e.preset_key==="fastest_growing"?`Fastest Growing (${e.window_days??7}d)`:e.preset_key==="premium_price_band"?`Premium Price Band · ${e.category_slug??""}`.trim():e.preset_key==="underpriced_outliers"?`Underpriced Outliers · ${e.category_slug??""}`.trim():e.category_slug?e.category_slug:e.keyword?e.keyword:"":""}function RGe({defaultName:e,onClose:t,onSave:n}){const[r,a]=p.useState(e),[i,o]=p.useState(!1),l=async()=>{const c=r.trim();if(c){o(!0);try{await n(c)}catch{}finally{o(!1)}}};return s.jsx(js,{open:!0,onOpenChange:c=>!c&&t(),children:s.jsxs(Ns,{className:"max-w-md",children:[s.jsx(La,{children:s.jsx(ma,{children:"Save as folder"})}),s.jsxs(Oa,{children:[s.jsx("label",{className:"block text-sm font-medium text-text-secondary mb-1",children:"Folder name"}),s.jsx(Re,{value:r,onChange:c=>a(c.target.value),placeholder:"e.g. Fish Oil ZA",autoFocus:!0,onKeyDown:c=>{c.key==="Enter"&&r.trim()&&!i&&l()}}),s.jsx("div",{className:"mt-2 text-xs text-text-tertiary",children:"Folders save the search query, not a frozen row list. Opening one shows the most recent cached result; the Refresh icon re-runs the query."})]}),s.jsxs(da,{children:[s.jsx(W,{variant:"ghost",onClick:t,disabled:i,children:"Cancel"}),s.jsx(W,{onClick:l,disabled:i||!r.trim(),children:i?"Savingâ¦":"Save"})]})]})})}const DGe=["catalogue","keywords","ranks","validate"];function OL(e,t,n,r,a,i){const o={marketplace:"takealot",page_count:n};switch(e){case"keyword":return{...o,keyword:t.trim()};case"biggest_sellers":return{...o,preset_key:"biggest_sellers"};case"by_category":return{...o,category_slug:t.trim()};case"by_brand":return{...o,keyword:t.trim()};case"premium_price_band":case"underpriced_outliers":return{...o,preset_key:e,category_slug:t.trim()};case"fastest_growing":return{...o,preset_key:"fastest_growing",window_days:r};case"weak_incumbents":{const l=t.trim();return l.includes("/")?{...o,preset_key:"weak_incumbents",category_slug:l}:{...o,preset_key:"weak_incumbents",keyword:l}}case"new_arrivals":return{...o,preset_key:"new_arrivals",new_arrival_days:a,department_slug:t.trim()||void 0};case"product_finder":return{...o,preset_key:"product_finder",product_finder_filters:i??{}};default:return o}}function MGe(e){return e?e.preset_key==="biggest_sellers"?"Biggest Sellers":e.preset_key==="fastest_growing"?`Fastest Growing · ${e.window_days??7}d`:e.preset_key==="premium_price_band"?`Premium Price Band · ${e.category_slug??""}`:e.preset_key==="underpriced_outliers"?`Underpriced Outliers · ${e.category_slug??""}
910`:e.preset_key==="weak_incumbents"?`Weak Incumbents · ${e.category_slug??e.keyword??""}`:e.preset_key==="new_arrivals"?`New Arrivals · ${e.new_arrival_days??30}d`:e.preset_key==="product_finder"?"Product Finder":e.category_slug?`Category · ${e.category_slug}`:e.keyword?`"${e.keyword}"`:"â":"â"}function yj(e){const t=(e==null?void 0:e.page_count)??1,n=(e==null?void 0:e.window_days)??7;return(e==null?void 0:e.preset_key)==="biggest_sellers"?{preset:"biggest_sellers",input:"",pages:t,windowDays:n}:(e==null?void 0:e.preset_key)==="fastest_growing"?{preset:"fastest_growing",input:"",pages:t,windowDays:n}:(e==null?void 0:e.preset_key)==="premium_price_band"?{preset:"premium_price_band",input:e.category_slug??"",pages:t,windowDays:n}:(e==null?void 0:e.preset_key)==="underpriced_outliers"?{preset:"underpriced_outliers",input:e.category_slug??"",pages:t,windowDays:n}:(e==null?void 0:e.preset_key)==="weak_incumbents"?{preset:"weak_incumbents",input:e.category_slug??e.keyword??"",pages:t,windowDays:n}:(e==null?void 0:e.preset_key)==="new_arrivals"?{preset:"new_arrivals",input:e.department_slug??"",pages:t,windowDays:n}:(e==null?void 0:e.preset_key)==="product_finder"?{preset:"product_finder",input:"",pages:t,windowDays:n}:e!=null&&e.category_slug?{preset:"by_category",input:e.category_slug,pages:t,windowDays:n}:e!=null&&e.keyword?{preset:"keyword",input:e.keyword,pages:t,windowDays:n}:{preset:"keyword",input:"",pages:t,windowDays:n}}function $Ge(){return s.jsx(qVe,{children:s.jsx(LGe,{})})}function LGe(){var ye;const e=Rw(),[t,n]=p.useState("keyword"),[r,a]=p.useState(""),[i,o]=p.useState(1),[l,c]=p.useState(7),[u,d]=p.useState(30),[h,f]=p.useState({}),[m,x]=ki(),[g,y]=p.useState(!1),[b,v]=p.useState([]),[w,_]=p.useState(null),[k,j]=p.useState(null),[N,E]=p.useState(null),[A,C]=p.useState(null),[T,S]=p.useState(null),[O,R]=p.useState(null),[I,$]=it("tab","catalogue"),P=DGe.includes(I)?I:"catalogue",[F,Z]=p.useState([]),[D,H]=p.useState(!1),Y=mc(),[M,z]=p.useState(t2),[G,te]=p.useState(()=>new Set(jGe)),[re,L]=p.useState("build"),[q,me]=p.useState(!1),[ee,ne]=p.useState(!1),[X,he]=p.useState(!1),[ae,je]=p.useState(new Set),[$e,J]=p.useState(null),[Ne,ve]=p.useState([]),Me=p.useMemo(()=>Uy.find(ie=>ie.key===t),[t]),Xe=p.useMemo(()=>_Ge(b),[b]),ze=p.useMemo(()=>yGe(b,M),[b,M]),Fe=p.useMemo(()=>w?wGe(ze,w):null,[ze,w]),tt=p.useCallback(()=>{z(t2),Y({page:"",sort:""})},[Y]),fe=p.useCallback((ie,pe)=>{$t.recordEvent("toolbar_action",{search_id:k,payload:pe?{action:ie,...pe}:{action:ie}})},[k]),U=p.useCallback(async()=>{try{const ie=await $t.quota();R(ie)}catch(ie){console.warn("[market-explorer] quota fetch failed:",ie)}},[]),ce=p.useCallback(async()=>{try{const{folders:ie}=await $t.listFolders();Z(ie)}catch(ie){console.warn("[market-explorer] folder list failed:",ie)}},[]);p.useEffect(()=>{U(),ce(),$t.recordEvent("view")},[U,ce]);const ue=p.useCallback((ie,pe,xe=null)=>{v(ie.rows),_(ie.rollup),j(ie.search_id),E(pe),C(xe),je(new Set),J(null),ve(Ke=>{const St=MGe(pe);return[{id:ie.search_id,label:St,spec:pe},...Ke.filter(yn=>yn.id!==ie.search_id)].slice(0,8)}),tt()},[tt]),Ee=p.useCallback(async(ie,pe)=>{y(!0),S(null);try{const xe=await $t.runSearch(ie,{entryMode:(pe==null?void 0:pe.entryMode)??"preset"});if(ue(xe,ie,null),pe!=null&&pe.syncControls){const Ke=yj(ie);n(Ke.preset),a(Ke.input),o(Ke.pages),c(Ke.windowDays)}U()}catch(xe){const Ke=xe instanceof Error?xe.message:String(xe);S(Ke),Ae("error",Ke)}finally{y(!1)}},[ue,U]),bt=p.useCallback(async()=>{if(Me.inputKind==="text"&&!r.trim()){Ae("warning","Please enter a search term first");return}if(Me.inputKind==="category"&&!r.trim()){Ae("warning","Please pick a category first");return}const ie=OL(t,r,i,l,u,h);await Ee(ie,{entryMode:"preset"})},[t,Me.inputKind,r,i,l,u,h,Ee]),[Ze,vt]=p.useState(null);p.useEffect(()=>{const ie=m.get("run"),pe=m.get("preset"),xe=m.get("q")||"",Ke=m.get("category")||"",St=pe==="keyword"&&!!xe||pe==="weak_incumbents"&&!!xe||pe==="by_category"&&!!Ke;!ie&&!St||(ie&&vt(ie),pe==="keyword"&&xe?(n("keyword"),a(xe),Ee({marketplace:"takealot",keyword:xe,page_count:1},{entryMode:"preset"})):pe==="weak_incumbents"&&xe?(n("weak_incumbents"),a(xe),Ee({marketplace:"takealot",preset_key:"weak_incumbents",keyword:xe,page_count:1},{entryMode:"preset"})):pe==="by_category"&&Ke&&(n("by_category"),a(Ke),Ee({marketplace:"takealot",category_slug:Ke,page_count:1},{entryMode:"preset"})),x(Jt=>{const yn=new URLSearchParams(Jt);return yn.delete("run"),yn.delete("preset"),yn.delete("category"),St&&yn.delete("q"),ie&&yn.set("tab","validate"),(yn.get("tab")||"catalogue")==="catalogue"&&yn.delete("tab"),yn},{replace:!0}))},[]);const Ot=p.useCallback(async ie=>{$t.recordEvent("folder_opened",{folder_id:ie.id});const pe=yj(ie.query_spec);n(pe.preset),a(pe.input),o(pe.pages),c(pe.windowDays),S(null),y(!0);try{if(ie.last_search_id){const{search:xe,rows:Ke}=await $t.getSearch(ie.last_search_id);ue({search_id:xe.id,rollup:xe.rollup,rows:Ke},ie.query_spec,ie.id)}else{const xe=await $t.refreshFolder(ie.id);ue(xe,ie.query_spec,ie.id),U(),ce()}}catch(xe){const Ke=xe instanceof Error?xe.message:String(xe);S(Ke),Ae("error",Ke)}finally{y(!1)}},[ue,U,ce]),It=p.useCallback(async ie=>{y(!0),S(null);try{const pe=await $t.refreshFolder(ie.id);ue(pe,ie.query_spec,ie.id),U(),ce(),Ae("success",`Refreshed "${ie.name}"`)}catch(pe){const xe=pe instanceof Error?pe.message:String(pe);S(xe),Ae("error",xe)}finally{y(!1)}},[ue,U,ce]),Ut=p.useCallback(async ie=>{if(!(!N||!k))try{const{folder:pe}=await $t.createFolder({name:ie,query_spec:N,last_search_id:k});Z(xe=>[pe,...xe]),C(pe.id),U(),Ae("success",`Saved as "${pe.name}"`)}catch(pe){const xe=pe instanceof Error?pe.message:String(pe);throw Ae("error",xe),pe}},[N,k,U]),Lr=p.useCallback(async(ie,pe)=>{try{const{folder:xe}=await $t.renameFolder(ie.id,pe);Z(Ke=>Ke.map(St=>St.id===xe.id?{...St,...xe}:St))}catch(xe){const Ke=xe instanceof Error?xe.message:String(xe);Ae("error",Ke)}},[]),en=p.useCallback(async ie=>{if(confirm(`Delete folder "${ie.name}"? This won't affect the underlying searches.`))try{await $t.deleteFolder(ie.id),Z(pe=>pe.filter(xe=>xe.id!==ie.id)),A===ie.id&&C(null),U(),Ae("success",`Deleted "${ie.name}"`)}catch(pe){const xe=pe instanceof Error?pe.message:String(pe);Ae("error",xe)}},[A,U]),Hs=p.useCallback(ie=>{te(pe=>{const xe=new Set(pe);return xe.has(ie)?xe.delete(ie):xe.add(ie),xe}),fe("column_toggle",{key:ie})},[fe]),Os=p.useCallback(async ie=>{if(ze.length===0){Ae("warning","Nothing to export yet â run a search f
910irst.");return}const pe=((N==null?void 0:N.keyword)||(N==null?void 0:N.category_slug)||(N==null?void 0:N.preset_key)||"results").toString().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"results";try{await $t.exportResults({columns:NGe(G),rows:SGe(ze),format:ie,filename:`market-explorer-${pe}.${ie}`}),fe("export",{format:ie,rows:ze.length})}catch(xe){Ae("error",xe instanceof Error?xe.message:String(xe))}},[ze,G,N,fe]),gr=Me.inputKind!=="window"&&Me.inputKind!=="days"&&t!=="new_arrivals"&&t!=="product_finder",Vs=g||(Me.inputKind==="text"||Me.inputKind==="category")&&!r.trim(),Xn=((ye=Fe==null?void 0:Fe.est_sales_meta)==null?void 0:ye.reason)==="demo_locked",le=p.useMemo(()=>ze.filter(ie=>ae.has(Zp(ie))),[ze,ae]),De=e.items.filter(ie=>ie.playbook_run_id).length,Ie=p.useCallback(ie=>{const pe=new URL(ie,window.location.origin),xe=pe.searchParams.get("tab"),Ke=pe.searchParams.get("preset"),St=pe.searchParams.get("q"),Jt=pe.searchParams.get("category");$(xe==="keywords"?"keywords":xe==="validate"?"validate":"catalogue"),Ke==="keyword"&&St?(n("keyword"),a(St),Ee({marketplace:"takealot",keyword:St,page_count:i},{entryMode:"preset"})):Ke==="weak_incumbents"&&St?(n("weak_incumbents"),a(St),Ee({marketplace:"takealot",preset_key:"weak_incumbents",keyword:St,page_count:i},{entryMode:"preset"})):Ke==="by_category"&&Jt&&(n("by_category"),a(Jt),Ee({marketplace:"takealot",category_slug:Jt,page_count:i},{entryMode:"preset"}))},[Ee,i,$]),Ge=s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[s.jsx(J3,{tabs:[{key:"detail",label:"Detail"},{key:"shortlist",label:"Shortlist",badge:e.items.length||void 0}],value:e.rightTab==="brief"?"shortlist":e.rightTab,onChange:ie=>e.setRightTab(ie)}),e.rightTab==="detail"?s.jsx(gqe,{row:$e,estLocked:Xn,alreadyShortlisted:e.hasPlid($e==null?void 0:$e.plid),onAddToShortlist:$e?()=>void e.addRows([$e],k):void 0}):s.jsx(X3,{items:e.items,onRemove:ie=>void e.remove(ie),onClear:()=>void e.clear(),onValidate:()=>{e.requestValidate(),$("validate")}})]});return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Market Explorer"}]}),s.jsx(As,{items:[{key:"catalogue",label:"Catalogue",icon:s.jsx(gf,{className:"h-3.5 w-3.5"}),active:P==="catalogue",onClick:()=>$("catalogue")},{key:"keywords",label:"Keywords",icon:s.jsx(Fa,{className:"h-3.5 w-3.5"}),active:P==="keywords",onClick:()=>$("keywords")},{key:"ranks",label:"Ranks",icon:s.jsx(Yne,{className:"h-3.5 w-3.5"}),active:P==="ranks",onClick:()=>$("ranks")},{key:"validate",label:"Validate",icon:s.jsx(qv,{className:"h-3.5 w-3.5"}),active:P==="validate",onClick:()=>$("validate"),trailing:De>0?s.jsx("span",{className:"rounded-full bg-surface-brandSubtle px-1.5 py-0.5 text-[10px] font-semibold text-text-brand",children:De}):void 0}]}),P==="validate"?s.jsx(uqe,{initialRunId:Ze,onOpenMe:Ie}):P==="keywords"?s.jsx(Wqe,{onOpenInCatalogue:ie=>{$("catalogue"),Ee({marketplace:"takealot",keyword:ie},{entryMode:"chat",syncControls:!0})},onGoValidate:()=>{e.requestValidate(),$("validate")}}):P==="ranks"?s.jsx(xGe,{onOpenKeyword:ie=>Y({tab:"keywords",mode:"search",q:ie})}):s.jsx(Dw,{leftRailOpen:ee,onCloseLeftRail:()=>ne(!1),rightPanelFilled:!!$e,queryBar:s.jsxs("div",{children:[s.jsxs(G3,{quota:O,running:g,runDisabled:re==="ask"?!0:Vs,onRun:re==="build"&&t!=="product_finder"?bt:void 0,children:[s.jsx(Y3,{onClick:()=>ne(!0)}),s.jsx(pG,{options:[{key:"build",label:"Build"},{key:"ask",label:"Ask",icon:s.jsx(Ht,{className:"h-3.5 w-3.5"})}],value:re,onChange:ie=>L(ie)}),re==="ask"?s.jsx(JVe,{disabled:g,onRunSpec:ie=>void Ee(ie,{entryMode:"chat",syncControls:!0})}):s.jsxs(s.Fragment,{children:[s.jsx(dqe,{preset:t,open:q,onToggle:()=>me(ie=>!ie),onSelect:ie=>{n(ie),a(""),me(!1)}}),Me.inputKind==="text"&&s.jsx(QS,{value:r,onChange:a,placeholder:Me.inputPlaceholder,onSubmit:bt,disabled:g}),Me.inputKind==="category"&&s.jsx("div",{className:"min-w-[180px] flex-1",children:s.jsx(q3,{value:r,onChange:a,placeholder:Me.inputPlaceholder,disabled:g})}),Me.inputKind==="window"&&s.jsxs("select",{value:l,onChange:ie=>c(Number(ie.target.value)),className:"h-9 rounded-md border border-outline-subtle bg-surface px-2 text-sm",children:[s.jsx("option",{value:7,children:"Last 7 days"}),s.jsx("option",{value:30,children:"Last 30 days"}),s.jsx("option",{value:90,children:"Last 90 days"})]}),Me.inputKind==="days"&&s.jsxs("select",{value:u,onChange:ie=>d(Number(ie.target.value)),className:"h-9 rounded-md border border-outline-subtle bg-surface px-2 text-sm",children:[s.jsx("option",{value:7,children:"7 days"}),s.jsx("option",{value:14,children:"14 days"}),s.jsx("option",{value:30,children:"30 days"}),s.jsx("option",{value:60,children:"60 days"})]}),Me.inputKind==="none"&&s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-text-secondary",children:Me.blurb}),gr&&s.jsx(YVe,{pages:i,onChange:o}),re==="build"&&s.jsx(ZVe,{onClick:()=>L("ask")})]})]}),re==="build"&&t==="product_finder"&&s.jsx(VVe,{compact:!0,running:g,onRun:ie=>{f(ie),Ee(OL("product_finder","",i,l,u,ie),{entryMode:"preset"})}})]}),leftRail:s.jsxs(Z3,{children:[s.jsx(QVe,{folders:F,activeFolderId:A,quota:O,onOpen:ie=>void Ot(ie),onRefresh:ie=>void It(ie),onRename:(ie,pe)=>void Lr(ie,pe),onDelete:ie=>void en(ie)}),s.jsxs(pd,{label:"Recent",children:[Ne.length===0&&s.jsx("p",{className:"px-1.5 text-[11px] leading-4 text-text-tertiary",children:"Runs from this session show up here."}),Ne.map(ie=>s.jsx(Yp,{title:ie.label,active:k===ie.id,onClick:()=>{const pe=yj(ie.spec);n(pe.preset),a(pe.input),o(pe.pages),Ee(ie.spec,{entryMode:"preset"})}},ie.id))]})]}),canvas:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:[Fe&&s.jsx(hqe,{rollup:Fe,estLocked:Xn,onFilter:()=>he(ie=>!ie),onSave:k&&!A?()=>H(!0):void 0,saveDisabled:(O==null?void 0:O.max_folders)!=null&&O.folder_count>=O.max_folders,extra:s.jsx(SG,{visibleCols:G,onToggleCol:Hs,onExport:Os,exportDisabled:ze.length===0})}),X&&b.length>0&&s.jsx("div",{className:"shrink-0 border-b border-outline-subtle bg-surface px-5 py-2",children:s.jsx(AGe,{embedded:!0,filters:M,setFilters:z,availableBrands:Xe,filteredCount:ze.length,totalCount:b.length,onAction:fe})}),k&&s.jsx(pqe,{searchId:k,disabled:g,hideMyCatalogue:M.hideMyCatalogue,onHideMyCatalogue:()=>z(ie=>({...ie,hideMyCatalogue:!ie.hideMyCatalogue})),onRefined:ie=>{ue(ie,N??{marketplace:"takealot"},A)}}),ae.size>0&&s.jsxs("div",{className:"flex shrink-0 items-center gap-3 border-b border-outline-subtle bg-surface-brandSubtle/40 px-5 py-2 text-sm",children:[s.jsxs("span",{children:[ae.size," ",ae.size===1?"listing":"listings"," selected"]}),s.jsx("button",{type:"button",className:"font-medium text-intent-brand hover:text-intent-brandHover",onClick:()=>void e.addRows(le,k),children:"Add to shortlist"}),s.jsx("button",{type:"button",className:"text-xs text-text-tertiary hover:text-text-primary",onClick:()=>je(new Set),children:"Clear"})]}),T&&s.jsx("div",{className:"shrink-0 px-5 py-3",children:s.jsx(TGe,{error:T})}),s.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:b.length>0?s.jsx(EGe,{compact:!0,rows:ze,allRowKeys:ze.map(Zp),selectedKeys:ae,onToggleRow:ie=>{je(pe=>{const xe=new Set(pe);return xe.has(ie)?xe.delete(ie):xe.add(ie),xe})},onToggleAll:(ie,pe)=>{je(xe=>{const Ke=new Set(xe);for(const St of ie)pe?Ke.add(St):Ke.delete(St);return Ke})},onRowClick:ie=>{J(ie),e.setRightTab("detail")},searchId:k,activeFolderId:A,quota:O,onSaveClick:()=>H(!0),estLocked:Xn,visibleCols:G,onToggleCol:Hs,onExport:Os}):!g&&k&&!T?s.jsx("div",{className:"p-5",children:s.jsx(IGe,{spec:N})}):!g&&!T?s.jsx("div",{className:"p-5",children:s.jsx(OGe,{})}):g?s.jsxs("div",{className:"flex items-center gap-2 p-6 text-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Searchingâ¦"]}):null})]}),rightPanel:Ge}),D&&s.jsx(RGe,{defaultName:PGe(N),onClose:()=>H(!1),onSave:async ie=>{await Ut(ie),H(!1)}})]})}const FGe=[{key:"all",label:"All"},{key:"how",label:"How"},{key:"what",label:"What"},{key:"why",label:"Why"}],BGe={how:"bg-surface-brandSubtle text-text-brand",what:"bg-surface-successSubtle text-intent-success",why:"bg-surface-warningSubtle text-intent-warning"};function UGe(e){if(!e||e<=0)return null;const t=Math.floor(e/60),n=Math.round(e%60);return`${t}:${n.toString().padStart(2,"0")}`}function IL({video:e,isNew:t,onPlay:n,activeTags:r=[]}){const a=UGe(e.duration_sec);return s.jsxs("button",{type:"button",onClick:()=>n(e),className:`group overflow-hidden rounded-xl border bg-surface text-left transition ${t?"border-outline-brand ring-1 ring-outline-brand/40 hover:border-outline-brand":"border-outline-subtle hover:border-outline-brand"}`,children:[s.jsxs("div",{className:"relative aspect-video w-full overflow-hidden bg-surface-sunken",children:[e.poster_url?s.jsx("img",{src:e.poster_url,alt:"",loading:"lazy",className:"h-full w-full object-cover"}):s.jsx("div",{className:"h-full w-full bg-gradient-to-br from-surface-brandSubtle to-surface-sunken"}),s.jsx("div",{className:"absolute inset-0 grid place-items-center",children:s.jsx("span",{className:"grid h-12 w-12 place-items-center rounded-full bg-black/55 text-text-inverse backdrop-blur-sm transition group-hover:scale-110",children:s.jsx(bd,{className:"h-5 w-5 translate-x-0.5"})})}),t&&s.jsx("span",{className:"absolute left-2 top-2 rounded-md bg-intent-brand px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-text-inverse shadow-sm",children:"New"}),a&&s.jsxs("span",{className:"absolute bottom-2 right-2 flex items-center gap-1 rounded-md bg-black/65 px-1.5 py-0.5 text-xs font-medium text-text-inverse",children:[s.jsx(pu,{className:"h-3 w-3"}),a]})]}),s.jsxs("div",{className:"p-3.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`rounded px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide ${BGe[e.tier]}`,children:e.tier}),s.jsx("h3",{className:"truncate text-sm font-semibold text-text-primary",children:e.title})]}),e.description&&s.jsx("p",{className:"mt-1 line-clamp-2 text-xs leading-relaxed text-text-secondary",children:e.description}),(e.tags??[]).length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1",children:e.tags.map(i=>s.jsx("span",{className:`rounded px-1.5 py-0.5 text-[10px] font-medium ${r.includes(i)?"bg-surface-brandSubtle text-text-brand":"bg-surface-sunken text-text-tertiary"}`,children:i},i))})]})]})}function zGe(){const[e,t]=p.useState(null),[n,r]=p.useState(null),[a,i]=p.useState(""),[o,l]=p.useState("all"),[c,u]=p.useState(!1),[d,h]=p.useState([]),[f,m]=p.useState(null),x=Lt(),[g,y]=p.useState(null),b=p.useRef(!1);p.useEffect(()=>{let C=!0;return wp.listCached().then(T=>C&&t(T)).catch(T=>C&&r(String((T==null?void 0:T.message)||T))),()=>{C=!1}},[]),p.useEffect(()=>{b.current||x.kind!=="ready"||(b.current=!0,y(x.me.academy_seen_at??null),wp.markSeen().then(ai).catch(()=>{}))},[x]),p.useEffect(()=>{if(!f)return;const C=T=>T.key==="Escape"&&m(null);return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[f]);const v=p.useMemo(()=>{const C=g?new Date(g).getTime():null;return T=>C!==null&&!!T.published_at&&new Date(T.published_at).getTime()>C},[g]),w=p.useMemo(()=>e?e.filter(v).length:0,[e,v]),_=p.useRef(!1);p.useEffect(()=>{_.current||!e||!g||(_.current=!0,e.some(v)&&u(!0))},[e,g,v]);const k=p.useMemo(()=>{const C=new Map;for(const T of e??[])for(const S of T.tags??[])C.set(S,(C.get(S)??0)+1);return[...C.entries()].sort((T,S)=>S[1]-T[1]||T[0].localeCompare(S[0]))},[e]),j=C=>h(T=>T.includes(C)?T.filter(S=>S!==C):[...T,C]),N=p.useMemo(()=>
910{if(!e)return[];const C=a.trim().toLowerCase();return e.filter(T=>o!=="all"&&T.tier!==o||d.length&&!d.some(O=>(T.tags??[]).includes(O))?!1:C?[T.title,T.description??"",T.section,...T.tags??[],...T.keywords].join(" ").toLowerCase().includes(C):!0)},[e,a,o,d]),E=p.useMemo(()=>{if(!c)return[];const C=T=>T.published_at?new Date(T.published_at).getTime():-1/0;return[...N].sort((T,S)=>C(S)-C(T))},[N,c]),A=p.useMemo(()=>{if(c)return[];const C=new Map;for(const T of N)C.has(T.section)||C.set(T.section,[]),C.get(T.section).push(T);return[...C.entries()]},[N,c]);return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Academy"}]}),s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full px-4 md:px-6 py-6",children:[s.jsxs("div",{className:"mb-6 flex items-start gap-3",children:[s.jsx("div",{className:"grid h-11 w-11 shrink-0 place-items-center rounded-xl bg-surface-brandSubtle text-text-brand",children:s.jsx(U2,{className:"h-6 w-6"})}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-bold tracking-tight text-text-primary",children:"Academy"}),s.jsx("p",{className:"mt-0.5 text-sm text-text-secondary",children:"Short videos on how to use every part of Gadjet. Browse, search, and learn."}),w>0&&s.jsxs("p",{className:"mt-1.5 flex items-center gap-1.5 text-sm font-medium text-text-brand",children:[s.jsx(Ht,{className:"h-3.5 w-3.5"}),w===1?"1 new video since your last visit":`${w} new videos since your last visit`]})]})]}),s.jsxs("div",{className:"mb-6 flex flex-col gap-3 sm:flex-row sm:items-center",children:[s.jsx(pc,{fieldClassName:"flex-1",value:a,onChange:C=>i(C.target.value),placeholder:"Search videosâ¦"}),s.jsx("div",{className:"flex gap-1 rounded-lg border border-outline-subtle bg-surface p-1",children:FGe.map(C=>s.jsx("button",{type:"button",onClick:()=>l(C.key),className:`rounded-md px-3 py-1.5 text-sm font-medium ${o===C.key?"bg-surface-brandSubtle text-text-brand":"text-text-secondary hover:text-text-primary"}`,children:C.label},C.key))}),s.jsx("button",{type:"button",onClick:()=>u(C=>!C),"aria-pressed":c,className:`shrink-0 rounded-lg border px-3 py-2 text-sm font-medium transition ${c?"border-outline-brand bg-surface-brandSubtle text-text-brand":"border-outline-subtle bg-surface text-text-secondary hover:text-text-primary"}`,children:"Recently added"})]}),k.length>0&&s.jsxs("div",{className:"mb-6 flex flex-wrap items-center gap-1.5",children:[k.map(([C,T])=>{const S=d.includes(C);return s.jsxs("button",{type:"button",onClick:()=>j(C),"aria-pressed":S,className:`rounded-full border px-2.5 py-1 text-xs font-medium transition ${S?"border-outline-brand bg-surface-brandSubtle text-text-brand":"border-outline-subtle bg-surface text-text-secondary hover:text-text-primary hover:border-outline-brand"}`,children:[C,s.jsx("span",{className:`ml-1.5 tabular-nums ${S?"text-text-brand/70":"text-text-tertiary"}`,children:T})]},C)}),d.length>0&&s.jsx("button",{type:"button",onClick:()=>h([]),className:"ml-1 rounded-full px-2.5 py-1 text-xs font-medium text-text-tertiary underline-offset-2 hover:text-text-primary hover:underline",children:"Clear"})]}),n&&s.jsxs("p",{className:"rounded-lg border border-outline-subtle bg-surface-warningSubtle px-4 py-3 text-sm text-intent-warning",children:["Couldnât load the Academy: ",n]}),!e&&!n&&s.jsx("p",{className:"py-12 text-center text-sm text-text-tertiary",children:"Loadingâ¦"}),e&&N.length===0&&!n&&s.jsx("p",{className:"py-12 text-center text-sm text-text-tertiary",children:e.length===0?"No videos published yet.":"No videos match your search."}),c&&E.length>0&&s.jsx("div",{className:"mb-8 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:E.map(C=>s.jsx(IL,{video:C,isNew:v(C),onPlay:m,activeTags:d},C.id))}),A.map(([C,T])=>s.jsxs("section",{className:"mb-8",children:[s.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-wider text-text-tertiary",children:C}),s.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:T.map(S=>s.jsx(IL,{video:S,isNew:v(S),onPlay:m,activeTags:d},S.id))})]},C))]})}),f&&s.jsx("div",{className:"fixed inset-0 z-modal grid place-items-center bg-black/70 p-4",onClick:()=>m(null),children:s.jsxs("div",{className:"relative w-full max-w-4xl overflow-hidden rounded-2xl bg-black shadow-2xl",onClick:C=>C.stopPropagation(),children:[s.jsx("button",{type:"button",onClick:()=>m(null),"aria-label":"Close",className:"absolute right-3 top-3 z-10 grid h-9 w-9 place-items-center rounded-full bg-black/55 text-text-inverse hover:bg-black/75",children:s.jsx(Bn,{className:"h-5 w-5"})}),s.jsx("video",{src:f.video_url,poster:f.poster_url??void 0,controls:!0,autoPlay:!0,className:"aspect-video w-full bg-black"}),s.jsxs("div",{className:"bg-surface px-4 py-3",children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:f.title}),f.description&&s.jsx("p",{className:"mt-0.5 text-xs text-text-secondary",children:f.description})]})]})})]})}let WGe=0;const KGe=()=>`v${Date.now()}_${WGe++}`;function PL(e){let t=[{}];for(const n of e){if(!n.values.length)continue;const r=[];for(const a of t)for(const i of n.values)r.push({...a,[n.id]:i});t=r}return e.some(n=>n.values.length)?t:[]}const fy="block w-full rounded-md border border-outline bg-surface px-2 py-1 text-body-xs text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus",RL="rounded-full border border-outline-subtle bg-surface px-2 py-0.5 text-body-xs text-text-body transition hover:bg-surface-subtle",DL="rounded-full border border-intent-brand bg-intent-brandSubtle px-2 py-0.5 text-body-xs text-text-primary";function HGe({variantAttributes:e,poolImages:t,initialMode:n,initialVariants:r,onSave:a,recolourImages:i,uploadVariantImage:o,variantImageUrls:l}
910){const[c,u]=p.useState(n),[d,h]=p.useState(r),[f,m]=p.useState({}),[x,g]=p.useState({}),[y,b]=p.useState(null),[v,w]=p.useState(null),[_,k]=p.useState(()=>({...l||{}})),[j,N]=p.useState(()=>{const z={},G=new Set(t.map(re=>re.storage_path).filter(Boolean)),te=l||{};for(const re of r){const L=(re.image_paths||[]).filter(q=>q&&!G.has(q)).map(q=>({storage_path:q,signed_url:te[q],mode:"recolour"}));L.length&&(z[re.id]=L)}return z}),E=p.useMemo(()=>e.find(z=>/colou?r/i.test(z.display_name||"")),[e]),A=z=>{var G;return E?(((G=z.attrs)==null?void 0:G[E.attribute_id])||"").trim():""};async function C(z){if(!i)return;const G=A(z);if(G){b(z.id);try{const te=new Set(z.image_paths&&z.image_paths.length?z.image_paths:t.map(q=>q.storage_path).filter(Boolean)),re=t.filter(q=>q.storage_path&&te.has(q.storage_path)&&q.mode!=="lifestyle"&&q.mode!=="dimensions").map(q=>q.storage_path);if(!re.length)return;const L=await i(re,G);if(L.length){k(me=>{const ee={...me};for(const ne of L)ne.signed_url&&(ee[ne.storage_path]=ne.signed_url);return ee}),N(me=>{const ee=me[z.id]||[],ne=new Set(ee.map(he=>he.storage_path)),X=L.filter(he=>!ne.has(he.storage_path)).map(he=>({storage_path:he.storage_path,signed_url:he.signed_url,mode:"recolour"}));return X.length?{...me,[z.id]:[...ee,...X]}:me});const q=(z.image_paths||[]).filter(me=>!re.includes(me));P(z.id,{image_paths:[...L.map(me=>me.storage_path),...q]})}}finally{b(null)}}}async function T(z,G){if(o){w(z.id);try{const te=await o(G);if(te!=null&&te.storage_path){if(te.signed_url){const re=te.signed_url;k(L=>({...L,[te.storage_path]:re}))}N(re=>{const L=re[z.id]||[];return L.some(q=>q.storage_path===te.storage_path)?re:{...re,[z.id]:[...L,{storage_path:te.storage_path,signed_url:te.signed_url,mode:"upload"}]}}),P(z.id,{image_paths:[...z.image_paths||[],te.storage_path]})}}finally{w(null)}}}async function S(){for(const z of d)A(z)&&await C(z)}function O(z,G){h(G),u(z),a(z,G)}const R=p.useMemo(()=>e.map(z=>({id:z.attribute_id,values:f[z.attribute_id]||[]})).filter(z=>z.values.length),[e,f]),I=PL(R).length;function $(){const z=t.map(te=>te.storage_path).filter(Boolean),G=PL(R).slice(0,60).map(te=>({id:KGe(),attrs:te,sku:"",barcode:"",selling_price:null,image_paths:z}));O("multiple",G)}function P(z,G){O(c,d.map(te=>te.id===z?{...te,...G}:te))}function F(z,G){m(te=>{const re=te[z]||[];return{...te,[z]:re.includes(G)?re.filter(L=>L!==G):[...re,G]}})}function Z(z){const G=(x[z]||"").trim();G&&(m(te=>{const re=te[z]||[];return re.includes(G)?te:{...te,[z]:[...re,G]}}),g(te=>({...te,[z]:""})))}const D=p.useMemo(()=>{const z={};for(const G of d)for(const[te,re]of Object.entries(G.attrs||{}))(z[te]||(z[te]=new Set)).add(re);return new Set(Object.entries(z).filter(([,G])=>G.size>1).map(([G])=>G))},[d]),H=z=>(D.size?e.filter(te=>D.has(te.attribute_id)):e).map(te=>z[te.attribute_id]).filter(Boolean).join(" · ");function Y(z){const G=new Map;for(const te of t)te.storage_path&&G.set(te.storage_path,te);for(const te of j[z.id]||[])te.storage_path&&!G.has(te.storage_path)&&G.set(te.storage_path,{...te,signed_url:te.signed_url??_[te.storage_path]});for(const te of z.image_paths||[])te&&!G.has(te)&&G.set(te,{storage_path:te,signed_url:_[te]});return[...G.values()]}const M=e.length>0;return s.jsxs("div",{children:[s.jsx("h3",{className:"mb-2 text-body-sm font-semibold text-text-primary",children:"Variants"}),s.jsxs("div",{className:"mb-3 flex gap-2",children:[s.jsx("button",{type:"button",onClick:()=>O("single",d),className:`rounded-md border px-3 py-1.5 text-body-sm transition ${c==="single"?"border-intent-brand bg-intent-brandSubtle text-text-primary":"border-outline-subtle bg-surface text-text-body hover:bg-surface-subtle"}`,children:"Single product"}),s.jsx("button",{type:"button",disabled:!M,onClick:()=>O("multiple",d),className:`rounded-md border px-3 py-1.5 text-body-sm transition disabled:opacity-40 ${c==="multiple"?"border-intent-brand bg-intent-brandSubtle text-text-primary":"border-outline-subtle bg-surface text-text-body hover:bg-surface-subtle"}`,children:"Multiple variants"})]}),M?null:s.jsx("p",{className:"text-body-xs text-text-secondary",children:"This category doesn't define variant axes â single product only."}),c==="multiple"&&M?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mb-3 flex flex-col gap-3",children:e.map(z=>{const G=f[z.attribute_id]||[],te=G.filter(re=>!z.options.includes(re));return s.jsxs("div",{children:[s.jsxs("div",{className:"text-body-xs font-medium text-text-primary",children:[z.display_name,z.required?s.jsx("span",{className:"text-text-error",children:" *"}):null]}),z.options.length>0?s.jsx("div",{className:"mt-1 flex max-h-28 flex-wrap gap-1 overflow-y-auto",children:z.options.map(re=>s.jsx("button",{type:"button",onClick:()=>F(z.attribute_id,re),className:G.includes(re)?DL:RL,children:re},re))}
910):null,s.jsxs("div",{className:"mt-1 flex gap-1",children:[s.jsx("input",{value:x[z.attribute_id]||"",onChange:re=>g(L=>({...L,[z.attribute_id]:re.target.value})),onKeyDown:re=>{re.key==="Enter"&&(re.preventDefault(),Z(z.attribute_id))},placeholder:z.options.length?`Add another ${z.display_name}`:`Add a ${z.display_name} value`,className:fy}),s.jsx("button",{type:"button",onClick:()=>Z(z.attribute_id),className:RL,children:s.jsx(In,{className:"h-3 w-3"})})]}),te.length>0?s.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:te.map(re=>s.jsxs("button",{type:"button",onClick:()=>F(z.attribute_id,re),className:DL,children:[re," â"]},re))}):null]},z.attribute_id)})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("button",{type:"button",onClick:$,disabled:R.length===0,className:"inline-flex items-center gap-1.5 rounded-md bg-intent-brand px-3 py-1.5 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover disabled:opacity-50",children:["Generate variants",I?` (${I})`:""]}),i&&E&&d.some(z=>A(z))?s.jsx("button",{type:"button",onClick:S,disabled:!!y,title:"Recolour every variant's images to its own colour â reuses the base images instead of generating from scratch",className:"inline-flex items-center gap-1.5 rounded-md border border-outline-subtle bg-surface px-3 py-1.5 text-body-sm text-text-primary shadow-xs transition hover:bg-surface-subtle disabled:opacity-50",children:y?"Recolouringâ¦":"Recolour all variants"}):null]}),i&&E&&d.some(z=>A(z))?(()=>{const z=t.filter(te=>te.mode==="lifestyle"||te.mode==="dimensions").length,G=t.length-z;return s.jsxs("div",{className:"mt-1.5 text-body-xs text-text-secondary",children:["Recolour updates the ",G," product shot",G===1?"":"s"," in the pool",z>0?s.jsxs(s.Fragment,{children:[" ","and leaves ",z," lifestyle/dimension image",z===1?"":"s"," unchanged â recolouring those renders the scene flat onto white. Add more white-background angles if you want a fuller recoloured set."]}):"."]})})():null,d.length>0?s.jsx("div",{className:"mt-4 flex flex-col gap-2",children:d.map(z=>s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface p-2 shadow-xs",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-body-sm font-medium text-text-primary",children:H(z.attrs)||"(variant)"}),s.jsxs("div",{className:"flex items-center gap-2",children:[i&&A(z)?s.jsx("button",{type:"button",onClick:()=>C(z),disabled:!!y,title:`Recolour this variant's images to ${A(z)}`,className:"rounded-md border border-outline-subtle bg-surface px-2 py-0.5 text-body-xs text-text-body shadow-xs transition hover:bg-surface-subtle disabled:opacity-50",children:y===z.id?"Recolouringâ¦":`Recolour to ${A(z)}`}):null,s.jsx("button",{type:"button",onClick:()=>O(c,d.filter(G=>G.id!==z.id)),title:"Remove variant",children:s.jsx(us,{className:"h-4 w-4 text-text-secondary hover:text-text-error"})})]})]}),s.jsxs("div",{className:"mt-1.5 grid grid-cols-3 gap-2",children:[s.jsx("input",{placeholder:"SKU",value:z.sku||"",onChange:G=>P(z.id,{sku:G.target.value}),className:fy}),s.jsx("input",{placeholder:"Barcode",value:z.barcode||"",onChange:G=>P(z.id,{barcode:G.target.value}),className:fy}),s.jsx("input",{placeholder:"Price (R)",type:"number",value:z.selling_price??"",onChange:G=>P(z.id,{selling_price:G.target.value===""?null:Number(G.target.value)}),className:fy})]}),Y(z).length>0||o?s.jsxs("div",{className:"mt-1.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("div",{className:"text-body-xs text-text-secondary",children:"Images (click to include or exclude â defaults to all; nothing is deleted)"}),o?s.jsxs("label",{className:"inline-flex cursor-pointer items-center gap-1 rounded border border-outline-subtle bg-surface px-1.5 py-0.5 text-body-xs text-text-body shadow-xs transition hover:bg-surface-subtle",children:[v===z.id?"Uploadingâ¦":"+ Add photo",s.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:v===z.id,onChange:G=>{var re;const te=(re=G.target.files)==null?void 0:re[0];te&&T(z,te),G.target.value=""}})]}):null]}),Y(z).length>0?s.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:Y(z).map((G,te)=>{const re=G.storage_path||"",L=(z.image_paths||[]).includes(re);return s.jsx("button",{type:"button",onClick:()=>P(z.id,{image_paths:L?(z.image_paths||[]).filter(q=>q!==re):[...z.image_paths||[],re]}),className:`h-12 w-12 overflow-hidden rounded border ${L?"ring-2 ring-intent-brand":"opacity-50"}`,children:s.jsx("img",{src:G.signed_url||void 0,alt:"",className:"h-full w-full bg-surface-subtle object-contain"})},te)})}):s.jsx("div",{className:"mt-1 text-body-xs text-text-tertiary",children:"No images yet â add a photo for this variant."})]}):null]},z.id))}):null]}):null]})}function ML(e){var a;const t=(a=e.listings)==null?void 0:a[0],n=(t==null?void 0:t.image_url)||null,r=typeof n=="string"&&n.startsWith("http://")?`https://${n.slice(7)}`:n;
910return{title:e.title||(t==null?void 0:t.title)||e.internal_sku||"Untitled",sku:(t==null?void 0:t.sku)||e.internal_sku,image_url:r}}function VGe({slug:e,selected:t,onChange:n}){const[r,a]=p.useState(""),[i,o]=p.useState(""),[l,c]=p.useState(!1),[u,d]=p.useState([]);p.useEffect(()=>{const x=setTimeout(()=>o(r.trim()),250);return()=>clearTimeout(x)},[r]),p.useEffect(()=>{let x=!0;if(i.length<2){d([]);return}return c(!0),K.catalogue(e,i,20).then(g=>{x&&d(g)}).catch(()=>{x&&d([])}).finally(()=>{x&&c(!1)}),()=>{x=!1}},[e,i]);const h=new Set(t.map(x=>x.warehouse_item_id));function f(x){const{title:g,sku:y,image_url:b}=ML(x);if(h.has(x.id)){n(t.map(v=>v.warehouse_item_id===x.id?{...v,quantity:v.quantity+1}:v));return}n([...t,{warehouse_item_id:x.id,quantity:1,title:g,sku:y,image_url:b}])}function m(x,g){if(g<1){n(t.filter(y=>y.warehouse_item_id!==x));return}n(t.map(y=>y.warehouse_item_id===x?{...y,quantity:g}:y))}return s.jsxs("div",{children:[s.jsx("label",{className:"mb-1 block text-body-sm font-medium text-text-primary",children:"Search your catalogue"}),s.jsx(pc,{fieldClassName:"mb-3",value:r,onChange:x=>a(x.target.value),placeholder:"SKU, title or barcode (a short phrase like laptop bag works)"}),l?s.jsxs("div",{className:"mb-3 flex items-center gap-2 text-body-xs text-text-secondary",children:[s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"})," Searchingâ¦"]}):null,u.length>0?s.jsx("ul",{className:"mb-4 max-h-48 overflow-y-auto rounded-md border border-outline-subtle",children:u.map(x=>{const{title:g,sku:y,image_url:b}=ML(x),v=h.has(x.id);return s.jsxs("li",{className:"flex items-center gap-2 border-b border-outline-faint px-2 py-1.5 last:border-b-0",children:[b?s.jsx("img",{src:b,alt:"",className:"h-8 w-8 shrink-0 rounded object-cover"}):s.jsx("div",{className:"h-8 w-8 shrink-0 rounded bg-surface-sunken"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"truncate text-body-sm text-text-primary",children:g}),y?s.jsx("div",{className:"truncate text-body-xs text-text-secondary",children:y}):null]}),s.jsxs("button",{type:"button",onClick:()=>f(x),className:"inline-flex items-center gap-1 rounded-md border border-outline-subtle px-2 py-1 text-body-xs text-text-primary hover:bg-surface-subtle",children:[s.jsx(In,{className:"h-3 w-3"})," ",v?"Add another":"Add"]})]},x.id)})}):i.length>=2&&!l?s.jsx("p",{className:"mb-4 text-body-xs text-text-secondary",children:"No catalogue matches."}):null,t.length>0?s.jsxs("div",{children:[s.jsxs("div",{className:"mb-1 text-body-xs font-medium text-text-secondary",children:["In this bundle (",t.length,")"]}),s.jsx("ul",{className:"rounded-md border border-outline-subtle",children:t.map(x=>s.jsxs("li",{className:"flex items-center gap-2 border-b border-outline-faint px-2 py-1.5 last:border-b-0",children:[x.image_url?s.jsx("img",{src:x.image_url,alt:"",className:"h-8 w-8 shrink-0 rounded object-cover"}):s.jsx("div",{className:"h-8 w-8 shrink-0 rounded bg-surface-sunken"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"truncate text-body-sm text-text-primary",children:x.title}),x.sku?s.jsx("div",{className:"truncate text-body-xs text-text-secondary",children:x.sku}):null]}),s.jsx("input",{type:"number",min:1,value:x.quantity,onChange:g=>m(x.warehouse_item_id,Number(g.target.value)||1),className:"w-14 rounded-md border border-outline bg-surface px-2 py-1 text-center text-body-sm","aria-label":`Quantity of ${x.title}`}),s.jsx("button",{type:"button",onClick:()=>m(x.warehouse_item_id,0),title:"Remove",className:"text-text-secondary hover:text-text-error",children:s.jsx(Bn,{className:"h-3.5 w-3.5"})})]},x.warehouse_item_id))})]}):s.jsx("p",{className:"text-body-xs text-text-secondary",children:"Add 1+ items. Quantity 3 of one SKU is a multi-pack; two different SKUs is a combo."})]})}function qGe({disabled:e,busy:t,onAdd:n}){const[r,a]=p.useState(""),[i,o]=p.useState(!1),l=e||t||i;async function c(u){u.preventDefault();const d=r.trim();if(!(!d||l)){o(!0);try{await n(d),a("")}catch{}finally{o(!1)}}}return s.jsxs("form",{onSubmit:c,className:"flex w-full max-w-xl flex-col items-stretch gap-1.5 sm:flex-row sm:items-center",children:[s.jsx("label",{className:"sr-only",htmlFor:"listing-image-url",children:"Image URL"}),s.jsxs("div",{className:"relative min-w-0 flex-1",children:[s.jsx(qne,{className:"pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-text-tertiary"}),s.jsx("input",{id:"listing-image-url",type:"text",inputMode:"url",autoComplete:"off",spellCheck:!1,disabled:l,value:r,onChange:u=>a(u.target.value),placeholder:"https://â¦/product.jpg",className:"block w-full rounded-md border border-outline bg-surface py-1.5 pl-8 pr-3 text-body-sm text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus disabled:opacity-50"})]}),s.jsxs("button",{type:"submit",disabled:l||!r.trim(),className:"inline-flex shrink-0 items-center justify-center gap-1 rounded-md border border-outline-subtle bg-surface px-3 py-1.5 text-body-sm text-text-primary transition hover:bg-surface-subtle disabled:opacity-50",children:[i?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):null,"Add URL"]})]})}function GGe(e){return e instanceof Set?e:Array.isArray(e)?new Set(e):null}const YGe=["product_dimensions","merchant_packaged_weight","merchant_packaged_dimensions"];function ZGe(e){return YGe.some(t=>e===t||e.startsWith(`${t}.`))}function CG(e,t){const n=String(e||"");if(!n.endsWith(".value"))return!1;const r=n.slice(0,-6);if(ZGe(r))return!1;const a=`${r}.unit`,i=GGe(t);return i?i.has(a):!1}function EG(e){const t=String(e||"");return t.endsWith(".value")?`${t.slice(0,-6)}.unit`:t.endsWith(".unit")?`${t.slice(0,-5)}.value`:null}function AG(e,t){return!e||e.data_type!=="Float"?!1:!CG(e.attribute_id,t)}function TG(e,t){return t&&(e||[]).find(n=>(n==null?void 0:n.attribute_id)===t)||null}function OG(e,t){var a;if(!(e!=null&&e.attribute_id))return!1;const n=new Set((t||[]).map(i=>
910i==null?void 0:i.attribute_id).filter(Boolean));if(AG(e,n))return!1;if(e.required)return!0;const r=EG(e.attribute_id);return r?!!((a=TG(t,r))!=null&&a.required):!1}function Mv(e){const t=Array.isArray(e)?e:[];return t.filter(n=>OG(n,t))}function XGe(e,t){if(!(e!=null&&e.attribute_id)||OG(e,t))return!1;const n=new Set((t||[]).map(r=>r==null?void 0:r.attribute_id).filter(Boolean));return!AG(e,n)}function $v(e){const t=Array.isArray(e)?e:[];return t.filter(n=>XGe(n,t))}const JGe=.5;function QGe(e){const t=Array.isArray(e)?e:[],n=new Set,r=[];for(const a of t){const i=a==null?void 0:a.attribute_id;if(!(!i||n.has(i))){if(i.endsWith(".value")){const o=TG(t,`${i.slice(0,-6)}.unit`);if(o){n.add(i),n.add(o.attribute_id),r.push({kind:"compound",valueAttr:a,unitAttr:o});continue}}n.add(i),r.push({kind:"single",attr:a})}}return r}function id(e){return!!(e==null||e===""||Array.isArray(e)&&e.length===0)}function eYe({productAttributes:e=[],variantAttributes:t=[],productlineAttributes:n={},variantAttributeSets:r=[{}]}={}){const a=Array.isArray(r)&&r.length?r:[{}],i=[...$v(e).map(u=>({a:u,bags:[n]})),...$v(t).map(u=>({a:u,bags:a}))],o=[];let l=0;for(const{a:u,bags:d}of i)d.some(h=>id(h==null?void 0:h[u.attribute_id]))?o.push(u):l++;const c=i.length;return{total:c,filled:l,missing:o,completion_pct:c===0?1:l/c}}function tYe(e){if(!e||e.total===0||e.completion_pct>=JGe)return null;const t=e.missing.slice(0,8).map(r=>`"${r.display_name}"`),n=e.missing.length>8?` and ${e.missing.length-8} more`:"";return`${e.filled} of ${e.total} recommended attributes filled. Takealot needs about half filled to rate a listing Excellent instead of Moderate. Fill ${t.join(", ")}${n} if you can â optional, won't block submit.`}function $L(e,t,n){const r=Array.isArray(e)?e:[],a=new Set(r.map(l=>l==null?void 0:l.attribute_id).filter(Boolean)),i=[],o=new Set;for(const l of r){const c=l==null?void 0:l.attribute_id;if(!CG(c,a)||o.has(c))continue;o.add(c);const u=EG(c),d=t.some(x=>id(x==null?void 0:x[c])),h=t.some(x=>id(x==null?void 0:x[u])),f=t.some(x=>!id(x==null?void 0:x[c]));(t.some(x=>!id(x==null?void 0:x[u]))&&d||f&&h)&&i.push(`${n} "${l.display_name||"Volume"}"`)}return i}function nYe({productAttributes:e=[],variantAttributes:t=[],productlineAttributes:n={},variantAttributeSets:r=[{}]}={}){const a=[];for(const o of Mv(e))id(n==null?void 0:n[o.attribute_id])&&a.push(`attribute "${o.display_name}"`);const i=Array.isArray(r)&&r.length?r:[{}];for(const o of Mv(t))i.some(l=>id(l==null?void 0:l[o.attribute_id]))&&a.push(`variant attribute "${o.display_name}"`);for(const o of $L(e,[n],"attribute"))a.includes(o)||a.push(o);for(const o of $L(t,i,"variant attribute"))a.includes(o)||a.push(o);return a}function rYe(e,t=[]){const r=String(e||"").match(/(\d+(?:[.,]\d+)?)\s*(ml|millilitres?|milliliters?|l|litres?|liters?)\b/i);if(!r)return null;const a=Number(String(r[1]).replace(",","."));if(!Number.isFinite(a)||a<=0)return null;const i=r[2].toLowerCase(),o=i==="ml"||i.startsWith("millilit"),l=o?a:a*1e3,c=(t||[]).map(String),u=f=>c.find(m=>f.test(m))||null;let d=u(/millilit/i)||u(/^ml$/i),h=l;if(!d){const f=u(/litres?|liters?/i)||u(/^l$/i);f&&(d=f,h=o?a/1e3:a)}return d||(d=c[0]||"Milliliters"),!c.length||c.some(f=>f.toLowerCase()===String(d).toLowerCase())?{value:h,unit:d}:{value:h,unit:u(new RegExp(`^${d}$`,"i"))||c[0]}}function LL(e){return String(e||"").toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}function FL(e){const t=String(e||"");return t.endsWith("ies")&&t.length>4?`${t.slice(0,-3)}y`:/(ses|xes|zes|ches|shes)$/.test(t)&&t.length>4?t.slice(0,-2):t.endsWith("s")&&!t.endsWith("ss")&&t.length>3?t.slice(0,-1):t}function sYe(e,t){const n=LL(e),r=LL(t);if(!r||n.includes(r))return!0;const a=new Set(n.split(/\s+/).filter(Boolean).map(FL)),i=r.split(/\s+/).filter(Boolean).map(FL);return i.length>0&&i.every(o=>a.has(o)||n.includes(o))}function aYe(e){return Array.isArray(e)?e.filter(Boolean).join(" "):String(e||"")}function iYe(e,t){var c;const n=aYe(e),r=String(t||"");if(!n||!r)return null;const a=n.toLowerCase(),i=/\b(cables?|bnc)\b/i.test(r),o=/\bcables?\b/.test(a),l=/\bkits?\b/.test(a);return i&&l&&!o?`title looks like a single cable but the category is "${((c=n.split(/->/).pop())==null?void 0:c.trim())||n}" â Takealot rejects cables submitted as a kit. Pick a cable c
910ategory (Audio & Video Cables, System & Power Cables), not a kit.`:null}const Cm="block w-full rounded-md border border-outline bg-surface px-3 py-1.5 text-body-sm text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus";function bj({label:e,children:t}){return s.jsxs("div",{children:[s.jsx("label",{className:"mb-1 block text-body-xs font-medium text-text-secondary",children:e}),t]})}function oYe(e){return/^multi/i.test(e||"")}function lYe(e){return Array.isArray(e)?e.map(String):e!=null&&e!==""?[String(e)]:[]}function vj({a:e,value:t,onChange:n}){if(oYe(e.data_type)){const a=lYe(t);return e.options.length?s.jsx("select",{multiple:!0,className:Cm,value:a,onChange:i=>n(Array.from(i.target.selectedOptions).map(o=>o.value)),children:e.options.map(i=>s.jsx("option",{value:i,children:i},i))}):s.jsx("input",{type:"text",className:Cm,value:a.length>1?a.join(", "):a[0]??"",onChange:i=>n(i.target.value===""?[]:[i.target.value])})}if(e.data_type==="Dropdown"&&e.options.length)return s.jsxs("select",{className:Cm,value:t??"",onChange:a=>n(a.target.value),children:[s.jsx("option",{value:"",children:"Selectâ¦"}),e.options.map(a=>s.jsx("option",{value:a,children:a},a))]});if(e.data_type==="Boolean")return s.jsxs("select",{className:Cm,value:t??"",onChange:a=>n(a.target.value),children:[s.jsx("option",{value:"",children:"Selectâ¦"}),s.jsx("option",{children:"Yes"}),s.jsx("option",{children:"No"})]});const r=e.data_type==="Float"||e.data_type==="Integer";return s.jsx("input",{type:r?"number":"text",className:Cm,value:t??"",onChange:a=>n(r?a.target.value===""?null:Number(a.target.value):a.target.value)})}function my({attrs:e,values:t,entity:n,onChange:r}){return e.length===0?null:s.jsx(s.Fragment,{children:QGe(e).map(a=>a.kind==="compound"?s.jsxs("div",{className:"col-span-2 grid grid-cols-2 gap-3",children:[s.jsx(bj,{label:a.valueAttr.display_name,children:s.jsx(vj,{a:a.valueAttr,value:t[a.valueAttr.attribute_id],onChange:i=>r(n,a.valueAttr.attribute_id,i)})}),s.jsx(bj,{label:a.unitAttr.display_name,children:s.jsx(vj,{a:a.unitAttr,value:t[a.unitAttr.attribute_id],onChange:i=>r(n,a.unitAttr.attribute_id,i)})})]},a.valueAttr.attribute_id):s.jsx(bj,{label:a.attr.display_name,children:s.jsx(vj,{a:a.attr,value:t[a.attr.attribute_id],onChange:i=>r(n,a.attr.attribute_id,i)})},a.attr.attribute_id))})}function cYe({reqProductAttrs:e,reqVariantAttrs:t,optProductAttrs:n,optVariantAttrs:r,variantCount:a,pAttrs:i,vAttrs:o,busy:l,onAutoFill:c,onSetAttr:u}){const d=a===0?t:[],h=e.length>0||d.length>0,f=n.length>0||r.length>0;return!h&&!f?null:s.jsxs("div",{className:"mt-5",children:[s.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[s.jsx("div",{className:"text-body-xs font-medium text-text-secondary",children:"Category attributes"}),s.jsxs("button",{type:"button",disabled:!!l,onClick:c,className:"inline-flex items-center gap-1.5 rounded-md border border-outline-subtle px-2.5 py-1 text-body-xs text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary disabled:opacity-50",children:[l==="attrs"?s.jsx(_e,{className:"h-3 w-3 animate-spin"}):s.jsx(Ht,{className:"h-3 w-3"}),"Auto-fill with AI"]})]}),h?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mb-1.5 text-body-xs font-medium text-text-secondary",children:"Required"}),s.jsx("p",{className:"mb-2 text-body-xs text-text-secondary",children:"AI fills these from your product â please review and confirm before submitting."}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsx(my,{attrs:e,values:i,entity:"product",onChange:u}),s.jsx(my,{attrs:d,values:o,entity:"variant",onChange:u})]}),a>0&&t.length>0?s.jsxs("p",{className:"mt-2 text-body-xs text-text-secondary",children:["Variant attributes (",t.map(m=>m.display_name).join(", "),") come from your variant axes in the Variants step."]}):null]}):null,f?s.jsxs("div",{className:h?"mt-5":"",children:[s.jsx("div",{className:"mb-1.5 text-body-xs font-medium text-text-secondary",children:"Recommended â lifts listing quality to Excellent"}),s.jsx("p",{className:"mb-2 text-body-xs text-text-secondary",children:"Optional, but Takealot needs about half of these filled to rate the listing Excellent instead of Moderate (better search placement). Skip any you can't answer."}),s.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[s.jsx(my,{attrs:n,values:i,entity:"product",onChange:u}
910),s.jsx(my,{attrs:r,values:o,entity:"variant",onChange:u})]})]}):null]})}const uYe=/<\/(p|ul|ol|div)\s*>/gi,dYe=/<\/li\s*>/gi,hYe=/<li\s*[^>]*>/gi,fYe=/<br\s*\/?>/gi,mYe=/<[^>]*>/g,pYe={"&":"&","<":"<",">":">",""":'"',"'":"'","'":"'"," ":" "};function BL(e){if(typeof e!="string")return"";if(!/[<&]/.test(e))return e.trim();let t=e.replace(fYe,` 911`).replace(dYe,"").replace(hYe,` 912⢠`).replace(uYe,` 913 914`).replace(mYe,"");for(const[n,r]of Object.entries(pYe))t=t.split(n).join(r);return t.replace(/[ \t]+/g," ").replace(/[ \t]*\n[ \t]*/g,` 915`).replace(/\n{2,}(?=⢠)/g,` 916`).replace(/\n{3,}/g,` 917 918`).trim()}function xYe(e){return typeof e=="string"&&/<(p|ul|ol|li|strong|em|br)\b[^>]*>/i.test(e)}const UL=["Input","Category","Content","Images","Variants","Details","Review"],gYe=[{key:"title",label:"Title"},{key:"subtitle",label:"Subtitle"},{key:"description",label:"Description",long:!0},{key:"whats_in_the_box",label:"What's in the box"}];function yYe({slug:e,resumeDraftId:t=null,onDraftsChanged:n}){var Zf,Xf,Jf,Xx,Jx,Qx;const[r,a]=p.useState("loading"),[i,o]=p.useState([]),[l,c]=p.useState(!1),u=p.useRef(0),[d,h]=p.useState(0),[f,m]=p.useState(null),[x,g]=p.useState(""),[y,b]=p.useState(""),[v,w]=p.useState("new"),[_,k]=p.useState([]),[j,N]=p.useState([]),[E,A]=p.useState(!0),[C,T]=p.useState(""),[S,O]=p.useState([]),[R,I]=p.useState({}),[$,P]=p.useState(null),[F,Z]=p.useState(!1),[D,H]=p.useState(null),[Y,M]=p.useState(""),[z,G]=p.useState(null),[te,re]=p.useState({length:"",height:"",width:""}),[L,q]=p.useState(null),[me,ee]=p.useState([]),[ne,X]=p.useState(!1),[he,ae]=p.useState([]),[je,$e]=p.useState([]),J=p.useRef(null),Ne=(f==null?void 0:f.category_id)??null;p.useEffect(()=>{if(!Ne){ae([]),$e([]);return}K.listingDrafts.categorySchema(e,Ne).then(se=>{ae(se.variant_attributes||[]),$e(se.product_attributes||[])}).catch(()=>{ae([]),$e([])})},[e,Ne]);async function ve(){if(f){Fe("attrs"),fe(null);try{const se=await K.listingDrafts.generateAttributes(e,f.id);se.draft&&m(se.draft)}catch(se){fe(se instanceof Error?se.message:String(se))}finally{Fe(null)}}}function Me(se,ke,Te){if(!f)return;const qe=f.attributes??{},ht=se==="product"?"productline_attributes":"variant_attributes",ut=qe[ht]??{},ct={...qe,[ht]:{...ut,[ke]:Te}};m({...f,attributes:ct}),It(K.listingDrafts.patch(e,f.id,{attributes:ct}))}function Xe(se,ke){if(!f)return;const Te={...f.attributes??{},_variant_mode:se,_variants:ke};m({...f,attributes:Te}),It(K.listingDrafts.patch(e,f.id,{attributes:Te}))}const[ze,Fe]=p.useState(null),[tt,fe]=p.useState(null),[U,ce]=p.useState(null),[ue,Ee]=p.useState(""),[bt,Ze]=p.useState(null);function vt(se){f&&(m({...f,...se}),It(K.listingDrafts.patch(e,f.id,se)))}p.useEffect(()=>{if(d!==5||!f)return;const se=f.warranty??{};se.type||vt({warranty:{type:"Limited",months:se.months??6}})},[d,f==null?void 0:f.id]);function Ot(se){u.current=Math.max(0,u.current+se),c(u.current>0)}function It(se){Ot(1),se.catch(()=>{}).finally(()=>Ot(-1))}function Ut(se){var ut,ct;if(se.status==="submitted"||(ut=se.submission)!=null&&ut.ok||((ct=se.submission)==null?void 0:ct.error)==="unconfirmed")return 6;const ke=se.content??{},Te=!!ke.title&&!!ke.description,qe=(se.images??[]).length>0,ht=!!se.sku&&se.selling_price!=null;return se.details?se.category_id?Te?qe?ht?6:5:3:2:1:0}function Lr(se){m(se),g(se.details??""),b((se.links??[]).map(qe=>qe.url).join(` 919`));const ke=Array.isArray(se.bundle_components)?se.bundle_components:[];ke.length?(w("bundle"),k(ke.map(qe=>({warehouse_item_id:qe.warehouse_item_id,quantity:qe.quantity,title:qe.title||"Catalogue item",sku:qe.sku??null})))):(w("new"),k([])),X(!1),N([]),O([]);const Te=se.submission;ce(Te&&(Te.ok===!0||Te.error==="unconfirmed")?{ok:Te.ok===!0,error:Te.error,message:Te.message,takealot_submission_id:Te.takealot_submission_id!=null?String(Te.takealot_submission_id):void 0,details:Te.details,reused:Te.reused}:null),T(""),fe(null),h(Ut(se)),a("builder")}function en(){m(null),g(""),b(""),w("new"),k([]),H(null),M(""),N([]),O([]),T(""),ce(null),fe(null),h(0),a("builder")}async function Hs(){try{const{drafts:se}
919=await K.listingDrafts.list(e),ke=se.filter(Te=>Te.status==="draft");return o(ke),ke}catch{return o([]),[]}}async function Os(se){a("loading");try{const{draft:ke}=await K.listingDrafts.get(e,se);Lr(ke)}catch(ke){fe(ke instanceof Error?ke.message:String(ke)),a("drafts")}}async function gr(){n==null||n(),a("loading");const se=await Hs();m(null),h(0),se.length===0?en():a("drafts")}async function Vs(se){try{await K.listingDrafts.discard(e,se)}catch(ke){fe(ke instanceof Error?ke.message:String(ke));return}n==null||n(),o(ke=>ke.filter(Te=>Te.id!==se)),(f==null?void 0:f.id)===se&&gr()}p.useEffect(()=>{let se=!0;return(async()=>{if(t)try{const{draft:Te}=await K.listingDrafts.get(e,t);se&&Lr(Te);return}catch{}const ke=await Hs();se&&(ke.length>0?a("drafts"):en())})(),()=>{se=!1}},[e,t]);async function Xn(){fe(null),Fe("analyse");try{const se=y.split(/\s+/).map(ut=>ut.trim()).filter(ut=>/^https?:\/\//.test(ut)).map(ut=>({url:ut}));let ke=(await K.listingDrafts.create(e,{details:x.trim()||void 0,links:se,...v==="bundle"?{bundle_components:_.map(ut=>({warehouse_item_id:ut.warehouse_item_id,quantity:ut.quantity,title:ut.title,sku:ut.sku}))}:{}})).draft;if(D)try{const ut=await py(D);ke=(await K.listingDrafts.uploadImage(e,ke.id,{filename:D.name,base64:ut,mime:D.type||"image/png"})).draft}catch{}const Te=Y.trim();if(Te)try{ke=(await K.listingDrafts.importImageUrl(e,ke.id,Te,{addToListing:!1})).draft}catch(ut){fe(ut instanceof Error?ut.message:String(ut))}m(ke);const{candidates:qe,confident:ht}=await K.listingDrafts.suggestCategories(e,ke.id);N(qe),A(ht),h(1),n==null||n()}catch(se){fe(se instanceof Error?se.message:String(se))}finally{Fe(null)}}async function le(se){if(f){Fe(`gen:${se}`),fe(null);try{const{draft:ke}=await K.listingDrafts.generate(e,f.id,se,ne);m(ke)}catch(ke){fe(ke instanceof Error?ke.message:String(ke))}finally{Fe(null)}}}async function De(se=!1){if(f){Fe(se?"draft":"submit"),ce(null);try{const ke=await K.listingDrafts.submit(e,f.id,se?{submit_as_draft:!0}:void 0);ce(ke),m(Te=>Te&&{...Te,status:ke.ok||ke.error==="unconfirmed"?"submitted":Te.status,submission:ke}),n==null||n()}catch(ke){fe(ke instanceof Error?ke.message:String(ke))}finally{Fe(null)}}}async function Ie(){if(f){Fe("autofix"),fe(null),Ze(null);try{const se=await K.listingDrafts.autoFix(e,f.id,ue);se.draft&&m(se.draft),Ze({applied:se.applied??[],unfixable:se.unfixable??[]}),ce(null)}catch(se){fe(se instanceof Error?se.message:String(se))}finally{Fe(null)}}}async function Ge(se){if(f){Fe("upload"),fe(null);try{const ke=await py(se),{draft:Te}=await K.listingDrafts.uploadImage(e,f.id,{filename:se.name,base64:ke,mime:se.type||"image/png"});m(Te)}catch(ke){fe(ke instanceof Error?ke.message:String(ke))}finally{Fe(null)}}}async function ye(se){if(f){Fe("upload"),fe(null);try{const{draft:ke}=await K.listingDrafts.importImageUrl(e,f.id,se);m(ke)}catch(ke){throw fe(ke instanceof Error?ke.message:String(ke)),ke}finally{Fe(null)}}}async function ie(se,ke,Te,qe){if(f){Fe(qe??`img:${se}:${ke}`),fe(null);try{const{draft:ht}=await K.listingDrafts.generateImage(e,f.id,{source_ref:se,mode:ke,prompt:Te!=null&&Te.trim()?Te.trim():void 0});m(ht)}catch(ht){fe(ht instanceof Error?ht.message:String(ht))}finally{Fe(null)}}}async function pe(se,ke){if(!f)return;const Te=ke.length.trim(),qe=ke.height.trim(),ht=ke.width.trim(),ut=[Te?`Length ${Te} cm`:null,qe?`Height ${qe} cm`:null,ht?`Width ${ht} cm`:null].filter(Boolean);if(ut.length===0){fe("Enter at least one measurement (length, height or width).");return}const ct={...f.package_dimensions??{},...Te?{length:Number(Te)}:{},...qe?{height:Number(qe)}:{},...ht?{width:Number(ht)}:{}};Fe(`img:${se}:dimensions`),fe(null);try{await K.listingDrafts.patch(e,f.id,{package_dimensions:ct});const{draft:ms}=await K.listingDrafts.generateImage(e,f.id,{source_ref:se,mode:"dimensions",prompt:ut.join(", ")});m(ms),G(null)}catch(ms){fe(ms instanceof Error?ms.message:String(ms))}finally{Fe(null)}}async function xe(se){var ke;if(f){Fe(`imgall:${se}`),fe(null);try{let Te=f;for(const qe of Te.source_images??[]){const ht=qe.ref||qe.storage_path;if(!ht)continue;const ut=se==="original"?void 0:((ke=R[ht])==null?void 0:ke.trim())||void 0;Te=(await K.listingDrafts.generateImage(e,Te.id,{source_ref:ht,mode:se,prompt:ut})).draft,m(Te)}}catch(Te){fe(Te instanceof Error?Te.message:String(Te))}finally{Fe(null)}}}async function Ke(se,ke="preset"){if(!f)return;let Te=se;if(!Te){const qe=(f.source_images??[])[0];Te=(qe==null?void 0:qe.ref)||(qe==null?void 0:qe.storage_path)}if(!Te){fe("Upload a photo first.");return}Fe(ke),fe(null);try{const{listing_image_preset:qe}=await K.getListingImagePreset();let ht=f;for(const ut of qe.shots){const ct=(ut.mode==="angle"||ut.mode==="lifestyle")&&ut.prompt||void 0;ht=(await K.listingDrafts.generateImage(e,ht.id,{source_ref:Te,mode:ut.mode,prompt:ct})).draft,m(ht)}}catch(qe){fe(qe instanceof Error?qe.message:String(qe))}finally{Fe(null)}}async function St(se){if(!f)return;const ke=(f.source_images??[]).filter((Te,qe)=>qe!==se);try{const{draft:Te}=await K.listingDrafts.patch(e,f.id,{source_images:ke});m(Te)}catch(Te){fe(Te instanceof Error?Te.message:String(Te))}}async function Jt(se,ke){if(!f||se===ke)return;const Te=[...f.images??[]],[qe]=Te.splice(se,1);Te.splice(ke,0,qe),m({...f,images:Te});try{const{draft:ht}=await K.listingDrafts.patch(e,f.id,{images:Te});m(ht)}catch(ht){fe(ht instanceof Error?ht.message:String(ht))}}async function yn(se,ke){if(!f||!ke.trim())return[];const Te=[];for(const qe of se){if(!qe)continue;const ut=(await K.listingDrafts.generateImage(e,f.id,{source_ref:qe,mode:"recolour",prompt:ke,variant_scoped:!0})).image;ut!=null&&ut.storage_path&&Te.push({storage_path:ut.storage_path,signed_url:ut.signed_url})}return Te}async function no(se){if(!f)return null;
919const ke=await py(se),qe=(await K.listingDrafts.uploadImage(e,f.id,{filename:se.name,base64:ke,mime:se.type||"image/png",variant_scoped:!0})).image;return qe!=null&&qe.storage_path?{storage_path:qe.storage_path,signed_url:qe.signed_url}:null}async function bc(se){if(!f)return;const ke=(f.images??[]).filter((Te,qe)=>qe!==se);try{const{draft:Te}=await K.listingDrafts.patch(e,f.id,{images:ke});m(Te)}catch(Te){fe(Te instanceof Error?Te.message:String(Te))}}async function Ce(se,ke){if(f){Fe(`replace:${se}`),fe(null);try{const Te=await py(ke),{draft:qe}=await K.listingDrafts.uploadImage(e,f.id,{filename:ke.name,base64:Te,mime:ke.type||"image/png"}),ht=(qe.source_images??[])[((qe.source_images??[]).length||1)-1],ut=(ht==null?void 0:ht.storage_path)||(ht==null?void 0:ht.ref);if(!ut)throw new Error("Upload failed â please try again.");const{draft:ct}=await K.listingDrafts.generateImage(e,f.id,{source_ref:ut,mode:"original",replace_index:se});m(ct)}catch(Te){fe(Te instanceof Error?Te.message:String(Te))}finally{Fe(null)}}}function yr(se){var qe;if(!f)return;const ke={...((qe=f.attributes)==null?void 0:qe.productline_attributes)??{},brand:se},Te={...f.attributes??{},productline_attributes:ke};m({...f,attributes:Te}),It(K.listingDrafts.patch(e,f.id,{attributes:Te}))}async function Ua(se){if(se.trim().length<2){ee([]);return}try{const{brands:ke}=await K.listingDrafts.searchBrands(e,se.trim());ee(ke)}catch{ee([])}}async function Ci(se){if(T(se),se.trim().length<2){O([]);return}try{const{rows:ke}=await K.listingDrafts.searchCategories(e,se.trim());O(ke)}catch{O([])}}const or=(f==null?void 0:f.content)??{},vc=((Xf=(Zf=f==null?void 0:f.attributes)==null?void 0:Zf.productline_attributes)==null?void 0:Xf.brand)??"",ro=(f==null?void 0:f.attributes)??{},Su=ro._variant_mode==="multiple"?((Jf=ro._variants)==null?void 0:Jf.length)??0:0,wc=(f==null?void 0:f.warranty)??{},so=(f==null?void 0:f.package_dimensions)??{},za=ro.productline_attributes??{},Cu=ro.variant_attributes??{};p.useEffect(()=>{if(!f||d!==5||!je.find(Fr=>Fr.attribute_id==="volume.value"))return;const ke=`${f.id}:${String(or.title||"")}`;if(J.current===ke)return;const Te=za["volume.value"];if(Te!=null&&Te!==""){J.current=ke;return}const qe=je.find(Fr=>Fr.attribute_id==="volume.unit"),ht=rYe(String(or.title||""),(qe==null?void 0:qe.options)||[]);if(!ht)return;J.current=ke;const ut=f.attributes??{},ct={...ut.productline_attributes??{}};ct["volume.value"]=ht.value,(ct["volume.unit"]==null||ct["volume.unit"]==="")&&(ct["volume.unit"]=ht.unit);const ms={...ut,productline_attributes:ct};m({...f,attributes:ms}),It(K.listingDrafts.patch(e,f.id,{attributes:ms}))},[d,f==null?void 0:f.id,je,or.title,e]);const Eu=[];vc&&String(vc).trim()&&Eu.push(`Brand "${vc}" is set â Takealot rejects a branded listing unless an image clearly shows the brand printed on the product or its packaging. Add a branded image, or leave Brand blank for an unbranded product.`);{const se=String(or.title??"").toLowerCase();if(se){const ke=(ro._variants??[]).map(ht=>ht.attrs??{}),Te=new Set;for(const ht of[za,Cu,...ke])for(const[ut,ct]of Object.entries(ht))if(/compat|fits/i.test(ut))for(const ms of Array.isArray(ct)?ct:[ct])typeof ms=="string"&&ms.trim()&&Te.add(ms.trim());const qe=[...Te].filter(ht=>!sYe(se,ht));qe.length&&Eu.push(`This product is marked compatible with ${qe.slice(0,4).map(ht=>`"${ht}"`).join(", ")}${qe.length>4?"â¦":""}, but the title doesn't mention it. Takealot rejects accessory titles that don't indicate compatibility â add the compatible model(s) to the title.`)}}const Ww=Mv(je),Kw=Mv(he),Hw=$v(je),Vd=$v(he),Vw=!!(f!=null&&f.category_id),Qe=!!or.title&&!!or.description,kt=(f==null?void 0:f.source_images)??[],Ft=(f==null?void 0:f.images)??[],Wt=[];(!(f!=null&&f.category_id)||!(f!=null&&f.template_id))&&Wt.push("a category"),or.title||Wt.push("a title"),or.description||Wt.push("a description"),Ft.length===0&&Wt.push("at least one product image"),(!wc.type||wc.months==null)&&Wt.push("warranty (type + months)"),(so.height==null||so.length==null||so.width==null)&&Wt.push("package dimensions (height/length/width in cm)"),(f==null?void 0:f.package_weight)==null&&Wt.push("package weight (g)");const Or=Su>0?(ro._variants??[]).map(se=>({...Cu,...se.attrs??{}})):[Cu];Wt.push(...nYe({productAttributes:je,variantAttributes:he,productlineAttributes:za,variantAttributeSets:Or}));const Wa=tYe(eYe({productAttributes:je,variantAttributes:he,productlineAttributes:za,variantAttributeSets:Or}));{const se=iYe(f==null?void 0:f.category_path,or.title);se&&Wt.push(se)}const Ei=[];for(const se of Ft){const ke=String(se.storage_path||"");/^https?:\/\//i.test(ke)?Ei.push(`An image points at an external link â re-add it with "Use original" so it's hosted and sized for Takealot.`):/\.(webp|heic|gif|tiff|avif)$/i.test(ke)&&Ei.push(`An image isn't a JPG/PNG â re-add it with "Use original" to convert it.`)}const Au=[...new Set(Ei)],ya=s.jsx("div",{className:"mb-5 flex items-center gap-1.5 text-body-xs",children:UL.map((se,ke)=>{const Te=ke===0||!!f,qe=ke<d;return s.jsxs("button",{type:"button",disabled:!Te||ke>d,onClick:()=>h(ke),className:`flex items-center gap-1 rounded-full px-2.5 py-1 transition ${ke===d?"bg-intent-brand text-text-inverse":qe?"bg-intent-brandSubtle text-text-primary hover:bg-surface-subtle":"bg-surface text-text-secondary"} ${ke>d?"opacity-50":""}`,children:[qe?s.jsx(fn,{className:"h-3 w-3"}):s.jsx("span",{children:ke+1}),se]},se)})});function qs(se={}){return s.jsxs("div",{className:"mt-6 flex items-center justify-between",children:[s.jsxs("button",{type:"button",disabled:d===0||!!ze,onClick:()=>h(ke=>Math.max(0,ke-1)),className:"inline-flex items-center gap-1 rounded-md border border-outline-subtle px-3 py-1.5 text-body-sm text-text-secondary transition hover:bg-surface-subtle disabled:opacity-40",children:[s.jsx(ud,{className:"h-4 w-4"})," Back"]}),se.onNext?s.jsxs("button",{type:"button",disabled:se.canNext===!1||!!ze,onClick:se.onNext,className:"inline-flex items-center gap-1 rounded-md bg-intent-brand px-4 py-1.5 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover disabled:opacity-50",children:[se.nextLabel??"Next"," ",s.jsx(fr,{className:"h-4 w-4"})]}):null]})}return r==="loading"?s.jsx("div",{className:"grid flex-1 place-items-center bg-surface-subtle/30",children:s.jsx(_e,{className:"h-5 w-5 animate-spin text-text-secondary"})}):r==="drafts"?s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"mx-auto max-w-2xl px-4 py-6 md:px-6",children:[tt?s.jsx("div",{className:"mb-3 rounded-md border border-outline-error bg-surface-errorSubtle px-3 py-2 text-body-sm text-text-error",children:tt}):null,s.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[s.jsx("h2",{className:"text-body-md font-semibold text-text-primary",children:"Your draft listings"}),s.jsxs("button",{type:"button",onClick:en,className:"inline-flex items-center gap-2 rounded-md bg-intent-brand px-3.5 py-2 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover",children:[s.jsx(Ht,{className:"h-4 w-4"})," Start a new listing"]})]}),s.jsx("p",{className:"mb-4 text-body-sm text-text-secondary",children:"Pick up where you left off â drafts auto-save as you go."}),s.jsx("div",{className:"flex flex-col gap-2",children:i.map(se=>s.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-outline-subtle bg-surface px-4 py-3 shadow-xs",children:[s.jsxs("button",{type:"button",onClick:()=>Os(se.id),className:"min-w-0 flex-1 text-left",children:[s.jsx("div",{className:"truncate text-body-sm font-medium text-text-primary",children:IG
919(se)}),s.jsxs("div",{className:"mt-0.5 truncate text-body-xs text-text-secondary",children:[se.category_path?`${se.category_path} · `:"",UL[Ut(se)]," · edited ",Ao(se.updated_at)]})]}),s.jsx("button",{type:"button",onClick:()=>Os(se.id),className:"rounded-md border border-outline-subtle px-3 py-1.5 text-body-sm text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary",children:"Resume"}),s.jsx("button",{type:"button",title:"Discard draft",onClick:()=>{window.confirm("Discard this draft? This can't be undone.")&&Vs(se.id)},className:"rounded-md p-1.5 text-text-secondary transition hover:bg-surface-errorSubtle hover:text-text-error",children:s.jsx(Bn,{className:"h-4 w-4"})})]},se.id))})]})}):s.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:[s.jsxs("div",{className:"mx-auto max-w-2xl px-4 py-6 md:px-6",children:[s.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[s.jsxs("button",{type:"button",onClick:gr,className:"inline-flex items-center gap-1 rounded-md border border-outline-subtle px-2.5 py-1.5 text-body-sm text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary",children:[s.jsx(ud,{className:"h-4 w-4"})," Drafts"]}),s.jsxs("div",{className:"flex items-center gap-3 text-body-xs",children:[l?s.jsxs("span",{className:"inline-flex items-center gap-1 text-text-secondary",children:[s.jsx(_e,{className:"h-3 w-3 animate-spin"})," Savingâ¦"]}):f?s.jsxs("span",{className:"inline-flex items-center gap-1 text-text-secondary",children:[s.jsx(fn,{className:"h-3 w-3 text-intent-success"})," Saved"]}):null,f?s.jsx("button",{type:"button",onClick:()=>{window.confirm("Discard this draft? This can't be undone.")&&Vs(f.id)},className:"rounded-md px-2 py-1 text-text-secondary transition hover:bg-surface-errorSubtle hover:text-text-error",children:"Discard"}):null]})]}),ya,tt?s.jsx("div",{className:"mb-3 rounded-md border border-outline-error bg-surface-errorSubtle px-3 py-2 text-body-sm text-text-error",children:tt}):null,d===0?s.jsxs("div",{children:[s.jsx("h2",{className:"mb-1 text-body-md font-semibold text-text-primary",children:v==="bundle"?"Bundle existing items":"Tell me about the product"}),s.jsx("p",{className:"mb-3 text-body-sm text-text-secondary",children:v==="bundle"?"Pick products already in your catalogue. We'll prefill the listing from their titles, images and barcodes â then you walk the usual category â content â images flow.":"Describe it in your own words. Paste a reference link if you have one."}),s.jsxs("div",{className:"mb-4 inline-flex rounded-md border border-outline-subtle p-0.5",children:[s.jsx("button",{type:"button",onClick:()=>w("new"),className:`rounded px-3 py-1 text-body-sm ${v==="new"?"bg-surface-sunken font-medium text-text-primary":"text-text-secondary hover:text-text-primary"}`,children:"New product"}),s.jsx("button",{type:"button",onClick:()=>w("bundle"),className:`rounded px-3 py-1 text-body-sm ${v==="bundle"?"bg-surface-sunken font-medium text-text-primary":"text-text-secondary hover:text-text-primary"}`,children:"Bundle existing items"})]}),v==="bundle"?s.jsx("div",{className:"mb-4",children:s.jsx(VGe,{slug:e,selected:_,onChange:k})}):s.jsxs(s.Fragment,{children:[s.jsx("label",{className:"mb-1 block text-body-sm font-medium text-text-primary",children:"Product details"}),s.jsx("textarea",{value:x,onChange:se=>g(se.target.value),rows:6,placeholder:"e.g. Organic raw shea butter, 250g tub. Unrefined, cold-pressed, from Ghana. For dry skin, hairâ¦",className:"mb-4 block w-full rounded-md border border-outline bg-surface px-3 py-2 text-body-md text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus"}),s.jsx("label",{className:"mb-1 block text-body-sm font-medium text-text-primary",children:"Reference links (optional)"}),s.jsx("textarea",{value:y,onChange:se=>b(se.target.value),rows:2,placeholder:"Paste product URLs (one per line) â a Takealot link to a similar product works well",className:"block w-full rounded-md border border-outline bg-surface px-3 py-2 text-body-sm text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus"}),s.jsx("label",{className:"mb-1 mt-4 block text-body-sm font-medium text-text-primary",children:"Reference photo (optional)"}),s.jsx("p",{className:"mb-2 text-body-xs text-text-secondary",children:"Add a product photo and the title, subtitle and description will be written from what's actually in the image â not a generic guess."}),s.jsxs("div",{onDragOver:se=>{se.preventDefault(),Z(!0)},onDragLeave:()=>Z(!1),onDrop:se=>{se.preventDefault(),Z(!1);const ke=Array.from(se.dataTransfer.files??[]).find(Te=>Te.type.startsWith("image/"));ke&&H(ke)},className:`flex items-center gap-3 rounded-md border border-dashed px-3 py-2 transition ${F?"border-outline-brand bg-brand-500/5":"border-outline-subtle"}`,children:[s.jsxs("label",{className:"inline-flex cursor-pointer items-center gap-2 rounded-md border border-outline-subtle bg-surface px-3 py-1.5 text-body-sm text-text-primary transition hover:bg-surface-subtle",children:[s.jsx(ti,{className:"h-4 w-4"}
919),D?"Change photo":"Add photo",s.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:se=>{var ke;H(((ke=se.target.files)==null?void 0:ke[0])??null),se.target.value=""}})]}),D?null:s.jsx("span",{className:"text-body-xs text-text-secondary",children:"or drag & drop"}),D?s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-body-xs text-text-secondary",children:[D.name,s.jsx("button",{type:"button",onClick:()=>H(null),title:"Remove",className:"text-text-secondary hover:text-text-error",children:s.jsx(Bn,{className:"h-3.5 w-3.5"})})]}):null]}),s.jsx("label",{className:"mb-1 mt-3 block text-body-xs font-medium text-text-secondary",children:"or paste an image URL"}),s.jsx("input",{type:"text",inputMode:"url",autoComplete:"off",spellCheck:!1,value:Y,onChange:se=>M(se.target.value),placeholder:"https://â¦/product.jpg",className:"block w-full rounded-md border border-outline bg-surface px-3 py-1.5 text-body-sm text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus"})]}),s.jsx("div",{className:"mt-6 flex justify-end",children:s.jsxs("button",{type:"button",disabled:ze==="analyse"||(v==="bundle"?_.length<1:x.trim().length<5),onClick:Xn,className:"inline-flex items-center gap-2 rounded-md bg-intent-brand px-4 py-2 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover disabled:cursor-not-allowed disabled:opacity-50",children:[ze==="analyse"?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):s.jsx(Ht,{className:"h-4 w-4"}),"Analyse & continue"]})})]}):null,d===1?s.jsxs("div",{children:[s.jsx("h3",{className:"mb-2 text-body-sm font-semibold text-text-primary",children:"Pick a category"}),E?null:s.jsx("div",{className:"mb-2 rounded-md border border-outline-warning bg-surface-warningSubtle px-3 py-1.5 text-body-xs text-text-primary",children:"No strong automatic match â pick the closest below, or search manually."}),s.jsx("div",{className:"mb-1 text-body-xs font-medium text-text-secondary",children:"AI suggestions"}),s.jsxs("div",{className:"max-h-56 overflow-y-auto rounded-md border border-outline-subtle",children:[j.map(se=>s.jsx(zL,{path:se.path,department:se.department,selected:(f==null?void 0:f.category_id)===se.category_id&&(f==null?void 0:f.template_id)===se.template_id,onPick:()=>vt({category_id:se.category_id,template_id:se.template_id,category_path:se.path})},`${se.category_id}:${se.template_id}`)),j.length===0?s.jsx("div",{className:"px-3 py-3 text-body-sm text-text-secondary",children:"No suggestions â search below."}):null]}),s.jsx("div",{className:"mb-1 mt-4 text-body-xs font-medium text-text-secondary",children:"Or search categories"}),s.jsx("input",{type:"text",value:C,onChange:se=>Ci(se.target.value),placeholder:"Type to search (e.g. moisturiser, earbuds, gift set)",className:oo}),S.length>0?s.jsx("div",{className:"mt-1 max-h-56 overflow-y-auto rounded-md border border-outline-subtle",children:S.map(se=>s.jsx(zL,{path:se.path,department:se.department,selected:(f==null?void 0:f.category_id)===se.category_id&&(f==null?void 0:f.template_id)===se.template_id,onPick:()=>vt({category_id:se.category_id,template_id:se.template_id,category_path:se.path})},`${se.category_id}:${se.template_id}`))}):null,f!=null&&f.category_path?s.jsxs("div",{className:"mt-3 text-body-sm text-text-primary",children:["Selected: ",s.jsx("span",{className:"font-medium",children:f.category_path})]}):null,qs({canNext:Vw,onNext:()=>h(2)})]}):null,d===2?s.jsxs("div",{children:[s.jsxs("div",{className:"mb-4",children:[s.jsx("label",{className:"mb-1 block text-body-sm font-medium text-text-primary",children:"Brand"}),s.jsx("input",{type:"text",value:vc,onChange:se=>{yr(se.target.value),Ua(se.target.value)},placeholder:"Your brand (e.g. NIVEA) â type to search, or enter a new one",className:oo}),me.length>0?s.jsx("div",{className:"mt-1 max-h-40 overflow-y-auto rounded-md border border-outline-subtle",children:me.map(se=>s.jsx("button",{type:"button",onClick:()=>{yr(se.brand_name),ee([])},className:"block w-full border-b border-outline-subtle px-3 py-1.5 text-left text-body-sm text-text-body transition last:border-0 hover:bg-surface-subtle",children:se.brand_name},se.brand_id))}
919):null,s.jsx("p",{className:"mt-1 text-body-xs text-text-secondary",children:'New brands are accepted by Takealot with review â enter "Generic" if unbranded.'}),s.jsxs("label",{className:"mt-2 flex w-fit items-center gap-2 text-body-sm text-text-body",children:[s.jsx("input",{type:"checkbox",checked:ne,onChange:se=>X(se.target.checked),className:"rounded border-outline text-intent-brand focus-visible:shadow-focus"}),"Add brand to title"]})]}),s.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[s.jsx("h3",{className:"text-body-sm font-semibold text-text-primary",children:"Listing content"}),s.jsxs("button",{type:"button",disabled:!!ze,onClick:()=>le("all"),className:"inline-flex items-center gap-1.5 rounded-md bg-intent-brand px-3 py-1.5 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover disabled:opacity-50",children:[ze==="gen:all"?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):s.jsx(Ht,{className:"h-3.5 w-3.5"}),"Generate all"]})]}),s.jsx("div",{className:"flex flex-col gap-3",children:gYe.map(se=>{const ke=(or==null?void 0:or[se.key])??"",Te=ze===`gen:${se.key}`||ze==="gen:all";return s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface p-3 shadow-xs",children:[s.jsxs("div",{className:"mb-1.5 flex items-center justify-between",children:[s.jsx("label",{className:"text-body-sm font-medium text-text-primary",children:se.label}),s.jsxs("button",{type:"button",disabled:!!ze,onClick:()=>le(se.key),className:"inline-flex items-center gap-1 rounded-md border border-outline-subtle px-2 py-1 text-body-xs text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary disabled:opacity-50",children:[Te?s.jsx(_e,{className:"h-3 w-3 animate-spin"}):s.jsx(pa,{className:"h-3 w-3"}),ke?"Rerun":"Generate"]})]}),se.long?s.jsxs(s.Fragment,{children:[s.jsx("textarea",{value:ke,onChange:qe=>vt({content:{...or,[se.key]:qe.target.value}}),rows:5,className:"block w-full rounded-md border border-outline bg-surface px-3 py-2 text-body-sm text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus"}),se.key==="description"&&xYe(ke)?s.jsxs("div",{className:"mt-2 rounded-md border border-outline-subtle bg-surface-subtle px-3 py-2",children:[s.jsx("div",{className:"text-body-xs font-medium text-text-secondary",children:"How this reads on Takealot"}),s.jsx("div",{className:"mt-1 whitespace-pre-line text-body-sm text-text-primary",children:BL(ke)}),s.jsxs("div",{className:"mt-2 text-body-xs text-text-secondary",children:["The ",s.jsx("code",{children:"<p>"})," / ",s.jsx("code",{children:"<li>"})," tags above are intentional and correct â Takealot rejects line breaks in the description, so the tags are what split it into sections on the product page. Leave them in."]})]}):null]}):s.jsx("input",{type:"text",value:ke,onChange:qe=>vt({content:{...or,[se.key]:qe.target.value}}),className:"block w-full rounded-md border border-outline bg-surface px-3 py-1.5 text-body-sm text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus"})]},se.key)})}),qs({canNext:Qe,onNext:()=>h(3)})]}):null,d===3&&f?s.jsxs("div",{children:[s.jsx("h3",{className:"mb-2 text-body-sm font-semibold text-text-primary",children:"Product images"}),s.jsx("p",{className:"mb-3 text-body-xs text-text-secondary",children:"Upload a product photo or paste an image URL, then use it as-is or generate clean angle / lifestyle shots (~10â30s each). At least one listing image is required to submit."}),s.jsxs("div",{onDragOver:se=>{se.preventDefault(),ze||Z(!0)},onDragLeave:()=>Z(!1),onDrop:se=>{if(se.preventDefault(),Z(!1),ze)return;const ke=Array.from(se.dataTransfer.files??[]).find(Te=>Te.type.startsWith("image/"));ke&&Ge(ke)},className:`mb-4 flex flex-col items-center gap-2 rounded-md border border-dashed px-3 py-4 text-center transition ${F?"border-outline-brand bg-brand-500/5":"border-outline-subtle"}`,children:[s.jsxs("label",{className:"inline-flex cursor-pointer items-center gap-2 rounded-md border border-outline-subtle bg-surface px-3 py-1.5 text-body-sm text-text-primary transition hover:bg-surface-subtle",children:[s.jsx(ti,{className:"h-4 w-4"}
919),ze==="upload"?"Uploadingâ¦":"Upload photo",s.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:!!ze,onChange:se=>{var Te;const ke=(Te=se.target.files)==null?void 0:Te[0];ke&&Ge(ke),se.target.value=""}})]}),s.jsx("span",{className:"text-body-xs text-text-secondary",children:"or drag & drop an image here"}),s.jsx("span",{className:"text-body-xs text-text-tertiary",children:"or paste a public image URL"}),s.jsx(qGe,{disabled:!!ze,busy:ze==="upload",onAdd:ye})]}),kt.length>0?s.jsxs("div",{className:"mb-4",children:[s.jsxs("div",{className:"mb-1.5 flex flex-wrap items-center justify-between gap-2",children:[s.jsx("span",{className:"text-body-xs font-medium text-text-secondary",children:"Your photos"}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsxs("button",{type:"button",disabled:!!ze,onClick:()=>Ke(),className:Uo,title:"Generate your saved set of shots from your main photo â edit the recipe in Settings â Listing image preset",children:[ze==="preset"?s.jsx(_e,{className:"h-3 w-3 animate-spin"}):s.jsx(Ht,{className:"h-3 w-3"})," Generate from preset"]}),kt.length>1?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"self-center text-body-xs text-text-tertiary",children:"· all as:"}),s.jsxs("button",{type:"button",disabled:!!ze,onClick:()=>xe("original"),className:Uo,children:[ze==="imgall:original"?s.jsx(_e,{className:"h-3 w-3 animate-spin"}):null," Originals"]}),s.jsxs("button",{type:"button",disabled:!!ze,onClick:()=>xe("angle"),className:Uo,children:[ze==="imgall:angle"?s.jsx(_e,{className:"h-3 w-3 animate-spin"}):null," Angle"]}),s.jsxs("button",{type:"button",disabled:!!ze,onClick:()=>xe("lifestyle"),className:Uo,children:[ze==="imgall:lifestyle"?s.jsx(_e,{className:"h-3 w-3 animate-spin"}):null," Lifestyle"]})]}):null]})]}),s.jsx("div",{className:"flex flex-col gap-3",children:kt.map((se,ke)=>{const Te=se.ref||se.storage_path||"",qe=se.signed_url||se.url||"",ht=R[Te]??"";return s.jsxs("div",{className:"flex gap-3 rounded-lg border border-outline-subtle bg-surface p-2 shadow-xs",children:[qe?s.jsxs("div",{className:"relative h-28 w-28 shrink-0",children:[s.jsx("img",{src:qe,alt:"",onClick:()=>qe&&q(qe),className:"h-28 w-28 cursor-zoom-in rounded bg-surface-subtle object-contain"}),s.jsx("button",{type:"button",onClick:()=>St(ke),title:"Remove this photo",disabled:!!ze,className:"absolute -right-1.5 -top-1.5 inline-flex h-5 w-5 items-center justify-center rounded-full border border-outline-subtle bg-surface text-text-secondary shadow-xs transition hover:text-text-error disabled:opacity-50",children:s.jsx(Bn,{className:"h-3 w-3"})})]}):null,s.jsxs("div",{className:"flex flex-1 flex-col gap-2",children:[s.jsx("input",{type:"text",value:ht,onChange:ut=>I(ct=>({...ct,[Te]:ut.target.value})),placeholder:"Describe the shot â e.g. top-down on marble, held in hand, on a bathroom shelf with candles",className:"block w-full rounded-md border border-outline bg-surface px-3 py-1.5 text-body-xs text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus"}),s.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[s.jsxs("button",{type:"button",disabled:!!ze||!Te,onClick:()=>Ke(Te,`img:${Te}:preset`),className:Uo,title:"Run your saved preset (Settings â Listing image preset) from this photo",children:[ze===`img:${Te}:preset`?s.jsx(_e,{className:"h-3 w-3 animate-spin"}):s.jsx(Ht,{className:"h-3 w-3"})," Preset"]}),s.jsxs("button",{type:"button",disabled:!!ze||!Te,onClick:()=>ie(Te,"original"),className:Uo,children:[ze===`img:${Te}:original`?s.jsx(_e,{className:"h-3 w-3 animate-spin"}):null," Use original"]}),s.jsxs("button",{type:"button",disabled:!!ze||!Te,onClick:()=>ie(Te,"angle",ht),className:Uo,children:[ze===`img:${Te}:angle`?s.jsx(_e,{className:"h-3 w-3 animate-spin"}):null," Angle shot"]}),s.jsxs("button",{type:"button",disabled:!!ze||!Te,onClick:()=>ie(Te,"lifestyle",ht),className:Uo,children:[ze===`img:${Te}:lifestyle`?s.jsx(_e,{className:"h-3 w-3 animate-spin"}):null," Lifestyle shot"]}),s.jsxs("button",{type:"button",disabled:!!ze||!Te,onClick:()=>ie(Te,ht.trim()?"angle":"cutout",ht.trim()||void 0,`img:${Te}:cutout`),className:Uo,title:ht.trim()?"Regenerate on a clean white background, steered by your text above":"Lift the product out of its packaging onto a clean white background. Add text above to steer the regenerate.",children:[ze===`img:${Te}:cutout`?s.jsx(_e,{className:"h-3 w-3 animate-spin"}):null," White background"]}
919),s.jsxs("button",{type:"button",disabled:!!ze||!Te,title:"Add a measurements image with length / height / width callouts",onClick:()=>{const ut=(f==null?void 0:f.package_dimensions)??{};re({length:ut.length!=null?String(ut.length):"",height:ut.height!=null?String(ut.height):"",width:ut.width!=null?String(ut.width):""}),G(z===Te?null:Te)},className:Uo,children:[ze===`img:${Te}:dimensions`?s.jsx(_e,{className:"h-3 w-3 animate-spin"}):null," Dimensions"]})]}),z===Te?s.jsxs("div",{className:"flex flex-wrap items-end gap-2 rounded-md border border-outline-subtle bg-surface-subtle p-2",children:[["length","height","width"].map(ut=>s.jsxs("label",{className:"text-body-xs capitalize text-text-secondary",children:[ut," (cm)",s.jsx("input",{type:"number",value:te[ut],onChange:ct=>re(ms=>({...ms,[ut]:ct.target.value})),className:"mt-0.5 block w-20 rounded-md border border-outline bg-surface px-2 py-1 text-body-xs text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus"})]},ut)),s.jsx("button",{type:"button",disabled:!!ze||!Te,onClick:()=>pe(Te,te),className:"rounded-md bg-intent-brand px-3 py-1.5 text-body-xs font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover disabled:opacity-50",children:"Generate dimensions image"})]}
919):null,s.jsxs("p",{className:"text-body-xs text-text-tertiary",children:[s.jsx("span",{className:"font-medium",children:"Angle"}),' = camera perspective (e.g. "3/4 front", "top-down", "back"). ',s.jsx("span",{className:"font-medium",children:"Lifestyle"})," = scene/setting. ",s.jsx("span",{className:"font-medium",children:"White background"}),' = product on clean white (add text above to steer the regenerate â e.g. "keep the label sharp"; leave it blank for a quick cut-out). ',s.jsx("span",{className:"font-medium",children:"Dimensions"})," = product with measurement callouts. Different text â different image."]})]})]},ke)})})]}):null,Ft.length>0?s.jsxs("div",{children:[s.jsxs("div",{className:"mb-1.5 text-body-xs font-medium text-text-secondary",children:["Listing images (",Ft.length,") â drag to reorder, click to enlarge"]}),s.jsx("div",{className:"flex flex-wrap gap-3",children:Ft.map((se,ke)=>{const Te=se.signed_url||se.url||"";return s.jsxs("div",{draggable:!ze,onDragStart:()=>P(ke),onDragOver:qe=>qe.preventDefault(),onDrop:qe=>{const ht=Array.from(qe.dataTransfer.files??[]).find(ut=>ut.type.startsWith("image/"));if(ht){qe.preventDefault(),ze||Ce(ke,ht),P(null);return}$!==null&&$!==ke&&Jt($,ke),P(null)},onDragEnd:()=>P(null),className:`relative h-24 w-24 ${$===ke?"opacity-40":""}`,children:[s.jsx("img",{src:Te||void 0,alt:"",onClick:()=>Te&&q(Te),title:"Drag to reorder",className:"h-24 w-24 cursor-grab rounded border border-outline-subtle bg-surface-subtle object-contain active:cursor-grabbing"}),s.jsx("button",{type:"button",onClick:()=>bc(ke),title:"Remove",disabled:!!ze,className:"absolute -right-1.5 -top-1.5 inline-flex h-5 w-5 items-center justify-center rounded-full border border-outline-subtle bg-surface text-text-secondary shadow-xs transition hover:text-text-error disabled:opacity-50",children:s.jsx(Bn,{className:"h-3 w-3"})}),s.jsxs("label",{title:"Replace",className:"absolute bottom-1 right-1 inline-flex cursor-pointer items-center justify-center rounded bg-surface/90 px-1 py-0.5 text-text-secondary shadow-xs transition hover:text-text-primary",children:[ze===`replace:${ke}`?s.jsx(_e,{className:"h-3 w-3 animate-spin"}):s.jsx(ti,{className:"h-3 w-3"}),s.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:!!ze,onChange:qe=>{var ut;const ht=(ut=qe.target.files)==null?void 0:ut[0];ht&&Ce(ke,ht),qe.target.value=""}})]})]},ke)})})]}):null,qs({canNext:!0,onNext:()=>h(4)})]}):null,d===4&&f?s.jsxs(s.Fragment,{children:[s.jsx(HGe,{variantAttributes:he,poolImages:Ft,initialMode:((Xx=f.attributes)==null?void 0:Xx._variant_mode)??"single",initialVariants:((Jx=f.attributes)==null?void 0:Jx._variants)??[],onSave:Xe,recolourImages:yn,uploadVariantImage:no,variantImageUrls:f.variant_image_urls}),qs({canNext:!0,onNext:()=>h(5)})]}):null,d===5&&f?s.jsxs("div",{children:[s.jsx("h3",{className:"mb-2 text-body-sm font-semibold text-text-primary",children:"Commercial details"}),Su===0?s.jsxs("div",{className:"mb-4 grid grid-cols-3 gap-3",children:[s.jsx(Sl,{label:"SKU",children:s.jsx("input",{className:oo,value:f.sku??"",onChange:se=>vt({sku:se.target.value})})}),s.jsx(Sl,{label:"Barcode",children:s.jsx("input",{className:oo,value:f.barcode??"",onChange:se=>vt({barcode:se.target.value})})}),s.jsx(Sl,{label:"Selling price (R)",children:s.jsx("input",{type:"number",className:oo,value:f.selling_price??"",onChange:se=>vt({selling_price:se.target.value===""?null:Number(se.target.value)})})})]}):s.jsx("p",{className:"mb-4 text-body-xs text-text-secondary",children:"SKU, barcode and price are set per variant in the Variants step."}),s.jsx("div",{className:"mb-1.5 text-body-xs font-medium text-text-secondary",children:"Warranty"}),s.jsxs("div",{className:"mb-4 grid grid-cols-2 gap-3",children:[s.jsx(Sl,{label:"Type",children:s.jsxs("select",{className:oo,value:wc.type??"Limited",onChange:se=>vt({warranty:{...wc,type:se.target.value}}),children:[s.jsx("option",{children:"Limited"}),s.jsx("option",{children:"Full"}),s.jsx("option",{children:"Lifetime"})]})}),s.jsx(Sl,{label:"Months",children:s.jsx("input",{type:"number",className:o
919o,value:wc.months??"",onChange:se=>vt({warranty:{...wc,months:se.target.value===""?null:Math.round(Number(se.target.value))}})})})]}),s.jsx("div",{className:"mb-1.5 text-body-xs font-medium text-text-secondary",children:"Package (for shipping)"}),s.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[s.jsx(Sl,{label:"Height (cm)",children:s.jsx("input",{type:"number",className:oo,value:so.height??"",onChange:se=>vt({package_dimensions:{...so,height:se.target.value===""?null:Number(se.target.value)}})})}),s.jsx(Sl,{label:"Length (cm)",children:s.jsx("input",{type:"number",className:oo,value:so.length??"",onChange:se=>vt({package_dimensions:{...so,length:se.target.value===""?null:Number(se.target.value)}})})}),s.jsx(Sl,{label:"Width (cm)",children:s.jsx("input",{type:"number",className:oo,value:so.width??"",onChange:se=>vt({package_dimensions:{...so,width:se.target.value===""?null:Number(se.target.value)}})})}),s.jsx(Sl,{label:"Weight (g)",children:s.jsx("input",{type:"number",className:oo,value:f.package_weight??"",onChange:se=>vt({package_weight:se.target.value===""?null:Number(se.target.value)})})})]}),s.jsx(cYe,{reqProductAttrs:Ww,reqVariantAttrs:Kw,optProductAttrs:Hw,optVariantAttrs:Vd,variantCount:Su,pAttrs:za,vAttrs:Cu,busy:ze,onAutoFill:ve,onSetAttr:Me}),qs({canNext:!0,onNext:()=>h(6)})]}):null,d===6&&f?s.jsxs("div",{children:[s.jsx("h3",{className:"mb-2 text-body-sm font-semibold text-text-primary",children:"Review"}),s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface p-4 shadow-xs",children:[s.jsx($u,{label:"Category",value:f.category_path??"â"}),s.jsx($u,{label:"Brand",value:vc||"â"}),s.jsx($u,{label:"Variants",value:Su>0?`${Su} variants`:"Single product"}),s.jsx($u,{label:"Title",value:or.title??"â"}),s.jsx($u,{label:"Subtitle",value:or.subtitle??"â"}),s.jsx($u,{label:"What's in the box",value:or.whats_in_the_box??"â"}),s.jsx($u,{label:"SKU / price",value:`${f.sku??"â"} · ${f.selling_price!=null?"R"+f.selling_price:"â"}`}),s.jsx("div",{className:"mt-2 whitespace-pre-line text-body-xs text-text-secondary line-clamp-3",children:BL(or.description)})]}),Wt.length>0&&!U?s.jsxs("div",{className:"mt-3 rounded-md border border-outline-warning bg-surface-warningSubtle px-3 py-2 text-body-xs text-text-primary",children:[s.jsx("div",{className:"mb-1 font-medium",children:"Still needed before submitting"}),s.jsx("ul",{className:"list-inside list-disc space-y-1",children:Wt.map((se,ke)=>s.jsx("li",{children:se},ke))})]}):null,Wa&&!U?s.jsxs("div",{className:"mt-3 rounded-md border border-outline-warning bg-surface-warningSubtle px-3 py-2 text-body-xs text-text-primary",children:[s.jsx("div",{className:"mb-1 font-medium",children:"Listing quality will land at Moderate, not Excellent"}),s.jsx("p",{children:Wa}),s.jsx("div",{className:"mt-1 text-text-secondary",children:"Won't block your submission â fill them on Details if you can."})]}):null,Au.length>0&&!U?s.jsxs("div",{className:"mt-3 rounded-md border border-outline-warning bg-surface-warningSubtle px-3 py-2 text-body-xs text-text-primary",children:[s.jsx("div",{className:"mb-1 font-medium",children:"Check these images"}),s.jsx("ul",{className:"list-inside list-disc space-y-1",children:Au.map((se,ke)=>s.jsx("li",{children:se},ke))})]}):null,Eu.length>0&&!U?s.jsxs("div",{className:"mt-3 rounded-md border border-outline-warning bg-surface-warningSubtle px-3 py-2 text-body-xs text-text-primary",children:[s.jsx("div",{className:"mb-1 font-medium",children:"Before you submit"}),s.jsx("ul",{className:"list-inside list-disc space-y-1",children:Eu.map((se,ke)=>s.jsx("li",{children:se},ke))}),s.jsx("div",{className:"mt-1 text-text-secondary",children:"Common reasons Takealot rejects listings at review â these won't block your submission."})]}):null,U?s.jsxs("div",{className:`mt-3 rounded-md border px-3 py-2 text-body-sm ${U.ok?"border-outline-success bg-surface-successSubtle text-text-success":"border-outline-warning bg-surface-warningSubtle text-text-primary"}`,children:[U.ok?U.is_draft?`Saved as a Takealot draft (${U.takealot_submission_id??"tracking"}). Send it for review from Submitted listings.`:`Submitted to Takealot â (${U.takealot_submission_id??"tracking"})`:U.message||U.error||"Submission could not be completed.",(Qx=U.details)!=null&&Qx.length?s.jsx("ul",{className:"mt-1 list-inside list-disc text-body-xs",children:U.details.slice(0,6).map((se,ke)=>s.jsx("li",{children:se},ke))}):null]}
919):null,s.jsxs("div",{className:"mt-3 rounded-md border border-outline-subtle bg-surface-subtle px-3 py-2.5",children:[s.jsxs("div",{className:"mb-1.5 flex items-center gap-1.5 text-body-sm font-medium text-text-primary",children:[s.jsx(Ht,{className:"h-4 w-4 text-intent-brand"})," Got a rejection from Takealot? Fix it with AI"]}),s.jsx("p",{className:"mb-2 text-body-xs text-text-secondary",children:"Paste the rejection reason from the Seller Portal. The AI fixes what it can on this draft (title, description, attributes, SKUâ¦) â review the changes, then submit again. Nothing is sent to Takealot until you press Submit."}),s.jsx("textarea",{value:ue,onChange:se=>Ee(se.target.value),rows:3,placeholder:"e.g. Title must be in Title Case; Description is too short; attribute 'Device Storage Capacity' is requiredâ¦",className:"block w-full rounded-md border border-outline bg-surface px-3 py-1.5 text-body-xs text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus"}),s.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[s.jsxs("button",{type:"button",disabled:!!ze||!ue.trim()&&!U,onClick:Ie,className:"inline-flex items-center gap-1.5 rounded-md border border-outline bg-surface px-3 py-1.5 text-body-xs font-medium text-text-primary shadow-xs transition hover:bg-surface-subtle disabled:opacity-50",children:[ze==="autofix"?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):s.jsx(Ht,{className:"h-3.5 w-3.5"})," Fix with AI"]}),s.jsx("span",{className:"text-body-xs text-text-tertiary",children:U&&!U.ok?"Will also use the rejection above.":"Tip: you can also paste from the Seller Portal."})]}),bt?s.jsxs("div",{className:"mt-2 rounded-md border border-outline-subtle bg-surface px-3 py-2 text-body-xs",children:[bt.applied.length?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"font-medium text-text-success",children:["Applied ",bt.applied.length," fix(es) â review above, then Submit:"]}),s.jsx("ul",{className:"mt-1 list-inside list-disc text-text-primary",children:bt.applied.map((se,ke)=>s.jsx("li",{children:se},ke))})]}):s.jsx("div",{className:"text-text-secondary",children:"No automatic changes were applied."}),bt.unfixable.length?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mt-1.5 font-medium text-text-primary",children:"Needs your attention:"}),s.jsx("ul",{className:"mt-1 list-inside list-disc text-text-secondary",children:bt.unfixable.map((se,ke)=>s.jsx("li",{children:se},ke))})]}):null]}):null]}),s.jsxs("div",{className:"mt-6 flex items-center justify-between",children:[s.jsxs("button",{type:"button",disabled:!!ze,onClick:()=>h(5),className:"inline-flex items-center gap-1 rounded-md border border-outline-subtle px-3 py-1.5 text-body-sm text-text-secondary transition hover:bg-surface-subtle disabled:opacity-40",children:[s.jsx(ud,{className:"h-4 w-4"})," Back"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",disabled:!!ze||(U==null?void 0:U.ok)===!0||f.status==="submitted"||(U==null?void 0:U.error)==="unconfirmed"||Wt.length>0,onClick:()=>De(!0),className:"inline-flex items-center gap-2 rounded-md border border-outline-subtle px-3 py-2 text-body-sm text-text-secondary transition hover:bg-surface-subtle disabled:opacity-50",children:[ze==="draft"?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):null,"Save as Takealot draft"]}),s.jsxs("button",{type:"button",disabled:!!ze||(U==null?void 0:U.ok)===!0||f.status==="submitted"||(U==null?void 0:U.error)==="unconfirmed"||Wt.length>0,onClick:()=>De(!1),className:"inline-flex items-center gap-2 rounded-md bg-intent-brand px-4 py-2 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover disabled:opacity-50",children:[ze==="submit"?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):s.jsx(fn,{className:"h-4 w-4"}),(U==null?void 0:U.error)==="unconfirmed"?"Waiting for Takealot":U!=null&&U.is_draft?"Saved as draft":U!=null&&U.ok||f.status==="submitted"?"Submitted":"Submit to Takealot"]})]})]})]}):null]}),L?s.jsxs("div",{className:"fixed inset-0 z-modal flex items-center justify-center bg-black/70 p-6",onClick:()=>q(null),children:[s.jsx("img",{src:L,alt:"",onClick:se=>se.stopPropagation(),className:"max-h-full max-w-full rounded-lg shadow-xl"}),s.jsx("button",{type:"button",onClick:()=>q(null),className:"absolute right-4 top-4 inline-flex h-9 w-9 items-center justify-center rounded-full bg-surface/90 text-text-primary shadow-xs transition hover:bg-surface",children:s.jsx(Bn,{className:"h-5 w-5"})})]}):null]})}function py(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const a=String(r.result),i=a.indexOf(",");t(i>=0?a.slice(i+1):a)},r.onerror=()=>
919n(r.error),r.readAsDataURL(e)})}const oo="block w-full rounded-md border border-outline bg-surface px-3 py-1.5 text-body-sm text-text-primary shadow-xs focus-visible:outline-none focus-visible:shadow-focus",Uo="inline-flex items-center gap-1 rounded border border-outline-subtle px-2 py-1 text-body-xs text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary disabled:opacity-50";function IG(e){var r,a,i;const t=(a=(r=e.content)==null?void 0:r.title)==null?void 0:a.trim();if(t)return t;const n=(i=e.details)==null?void 0:i.trim();return n?n.length>60?`${n.slice(0,60)}â¦`:n:"Untitled draft"}function Ao(e){const t=Math.round((Date.now()-new Date(e).getTime())/6e4);if(t<1)return"just now";if(t<60)return`${t}m ago`;const n=Math.round(t/60);return n<24?`${n}h ago`:`${Math.round(n/24)}d ago`}function Sl({label:e,children:t}){return s.jsxs("div",{children:[s.jsx("label",{className:"mb-1 block text-body-xs font-medium text-text-secondary",children:e}),t]})}function $u({label:e,value:t}){return s.jsxs("div",{className:"flex gap-2 border-b border-outline-subtle py-1.5 text-body-sm last:border-0",children:[s.jsx("span",{className:"w-32 shrink-0 text-text-secondary",children:e}),s.jsx("span",{className:"text-text-primary",children:t})]})}function zL({path:e,department:t,selected:n,onPick:r}){return s.jsxs("button",{type:"button",onClick:r,className:`flex w-full items-center justify-between gap-2 border-b border-outline-subtle px-3 py-2 text-left text-body-sm transition last:border-0 ${n?"bg-intent-brandSubtle":"bg-surface hover:bg-surface-subtle"}`,children:[s.jsx("span",{className:"min-w-0 truncate text-text-body",children:e}),s.jsxs("span",{className:"flex shrink-0 items-center gap-2",children:[t?s.jsx("span",{className:"rounded-full bg-surface-subtle px-2 py-0.5 text-body-xs text-text-secondary",children:t}):null,n?s.jsx(fn,{className:"h-4 w-4 text-intent-brand"}):null]})]})}function Hf(e){var t;return((t=e.marketplaces)==null?void 0:t[0])??"takealot"}const Fc=Nq.filter(e=>{var t;return(t=e.surfaces)==null?void 0:t.includes("sops")});function n2(e){var t;return((t=Fc.find(n=>n.id===e))==null?void 0:t.label)??e}function PG(e,t){if(!t)return null;const n=t.context??{},r=(a,i,o)=>a===1?i:o;switch(e){case"stock-cover":{const a=n.understocked??0,i=n.cover_days??21;return`${a} ${r(a,"SKU has","SKUs have")} under ${i} days of cover at Takealot's DCs â stock you already own, waiting to be shipped in.`}case"supplier-order":{const a=n.low_cover_skus??0,i=n.cover_days??30;return`${a} ${r(a,"SKU is","SKUs are")} under ${i} days of cover across the DCs and your own warehouse combined â shipping won't fix these, they need reordering.`}case"promotion-builder":{const a=n.joinable??0;return`${a} ${r(a,"promotion is","promotions are")} open on Takealot right now, and you're not in any of them.`}case"listing-upgrades":{const a=n.weak??0,i=n.quality_ceiling??1;return`${a} buyable ${r(a,"listing scores","listings score")} ${i} or below on Takealot's own 0â3 quality scale â the ones shoppers are least likely to find.`}case"listing-creation":{const a=n.unlisted??0;return`${a} ${r(a,"product in your catalogue has","products in your catalogue have")} no marketplace listing yet.`}case"stock-recon":return n.last_filed_at?`This month's stock recon claim hasn't been filed. You last filed one ${Ao(n.last_filed_at)}.`:"This month's stock recon claim hasn't been filed yet.";default:return t.message}}const Em=Fc.find(e=>e.mode==="builder")??null,wj="gadjet:sops:lastSeller",bYe=e=>e==="procedures"||e==="listings"||e==="runs"||e==="claims"||e==="approvals";function vYe(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const a=String(r.result),i=a.indexOf(",");t(i>=0?a.slice(i+1):a)},r.onerror=()=>
919n(r.error),r.readAsDataURL(e)})}function wYe(){const e=Rt(),[t,n]=ki(),[r,a]=p.useState([]),[i,o]=p.useState(()=>t.get("seller")||""),[l,c]=p.useState(null),[u,d]=p.useState(null),[h,f]=p.useState(null),[m,x]=p.useState(null),[g,y]=p.useState([]),[b,v]=p.useState([]),[w,_]=p.useState([]),[k,j]=p.useState([]),[N,E]=p.useState({}),[A,C]=p.useState(()=>t.get("marketplace")||"all"),[T,S]=p.useState(null),[O,R]=p.useState([]),[I,$]=p.useState(null),[P,F]=p.useState(0),[Z,D]=p.useState([]),[H,Y]=it("tab","procedures"),M=bYe(H)?H:"procedures",[z,G]=it("claim",""),te=z||null,re=p.useRef(new Set);function L(U){o(U),typeof window<"u"&&localStorage.setItem(wj,U),n(ce=>{const ue=new URLSearchParams(ce);return ue.set("seller",U),ue},{replace:!0})}function q(U){Y(U)}function me(U){C(U),n(ce=>{const ue=new URLSearchParams(ce);return U==="all"?ue.delete("marketplace"):ue.set("marketplace",U),ue},{replace:!0})}function ee(U,ce){U&&($(null),d(ce??null),c(U))}p.useEffect(()=>{K.sellers().then(U=>{var Ee;a(U);const ce=typeof window<"u"?localStorage.getItem(wj):null,ue=[t.get("seller"),i,ce].find(bt=>bt&&U.some(Ze=>Ze.slug===bt))||((Ee=U[0])==null?void 0:Ee.slug)||"";ue&&L(ue)}).catch(U=>S(String((U==null?void 0:U.message)||U)))},[]),p.useEffect(()=>{const U=t.get("sop");if(!U||!i||l)return;const ce=Fc.find(ue=>ue.id===U);ce&&(ee(ce),n(ue=>{const Ee=new URLSearchParams(ue);return Ee.delete("sop"),Ee},{replace:!0}))},[t,i,l]),p.useEffect(()=>{const U=t.get("seller");U&&U!==i&&r.some(ce=>ce.slug===U)&&(o(U),typeof window<"u"&&localStorage.setItem(wj,U))},[t,r,i]),p.useEffect(()=>{i&&K.sops.listRuns(i).then(U=>y(U.runs)).catch(()=>y([]))},[i,h,m]),p.useEffect(()=>{if(!i){v([]);return}K.stockReconClaims.list(i).then(U=>v(U.claims)).catch(()=>v([]))},[i,m]),p.useEffect(()=>{if(!i){_([]),j([]);return}K.promotionDrafts.list(i).then(U=>_(U.drafts)).catch(()=>_([])),K.experiments.listApprovals(i).then(U=>j(U.approvals)).catch(()=>j([]))},[i,m,M]),p.useEffect(()=>{if(!i){E({});return}let U=!0;return K.sops.catalogue(i).then(ce=>{if(!U)return;const ue={};for(const Ee of ce.sops)Ee.relevance&&(ue[Ee.id]=Ee.relevance);E(ue)}).catch(()=>U&&E({})),()=>{U=!1}},[i]),p.useEffect(()=>{if(!i||!Em){R([]);return}K.listingDrafts.list(i).then(U=>R(U.drafts.filter(ce=>ce.status==="draft"))).catch(()=>R([]))},[i,P]),p.useEffect(()=>{if(!i||!Em){D([]);return}K.listingDrafts.submissions(i).then(U=>D(U.submissions)).catch(()=>D([]))},[i,P]);const ne=p.useMemo(()=>{var U;return((U=r.find(ce=>ce.slug===i))==null?void 0:U.display_name)??i},[r,i]),X=p.useMemo(()=>w.filter(U=>U.status!=="uploaded").length+k.filter(U=>U.status==="draft").length,[w,k]),he=p.useMemo(()=>{const U=r.find(Ee=>Ee.slug===i);if(!U)return[];const ce=U.account_id?r.filter(Ee=>Ee.account_id===U.account_id&&Ee.status==="active"):[U],ue=new Set;for(const Ee of ce)ue.add(Ee.marketplace??"takealot");return[...ue]},[r,i]),ae=p.useMemo(()=>{const U={all:Fc.length};for(const ce of Fc){const ue=Hf(ce);U[ue]=(U[ue]??0)+1}return U},[]),je=he.length>1;p.useEffect(()=>{A!=="all"&&!he.includes(A)&&C("all")},[A,he]);const $e=p.useMemo(()=>{const U=ce=>{const ue=N[ce];return ue?ue.tone==="warning"?2:1:0};return[...Fc].sort((ce,ue)=>U(ue.id)-U(ce.id))},[N]);Object.keys(N).length>0;const J=Object.keys(N).length,Ne=p.useMemo(()=>{const U={};for(const ce of g)U[ce.sop_id]||(U[ce.sop_id]=ce);return U},[g]),ve=O.length+Z.length,Me=p.useMemo(()=>Z.reduce((U,ce)=>U+(Number(ce.rejected_products)>0?1:0),0),[Z]);async function Xe(U,ce,ue){try{const Ee=Object.values(ue);if(U.mode==="direct"){let vt;if(Ee[0]){const It=Ee[0];vt={filename:It.name,base64:await vYe(It),mime:It.type||"text/csv"}}const Ot=await K.sops.createRun(i,{sop_id:U.id,values:ce,file:vt});return Ot.mode!=="direct"?{ok:!1,message:"Unexpected response."}:Ot.ok?(c(null),x({runId:Ot.run_id,sopId:Ot.sop_id,downloadUrl:Ot.download_url??"",filename:Ot.filename,summary:Ot.summary,kind:Ot.kind,prompt:Ot.prompt,approvalPath:Ot.approval_path??null,draftId:Ot.draft_id??null}),{ok:!0}):{ok:!1,message:Ot.message??"Run failed."}}const bt=await K.sops.createRun(i,{sop_id:U.id,values:ce});if(bt.mode!=="chat")return{ok:!1,message:"Unexpected response."};const Ze=await K.getChat(i,bt.chat_id);return c(null),f({runId:bt.run_id,chatId:bt.chat_id,prompt:bt.prompt,sopId:bt.sop_id,chat:Ze,files:Ee}),{ok:!0}}catch(Ee){return{ok:!1,message:Ee instanceof Error?Ee.message:String(Ee)}}}async function ze(U){try{const ce=await K.createChat(i);x(null),f({runId:U.runId,chatId:ce.id,prompt:U.prompt,sopId:U.sopId,chat:ce})}catch(ce){S(ce instanceof Error?ce.message:String(ce))}}async function Fe(U){const ce=U.deliverable;if(!U.chat_id&&(ce!=null&&ce.download_url)){x({runId:U.id,sopId:U.sop_id,downloadUrl:ce.download_url,filename:ce.filename??null,summary:typeof ce.summary=="string"?ce.summary:null,kind:ce.kind??null,prompt:""});return}if(U.chat_id)try{const ue=await K.getChat(i,U.chat_id);f({runId:U.id,chatId:U.chat_id,prompt:"",sopId:U.sop_id,chat:ue})}catch(ue){S(ue instanceof Error?ue.message:String(ue))}}function tt(U){const ce=Fc.find(ue=>ue.id===U.sop_id);ce&&ee(ce,U.form_values??{})}async function fe(U){const ce=U.products.filter(Ze=>Ze.approval_status==="rejected");if(ce.length===0)return;const ue=ce.map(Ze=>`- ${Ze.sku||Ze.title||"product"}: ${Ze.rejection_reason||Ze.system_validation||"rejected"}`).join(` 920`),bt=`These products were rejected in ${U.submission_name||`submission ${U.takealot_submission_id??U.id}`} on Takealot. Help me fix the issues and resubmit them: 921${ue}`;try{const Ze=await K.createChat(i);sessionStorage.setItem(`gadjet:seed:${Ze.id}`,bt),e(`/sellers/${i}/chats/${Ze.id}`)}catch(Ze){S(Ze instanceof Error?Ze.message:String(Ze))}}if(h)return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"SOPs",to:"/sops"},{label:n2(h.sopId)}],actions:s.jsx(Nj,{onClick:()=>f(null),label:"Back to SOPs"})}),s.jsx(of,{initialMessages:Aw(h.chat.messages),initialInput:h.prompt,autoSendInitial:h.prompt.length>0,initialFiles:h.files,extraRequestBody:{seller_slug:i,chat_id:h.chatId},chatId:h.chatId,onConversationChange:async U=>{await K.saveChat(i,h.chatId,{messages:Hp(U)}),h.runId&&!re.current.has(h.runId)&&U.some(ce=>
921ce.role==="assistant")&&(re.current.add(h.runId),K.sops.markRun(i,h.runId,{status:"completed"}).catch(()=>{}))},placeholder:`SOP run for ${ne}â¦`},h.chatId)]});if(m){const U=m;return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"SOPs",to:"/sops"},{label:n2(U.sopId)}],actions:s.jsx(Nj,{onClick:()=>x(null),label:"Back to SOPs"})}),s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsx("div",{className:"mx-auto max-w-2xl px-4 py-6 md:px-6",children:s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface p-4 shadow-xs",children:[typeof U.summary=="string"&&U.summary?s.jsx("div",{className:"mb-3 text-body-sm text-text-secondary",children:U.summary}):null,U.approvalPath?s.jsxs(st,{to:U.approvalPath,className:"inline-flex items-center gap-2 rounded-md bg-intent-brand px-3.5 py-2 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover",children:[s.jsx(cd,{className:"h-4 w-4"}),"Open for seller sign-off"]}):s.jsxs("a",{href:U.downloadUrl||"#",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-2 rounded-md bg-intent-brand px-3.5 py-2 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover",children:[s.jsx(Dr,{className:"h-4 w-4"}),U.filename||"Download"]}),(()=>{const ce=qV(U.kind);return!ce||!ce.url?null:s.jsxs("a",{href:ce.url,target:"_blank",rel:"noopener noreferrer",className:"mt-3 flex items-center justify-between gap-3 rounded-md border border-outline-subtle bg-surface-brandSubtle/40 px-3.5 py-2.5 text-body-sm text-text-body transition hover:bg-surface-brandSubtle/70",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary",children:"Next step â file it on Takealot"}),s.jsx("div",{className:"truncate text-body-xs text-text-secondary",children:ce.service})]}),s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 rounded-md bg-intent-brand px-3 py-1.5 text-body-sm font-medium text-text-inverse shadow-xs",children:[ce.label,s.jsx(Qt,{className:"h-3.5 w-3.5"})]})]})})(),s.jsx("div",{className:"mt-4",children:s.jsxs("button",{type:"button",onClick:()=>ze(U),className:"inline-flex items-center gap-1.5 rounded-md border border-outline-subtle px-3 py-1.5 text-body-sm text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary",children:[s.jsx(Rd,{className:"h-3.5 w-3.5"})," Ask about this in chat"]})})]})})})]})}return l?s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"SOPs",to:"/sops"},{label:l.label}],actions:s.jsx(Nj,{onClick:()=>{c(null),$(null),d(null)},label:"Back to SOPs"})}),l.mode==="builder"?s.jsx(yYe,{slug:i,resumeDraftId:I,onDraftsChanged:()=>F(U=>U+1)}):s.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:"mx-auto max-w-2xl px-4 py-6 md:px-6",children:[s.jsxs("div",{className:"mb-3 text-body-sm text-text-secondary",children:["Running for"," ",s.jsx("span",{className:"font-medium text-text-primary",children:ne}),u?s.jsx("span",{className:"ml-2 text-body-xs text-text-tertiary",children:"· pre-filled from your last run"}):null]}),s.jsx(T3,{formSpec:l.form,sellerSlug:i,prefill:u??void 0,onSubmit:(U,ce)=>Xe(l,U,ce??{})})]})})]}):s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"SOPs"}]}),s.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:[s.jsx(As,{items:[{key:"procedures",label:"Procedures",icon:s.jsx(n0,{className:"h-3.5 w-3.5"}),active:M==="procedures",onClick:()=>q("procedures"),trailing:J>0?s.jsx(Lu,{n:J,tone:"brand"}):void 0},{key:"listings",label:"Listings",icon:s.jsx(Gm,{className:"h-3.5 w-3.5"}),active:M==="listings",onClick:()=>q("listings"),trailing:Me>0?s.jsx(Lu,{n:Me,tone:"warning"}):ve>0?s.jsx(Lu,{n:ve,tone:"neutral"}):void 0},{key:"runs",label:"Runs",icon:s.jsx(r0,{className:"h-3.5 w-3.5"}),active:M==="runs",onClick:()=>q("runs"),trailing:g.length>0?s.jsx(Lu,{n:g.length,tone:"neutral"}):void 0},{key:"claims",label:"Claims",icon:s.jsx(yf,{className:"h-3.5 w-3.5"}),active:M==="claims",onClick:()=>q("claims"),trailing:b.length>0?s.jsx(Lu,{n:b.length,tone:"neutral"}):void 0},{key:"approvals",label:"Approvals",icon:s.jsx(cd,{className:"h-3.5 w-3.5"}),active:M==="approvals",onClick:()=>q("approvals"),trailing:X>0?s.jsx(Lu,{n:X,tone:"brand"}):w.length>0?s.jsx(Lu,{n:w.length,tone:"neutral"}):void 0}]}),je?s.jsx(SYe,{marketplaces:he,active:A,counts:ae,onPick:me}):null,s.jsxs("div",{className:"w-full px-4 md:px-6 py-6",children:[T?s.jsx("div",{className:"mb-4 rounded-md border border-outline-error bg-surface-errorSubtle px-3 py-2 text-body-sm text-text-error",children:T}):null,M==="procedures"?s.jsx(TYe,{slug:i,sellerName:ne,sops:$e,relevance:N,lastRunBySop:Ne,runs:g,marketplace:A,marketplacesInScope:he,onRerun:tt,onLaunch:U=>ee(U,N[U.id]&&Ne[U.id]?Ne[U.id].form_values??{}:void 0)}):null,M==="listings"?s.jsx($Ye,{slug:i,drafts:O,submissions:Z,onResumeDraft:U=>{Em&&($(U),c(Em))},onStartListing:()=>ee(Em),onChanged:()=>F(U=>U+1),onFixRejected:fe}):null,M==="runs"?s.jsx(WYe,{runs:g,sellerName:ne,onResume:Fe,onRerun:tt,onGoProcedures:()=>q("procedures")}):null,M==="claims"?s.jsx(FYe,{slug:i,claims:b,selectedClaimId:te,onSelect:U=>G(U??""),onGoProcedures:()=>q("procedures"),onClaimsChanged:()=>{i&&K.stockReconClaims.list(i).then(U=>v(U.claims)).catch(()=>{})}}):null,M==="approvals"?s.jsx(NYe,{slug:i,sellerName:ne,drafts:w,experimentApprovals:k,onGoProcedures:()=>q("procedures")}):null]})]})]})}function _Ye({status:e,changesRequestedAt:t}){const a={awaiting:{label:"Awaiting seller",cls:"border-outline-warning bg-surface-warningSubtle text-text-primary"},replied:{label:"Seller replied",cls:"border-outline-brand bg-surface-brandSubtle text-text-primary"},approved:{label:"Approved â file it",cls:"border-outline-success bg-surface-successSubtle text-text-success"},uploaded:{label:"Submitted",cls:"border-outline-subtle bg-surface-subtle text-text-secondary"}}[e==="uploaded"?"uploaded":e==="approved"?"approved":t?"replied":"awaiting"];return s.jsx("span",{className:`inline-flex items-center rounded-full border px-2 py-0.5 text-body-xs font-medium ${a.cls}`,children:a.label})}
921function kYe(e){return e.status==="uploaded"?"submitted":e.status==="approved"?"file_it":e.changes_requested_at?"replied":"awaiting"}const jYe=[{key:"replied",label:"Seller replied"},{key:"awaiting",label:"Awaiting seller"},{key:"file_it",label:"Approved â file it"},{key:"submitted",label:"Submitted"}];function NYe({slug:e,sellerName:t,drafts:n,experimentApprovals:r,onGoProcedures:a}){const i=r.filter(o=>o.status!=="discarded");return e?n.length===0&&i.length===0?s.jsxs("div",{className:"rounded-lg border border-dashed border-outline-subtle bg-surface px-4 py-8 text-center",children:[s.jsx(cd,{className:"mx-auto mb-2 h-6 w-6 text-text-tertiary"}),s.jsx("p",{className:"text-body-sm text-text-primary",children:"Nothing to approve"}),s.jsxs("p",{className:"mt-1 text-body-xs text-text-secondary",children:["Promotions and price experiments for"," ",s.jsx("span",{className:"font-medium text-text-primary",children:t})," land here for sign-off."]}),s.jsxs("button",{type:"button",onClick:a,className:"mt-3 inline-flex items-center gap-1.5 rounded-md bg-intent-brand px-3 py-1.5 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover",children:[s.jsx(n0,{className:"h-3.5 w-3.5"})," Browse procedures"]})]}):s.jsxs("div",{className:"flex flex-col gap-5",children:[i.length>0&&s.jsxs("div",{children:[s.jsxs("h3",{className:"mb-2 text-body-xs font-semibold uppercase tracking-wide text-text-tertiary",children:["Price experiments",s.jsx("span",{className:"ml-1.5 font-medium text-text-tertiary",children:i.length})]}),s.jsx("div",{className:"flex flex-col gap-2",children:i.map(o=>s.jsxs(st,{to:`/approvals/${e}/experiments/${o.batch_id}`,className:"flex items-center gap-2 rounded-md border border-outline-subtle bg-surface px-2 py-2.5 pl-4 shadow-xs transition hover:bg-surface-subtle",children:[s.jsx("span",{className:"shrink-0 text-intent-brand",children:s.jsx(cd,{className:"h-4 w-4"})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-body-sm font-medium text-text-primary",children:o.task_title||"Price experiment"}),s.jsxs("span",{className:"text-body-xs text-text-secondary",children:[o.line_count!=null?`${o.line_count} SKUs · `:"",o.status==="draft"?"awaiting sign-off":o.status]})]})]},o.id))})]}),jYe.map(o=>{const l=n.filter(c=>kYe(c)===o.key);return l.length===0?null:s.jsxs("div",{children:[s.jsxs("h3",{className:"mb-2 text-body-xs font-semibold uppercase tracking-wide text-text-tertiary",children:[o.label,s.jsx("span",{className:"ml-1.5 font-medium text-text-tertiary",children:l.length})]}),s.jsx("div",{className:"flex flex-col gap-2",children:l.map(c=>s.jsxs(st,{to:`/approvals/${e}/${c.id}`,className:"flex items-center gap-2 rounded-md border border-outline-subtle bg-surface px-2 py-2.5 pl-4 shadow-xs transition hover:bg-surface-subtle",children:[s.jsx("span",{className:"shrink-0 text-intent-brand",children:s.jsx(cd,{className:"h-4 w-4"})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-body-sm font-medium text-text-primary",children:c.task_title||"Promotion"}),s.jsxs("span",{className:"text-body-xs text-text-secondary",children:[c.line_count!=null?`${c.line_count} SKUs · `:"","edited ",Ao(c.updated_at)]})]}),s.jsx("span",{className:"flex shrink-0 items-center gap-1.5",children:s.jsx(_Ye,{status:c.status,changesRequestedAt:c.changes_requested_at})})]},c.id))})]},o.key)})]}):s.jsx("div",{className:"rounded-lg border border-dashed border-outline-subtle bg-surface px-4 py-8 text-center text-body-sm text-text-secondary",children:"Pick a seller to see their promotion and experiment approvals."})}function SYe({marketplaces:e,active:t,counts:n,onPick:r}){const a=Object.keys(c0),i=[...e].sort((l,c)=>{const u=a.indexOf(l),d=a.indexOf(c);return(u===-1?99:u)-(d===-1?99:d)}),o=[{key:"all",label:"All"},...i.map(l=>({key:l,label:_p(l)}))];return s.jsxs("div",{className:"flex items-center gap-2.5 border-b border-outline-subtle bg-surface-subtle px-4 py-2.5 md:px-6",children:[s.jsx("span",{className:"text-body-xs font-semibold uppercase tracking-[0.06em] text-text-tertiary",children:"Marketplace"}),s.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:o.map(l
921=>{const c=t===l.key,u=n[l.key]??0;return s.jsxs("button",{type:"button",onClick:()=>r(l.key),"aria-pressed":c,className:`inline-flex items-center gap-1.5 rounded-full border py-1 pr-[11px] text-body-sm transition ${l.key==="all"?"pl-[11px]":"pl-[7px]"} ${c?"border-outline bg-surface font-medium text-text-primary":"border-outline-subtle bg-transparent text-text-secondary hover:border-outline hover:text-text-primary"}`,children:[l.key==="all"?null:s.jsx(kf,{marketplace:l.key,size:14}),l.label,s.jsx("span",{className:"text-text-tertiary",children:u})]},l.key)})})]})}function Lu({n:e,tone:t}){const n=t==="warning"?"border border-outline-warning bg-surface-warningSubtle text-text-primary":t==="brand"?"bg-surface-brandSubtle/60 text-intent-brand":"bg-surface-subtle text-text-secondary";return s.jsx("span",{className:`ml-0.5 inline-flex min-w-[1.1rem] items-center justify-center rounded-full px-1.5 py-0.5 text-[10px] font-semibold leading-none ${n}`,children:e})}function CYe({options:e,value:t,onChange:n}){return s.jsx("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:e.map(r=>s.jsxs("button",{type:"button",onClick:()=>n(r.key),className:`rounded-full border px-2.5 py-1 text-body-xs transition ${t===r.key?"border-outline bg-surface-subtle font-medium text-text-primary":"border-outline-subtle text-text-secondary hover:bg-surface-subtle"}`,children:[r.label,r.count!=null?s.jsx("span",{className:"ml-1 text-text-tertiary",children:r.count}):null]},r.key))})}function EYe(e){var r,a,i;const t=[{label:"category",ok:e.category_id!=null||!!e.category_path},{label:"title",ok:!!((r=e.content)!=null&&r.title)},{label:"description",ok:!!((a=e.content)!=null&&a.description)},{label:"images",ok:(((i=e.images)==null?void 0:i.length)??0)>0},{label:"price",ok:e.selling_price!=null},{label:"SKU",ok:!!e.sku}],n=t.filter(o=>o.ok).length;return{done:n,total:t.length,ready:n===t.length,missing:t.filter(o=>!o.ok).map(o=>o.label)}}function AYe({status:e}){const t=e.toLowerCase(),n=t==="completed"?"border-outline-success bg-surface-successSubtle text-text-success":t==="failed"||t==="error"?"border-outline-error bg-surface-errorSubtle text-text-error":t==="running"||t==="in_progress"||t==="pending"?"border-outline-subtle bg-surface-brandSubtle/50 text-intent-brand":"border-outline-subtle bg-surface-subtle text-text-secondary";return s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-body-xs ${n}`,children:e})}function TYe({slug:e,sellerName:t,sops:n,relevance:r,lastRunBySop:a,runs:i,marketplace:o,marketplacesInScope:l,onLaunch:c,onRerun:u}){const d=y=>{const b=r[y];return b?b.tone==="warning"?2:1:0},h=n.filter(y=>o==="all"||Hf(y)===o),f=h.filter(y=>r[y.id]).sort((y,b)=>d(b.id)-d(y.id)),m=f[0]??null,x=f.slice(1),g=p.useMemo(()=>{const y=Date.now()-2592e6,b=new Set(i.filter(v=>new Date(v.created_at).getTime()>=y).map(v=>v.sop_id));return h.filter(v=>b.has(v.id)).length},[i,h]);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-4 flex flex-wrap items-baseline justify-between gap-4",children:[s.jsx("p",{className:"text-body-sm text-text-body",children:f.length>0?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"font-medium text-text-primary",children:[f.length," ",f.length===1?"procedure is":"procedures are"," due"]}),l.length>1?` across ${t}'s ${l.length} marketplaces.`:` for ${t}.`]}):`Nothing is flagged for ${t} right now â pick a procedure to run it.`}),s.jsxs("p",{className:"text-body-xs text-text-tertiary",children:[g," of ",h.length," run in the last 30 days"]})]}),m?s.jsx(IYe,{sop:m,relevance:r[m.id],lastRun:a[m.id],disabled:!e,onLaunch:()=>c(m),onRerun:u}):null,x.length>0?s.jsxs("div",{className:"mb-7",children:[s.jsxs("div",{className:"mb-2.5 flex items-center gap-2",children:[s.jsx("h2",{className:"text-body-md font-semibold text-text-primary",children:"Also worth running"}),s.jsx("span",{className:"text-body-xs text-text-tertiary",children:x.length})]}),s.jsx("div",{className:"flex flex-col gap-2",children:x.map(y=>s.jsx(PYe,{sop:y,relevance:r[y.id],lastRun:a[y.id],disabled:!e,onLaunch:()=>c(y)},y.id))})]}
921):null,s.jsx(RYe,{sops:h,lastRunBySop:a,marketplacesInScope:l,disabled:!e,onLaunch:c})]})}function OYe(e){return e.mode==="direct"?"Takes about a minute":"Takes a few minutes"}function IYe({sop:e,relevance:t,lastRun:n,disabled:r,onLaunch:a,onRerun:i}){var d,h;const o=Vx[e.icon],l=PG(e.id,t),c=((d=e.form)==null?void 0:d.submit_label)??`Run ${e.label}`,u=((h=n==null?void 0:n.deliverable)==null?void 0:h.filename)??null;return s.jsxs("div",{className:"mb-7 overflow-hidden rounded-lg border border-outline-warning bg-surface shadow-md",children:[s.jsxs("div",{className:"flex items-center gap-1.5 border-b border-outline-warning bg-surface-warningSubtle px-5 py-2",children:[s.jsx(zn,{className:"h-3.5 w-3.5 text-text-warning"}),s.jsx("span",{className:"text-body-xs font-semibold uppercase tracking-[0.06em] text-text-warning",children:"Run this first"})]}),s.jsxs("div",{className:"flex flex-col gap-5 p-5 md:flex-row md:items-start md:gap-6",children:[o?s.jsx("span",{className:"grid h-11 w-11 shrink-0 place-items-center rounded-lg bg-surface-brandSubtle text-intent-brand",children:s.jsx(o,{className:"h-[22px] w-[22px]"})}):null,s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("h2",{className:"text-headline-md font-semibold text-text-primary",children:e.label}),s.jsx(RG,{marketplace:Hf(e)})]}),l?s.jsx("p",{className:"mt-1.5 max-w-[70ch] text-body-md text-text-body",children:l}):null,s.jsxs("div",{className:"mt-3.5 flex flex-wrap items-center gap-x-5 gap-y-2",children:[s.jsx(_j,{icon:r0,children:n?`Last run ${Ao(n.created_at)}`:"Not run yet"}),u?s.jsx(_j,{icon:Dr,children:s.jsx("span",{className:"max-w-[32ch] truncate",children:u})}):null,s.jsx(_j,{icon:pu,children:OYe(e)})]})]}),s.jsxs("div",{className:"flex shrink-0 flex-col gap-2",children:[s.jsx("button",{type:"button",disabled:r,onClick:a,className:"whitespace-nowrap rounded-md bg-intent-brand px-4 py-2.5 text-body-md font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover disabled:cursor-not-allowed disabled:opacity-50",children:c}),n?s.jsxs("button",{type:"button",disabled:r,onClick:()=>i(n),className:"inline-flex items-center justify-center gap-1.5 whitespace-nowrap rounded-md border border-outline-subtle bg-surface px-4 py-2 text-body-sm text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-50",children:[s.jsx(_o,{className:"h-3.5 w-3.5"}),"Re-run last inputs"]}):null]})]})]})}function PYe({sop:e,relevance:t,lastRun:n,disabled:r,onLaunch:a}){var c;const i=Vx[e.icon],o=PG(e.id,t),l=((c=n==null?void 0:n.deliverable)==null?void 0:c.filename)??null;return s.jsxs("button",{type:"button",disabled:r,onClick:a,className:"flex w-full items-center gap-3.5 rounded-lg border border-outline-subtle border-l-[3px] border-l-outline-warning bg-surface px-4 py-3.5 text-left shadow-xs transition hover:bg-surface-subtle disabled:cursor-not-allowed disabled:opacity-50",children:[i?s.jsx("span",{className:"shrink-0 text-intent-brand",children:s.jsx(i,{className:"h-[18px] w-[18px]"})}):null,s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"text-body-md font-medium text-text-primary",children:e.label}),s.jsx(RG,{marketplace:Hf(e)})]}),o?s.jsx("span",{className:"mt-0.5 block text-body-sm text-text-body",children:o}):null,s.jsx("span",{className:"mt-1 block text-body-xs text-text-tertiary",children:n?`Last run ${Ao(n.created_at)}${l?` · ${l}`:""}`:"Not run yet"})]}),s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 rounded-md border border-outline bg-surface px-3.5 py-2 text-body-sm font-medium text-text-primary",children:["Run",s.jsx(os,{className:"h-3.5 w-3.5"})]})]})}function RYe({sops:e,lastRunBySop:t,marketplacesInScope:n,disabled:r,onLaunch:a}){const i=p.useMemo(()=>{const c=new Map;for(const u of e){const d=Hf(u);c.has(d)||c.set(d,[]),c.get(d).push(u)}return[...c.entries()].map(([u,d])=>({key:u,items:d,connected:n.includes(u)})).sort((u,d)=>Number(d.connected)-Number(u.connected))},[e,n]),o=i.length>1,l=i.filter(c=>c.connected).length>1;return s.jsxs("div",{children:[s.jsxs("div",{className:"mb-2.5 flex items-center gap-2",children:[s.jsx("h2",{className:"text-body-md font-semibold text-text-primary",children:"All procedures"}),l?s.jsx("span",{className:"text-body-xs text-text-tertiary",children:"grouped by marketplace"}):null]}),s.jsx("div",{className:"overflow-hidden rounded-lg border border-outline-subtle bg-surface shadow-xs",children:i.map(c=>s.jsxs("div",{children:[o?s.jsxs("div",{className:"flex items-center gap-2 border-b border-outline-subtle bg-surface-subtle px-4 py-2",children:[c.connected?s.jsx(kf,{marketplace:c.key}
921):null,s.jsx("span",{className:"text-body-xs font-semibold uppercase tracking-[0.06em] text-text-secondary",children:_p(c.key)}),s.jsx("span",{className:"text-body-xs text-text-tertiary",children:c.connected?c.items.length:"not connected on this account"})]}):null,c.items.map(u=>{const d=Vx[u.icon],h=t[u.id];return s.jsxs("div",{className:`flex items-center gap-3.5 border-b border-outline-faint px-4 py-3.5 transition last:border-b-0 hover:bg-surface-subtle ${c.connected?"":"opacity-55"}`,children:[d?s.jsx("span",{className:"shrink-0 text-text-tertiary",children:s.jsx(d,{className:"h-4 w-4"})}):null,s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-body-sm font-medium text-text-primary",children:u.label}),u.description?s.jsx("div",{className:"mt-px text-body-xs text-text-secondary",children:u.description}):null]}),s.jsx("div",{className:"hidden w-[140px] shrink-0 text-right text-body-xs text-text-tertiary sm:block",children:h?`Last run ${Ao(h.created_at)}`:"Not run yet"}),c.connected?s.jsx("button",{type:"button",disabled:r,onClick:()=>a(u),className:"shrink-0 rounded-md border border-outline-subtle bg-surface px-3 py-1.5 text-body-xs font-medium text-text-secondary transition hover:border-outline hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-50",children:"Run"}):s.jsx(st,{to:"/settings/stores",className:"shrink-0 rounded-md border border-outline-subtle bg-surface px-3 py-1.5 text-body-xs font-medium text-text-secondary transition hover:border-outline hover:text-text-primary",children:"Connect"})]},u.id)})]},c.key))}),l?s.jsx("p",{className:"mt-2.5 text-body-xs text-text-tertiary",children:"Sellers on a single marketplace see only their own section â the grouping appears once an account holds two or more."}):null]})}function RG({marketplace:e}){return s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1.5 rounded-xs bg-surface-sunken px-1.5 py-0.5 text-body-xs text-text-body",children:[s.jsx(kf,{marketplace:e,size:12}),_p(e)]})}function _j({icon:e,children:t}){return s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-body-xs text-text-secondary",children:[s.jsx(e,{className:"h-3.5 w-3.5 text-text-tertiary"}),t]})}function DG({onClick:e}){return s.jsxs("button",{type:"button",onClick:t=>{t.stopPropagation(),e()},className:"inline-flex items-center gap-1.5 rounded-md border border-outline-subtle bg-surface px-2.5 py-1.5 text-body-xs text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary",children:[s.jsx(Rd,{className:"h-3.5 w-3.5"})," Fix & resubmit in chat"]})}function DYe({submission:e,reasonsRecorded:t,onFixRejected:n}){const a=e.products.filter(l=>l.approval_status==="rejected").filter(l=>l.rejection_reason||l.system_validation),i=a.slice(0,2),o=a.length-i.length;return s.jsxs("div",{className:"mx-4 mb-2.5 flex items-start gap-2 rounded-md border border-outline-error bg-surface-errorSubtle px-2.5 py-[7px]",children:[s.jsx(yt,{className:"mt-px h-3.5 w-3.5 shrink-0 text-intent-error"}),s.jsxs("div",{className:"min-w-0 flex-1 text-body-xs leading-4 text-text-error",children:[t?s.jsxs(s.Fragment,{children:[i.map((l,c)=>s.jsxs("div",{className:"truncate",children:[s.jsx("span",{className:"font-medium",children:l.sku||l.title||"product"})," ","â ",l.rejection_reason||l.system_validation]},c)),o>0?s.jsxs("div",{children:["+",o," more"]}):null]}):s.jsx("div",{children:"Reasons aren't recorded yet â upload the submission results file in chat to see why each product failed."}),s.jsx("div",{className:"mt-1.5",children:s.jsx(DG,{onClick:()=>n(e)})})]})]})}function MYe({products:e}){return s.jsx("div",{className:"-mx-4 overflow-x-auto",children:s.jsxs("div",{className:"min-w-[640px]",children:[s.jsxs("div",{className:"grid grid-cols-[120px_1fr_100px_1.4fr] gap-3 border-y border-outline-subtle bg-surface-subtle px-4 py-[7px] text-body-xs font-semibold uppercase tracking-[0.04em] text-text-tertiary",children:[s.jsx("span",{children:"SKU"}),s.jsx("span",{children:"Product"}),s.jsx("span",{children:"Status"}),s.jsx("span",{children:"Reason"})]}),e.map((t,n)=>{const r=t.rejection_reason||t.system_validation;return s.jsxs("div",{className:"grid grid-cols-[120px_1fr_100px_1.4fr] items-baseline gap-3 border-b border-outline-faint px-4 py-2.5 text-body-xs last:border-b-0",children:[s.jsx("span",{className:"truncate font-mono text-text-body",children:t.sku||"â"}),s.jsx("span",{className:"truncate text-text-primary",children:t.title||`Product ${n+1}`}),s.jsx("span",{className:`font-medium ${t.approval_status==="rejected"?"text-text-error":t.approval_status==="approved"?"text-text-success":"text-text-secondary"}`,children:t.approval_status}),s.jsx("span",{className:"text-text-secondary",children:r||"â"})]},n)})]})})}function $Ye({slug:e,drafts:t,submissions:n,onResumeDraft:r,onStartListing:a,onChanged:i,onFixRejected:o}){const[l,c]=p.useState(null),[u,d]=p.useState(null),[h,f]=p.useState(null),[m,x]=p.useState("all"),[g,y]=p.useState(null);async function b(E){d(E),f(null);try{await K.listingDrafts.submitTakealotDraft(e,E),i()}catch(A){f({id:E,message:A instanceof Error?A.message:"Could not submit this draft"})}finally{d(null)}}async function v(E){if(window.confirm("Discard this draft? This can't be und
921one from here.")){y(E);try{await K.listingDrafts.discard(e,E),i()}catch{}finally{y(null)}}}const w=E=>Number(E.rejected_products||0)>0?"rejected":E.status==="Complete"?"approved":"pending",_={all:n.length,pending:0,approved:0,rejected:0};for(const E of n)_[w(E)]++;const k=m==="all"?n:n.filter(E=>w(E)===m),j=_.approved+_.rejected,N=j>0?Math.round(_.approved/j*100):null;return t.length===0&&n.length===0?s.jsxs("div",{className:"rounded-lg border border-dashed border-outline-subtle bg-surface px-4 py-8 text-center",children:[s.jsx(Gm,{className:"mx-auto mb-2 h-6 w-6 text-text-tertiary"}),s.jsx("p",{className:"text-body-sm text-text-primary",children:"No listings yet"}),s.jsx("p",{className:"mt-1 text-body-xs text-text-secondary",children:"Drafts you start and listings you submit to Takealot will show up here."}),s.jsxs("button",{type:"button",onClick:a,className:"mt-3 inline-flex items-center gap-1.5 rounded-md bg-intent-brand px-3 py-1.5 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover",children:[s.jsx(Gm,{className:"h-3.5 w-3.5"})," Create new listings"]})]}):s.jsxs("div",{className:"flex flex-col gap-8",children:[s.jsxs("section",{children:[s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-3",children:[s.jsxs("h2",{className:"text-body-md font-semibold text-text-primary",children:["In progress",t.length>0?s.jsx("span",{className:"ml-1.5 text-body-xs font-normal text-text-secondary",children:t.length}):null]}),s.jsxs("button",{type:"button",onClick:a,className:"inline-flex items-center gap-1.5 rounded-md border border-outline-subtle px-2.5 py-1.5 text-body-xs text-text-secondary transition hover:bg-surface-subtle hover:text-text-primary",children:[s.jsx(Gm,{className:"h-3.5 w-3.5"})," New listing"]})]}),t.length===0?s.jsx("p",{className:"text-body-xs text-text-secondary",children:"No drafts in progress."}):s.jsx("div",{className:"flex flex-col gap-2",children:t.map(E=>{const A=EYe(E);return s.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-outline-subtle bg-surface px-2 py-2.5 pl-4 shadow-xs transition hover:bg-surface-subtle",children:[s.jsxs("button",{type:"button",onClick:()=>r(E.id),className:"flex min-w-0 flex-1 items-center justify-between gap-3 text-left",children:[s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block truncate text-body-sm text-text-primary",children:IG
921(E)}),s.jsxs("span",{className:"mt-0.5 block text-body-xs text-text-secondary",children:["edited ",Ao(E.updated_at),!A.ready&&A.missing.length>0?s.jsxs("span",{className:"text-text-tertiary",children:[" ","· needs ",A.missing.slice(0,3).join(", ")]}):null]})]}),s.jsx("span",{className:`shrink-0 rounded-full border px-2 py-0.5 text-body-xs ${A.ready?"border-outline-success bg-surface-successSubtle text-text-success":"border-outline-subtle bg-surface-subtle text-text-secondary"}`,children:A.ready?"Ready to submit":`${A.done}/${A.total} ready`})]}),s.jsx("button",{type:"button",title:"Discard draft",disabled:g===E.id,onClick:()=>v(E.id),className:"shrink-0 rounded-md p-1.5 text-text-tertiary transition hover:bg-surface-errorSubtle hover:text-text-error disabled:opacity-50",children:s.jsx(us,{className:"h-3.5 w-3.5"})})]},E.id)})})]}),s.jsxs("section",{children:[s.jsxs("h2",{className:"mb-3 text-body-md font-semibold text-text-primary",children:["Submitted",n.length>0?s.jsx("span",{className:"ml-1.5 text-body-xs font-normal text-text-secondary",children:n.length}):null]}),n.length===0?s.jsx("p",{className:"text-body-xs text-text-secondary",children:"Nothing submitted to Takealot yet."}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-x-3 gap-y-1 rounded-md border border-outline-subtle bg-surface px-3 py-2 text-body-xs text-text-secondary",children:[s.jsxs("span",{className:"font-medium text-text-primary",children:[_.all," submitted"]}),s.jsxs("span",{className:"text-text-success",children:[_.approved," approved"]}),s.jsxs("span",{className:"text-text-error",children:[_.rejected," rejected"]}),_.pending>0?s.jsxs("span",{children:[_.pending," pending"]}):null,N!=null?s.jsxs("span",{className:"ml-auto font-medium text-text-primary",children:[N,"% pass rate"]}):null]}),s.jsx(CYe,{value:m,onChange:x,options:[{key:"all",label:"All",count:_.all},{key:"rejected",label:"Rejected",count:_.rejected},{key:"approved",label:"Approved",count:_.approved},{key:"pending",label:"Pending",count:_.pending}]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[k.map(E=>{const A=Number(E.rejected_products||0),C=l===E.id,T=A>0?{text:`${A} rejected`,cls:"border-outline-warning bg-surface-warningSubtle text-text-primary"}:E.status==="Complete"?{text:"Approved",cls:"border-outline-success bg-surface-successSubtle text-text-success"}:{text:E.status,cls:"border-outline-subtle bg-surface-subtle text-text-secondary"},S=E.products.some(O=>O.rejection_reason||O.system_validation);return s.jsxs("div",{className:`rounded-md border bg-surface shadow-xs ${A>0?"border-outline-error":"border-outline-subtle"}`,children:[s.jsxs("button",{type:"button",onClick:()=>c(C?null:E.id),className:"flex w-full items-center justify-between gap-3 px-4 py-2.5 text-left transition hover:bg-surface-subtle",children:[s.jsx("span",{className:"min-w-0 truncate text-body-sm text-text-primary",children:E.submission_name||`Submission ${E.takealot_submission_id??E.id}`}),s.jsxs("span",{className:"flex shrink-0 items-center gap-2",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-body-xs ${T.cls}`,children:T.text}),s.jsx("span",{className:"text-body-xs text-text-secondary",children:Ao(E.created_at)})]})]}),(E.status==="Draft"||E.is_draft)&&E.takealot_submission_id?s.jsxs("div",{className:"mx-4 mb-2.5 flex flex-wrap items-center gap-2",children:[s.jsx("button",{type:"button",disabled:u===E.id,onClick:()=>b(E.id),className:"inline-flex items-center rounded-md bg-intent-brand px-2.5 py-1.5 text-body-xs font-medium text-text-inverse disabled:opacity-50",children:u===E.id?"Submittingâ¦":"Submit for review"}),(h==null?void 0:h.id)===E.id?s.jsx("span",{className:"text-body-xs text-text-error",children:h.message}):null]}):null,A>0&&!C?s.jsx(DYe,{submission:E,reasonsRecorded:S,onFixRejected:o}):null,C?s.jsxs("div",{className:"border-t border-outline-subtle px-4 py-2",children:[E.products.length===0?s.jsx("p",{className:"py-1 text-body-xs text-text-secondary",children:"No product detail recorded."}):s.jsx(MYe,{products:E.products}),A>0&&!S?s.jsx("p",{className:"mt-1.5 text-body-xs text-text-tertiary",children:"Reasons aren't recorded yet â upload the submission results file in chat to see why each product failed."}):null,A>0?s.jsx("div",{className:"mt-2",children:s.jsx(DG,{onClick:()=>o(E)})}):null]}):null]},E.id)}),k.length===0?s.jsxs("p",{className:"text-body-xs text-text-secondary",children:["No ",m," submissions."]}):null]})]})]})]})}const LYe=["January","February","March","April","May","June","July","August","September","October","November","December"];function MG(e){if(!/^\d{6}$/.test(e))return e;
921const t=e.slice(0,4),n=Number(e.slice(4,6))-1;return n>=0&&n<12?`${LYe[n]} ${t}`:e}function Uc(e){const t=Number(e);return Number.isFinite(t)?t.toLocaleString("en-ZA",{minimumFractionDigits:2,maximumFractionDigits:2}):"0.00"}function $G({status:e}){const t={draft:{label:"Draft",cls:"border-outline-subtle bg-surface-subtle text-text-secondary"},submitted:{label:"Submitted",cls:"border-outline-success bg-surface-successSubtle text-text-success"},amended:{label:"Amended",cls:"border-outline-warning bg-surface-warningSubtle text-text-primary"}},n=t[e]??t.draft;return s.jsx("span",{className:`inline-flex items-center rounded-full border px-2 py-0.5 text-body-xs font-medium ${n.cls}`,children:n.label})}function FYe({slug:e,claims:t,selectedClaimId:n,onSelect:r,onGoProcedures:a,onClaimsChanged:i}){return e?n?s.jsx(zYe,{slug:e,claimId:n,onBack:()=>r(null),onChanged:i}):t.length===0?s.jsxs("div",{className:"rounded-lg border border-dashed border-outline-subtle bg-surface px-4 py-8 text-center",children:[s.jsx(yf,{className:"mx-auto mb-2 h-6 w-6 text-text-tertiary"}),s.jsx("p",{className:"text-body-sm text-text-primary",children:"No claims yet"}),s.jsxs("p",{className:"mt-1 text-body-xs text-text-secondary",children:["Run ",s.jsx("span",{className:"font-medium text-text-primary",children:"File the monthly stock recon claim"})," ","and the invoice is saved here â editable if Takealot later finds some of the stock."]}),s.jsxs("button",{type:"button",onClick:a,className:"mt-3 inline-flex items-center gap-1.5 rounded-md bg-intent-brand px-3 py-1.5 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover",children:[s.jsx(n0,{className:"h-3.5 w-3.5"})," Browse procedures"]})]}):s.jsx(BYe,{slug:e,claims:t,onSelect:r,onChanged:i}):s.jsx("div",{className:"rounded-lg border border-dashed border-outline-subtle bg-surface px-4 py-8 text-center text-body-sm text-text-secondary",children:"Pick a seller to see their stock loss claims."})}function WL(e){if(!/^\d{6}$/.test(e))return null;const t=Number(e.slice(0,4)),n=Number(e.slice(4,6));return new Date(t,n+1,0)}const kj=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function BYe({slug:e,claims:t,onSelect:n,onChanged:r}){const[a,i]=p.useState(null);async function o(y){i(y.id);try{await K.stockReconClaims.setFiled(e,y.id,y.status!=="submitted"),r()}catch{}finally{i(null)}}const[l,c]=p.useState(null);p.useEffect(()=>{if(!e)return;let y=!0;return K.businessInfo.get(e).then(b=>y&&c(b.business_info??null)).catch(()=>{}),()=>{y=!1}},[e]);const d=((l==null?void 0:l.missing_for_invoice)??[]).map(y=>LG[y]??y),h=t.filter(y=>y.status==="submitted"),f=t.filter(y=>y.status!=="submitted"),m=y=>y.reduce((b,v)=>b+Number(v.grand_total||0),0),x=y=>y.reduce((b,v)=>b+Number(v.total_units||0),0),g=f.map(y=>WL(y.period)).filter(y=>!!y).sort((y,b)=>y.getTime()-b.getTime())[0];return s.jsxs(s.Fragment,{children:[d.length>0?s.jsxs("div",{className:"mb-4 flex items-center gap-2 rounded-lg border border-outline-warning bg-surface-warningSubtle px-4 py-2.5",children:[s.jsx(zn,{className:"h-3.5 w-3.5 shrink-0 text-text-warning"}),s.jsxs("span",{className:"min-w-0 flex-1 text-body-xs leading-4 text-text-warning",children:[d.length," invoicing"," ",d.length===1?"detail is":"details are"," missing â every claim PDF will print [MISSING] for"," ",d.join(" and "),"."]}),s.jsx(st,{to:`/settings/stores/${e}/billing`,className:"shrink-0 text-body-xs font-medium text-text-warning underline",children:"Edit invoicing details"})]}):null,s.jsxs("div",{className:"mb-5 flex flex-col gap-3 sm:flex-row",children:[s.jsx(jj,{eyebrow:"Claimed to date",figure:`R ${Uc(m(t))}`,sub:`${t.length} ${t.length===1?"invoice":"invoices"} · ${x(t)} units`}),h.length>0?s.jsx(jj,{eyebrow:"Filed with Takealot",figure:`R ${Uc(m(h))}`,figureClass:"text-text-success",sub:`${h.length} ${h.length===1?"invoice":"invoices"} · ${x(h)} units`}):null,f.length>0?s.jsx(jj,{eyebrow:"Not filed yet",figure:`R ${Uc(m(f))}`,tone:"warning",sub:g?g.getTime()<Date.now()?`Oldest window closed ${g.getDate()} ${kj[g.getMonth()]}`:`Earliest closes ${g.getDate()} ${kj[g.getMonth()]}`:`${f.length} outstanding`}):null]}),s.jsx("div",{className:"flex flex-col gap-2",children:t.map(y=>{const b=y.status==="submitted",v=WL(y.period);return s.jsx("div",{className:"overflow-hidden rounded-lg border border-outline-subtle bg-surface shadow-xs",children:s.jsxs("div",{className:`flex items-center gap-3.5 border-l-[3px] px-4 py-3.5 transition hover:bg-surface-subtle ${b?"border-l-success-500":"border-l-outline-warning"}`,children:[s.jsxs("button",{type:"button",onClick:()=>n(y.id),className:"flex min-w-0 flex-1 items-center gap-3 text-left",children:[s.jsx("span",{className:"shrink-0 text-intent-brand",children:s.jsx(yf,{className:"h-[18px] w-[18px]"})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex flex-wrap items-baseline gap-2",children:[s.jsx("span",{className:"truncate text-body-sm font-medium text-text-primary",children:y.invoice_number}),s.jsx("span",{className:"text-body-xs text-text-secondary",children:MG(y.peri
921od)})]}),s.jsxs("span",{className:"mt-0.5 block text-body-xs text-text-secondary",children:[Number(y.total_units||0)," units",y.is_vat_registered?" · incl VAT":""," · built"," ",Ao(y.created_at)]})]})]}),s.jsxs("span",{className:"hidden w-[120px] shrink-0 text-right text-body-md font-semibold tabular-nums text-text-primary sm:block",children:["R ",Uc(y.grand_total)]}),s.jsxs("span",{className:"flex shrink-0 items-center gap-2",children:[!b&&v?s.jsxs("span",{className:`hidden text-body-xs font-medium md:inline ${v.getTime()<Date.now()?"text-text-error":"text-text-warning"}`,children:[v.getTime()<Date.now()?"Closed":"Due"," ",v.getDate()," ",kj[v.getMonth()]]}):null,s.jsx($G,{status:y.status}),s.jsx("button",{type:"button",disabled:a===y.id,onClick:()=>o(y),title:b?"Un-mark this claim as filed":"Mark this claim as filed with Takealot",className:`shrink-0 rounded-md border px-2.5 py-1.5 text-body-xs font-medium transition disabled:opacity-50 ${b?"border-outline-subtle bg-surface text-text-secondary hover:border-outline hover:text-text-primary":"border-outline bg-surface text-text-primary hover:bg-surface-subtle"}`,children:a===y.id?"Savingâ¦":b?"Un-file":"Mark filed"}),y.download_url?s.jsx("a",{href:y.download_url,target:"_blank",rel:"noreferrer",title:"Download PDF",className:"rounded-md p-1.5 text-text-tertiary transition hover:bg-surface-subtle hover:text-text-primary",children:s.jsx(Dr,{className:"h-3.5 w-3.5"})}):null]})]})},y.id)})})]})}function jj({eyebrow:e,figure:t,sub:n,tone:r,figureClass:a}){const i=r==="warning";return s.jsxs("div",{className:`flex-1 rounded-lg border p-4 shadow-xs ${i?"border-outline-warning bg-surface-warningSubtle":"border-outline-subtle bg-surface"}`,children:[s.jsx("div",{className:`text-body-xs font-semibold uppercase tracking-[0.06em] ${i?"text-text-warning":"text-text-tertiary"}`,children:e}),s.jsx("div",{className:`mt-1 text-headline-lg font-semibold tabular-nums ${i?"text-text-warning":a??"text-text-primary"}`,children:t}),s.jsx("div",{className:`mt-0.5 text-body-xs ${i?"text-text-warning":"text-text-secondary"}`,children:n})]})}const LG={trading_name:"Trading name",contact_email:"Contact email",billing_address:"Billing address","bank.account_holder":"Account holder","bank.bank":"Bank","bank.branch_code":"Branch code","bank.account_number":"Account number"};function UYe({slug:e,info:t,isVatClaim:n}){var d;if(!t)return null;const r=t.fields,a=h=>{var m;const f=(m=r[h])==null?void 0:m.value;return typeof f=="string"&&f.trim()?f:null},i=(d=r.billing_address)==null?void 0:d.value,o=i&&typeof i=="object"?[i.street,i.suburb,i.city,i.postal_code].filter(Boolean).join(", "):null,l=t.missing_for_invoice??[],c=n&&!a("vat_number"),u=a("bank.account_number");return s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface p-4 shadow-xs",children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-body-sm font-medium text-text-primary",children:"Bill from"}),s.jsx("div",{className:"text-body-xs text-text-secondary",children:"Printed on the invoice. Re-generating picks up any change."})]}),s.jsx(st,{to:`/settings/stores/${e}/billing`,className:"shrink-0 rounded-md border border-outline-subtle bg-surface px-3 py-1.5 text-body-xs font-medium text-text-primary shadow-xs transition hover:bg-surface-subtle",children:"Edit details"})]}),(l.length>0||c)&&s.jsx("div",{className:"mb-3 rounded-md border border-outline-warning bg-surface-warningSubtle px-3 py-2",children:s.jsxs("div",{className:"text-body-xs text-text-warning",children:[s.jsx("span",{className:"font-medium",children:c?"This is a tax invoice with no VAT number on file.":`${l.length} detail${l.length===1?"":"s"} missing.`})," ",c?"Re-generating will fail until a VAT number is added.":`The invoice will print â[MISSING]â for ${l.map(h=>LG[h]??h).join(", ")}.`]})}),s.jsxs("dl",{className:"grid grid-cols-[minmax(0,7rem)_1fr] gap-x-3 gap-y-1.5 text-body-xs",children:[s.jsx(Ec,{label:"Trading name",value:a("trading_name")}),n&&s.jsx(Ec,{label:"VAT number",value:a("vat_number")}),s.jsx(Ec,{label:"Contact",value:a("contact_email")}),s.jsx(Ec,{label:"Address",value:o}),s.jsx(Ec,{label:"Account holder",value:a("bank.account_holder")}),s.jsx(Ec,{label:"Bank",value:a("bank.bank")}),s.jsx(Ec,{label:"Branch code",value:a("bank.branch_code")}),s.jsx(Ec,{label:"Account no.",value:u?u.length>4?`â¢â¢â¢â¢${u.slice(-4)}`:"â¢â¢â¢â¢":null})]})]})}function Ec({label:e,value:t}){return s.jsxs(s.Fragment,{children:[s.jsx("dt",{className:"text-text-tertiary",children:e}),s.jsx("dd",{className:t?"truncate text-text-primary":"text-text-warning",title:t??void 0,children:t??"[MISSING]"})]})}function zYe({slug:e,claimId:t,onBack:n,onChanged:r}){const[a,i]=p.useState(null),[o,l]=p.useState(""),[c,u]=p.useState(!1),[d,h]=p.useState(null),[f,m]=p.useState(null),[x,g]=p.useState(null);p.useEffect(()=>{let N=!0;return h(null),K.stockReconClaims.get(e,t).then(E=>{N&&(i(E.claim),l(E.claim.invoice_number))}).catch(E=>N&&h(String((E==null?void 0:E.message)||E))),K.businessInfo.get(e).then(E=>N&&g(E.business_info)).catch(()=>{}),()=>{N=!1}},[e,t]);function y(N){i(N),r()}async function b(){if(!a)return;const N=o.trim();if(!(!N||N===a.invoice_number)){u(!0),h(null);try{const E=await K.stockReconClaims.setInvoiceNumber(e,t,N);y(E.claim)}catch(E){h(String((E==null?void 0:E.message)||E))}finally{u(!1)}}}async function v(N,E){u(!0),h(null);try{const A=await K.stockReconClaims.updateLine(e,t,N,E);y(A.claim),m(null)}catch(A){h(String((A==null?void 0:A.message)||A))}finally{u(!1)}}async function w(){u(!0),h(null);try{const N=await K.stockReconClaims.setFiled(e,t,(a==null?void 0:a.status)!=="submitted");y(N.claim),r()}catch(N){h(String((N==null?void 0:N.message)||N))}finally{u(!1)}}async function _(){u(!0),h(null);try{const N=await K.stockReconClaims.regenerate(e,t);i(N.claim),m(N.download_url),r()}catch(N){h(String((N==null?void 0:N.message)||N))}finally{u(!1)}}const k=!!(a!=null&&a.is_vat_registered),j=(a==null?void 0:a.lines)??[];return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("button",{type:"button",onClick:n,className:"inline-flex w-fit items-center gap-1 text-body-sm text-text-secondary transition hover:text-text-primary",children:[s.jsx(ff,{className:"h-3.5 w-3.5"})," Back to claims"]}),d?s.jsx("div",{className:"rounded-md border border-outline-error bg-surface-errorSubtle px-3 py-2 text-body-sm text-text-error",children:d}):null,a?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-lg border border-outline-subtle bg-surface p-4 shadow-xs",children:[s.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-body-sm font-medium text-text-primary",children:["Stock Loss Claim · ",MG(a.period)]}),s.jsxs("div",{className:"text-body-xs text-text-secondary",children:[k?"Tax invoice":"Invoice"," · R ",Uc(a.grand_total),k?` (incl R ${Uc(a.total_vat)} VAT)`:""]})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[s.jsx($G,{status:a.status}),s.jsx("button",{type:"button",disabled:c,onClick:w,className:`rounded-md border px-2.5 py-1 text-body-xs font-medium transition disabled:opacity-50 ${a.status==="submitted"?"border-outline-subtle bg-surface text-text-secondary hover:border-outline hover:text-text-primary":"border-outline bg-surface text-text-primary hover:bg-surface-subtle"}`,children:a.status==="submitted"?"Un-file":"Mark filed"})]})]}),a.status==="submitted"&&a.filed_at?s.jsxs("p",{className:"mb-3 text-body-xs text-text-success",children:["Filed with Takealot ",Ao(a.filed_at),"."]}
921):null,s.jsx("label",{className:"block text-body-xs font-medium text-text-secondary",children:"Invoice number"}),s.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[s.jsx("input",{type:"text",value:o,maxLength:60,onChange:N=>l(N.target.value),onKeyDown:N=>{N.key==="Enter"&&b()},className:"min-w-0 flex-1 rounded-md border border-outline-subtle bg-surface px-2.5 py-1.5 text-body-sm text-text-primary outline-none focus:border-outline-brand"}),s.jsx("button",{type:"button",disabled:c||o.trim()===a.invoice_number||!o.trim(),onClick:b,className:"rounded-md border border-outline-subtle bg-surface px-3 py-1.5 text-body-sm font-medium text-text-primary shadow-xs transition hover:bg-surface-subtle disabled:opacity-50",children:"Save"})]}),s.jsx("p",{className:"mt-1 text-body-xs text-text-tertiary",children:"Blank on build uses our default (SR-<seller id>-<month year>). Set your own sequence here."})]}),s.jsx(UYe,{slug:e,info:x,isVatClaim:k}),s.jsxs("div",{className:"overflow-hidden rounded-lg border border-outline-subtle bg-surface shadow-xs",children:[s.jsxs("div",{className:"grid grid-cols-[auto_1fr_auto_auto] items-center gap-3 border-b border-outline-subtle bg-surface-subtle px-3 py-2 text-body-xs font-medium uppercase tracking-wide text-text-tertiary",children:[s.jsx("span",{children:"In"}),s.jsx("span",{children:"Item"}),s.jsx("span",{className:"text-right",children:"Units"}),s.jsx("span",{className:"text-right",children:k?"Price (incl VAT)":"Price"})]}),j.map(N=>{const E=!N.included,A=Number(N.found_units)>0,C=Number(N.units)!==Number(N.original_units);return s.jsxs("div",{className:`grid grid-cols-[auto_1fr_auto_auto] items-center gap-3 border-b border-outline-subtle px-3 py-2.5 last:border-b-0 ${E?"opacity-50":""}`,children:[s.jsx("input",{type:"checkbox",checked:N.included,disabled:c,title:N.included?"Included in the claim":"Excluded",onChange:T=>v(N.id,{included:T.target.checked}),className:"h-4 w-4 accent-intent-brand"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"truncate text-body-sm text-text-primary",children:N.product_title||N.sku||N.tsin_id||"â"}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 text-body-xs text-text-secondary",children:[s.jsxs("span",{children:["TSIN ",N.tsin_id??"â"]}),A?s.jsxs("span",{className:"inline-flex items-center rounded-full border border-outline-warning bg-surface-warningSubtle px-1.5 py-0.5 text-text-primary",children:["Takealot found ",Number(N.found_units)]}):null,C?s.jsxs("span",{className:"text-text-tertiary",children:["(was ",N.original_units,")"]}):null]})]}),s.jsx("input",{type:"number",min:0,max:N.original_units,value:N.units,disabled:c||!N.included,onChange:T=>{const S=Math.max(0,Math.min(N.original_units,Math.floor(Number(T.target.value)||0)));S!==N.units&&v(N.id,{units:S})},className:"w-16 rounded-md border border-outline-subtle bg-surface px-2 py-1 text-right text-body-sm text-text-primary outline-none focus:border-outline-brand disabled:opacity-60"}),s.jsxs("span",{className:"text-right text-body-sm tabular-nums text-text-primary",children:["R ",Uc(N.line_price)]})]},N.id)}),s.jsxs("div",{className:"grid grid-cols-[auto_1fr_auto_auto] items-center gap-3 bg-surface-subtle px-3 py-2.5 text-body-sm font-medium",children:[s.jsx("span",{}),s.jsxs("span",{className:"text-text-secondary",children:["Total",k?" (incl VAT)":""]}),s.jsx("span",{}),s.jsxs("span",{className:"text-right tabular-nums text-text-primary",children:["R ",Uc(a.grand_total)]})]})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("button",{type:"button",disabled:c,onClick:_,className:"inline-flex items-center gap-1.5 rounded-md bg-intent-brand px-3 py-1.5 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover disabled:opacity-50",children:[s.jsx(pa,{className:"h-3.5 w-3.5"})," Regenerate PDF"]}),f?s.jsxs("a",{href:f,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 rounded-md border border-outline-subtle bg-surface px-3 py-1.5 text-body-sm font-medium text-text-primary shadow-xs transition hover:bg-surface-subtle",children:[s.jsx(Dr,{className:"h-3.5 w-3.5"})," Download updated PDF"]}):a.download_url?s.jsxs("a",{href:a.download_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1.5 text-body-sm text-text-secondary transition hover:text-text-primary",children:[s.jsx(Dr,{className:"h-3.5 w-3.5"})," Current PDF"]}):null]})]}):s.jsx("div",{className:"rounded-lg border border-outline-subtle bg-surface px-4 py-8 text-center text-body-sm text-text-secondary",children:"Loading claimâ¦"})]})}function WYe({runs:e,sellerName:t,onResume:n,onRerun:r,onGoProcedures:a}){const[i,o]=p.useState(null),l=p.useMemo(()=>{const u=new Map;for(const d of e)u.has(d.sop_id)||u.set(d.sop_id,[]),u.get(d.sop_id).push(d);return[...u.entries()].map(([d,h])=>({sop_id:d,runs:h,latest:h[0]})).sort((d,h)=>new Date(h.latest.created_at).getTime()-new Date(d.latest.created_at).getTime())}
921,[e]),c=e.filter(u=>u.status==="failed").length;return e.length===0?s.jsxs("div",{className:"rounded-lg border border-dashed border-outline-subtle bg-surface px-4 py-8 text-center",children:[s.jsx(r0,{className:"mx-auto mb-2 h-6 w-6 text-text-tertiary"}),s.jsx("p",{className:"text-body-sm text-text-primary",children:"No runs yet"}),s.jsxs("p",{className:"mt-1 text-body-xs text-text-secondary",children:["Procedures you run for"," ",s.jsx("span",{className:"font-medium text-text-primary",children:t})," show up here for quick re-run and resume."]}),s.jsxs("button",{type:"button",onClick:a,className:"mt-3 inline-flex items-center gap-1.5 rounded-md bg-intent-brand px-3 py-1.5 text-body-sm font-medium text-text-inverse shadow-xs transition hover:bg-intent-brandHover",children:[s.jsx(n0,{className:"h-3.5 w-3.5"})," Browse procedures"]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[s.jsx("h2",{className:"text-body-md font-semibold text-text-primary",children:"Runs"}),s.jsxs("span",{className:"text-body-xs text-text-tertiary",children:[e.length," ",e.length===1?"run":"runs"," · grouped by procedure",c>0?` · ${c} failed`:""]})]}),s.jsx("div",{className:"flex flex-col gap-2",children:l.map(u=>s.jsx(KYe,{group:u,open:i===u.sop_id,onToggle:()=>o(d=>d===u.sop_id?null:u.sop_id),onResume:n,onRerun:r},u.sop_id))})]})}function KL(e){if(e.status==="failed")return null;const t=e.deliverable;return t!=null&&t.summary?t.filename?`${t.summary} · ${t.filename}`:t.summary:null}function KYe({group:e,open:t,onToggle:n,onResume:r,onRerun:a}){var m,x;const{sop_id:i,runs:o,latest:l}=e,c=Fc.find(g=>g.id===i),u=c?Vx[c.icon]:null,d=KL(l),h=l.status==="failed",f=((m=l.deliverable)==null?void 0:m.download_url)??null;return s.jsxs("div",{className:`overflow-hidden rounded-lg border bg-surface shadow-xs ${h?"border-outline-error":"border-outline-subtle"}`,children:[s.jsxs("div",{className:"flex items-center gap-3.5 px-4 py-3.5",children:[s.jsxs("button",{type:"button",onClick:n,"aria-expanded":t,className:"flex min-w-0 flex-1 items-center gap-3.5 text-left",children:[u?s.jsx("span",{className:"shrink-0 text-intent-brand",children:s.jsx(u,{className:"h-[18px] w-[18px]"})}):null,s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsxs("span",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"text-body-sm font-medium text-text-primary",children:n2(i)}),c?s.jsx(kf,{marketplace:Hf(c),size:12}):null,s.jsxs("span",{className:"text-body-xs text-text-tertiary",children:[o.length," ",o.length===1?"run":"runs"]})]}),s.jsx("span",{className:"mt-0.5 flex items-center gap-1.5",children:h?s.jsxs(s.Fragment,{children:[s.jsx(zn,{className:"h-3 w-3 shrink-0 text-intent-error"}),s.jsx("span",{className:"truncate text-body-xs text-text-error",children:"Failed"})]}):d?s.jsx("span",{className:"truncate text-body-xs text-text-body",children:d}):s.jsx("span",{className:"text-body-xs text-text-secondary",children:"Ran in chat â open to see what changed"})})]})]}),s.jsx("span",{className:"hidden w-[110px] shrink-0 text-right text-body-xs text-text-secondary sm:block",children:Ao(l.created_at)}),s.jsxs("span",{className:"flex shrink-0 items-center gap-1",children:[l.status!=="completed"?s.jsx(AYe,{status:l.status}):null,f?s.jsx("a",{href:f,target:"_blank",rel:"noreferrer",download:((x=l.deliverable)==null?void 0:x.filename)??void 0,title:"Download latest deliverable",className:"rounded-md p-1.5 text-text-tertiary transition hover:bg-surface-subtle hover:text-text-primary",children:s.jsx(Dr,{className:"h-3.5 w-3.5"})}
921):null,s.jsx("button",{type:"button",title:"Re-run with same inputs",onClick:()=>a(l),className:"rounded-md p-1.5 text-text-tertiary transition hover:bg-surface-subtle hover:text-text-primary",children:s.jsx(_o,{className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:n,"aria-label":t?"Collapse run history":"Expand run history",className:"rounded-md p-1.5 text-text-tertiary transition hover:bg-surface-subtle hover:text-text-primary",children:t?s.jsx(t0,{className:"h-3.5 w-3.5"}):s.jsx(Pn,{className:"h-3.5 w-3.5"})})]})]}),t?s.jsx("div",{className:"border-t border-outline-subtle bg-surface-subtle",children:o.map(g=>{var w,_;const y=KL(g),b=((w=g.deliverable)==null?void 0:w.download_url)??null,v=!!g.chat_id||!!b;return s.jsxs("div",{className:"flex items-center gap-3.5 border-b border-outline-subtle py-2.5 pl-12 pr-4 last:border-b-0",children:[s.jsx("button",{type:"button",disabled:!v,onClick:()=>r(g),className:"min-w-0 flex-1 truncate text-left text-body-xs text-text-body disabled:cursor-default disabled:opacity-70",children:g.status==="failed"?"Failed â open for detail":y??"Ran in chat â open to see what changed"}),s.jsx("span",{className:"hidden w-[150px] shrink-0 text-right text-body-xs text-text-secondary md:block",children:new Date(g.created_at).toLocaleString()}),s.jsx("span",{className:`w-[70px] shrink-0 text-right text-body-xs font-medium ${g.status==="failed"?"text-text-error":g.status==="completed"?"text-text-success":"text-text-secondary"}`,children:g.status}),b?s.jsx("a",{href:b,target:"_blank",rel:"noreferrer",download:((_=g.deliverable)==null?void 0:_.filename)??void 0,title:"Download deliverable",className:"shrink-0 rounded-md p-1 text-text-tertiary transition hover:bg-surface hover:text-text-primary",children:s.jsx(Dr,{className:"h-3.5 w-3.5"})}):s.jsx("span",{className:"w-[22px] shrink-0"})]},g.id)})}):null]})}function Nj({onClick:e,label:t}){return s.jsxs("button",{onClick:e,className:"flex items-center gap-1 rounded-md border border-outline-subtle px-2 py-1 text-xs text-text-secondary hover:bg-surface-subtle hover:text-text-primary",children:[s.jsx(ff,{className:"h-3 w-3"})," ",t]})}function $i(e){const t=e==null?void 0:e.excluded;if(t===!0||t===1)return!0;if(t===!1||t===0||t==null)return!1;const n=String(t).trim().toLowerCase();return n==="t"||n==="true"||n==="yes"||n==="1"}function HYe(e,t={}){const n=String(t.query||"").trim().toLowerCase(),r=t.maxMarginPct,a=r==null||r===""?null:Number(r),i=Number.isFinite(a);if(!n&&!i)return[];const o=t.includeVat!==!1,l=[];for(const c of e||[])if(!$i(c)&&!(n&&!`${c.title||""} ${c.sku||""} ${c.tsin_id??""}`.toLowerCase().includes(n))){if(i){const u=c.economics||{},d=o?u.margin_pct_incl_vat??u.margin_pct:u.margin_pct;if(d==null||!Number.isFinite(Number(d))||Number(d)>=a)continue}c.id!=null&&l.push(c.id)}return l}function xy(e){if(e==null||e==="")return null;const t=Number(e);return Number.isFinite(t)?t:null}function gy(e,t,n){const r=e?t??n:n;return r==null?null:Number(r)}function Cl(e,t,n={}){const r=n.includeVat!==!1,a=n.profitMetric||"rand",i=(e==null?void 0:e.economics)||{};switch(t){case"product":return(e==null?void 0:e.title)||(e==null?void 0:e.sku)||((e==null?void 0:e.tsin_id)!=null?`TSIN ${e.tsin_id}`:"");case"sku":return(e==null?void 0:e.sku)||((e==null?void 0:e.tsin_id)!=null?`TSIN ${e.tsin_id}`:"");case"current":return xy(e==null?void 0:e.current_price);case"promo_price":return xy(e==null?void 0:e.promo_price);case"qty":return xy(e==null?void 0:e.qty);case"cost":return xy(e==null?void 0:e.unit_cost);case"fees":return gy(r,i.unit_fees_incl_vat,i.unit_fees);case"profit":return a==="pct"?gy(r,i.margin_pct_incl_vat,i.margin_pct):a==="roi"?gy(r,i.roi_pct_incl_vat,i.roi_pct):gy(r,i.unit_profit_incl_vat,i.unit_profit);case"revenue":return i.line_revenue==null?null:Number(i.line_revenue);default:return null}}function Sj(e){if(e==null||e==="")return null;const t=Number(e);return Number.isFinite(t)?t:null}function Rc(e){return e==null?"â":`R${e.toLocaleString("en-ZA",{minimumFractionDigits:0,maximumFractionDigits:2})}`}function VYe(e){return e==null||!Number.isFinite(Number(e))?"â":`${Number(e).toFixed(1)}%`}const FG=.15;function BG(e){return Math.round((Number(e)+Number.EPSILON)*100)/100}function qYe(e){return BG(e*(1+FG))}function GYe(e){return BG(e/(1+FG))}function Lv(e,t,n){const r=e?t??n:n;return r==null?null:Number(r)}function Cj(e,t=!0){if(!e)return null;const n=Lv(t,e.success_fee_incl_vat,e.success_fee),r=Lv(t,e.fulfilment_fee_incl_vat,e.fulfilment_fee),a=e.success_fee_pct;if(n==null&&r==null)return null;const i=[];n!=null&&i.push(`success ${Rc(n)}${a!=null?` (${Number(a)}%)`:""}`),r!=null&&i.push(`fulfilment ${Rc(r)}`);const o=t?e.margin_pct_incl_vat??e.margin_pct:e.margin_pct,l=o!=null&&Number.isFinite(o)?` · ${o.toFixed(0)}% margin`:"";return`Takealot fees: ${i.join(" + ")}${l}`}function Ej({value:e,onCommit:t,disabled:n,placeholder:r,className:a=""}
921){const i=e==null||e===""?"":String(Number(e)),[o,l]=p.useState(i);p.useEffect(()=>{l(e==null||e===""?"":String(Number(e)))},[e]);function c(){const u=o.trim(),d=u===""?null:Number(u),h=e==null||e===""?null:Number(e);if(u!==""&&!Number.isFinite(d)){l(h==null?"":String(h));return}d!==h&&t(d)}return s.jsx("input",{type:"number",inputMode:"decimal",value:o,disabled:n,placeholder:r,onChange:u=>l(u.target.value),onBlur:c,onKeyDown:u=>{u.key==="Enter"&&u.target.blur()},className:`w-24 rounded-md border border-outline-subtle bg-surface px-2 py-1 text-right text-body-sm text-text-primary outline-none focus:border-outline-brand disabled:opacity-60 ${a}`})}function YYe({lines:e,editable:t,includeVat:n,profitMetric:r,onProfitMetricChange:a,savingLine:i,onCommit:o,onDropMatching:l,bulkBusy:c}){const[u,d]=p.useState(""),[h,f]=p.useState(""),[m,x]=p.useState(!1),g=p.useMemo(()=>{const _=Number(h);return h.trim()!==""&&Number.isFinite(_)?_:null},[h]),y=p.useMemo(()=>HYe(e,{query:u,maxMarginPct:g,includeVat:n}),[e,u,g,n]),b=p.useMemo(()=>{const _=u.trim().toLowerCase();return e.filter(k=>!m&&$i(k)?!1:_?`${k.title||""} ${k.sku||""} ${k.tsin_id??""}`.toLowerCase().includes(_):!0)},[e,u,m]),v=e.filter(_=>$i(_)).length;async function w(){if(!(!t||y.length===0||c))try{const _=await l({query:u,maxMarginPct:g});Ae.success(_===1?"Dropped 1 SKU from the workbook":`Dropped ${_} SKUs from the workbook`)}catch(_){Ae.error("Couldn't drop matching SKUs",{description:_ instanceof Error?_.message:String(_)})}}return s.jsxs(V,{className:"min-w-0 overflow-hidden",children:[t?s.jsxs("div",{className:"flex flex-wrap items-end gap-2 border-b border-outline-faint px-3 py-2",children:[s.jsx("div",{className:"min-w-[12rem] flex-1",children:s.jsx(Ni,{value:u,onChange:d,placeholder:"Search title or SKU (e.g. Absolute Decor)"})}),s.jsxs("label",{className:"flex flex-col gap-0.5 text-body-xs text-text-secondary",children:["Drop below % margin",s.jsx("input",{type:"number",inputMode:"decimal",min:0,max:100,step:1,value:h,onChange:_=>f(_.target.value),placeholder:"e.g. 25",className:"w-24 rounded-md border border-outline-subtle bg-surface px-2 py-1 text-right text-body-sm text-text-primary outline-none focus:border-outline-brand"})]}),s.jsxs(W,{type:"button",size:"sm",intent:"neutral",variant:"outline",disabled:c||y.length===0,onClick:()=>void w(),children:[c?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):null,"Drop ",y.length||""," matching"]}),v>0?s.jsx("button",{type:"button",onClick:()=>x(_=>!_),className:"ml-auto text-body-xs text-text-secondary underline-offset-2 hover:text-text-primary hover:underline",children:m?"Hide dropped":`Show ${v} dropped`}):null]}):v>0?s.jsx("div",{className:"flex justify-end border-b border-outline-faint px-3 py-2",children:s.jsx("button",{type:"button",onClick:()=>x(_=>!_),className:"text-body-xs text-text-secondary underline-offset-2 hover:text-text-primary hover:underline",children:m?"Hide dropped":`Show ${v} dropped`})}):null,s.jsx(dt,{className:"min-w-0",rows:b,columns:ZYe({editable:t,includeVat:n,profitMetric:r,onProfitMetricChange:a,savingLine:i,onCommit:o}),getRowKey:_=>_.id,persist:!1,paginate:!1,density:"comfortable",tableClassName:"min-w-[36rem] md:min-w-[72rem]",rowClassName:_=>$i(_)?"opacity-50":void 0,empty:{title:u.trim()?"No SKUs match that search.":m?"No SKUs in this promotion.":"No SKUs in the workbook â restore a dropped row or clear filters."}})]})}function ZYe({editable:e,includeVat:t,profitMetric:n,onProfitMetricChange:r,savingLine:a,onCommit:i}){const o=t?"incl":"ex",l=[{key:"product",label:"Product",sortable:!0,getValue:c=>Cl(c,"product"),sticky:!0,className:"w-[9.5rem] max-w-[42vw] overflow-hidden sm:w-64 sm:max-w-64",render:c=>{var b,v,w;const u=$i(c),d=((b=c.economics)==null?void 0:b.below_cost)??!1,h=((v=c.economics)==null?void 0:v.below_takealot_floor)??!1,f=Cj(c.economics,t),m=(w=c.economics)==null?void 0:w.unit_profit,x=d?`After Takealot fees (net of VAT) you'd lose ${Rc(Math.abs(m??0))}/unit at this price.${f?` ${f}`:""}`:f,g=c.title||c.sku||(c.tsin_id!=null?`TSIN ${c.tsin_id}`:"â"),y=c.sku||(c.tsin_id!=null?`TSIN ${c.tsin_id}`:null);return s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx("span",{className:`min-w-0 truncate text-body-sm font-medium text-text-primary ${u?"line-through":""}`,title:g,children:g}),u?s.jsx("span",{className:"shrink-0 text-body-xs text-text-tertiary",children:"dropped"}):null,!u&&d?s.jsx("span",{title:x??void 0,className:"inline-flex shrink-0 items-center text-text-error",children:s.jsx(zn,{className:"h-3.5 w-3.5"})}):null,!u&&h?s.jsx("span",{title:"Below Takealot's â¥5 units / â¥R7,000 per-row minimum â this line will be rejected on upload.",className:"inline-flex shrink-0 items-center text-text-warning",children:s.jsx(zn,{className:"h-3.5 w-3.5"})}):null,a===c.id?s.jsx(_e,{className:"h-3 w-3 shrink-0 animate-spin text-text-tertiary"}):null]}),c.title&&y?s.jsx("div",{className:"truncate font-mono text-body-xs text-text-tertiary",title:y,children:y}):null]})}},{key:"sku",label:"SKU",sortable:!0,getValue:c=>Cl(c,"sku"),hideBelow:"md",render:c=>s.jsx("span",{className:"whitespace-nowrap text-text-secondary",children:c.sku||(c.tsin_id!=null?`TSIN ${c.tsin_id}`:"â")})},{key:"current",label:"Current",sortable:!0,getValue:c=>Cl(c,"current"),align:"right",hideBelow:"md",render:c=>s.jsx("span",{className:"tabular-nums text-text-secondary",children:Rc(Sj(c.current_price))})},{key:"promo_price",label:"Promo price",sortable:!0,getValue:c=>Cl(c,"promo_price"),align:"right",render:c=>{var h;const u=$i(c),d=((h=c.economics)==null?void 0:h.below_cost)??!1;return s.jsx("div",{className:"flex items-center justify-end",children:s.jsx(Ej,{value:c.promo_price,disabled:!e||u,onCommit:f=>i(c.id,"promo_price",f),className:d&&!u?"border-outline-error":""})})}},{key:"qty",label:"Qty",sortable:!0,getValue:c=>Cl(c,"qty"),align:"right",render:c=>{var h;const u=$i(c),d=((h=c.economics)==null?void 0:h.below_takealot_floor)??!1;return s.jsx("div",{className:"flex items-center justify-end",children:s.jsx(Ej,{value:c.qty,disabled:!e||u,onCommit:f=>i(c.id,"qty",f),className:`w-16 ${d&&!u?"border-outline-warning":""}`})})}},{key:"cost",label:`Cost (${o}-VAT)`,sortable:!0,getValue:c=>Cl(c,"cost"),title:"Leaving this field saves the cost on the product as well as this promotion.",align:"right",render:c=>{const u=$i(c),d=Sj(c.unit_cost),h=t&&d!=null?qYe(d):d,f=Sj(c.unit_cost)==null;return s.jsxs("div",{className:"flex items-center justify-end gap-1",children:[s.jsx(Ej,{value:h,disabled:!e||u,placeholder:"set",onCommit:m=>i(c.id,"unit_cost",m==null?null:t?GYe(m):m),className:"w-20"}),f&&!u?s.jsx("span",{className:"text-body-xs text-text-tertiary",children:"not set"}):null]})}},{key:"fees",label:`Fees / unit (${o}-VAT)`,sortable:!0,getValue:c=>Cl(c,"fees",{includeVat:t}),align:"right",hideBelow:"md",render:c=>{var f,m;const u=$i(c),d=Lv(t,(f=c.economics)==null?void 0:f.unit_fees_incl_vat,(m=c.economics)==null?void 0:m.unit_fees),h=Cj(c.ec
921onomics,t);return s.jsx("span",{className:"tabular-nums text-text-secondary",title:h??void 0,children:u||d==null?"â":Rc(d)})}},{key:"profit",label:n==="pct"?"Margin (%)":n==="roi"?"ROI (%)":`Unit profit (${o}-VAT)`,sortable:!0,getValue:c=>Cl(c,"profit",{includeVat:t,profitMetric:n}),align:"right",header:s.jsxs("select",{value:n,"aria-label":"Show unit profit, margin, or ROI",onChange:c=>r(c.target.value),className:"max-w-[11rem] rounded border border-transparent bg-transparent py-0.5 text-right text-body-xs font-medium uppercase tracking-wide text-text-secondary outline-none hover:border-outline-subtle focus:border-outline-brand",children:[s.jsx("option",{value:"rand",children:"Unit profit (R)"}),s.jsx("option",{value:"pct",children:"Margin (%)"}),s.jsx("option",{value:"roi",children:"ROI (%)"})]}),render:c=>{var v,w,_,k,j,N,E,A,C,T;const u=$i(c),d=Lv(t,(v=c.economics)==null?void 0:v.unit_profit_incl_vat,(w=c.economics)==null?void 0:w.unit_profit),h=t?((_=c.economics)==null?void 0:_.margin_pct_incl_vat)??((k=c.economics)==null?void 0:k.margin_pct):(j=c.economics)==null?void 0:j.margin_pct,f=t?((N=c.economics)==null?void 0:N.roi_pct_incl_vat)??((E=c.economics)==null?void 0:E.roi_pct):(A=c.economics)==null?void 0:A.roi_pct,m=n==="pct"?h:n==="roi"?f:d,x=Cj(c.economics,t),g=(C=c.economics)==null?void 0:C.unit_profit,b=((T=c.economics)==null?void 0:T.below_cost)??!1?`After Takealot fees (net of VAT) you'd lose ${Rc(Math.abs(g??0))}/unit at this price.${x?` ${x}`:""}`:x;return s.jsx("span",{className:`tabular-nums ${u||m==null?"text-text-tertiary":Number(m)<0?"text-text-error":"text-text-success"}`,title:b??void 0,children:u||m==null?"â":n==="pct"||n==="roi"?VYe(m):Rc(m)})}},{key:"revenue",label:"Line revenue",sortable:!0,getValue:c=>Cl(c,"revenue"),align:"right",hideBelow:"md",render:c=>{var h;const u=$i(c),d=((h=c.economics)==null?void 0:h.line_revenue)??null;return s.jsx("span",{className:"tabular-nums text-text-primary",children:u||d==null?"â":Rc(d)})}}];return e&&l.push({key:"actions",label:"",sortable:!1,align:"right",className:"w-12",render:c=>{const u=$i(c),d=a===c.id;return s.jsx("button",{type:"button",disabled:d,title:u?"Restore this SKU":"Drop this SKU from the promotion",onClick:()=>i(c.id,"excluded",!u),className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-text-tertiary transition hover:bg-surface-subtle hover:text-text-primary disabled:opacity-50",children:u?s.jsx(_o,{className:"h-3.5 w-3.5"}):s.jsx(us,{className:"h-3.5 w-3.5"})})}}),l}const UG="gadjet:approvals:profitMetric";function XYe(){try{const e=localStorage.getItem(UG);return e==="pct"||e==="roi"||e==="rand"?e:"rand"}catch{return"rand"}}function JYe(e){try{localStorage.setItem(UG,e)}catch{}}function QYe(e){const t=e.promotion_start_at?cn(e.promotion_start_at):null,n=e.promotion_end_at?cn(e.promotion_end_at):null;if(!t&&!n&&!e.promotion_title)return null;const r=[];return e.promotion_title&&r.push(e.promotion_title),t&&n?r.push(`Goes live ${t} · Ends ${n}`):t?r.push(`Goes live ${t}`):n&&r.push(`Ends ${n}`),r.join(" · ")}function eZe(e){return e==null?"â":`R${e.toLocaleString("en-ZA",{minimumFractionDigits:0,maximumFractionDigits:2})}`}function tZe({includeVat:e,onChange:t}){const n=(r,a,i)=>s.jsx("button",{type:"button","aria-pressed":r,onClick:()=>t(i),className:`rounded px-2.5 py-1 text-body-xs font-medium transition ${r?"bg-surface text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary"}`,children:a});return s.jsxs("div",{className:"inline-flex items-center rounded-md border border-outline-subtle bg-surface-subtle p-0.5",role:"group","aria-label":"VAT basis for fees and profit",children:[n(e,"Incl. VAT",!0),n(!e,"Excl. VAT",!1)]})}function nZe(){var M;const{slug:e="",id:t=""}=jn(),n=Lt(),r=n.kind==="ready"?n.me.role:null,a=r==="am"||r==="super_admin",i=`/sops?tab=approvals${e?`&seller=${encodeURIComponent(e)}`:""}`,[o,l]=p.useState(null),[c,u]=p.useState(!0),[d,h]=p.useState(null),[f,m]=p.useState(null),[x,g]=p.useState(""),[y,b]=p.useState(""),[v,w]=p.useState(!1),[_,k]=p.useState(!0),[j,N]=p.useState(XYe);function E(z){N(z),JYe(z)}const A=p.useCallback(async()=>
921{if(!(!e||!t)){u(!0),h(null);try{const z=await K.promotionDrafts.get(e,t);l(z.draft)}catch(z){h(z instanceof Error?z.message:String(z))}finally{u(!1)}}},[e,t]);p.useEffect(()=>{A()},[A]);const C=(o==null?void 0:o.status)==="draft";async function T(z,G,te){m(z),h(null);try{const re=await K.promotionDrafts.updateLine(e,t,z,{[G]:te});l(re.draft)}catch(re){h(re instanceof Error?re.message:String(re))}finally{m(null)}}async function S(z){g("bulk"),h(null);try{const G=await K.promotionDrafts.excludeMatching(e,t,{query:z.query,max_margin_pct:z.maxMarginPct,include_vat:_});return l(G.draft),G.dropped}finally{g("")}}async function O(){g("approve"),h(null);try{const z=await K.promotionDrafts.approve(e,t);l(z.draft),Ae.success("Promotion approved")}catch(z){h(z instanceof Error?z.message:String(z))}finally{g("")}}async function R(){g("changes"),h(null);try{await K.promotionDrafts.requestChanges(e,t,y.trim()),w(!1),b(""),await A(),Ae.success("Sent to your account manager")}catch(z){h(z instanceof Error?z.message:String(z))}finally{g("")}}async function I(){g("uploaded"),h(null);try{const z=await K.promotionDrafts.markUploaded(e,t);l(z.draft),Ae.success("Marked as uploaded to Takealot")}catch(z){h(z instanceof Error?z.message:String(z))}finally{g("")}}async function $(){g("resend"),h(null);try{const z=await K.promotionDrafts.resend(e,t);l(z.draft),Ae.success("Resent to the seller")}catch(z){h(z instanceof Error?z.message:String(z))}finally{g("")}}async function P(){g("xlsx"),h(null);try{const z=await K.promotionDrafts.downloadWorkbook(e,t);if(z.id!=null)await Ul.download(z.id);else if(z.signed_url)window.location.assign(z.signed_url);else throw new Error("Workbook was built but no download link came back.");Ae.success("Takealot workbook downloaded")}catch(z){const G=z instanceof Error?z.message:String(z),te=z&&typeof z=="object"&&"code"in z?String(z.code):"";h(G),te==="viewer_read_only"?Ae.error("View-only â can't download this workbook",{description:G,duration:12e3}):Ae.error("Couldn't download the workbook",{description:G})}finally{g("")}}const F=o==null?void 0:o.totals,Z=Math.max(0,(((M=o==null?void 0:o.lines)==null?void 0:M.length)??0)-((F==null?void 0:F.excluded_count)??0)),D=_?(F==null?void 0:F.total_profit_incl_vat)??(F==null?void 0:F.total_profit)??null:(F==null?void 0:F.total_profit)??null,H=_?(F==null?void 0:F.total_fees_incl_vat)??(F==null?void 0:F.total_fees):F==null?void 0:F.total_fees,Y=o?QYe(o):null;return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"SOPs",to:"/sops"},{label:"Approvals",to:i},{label:(o==null?void 0:o.task_title)||"Promotion"}]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-y-auto overflow-x-hidden bg-surface-subtle/30",children:s.jsxs("div",{className:"w-full min-w-0 px-4 py-5 md:px-6",children:[d?s.jsx("div",{className:"mb-4 rounded-md border border-outline-error bg-surface-errorSubtle px-3 py-2 text-body-sm text-text-error",children:d}):null,c?s.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-outline-subtle bg-surface px-4 py-8 text-body-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"})," Loading promotionâ¦"]}):o?s.jsxs("div",{className:"flex min-w-0 flex-col gap-4",children:[s.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("h1",{className:"text-lg font-semibold tracking-tight text-text-primary",children:o.task_title||"Promotion"}),s.jsx(sZe,{status:o.status,changesRequestedAt:o.changes_requested_at})]}),Y?s.jsx("p",{className:"mt-1 text-body-sm text-text-secondary",children:Y}):null,s.jsx("p",{className:"mt-1 text-body-sm text-text-secondary",children:rZe(o.status,o.changes_requested_at)})]}),s.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[s.jsx(tZe,{includeVat:_,onChange:k}),s.jsx(aZe,{editable:C,isInternal:a,status:o.status,busy:x,onApprove:O,onToggleNote:()=>w(z=>!z),onResend:$,onMarkUploaded:I,onDownload:P})]})]}),s.jsxs(dr,{children:[s.jsx(Ye,{label:"If this sells out · revenue",value:ge(F==null?void 0:F.total_revenue),hint:`${Z} SKU${Z===1?"":"s"} in the workbook`}),s.jsx(Ye,{label:`If this sells out · profit (${_?"incl":"excl"}. VAT)`,value:ge(D),tone:D!=null&&D<0?"error":"success",hint:F!=null&&F.has_missing_cost?`After Takealot fees · excludes ${F.missing_cost_count} line${F.missing_cost_count===1?"":"s"}
921 with no cost`:H?`After Takealot fees (${eZe(H)})`:"After Takealot fees"}),s.jsx(Ye,{label:"SKUs in promo",value:Z,hint:((F==null?void 0:F.excluded_count)??0)>0?`${F==null?void 0:F.excluded_count} dropped`:"None dropped"}),s.jsx(Ye,{label:"Takealot floor",value:((F==null?void 0:F.below_floor_count)??0)>0?`${F==null?void 0:F.below_floor_count} below`:"All clear",tone:((F==null?void 0:F.below_floor_count)??0)>0?"warn":"success",hint:"â¥5 units and â¥R7,000 per row"})]}),((F==null?void 0:F.has_missing_cost)||((F==null?void 0:F.below_floor_count)??0)>0||((F==null?void 0:F.excluded_count)??0)>0)&&s.jsxs("ul",{className:"space-y-1 text-body-xs text-text-secondary",children:[F!=null&&F.has_missing_cost?s.jsxs("li",{children:["Profit excludes ",F.missing_cost_count," line",F.missing_cost_count===1?"":"s"," with no cost set â fill the cost in to include ",F.missing_cost_count===1?"it":"them","after Takealot fees."]}):null,((F==null?void 0:F.below_floor_count)??0)>0?s.jsxs("li",{className:"text-text-warning",children:[F==null?void 0:F.below_floor_count," line",(F==null?void 0:F.below_floor_count)===1?"":"s"," below Takealot's â¥5 units / â¥R7,000 row minimum â Takealot will reject"," ",(F==null?void 0:F.below_floor_count)===1?"it":"them"," on upload. Informational; you can still approve."]}):null,((F==null?void 0:F.excluded_count)??0)>0?s.jsxs("li",{children:[F==null?void 0:F.excluded_count," SKU",(F==null?void 0:F.excluded_count)===1?"":"s"," dropped â not in the totals or the Takealot workbook. Restore a row to include it again."]}):null]}),v?s.jsxs(V,{padding:"md",children:[s.jsx("label",{className:"block text-body-xs font-medium text-text-secondary",children:"What would you like changed?"}),s.jsx("textarea",{value:y,onChange:z=>b(z.target.value),rows:3,placeholder:"e.g. drop the promo price on the 5kg bag, or remove SKU ABC-123",className:"mt-1 w-full rounded-md border border-outline-subtle bg-surface px-2.5 py-1.5 text-body-sm text-text-primary outline-none focus:border-outline-brand"}),s.jsxs("div",{className:"mt-2 flex justify-end gap-2",children:[s.jsx(W,{type:"button",intent:"neutral",variant:"ghost",size:"sm",onClick:()=>w(!1),children:"Cancel"}),s.jsxs(W,{type:"button",size:"sm",disabled:x!=="",onClick:R,children:[x==="changes"?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):null,"Send to my account manager"]})]})]}):null,s.jsx("p",{className:"text-body-xs text-text-tertiary",children:_?"Incl. VAT matches Takealot's calculator with Include VAT ticked. Switch to Excl. VAT to see what a VAT-registered seller actually keeps.":"Excl. VAT is the real figure for a VAT-registered seller â you owe the VAT on the sale and reclaim the VAT on Takealot's fees. Switch to Incl. VAT to compare against Takealot."}),s.jsx(YYe,{lines:o.lines??[],editable:C,includeVat:_,profitMetric:j,onProfitMetricChange:E,savingLine:f,onCommit:T,onDropMatching:S,bulkBusy:x==="bulk"})]}):s.jsx("div",{className:"rounded-lg border border-outline-subtle bg-surface px-4 py-8 text-center text-body-sm text-text-secondary",children:"This promotion draft couldn't be found."})]})})]})}function rZe(e,t){return e==="draft"?t?"Changes were requested. Drop or edit lines below, then the account manager can resend this to the seller â or approve as-is.":"Review the prices and quantities. Adjust anything you need, drop SKUs you don't want, then approve â your account manager will submit it to Takealot.":e==="uploaded"?"Submitted to Takealot. This promotion is locked.":"Approved â with your account manager. This promotion is locked."}function sZe({status:e,changesRequestedAt:t}){const a={awaiting:{label:"Awaiting seller",cls:"border-outline-warning bg-surface-warningSubtle text-text-primary"},replied:{label:"Seller replied",cls:"border-outline-brand bg-surface-brandSubtle text-text-primary"},approved:{label:"Approved â file it",cls:"border-outline-success bg-surface-successSubtle text-text-success"},uploaded:{label:"Submitted",cls:"border-outline-subtle bg-surface-subtle text-text-secondary"}}[e==="uploaded"?"uploaded":e==="approved"?"approved":t?"replied":"awaiting"];return s.jsx("span",{className:`inline-flex items-center rounded-full border px-2 py-0.5 text-body-xs font-medium ${a.cls}`,children:a.label})}function aZe({editable:e,isInternal:t,status:n,busy:r,onApprove:a,onToggleNote:i,onResend:o,onMarkUploaded:l,onDownload:c}){return s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",disabled:r!=="",onClick:c,children:[r==="xlsx"?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):s.jsx(Dr,{className:"h-3.5 w-3.5"}),"Download workbook"]}),e?s.jsxs(s.Fragment,{children:[s.jsxs(W,{type:"button",size:"sm",disabled:r!=="",onClick:a,children:[r==="approve"?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):s.jsx(Xt,{className:"h-4 w-4"}),"Approve promotion"]}),s.jsx(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",disabled:r!=="",onClick:i,children:"Request changes"}),t?s.jsxs(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",disabled:r!=="",onClick:o,children:[r==="resend"?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):s.jsx(V2,{className:"h-4 w-4"}
921),"Resend to seller"]}):null]}):t&&n==="approved"?s.jsxs(W,{type:"button",size:"sm",disabled:r!=="",onClick:l,children:[r==="uploaded"?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):s.jsx(Xt,{className:"h-4 w-4"}),"Mark uploaded to Takealot"]}):null]})}function iZe(){const{slug:e="",batchId:t=""}=jn(),n=Lt(),r=n.kind==="ready"?n.me.role:"unknown",a=r==="am"||r==="super_admin",[i,o]=p.useState(null),[l,c]=p.useState([]),[u,d]=p.useState(!0),[h,f]=p.useState(""),[m,x]=p.useState(!1),[g,y]=p.useState(null),b=p.useCallback(()=>{!e||!t||(d(!0),K.experiments.getApproval(e,t).then(C=>{o(C.approval),c(C.experiments)}).catch(()=>{o(null),c([])}).finally(()=>d(!1)))},[e,t]);p.useEffect(()=>b(),[b]);const v=l.filter(C=>C.status==="draft"&&!C.excluded),w=l.filter(C=>C.excluded),_=(i==null?void 0:i.status)&&i.status!=="draft";async function k(){var C,T,S;if(!(m||!v.length)){x(!0);try{const O=await K.experiments.approveBatch(e,t),R=((C=O.skipped)==null?void 0:C.length)??0;Ae.success(R?`Scheduled ${((T=O.scheduled)==null?void 0:T.length)??0}. ${R} still drafted (no longer eligible).`:`Scheduled ${((S=O.scheduled)==null?void 0:S.length)??0}. Prices move on the next hourly tick.`),b()}catch(O){Ae.error("Approve failed",{description:String((O==null?void 0:O.message)||O)})}finally{x(!1)}}}async function j(){if(!m){x(!0);try{await K.experiments.requestApprovalChanges(e,t,h),Ae.success("Asked your AM for changes."),b()}catch(C){Ae.error("Couldn't send",{description:String((C==null?void 0:C.message)||C)})}finally{x(!1)}}}async function N(){if(!m){x(!0);try{await K.experiments.resendApproval(e,t),Ae.success("Resent to the seller."),b()}catch(C){Ae.error("Resend failed",{description:String((C==null?void 0:C.message)||C)})}finally{x(!1)}}}async function E(C,T){try{const S=await K.experiments.excludeApprovalSku(e,t,C,T);o(S.approval),c(S.experiments)}catch(S){Ae.error("Couldn't update SKU",{description:String((S==null?void 0:S.message)||S)})}}const A=`/sops?tab=approvals${e?`&seller=${encodeURIComponent(e)}`:""}`;return u?s.jsx("div",{className:"flex items-center justify-center p-12 text-text-secondary",children:s.jsx(_e,{className:"h-5 w-5 animate-spin"})}):s.jsxs("div",{className:"mx-auto max-w-3xl p-4 md:p-6 space-y-4",children:[s.jsx(Pt,{crumbs:[{label:"SOPs",to:"/sops"},{label:"Approvals",to:A},{label:(i==null?void 0:i.task_title)||"Price experiment"}]}),s.jsx(st,{to:A,className:"text-sm text-text-secondary hover:text-text-primary",children:"â Approvals"}),s.jsx("p",{className:"text-sm text-text-secondary",children:"Approving lets Gadjet change these Takealot prices for the window, then revert unless you Keep."}),(i==null?void 0:i.expires_at)&&i.status==="draft"&&s.jsxs("p",{className:"text-xs text-text-secondary",children:["Expires ",new Date(i.expires_at).toLocaleString()," â after that we discard the draft so a stale Approve cannot PATCH."]}),s.jsxs(V,{className:"p-4 space-y-2",children:[v.map(C=>{var T,S;return s.jsxs("div",{className:"flex items-center gap-3 text-sm py-1",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx(Od,{onClick:()=>y({offerId:Number(C.offer_id),title:tc(C)??null}),children:tc(C)}),s.jsxs("div",{className:"text-xs text-text-secondary",children:[ge(Number(C.baseline_price))," â ",ge(Number((T=C.test_prices)==null?void 0:T[0]))," ·"," ",C.window_days,"d · ",(S=C.design)==null?void 0:S.replace("_"," ")]})]}),!_&&s.jsx(W,{type:"button",variant:"ghost",size:"sm",onClick:()=>E(C.id,!0),children:"Drop"})]},C.id)}),w.map(C=>s.jsxs("div",{className:"flex items-center gap-3 text-sm py-1 text-text-secondary",children:[s.jsx("div",{className:"flex-1 line-through",children:tc(C)}),!_&&s.jsx(W,{type:"button",variant:"ghost",size:"sm",onClick:()=>E(C.id,!1),children:"Restore"})]},C.id)),!v.length&&s.jsx("p",{className:"text-sm text-text-secondary",children:"No SKUs left on this draft."})]}),(i==null?void 0:i.status)==="approved"&&s.jsxs("div",{className:"flex items-center gap-2 text-sm text-success-text",children:[s.jsx(Xt,{className:"h-4 w-4"})," Approved â scheduled experiments start on the next hourly tick."]}),(i==null?void 0:i.status)==="draft"&&s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("textarea",{className:"w-full rounded-md border border-outline-subtle bg-surface p-2 text-sm",rows:3,placeholder:"Request changes (optional note for your AM)",value:h,onChange:C=>f(C.target.value)}),s.jsxs("div",{className:"flex flex-wrap gap-2 justify-end",children:[s.jsx(W,{type:"button",variant:"outline",onClick:j,disabled:m,children:"Request changes"}),a&&s.jsxs(W,{type:"button",variant:"outline",onClick:N,disabled:m,children:[s.jsx(V2,{className:"h-3.5 w-3.5 mr-1"}
921)," Resend to seller"]}),s.jsx(W,{type:"button",onClick:k,disabled:m||!v.length,children:m?"Workingâ¦":`Approve ${v.length} SKU${v.length===1?"":"s"}`})]})]}),s.jsx(Wp,{slug:e,offerId:(g==null?void 0:g.offerId)??null,title:g==null?void 0:g.title,open:!!g,onOpenChange:C=>!C&&y(null)})]})}function Am(e){const t=typeof e=="string"?Number(e):e??0;return ge(Number.isFinite(t)?t/100:0)}function oZe({coverage:e,slug:t}){if(!(e!=null&&e.actionable))return null;const n=e.pct_of_spend_trusted??0,r=e.pct_of_spend_understated??0,a=e.pct_of_spend_default??0;return s.jsxs(V,{className:"p-4 border-intent-warning/40",children:[s.jsxs("div",{className:"text-body-sm font-semibold flex items-center gap-1.5",children:[s.jsx(fF,{className:"w-4 h-4 text-text-warning"}),"Break-even is a guess on ",(100-n).toFixed(0),"% of your ad spend"]}),s.jsxs("p",{className:"text-body-sm text-text-secondary mt-1",children:["COGS is on file for ",Am(e.spend_full_cents)," of"," ",Am(e.spend_total_cents)," in advertised spend (",n.toFixed(0),"%). Every keep / cap / pause call below is measured against break-even ROAS, so the rest of the table is directional only."]}),s.jsxs("ul",{className:"mt-2 space-y-1 text-body-xs text-text-tertiary",children:[r>0&&s.jsxs("li",{children:[s.jsxs("span",{className:"text-text-error font-medium",children:[r.toFixed(0),"% of spend (",Am(e.spend_fees_only_cents),")"]})," ","has Takealot fees but no product cost â break-even is computed"," ",s.jsx("strong",{children:"too low"})," there, so a SKU can read profitable while it is not."]}),a>0&&s.jsxs("li",{children:[a.toFixed(0),"% of spend (",Am(e.spend_default_cents),") has neither fees nor cost on file â those rows fall back to the flat 3à rule of thumb."]})]}),e.top_gaps.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-body-xs text-text-secondary mb-1",children:"Fill these first â biggest advertised spend with no usable margin:"}),s.jsx("ul",{className:"space-y-0.5",children:e.top_gaps.map((i,o)=>s.jsxs("li",{className:"text-body-xs",children:[s.jsx("span",{className:"font-mono text-text-secondary",children:i.sku??"â"})," ",s.jsxs("span",{className:"text-text-tertiary",children:[i.product_name??""," · ",Am(i.spend_cents),i.cogs_on_file?" · cost on file but no sales in window":""]})]},`${i.sku??i.tsin??o}`))})]}),s.jsx("div",{className:"mt-3",children:s.jsx(W,{intent:"brand",variant:"outline",size:"sm",asChild:!0,children:s.jsx(st,{to:`/sellers/${t}/inventory?upload=cogs`,children:"Upload COGS"})})})]})}async function zG(e){if(e.export_id!=null){await Ul.download(e.export_id);return}if(e.signed_url){lZe(e.signed_url,e.filename);return}Ae.error("The file was built but no download link came back â check the Exports drawer.")}function lZe(e,t){const n=document.createElement("a");n.href=e,t&&(n.download=t),n.rel="noopener",n.style.display="none",document.body.appendChild(n),n.click(),document.body.removeChild(n)}const cZe=[{kind:"pause",label:"Pause list",hint:"SKUs burning spend â out of stock, buybox lost, or under break-even"},{kind:"negatives",label:"Negative keywords",hint:"Shopper queries taking spend that you don't target"},{kind:"bids",label:"Bid changes",hint:"Keywords below floor, under-funded, or wasteful, with a suggested bid"}];function uZe({slug:e,days:t,counts:n}){const[r,a]=p.useState(null),i=p.useCallback(async l=>{if(!r){a(l);try{const c=await K.ads.changeSheet(e,{kind:l,days:t});if(!c.ok){Ae.info(c.message||"Nothing to export.");return}Ae.success(`${c.label} â ${c.row_count} row${c.row_count===1?"":"s"}.`),await zG(c)}catch(c){Ae.error(String((c==null?void 0:c.message)||c))}finally{a(null)}}},[e,t,r]);return(n?Object.values(n).reduce((l,c)=>l+c,0):null)===0?null:s.jsxs(V,{className:"p-4",children:[s.jsx("div",{className:"text-body-sm font-semibold",children:"Work sheets"}),s.jsx("p",{className:"text-body-xs text-text-tertiary mt-0.5",children:"The findings below as a spreadsheet to action in your Takealot portal. Not a portal upload template â a list to work down."}),s.jsx("div",{className:"flex flex-wrap gap-2 mt-3",children:cZe.map(l=>{const c=n==null?void 0:n[l.kind],u=c===0;return s.jsxs(W,{intent:"neutral",variant:"outline",size:"sm",title:u?`Nothing to action in the last ${t} days`:l.hint,disabled:r!=null||u,onClick:()=>i(l.kind),children:[r===l.kind?s.jsx(_e,{className:"w-4 h-4 animate-spin"}):s.jsx(Dr,{className:"w-4 h-4"}),l.label,c!=null&&s.jsxs("span",{className:"text-text-tertiary",children:["· ",c]})]},l.kind)})})]})}const Aj=8,HL=30;function VL(e){if(e.status==="acknowledged")return"acknowledged";if(e.status==="muted"){if(!e.muted_until)return"muted";const t=Math.ceil((new Date(e.muted_until).getTime()-Date.now())/864e5);return t>0?`muted ${t}d`:"muted"}return null}function dZe({alerts:e,slug:t,onChanged:n}){const[r,a]=p.useState(null),i=p.useMemo(()=>{const c=u=>u.status==="open"||u.status==null?0:1;return[...e].sort((u,d)=>c(u)-c(d))},[e]),o=p.useCallback(async(c,u)=>{const d=c.alert_key;if(!(!d||r)){a(d);try{const h=await K.ads.setAlertState(t,{alert_key:d,action:u,days:u==="mute"?HL:void 0});if(!h.ok){Ae.error(h.error==="not_migrated"?"Not available yet.":"Couldn't update that alert.");return}n==null||n()}catch(h){Ae.error(String((h==null?void 0:h.message)||h))}finally{a(null)}}},[t,r,n]);if(!i.length)return null;const l=i.filter(c=>c.status==="open"||c.status==null).length;return s.jsxs(V,{className:"p-4 border-intent-warning/40",children:[s.jsxs("div",{className:"text-body-sm font-semibold flex items-center gap-1.5 mb-2",children:[s.jsx(zn,{className:"w-4 h-4 text-text-warning"}),l," issue",l===1?"":"s"," this window",l<i.length&&s.jsxs("span",{className:"font-normal text-text-tertiary",children:["· ",i.length-l," silenced"]})]}),s.jsx("ul",{className:"space-y-1.5",children:i.slice(0,Aj).map((c,u)=>{const d=c.status!=null&&c.status!=="open",h=c.alert_key??`${c.kind}-${u}`,f=r===c.alert_key;return s.jsxs("li",{className:B("text-body-sm flex items-start justify-between gap-3",d&&"opacity-55"),children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("span",{className:c.severity==="high"&&!d?"text-text-error font-medium":"text-text-primary",children:c.title}),c.detail?s.jsxs("span",{className:"text-text-tertiary",children:[" â ",c.detail]}):null,VL(c)&&s.jsxs("span",{className:"ml-1.5 text-body-xs text-text-tertiary",children:["(",VL(c),")"]})]}),c.alert_key&&s.jsx("div",{className:"flex items-center gap-1 shrink-0",children:f?s.jsx(_e,{className:"w-4 h-4 animate-spin text-text-tertiary"}):d?s.jsx(W,{intent:"neutral",variant:"ghost",size:"sm",title:"Start telling me about this again",onClick:()=>o(c,"unmute"),children:s.jsx(vd,{className:"w-3.5 h-3.5"})}):s.jsxs(s.Fragment,{children:[s.jsx(W,{intent:"neutral",variant:"ghost",size:"sm",title:"I've seen this â stop the daily chat reminder until it escalates",onClick:()=>
921o(c,"ack"),children:s.jsx(fn,{className:"w-3.5 h-3.5"})}),s.jsx(W,{intent:"neutral",variant:"ghost",size:"sm",title:`Mute for ${HL} days`,onClick:()=>o(c,"mute"),children:s.jsx(mte,{className:"w-3.5 h-3.5"})})]})})]},h)})}),i.length>Aj&&s.jsxs("div",{className:"text-body-xs text-text-tertiary mt-2",children:["+",i.length-Aj," more"]}),s.jsx("p",{className:"text-body-xs text-text-tertiary mt-2",children:"Acknowledging or muting stops the daily chat reminder. Issues stay listed here until they clear, and an acknowledged one speaks up again if it gets worse."})]})}const Tj=6,Oj=8;function r2(e){const t=typeof e=="string"?Number(e):typeof e=="number"?e:0;return ge(Number.isFinite(t)?t/100:0)}const hZe={improved:{label:"improved",className:"text-text-success"},worse:{label:"worse",className:"text-text-error"},unchanged:{label:"no change",className:"text-text-tertiary"},not_measurable:{label:"too little data",className:"text-text-tertiary"}};function fZe({entry:e}){var a,i;if(e.decision==="snoozed")return s.jsx("span",{className:"text-text-tertiary",children:"snoozed â nothing to score"});if(!e.measured_at){const o=e.measure_after?new Date(e.measure_after):null;if(!o)return s.jsx("span",{className:"text-text-tertiary",children:"â"});const l=Math.ceil((o.getTime()-Date.now())/864e5);return s.jsx("span",{className:"text-text-tertiary",children:l>0?`measuring â ${l}d to go`:"measuring"})}const t=e.outcome_verdict?hZe[e.outcome_verdict]:null,n=r2((a=e.baseline)==null?void 0:a.spend_cents),r=r2((i=e.outcome)==null?void 0:i.spend_cents);return s.jsxs("span",{className:t==null?void 0:t.className,children:[(t==null?void 0:t.label)??"measured"," · ",n," â ",r," spend"]})}function mZe({slug:e,windowDays:t,recommendations:n,ledger:r,onChanged:a}){const[i,o]=p.useState(null),l=n??[],c=r??[],u=p.useCallback(async(d,h)=>{if(!i){o(d);try{const f=await K.ads.decideRecommendation(e,{rec_key:d,decision:h,window_days:t});if(!f.ok){Ae.info(f.message||"Couldn't record that decision.");return}a==null||a()}catch(f){Ae.error(String((f==null?void 0:f.message)||f))}finally{o(null)}}},[e,t,i,a]);return!l.length&&!c.length?null:s.jsxs(V,{className:"p-4 space-y-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-body-sm font-semibold",children:"Decisions"}),s.jsx("p",{className:"text-body-xs text-text-tertiary mt-0.5",children:"Mark what you've actioned. We re-measure each one 14 days later and record the result â including the ones you pass on."})]}),l.length>0&&s.jsxs("ul",{className:"space-y-1.5",children:[l.slice(0,Tj).map(d=>s.jsxs("li",{className:"text-body-sm flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("span",{className:"text-text-primary",children:d.title}),d.detail&&s.jsxs("span",{className:"text-text-tertiary",children:[" â ",d.detail]}),s.jsxs("span",{className:"text-text-tertiary",children:[" · ",r2(d.spend_cents)]})]}),s.jsx("div",{className:"flex items-center gap-1 shrink-0",children:i===d.rec_key?s.jsx(_e,{className:"w-4 h-4 animate-spin text-text-tertiary"}):s.jsxs(s.Fragment,{children:[s.jsx(W,{intent:"success",variant:"ghost",size:"sm",title:"I've done this",onClick:()=>u(d.rec_key,"accepted"),children:s.jsx(fn,{className:"w-3.5 h-3.5"})}),s.jsx(W,{intent:"neutral",variant:"ghost",size:"sm",title:"Not doing this",onClick:()=>u(d.rec_key,"dismissed"),children:s.jsx(Bn,{className:"w-3.5 h-3.5"})}),s.jsx(W,{intent:"neutral",variant:"ghost",size:"sm",title:"Ask me again in 14 days",onClick:()=>u(d.rec_key,"snoozed"),children:s.jsx(pu,{className:"w-3.5 h-3.5"})})]})})]},d.rec_key)),l.length>Tj&&s.jsxs("li",{className:"text-body-xs text-text-tertiary",children:["+",l.length-Tj," more open"]})]}),c.length>0&&s.jsxs("div",{className:"border-t border-outline-subtle pt-3",children:[s.jsx("div",{className:"text-body-xs uppercase tracking-wider text-text-tertiary mb-1.5",children:"Decided"}),s.jsx("ul",{className:"space-y-1",children:c.slice(0,Oj).map(d=>s.jsxs("li",{className:"text-body-xs flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("span",{className:B("font-medium",d.decision==="accepted"?"text-text-success":"text-text-tertiary"),children:d.decision})," ",s.jsx("span",{className:"text-text-secondary",children:d.title})]}),s.jsx("div",{className:"shrink-0",children:s.jsx(fZe,{entry:d})})]},d.id))}),c.length>Oj&&s.jsxs("div",{className:"text-body-xs text-text-tertiary mt-1",children:["+",c.length-Oj," more"]})]})]})}const qL=[7,14,30,90];function nr(e){const t=typeof e=="string"?Number(e):e??0;return Number.isFinite(t)?t/100:0}function an(e){const t=typeof e=="string"?Number(e):e??0;return Number.isFinite(t)?t:0}function ia(e){if(e==null||e==="")return null;const t=typeof e=="string"?Number(e):e;return Number.isFinite(t)?t:null}function sl(e){const t=ia(e);return t!=null&&t>0?`${t.toFixed(2)}Ã`:"â"}function Lw(e){const t=ia(e);return t==null?"â":`${((t>1?t/100:t)*100).toFixed(2)}%`}function eT(e){const t=ia(e);return t==null?null:t>1?t/100:t}function Ij(e,t){const n=ia(e),r=ia(t);if(n==null||r==null||r===0)return null;const a=(n-r)/Math.abs(r);return{text:`${a>=0?"+":""}${(a*100).toFixed(0)}%`,positive:a>=0}}const GL={scale:"bg-intent-success/10 text-text-success",healthy:"bg-intent-brand/10 text-intent-brand",marginal:"bg-intent-warning/10 text-text-warning",loss:"bg-intent-danger/10 text-text-error",unknown:"bg-surface-subtle text-text-tertiary"};function tT({band:e}){const t=e||"unknown",n=t==="unknown"?"â":t;return s.jsx("span",{className:B("inline-flex px-1.5 py-0.5 rounded text-[11px] font-medium capitalize",GL[t]||GL.unknown),children:n})}function pZe({product:e}
921){const t=e.break_even_basis??(e.cogs_known?"full":"default");return t==="full"?null:t==="fees_only"?s.jsx("div",{className:"text-body-xs text-text-warning",children:"fees only â excl. cost"}):s.jsx("div",{className:"text-body-xs text-text-tertiary",children:"est. 3Ã"})}function nT({value:e}){if(!e||e==="hold")return s.jsx("span",{className:"text-text-tertiary",children:"hold"});const t=e==="scale"||e==="raise"?"text-text-success":e==="pause"||e==="pause_oos"||e==="pause_buybox"||e==="lower"||e==="below_floor"?"text-text-error":e==="cap"||e==="fix_listing"||e==="negate"?"text-text-warning":"text-text-secondary";return s.jsx("span",{className:B("font-medium",t),children:e.replaceAll("_"," ")})}function xZe({slug:e}){const[t,n]=it("days","30"),r=Number(t),a=qL.includes(r)?r:30,[i,o]=p.useState(null),[l,c]=p.useState(null),[u,d]=p.useState(!0),h=p.useCallback(()=>{d(!0),K.ads.performance(e,a).then(m=>{o(m),c(null)}).catch(m=>c(String((m==null?void 0:m.message)||m))).finally(()=>d(!1))},[e,a]);if(p.useEffect(()=>{o(null),c(null),h()},[h]),u&&!i)return s.jsxs("div",{className:"w-full px-4 py-10 flex items-center gap-2 text-text-tertiary text-body-sm",children:[s.jsx(_e,{className:"w-4 h-4 animate-spin"})," Loading ad performanceâ¦"]});if(l)return s.jsx("div",{className:"w-full px-4 py-10",children:s.jsxs(V,{className:"p-4 text-body-sm text-intent-danger",children:["Couldn't load ad performance: ",l]})});const f=!!(i!=null&&i.data_present);return s.jsxs("div",{className:"w-full px-4 py-6 space-y-6",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[s.jsx("div",{className:"flex items-center gap-1 rounded-md border border-outline-subtle p-0.5",children:qL.map(m=>s.jsxs("button",{type:"button",onClick:()=>n(String(m)),className:B("px-2.5 py-1 text-body-xs rounded",a===m?"bg-surface-inverse text-text-inverse":"text-text-secondary hover:text-text-primary"),children:[m,"d"]},m))}),s.jsx(gZe,{data:i})]}),s.jsx(bZe,{slug:e,osmos:i==null?void 0:i.osmos,campaigns:i==null?void 0:i.campaigns,onImported:h,compact:f}),f?s.jsxs(s.Fragment,{children:[s.jsx(dZe,{alerts:i.alerts??[],slug:e,onChanged:h}),s.jsx(oZe,{coverage:i.cogs_coverage,slug:e}),s.jsx(uZe,{slug:e,days:a,counts:i.change_sheets}),s.jsx(mZe,{slug:e,windowDays:a,recommendations:i.recommendations,ledger:i.ledger,onChanged:h}),s.jsx(vZe,{data:i}),s.jsx(wZe,{data:i}),s.jsx(_Ze,{data:i}),s.jsx(kZe,{data:i}),s.jsx(NZe,{data:i}),s.jsx(jZe,{data:i}),s.jsx(SZe,{data:i}),s.jsx(CZe,{data:i}),s.jsx(EZe,{data:i}),s.jsx(AZe,{data:i}),s.jsx(TZe,{data:i}),s.jsx(OZe,{data:i})]}):s.jsx(yZe,{osmos:i==null?void 0:i.osmos})]})}function gZe({data:e}){const t=e==null?void 0:e.coverage;if(!t)return null;const n=[];return t.has_osmos&&n.push("live Osmos"),t.has_campaign&&n.push("campaigns"),t.has_product&&n.push("products"),t.has_keyword_facts?n.push("keyword ROAS"):n.push("no keyword ROAS export yet"),t.has_search_queries?n.push("search queries"):n.push("no search-query export yet"),t.has_category_sov&&n.push("category share of voice"),s.jsx("div",{className:"text-body-xs text-text-tertiary",children:n.join(" · ")})}function yZe({osmos:e}){const t=e==null?void 0:e.grab_triggered,n=(e==null?void 0:e.enabled)&&(e==null?void 0:e.jwt_valid);return s.jsxs(V,{className:"p-8 text-center",children:[s.jsx(oF,{className:"w-8 h-8 mx-auto text-text-tertiary mb-3"}),s.jsx("div",{className:"text-body font-semibold mb-1",children:"No ad data yet"}),s.jsx("p",{className:"text-body-sm text-text-tertiary max-w-md mx-auto",children:t?"We're pulling your latest Sponsored Ads data from your connected Takealot account now â refresh in a moment. You can also upload an export above to seed it instantly.":n?"Upload a Takealot Sponsored Ads export above to get started, or open your Takealot seller portal with the Gadjet extension to sync live.":"Upload a Takealot Sponsored Ads export above to get started. Install the Gadjet Chrome extension to sync live ad data automatically."})]})}function bZe({slug:e,osmos:t,campaigns:n,onImported:r,compact:a}
921){const i=p.useRef(null),[o,l]=p.useState(!1),[c,u]=p.useState(!1),[d,h]=p.useState(null),[f,m]=p.useState(""),x=p.useCallback(async(b,v)=>{l(!0);try{const w=await K.ads.import(e,b,v);w.ok?(Ae.success(w.already_imported?`${b.name} was already imported.`:`Imported ${w.saved??0} row(s) from ${b.name}${w.report_type?` (${w.report_type})`:""}.`),h(null),m(""),r()):w.error==="needs_campaign"?h(b):Ae.error(w.message||`Couldn't import ${b.name}.`)}catch(w){Ae.error(`Upload failed: ${String((w==null?void 0:w.message)||w)}`)}finally{l(!1),i.current&&(i.current.value="")}},[e,r]),g=p.useCallback(async b=>{!b||o||await x(b)},[o,x]),y=(n??[]).map(b=>b.campaign_name).filter(Boolean);return s.jsxs(s.Fragment,{children:[s.jsxs(V,{className:B("p-4 border-dashed transition-colors",c?"border-outline-brand bg-brand-500/5":"border-outline-subtle"),onDragOver:b=>{b.preventDefault(),u(!0)},onDragLeave:()=>u(!1),onDrop:b=>{var v;b.preventDefault(),u(!1),g((v=b.dataTransfer.files)==null?void 0:v[0])},children:[s.jsx("input",{ref:i,type:"file",accept:".csv,.xlsx,.xls,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",className:"hidden",onChange:b=>{var v;return g((v=b.target.files)==null?void 0:v[0])}}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("div",{className:"flex-1 min-w-[220px]",children:[s.jsxs("div",{className:"text-body-sm font-semibold flex items-center gap-1.5",children:[s.jsx(ti,{className:"w-4 h-4"}),a?"Upload another Sponsored Ads export":"Upload a Takealot Sponsored Ads export"]}),s.jsxs("div",{className:"text-body-xs text-text-tertiary mt-0.5",children:["Drag a .csv / .xlsx export here, or click to choose. Keyword Performance and Search Query reports unlock per-keyword ROAS and query harvest. Campaign-scoped files ask for a campaign name.",t!=null&&t.jwt_valid&&(t!=null&&t.enabled)?" Live Osmos sync is connected.":""]})]}),s.jsxs(W,{variant:"outline",intent:"neutral",disabled:o,onClick:()=>{var b;return(b=i.current)==null?void 0:b.click()},children:[o?s.jsx(_e,{className:"w-4 h-4 animate-spin"}):s.jsx(ti,{className:"w-4 h-4"}),o?"Importingâ¦":"Choose file"]})]}),t&&s.jsxs("div",{className:"mt-2 text-body-xs text-text-tertiary flex items-center gap-1.5",children:[s.jsx(hF,{className:"w-3.5 h-3.5"}),t.jwt_valid?t.grab_triggered?"Syncing live ad data from your connected Takealot accountâ¦":`Live sync connected${t.last_grab_at?` · last synced ${Ca(t.last_grab_at)}`:""}.`:"Live sync not connected â install the Gadjet extension and open your Takealot portal to enable automatic data."]})]}),s.jsx(js,{open:!!d,onOpenChange:b=>{b||h(null)},children:s.jsxs(Ns,{size:"md",children:[s.jsxs(La,{children:[s.jsx(ma,{children:"Which campaign is this export for?"}),s.jsx(hc,{children:"Takealot's campaign-scoped reports don't name the campaign inside the file. Pick one so we can store the rows against the right campaign."})]}),s.jsxs(Oa,{className:"space-y-3",children:[y.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5",children:y.map(b=>s.jsx("button",{type:"button",onClick:()=>m(b),className:B("px-2 py-1 rounded border text-body-xs",f===b?"border-outline-brand bg-brand-500/10 text-text-primary":"border-outline-subtle text-text-secondary hover:border-outline-strong"),children:b},b))}),s.jsx(Re,{value:f,onChange:b=>m(b.target.value),placeholder:"Campaign name"})]}),s.jsxs(da,{children:[s.jsx(W,{variant:"ghost",intent:"neutral",onClick:()=>h(null),children:"Cancel"}),s.jsx(W,{intent:"brand",disabled:!f.trim()||o||!d,onClick:()=>d&&x(d,f.trim()),children:"Import"})]})]})})]})}function vZe({data:e}){const t=e.totals,n=e.prior;if(!t)return null;const r=(e.series??[]).map(i=>nr(i.spend_cents)),a=(e.series??[]).map(i=>an(i.roas));return s.jsxs("div",{className:"space-y-3",children:[s.jsxs(dr,{cols:4,children:[s.jsx(Ye,{label:`Ad spend (${e.window_days}d)`,value:ge(nr(t.spend_cents)),delta:Ij(t.spend_cents,n==null?void 0:n.spend_cents)??void 0,deltaIsBadWhenUp:!0}),s.jsx(Ye,{label:"Ad revenue",value:ge(nr(t.revenue_cents)),delta:Ij(t.revenue_cents,n==null?void 0:n.revenue_cents)??void 0}),s.jsx(Ye,{label:"Blended ROAS",value:sl(t.roas),tone:an(t.roas)>=3?"success":an(t.roas)>0&&an(t.roas)<2?"error":"warn",delta:Ij(t.roas,n==null?void 0:n.roas)??void 0,hint:t.direct_roas?`direct ${sl(t.direct_roas)}`:void 0}),s.jsx(Ye,{label:"Orders",value:de(an(t.orders)),hint:`${de(an(t.clicks))} clicks · ${Lw(t.ctr)} CTR`})]}),r.length>=2&&s.jsxs(V,{className:"px-4 py-3 flex flex-wrap items-center gap-6",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-tertiary",children:"Spend"}),s.jsx(Ws,{data:r,width:160,height:32,className:"text-text-primary"})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-tertiary",children:"ROAS"}),s.jsx(Ws,{data:a,width:160,height:32,className:"text-intent-brand"})]}),s.jsxs("div",{className:"text-body-xs text-text-tertiary",children:["CPC ",t.cpc_cents?ge(nr(t.cpc_cents)):"â",n?` · prior window ${ge(nr(n.spend_cents))} at ${sl(n.roas)}`:""]})]})]})}function wZe({data:e}){const t=e.budget,n=e.wallet;return!t&&!n?null:s.jsxs(dr,{cols:3,children:[t?s.jsx(Ye,{label:"Daily budget (Data Insights)",value:ge(t.daily_budget),tone:t.hitting_cap?"warn":"default",hint:t.hitting_cap?`Hitting the cap â ${ge(t.actual_spend)} vs ${ge(t.expected_spend)} expected`:`${ge(t.actual_spend)} spent vs ${ge(t.expected_spend)} expected`}):null,n?s.jsx(Ye,{label:"Ads wallet",value:n.remaining_balance!=null?ge(n.remaining_balance):"â",hint:n.runway_days!=null?`~${n.runway_days} days of runway at this spend rate`:n.status??void 0,tone:n.runway_days!=null&&n.runway_days<7?"warn":"default"}):null,n!=null&&n.incentive_balance?s.jsx(Ye,{label:"Incentive balance",value:ge(n.incentive_balance)}):null]})}function _Ze({data:e}){const t=e.totals;if(!t)return null;const n=an(t.same_sku_revenue_cents)+an(t.other_sku_revenue_cents)>0,r=an(t.view_products)+an(t.add_to_cart)+an(t.detail_page_views)>0;return!n&&!r?null:s.jsxs(V,{className:"p-4",children:[s.jsx("div",{className:"text-body-sm font-semibold mb-2",children:"Direct vs halo · funnel"}),s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3 text-body-sm",children:[n&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-body-xs text-text-tertiary",children:"Same-SKU revenue"}),s.jsx("div",{className:"tabular-nums",children:ge(nr(t.same_sku_revenue_cents))})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-body-xs text-text-tertiary",children:"Other-SKU (halo)"}),s.jsx("div",{className:"tabular-nums",children:ge(nr(t.other_sku_revenue_cents))})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-body-xs text-text-tertiary",children:"Direct ROAS"}),s.jsx("div",{className:"tabular-nums",children:sl(t.direct_roas)})]})]}),r&&s.jsx(s.Fragment,{children:s.jsxs("div",{children:[s.jsx("div",{className:"text-body-xs text-text-tertiary",children:"Clicks â PDP views â ATC â orders"}),s.jsxs("div",{className:"tabular-nums",children:[de(an(t.clicks))," â ",de(an(t.view_products)||an(t.detail_page_views))," â"," ",de(an(t.add_to_cart))," â ",de(an(t.orders))]})]})})]}),n&&s.jsx("p",{className:"text-body-xs text-text-tertiary mt-2",children:"Blended ROAS credits halo sales (other SKUs / same category). Direct ROAS is same-SKU only â use that when deciding whether a campaign is actually paying for itself."})]})}function kZe({data:e}){const t=e.reallocation??[];return t.length?s.jsxs(V,{className:"p-4",children:[s.jsx("div",{className:"text-body-sm font-semibold mb-1",children:"Where the next rand should go"}),t.map((n,r)=>s.jsx("p",{className:"text-body-sm text-text-secondary",children:n.rationale},r))]}):null}function jZe({data:e}){const t=e.category_sov??[];return t.length?s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-4 py-3 border-b border-outline-subtle",children:[s.jsx("div",{className:"text-body-sm font-semibold",children:"Category share of voice"}),s.jsx("div",{className:"text-body-xs text-text-tertiary",children:"From a campaign Category Performance export. Portal-
921only."})]}),s.jsx(dt,{rows:t,columns:[{key:"category",label:"Category",sortable:!0,className:"truncate max-w-[360px]",getValue:n=>[n.cat_l1,n.cat_l2,n.cat_l3].filter(Boolean).join(" ⺠")||"â"},{key:"campaign",label:"Campaign",sortable:!0,className:"text-body-xs text-text-secondary",getValue:n=>n.campaign_name},{key:"sov",label:"SOV",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>{const r=ia(n.share_of_voice);return r==null?null:r>1?r/100:r},render:n=>{const r=ia(n.share_of_voice);return r==null?"â":`${r>1?r.toFixed(1):(r*100).toFixed(1)}%`}},{key:"spend",label:"Spend",sortable:!0,align:"right",format:"zar",getValue:n=>nr(n.spend_cents)},{key:"roas",label:"ROAS",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>ia(n.roas),render:n=>sl(n.roas)}],getRowKey:n=>`${[n.cat_l1,n.cat_l2,n.cat_l3].filter(Boolean).join(" ⺠")}-${n.campaign_name??""}`,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No category share-of-voice rows."}})]}):null}function NZe({data:e}){const t=e.campaigns??[];return s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-4 py-3 border-b border-outline-subtle flex items-center justify-between",children:[s.jsxs("div",{className:"text-body-sm font-semibold",children:["Campaigns · last ",e.window_days," days"]}),s.jsxs("div",{className:"text-body-xs text-text-tertiary",children:[t.length," campaign(s)"]})]}),s.jsx(dt,{rows:t,columns:[{key:"campaign",label:"Campaign",sortable:!0,sticky:!0,getValue:n=>n.campaign_name||n.campaign_id,render:n=>n.campaign_name||n.campaign_id||"â"},{key:"spend",label:"Spend",sortable:!0,align:"right",format:"zar",getValue:n=>nr(n.spend_cents)},{key:"revenue",label:"Revenue",sortable:!0,align:"right",format:"zar",getValue:n=>nr(n.revenue_cents)},{key:"direct_roas",label:"Direct ROAS",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>ia(n.direct_roas),render:n=>sl(n.direct_roas)},{key:"roas",label:"ROAS",sortable:!0,align:"right",className:"tabular-nums font-medium",getValue:n=>ia(n.roas),render:n=>sl(n.roas)},{key:"band",label:"Band",render:n=>s.jsx(tT,{band:n.roas_band})},{key:"clicks",label:"Clicks",sortable:!0,align:"right",format:"number",getValue:n=>an(n.clicks)},{key:"ctr",label:"CTR",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>eT(n.ctr),render:n=>Lw(n.ctr)},{key:"action",label:"Action",render:n=>s.jsx(nT,{value:n.action})}],getRowKey:n=>String(n.campaign_id??n.campaign_name??""),paginate:!0,persist:!1,tableClassName:"text-body-sm",empty:{title:"No campaign-level rows in this window."}})]})}function SZe({data:e}){const t=e.products??[];return s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-4 py-3 border-b border-outline-subtle flex items-center justify-between",children:[s.jsxs("div",{className:"text-body-sm font-semibold",children:["Advertised products
921· last ",e.window_days," days"]}),s.jsxs("div",{className:"text-body-xs text-text-tertiary",children:[t.length," product(s)"]})]}),s.jsx(dt,{rows:t,columns:[{key:"product",label:"Product",sortable:!0,sticky:!0,getValue:n=>n.product_name||n.sku||n.tsin||n.plid,render:n=>s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"truncate max-w-[320px]",children:n.product_name||n.sku||n.tsin||n.plid||"â"}),s.jsx("div",{className:"text-body-xs text-text-tertiary truncate max-w-[320px]",children:[n.sku,n.category].filter(Boolean).join(" · ")})]})},{key:"campaign",label:"Campaign",sortable:!0,className:"text-body-xs text-text-secondary",getValue:n=>n.campaign_name},{key:"spend",label:"Spend",sortable:!0,align:"right",format:"zar",getValue:n=>nr(n.spend_cents)},{key:"roas",label:"ROAS",sortable:!0,align:"right",className:"tabular-nums font-medium",getValue:n=>ia(n.roas),render:n=>s.jsxs(s.Fragment,{children:[sl(n.roas),s.jsx("div",{className:"mt-0.5",children:s.jsx(tT,{band:n.roas_band})})]})},{key:"break_even",label:"Break-even",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>ia(n.break_even_roas),render:n=>s.jsxs(s.Fragment,{children:[sl(n.break_even_roas),s.jsx(pZe,{product:n})]})},{key:"ad_profit",label:"Ad profit",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>n.ad_profit_cents==null?null:nr(n.ad_profit_cents),render:n=>n.ad_profit_cents==null?"â":ge(nr(n.ad_profit_cents))},{key:"buybox",label:"Buybox",sortable:!0,getValue:n=>n.buybox_owner==null?null:n.buybox_owner?"winning":"losing",render:n=>n.buybox_owner==null?"â":n.buybox_owner?"winning":"losing"},{key:"stock",label:"Stock",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>n.stock==null?null:an(n.stock),render:n=>n.stock==null?"â":de(an(n.stock))},{key:"organic_rank",label:"Org. rank",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>n.organic_rank==null?null:an(n.organic_rank),render:n=>n.organic_rank==null?"â":`#${an(n.organic_rank)}`},{key:"search_visibility",label:"Search vis.",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>n.organic_visibility_score==null?null:an(n.organic_visibility_score),render:n=>s.jsx(DS,{score:ia(n.organic_visibility_score),delta:ia(n.organic_visibility_delta)})},{key:"action",label:"Action",render:n=>s.jsx(nT,{value:n.action})}],getRowKey:n=>`${n.tsin??n.plid??n.product_id??n.sku??""}|${n.campaign_name??""}`,paginate:!0,persist:!1,tableClassName:"text-body-sm",empty:{title:"No product-level rows in this window."}})]})}function CZe({data:e}){const t=e.unadvertised??[];return t.length?s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-4 py-3 border-b border-outline-subtle",children:[s.jsx("div",{className:"text-body-sm font-semibold",children:"High-traffic SKUs with no ad spend"}),s.jsx("div",{className:"text-body-xs text-text-tertiary",children:"Buyable listings with page views that did not appear in this window's advertised products."})]}),s.jsx(dt,{rows:t,columns:[{key:"product",label:"Product",sortable:!0,getValue:n=>n.title||n.sku,render:n=>s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"truncate max-w-[420px]",children:n.title||n.sku||"â"}),s.jsx("div",{className:"text-body-xs text-text-tertiary",children:n.sku})]})},{key:"views",label:"Views 30d",sortable:!0,align:"right",format:"number",getValue:n=>an(n.page_views_30_days)},{key:"conv",label:"Conv. %",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>{if(n.conversion_percentage_30_days==null)return null;const r=an(n.conversion_percentage_30_days);return r>1?r/100:r},render:n=>n.conversion_percentage_30_days==null?"â":an(n.conversion_percentage_30_days)>1?`${an(n.conversion_percentage_30_days).toFixed(1)}%`:Yn(an(n.conversion_percentage_30_days))},{key:"stock",label:"Stock",sortable:!0,align:"right",format:"number",getValue:n=>an(n.total_takealot_stock)},{key:"quality",label:"Quality",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>ia(n.listing_quality),render:n=>n.listing_quality??"â"}],getRowKey:n=>String(n.sku??n.tsin??n.plid??""),paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No unadvertised SKUs."}})]}):null}function EZe({data:e}){const t=e.keyword_bids??[];return t.length?s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-4 py-3 border-b border-outline-subtle",children:[s.jsx("div",{className:"text-body-sm font-semibold",children:"Keyword bid health"}),s.jsx("div",{className:"text-body-xs text-text-tertiary",children:"Osmos snapshot â impression share, CTR, relevancy. Takealot does not attribute orders to keywords here."})]}),s.jsx(dt,{rows:t,columns:[{key:"keyword",label:"Keyword",sortable:!0,sticky:!0,getValue:n=>n.keyword},{key:"match",label:"Match",sortable:!0,className:"text-body-xs uppercase",getValue:n=>n.match_type},{key:"bid",label:"Bid",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>n.bid_cents?nr(n.bid_cents):null,render:n=>n.bid_cents?ge(nr(n.bid_cents)):"â"},{key:"floor",label:"Floor",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>n.floor_cents?nr(n.floor_cents):null,render:n=>n.floor_cents?ge(nr(n.floor_cents)):"â"},{key:"impr_share",label:"Impr. share",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>n.impression_share_pct==null?null:an(n.impression_share_pct),render:n=>n.impression_share_pct==null?"â":`${an(n.impression_share_pct).toFixed(1)}%`},{key:"ctr",label:"CTR",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>eT(n.ctr),render:n=>Lw(n.ctr)},{key:"spend",label:"Spend",sortable:!0,align:"right",format:"zar",getValue:n=>nr(n.spend_cents)},{key:"action",label:"Action",render:n=>s.jsxs(s.Fragment,{children:[s.jsx(nT,{value:n.action}),n.reason?s.jsx("div",{className:"text-body-xs text-text-tertiary max-w-[280px]",children:n.reason}):null]})}],getRowKey:n=>`${n.keyword??""}|${n.match_type??""}|${n.bid_cents??""}`,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No keyword bids."}})]}):null}function AZe({data:e}){const t=e.keywords??[];return e.coverage&&!e.coverage.has_keyword_facts?s.jsxs(V,{className:"p-4",children:[s.jsx("div",{className:"text-body-sm font-semibold",children:"Keyword ROAS"}),s.jsxs("p",{className:"text-body-sm text-text-tertiary mt-1",children:["Upload Takealot's store-scoped ",s.jsx("strong",{children:"Keyword Performance"})," export to see per-keyword revenue and ROAS. Osmos live sync does not include that grain."]})]}):t.length?s.jsxs(V,{className:"overflow-hidden",children:[s.jsx("div",{className:"px-4 py-3 border-b border-outline-subtle",children:s.jsx("div",{className:"text-body-sm font-semibold",children:"Keyword ROAS (portal export)"})}),s.jsx(dt,{rows:t,columns:[{key:"keyword",label:"Keyword",sortable:!0,sticky:!0,getValue:r=>r.keyword},{key:"match",label:"Match",sortable:!0,className:"text-body-xs uppercase",getValue:r=>r.match_type},{key:"spend",label:"Spend",sortable:!0,align:"right",format:"zar",getValue:r=>nr(r.spend_cents)}
921,{key:"revenue",label:"Revenue",sortable:!0,align:"right",format:"zar",getValue:r=>nr(r.revenue_cents)},{key:"orders",label:"Orders",sortable:!0,align:"right",format:"number",getValue:r=>an(r.orders)},{key:"roas",label:"ROAS",sortable:!0,align:"right",className:"tabular-nums font-medium",getValue:r=>ia(r.roas),render:r=>sl(r.roas)},{key:"band",label:"Band",render:r=>s.jsx(tT,{band:r.roas_band})}],getRowKey:r=>`${r.keyword??""}|${r.match_type??""}|${r.campaign_name??""}`,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No keyword ROAS rows."}})]}):null}function TZe({data:e}){const t=e.search_queries;return e.coverage&&!e.coverage.has_search_queries?s.jsxs(V,{className:"p-4",children:[s.jsx("div",{className:"text-body-sm font-semibold",children:"Search query harvest"}),s.jsxs("p",{className:"text-body-sm text-text-tertiary mt-1",children:["Upload a campaign-scoped ",s.jsx("strong",{children:"Search Query"})," export to see shopper queries to harvest as keywords and queries to add as negatives. That report has spend and share, not ROAS."]})]}):!t||!t.harvest.length&&!t.negate.length?null:s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[s.jsx(YL,{title:"Harvest â queries you don't target",rows:t.harvest,empty:"No harvest candidates in this window."}),s.jsx(YL,{title:"Negatives â spend on untargeted poor-CTR queries",rows:t.negate,empty:"No negate candidates in this window."})]})}function YL({title:e,rows:t,empty:n}){return s.jsxs(V,{className:"overflow-hidden",children:[s.jsx("div",{className:"px-4 py-3 border-b border-outline-subtle text-body-sm font-semibold",children:e}),s.jsx(dt,{rows:t,columns:[{key:"query",label:"Query",sortable:!0,getValue:r=>r.search_query,render:r=>s.jsxs(s.Fragment,{children:[s.jsx("div",{children:r.search_query}),r.targeted_keyword?s.jsxs("div",{className:"text-body-xs text-text-tertiary",children:["via ",r.targeted_keyword]}):null]})},{key:"spend",label:"Spend",sortable:!0,align:"right",format:"zar",getValue:r=>nr(r.spend_cents)},{key:"clicks",label:"Clicks",sortable:!0,align:"right",format:"number",getValue:r=>an(r.clicks)},{key:"ctr",label:"CTR",sortable:!0,align:"right",className:"tabular-nums",getValue:r=>eT(r.ctr),render:r=>Lw(r.ctr)}],getRowKey:r=>`${r.search_query??""}|${r.targeted_keyword??""}|${r.spend_cents??""}|${r.clicks??""}`,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:n}})]})}function OZe({data:e}){const t=(e.keyword_candidates??[]).filter(n=>!n.already_targeted).slice(0,20);return t.length?s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-4 py-3 border-b border-outline-subtle",children:[s.jsx("div",{className:"text-body-sm font-semibold",children:"Keyword opportunities (corpus)"}),s.jsx("div",{className:"text-body-xs text-text-tertiary",children:"Category keywords with search volume that you are not currently targeting."})]}),s.jsx(dt,{rows:t,columns:[{key:"keyword",label:"Keyword",sortable:!0,sticky:!0,getValue:n=>n.keyword},{key:"volume",label:"Vol/mo",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>n.avg_monthly_searches==null?null:an(n.avg_monthly_searches),render:n=>n.avg_monthly_searches==null?"â":de(an(n.avg_monthly_searches))},{key:"cpc",label:"CPC range",sortable:!0,align:"right",className:"tabular-nums",getValue:n=>n.min_cpc_cents?nr(n.min_cpc_cents):n.max_cpc_cents?nr(n.max_cpc_cents):null,render:n=>n.min_cpc_cents||n.max_cpc_cents?`${ge(nr(n.min_cpc_cents))}â${ge(nr(n.max_cpc_cents))}`:"â"},{key:"competition",label:"Competition",sortable:!0,getValue:n=>n.competition}],getRowKey:n=>`${n.keyword??""}|${n.category??""}`,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No keyword opportunities."}})]}):null}const WG=[{key:"performance",label:"Performance",icon:s.jsx(fc,{className:"w-4 h-4"})},{key:"creatives",label:"Creatives",icon:s.jsx(Qy,{className:"w-4 h-4"})},{key:"targeting",label:"Targeting",icon:s.jsx(L2,{className:"w-4 h-4"})}],IZe=WG.map(e=>e.key);function ZL(){const{slug:e}=jn(),t=Rt(),[n,r]=p.useState(null),[a,i]=it("tab","performance"),o=IZe.includes(a)?a:"performance";p.useEffect(()=>{let c=!0;return K.sellers().then(u=>c&&r(u)).catch(()=>c&&r([])),()=>{c=!1}},[]),p.useEffect(()=>{e||n===null||n.length>0&&t(`/ads/${n[0].slug}`,{replace:!0})},[e,n,t]);const l=e?(n==null?void 0:n.find(c=>c.slug===e))??null:null;return s.jsxs(s.Fragment,{children:[s.jsx(Pt,{crumbs:[{label:"Ads"},...l?[{label:l.display_name}]:[]]}),s.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-subtle/30",children:[s.jsx(As,{items:WG.map(c=>
921({key:c.key,label:c.label,icon:c.icon,active:o===c.key,onClick:()=>i(c.key)}))}),!e&&s.jsx("div",{className:"w-full px-4 py-10 text-center text-text-tertiary text-body-sm",children:n===null?"Loading storesâ¦":n.length===0?"No stores yet.":"Opening your storeâ¦"}),e&&o==="performance"&&s.jsx(xZe,{slug:e}),e&&o==="creatives"&&s.jsx(PZe,{slug:e}),e&&o==="targeting"&&s.jsx(RZe,{slug:e})]})]})}function PZe({slug:e}){const[t,n]=p.useState(""),[r,a]=p.useState(""),[i,o]=p.useState(""),[l,c]=p.useState(!1),[u,d]=p.useState([]),[h,f]=p.useState(null),m=p.useCallback(()=>{K.ads.listCreatives(e).then(g=>d(g.packs)).catch(()=>{})},[e]);p.useEffect(()=>{d([]),m()},[m]);const x=p.useCallback(async()=>{if(!l){c(!0),f(null);try{const g=await K.ads.generateCreatives(e,{sku:t.trim()||void 0,headline:r.trim()||void 0,cta:i.trim()||void 0});Ae.success(g.was_free_bucket?"Banner pack generated.":`Banner pack generated · R${Number(g.charged_zar??0).toFixed(2)} charged.`),m()}catch(g){f(String((g==null?void 0:g.message)||g))}finally{c(!1)}}},[e,t,r,i,l,m]);return s.jsxs("div",{className:"w-full px-4 py-6 space-y-6",children:[s.jsxs(V,{className:"p-5 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-body-sm font-semibold flex items-center gap-1.5",children:[s.jsx(bT,{className:"w-4 h-4 text-brand-500"})," Generate Sponsored Display banners"]}),s.jsx("p",{className:"text-body-xs text-text-tertiary mt-0.5",children:"Search-listing pack (1292Ã120, 728Ã90, 320Ã100), themed by your brand kit. Leave copy blank to have it written for you."})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx("label",{className:"text-body-xs text-text-secondary",children:"Product SKU"}),s.jsx(Re,{value:t,onChange:g=>n(g.target.value),placeholder:"e.g. KMF-BALL-8",disabled:l})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("label",{className:"text-body-xs text-text-secondary",children:"Headline (optional)"}),s.jsx(Re,{value:r,onChange:g=>a(g.target.value),placeholder:"auto-written",disabled:l,maxLength:30})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("label",{className:"text-body-xs text-text-secondary",children:"CTA (optional)"}),s.jsx(Re,{value:i,onChange:g=>o(g.target.value),placeholder:"Shop Now",disabled:l,maxLength:14})]})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs(W,{intent:"brand",onClick:x,disabled:l||!t.trim()&&!r.trim(),children:[l?s.jsx(_e,{className:"w-4 h-4 animate-spin"}):s.jsx(bT,{className:"w-4 h-4"}),l?"Generatingâ¦":"Generate banners"]}),s.jsx("span",{className:"text-body-xs text-text-tertiary",children:"Takes ~10â20s â cut-out, copy, and three renders."})]}),h&&s.jsx("div",{className:"text-body-sm text-intent-danger",children:h})]}),u.length>0&&s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"text-body-sm font-semibold",children:"Your creatives"}),u.map(g=>s.jsx(BZe,{pack:g,heading:`${g.sku||"Banner pack"} · ${Ca(g.created_at)}`},g.id))]})]})}function RZe({slug:e}){var T;const[t,n]=p.useState(""),[r,a]=p.useState(null),[i,o]=p.useState(null),[l,c]=p.useState(null),[u,d]=p.useState(new Set),[h,f]=p.useState(!1),[m,x]=p.useState(!1),[g,y]=p.useState(null),[b,v]=p.useState([]),w=p.useCallback(()=>{K.ads.targetLists(e).then(S=>v(S.lists)).catch(()=>{})},[e]);p.useEffect(()=>{a(null),o(null),c(null),d(new Set),K.ads.targetSeeds(e).then(S=>a(S.offers)).catch(()=>a([])),w()},[e,w]);const _=p.useCallback(()=>{K.ads.targetSeeds(e,t.trim()||void 0).then(S=>a(S.offers)).catch(()=>{})},[e,t]),k=p.useCallback(async S=>{f(!0),y(null),o(S),c(null);try{const O=await K.ads.suggestTargets(e,{plid:S});c(O),d(new Set(O.candidates.map(R=>R.plid)))}catch(O){y(FZe(String((O==null?void 0:O.message)||O)))}finally{f(!1)}},[e]),j=p.useCallback(S=>{d(O=>{const R=new Set(O);return R.has(S)?R.delete(S):R.add(S),R})},[]),N=p.useCallback(()=>{d(S=>{if(!l)return S;const O=l.candidates.map(I=>I.plid);return O.length>0&&O.every(I=>S.has(I))?new Set:new Set(O)})},[l]),E=p.useCallback(async()=>{var S;if(!(!l||u.size===0)){x(!0),y(null);try{const O=l.candidates.filter(I=>u.has(I.plid)),R=await K.ads.exportTargets(e,{plid:l.seed.plid,candidates:O,seed:l.seed,leaf:l.leaf});
921(S=R.warnings)==null||S.forEach(I=>Ae.info(I)),Ae.success(`${R.target_count} targets exported â ${R.filename}`),await zG(R),w()}catch(O){y(String((O==null?void 0:O.message)||O))}finally{x(!1)}}},[e,l,u,w]),A=((T=l==null?void 0:l.limits)==null?void 0:T.soft_max)??50,C=u.size>A;return s.jsxs("div",{className:"w-full px-4 py-6 space-y-6",children:[s.jsxs(V,{className:"p-5 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-body-sm font-semibold flex items-center gap-1.5",children:[s.jsx(L2,{className:"w-4 h-4 text-brand-500"})," Target competitors' product pages"]}),s.jsxs("p",{className:"text-body-xs text-text-tertiary mt-0.5",children:["Pick one of your products and we'll find competitor listings worth advertising on â from its category and from what shoppers search. Exports the ",s.jsx("code",{children:"sku_id.tsv"})," Takealot's Sponsored Display uploader expects."]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Re,{value:t,onChange:S=>n(S.target.value),onKeyDown:S=>S.key==="Enter"&&_(),placeholder:"Search your products by SKU, title or PLID",disabled:h}),s.jsxs(W,{intent:"neutral",onClick:_,disabled:h,children:[s.jsx(Fa,{className:"w-4 h-4"})," Search"]})]}),r===null?s.jsx("div",{className:"text-body-sm text-text-tertiary",children:"Loading your productsâ¦"}):r.length===0?s.jsx("div",{className:"text-body-sm text-text-tertiary",children:"No buyable Takealot products with a PLID found for this store."}):s.jsx("div",{className:"border border-outline-subtle rounded overflow-hidden max-h-72 overflow-y-auto",children:s.jsx(dt,{rows:r,columns:DZe(i,h,k),getRowKey:S=>S.offer_id,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No products match."},rowClassName:S=>i===S.plid?"bg-surface-brandSubtle":void 0})}),g&&s.jsx("div",{className:"text-body-sm text-intent-danger",children:g})]}),h&&!l&&s.jsxs(V,{className:"p-5 text-body-sm text-text-tertiary flex items-center gap-2",children:[s.jsx(_e,{className:"w-4 h-4 animate-spin"})," Reading your category and what shoppers searchâ¦"]}),l&&s.jsxs(V,{className:"p-5 space-y-4",children:[s.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-2",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-body-sm font-semibold",children:[l.candidates.length," suggested targets"]}),s.jsxs("div",{className:"text-body-xs text-text-tertiary mt-0.5",children:["For ",l.seed.title??l.seed.plid,l.leaf.display_name?s.jsxs(s.Fragment,{children:[" · ","placed in ",s.jsx("span",{className:"font-medium",children:l.leaf.display_name})," ",s.jsxs("span",{className:"text-text-tertiary",children:["(",LZe(l.leaf.resolution_tier),")"]})]}):null]})]}),s.jsxs("div",{className:"text-body-xs text-text-tertiary text-right",children:[l.lanes.leaf," from category · ",l.lanes.keyword," from search",l.keyword_terms.length>0&&s.jsxs("div",{className:"mt-0.5",children:["terms: ",l.keyword_terms.join(", ")]})]})]}),l.notes.length>0&&s.jsx("div",{className:"space-y-1",children:l.notes.map((S,O)=>s.jsxs("div",{className:"text-body-xs text-text-secondary flex items-start gap-1.5",children:[s.jsx(zn,{className:"w-3.5 h-3.5 mt-0.5 shrink-0 text-intent-warning"}),s.jsx("span",{children:S})]},O))}),l.candidates.length===0?s.jsx("div",{className:"text-body-sm text-text-tertiary",children:"No usable targets found. Try a different product, or a seed that sits in a category we've crawled."}):s.jsx("div",{className:"border border-outline-subtle rounded overflow-hidden",children:s.jsx(dt,{rows:l.candidates,columns:MZe(l.candidates,u,j,N),getRowKey:S=>S.plid,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No usable targets found."}})}),l.candidates.length>0&&s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs(W,{intent:"brand",onClick:E,disabled:m||u.size===0,children:[m?s.jsx(_e,{className:"w-4 h-4 animate-spin"}):s.jsx(Dr,{className:"w-4 h-4"}),m?"Building fileâ¦":`Export ${u.size} as .tsv`]}),s.jsx("span",{className:B("text-body-xs",C?"text-intent-warning":"text-text-tertiary"),children:C?`${u.size} selected â above the recommended maximum of ${A}.`:"One column of PLIDs, ready to upload to Sponsored Display."})]})]}),b.length>0&&s.jsxs(V,{className:"p-5 space-y-3",children:[s.jsx("div",{className:"text-body-sm font-semibold",children:"Previous target lists"}),s.jsx(dt,{rows:b,columns:$Ze,getRowKey:S=>S.id,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No previous lists."}})]})]})}function XL({checked:e,onClick:t,label:n}){return s.jsx("button",{type:"button",onClick:t,"aria-label":n,className:B("w-4 h-4 rounded border flex items-center justify-center",e?"bg-brand-500 border-outline-brand text-text-inverse":"border-outline"),children:e&&s.jsx(fn,{className:"w-3 h-3"})})}function DZe(e,t,n){return[{key:"product",label:"Product",className:"max-w-md truncate",render:r=>s.jsx("span",{title:r.title??"",children:r.title??"â"})},{key:"sku",label:"SKU",render:r=>s.jsx("span",{className:"text-text-tertiary",children:r.sku??"â"})},{key:"price",label:"Price",align:"right",getValue:r=>r.selling_price!=null?Number(r.selling_price):null,render:r=>r.selling_price!=null?ge(Number(r.selling_price)):"â"},{key:"views",label:"Views 30d",align:"right",getValue:r=>r.page_views_30_days,render:r=>s.jsx("span",{className:"text-text-tertiary",children:r.page_views_30_days??"â"})},{key:"actions",label:"",align:"right",stopRowClick:!0,render:r=>s.jsxs(W,{intent:e===r.plid?"brand":"neutral",onClick:()=>n(r.plid),disabled:t,children:[t&&e===r.plid?s.jsx(_e,{className:"w-3.5 h-3.5 animate-spin"}):s.jsx(L2,{className:"w-3.5 h-3.5"}),"Find targets"]})}]}function MZe(e,t,n,r){const a=e.length>0&&e.every(i=>t.has(i.plid));return[{key:"select",label:"",stopRowClick:!0,className:"w-8",headerPrefix:s.jsx(XL,{checked:a,onClick:r,label:a?"Deselect all":"Select all"}),render:i=>s.jsx(XL,{checked:t.has(i.plid),onClick:()=>n(i.plid),label:t.has(i.plid)?"Remove target":"Add target"})},{key:"listing",label:"Competitor listing",className:"max-w-sm",render:i=>s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"truncate",title:i.title??"",children:i.title??"â"}),s.jsxs("div",{className:"text-body-xs text-text-tertiary",children:[i.brand??"â",i.lane==="keyword"?" · from search":""]})]})},{key:"plid",label:"PLID",render:i=>s.jsxs("span",{className:"text-text-tertiary tabular-nums",children:["PLID",i.plid]})},{key:"price",label:"Their price",align:"right",getValue:i=>i.price_cents,render:i=>i.price_cents!=null?ge(i.price_cents/100):"â"},{key:"rating",label:"Rating",align:"right",getValue:i=>i.star_rating,render:i=>s.jsxs(s.Fragment,{children:[i.star_rating!=null?i.star_rating.toFixed(1):"â",i.review_count!=null&&s.jsxs("span",{className:"text-text-tertiary",children:[" (",i.review_count,")"]})]})},{key:"score",label:"Score",align:"right",getValue:i=>i.score,render:i=>s.jsx("span",{className:"font-medium",children:i.score})},{key:"why",label:"Why",render:i=>s.jsx("span",{className:"text-body-xs text-text-secondary",children:i.reason})}]}const $Ze=[{key:"seed",label:"Seed",className:"max-w-xs truncate",render:e=>s.jsx("span",{title:e.seed_title??"",children:e.seed_title??`PLID${e.seed_plid}`})},{key:"category",label:"Category",render:e=>s.jsx("span",{className:"text-text-tertiary",children:e.leaf_display_name??"â"})},{key:"targets",label:"Targets",align:"right",getValue:e=>e.target_count,format:"number"},{key:"created",label:"Created",align:"right",getValue:e=>e.created_at,render:e=>s.jsx("span",{className:"text-text-tertiary",children:Ca(e.created_at)})},{key:"download",label:"",align:"right",render:e=>e.export_id!=null?s.jsxs("button",{type:"button",onClick:()=>Ul.download(e.export_id).catch(t=>Ae.error(`Couldn't fetch that file: ${String((t==null?void 0:t.message)||t)}`)),className:"text-body-xs text-text-brand inline-flex items-center gap-1 hover:underline",children:[s.jsx(Dr,{className:"w-3.5 h-3.5"})," .tsv"]}):null}];function LZe(e){return e==="rank_snapshot"?"from its category ranking":e==="lineage"?"from its Takealot lineage":e==="mpv"?"looked up on Takealot":"not resolved"}function FZe(e){return e.includes("seed_not_yours")?"That PLID isn't on this store's catalogue.":e.includes("pli
921d_invalid")?"That doesn't look like a PLID.":e}function BZe({pack:e,heading:t}){const n={logo:"from your logo",product:"from your products",house:"default theme",manual:"your custom kit"};return s.jsxs(V,{className:"p-5 space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[s.jsx("div",{className:"text-body-sm font-semibold",children:t||"Generated pack"}),s.jsxs("div",{className:"text-body-xs text-text-tertiary",children:["â",e.copy.headline,"â",e.copy.subline?` · ${e.copy.subline}`:""," · ",e.copy.cta,e.brand_source?` · brand ${n[e.brand_source]??e.brand_source}`:""]})]}),s.jsx("div",{className:"space-y-4",children:e.items.map(r=>{const a=r.preview_url||r.durable_url;return s.jsxs("div",{className:"space-y-1.5",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("span",{className:"text-body-xs font-medium text-text-secondary",children:[r.width," à ",r.height]}),a&&s.jsxs("a",{href:r.durable_url||a,download:`banner-${r.width}x${r.height}.png`,target:"_blank",rel:"noreferrer",className:"text-body-xs text-text-brand inline-flex items-center gap-1 hover:underline",children:[s.jsx(Dr,{className:"w-3.5 h-3.5"})," Download"]})]}),a?s.jsx("img",{src:a,alt:`${r.width}Ã${r.height} banner`,className:"max-w-full border border-outline-subtle rounded",style:{width:Math.min(r.width,1e3)}}):s.jsx("div",{className:"text-body-xs text-text-tertiary",children:"Rendered (no preview URL)."})]},`${r.width}x${r.height}`)})})]})}function KG({url:e,initials:t,shape:n="circle",disabled:r,onPick:a,onRemove:i}){const o=p.useRef(null),[l,c]=p.useState(!1),[u,d]=p.useState(null),h=n==="circle"?"rounded-full":"rounded-md";async function f(x){if(x){c(!0),d(null);try{await a(x)}catch(g){d(JL(g))}finally{c(!1),o.current&&(o.current.value="")}}}async function m(){if(i){c(!0),d(null);try{await i()}catch(x){d(JL(x))}finally{c(!1)}}}return s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:B("w-12 h-12 overflow-hidden flex items-center justify-center bg-surface-sunken text-text-secondary text-sm font-semibold shrink-0",h),children:e?s.jsx("img",{src:e,alt:"",className:"w-full h-full object-cover"}):t}),s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{ref:o,type:"file",accept:"image/png,image/jpeg",className:"hidden",disabled:r||l,onChange:x=>{var g;return f((g=x.target.files)==null?void 0:g[0])}}),s.jsxs(W,{onClick:()=>{var x;return(x=o.current)==null?void 0:x.click()},disabled:r||l,intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(ti,{className:"w-3 h-3"})," ",l?"Uploadingâ¦":e?"Change":"Upload"]}),e&&i&&s.jsxs(W,{onClick:m,disabled:r||l,intent:"neutral",variant:"link",size:"sm",children:[s.jsx(us,{className:"w-3 h-3"})," Remove"]})]}),s.jsx("span",{className:"text-body-xs text-text-tertiary",children:"PNG or JPG, up to 5MB."}),u&&s.jsx("span",{className:"text-body-xs text-text-error",children:u})]})]})}function JL(e){const t=String((e==null?void 0:e.message)||e);return t.includes("too_large")?"That image is over 5MB.":t.includes("unsupported_type")?"Use a PNG or JPG.":t.includes("owner_only")?"Only the workspace owner can change this.":t}const s2="gadjet-pair:";async function HG(e,t){const n=await e.json().catch(()=>({})),r=new Error((n==null?void 0:n.error)||t);throw r.status=e.status,r.code=n==null?void 0:n.error,r}async function UZe(){const e=await oe("/api/pair/start",{method:"POST"});return e.ok?e.json():HG(e,`pair_start_${e.status}`)}function zZe(e){return s2+e}function WZe(e){if(typeof e!="string"||!e.startsWith(s2))return null;const t=e.slice(s2.length).trim();return t.length>0?t:null}async function KZe(e){const t=await oe("/api/pair/claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({code:e,device:VZe()})});return t.ok?t.json():HG(t,`pair_claim_${t.status}`)}async function HZe(e){const{error:t}=await xn.auth.setSession({access_token:e.access_token,refresh_token:e.refresh_token});if(t)throw t}function VZe(){return typeof navigator>"u"?{}:{user_agent:navigator.userAgent,platform:navigator.platform??"",language:navigator.language??""}}
921function qZe(e,t){var n=Object.setPrototypeOf;n?n(e,t):e.__proto__=t}function GZe(e,t){t===void 0&&(t=e.constructor);var n=Error.captureStackTrace;n&&n(e,t)}var YZe=(function(){var e=function(n,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,i){a.__proto__=i}||function(a,i){for(var o in i)Object.prototype.hasOwnProperty.call(i,o)&&(a[o]=i[o])},e(n,r)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),ZZe=(function(e){YZe(t,e);function t(n,r){var a=this.constructor,i=e.call(this,n,r)||this;return Object.defineProperty(i,"name",{value:a.name,enumerable:!1,configurable:!0}),qZe(i,a.prototype),GZe(i),i}return t})(Error),XZe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),ui=(function(e){XZe(t,e);function t(n){n===void 0&&(n=void 0);var r=e.call(this,n)||this;return r.message=n,r}return t.prototype.getKind=function(){var n=this.constructor;return n.kind},t.kind="Exception",t})(ZZe),JZe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),co=(function(e){JZe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.kind="ArgumentException",t})(ui),QZe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Ct=(function(e){QZe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.kind="IllegalArgumentException",t})(ui),QL=(function(){function e(t){if(this.binarizer=t,t===null)throw new Ct("Binarizer must be non-null.")}return e.prototype.getWidth=function(){return this.binarizer.getWidth()},e.prototype.getHeight=function(){return this.binarizer.getHeight()},e.prototype.getBlackRow=function(t,n){return this.binarizer.getBlackRow(t,n)},e.prototype.getBlackMatrix=function(){return(this.matrix===null||this.matrix===void 0)&&(this.matrix=this.binarizer.getBlackMatrix()),this.matrix},e.prototype.isCropSupported=function(){return this.binarizer.getLuminanceSource().isCropSupported()},e.prototype.crop=function(t,n,r,a){var i=this.binarizer.getLuminanceSource().crop(t,n,r,a);return new e(this.binarizer.createBinarizer(i))},e.prototype.isRotateSupported=function(){return this.binarizer.getLuminanceSource().isRotateSupported()},e.prototype.rotateCounterClockwise=function(){var t=this.binarizer.getLuminanceSource().rotateCounterClockwise();return new e(this.binarizer.createBinarizer(t))},e.prototype.rotateCounterClockwise45=function(){var t=this.binarizer.getLuminanceSource().rotateCounterClockwise45();return new e(this.binarizer.createBinarizer(t))},e.prototype.toString=function(){try{return this.getBlackMatrix().toString()}catch{return""}},e})(),eXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
921t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Yr=(function(e){eXe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.getChecksumInstance=function(){return new t},t.kind="ChecksumException",t})(ui),tXe=(function(){function e(t){this.source=t}return e.prototype.getLuminanceSource=function(){return this.source},e.prototype.getWidth=function(){return this.source.getWidth()},e.prototype.getHeight=function(){return this.source.getHeight()},e})(),Fn=(function(){function e(){}return e.arraycopy=function(t,n,r,a,i){if(t===r&&n<a)for(a+=i-1,n+=i-1;i--;)r[a--]=t[n--];else for(;i--;)r[a++]=t[n++]},e.currentTimeMillis=function(){return Date.now()},e})(),nXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),rT=(function(e){nXe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.kind="IndexOutOfBoundsException",t})(ui),rXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),e8=(function(e){rXe(t,e);function t(n,r){n===void 0&&(n=void 0),r===void 0&&(r=void 0);var a=e.call(this,r)||this;return a.index=n,a.message=r,a}return t.kind="ArrayIndexOutOfBoundsException",t})(rT),sXe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},is=(function(){function e(){}return e.fill=function(t,n){for(var r=0,a=t.length;r<a;r++)t[r]=n},e.fillWithin=function(t,n,r,a){e.rangeCheck(t.length,n,r);for(var i=n;i<r;i++)t[i]=a},e.rangeCheck=function(t,n,r){if(n>r)throw new Ct("fromIndex("+n+") > toIndex("+r+")");if(n<0)throw new e8(n);if(r>t)throw new e8(r)},e.asList=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return t},e.create=function(t,n,r){var a=Array.from({length:t});return a.map(function(i){return Array.from({length:n}).fill(r)})},e.createInt32Array=function(t,n,r){var a=Array.from({length:t});return a.map(function(i){return Int32Array.from({length:n}).fill(r)})},e.equals=function(t,n){if(!t||!n||!t.length||!n.length||t.length!==n.length)return!1;for(var r=0,a=t.length;r<a;r++)if(t[r]!==n[r])return!1;return!0},e.hashCode=function(t){var n,r;if(t===null)return 0;var a=1;try{for(var i=sXe(t),o=i.next();!o.done;o=i.next()){var l=o.value;a=31*a+l}}catch(c){n={error:c}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return a},e.fillUint8Array=function(t,n){for(var r=0;r!==t.length;r++)t[r]=n},e.copyOf=function(t,n){return t.slice(0,n)},e.copyOfUint8Array=function(t,n){if(t.length<=n){var r=new Uint8Array(n);return r.set(t),r}return t.slice(0,n)},e.copyOfRange=function(t,n,r){var a=r-n,i=new Int32Array(a);return Fn.arraycopy(t,n,i,0,a),i},e.binarySearch=function(t,n,r){r===void 0&&(r=e.numberComparator);for(var a=0,i=t.length-1;a<=i;){var o=i+a>>1,l=r(n,t[o]);if(l>0)a=o+1;else if(l<0)i=o-1;else return o}return-a-1},e.numberComparator=function(t,n){return t-n},e})(),Zt=(function(){function e(){}return e.numberOfTrailingZeros=function(t){var n;if(t===0)return 32;var r=31;return n=t<<16,n!==0&&(r-=16,t=n),n=t<<8,n!==0&&(r-=8,t=n),n=t<<4,n!==0&&(r-=4,t=n),n=t<<2,n!==0&&(r-=2,t=n),r-(t<<1>>>31)},e.numberOfLeadingZeros=function(t){if(t===0)return 32;var n=1;return t>>>16||(n+=16,t<<=16),t>>>24||(n+=8,t<<=8),t>>>28||(n+=4,t<<=4),t>>>30||(n+=2,t<<=2),n-=t>>>31,n},e.toHexString=function(t){return t.toString(16)},e.toBinaryString=function(t){return String(parseInt(String(t),2))},e.bitCount=function(t){return t=t-(t>>>1&1431655765),t=(t&858993459)+(t>>>2&858993459),t=t+(t>>>4)&252645135,t=t+(t>>>8),t=t+(t>>>16),t&63},e.truncDivision=function(t,n){return Math.trunc(t/n)},e.parseInt=function(t,n){return n===void 0&&(n=void 0),parseInt(t,n)},e.MIN_VALUE_32_BITS=-2147483648,e.MAX_VALUE=Number.MAX_SAFE_INTEGER,e})(),ks=(function(){function e(t,n){t===void 0?(this.size=0,this.bits=new Int32Array(1)):(this.size=t,n==null?this.bits=e.makeArray(t):this.bits=n)}return e.prototype.getSize=function(){return this.size},e.prototype.getSizeInBytes=function(){return Math.floor((this.size+7)/8)},e.prototype.ensureCapacity=function(t){if(t>this.bits.length*32){var n=e.makeArray(t);Fn.arraycopy(this.bits,0,n,0,this.bits.length),this.bits=n}},e.prototype.get=function(t){return(this.bits[Math.floor(t/32)]&1<<(t&31))!==0},e.prototype.set=function(t){this.bits[Math.floor(t/32)]|=1<<(t&31)},e.prototype.flip=function(t){this.bits[Math.floor(t/32)]^=1<<(t&31)},e.prototype.getNextSet=function(t){var n=this.size;if(t>=n)return n;var r=this.bits,a=Math.floor(t/32),i=r[a];i&=~((1<<(t&31))-1);for(var o=r.length;i===0;){if(++a===o)return n;i=r[a]}var l=a*32+Zt.numberOfTrailingZeros(i);return l>n?n:l},e.prototype.getNextUnset=function(t){var n=this.size;if(t>=n)return n;var r=this.bits,a=Math.floor(t/32),i=~r[a];i&=~((1<<(t&31))-1);for(var o=r.length;i===0;){if(++a===o)return n;i=~r[a]}var l=a*32+Zt.numberOfTrailingZeros(i);return l>n?n:l},e.prototype.setBulk=function(t,n){this.bits[Math.floor(t/32)]=n},e.prototype.setRange=function(t,n){if(n<t||t<0||n>this.size)throw new Ct;if(n!==t){n--;for(var r=Math.floor(t/32),a=Math.floor(n/32),i=this.bits,o=r;o<=a;o++){var l=o>r?0:t&31,c=o<a?31:n&31,u=(2<<c)-(1<<l);i[o]|=u}}},e.prototype.clear=function(){for(var t=this.bits.length,n=this.bits,r=0;r<t;r++)n[r]=0},e.prototype.isRange=function(t,n,r){if(n<t||t<0||n>this.size)throw new Ct;if(n===t)return!0;n--;for(var a=Math.floor(t/32),i=Math.floor(n/32),o=this.bits,l=a;l<=i;l++){var c=l>a?0:t&31,u=l<i?31:n&31,d=(2<<u)-(1<<c)&4294967295;if((o[l]&d)!==(r?d:0))return!1}return!0},e.prototype.appendBit=function(t){this.ensureCapacity(this.size+1),t&&(this.bits[Math.floor(this.size/32)]|=1<<(this.size&31)),this.size++},e.prototype.appendBits=function(t,n){if(n<0||n>32)throw new Ct("Num bits must be between 0 and 32");this.ensureCapacity(this.size+n);for(var r=n;r>0;r--)this.appendBit((t>>r-1&1)===1)},e.prototype.appendBitArray=function(t){var n=t.size;this.ensureCapacity(this.size+n);for(var r=0;r<n;r++)this.appendBit(t.get(r))},e.prototype.xor=function(t){if(this.size!==t.size)throw new Ct("Sizes don't match");for(var n=this.bits,r=0,a=n.length;r<a;r++)n[r]^=t.bits[r]},e.prototype.toBytes=function(t,n,r,a){for(var i=0;i<a;i++){for(var o=0,l=0;l<8;l++)this.get(t)&&(o|=1<<7-l),t++;n[r+i]=o}},e.prototype.getBitArray=function(){return this.bits},e.prototype.reverse=function(){for(var t=new Int32Array(this.bits.length),n=Math.floor((this.size-1)/32),r=n+1,a=this.bits,i=0;i<r;i++){var o=a[i];o=o>>1&1431655765|(o&1431655765)<<1,o=o>>2&858993459|(o&858993459)<<2,o=o>>4&252645135|(o&252645135)<<4,o=o>>8&16711935|(o&16711935)<<8,o=o>>16&65535|(o&65535)<<16,t[n-i]=o}if(this.size!==r*32){for(var l=r*32-this.size,c=t[0]>>>l,i=1;i<r;i++){var u=t[i];c|=u<<32-l,t[i-1]=c,c=u>>>l}t[r-1]=c}this.bits=t},e.makeArray=function(t){return new Int32Array(Math.floor((t+31)/32))},e.prototype.equals=function(t){if(!(t instanceof e))return!1;var n=t;return this.size===n.size&&is.equals(this.bits,n.bits)}
921,e.prototype.hashCode=function(){return 31*this.size+is.hashCode(this.bits)},e.prototype.toString=function(){for(var t="",n=0,r=this.size;n<r;n++)(n&7)===0&&(t+=" "),t+=this.get(n)?"X":".";return t},e.prototype.clone=function(){return new e(this.size,this.bits.slice())},e.prototype.toArray=function(){for(var t=[],n=0,r=this.size;n<r;n++)t.push(this.get(n));return t},e})(),On;(function(e){e[e.OTHER=0]="OTHER",e[e.PURE_BARCODE=1]="PURE_BARCODE",e[e.POSSIBLE_FORMATS=2]="POSSIBLE_FORMATS",e[e.TRY_HARDER=3]="TRY_HARDER",e[e.CHARACTER_SET=4]="CHARACTER_SET",e[e.ALLOWED_LENGTHS=5]="ALLOWED_LENGTHS",e[e.ASSUME_CODE_39_CHECK_DIGIT=6]="ASSUME_CODE_39_CHECK_DIGIT",e[e.ENABLE_CODE_39_EXTENDED_MODE=7]="ENABLE_CODE_39_EXTENDED_MODE",e[e.ASSUME_GS1=8]="ASSUME_GS1",e[e.RETURN_CODABAR_START_END=9]="RETURN_CODABAR_START_END",e[e.NEED_RESULT_POINT_CALLBACK=10]="NEED_RESULT_POINT_CALLBACK",e[e.ALLOWED_EAN_EXTENSIONS=11]="ALLOWED_EAN_EXTENSIONS"})(On||(On={}));var aXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),We=(function(e){aXe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.getFormatInstance=function(){return new t},t.kind="FormatException",t})(ui),iXe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},En;(function(e){e[e.Cp437=0]="Cp437",e[e.ISO8859_1=1]="ISO8859_1",e[e.ISO8859_2=2]="ISO8859_2",e[e.ISO8859_3=3]="ISO8859_3",e[e.ISO8859_4=4]="ISO8859_4",e[e.ISO8859_5=5]="ISO8859_5",e[e.ISO8859_6=6]="ISO8859_6",e[e.ISO8859_7=7]="ISO8859_7",e[e.ISO8859_8=8]="ISO8859_8",e[e.ISO8859_9=9]="ISO8859_9",e[e.ISO8859_10=10]="ISO8859_10",e[e.ISO8859_11=11]="ISO8859_11",e[e.ISO8859_13=12]="ISO8859_13",e[e.ISO8859_14=13]="ISO8859_14",e[e.ISO8859_15=14]="ISO8859_15",e[e.ISO8859_16=15]="ISO8859_16",e[e.SJIS=16]="SJIS",e[e.Cp1250=17]="Cp1250",e[e.Cp1251=18]="Cp1251",e[e.Cp1252=19]="Cp1252",e[e.Cp1256=20]="Cp1256",e[e.UnicodeBigUnmarked=21]="UnicodeBigUnmarked",e[e.UTF8=22]="UTF8",e[e.ASCII=23]="ASCII",e[e.Big5=24]="Big5",e[e.GB18030=25]="GB18030",e[e.EUC_KR=26]="EUC_KR"})(En||(En={}));var as=(function(){function e(t,n,r){for(var a,i,o=[],l=3;l<arguments.length;l++)o[l-3]=arguments[l];this.valueIdentifier=t,this.name=r,typeof n=="number"?this.values=Int32Array.from([n]):this.values=n,this.otherEncodingNames=o,e.VALUE_IDENTIFIER_TO_ECI.set(t,this),e.NAME_TO_ECI.set(r,this);for(var c=this.values,u=0,d=c.length;u!==d;u++){var h=c[u];e.VALUES_TO_ECI.set(h,this)}try{for(var f=iXe(o),m=f.next();!m.done;m=f.next()){var x=m.value;e.NAME_TO_ECI.set(x,this)}}catch(g){a={error:g}}finally{try{m&&!m.done&&(i=f.return)&&i.call(f)}finally{if(a)throw a.error}}}return e.prototype.getValueIdentifier=function(){return this.valueIdentifier},e.prototype.getName=function(){return this.name},e.prototype.getValue=function(){return this.values[0]},e.getCharacterSetECIByValue=function(t){if(t<0||t>=900)throw new We("incorect value");var n=e.VALUES_TO_ECI.get(t);if(n===void 0)throw new We("incorect value");return n},e.getCharacterSetECIByName=function(t){var n=e.NAME_TO_ECI.get(t);if(n===void 0)throw new We("incorect value");return n},e.prototype.equals=function(t){if(!(t instanceof e))return!1;var n=t;return this.getName()===n.getName()},e.VALUE_IDENTIFIER_TO_ECI=new Map,e.VALUES_TO_ECI=new Map,e.NAME_TO_ECI=new Map,e.Cp437=new e(En.Cp437,Int32Array.from([0,2]),"Cp437"),e.ISO8859_1=new e(En.ISO8859_1,Int32Array.from([1,3]),"ISO-8859-1","ISO88591","ISO8859_1"),e.ISO8859_2=new e(En.ISO8859_2,4,"ISO-8859-2","ISO88592","ISO8859_2"),e.ISO8859_3=new e(En.ISO8859_3,5,"ISO-8859-3","ISO88593","ISO8859_3"),e.ISO8859_4
921=new e(En.ISO8859_4,6,"ISO-8859-4","ISO88594","ISO8859_4"),e.ISO8859_5=new e(En.ISO8859_5,7,"ISO-8859-5","ISO88595","ISO8859_5"),e.ISO8859_6=new e(En.ISO8859_6,8,"ISO-8859-6","ISO88596","ISO8859_6"),e.ISO8859_7=new e(En.ISO8859_7,9,"ISO-8859-7","ISO88597","ISO8859_7"),e.ISO8859_8=new e(En.ISO8859_8,10,"ISO-8859-8","ISO88598","ISO8859_8"),e.ISO8859_9=new e(En.ISO8859_9,11,"ISO-8859-9","ISO88599","ISO8859_9"),e.ISO8859_10=new e(En.ISO8859_10,12,"ISO-8859-10","ISO885910","ISO8859_10"),e.ISO8859_11=new e(En.ISO8859_11,13,"ISO-8859-11","ISO885911","ISO8859_11"),e.ISO8859_13=new e(En.ISO8859_13,15,"ISO-8859-13","ISO885913","ISO8859_13"),e.ISO8859_14=new e(En.ISO8859_14,16,"ISO-8859-14","ISO885914","ISO8859_14"),e.ISO8859_15=new e(En.ISO8859_15,17,"ISO-8859-15","ISO885915","ISO8859_15"),e.ISO8859_16=new e(En.ISO8859_16,18,"ISO-8859-16","ISO885916","ISO8859_16"),e.SJIS=new e(En.SJIS,20,"SJIS","Shift_JIS"),e.Cp1250=new e(En.Cp1250,21,"Cp1250","windows-1250"),e.Cp1251=new e(En.Cp1251,22,"Cp1251","windows-1251"),e.Cp1252=new e(En.Cp1252,23,"Cp1252","windows-1252"),e.Cp1256=new e(En.Cp1256,24,"Cp1256","windows-1256"),e.UnicodeBigUnmarked=new e(En.UnicodeBigUnmarked,25,"UnicodeBigUnmarked","UTF-16BE","UnicodeBig"),e.UTF8=new e(En.UTF8,26,"UTF8","UTF-8"),e.ASCII=new e(En.ASCII,Int32Array.from([27,170]),"ASCII","US-ASCII"),e.Big5=new e(En.Big5,28,"Big5"),e.GB18030=new e(En.GB18030,29,"GB18030","GB2312","EUC_CN","GBK"),e.EUC_KR=new e(En.EUC_KR,30,"EUC_KR","EUC-KR"),e})(),oXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),zy=(function(e){oXe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.kind="UnsupportedOperationException",t})(ui),ri=(function(){function e(){}return e.decode=function(t,n){var r=this.encodingName(n);return this.customDecoder?this.customDecoder(t,r):typeof TextDecoder>"u"||this.shouldDecodeOnFallback(r)?this.decodeFallback(t,r):new TextDecoder(r).decode(t)},e.shouldDecodeOnFallback=function(t){return!1},e.encode=function(t,n){var r=this.encodingName(n);return this.customEncoder?this.customEncoder(t,r):typeof TextEncoder>"u"?this.encodeFallback(t):new TextEncoder().encode(t)},e.isBrowser=function(){return typeof window<"u"&&{}.toString.call(window)==="[object Window]"},e.encodingName=function(t){return typeof t=="string"?t:t.getName()},e.encodingCharacterSet=function(t){return t instanceof as?t:as.getCharacterSetECIByName(t)},e.decodeFallback=function(t,n){var r=this.encodingCharacterSet(n);if(e.isDecodeFallbackSupported(r)){for(var a="",i=0,o=t.length;i<o;i++){var l=t[i].toString(16);l.length<2&&(l="0"+l),a+="%"+l}return decodeURIComponent(a)}if(r.equals(as.UnicodeBigUnmarked))return String.fromCharCode.apply(null,Array.from(new Uint16Array(t.buffer)));throw new zy("Encoding ".concat(this.encodingName(n)," not supported by fallback."))},e.isDecodeFallbackSupported=function(t){return t.equals(as.UTF8)||t.equals(as.ISO8859_1)||t.equals(as.ASCII)},e.encodeFallback=function(t){for(var n=btoa(unescape(encodeURIComponent(t))),r=n.split(""),a=[],i=0;i<r.length;i++)a.push(r[i].charCodeAt(0));return new Uint8Array(a)},e})(),tn=(function(){function e(){}return e.castAsNonUtf8Char=function(t,n){n===void 0&&(n=null);var r=n?n.getName():this.ISO88591;return ri.decode(new Uint8Array([t]),r)},e.guessEncoding=function(t,n){if(n!=null&&n.get(On.CHARACTER_SET)!==void 0)return n.get(On.CHARACTER_SET).toString();for(var r=t.length,a=!0,i=!0,o=!0,l=0,c=0,u=0,d=0,h=0,f=0,m=0,x=0,g=0,y=0,b=0,v=t.length>3&&t[0]===239&&t[1]===187&&t[2]===191,w=0;w<r&&(a||i||o);w++){var _=t[w]&255;o&&(l>0?(_&128)===0?o=!1:l--:(_&128)!==0&&((_&64)===0?o=!1:(l++,(_&32)===0?c++:(l++,(_&16)===0?u++:(l++,(_&8)===0?d++:o=!1))))),a&&(_>127&&_<160?a=!1:_>159&&(_<192||_===215||_===247)&&b++),i&&(h>0?_<64||_===127||_>
921252?i=!1:h--:_===128||_===160||_>239?i=!1:_>160&&_<224?(f++,x=0,m++,m>g&&(g=m)):_>127?(h++,m=0,x++,x>y&&(y=x)):(m=0,x=0))}return o&&l>0&&(o=!1),i&&h>0&&(i=!1),o&&(v||c+u+d>0)?e.UTF8:i&&(e.ASSUME_SHIFT_JIS||g>=3||y>=3)?e.SHIFT_JIS:a&&i?g===2&&f===2||b*10>=r?e.SHIFT_JIS:e.ISO88591:a?e.ISO88591:i?e.SHIFT_JIS:o?e.UTF8:e.PLATFORM_DEFAULT_ENCODING},e.format=function(t){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];var a=-1;function i(l,c,u,d,h,f){if(l==="%%")return"%";if(n[++a]!==void 0){l=d?parseInt(d.substr(1)):void 0;var m=h?parseInt(h.substr(1)):void 0,x;switch(f){case"s":x=n[a];break;case"c":x=n[a][0];break;case"f":x=parseFloat(n[a]).toFixed(l);break;case"p":x=parseFloat(n[a]).toPrecision(l);break;case"e":x=parseFloat(n[a]).toExponential(l);break;case"x":x=parseInt(n[a]).toString(m||16);break;case"d":x=parseFloat(parseInt(n[a],m||10).toPrecision(l)).toFixed(0);break}x=typeof x=="object"?JSON.stringify(x):(+x).toString(m);for(var g=parseInt(u),y=u&&u[0]+""=="0"?"0":" ";x.length<g;)x=c!==void 0?x+y:y+x;return x}}var o=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return t.replace(o,i)},e.getBytes=function(t,n){return ri.encode(t,n)},e.getCharCode=function(t,n){return n===void 0&&(n=0),t.charCodeAt(n)},e.getCharAt=function(t){return String.fromCharCode(t)},e.SHIFT_JIS=as.SJIS.getName(),e.GB2312="GB2312",e.ISO88591=as.ISO8859_1.getName(),e.EUC_JP="EUC_JP",e.UTF8=as.UTF8.getName(),e.PLATFORM_DEFAULT_ENCODING=e.UTF8,e.ASSUME_SHIFT_JIS=!1,e})(),Kt=(function(){function e(t){t===void 0&&(t=""),this.value=t}return e.prototype.enableDecoding=function(t){return this.encoding=t,this},e.prototype.append=function(t){return typeof t=="string"?this.value+=t.toString():this.encoding?this.value+=tn.castAsNonUtf8Char(t,this.encoding):this.value+=String.fromCharCode(t),this},e.prototype.appendChars=function(t,n,r){for(var a=n;n<n+r;a++)this.append(t[a]);return this},e.prototype.length=function(){return this.value.length},e.prototype.charAt=function(t){return this.value.charAt(t)},e.prototype.deleteCharAt=function(t){this.value=this.value.substr(0,t)+this.value.substring(t+1)},e.prototype.setCharAt=function(t,n){this.value=this.value.substr(0,t)+n+this.value.substr(t+1)},e.prototype.substring=function(t,n){return this.value.substring(t,n)},e.prototype.setLengthToZero=function(){this.value=""},e.prototype.toString=function(){return this.value},e.prototype.insert=function(t,n){this.value=this.value.substring(0,t)+n+this.value.substring(t)},e})(),_i=(function(){function e(t,n,r,a){if(this.width=t,this.height=n,this.rowSize=r,this.bits=a,n==null&&(n=t),this.height=n,t<1||n<1)throw new Ct("Both dimensions must be greater than 0");r==null&&(r=t+31>>5),this.rowSize=r,a==null&&(this.bits=new Int32Array(this.rowSize*this.height))}return e.parseFromBooleanArray=function(t){for(var n=t.length,r=t[0].length,a=new e(r,n),i=0;i<n;i++)for(var o=t[i],l=0;l<r;l++)o[l]&&a.set(l,i);return a},e.parseFromString=function(t,n,r){if(t===null)throw new Ct("stringRepresentation cannot be null");for(var a=new Array(t.length),i=0,o=0,l=-1,c=0,u=0;u<t.length;)if(t.charAt(u)===` 922`||t.charAt(u)==="\r"){if(i>o){if(l===-1)l=i-o;else if(i-o!==l)throw new Ct("row lengths do not match");o=i,c++}u++}else if(t.substring(u,u+n.length)===n)u+=n.length,a[i]=!0,i++;else if(t.substring(u,u+r.length)===r)u+=r.length,a[i]=!1,i++;else throw new Ct("illegal character encountered: "+t.substring(u));if(i>o){if(l===-1)l=i-o;else if(i-o!==l)throw new Ct("row lengths do not match");c++}for(var d=new e(l,c),h=0;h<i;h++)a[h]&&d.set(Math.floor(h%l),Math.floor(h/l));return d},e.prototype.get=function(t,n){var r=n*this.rowSize+(t>>5);return(this.bits[r]>>>(t&31)&1)!==0},e.prototype.set=function(t,n){var r=n*this.rowSize+(t>>5);this.bits[r]|=1<<(t&31)&4294967295},e.prototype.unset=function(t,n){var r=n*this.rowSize+(t>>5);this.bits[r]&=~(1<<(t&31)&4294967295)},e.prototype.flip=function(t,n){var r=n*this.rowSize+(t>>5);this.bits[r]^=1<<(t&31)&4294967295},e.prototype.xor=function(t){if(this.width!==t.getWidth()||this.height!==t.getHeight()||this.rowSize!==t.getRowSize())throw new Ct("input matrix dimensions do not match");for(var n=new ks((this.width>>5)+1),r=this.rowSize,a=this.bits,i=0,o=this.height;i<o;i++)for(var l=i*r,c=t.getRow(i,n).getBitArray(),u=0;u<r;u++)a[l+u]^=c[u]},e.prototype.clear=function(){this.bits.fill(0)},e.prototype.setRegion=function(t,n,r,a){if(n<0||t<0)throw new Ct("Left and top must be nonnegative");if(a<1||r<1)throw new Ct("Height and width must be at least 1");var i=t+r,o=n+a;if(o>this.height||i>this.width)throw new Ct("The region must fit inside the matrix");for(var l=this.rowSize,c=this.bits,u=n;u<o;u++)for(var d=u*l,h=t;h<i;h++)c[d+(h>>5)]|=1<<(h&31)&4294967295},e.prototype.getRow=function(t,n){n==null||n.getSize()<this.width?n=new ks(this.width):n.clear();for(var r=this.rowSize,a=this.bits,i=t*r,o=0;o<r;o++)n.setBulk(o*32,a[i+o]);return n},e.prototype.setRow=function(t,n){Fn.arraycopy(n.getBitArray(),0,this.bits,t*this.rowSize,this.rowSize)},e.prototype.rotate180=function(){for(var t=this.getWidth(),n=this.getHeight(),r=new ks(t),a=new ks(t),i=0,o=Math.floor((n+1)/2);i<o;i++)r=this.getRow(i,r),a=this.getRow(n-1-i,a),r.reverse(),a.reverse(),this.setRow(i,a),this.setRow(n-1-i,r)},e.prototype.getEnclosingRectangle=function(){for(var t=this.width,n=this.height,r=this.rowSize,a=this.bits,i=t,o=n,l=-1,c=-1,u=0;u<n;u++)for(var d=0;d<r;d++){var h=a[u*r+d];if(h!==0){if(u<o&&(o=u),u>c&&(c=u),d*32<i){for(var f=0;(h<<31-f&4294967295)===0;)f++;d*32+f<i&&(i=d*32+f)}if(d*32+31>l){for(var f=31;!(h>>>f);)f--;d*32+f>l&&(l=d*32+f)}}}return l<i||c<o?null:Int32Array.from([i,o,l-i+1,c-o+1])},e.prototype.getTopLeftOnBit=function(){for(var t=this.rowSize,n=this.bits,r=0;r<n.length&&n[r]===0;)r++;if(r===n.length)return null;for(var a=r/t,i=r%t*32,o=n[r],l=0;(o<<31-l&4294967295)===0;)l++;return i+=l,Int32Array.from([i,a])},e.prototype.getBottomRightOnBit=function(){for(var t=this.rowSize,n=this.bits,r=n.length-1;r>=0&&n[r]===0;)r--;if(r<0)return null;for(var a=Math.floor(r/t),i=Math.floor(r%t)*32,o=n[r],l=31;!(o>>>l);)l--;return i+=l,Int32Array.from([i,a])},e.prototype.getWidth=function(){return this.width},e.prototype.getHeight=function(){return this.height},e.prototype.getRowSize=function(){return this.rowSize},e.prototype.equals=function(t){if(!(t instanceof e))return!1;var n=t;return this.width===n.width&&this.height===n.height&&this.rowSize===n.rowSize&&is.equals(this.bits,n.bits)},e.prototype.hashCode=function(){var t=this.width;return t=31*t+this.width,t=31*t+this.height,t=31*t+this.rowSize,t=31*t+is.hashCode(this.bits),t},e.prototype.toString=function(t,n,r){return t===void 0&&(t="X "),n===void 0&&(n=" "),r===void 0&&(r=` 923`),this.buildToString(t,n,r)},e.prototype.buildToString=function(t,n,r){for(var a=new Kt,i=0,o=this.height;i<o;i++){for(var l=0,c=this.width;l<c;l++)a.append(this.get(l,i)?t:n);a.append(r)}return a.toString()},e.prototype.clone=function(){return new e(this.width,this.height,this.rowSize,this.bits.slice())},e})(),lXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
923t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Oe=(function(e){lXe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.getNotFoundInstance=function(){return new t},t.kind="NotFoundException",t})(ui),cXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),VG=(function(e){cXe(t,e);function t(n){var r=e.call(this,n)||this;return r.luminances=t.EMPTY,r.buckets=new Int32Array(t.LUMINANCE_BUCKETS),r}return t.prototype.getBlackRow=function(n,r){var a=this.getLuminanceSource(),i=a.getWidth();r==null||r.getSize()<i?r=new ks(i):r.clear(),this.initArrays(i);for(var o=a.getRow(n,this.luminances),l=this.buckets,c=0;c<i;c++)l[(o[c]&255)>>t.LUMINANCE_SHIFT]++;var u=t.estimateBlackPoint(l);if(i<3)for(var c=0;c<i;c++)(o[c]&255)<u&&r.set(c);else for(var d=o[0]&255,h=o[1]&255,c=1;c<i-1;c++){var f=o[c+1]&255;(h*4-d-f)/2<u&&r.set(c),d=h,h=f}return r},t.prototype.getBlackMatrix=function(){var n=this.getLuminanceSource(),r=n.getWidth(),a=n.getHeight(),i=new _i(r,a);this.initArrays(r);for(var o=this.buckets,l=1;l<5;l++)for(var c=Math.floor(a*l/5),u=n.getRow(c,this.luminances),d=Math.floor(r*4/5),h=Math.floor(r/5);h<d;h++){var f=u[h]&255;o[f>>t.LUMINANCE_SHIFT]++}for(var m=t.estimateBlackPoint(o),x=n.getMatrix(),l=0;l<a;l++)for(var g=l*r,h=0;h<r;h++){var f=x[g+h]&255;f<m&&i.set(h,l)}return i},t.prototype.createBinarizer=function(n){return new t(n)},t.prototype.initArrays=function(n){this.luminances.length<n&&(this.luminances=new Uint8ClampedArray(n)),this.buckets.fill(0)},t.estimateBlackPoint=function(n){for(var r=n.length,a=0,i=0,o=0,l=0;l<r;l++)n[l]>o&&(i=l,o=n[l]),n[l]>a&&(a=n[l]);for(var c=0,u=0,l=0;l<r;l++){var d=l-i,h=n[l]*d*d;h>u&&(c=l,u=h)}if(i>c){var f=i;i=c,c=f}if(c-i<=r/16)throw new Oe;for(var m=c-1,x=-1,l=c-1;l>i;l--){var g=l-i,h=g*g*(c-l)*(a-n[l]);h>x&&(m=l,x=h)}return m<<t.LUMINANCE_SHIFT},t.LUMINANCE_BITS=5,t.LUMINANCE_SHIFT=8-t.LUMINANCE_BITS,t.LUMINANCE_BUCKETS=1<<t.LUMINANCE_BITS,t.EMPTY=Uint8ClampedArray.from([0]),t})(tXe),uXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),dXe=(function(e){uXe(t,e);function t(n){var r=e.call(this,n)||this;return r.matrix=null,r}return t.prototype.getBlackMatrix=function(){if(this.matrix!==null)return this.matrix;var n=this.getLuminanceSource(),r=n.getWidth(),a=n.getHeight();if(r>=t.MINIMUM_DIMENSION&&a>=t.MINIMUM_DIMENSION){var i=n.getMatrix(),o=r>>t.BLOCK_SIZE_POWER;(r&t.BLOCK_SIZE_MASK)!==0&&o++;var l=a>>t.BLOCK_SIZE_POWER;(a&t.BLOCK_SIZE_MASK)!==0&&l++;var c=t.calculateBlackPoints(i,o,l,r,a),u=new _i(r,a);t.calculateThresholdForBlock(i,o,l,r,a,c,u),this.matrix=u}else this.matrix=e.prototype.getBlackMatrix.call(this);return this.matrix},t.prototype.createBinarizer=function(n){return new t(n)},t.calculateThresholdForBlock=function(n,r,a,i,o,l,c){for(var u=o-t.BLOCK_SIZE,d=i-t.BLOCK_SIZE,h=0;h<a;h++){var f=h<<t.BLOCK_SIZE_POWER;f>u&&(f=u);for(var m=t.cap(h,2,a-3),x=0;x<r;x++){var g=x<<t.BLOCK_SIZE_POWER;g>d&&(g=d);for(var y=t.cap(x,2,r-3),b=0,v=-2;v<=2;v++){var w=l[m+v];b+=w[y-2]+w[y-1]+w[y]+w[y+1]+w[y+2]}var _=b/25;t.thresholdBlock(n,g,f,_,i,c)}}},t.cap=function(n,r,a){return n<r?r:n>a?a:n},t.thresholdBlock=function(n,r,a,i,o,l){for(var c=0,u=a*o+r;c<t.BLOCK_SIZE;c++,u+=o)for(var d=0;d<t.BLOCK_SIZE;d++)(n[u+d]&255)<=i&&l.set(r+d,a+c)},t.calculateBlackPoints=function(n,r,a,i,o){for(var l=o-t.BLOCK_SIZE,c=i-t.BLOCK_SIZE,u=new Array(a),d=0;d<a;
923d++){u[d]=new Int32Array(r);var h=d<<t.BLOCK_SIZE_POWER;h>l&&(h=l);for(var f=0;f<r;f++){var m=f<<t.BLOCK_SIZE_POWER;m>c&&(m=c);for(var x=0,g=255,y=0,b=0,v=h*i+m;b<t.BLOCK_SIZE;b++,v+=i){for(var w=0;w<t.BLOCK_SIZE;w++){var _=n[v+w]&255;x+=_,_<g&&(g=_),_>y&&(y=_)}if(y-g>t.MIN_DYNAMIC_RANGE)for(b++,v+=i;b<t.BLOCK_SIZE;b++,v+=i)for(var w=0;w<t.BLOCK_SIZE;w++)x+=n[v+w]&255}var k=x>>t.BLOCK_SIZE_POWER*2;if(y-g<=t.MIN_DYNAMIC_RANGE&&(k=g/2,d>0&&f>0)){var j=(u[d-1][f]+2*u[d][f-1]+u[d-1][f-1])/4;g<j&&(k=j)}u[d][f]=k}}return u},t.BLOCK_SIZE_POWER=3,t.BLOCK_SIZE=1<<t.BLOCK_SIZE_POWER,t.BLOCK_SIZE_MASK=t.BLOCK_SIZE-1,t.MINIMUM_DIMENSION=t.BLOCK_SIZE*5,t.MIN_DYNAMIC_RANGE=24,t})(VG),Fw=(function(){function e(t,n){this.width=t,this.height=n}return e.prototype.getWidth=function(){return this.width},e.prototype.getHeight=function(){return this.height},e.prototype.isCropSupported=function(){return!1},e.prototype.crop=function(t,n,r,a){throw new zy("This luminance source does not support cropping.")},e.prototype.isRotateSupported=function(){return!1},e.prototype.rotateCounterClockwise=function(){throw new zy("This luminance source does not support rotation by 90 degrees.")},e.prototype.rotateCounterClockwise45=function(){throw new zy("This luminance source does not support rotation by 45 degrees.")},e.prototype.toString=function(){for(var t=new Uint8ClampedArray(this.width),n=new Kt,r=0;r<this.height;r++){for(var a=this.getRow(r,t),i=0;i<this.width;i++){var o=a[i]&255,l=void 0;o<64?l="#":o<128?l="+":o<192?l=".":l=" ",n.append(l)}n.append(` 924`)}return n.toString()},e})(),hXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),sT=(function(e){hXe(t,e);function t(n){var r=e.call(this,n.getWidth(),n.getHeight())||this;return r.delegate=n,r}return t.prototype.getRow=function(n,r){for(var a=this.delegate.getRow(n,r),i=this.getWidth(),o=0;o<i;o++)a[o]=255-(a[o]&255);return a},t.prototype.getMatrix=function(){for(var n=this.delegate.getMatrix(),r=this.getWidth()*this.getHeight(),a=new Uint8ClampedArray(r),i=0;i<r;i++)a[i]=255-(n[i]&255);return a},t.prototype.isCropSupported=function(){return this.delegate.isCropSupported()},t.prototype.crop=function(n,r,a,i){return new t(this.delegate.crop(n,r,a,i))},t.prototype.isRotateSupported=function(){return this.delegate.isRotateSupported()},t.prototype.invert=function(){return this.delegate},t.prototype.rotateCounterClockwise=function(){return new t(this.delegate.rotateCounterClockwise())},t.prototype.rotateCounterClockwise45=function(){return new t(this.delegate.rotateCounterClockwise45())},t})(Fw),fXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),t8=(function(e){fXe(t,e);function t(n,r,a){r===void 0&&(r=!1);var i=e.call(this,n.width,n.height)||this;return i.canvas=n,i.tempCanvasElement=null,i.buffer=t.makeBufferFromCanvasImageData(n,r,a),i}return t.makeBufferFromCanvasImageData=function(n,r,a){r===void 0&&(r=!1);var i=n.getContext("2d").getImageData(0,0,n.width,n.height);return t.toGrayscaleBuffer(i.data,n.width,n.height,r,a)},t.toGrayscaleBuffer=function(n,r,a,i,o){i===void 0&&(i=!1);var l=r*a,c=o&&o.length>=l?o:new Uint8ClampedArray(l);t.FRAME_INDEX=!t.FRAME_INDEX;for(var u=!t.FRAME_INDEX&&i?255:0,d=0,h=0,f=n.length;d<f;d+=4,h++){var m=void 0,x=n[d+3];if(x===0)m=255;else{var g=n[d],y=n[d+1],b=n[d+2];m=306*g+601*y+117*b+512>>10}c[h]=m^u}return c},t.prototype.getRow=function(n,r){if(n<0||n>=this.getHeight())throw new Ct("Requested row is outside the image: "+n);var a=this.getWidth(),i=n*a;return r===null?r=this.buffer.slice(i,i+a):(r.length<a&&(r=new Uint8ClampedArray(a)),r.set(this.buffer.subarray(i,i+a))),r},t.prototype.getMatrix=function(){return this.buffer},t.prototype.isCropSupported=function(){return!0},t.prototype.crop=function(n,r,a,i){return e.prototype.crop.call(this,n,r,a,i),this},t.prototype.isRotateSupported=function(){return!0},t.prototype.rotateCounterClockwise=function(){return this.rotate(-90),this},t.prototype.rotateCounterClockwise45=function(){return this.rotate(-45),this},t.prototype.getTempCanvasElement=function(){if(this.tempCanvasElement===null){var n=this.canvas.ownerDocument.createElement("canvas");n.width=this.canvas.width,n.height=this.canvas.height,this.tempCanvasElement=n}return this.tempCanvasElement},t.prototype.rotate=function(n){var r=this.getTempCanvasElement(),a=r.getContext("2d"),i=n*t.DEGREE_TO_RADIANS,o=this.canvas.width,l=this.canvas.height,c=Math.ceil(Math.abs(Math.cos(i))*o+Math.abs(Math.sin(i))*l),u=Math.ceil(Math.abs(Math.sin(i))*o+Math.abs(Math.cos(i))*l);return r.width=c,r.height=u,a.translate(c/2,u/2),a.rotate(i),a.drawImage(this.canvas,o/-2,l/-2),this.buffer=t.makeBufferFromCanvasImageData(r),this},t.prototype.invert=function(){return new sT(this)},t.DEGREE_TO_RADIANS=Math.PI/180,t.FRAME_INDEX=!0,t})(Fw),mXe=(function(){function e(t,n,r){this.deviceId=t,this.label=n,this.kind="videoinput",this.groupId=r||void 0}return e.prototype.toJSON=function(){return{kind:this.kind,groupId:this.groupId,deviceId:this.deviceId,label:this.label}},e})(),va=function(e,t,n,r){function a(i){return i instanceof n?i:new n(function(o){o(i)})}
924return new(n||(n=Promise))(function(i,o){function l(d){try{u(r.next(d))}catch(h){o(h)}}function c(d){try{u(r.throw(d))}catch(h){o(h)}}function u(d){d.done?i(d.value):a(d.value).then(l,c)}u((r=r.apply(e,t||[])).next())})},wa=function(e,t){var n={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,a,i,o=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return o.next=l(0),o.throw=l(1),o.return=l(2),typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function l(u){return function(d){return c([u,d])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;o&&(o=0,u[0]&&(n=0)),n;)try{if(r=1,a&&(i=u[0]&2?a.return:u[0]?a.throw||((i=a.return)&&i.call(a),0):a.next)&&!(i=i.call(a,u[1])).done)return i;switch(a=0,i&&(u=[u[0]&2,i.value]),u[0]){case 0:case 1:i=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,a=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(i=n.trys,!(i=i.length>0&&i[i.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!i||u[1]>i[0]&&u[1]<i[3])){n.label=u[1];break}if(u[0]===6&&n.label<i[1]){n.label=i[1],i=u;break}if(i&&n.label<i[2]){n.label=i[2],n.ops.push(u);break}i[2]&&n.ops.pop(),n.trys.pop();continue}u=t.call(e,n)}catch(d){u=[6,d],a=0}finally{r=i=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}},pXe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},Vf=(function(){function e(t,n,r){n===void 0&&(n=500),this.reader=t,this.timeBetweenScansMillis=n,this._hints=r,this._stopContinuousDecode=!1,this._stopAsyncDecode=!1,this._timeBetweenDecodingAttempts=0}return Object.defineProperty(e.prototype,"hasNavigator",{get:function(){return typeof navigator<"u"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isMediaDevicesSuported",{get:function(){return this.hasNavigator&&!!navigator.mediaDevices},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"canEnumerateDevices",{get:function(){return!!(this.isMediaDevicesSuported&&navigator.mediaDevices.enumerateDevices)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"timeBetweenDecodingAttempts",{get:function(){return this._timeBetweenDecodingAttempts},set:function(t){this._timeBetweenDecodingAttempts=t<0?0:t},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hints",{get:function(){return this._hints},set:function(t){this._hints=t||null},enumerable:!1,configurable:!0}),e.prototype.listVideoInputDevices=function(){return va(this,void 0,void 0,function(){var t,n,r,a,i,o,l,c,u,d,h,f;return wa(this,function(m){switch(m.label){case 0:if(!this.hasNavigator)throw new Error("Can't enumerate devices, navigator is not present.");if(!this.canEnumerateDevices)throw new Error("Can't enumerate devices, method not supported.");return[4,navigator.mediaDevices.enumerateDevices()];case 1:t=m.sent(),n=[];try{for(r=pXe(t),a=r.next();!a.done;a=r.next())i=a.value,o=i.kind==="video"?"videoinput":i.kind,o==="videoinput"&&(l=i.deviceId||i.id,c=i.label||"Video device ".concat(n.length+1),u=i.groupId,d={deviceId:l,label:c,kind:o,groupId:u},n.push(d))}catch(x){h={error:x}}finally{try{a&&!a.done&&(f=r.return)&&f.call(r)}finally{if(h)throw h.error}}return[2,n]}})})},e.prototype.getVideoInputDevices=function(){return va(this,void 0,void 0,function(){var t;return wa(this,function(n){switch(n.label){case 0:return[4,this.listVideoInputDevices()];case 1:return t=n.sent(),[2,t.map(function(r){return new mXe(r.deviceId,r.label)})]}})})},e.prototype.findDeviceById=function(t){return va(this,void 0,void 0,function(){var n;return wa(this,function(r){switch(r.label){case 0:return[4,this.listVideoInputDevices()];case 1:return n=r.sent(),n?[2,n.find(function(a){return a.deviceId===t})]:[2,null]}})})},e.prototype.decodeFromInputVideoDevice=function(t,n){return va(this,void 0,void 0,function(){return wa(this,function(r){switch(r.label){case 0:return[4,this.decodeOnceFromVideoDevice(t,n)];case 1:return[2,r.sent()]}})})},e.prototype.decodeOnceFromVideoDevice=function(t,n){return va(this,void 0,void 0,function(){var r,a;return wa(this,function(i){switch(i.label){case 0:return this.reset(),t?r={deviceId:{exact:t}}:r={facingMode:"environment"},a={video:r},[4,this.decodeOnceFromConstraints(a,n)];case 1:return[2,i.sent()]}})})},e.prototype.decodeOnceFromConstraints=function(t,n){return va(this,void 0,void 0,function(){var r;return wa(this,function(a){switch(a.label){case 0:return[4,navigator.mediaDevices.getUserMedia(t)];case 1:return r=a.sent(),[4,this.decodeOnceFromStream(r,n)];case 2:return[2,a.sent()]}})})},e.prototype.decodeOnceFromStream=function(t,n){return va(this,void 0,void 0,function(){var r,a;return wa(this,function(i){switch(i.label){case 0:return this.reset(),[4,this.attachStreamToVideo(t,n)];case 1:return r=i.sent(),[4,this.decodeOnce(r)];case 2:return a=i.sent(),[2,a]}})})},e.prototype.decodeFromInputVideoDeviceContinuously=function(t,n,r){return va(this,void 0,void 0,function(){return wa(this,function(a){switch(a.label){case 0:return[4,this.decodeFromVideoDevice(t,n,r)];case 1:return[2,a.sent()]}})})},e.prototype.decodeFromVideoDevice=function(t,n,r){return va(this,void 0,void 0,function(){var a,i;return wa(this,function(o){switch(o.label){case 0:return t?a={deviceId:{exact:t}}:a={facingMode:"environment"},i={video:a},[4,this.decodeFromConstraints(i,n,r)];case 1:return[2,o.sent()]}})})},e.prototype.decodeFromConstraints=function(t,n,r){return va(this,void 0,void 0,function(){var a;return wa(this,function(i){switch(i.label){case 0:return[4,navigator.mediaDevices.getUserMedia(t)];case 1:return a=i.sent(),[4,this.decodeFromStream(a,n,r)];case 2:return[2,i.sent()]}})})},e.prototype.decodeFromStream=function(t,n,r){return va(this,void 0,void 0,function(){var a;return wa(this,function(i){switch(i.label){case 0:return this.reset(),[4,this.attachStreamToVideo(t,n)];case 1:return a=i.sent(),[4,this.decodeContinuously(a,r)];case 2:return[2,i.sent()]}})})},e.prototype.stopAsyncDecode=function(){this._stopAsyncDecode=!0},e.prototype.stopContinuousDecode=function(){this._stopContinuousDecode=!0},e.prototype.attachStreamToVideo=function(t,n){return va(this,void 0,void 0,function(){var r;return wa(this,function(a){switch(a.label){case 0:return r=this.prepareVideoElement(n),this.addVideoSource(r,t),this.videoElement=r,this.stream=t,[4,this.playVideoOnLoadAsync(r)];case 1:return a.sent(),[2,r]}})})},e.prototype.playVideoOnLoadAsync=function(t){var n=this;return new Promise(function(r,a){return n.playVideoOnLoad(t,function(){return r()})})},e.prototype.playVideoOnLoad=function(t,n){var r=this;this.videoEndedListener=function(){return r.stopStreams()},this.videoCanPlayListener=function(){return r.tryPlayVideo(t)},t.addEventListener("ended",this.videoEndedListener),t.addEventListener("canplay",this.videoCanPlayListener),t.addEventListener("playing",n),this.tryPlayVideo(t)},e.prototype.isVideoPlaying=function(t){return t.currentTime>0&&!t.paused&&!t.ended&&t.readyState>2},e.prototype.tryPlayVideo=function(t){return va(this,void 0,void 0,function(){return wa(this,function(n){switch(n.label){case 0:if(this.isVideoPlaying(t))return console.warn("Trying to play video that is already playing."),[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,t.play()];case 2:return n.sent(),[3,4];case 3:return n.sent(),console.warn("It was not possible to play the video."),[3,4];case 4:return[2]}})})},e.prototype.getMediaElement=function(t,n){var r=document.getElementById(t);if(!r)throw new co("element with id '".concat(t,"' not found"));if(r.nodeName.toLowerCase()!==n.toLowerCase())throw new co("element with id '".concat(t,"' must be an ").concat(n," element"));return r},e.prototype.decodeFromImage=function(t,n){if(!t&&!n)throw new co("either imageElement with a src set or an url must be provided");return n&&!t?this.decodeFromImageUrl(n):this.decodeFromImageElement(t)},e.prototype.decodeFromVideo=function(t,n){if(!t&&!n)throw new co("Either an element with a src set or an URL must be provided");return n&&!t?this.decodeFromVideoUrl(n):this.decodeFromVideoElement(t)},e.prototype.decodeFromVideoContinuously=function(t,n,r){if(t===void 0&&n===void 0)throw new co("Either an element with a src set or an URL must be provided");return n&&!t?this.decodeFromVideoUrlContinuously(n,r):this.decodeFromVideoElementContinuously(t,r)},e.prototype.decodeFromImageElement=function(t){if(!t)throw new co("An image element must be provided.");this.reset();var n=this.prepareImageElement(t);this.imageElement=n;var r;return this.isImageLoaded(n)?r=this.decodeOnce(n,!1,!0):r=this._decodeOnLoadImage(n),r},e.prototype.decodeFromVideoElement=function(t){var n=this._decodeFromVideoElementSetup(t);return this._decodeOnLoadVideo(n)},e.prototype.decodeFromVideoElementContinuously=function(t,n){var r=this._decodeFromVideoElementSetup(t);return this._decodeOnLoadVideoContinuously(r,n)},e.prototype._decodeFromVideoElementSetup=function(t){if(!t)throw new co("A video element must be provided.");this.reset();var n=this.prepareVideoElement(t);return this.videoElement=n,n},e.prototype.decodeFromImageUrl=function(t){if(!t)throw new co("An URL must be provided.");this.reset();var n=this.prepareImageElement();this.imageElement=n;var r=this._decodeOnLoadImage(n);return n.src=t,r},e.prototype.decodeFromVideoUrl=function(t){if(!t)throw new co("An URL must be provided.");this.reset();var n=this.prepareVideoElement(),r=this.decodeFromVideoElement(n);return n.src=t,r},e.prototype.decodeFromVideoUrlContinuously=function(t,n){if(!t)throw new co("An URL must be provided.");this.reset();var r=this.prepareVideoElement(),a=this.decodeFromVideoElementContinuously(r,n);return r.src=t,a},e.prototype._decodeOnLoadImage=function(t){var n=this;return new Promise(function(r,a){n.imageLoadedListener=function(){return n.decodeOnce(t,!1,!0).then(r,a)},t.addEventListener("load",n.imageLoadedListener)})},e.prototype._decodeOnLoadVideo=function(t){return va(this,void 0,void 0,function(){return wa(this,function(n){switch(n.label){case 0:return[4,this.playVideoOnLoadAsync(t)];case 1:return n.sent(),[4,this.decodeOnce(t)];case 2:return[2,n.sent()]}})})},e.prototype._decodeOnLoadVideoContinuously=function(t,n){return va(this,void 0,void 0,function(){return wa(this,function(r){switch(r.label){case 0:return[4,this.playVideoOnLoadAsync(t)];case 1:return r.sent(),this.decodeContinuously(t,n),[2]}})})},e.prototype.isImageLoaded=function(t){return!(!t.complete||t.naturalWi
924dth===0)},e.prototype.prepareImageElement=function(t){var n;return typeof t>"u"&&(n=document.createElement("img"),n.width=200,n.height=200),typeof t=="string"&&(n=this.getMediaElement(t,"img")),t instanceof HTMLImageElement&&(n=t),n},e.prototype.prepareVideoElement=function(t){var n;return!t&&typeof document<"u"&&(n=document.createElement("video"),n.width=200,n.height=200),typeof t=="string"&&(n=this.getMediaElement(t,"video")),t instanceof HTMLVideoElement&&(n=t),n.setAttribute("autoplay","true"),n.setAttribute("muted","true"),n.setAttribute("playsinline","true"),n},e.prototype.decodeOnce=function(t,n,r){var a=this;n===void 0&&(n=!0),r===void 0&&(r=!0),this._stopAsyncDecode=!1;var i=function(o,l){if(a._stopAsyncDecode){l(new Oe("Video stream has ended before any code could be detected.")),a._stopAsyncDecode=void 0;return}try{var c=a.decode(t);o(c)}catch(f){var u=n&&f instanceof Oe,d=f instanceof Yr||f instanceof We,h=d&&r;if(u||h)return setTimeout(i,a._timeBetweenDecodingAttempts,o,l);l(f)}};return new Promise(function(o,l){return i(o,l)})},e.prototype.decodeContinuously=function(t,n){var r=this;this._stopContinuousDecode=!1;var a=function(){if(r._stopContinuousDecode){r._stopContinuousDecode=void 0;return}try{var i=r.decode(t);n(i,null),setTimeout(a,r.timeBetweenScansMillis)}catch(c){n(null,c);var o=c instanceof Yr||c instanceof We,l=c instanceof Oe;o||l?setTimeout(a,r._timeBetweenDecodingAttempts):console.error("BrowserCodeReader: unexpected error during decode, stopping scan loop:",c)}};a()},e.prototype.decode=function(t){var n=this.createBinaryBitmap(t);try{return this.decodeBitmap(n)}catch(l){if(l instanceof Oe){var r=this.getCaptureCanvas(t),a=new t8(r,!1),i=new VG(a),o=new QL(i);return this.decodeBitmap(o)}throw l}},e.prototype.createBinaryBitmap=function(t){this.getCaptureCanvasContext(t);var n=!1;t instanceof HTMLVideoElement?(this.drawFrameOnCanvas(t),n=!0):this.drawImageOnCanvas(t);var r=this.getCaptureCanvas(t),a=new t8(r,n,this._grayscaleBuffer);this._grayscaleBuffer=a.getMatrix();var i=new dXe(a);return new QL(i)},e.prototype.getCaptureCanvasContext=function(t){if(!this.captureCanvasContext){var n=this.getCaptureCanvas(t),r=void 0;try{r=n.getContext("2d",{willReadFrequently:!0})}catch{r=n.getContext("2d")}this.captureCanvasContext=r}return this.captureCanvasContext},e.prototype.getCaptureCanvas=function(t){if(!this.captureCanvas){var n=this.createCaptureCanvas(t);this.captureCanvas=n}return this.captureCanvas},e.prototype.drawFrameOnCanvas=function(t,n,r){n===void 0&&(n={sx:0,sy:0,sWidth:t.videoWidth,sHeight:t.videoHeight,dx:0,dy:0,dWidth:t.videoWidth,dHeight:t.videoHeight}),r===void 0&&(r=this.captureCanvasContext),r.drawImage(t,n.sx,n.sy,n.sWidth,n.sHeight,n.dx,n.dy,n.dWidth,n.dHeight)},e.prototype.drawImageOnCanvas=function(t,n,r){n===void 0&&(n={sx:0,sy:0,sWidth:t.naturalWidth,sHeight:t.naturalHeight,dx:0,dy:0,dWidth:t.naturalWidth,dHeight:t.naturalHeight}),r===void 0&&(r=this.captureCanvasContext),r.drawImage(t,n.sx,n.sy,n.sWidth,n.sHeight,n.dx,n.dy,n.dWidth,n.dHeight)},e.prototype.decodeBitmap=function(t){try{return this.reader.decode(t,this._hints)}finally{this.reader.reset()}},e.prototype.createCaptureCanvas=function(t){if(typeof document>"u")return this._destroyCaptureCanvas(),null;var n=document.createElement("canvas"),r,a;return typeof t<"u"&&(t instanceof HTMLVideoElement?(r=t.videoWidth,a=t.videoHeight):t instanceof HTMLImageElement&&(r=t.naturalWidth||t.width,a=t.naturalHeight||t.height)),n.style.width=r+"px",n.style.height=a+"px",n.width=r,n.height=a,n},e.prototype.stopStreams=function(){this.stream&&(this.stream.getVideoTracks().forEach(function(t){return t.stop()}),this.stream=void 0),this._stopAsyncDecode===!1&&this.stopAsyncDecode(),this._stopContinuousDecode===!1&&this.stopContinuousDecode()},e.prototype.reset=function(){this.stopStreams(),this._destroyVideoElement(),this._destroyImageElement(),this._destroyCaptureCanvas()},e.prototype._destroyVideoElement=function(){this.videoElement&&(typeof this.videoEndedListener<"u"&&this.videoElement.removeEventListener("ended",this.videoEndedListener),typeof this.videoPlayingEventListener<"u"&&this.videoElement.removeEventListener("playing",this.videoPlayingEventListener),typeof this.videoCanPlayListener<"u"&&this.videoElement.removeEventListener("loadedmetadata",this.videoCanPlayListener),this.cleanVideoSource(this.videoElement),this.videoElement=void 0)},e.prototype._destroyImageElement=function(){this.imageElement&&(this.imageLoadedListener!==void 0&&this.imageElement.removeEventListener("load",this.imageLoadedListener),this.imageElement.src=void 0,this.imageElement.removeAttribute("src"),this.imageElement=void 0)},e.prototype._destroyCaptureCanvas=function(){this.captureCanvasContext=void 0,this.captureCanvas=void 0},e.prototype.addVideoSource=function(t,n){try{t.srcObject=n}catch{t.src=URL.createObjectURL(n)}},e.prototype.cleanVideoSource=function(t){try{t.srcObject=null}catch{t.src=""}this.videoElement.removeAttribute("src")},e})(),Ts=(function(){function e(t,n,r,a,i,o){r===void 0&&(r=n==null?0:8*n.length),o===void 0&&(o=
924Fn.currentTimeMillis()),this.text=t,this.rawBytes=n,this.numBits=r,this.resultPoints=a,this.format=i,this.timestamp=o,this.text=t,this.rawBytes=n,r==null?this.numBits=n==null?0:8*n.length:this.numBits=r,this.resultPoints=a,this.format=i,this.resultMetadata=null,o==null?this.timestamp=Fn.currentTimeMillis():this.timestamp=o}return e.prototype.getText=function(){return this.text},e.prototype.getRawBytes=function(){return this.rawBytes},e.prototype.getNumBits=function(){return this.numBits},e.prototype.getResultPoints=function(){return this.resultPoints},e.prototype.getBarcodeFormat=function(){return this.format},e.prototype.getResultMetadata=function(){return this.resultMetadata},e.prototype.putMetadata=function(t,n){this.resultMetadata===null&&(this.resultMetadata=new Map),this.resultMetadata.set(t,n)},e.prototype.putAllMetadata=function(t){t!==null&&(this.resultMetadata===null?this.resultMetadata=t:this.resultMetadata=new Map(t))},e.prototype.addResultPoints=function(t){var n=this.resultPoints;if(n===null)this.resultPoints=t;else if(t!==null&&t.length>0){var r=new Array(n.length+t.length);Fn.arraycopy(n,0,r,0,n.length),Fn.arraycopy(t,0,r,n.length,t.length),this.resultPoints=r}},e.prototype.getTimestamp=function(){return this.timestamp},e.prototype.toString=function(){return this.text},e})(),wt;(function(e){e[e.AZTEC=0]="AZTEC",e[e.CODABAR=1]="CODABAR",e[e.CODE_39=2]="CODE_39",e[e.CODE_93=3]="CODE_93",e[e.CODE_128=4]="CODE_128",e[e.DATA_MATRIX=5]="DATA_MATRIX",e[e.EAN_8=6]="EAN_8",e[e.EAN_13=7]="EAN_13",e[e.ITF=8]="ITF",e[e.MAXICODE=9]="MAXICODE",e[e.PDF_417=10]="PDF_417",e[e.QR_CODE=11]="QR_CODE",e[e.RSS_14=12]="RSS_14",e[e.RSS_EXPANDED=13]="RSS_EXPANDED",e[e.UPC_A=14]="UPC_A",e[e.UPC_E=15]="UPC_E",e[e.UPC_EAN_EXTENSION=16]="UPC_EAN_EXTENSION",e[e.MICRO_QR_CODE=17]="MICRO_QR_CODE"})(wt||(wt={}));var jr;(function(e){e[e.OTHER=0]="OTHER",e[e.ORIENTATION=1]="ORIENTATION",e[e.BYTE_SEGMENTS=2]="BYTE_SEGMENTS",e[e.ERROR_CORRECTION_LEVEL=3]="ERROR_CORRECTION_LEVEL",e[e.ISSUE_NUMBER=4]="ISSUE_NUMBER",e[e.SUGGESTED_PRICE=5]="SUGGESTED_PRICE",e[e.POSSIBLE_COUNTRY=6]="POSSIBLE_COUNTRY",e[e.UPC_EAN_EXTENSION=7]="UPC_EAN_EXTENSION",e[e.PDF417_EXTRA_METADATA=8]="PDF417_EXTRA_METADATA",e[e.STRUCTURED_APPEND_SEQUENCE=9]="STRUCTURED_APPEND_SEQUENCE",e[e.STRUCTURED_APPEND_PARITY=10]="STRUCTURED_APPEND_PARITY",e[e.ERRORS_CORRECTED=11]="ERRORS_CORRECTED"})(jr||(jr={}));var qf=(function(){function e(t,n,r,a,i,o){i===void 0&&(i=-1),o===void 0&&(o=-1),this.rawBytes=t,this.text=n,this.byteSegments=r,this.ecLevel=a,this.structuredAppendSequenceNumber=i,this.structuredAppendParity=o,this.numBits=t==null?0:8*t.length}return e.prototype.getRawBytes=function(){return this.rawBytes},e.prototype.getNumBits=function(){return this.numBits},e.prototype.setNumBits=function(t){this.numBits=t},e.prototype.getText=function(){return this.text},e.prototype.getByteSegments=function(){return this.byteSegments},e.prototype.getECLevel=function(){return this.ecLevel},e.prototype.getErrorsCorrected=function(){return this.errorsCorrected},e.prototype.setErrorsCorrected=function(t){this.errorsCorrected=t},e.prototype.getErasures=function(){return this.erasures},e.prototype.setErasures=function(t){this.erasures=t},e.prototype.getOther=function(){return this.other},e.prototype.setOther=function(t){this.other=t},e.prototype.hasStructuredAppend=function(){return this.structuredAppendParity>=0&&this.structuredAppendSequenceNumber>=0},e.prototype.getStructuredAppendParity=function(){return this.structuredAppendParity},e.prototype.getStructuredAppendSequenceNumber=function(){return this.structuredAppendSequenceNumber},e})(),Um=(function(){function e(){}return e.prototype.exp=function(t){return this.expTable[t]},e.prototype.log=function(t){if(t===0)throw new Ct;return this.logTable[t]},e.addOrSubtract=function(t,n){return t^n},e})(),Qc=(function(){function e(t,n){if(n.length===0)throw new Ct;this.field=t;var r=n.length;if(r>1&&n[0]===0){for(var a=1;a<r&&n[a]===0;)a++;a===r?this.coefficients=Int32Array.from([0]):(this.coefficients=new Int32Array(r-a),Fn.arraycopy(n,a,this.coefficients,0,this.coefficients.length))}else this.coefficients=n}return e.prototype.getCoefficients=function(){return this.coefficients},e.prototype.getDegree=function(){return this.coefficients.length-1},e.prototype.isZero=function(){return this.coefficients[0]===0},e.prototype.getCoefficient=function(t){return this.coefficients[this.coefficients.length-1-t]},e.prototype.evaluateAt=function(t){if(t===0)return this.getCoefficient(0);var n=this.coefficients,r;if(t===1){r=0;for(var a=0,i=n.length;a!==i;a++){var o=n[a];r=Um.addOrSubtract(r,o)}return r}r=n[0];for(var l=n.length,c=this.field,a=1;a<l;a++)r=Um.addOrSubtract(c.multiply(t,r),n[a]);return r},e.prototype.addOrSubtract=function(t){if(!this.field.equals(t.field))throw new Ct("GenericGFPolys do n
924ot have same GenericGF field");if(this.isZero())return t;if(t.isZero())return this;var n=this.coefficients,r=t.coefficients;if(n.length>r.length){var a=n;n=r,r=a}var i=new Int32Array(r.length),o=r.length-n.length;Fn.arraycopy(r,0,i,0,o);for(var l=o;l<r.length;l++)i[l]=Um.addOrSubtract(n[l-o],r[l]);return new e(this.field,i)},e.prototype.multiply=function(t){if(!this.field.equals(t.field))throw new Ct("GenericGFPolys do not have same GenericGF field");if(this.isZero()||t.isZero())return this.field.getZero();for(var n=this.coefficients,r=n.length,a=t.coefficients,i=a.length,o=new Int32Array(r+i-1),l=this.field,c=0;c<r;c++)for(var u=n[c],d=0;d<i;d++)o[c+d]=Um.addOrSubtract(o[c+d],l.multiply(u,a[d]));return new e(l,o)},e.prototype.multiplyScalar=function(t){if(t===0)return this.field.getZero();if(t===1)return this;for(var n=this.coefficients.length,r=this.field,a=new Int32Array(n),i=this.coefficients,o=0;o<n;o++)a[o]=r.multiply(i[o],t);return new e(r,a)},e.prototype.multiplyByMonomial=function(t,n){if(t<0)throw new Ct;if(n===0)return this.field.getZero();for(var r=this.coefficients,a=r.length,i=new Int32Array(a+t),o=this.field,l=0;l<a;l++)i[l]=o.multiply(r[l],n);return new e(o,i)},e.prototype.divide=function(t){if(!this.field.equals(t.field))throw new Ct("GenericGFPolys do not have same GenericGF field");if(t.isZero())throw new Ct("Divide by 0");for(var n=this.field,r=n.getZero(),a=this,i=t.getCoefficient(t.getDegree()),o=n.inverse(i);a.getDegree()>=t.getDegree()&&!a.isZero();){var l=a.getDegree()-t.getDegree(),c=n.multiply(a.getCoefficient(a.getDegree()),o),u=t.multiplyByMonomial(l,c),d=n.buildMonomial(l,c);r=r.addOrSubtract(d),a=a.addOrSubtract(u)}return[r,a]},e.prototype.toString=function(){for(var t="",n=this.getDegree();n>=0;n--){var r=this.getCoefficient(n);if(r!==0){if(r<0?(t+=" - ",r=-r):t.length>0&&(t+=" + "),n===0||r!==1){var a=this.field.log(r);a===0?t+="1":a===1?t+="a":(t+="a^",t+=a)}n!==0&&(n===1?t+="x":(t+="x^",t+=n))}}return t},e})(),xXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),qG=(function(e){xXe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.kind="ArithmeticException",t})(ui),gXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),ra=(function(e){gXe(t,e);function t(n,r,a){var i=e.call(this)||this;i.primitive=n,i.size=r,i.generatorBase=a;for(var o=new Int32Array(r),l=1,c=0;c<r;c++)o[c]=l,l*=2,l>=r&&(l^=n,l&=r-1);i.expTable=o;for(var u=new Int32Array(r),c=0;c<r-1;c++)u[o[c]]=c;return i.logTable=u,i.zero=new Qc(i,Int32Array.from([0])),i.one=new Qc(i,Int32Array.from([1])),i}return t.prototype.getZero=function(){return this.zero},t.prototype.getOne=function(){return this.one},t.prototype.buildMonomial=function(n,r){if(n<0)throw new Ct;if(r===0)return this.zero;var a=new Int32Array(n+1);return a[0]=r,new Qc(this,a)},t.prototype.inverse=function(n){if(n===0)throw new qG;return this.expTable[this.size-this.logTable[n]-1]},t.prototype.multiply=function(n,r){return n===0||r===0?0:this.expTable[(this.logTable[n]+this.logTable[r])%(this.size-1)]},t.prototype.getSize=function(){return this.size},t.prototype.getGeneratorBase=function(){return this.generatorBase},t.prototype.toString=function(){return"GF(0x"+Zt.toHexString(this.primitive)+","+this.size+")"},t.prototype.equals=function(n){return n===this},t.AZTEC_DATA_12=new t(4201,4096,1),t.AZTEC_DATA_10=new t(1033,1024,1),t.AZTEC_DATA_6=new t(67,64,1),t.AZTEC_PARAM=new t(19,16,1),t.QR_CODE_FIELD_256=new t(285,256,0),t.DATA_MATRIX_FIELD_256=new t(301,256,1),t.AZTEC_DATA_8=t.DATA_MATRIX_FIELD_256,t.MAXICODE_FIELD_64=t.AZTEC_DATA_6,t})(Um),yXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
924t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),zm=(function(e){yXe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.kind="ReedSolomonException",t})(ui),bXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Gf=(function(e){bXe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.kind="IllegalStateException",t})(ui),Yf=(function(){function e(t){this.field=t}return e.prototype.decode=function(t,n){this.decodeWithECCount(t,n)},e.prototype.decodeWithECCount=function(t,n){for(var r=this.field,a=new Qc(r,t),i=new Int32Array(n),o=!0,l=0;l<n;l++){var c=a.evaluateAt(r.exp(l+r.getGeneratorBase()));i[i.length-1-l]=c,c!==0&&(o=!1)}if(o)return 0;for(var u=new Qc(r,i),d=this.runEuclideanAlgorithm(r.buildMonomial(n,1),u,n),h=d[0],f=d[1],m=this.findErrorLocations(h),x=this.findErrorMagnitudes(f,m),l=0;l<m.length;l++){var g=t.length-1-r.log(m[l]);if(g<0)throw new zm("Bad error location");t[g]=ra.addOrSubtract(t[g],x[l])}return m.length},e.prototype.runEuclideanAlgorithm=function(t,n,r){if(t.getDegree()<n.getDegree()){var a=t;t=n,n=a}for(var i=this.field,o=t,l=n,c=i.getZero(),u=i.getOne();l.getDegree()>=(r/2|0);){var d=o,h=c;if(o=l,c=u,o.isZero())throw new zm("r_{i-1} was zero");l=d;for(var f=i.getZero(),m=o.getCoefficient(o.getDegree()),x=i.inverse(m);l.getDegree()>=o.getDegree()&&!l.isZero();){var g=l.getDegree()-o.getDegree(),y=i.multiply(l.getCoefficient(l.getDegree()),x);f=f.addOrSubtract(i.buildMonomial(g,y)),l=l.addOrSubtract(o.multiplyByMonomial(g,y))}if(u=f.multiply(c).addOrSubtract(h),l.getDegree()>=o.getDegree())throw new Gf("Division algorithm failed to reduce polynomial?")}var b=u.getCoefficient(0);if(b===0)throw new zm("sigmaTilde(0) was zero");var v=i.inverse(b),w=u.multiplyScalar(v),_=l.multiplyScalar(v);return[w,_]},e.prototype.findErrorLocations=function(t){var n=t.getDegree();if(n===1)return Int32Array.from([t.getCoefficient(1)]);for(var r=new Int32Array(n),a=0,i=this.field,o=1;o<i.getSize()&&a<n;o++)t.evaluateAt(o)===0&&(r[a]=i.inverse(o),a++);if(a!==n)throw new zm("Error locator degree does not match number of roots");return r},e.prototype.findErrorMagnitudes=function(t,n){for(var r=n.length,a=new Int32Array(r),i=this.field,o=0;o<r;o++){for(var l=i.inverse(n[o]),c=1,u=0;u<r;u++)if(o!==u){var d=i.multiply(n[u],l),h=(d&1)===0?d|1:d&-2;c=i.multiply(c,h)}a[o]=i.multiply(t.evaluateAt(l),i.inverse(c)),i.getGeneratorBase()!==0&&(a[o]=i.multiply(a[o],l))}return a},e})(),Ps;(function(e){e[e.UPPER=0]="UPPER",e[e.LOWER=1]="LOWER",e[e.MIXED=2]="MIXED",e[e.DIGIT=3]="DIGIT",e[e.PUNCT=4]="PUNCT",e[e.BINARY=5]="BINARY"})(Ps||(Ps={}));var n8=(function(){function e(){}return e.prototype.decode=function(t){this.ddata=t;var n=t.getBits(),r=this.extractBits(n),a=this.correctBits(r),i=e.convertBoolArrayToByteArray(a),o=e.getEncodedData(a),l=new qf(i,o,null,null);return l.setNumBits(a.length),l},e.highLevelDecode=function(t){return this.getEncodedData(t)},e.getEncodedData=function(t){for(var n=t.length,r=Ps.UPPER,a=Ps.UPPER,i="",o=0;o<n;)if(a===Ps.BINARY){if(n-o<5)break;var l=e.readCode(t,o,5);if(o+=5,l===0){if(n-o<11)break;l=e.readCode(t,o,11)+31,o+=11}for(var c=0;c<l;c++){if(n-o<8){o=n;break}var u=e.readCode(t,o,8);i+=tn.castAsNonUtf8Char(u),o+=8}a=r}else{var d=a===Ps.DIGIT?4:5;if(n-o<d)break;var u=e.readCode(t,o,d);o+=d;var h=e.getCharacter(a,u);h.startsWith("CTRL_")?(r=a,a=e.getTable(h.charAt(5)),h.charAt(6)==="L"&&(r=a)):(i+=h,a=r)}return i},e.getTable=function(t){switch(t){case"L":return Ps.LOWER;case"P":return Ps.PUNCT;case"M":return Ps.MIXED;case"D":return Ps.DIGIT;case"B":return Ps.BINARY;case"U":default:return Ps.UPPER}},e.getCharacter=function(t,n){switch(t){case Ps.UPPER:return e.UPPER_TABLE[n];case Ps.LOWER:return e.LOWER_TABLE[n];case Ps.MIXED:return e.MIXED_TABLE[n];case Ps.PUNCT:return e.PUNCT_TABLE[n];case Ps.DIGIT:return e.DIGIT_TABLE[n];default:throw new Gf("Bad table")}},e.prototype.correctBits=function(t){var n,r;this.ddata.getNbLayers()<=2?(r=6,n=ra.AZTEC_DATA_6):this.ddata.getNbLayers()<=8?(r=8,n=ra.AZTEC_DATA_8):this.ddata.getNbLayers()<=22?(r=10,n=ra.AZTEC_DATA_10):(r=12,n=ra.AZTEC_DATA_12);var a=this.ddata.getNbDatablocks(),i=t.length/r;if(i<a)throw new We;
924for(var o=t.length%r,l=new Int32Array(i),c=0;c<i;c++,o+=r)l[c]=e.readCode(t,o,r);try{var u=new Yf(n);u.decode(l,i-a)}catch(y){throw new We(y)}for(var d=(1<<r)-1,h=0,c=0;c<a;c++){var f=l[c];if(f===0||f===d)throw new We;(f===1||f===d-1)&&h++}for(var m=new Array(a*r-h),x=0,c=0;c<a;c++){var f=l[c];if(f===1||f===d-1)m.fill(f>1,x,x+r-1),x+=r-1;else for(var g=r-1;g>=0;--g)m[x++]=(f&1<<g)!==0}return m},e.prototype.extractBits=function(t){var n=this.ddata.isCompact(),r=this.ddata.getNbLayers(),a=(n?11:14)+r*4,i=new Int32Array(a),o=new Array(this.totalBitsInLayer(r,n));if(n)for(var l=0;l<i.length;l++)i[l]=l;else for(var c=a+1+2*Zt.truncDivision(Zt.truncDivision(a,2)-1,15),u=a/2,d=Zt.truncDivision(c,2),l=0;l<u;l++){var h=l+Zt.truncDivision(l,15);i[u-l-1]=d-h-1,i[u+l]=d+h+1}for(var l=0,f=0;l<r;l++){for(var m=(r-l)*4+(n?9:12),x=l*2,g=a-1-x,y=0;y<m;y++)for(var b=y*2,v=0;v<2;v++)o[f+b+v]=t.get(i[x+v],i[x+y]),o[f+2*m+b+v]=t.get(i[x+y],i[g-v]),o[f+4*m+b+v]=t.get(i[g-v],i[g-y]),o[f+6*m+b+v]=t.get(i[g-y],i[x+v]);f+=m*8}return o},e.readCode=function(t,n,r){for(var a=0,i=n;i<n+r;i++)a<<=1,t[i]&&(a|=1);return a},e.readByte=function(t,n){var r=t.length-n;return r>=8?e.readCode(t,n,8):e.readCode(t,n,r)<<8-r},e.convertBoolArrayToByteArray=function(t){for(var n=new Uint8Array((t.length+7)/8),r=0;r<n.length;r++)n[r]=e.readByte(t,8*r);return n},e.prototype.totalBitsInLayer=function(t,n){return((n?88:112)+16*t)*t},e.UPPER_TABLE=["CTRL_PS"," ","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","CTRL_LL","CTRL_ML","CTRL_DL","CTRL_BS"],e.LOWER_TABLE=["CTRL_PS"," ","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","CTRL_US","CTRL_ML","CTRL_DL","CTRL_BS"],e.MIXED_TABLE=["CTRL_PS"," ","�","�","�","�","�","�","\x07","\b"," ",` 925`,"\v","\f","\r","\x1B","�","�","�","�","@","\\","^","_","`","|","~","�","CTRL_LL","CTRL_UL","CTRL_PL","CTRL_BS"],e.PUNCT_TABLE=["","\r",`\r 926`,". ",", ",": ","!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}","CTRL_UL"],e.DIGIT_TABLE=["CTRL_PS"," ","0","1","2","3","4","5","6","7","8","9",",",".","CTRL_UL","CTRL_US"],e})(),mn=(function(){function e(){}return e.round=function(t){return isNaN(t)?0:t<=Number.MIN_SAFE_INTEGER?Number.MIN_SAFE_INTEGER:t>=Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:t+(t<0?-.5:.5)|0},e.distance=function(t,n,r,a){var i=t-r,o=n-a;return Math.sqrt(i*i+o*o)},e.sum=function(t){for(var n=0,r=0,a=t.length;r!==a;r++){var i=t[r];n+=i}return n},e})(),a2=(function(){function e(){}return e.floatToIntBits=function(t){return t},e.MAX_VALUE=Number.MAX_SAFE_INTEGER,e})(),mt=(function(){function e(t,n){this.x=t,this.y=n}return e.prototype.getX=function(){return this.x},e.prototype.getY=function(){return this.y},e.prototype.equals=function(t){if(t instanceof e){var n=t;return this.x===n.x&&this.y===n.y}return!1},e.prototype.hashCode=function(){return 31*a2.floatToIntBits(this.x)+a2.floatToIntBits(this.y)},e.prototype.toString=function(){return"("+this.x+","+this.y+")"},e.orderBestPatterns=function(t){var n=this.distance(t[0],t[1]),r=this.distance(t[1],t[2]),a=this.distance(t[0],t[2]),i,o,l;if(r>=n&&r>=a?(o=t[0],i=t[1],l=t[2]):a>=r&&a>=n?(o=t[1],i=t[0],l=t[2]):(o=t[2],i=t[0],l=t[1]),this.crossProductZ(i,o,l)<0){var c=i;i=l,l=c}t[0]=i,t[1]=o,t[2]=l},e.distance=function(t,n){return mn.distance(t.x,t.y,n.x,n.y)},e.crossProductZ=function(t,n,r){var a=n.x,i=n.y;return(r.x-a)*(t.y-i)-(r.y-i)*(t.x-a)},e})(),Bw=(function(){function e(t,n){this.bits=t,this.points=n}return e.prototype.getBits=function(){return this.bits},e.prototype.getPoints=function(){return this.points},e})(),vXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
926t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),wXe=(function(e){vXe(t,e);function t(n,r,a,i,o){var l=e.call(this,n,r)||this;return l.compact=a,l.nbDatablocks=i,l.nbLayers=o,l}return t.prototype.getNbLayers=function(){return this.nbLayers},t.prototype.getNbDatablocks=function(){return this.nbDatablocks},t.prototype.isCompact=function(){return this.compact},t})(Bw),i2=(function(){function e(t,n,r,a){this.image=t,this.height=t.getHeight(),this.width=t.getWidth(),n==null&&(n=e.INIT_SIZE),r==null&&(r=t.getWidth()/2|0),a==null&&(a=t.getHeight()/2|0);var i=n/2|0;if(this.leftInit=r-i,this.rightInit=r+i,this.upInit=a-i,this.downInit=a+i,this.upInit<0||this.leftInit<0||this.downInit>=this.height||this.rightInit>=this.width)throw new Oe}return e.prototype.detect=function(){for(var t=this.leftInit,n=this.rightInit,r=this.upInit,a=this.downInit,i=!1,o=!0,l=!1,c=!1,u=!1,d=!1,h=!1,f=this.width,m=this.height;o;){o=!1;for(var x=!0;(x||!c)&&n<f;)x=this.containsBlackPoint(r,a,n,!1),x?(n++,o=!0,c=!0):c||n++;if(n>=f){i=!0;break}for(var g=!0;(g||!u)&&a<m;)g=this.containsBlackPoint(t,n,a,!0),g?(a++,o=!0,u=!0):u||a++;if(a>=m){i=!0;break}for(var y=!0;(y||!d)&&t>=0;)y=this.containsBlackPoint(r,a,t,!1),y?(t--,o=!0,d=!0):d||t--;if(t<0){i=!0;break}for(var b=!0;(b||!h)&&r>=0;)b=this.containsBlackPoint(t,n,r,!0),b?(r--,o=!0,h=!0):h||r--;if(r<0){i=!0;break}
926o&&(l=!0)}if(!i&&l){for(var v=n-t,w=null,_=1;w===null&&_<v;_++)w=this.getBlackPointOnSegment(t,a-_,t+_,a);if(w==null)throw new Oe;for(var k=null,_=1;k===null&&_<v;_++)k=this.getBlackPointOnSegment(t,r+_,t+_,r);if(k==null)throw new Oe;for(var j=null,_=1;j===null&&_<v;_++)j=this.getBlackPointOnSegment(n,r+_,n-_,r);if(j==null)throw new Oe;for(var N=null,_=1;N===null&&_<v;_++)N=this.getBlackPointOnSegment(n,a-_,n-_,a);if(N==null)throw new Oe;return this.centerEdges(N,w,j,k)}else throw new Oe},e.prototype.getBlackPointOnSegment=function(t,n,r,a){for(var i=mn.round(mn.distance(t,n,r,a)),o=(r-t)/i,l=(a-n)/i,c=this.image,u=0;u<i;u++){var d=mn.round(t+u*o),h=mn.round(n+u*l);if(c.get(d,h))return new mt(d,h)}return null},e.prototype.centerEdges=function(t,n,r,a){var i=t.getX(),o=t.getY(),l=n.getX(),c=n.getY(),u=r.getX(),d=r.getY(),h=a.getX(),f=a.getY(),m=e.CORR;return i<this.width/2?[new mt(h-m,f+m),new mt(l+m,c+m),new mt(u-m,d-m),new mt(i+m,o-m)]:[new mt(h+m,f+m),new mt(l+m,c-m),new mt(u-m,d+m),new mt(i-m,o-m)]},e.prototype.containsBlackPoint=function(t,n,r,a){var i=this.image;if(a){for(var o=t;o<=n;o++)if(i.get(o,r))return!0}else for(var l=t;l<=n;l++)if(i.get(r,l))return!0;return!1},e.INIT_SIZE=10,e.CORR=1,e})(),r8=(function(){function e(){}return e.checkAndNudgePoints=function(t,n){for(var r=t.getWidth(),a=t.getHeight(),i=!0,o=0;o<n.length&&i;o+=2){var l=Math.floor(n[o]),c=Math.floor(n[o+1]);if(l<-1||l>r||c<-1||c>a)throw new Oe;i=!1,l===-1?(n[o]=0,i=!0):l===r&&(n[o]=r-1,i=!0),c===-1?(n[o+1]=0,i=!0):c===a&&(n[o+1]=a-1,i=!0)}i=!0;for(var o=n.length-2;o>=0&&i;o-=2){var l=Math.floor(n[o]),c=Math.floor(n[o+1]);if(l<-1||l>r||c<-1||c>a)throw new Oe;i=!1,l===-1?(n[o]=0,i=!0):l===r&&(n[o]=r-1,i=!0),c===-1?(n[o+1]=0,i=!0):c===a&&(n[o+1]=a-1,i=!0)}},e})(),aT=(function(){function e(t,n,r,a,i,o,l,c,u){this.a11=t,this.a21=n,this.a31=r,this.a12=a,this.a22=i,this.a32=o,this.a13=l,this.a23=c,this.a33=u}return e.quadrilateralToQuadrilateral=function(t,n,r,a,i,o,l,c,u,d,h,f,m,x,g,y){var b=e.quadrilateralToSquare(t,n,r,a,i,o,l,c),v=e.squareToQuadrilateral(u,d,h,f,m,x,g,y);return v.times(b)},e.prototype.transformPoints=function(t){for(var n=t.length,r=this.a11,a=this.a12,i=this.a13,o=this.a21,l=this.a22,c=this.a23,u=this.a31,d=this.a32,h=this.a33,f=0;f<n;f+=2){var m=t[f],x=t[f+1],g=i*m+c*x+h;t[f]=(r*m+o*x+u)/g,t[f+1]=(a*m+l*x+d)/g}},e.prototype.transformPointsWithValues=function(t,n){for(var r=this.a11,a=this.a12,i=this.a13,o=this.a21,l=this.a22,c=this.a23,u=this.a31,d=this.a32,h=this.a33,f=t.length,m=0;m<f;m++){var x=t[m],g=n[m],y=i*x+c*g+h;t[m]=(r*x+o*g+u)/y,n[m]=(a*x+l*g+d)/y}},e.squareToQuadrilateral=function(t,n,r,a,i,o,l,c){var u=t-r+i-l,d=n-a+o-c;if(u===0&&d===0)return new e(r-t,i-r,t,a-n,o-a,n,0,0,1);var h=r-i,f=l-i,m=a-o,x=c-o,g=h*x-f*m,y=(u*x-f*d)/g,b=(h*d-u*m)/g;return new e(r-t+y*r,l-t+b*l,t,a-n+y*a,c-n+b*c,n,y,b,1)},e.quadrilateralToSquare=function(t,n,r,a,i,o,l,c){return e.squareToQuadrilateral(t,n,r,a,i,o,l,c).buildAdjoint()},e.prototype.buildAdjoint=function(){return new e(this.a22*this.a33-this.a23*this.a32,this.a23*this.a31-this.a21*this.a33,this.a21*this.a32-this.a22*this.a31,this.a13*this.a32-this.a12*this.a33,this.a11*this.a33-this.a13*this.a31,this.a12*this.a31-this.a11*this.a32,this.a12*this.a23-this.a13*this.a22,this.a13*this.a21-this.a11*this.a23,this.a11*this.a22-this.a12*this.a21)},e.prototype.times=function(t){return new e(this.a11*t.a11+this.a21*t.a12+this.a31*t.a13,this.a11*t.a21+this.a21*t.a22+this.a31*t.a23,this.a11*t.a31+this.a21*t.a32+this.a31*t.a33,this.a12*t.a11+this.a22*t.a12+this.a32*t.a13,this.a12*t.a21+this.a22*t.a22+this.a32*t.a23,this.a12*t.a31+this.a22*t.a32+this.a32*t.a33,this.a13*t.a11+this.a23*t.a12+this.a33*t.a13,this.a13*t.a21+this.a23*t.a22+this.a33*t.a23,this.a13*t.a31+this.a23*t.a32+this.a33*t.a33)},e})(),_Xe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
926t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),kXe=(function(e){_Xe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.sampleGrid=function(n,r,a,i,o,l,c,u,d,h,f,m,x,g,y,b,v,w,_){var k=aT.quadrilateralToQuadrilateral(i,o,l,c,u,d,h,f,m,x,g,y,b,v,w,_);return this.sampleGridWithTransform(n,r,a,k)},t.prototype.sampleGridWithTransform=function(n,r,a,i){if(r<=0||a<=0)throw new Oe;for(var o=new _i(r,a),l=new Float32Array(2*r),c=0;c<a;c++){for(var u=l.length,d=c+.5,h=0;h<u;h+=2)l[h]=h/2+.5,l[h+1]=d;i.transformPoints(l),r8.checkAndNudgePoints(n,l);try{for(var h=0;h<u;h+=2)n.get(l[h]|0,l[h+1]|0)&&o.set(h/2,c)}catch{throw new Oe}}return o},t})(r8),Uw=(function(){function e(){}return e.setGridSampler=function(t){e.gridSampler=t},e.getInstance=function(){return e.gridSampler},e.gridSampler=new kXe,e})(),Va=(function(){function e(t,n){this.x=t,this.y=n}return e.prototype.toResultPoint=function(){return new mt(this.getX(),this.getY())},e.prototype.getX=function(){return this.x},e.prototype.getY=function(){return this.y},e})(),jXe=(function(){function e(t){this.EXPECTED_CORNER_BITS=new Int32Array([3808,476,2107,1799]),this.image=t}return e.prototype.detect=function(){return this.detectMirror(!1)},e.prototype.detectMirror=function(t){var n=this.getMatrixCenter(),r=this.getBullsEyeCorners(n);if(t){var a=r[0];r[0]=r[2],r[2]=a}this.extractParameters(r);var i=this.sampleGrid(this.image,r[this.shift%4],r[(this.shift+1)%4],r[(this.shift+2)%4],r[(this.shift+3)%4]),o=this.getMatrixCornerPoints(r);return new wXe(i,o,this.compact,this.nbDataBlocks,this.nbLayers)},e.prototype.extractParameters=function(t){if(!this.isValidPoint(t[0])||!this.isValidPoint(t[1])||!this.isValidPoint(t[2])||!this.isValidPoint(t[3]))throw new Oe;var n=2*this.nbCenterLayers,r=new Int32Array([this.sampleLine(t[0],t[1],n),this.sampleLine(t[1],t[2],n),this.sampleLine(t[2],t[3],n),this.sampleLine(t[3],t[0],n)]);this.shift=this.getRotation(r,n);for(var a=0,i=0;i<4;i++){var o=r[(this.shift+i)%4];this.compact?(a<<=7,a+=o>>1&127):(a<<=10,a+=(o>>2&992)+(o>>1&31))}var l=this.getCorrectedParameterData(a,this.compact);this.compact?(this.nbLayers=(l>>6)+1,this.nbDataBlocks=(l&63)+1):(this.nbLayers=(l>>11)+1,this.nbDataBlocks=(l&2047)+1)},e.prototype.getRotation=function(t,n){var r=0;t.forEach(function(i,o,l){var c=(i>>n-2<<1)+(i&1);r=(r<<3)+c}),r=((r&1)<<11)+(r>>1);for(var a=0;a<4;a++)if(Zt.bitCount(r^this.EXPECTED_CORNER_BITS[a])<=2)return a;throw new Oe},e.prototype.getCorrectedParameterData=function(t,n){var r,a;n?(r=7,a=2):(r=10,a=4);for(var i=r-a,o=new Int32Array(r),l=r-1;l>=0;--l)o[l]=t&15,t>>=4;try{var c=new Yf(ra.AZTEC_PARAM);c.decode(o,i)}catch{throw new Oe}for(var u=0,l=0;l<a;l++)u=(u<<4)+o[l];return u},e.prototype.getBullsEyeCorners=function(t){var n=t,r=t,a=t,i=t,o=!0;for(this.nbCenterLayers=1;this.nbCenterLayers<9;this.nbCenterLayers++){var l=this.getFirstDifferent(n,o,1,-1),c=this.getFirstDifferent(r,o,1,1),u=this.getFirstDifferent(a,o,-1,1),d=this.getFirstDifferent(i,o,-1,-1);if(this.nbCenterLayers>2){var h=this.distancePoint(d,l)*this.nbCenterLayers/(this.distancePoint(i,n)*(this.nbCenterLayers+2));if(h<.75||h>1.25||!this.isWhiteOrBlackRectangle(l,c,u,d))break}n=l,r=c,a=u,i=d,o=!o}if(this.nbCenterLayers!==5&&this.nbCenterLayers!==7)throw new Oe;this.compact=this.nbCenterLayers===5;var f=new mt(n.getX()+.5,n.getY()-.5),m=new mt(r.getX()+.5,r.getY()+.5),x=new mt(a.getX()-.5,a.getY()+.5),g=new mt(i.getX()-.5,i.getY()-.5);return this.expandSquare([f,m,x,g],2*this.nbCenterLayers-3,2*this.nbCenterLayers)},e.prototype.getMatrixCenter=function(){var t,n,r,a;try{var i=new i2(this.image).detect();t=i[0],n=i[1],r=i[2],a=i[3]}catch{var o=this.image.getWidth()/2,l=this.image.getHeight()/2;t=this.getFirstDifferent(new Va(o+7,l-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new Va(o+7,l+7),!1,1,1).toResultPoint(),r=this.getFirstDifferent(new Va(o-7,l+7),!1,-1,1).toResultPoint(),a=this.getFirstDifferent(new Va(o-7,l-7),!1,-1,-1).toResultPoint()}var c=mn.round((t.getX()+a.getX()+n.getX()+r.getX())/4),u=mn.round((t.getY()+a.getY()+n.getY()+r.getY())/4);try{var i=new i2(this.image,15,c,u).detect();t=i[0],n=i[1],r=i[2],a=i[3]}catch{t=this.getFirstDifferent(new Va(c+7,u-7),!1,1,-1).toResultPoint(),n=this.getFirstDifferent(new Va(c+7,u+7),!1,1,1).toResultPoint(),r=this.getFirstDifferent(new Va(c-7,u+7),!1,-1,1).toResultPoint(),a=this.getFirstDifferent(new Va(c-7,u-7),!1,-1,-1).toResultPoint()}return c=mn.round((t.getX()+a.getX()+n.getX()+r.getX())/4),u=mn.round((t.getY()+a.getY()+n.getY()+r.getY())/4),new Va(c,u)},e.prototype.getMatrixCornerPoints=function(t){return this.expandSquare(t,2*this.nbCenterLayers,this.getDimension())},e.prototype.sampleGrid=function(t,n,r,a,i){var o=Uw.getInstance(),l=this.getDimension(),c=l/2-this.nbCenterLayers,u=l/2+this.nbCenterLayers;return o.sampleGrid(t,l,l,c,c,u,c,u,u,c,u,n.getX(),n.getY(),r.getX(),r.getY(),a.getX(),a.getY(),i.getX(),i.getY())},e.prototype.sampleLine=function(t,n,r){for(var a=0,i=this.distanceResultPoint(t,n),o=i/r,l=t.getX(),c=t.getY(),u=o*(n.getX()-t.getX())/i,d=o*(n.getY()-t.getY())/i,h=0;h<r;h++)this.image.get(mn.round(l+h*u),mn.round(c+h*d))&&(a|=1<<r-h-1);return a},e.prototype.isWhiteOrBlackRectangle=function(t,n,r,a){var i=3;t=new Va(t.getX()-i,t.getY()+i),n=new Va(n.getX()-i,n.getY()-i),r=new Va(r.getX()+i,r.getY()-i),a=new Va(a.getX()+i,a.getY()+i);var o=this.getColor(a,t);if(o===0)return!1;var l=this.getColor(t,n);return l!==o||(l=this.getColor(n,r),l!==o)?!1:(l=this.getColor(r,a),l===o)},e.prototype.getColor=function(t,n){for(var r=this.distancePoint(t,n),a=(n.getX()-t.getX())/r,i=(n.getY()-t.getY())/r,o=0,l=t.getX(),c=t.getY(),u=this.image.get(t.getX(),t.getY()),d=Math.ceil(r),h=0;h<d;h++)l+=a,c+=i,this.image.get(mn.round(l),mn.round(c))!==u&&o++;var f=o/r;return f>.1&&f<.9?0:f<=.1===u?1:-1},e.prototype.getFirstDifferent=function(t,n,r,a){for(var i=t.getX()+r,o=t.getY()+a;this.isValid(i,o)&&this.image.get(i,o)===n;)i+=r,o+=a;for(i-=r,o-=a;this.isValid(i,o)&&this.image.get(i,o)===n;)i+=r;for(i-=r;this.isValid(i,o)&&this.image.get(i,o)===n;)o+=a;return o-=a,new Va(i,o)},e.prototype.expandSquare=function(t,n,r){var a=r/(2*n),i=t[0].getX()-t[2].getX(),o=t[0].getY()-t[2].getY(),l=(t[0].getX()+t[2].getX())/2,c=(t[0].getY()+t[2].getY())/2,u=new mt(l+a*i,c+a*o),d=new mt(l-a*i,c-a*o);i=t[1].getX()-t[3].getX(),o=t[1].getY()-t[3].getY(),l=(t[1].getX()+t[3].getX())/2,c=(t[1].getY()+t[3].getY())/2;var h=new mt(l+a*i,c+a*o),f=new mt(l-a*i,c-a*o),m=[u,h,d,f];return m},e.prototype.isValid=function(t,n){return t>=0&&t<this.image.getWidth()&&n>0&&n<this.image.getHeight()},e.prototype.isValidPoint=function(t){var n=mn.round(t.getX()),r=mn.round(t.getY());return this.isValid(n,r)},e.prototype.distancePoint=function(t,n){return mn.distance(t.getX(),t.getY(),n.getX(),n.getY())},e.prototype.distanceResultPoint=function(t,n){return mn.distance(t.getX(),t.getY(),n.getX(),n.getY())},e.prototype.getDimension=function(){return this.compact?4*this.nbLayers+11:this.nbLayers<=4?4*this.nbLayers+15:4*this.nbLayers+2*(Zt.truncDivision(this.nbLayers-4,8)+1)+15},e})(),o2=(function(){function e(){}return e.prototype.decode=function(t,n){n===void 0&&(n=null);var r=null,a=new jXe(t.getBlackMatrix()),i=null,o=null;try{var l=a.detectMirror(!1);i=l.getPoints(),this.reportFoundResultPoints(n,i),o=new n8().decode(l)}catch(h){r=h}if(o==null)try{var l=a.detectMirror(!0);i=l.getPoints(),this.reportFoundResultPoints(n,i),o=new n8().decode(l)}catch(h){throw r??h}var c=new Ts(o.getText(),o.getRawBytes(),o.getNumBits(),i,wt.AZTEC,Fn.currentTimeMillis()),u=o.getByteSegments();u!=null&&c.putMetadata(jr.BYTE_SEGMENTS,u);var d=o.getECLevel();return d!=null&&c.putMetadata(jr.ERROR_CORRECTION_LEVEL,d),c},e.prototype.reportFoundResultPoints=function(t,n){if(t!=null){var r=t.get(On.NEED_RESULT_POINT_CALLBACK);
926r!=null&&n.forEach(function(a,i,o){r.foundPossibleResultPoint(a)})}},e.prototype.reset=function(){},e})(),NXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();(function(e){NXe(t,e);function t(n){return n===void 0&&(n=500),e.call(this,new o2,n)||this}return t})(Vf);var ls=(function(){function e(){}return e.prototype.decode=function(t,n){try{return this.doDecode(t,n)}catch{var r=n&&n.get(On.TRY_HARDER)===!0;if(r&&t.isRotateSupported()){var a=t.rotateCounterClockwise(),i=this.doDecode(a,n),o=i.getResultMetadata(),l=270;o!==null&&o.get(jr.ORIENTATION)===!0&&(l=l+o.get(jr.ORIENTATION)%360),i.putMetadata(jr.ORIENTATION,l);var c=i.getResultPoints();if(c!==null)for(var u=a.getHeight(),d=0;d<c.length;d++)c[d]=new mt(u-c[d].getY()-1,c[d].getX());return i}else throw new Oe}},e.prototype.reset=function(){},e.prototype.doDecode=function(t,n){var r=t.getWidth(),a=t.getHeight(),i=new ks(r),o=n&&n.get(On.TRY_HARDER)===!0,l=Math.max(1,a>>(o?8:5)),c;o?c=a:c=25;for(var u=Math.trunc(a/2),d=0;d<c;d++){var h=Math.trunc((d+1)/2),f=(d&1)===0,m=u+l*(f?h:-h);if(m<0||m>=a)break;try{i=t.getBlackRow(m,i)}catch{continue}for(var x=function(v){if(v===1&&(i.reverse(),n&&n.get(On.NEED_RESULT_POINT_CALLBACK)===!0)){var w=new Map;n.forEach(function(j,N){return w.set(N,j)}),w.delete(On.NEED_RESULT_POINT_CALLBACK),n=w}try{var _=g.decodeRow(m,i,n);if(v===1){_.putMetadata(jr.ORIENTATION,180);var k=_.getResultPoints();k!==null&&(k[0]=new mt(r-k[0].getX()-1,k[0].getY()),k[1]=new mt(r-k[1].getX()-1,k[1].getY()))}return{value:_}}catch{}},g=this,y=0;y<2;y++){var b=x(y);if(typeof b=="object")return b.value}}throw new Oe},e.recordPattern=function(t,n,r){for(var a=r.length,i=0;i<a;i++)r[i]=0;var o=t.getSize();if(n>=o)throw new Oe;for(var l=!t.get(n),c=0,u=n;u<o;){if(t.get(u)!==l)r[c]++;else{if(++c===a)break;r[c]=1,l=!l}u++}if(!(c===a||c===a-1&&u===o))throw new Oe},e.recordPatternInReverse=function(t,n,r){for(var a=r.length,i=t.get(n);n>0&&a>=0;)t.get(--n)!==i&&(a--,i=!i);if(a>=0)throw new Oe;e.recordPattern(t,n+1,r)},e.patternMatchVariance=function(t,n,r){for(var a=t.length,i=0,o=0,l=0;l<a;l++)i+=t[l],o+=n[l];if(i<o)return Number.POSITIVE_INFINITY;var c=i/o;r*=c;for(var u=0,d=0;d<a;d++){var h=t[d],f=n[d]*c,m=h>f?h-f:f-h;if(m>r)return Number.POSITIVE_INFINITY;u+=m}return u/i},e})(),SXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),s8=(function(e){SXe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.findStartPattern=function(n){for(var r=n.getSize(),a=n.getNextSet(0),i=0,o=Int32Array.from([0,0,0,0,0,0]),l=a,c=!1,u=6,d=a;d<r;d++)if(n.get(d)!==c)o[i]++;else{if(i===u-1){for(var h=t.MAX_AVG_VARIANCE,f=-1,m=t.CODE_START_A;m<=t.CODE_START_C;m++){var x=ls.patternMatchVariance(o,t.CODE_PATTERNS[m],t.MAX_INDIVIDUAL_VARIANCE);x<h&&(h=x,f=m)}if(f>=0&&n.isRange(Math.max(0,l-(d-l)/2),l,!1))return Int32Array.from([l,d,f]);l+=o[0]+o[1],o=o.slice(2,o.length),o[i-1]=0,o[i]=0,i--}else i++;o[i]=1,c=!c}throw new Oe},t.decodeCode=function(n,r,a){ls.recordPattern(n,a,r);for(var i=t.MAX_AVG_VARIANCE,o=-1,l=0;l<t.CODE_PATTERNS.length;l++){var c=t.CODE_PATTERNS[l],u=this.patternMatchVariance(r,c,t.MAX_INDIVIDUAL_VARIANCE);u<i&&(i=u,o=l)}if(o>=0)return o;throw new Oe},t.prototype.decodeRow=function(n,r,a){var i=a&&a.get(On.ASSUME_GS1)===!0,o=t.findStartPattern(r),l=o[2],c=0,u=new Uint8Array(20);u[c++]=l;var d;switch(l){case t.CODE_START_A:d=t.CODE_CODE_A;break;case t.CODE_START_B:d=t.CODE_CODE_B;break;case t.CODE_START_C:d=t.CODE_CODE_C;break;default:throw new We}for(var h=!1,f=!1,m="",x=o[0],g=o[1],y=Int32Array.from([0,0,0,0,0,0]),b=0,v=0,w=l,_=0,k=!0,j=!1,N=!1;!h;){var E=f;switch(f=!1,b=v,v=t.decodeCode(r,y,g),u[c++]=v,v!==t.CODE_STOP&&(k=!0),v!==t.CODE_STOP&&(_++,w+=_*v),x=g,g+=y.reduce(function(P,F){return P+F},0),v){case t.CODE_START_A:case t.CODE_START_B:case t.CODE_START_C:throw new We}switch(d){case t.CODE_CODE_A:if(v<64)N===j?m+=String.fromCharCode(32+v):m+=String.fromCharCode(32+v+128),N=!1;else if(v<96)N===j?m+=String.fromCharCode(v-64):m+=String.fromCharCode(v+64),N=!1;else switch(v!==t.CODE_STOP&&(k=!1),v){case t.CODE_FNC_1:i&&(m.length===0?m+="]C1":m+="�");break;case t.CODE_FNC_2:case t.CODE_FNC_3:break;case t.CODE_FNC_4_A:!j&&N?(j=!0,N=!1):j&&N?(j=!1,N=!1):N=!0;break;case t.CODE_SHIFT:f=!0,d=t.CODE_CODE_B;break;case t.CODE_CODE_B:d=t.CODE_CODE_B;break;case t.CODE_CODE_C:d=t.CODE_CODE_C;break;case t.CODE_STOP:h=!0;break}break;case t.CODE_CODE_B:if(v<96)N===j?m+=String.fromCharCode(32+v):m+=String.fromCharCode(32+v+128),N=!1;else switch(v!==t.CODE_STOP&&(k=!1),v){case t.CODE_FNC_1:i&&(m.length===0?m+="]C1":m+="�");break;case t.CODE_FNC_2:case t.CODE_FNC_3:break;case t.CODE_FNC_4_B:!j&&N?(j=!0,N=!1):j&&N?(j=!1,N=!1):N=!0;break;case t.CODE_SHIFT:f=!0,d=t.CODE_CODE_A;break;case t.CODE_CODE_A:d=t.CODE_CODE_A;break;case t.CODE_CODE_C:d=t.CODE_CODE_C;break;case t.CODE_STOP:h=!0;break}break;case t.CODE_CODE_C:if(v<100)v<10&&(m+="0"),m+=v;else switch(v!==t.CODE_STOP&&(k=!1),v){case t.CODE_FNC_1:i&&(m.length===0?m+="]C1":m+="�");break;case t.CODE_CODE_A:d=t.CODE_CODE_A;break;case t.CODE_CODE_B:d=t.CODE_CODE_B;break;case t.CODE_STOP:h=!0;break}break}E&&(d=d===t.CODE_CODE_A?t.CODE_CODE_B:t.CODE_CODE_A)}var A=g-x;if(g=r.getNextUnset(g),!r.isRange(g,Math.min(r.getSize(),g+(g-x)/2),!1))throw new Oe;if(w-=_*b,w%103!==b)throw new Yr;var C=m.length;if(C===0)throw new Oe;C>0&&k&&(d===t.CODE_CODE_C?m=m.substring(0,C-2):m=m.substring(0,C-1));for(var T=(o[1]+o[0])/2,S=x+A/2,O=u.length,R=new Uint8Array(O),I=0;I<O;I++)R[I]=u[I];var $=[new mt(T,n),new mt(S,n)];return new Ts(m,R,0,$,wt.CODE_128,new Date().getTime())},t.CODE_PATTERNS=[Int32Array.from([2,1,2,2,2,2]),Int32Array.from([2,2,2,1,2,2]),Int32Array.from([2,2,2,2,2,1]),Int32Array.from([1,2,1,2,2,3]),Int32Array.from([1,2,1,3,2,2]),Int32Array.from([1,3,1,2,2,2]),Int32Array.from([1,2,2,2,1,3]),Int32Array.from([1,2,2,3,1,2]),Int32Array.from([1,3,2,2,1,2]),Int32Array.from([2,2,1,2,1,3]),Int32Array.from([2,2,1,3,1,2]),Int32Array.from([2,3,1,2,1,2]),Int32Array.from([1,1,2,2,3,2]),Int32Array.from([1,2,2,1,3,2]),Int32Array.from([1,2,2,2,3,1]),Int32Array.from([1,1,3,2,2,2]),Int32Array.from([1,2,3,1,2,2]),Int32Array.from([1,2,3,2,2,1]),Int32Array.from([2,2,3,2,1,1]),Int32Array.from([2,2,1,1,3,2]),Int32Array.from([2,2,1,2,3,1]),Int32Array.from([2,1,3,2,1,2]),Int32Array.from([2,2,3,1,1,2]),Int32Array.from([3,1,2,1,3,1]),Int32Array.from([3,1,1,2,2,2]),Int32Array.from([3,2,1,1,2,2]),Int32Array.from([3,2,1,2,2,1]),Int32Array.from([3,1,2,2,1,2]),Int32Array.from([3,2,2,1,1,2]),Int32Array.from([3,2,2,2,1,1]),Int32Array.from([2,1,2,1,2,3]),Int32Array.from([2,1,2,3,2,1]),Int32Array.from([2,3,2,1,2,1]),Int32Array.from([1,1,1,3,2,3]),Int32Array.from([1,3,1,1,2,3]),Int32Array.from([1,3,1,3,2,1]),Int32Array.from([1,1,2,3,1,3]),Int32Array.from([1,3,2,1,1,3]),Int32Array.from([1,3,2,3,1,1]),Int32Array.from([2,1,1,3,1,3]),Int32Array.from([2,3,1,1,1,3]),Int32Array.from([2,3,1,3,1,1]),Int32Array.from([1,1,2,1,3,3]),Int32Array.from([1,1,2,3,3,1]),Int32Array.from([1,3,2,1,3,1]),Int32Array.from([1,1,3,1,2,3]),Int32Array.from([1,1,3,3,2,1]),Int32Array.from([1,3,3,1,2,1]),Int32Array.from([3,1,3,1,2,1]),Int32Array.from([2,1,1,3,3,1]),Int32Array.from([2,3,1,1,3,1]),Int32Array.from([2,1,3,1,1,3]),Int32Array.from([2,1,3,3,1,1]),Int32Array.from([2,1,3,1,3,1]),Int32Array.from([3,1,1,1,2,3]),Int32Array.from([3,1,1,3,2,1]),Int32Array.from([3,3,1,1,2,1]),Int32Array.from([3,1,2,1,1,3]),Int32Array.from([3,1,2,3,1,1]),Int32Array.from([3,3,2,1,1,1]),Int32Array.from([3,1,4,1,1,1]),Int32Array.from([2,2,1,4,1,1]),Int32Array.from([4,3,1,1,1,1]),Int32Array.from([1,1,1,2,2,4]),Int32Array.from([1,1,1,4,2,2]),Int32Array.from([1,2,1,1,2,4]),Int32Array.from([1,2,1,4,2,1]),Int32Array.from([1,4,1,1,2,2]),Int32Array.from([1,4,1,2,2,1]),Int32Array.from([1,1,2,2,1,4]),Int32Array.from([1,1,2,4,1,2]),Int32Array.from([1,2,2,1,1,4]),Int32Array.from([1,2,2,4,1,1]),Int32Array.from([1,4,2,1,1,2]),Int32Array.from([1,4,2,2,1,1]),Int32Array.from([2,4,1,2,1,1]),Int32Array.from([2,2,1,1,1,4]),Int32Array.from([4,1,3,1,1,1]),Int32Array.from([2,4,1,1,1,2]),Int32Array.from([1,3,4,1,1,1]),Int32Array.from([1,1,1,2,4,2]),Int32Array.from([1,2,1,1,4,2]),Int32Array.from([1,2,1,2,4,1]),Int32Array.from([1,1,4,2,1,2]),Int32Array.from([1,2,4,1,1,2]),Int32Array.from([1,2,4,2,1,1]),Int32Array.from([4,1,1,2,1,2]),Int32Array.from([4,2,1,1,1,2]),Int32Array.from([4,2,1,2,1,1]),Int32Array.from([2,1,2,1,4,1]),Int32Array.from([2,1,4,1,2,1]),Int32Array.from([4,1,2,1,2,1]),Int32Array.from([1,1,1,1,4,3]),Int32Array.from([1,1,1,3,4,1]),Int32Array.from([1,3,1,1,4,1]),Int32Array.from([1,1,4,1,1,3]),Int32Array.from([1,1,4,3,1,1]),Int32Array.from([4,1,1,1,1,3]),Int32Array.from([4,1,1,3,1,1]),Int32Array.from([1,1,3,1,4,1]),Int32Array.from([1,1,4,1,3,1]),Int32Array.from([3,1,1,1,4,1]),Int32Array.from([4,1,1,1,3,1]),Int32Array.from([2,1,1,4,1,2]),Int32Array.from([2,1,1,2,1,4]),Int32Array.from([2,1,1,2,3,2]),Int32Array.from([2,3,3,1,1,1,2])],t.MAX_AVG_VARIANCE=.25,t.MAX_INDIVIDUAL_VARIA
926NCE=.7,t.CODE_SHIFT=98,t.CODE_CODE_C=99,t.CODE_CODE_B=100,t.CODE_CODE_A=101,t.CODE_FNC_1=102,t.CODE_FNC_2=97,t.CODE_FNC_3=96,t.CODE_FNC_4_A=101,t.CODE_FNC_4_B=100,t.CODE_START_A=103,t.CODE_START_B=104,t.CODE_START_C=105,t.CODE_STOP=106,t})(ls),CXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Pj=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},a8=(function(e){CXe(t,e);function t(n,r){n===void 0&&(n=!1),r===void 0&&(r=!1);var a=e.call(this)||this;return a.usingCheckDigit=n,a.extendedMode=r,a.decodeRowResult="",a.counters=new Int32Array(9),a}return t.prototype.decodeRow=function(n,r,a){var i,o,l,c,u=this.counters;u.fill(0),this.decodeRowResult="";var d=t.findAsteriskPattern(r,u),h=r.getNextSet(d[1]),f=r.getSize(),m,x;do{t.recordPattern(r,h,u);var g=t.toNarrowWidePattern(u);if(g<0)throw new Oe;m=t.patternToChar(g),this.decodeRowResult+=m,x=h;try{for(var y=(i=void 0,Pj(u)),b=y.next();!b.done;b=y.next()){var v=b.value;h+=v}}catch(O){i={error:O}}finally{try{b&&!b.done&&(o=y.return)&&o.call(y)}finally{if(i)throw i.error}}h=r.getNextSet(h)}while(m!=="*");this.decodeRowResult=this.decodeRowResult.substring(0,this.decodeRowResult.length-1);var w=0;try{for(var _=Pj(u),k=_.next();!k.done;k=_.next()){var v=k.value;w+=v}}catch(O){l={error:O}}finally{try{k&&!k.done&&(c=_.return)&&c.call(_)}finally{if(l)throw l.error}}var j=h-x-w;if(h!==f&&j*2<w)throw new Oe;if(this.usingCheckDigit){for(var N=this.decodeRowResult.length-1,E=0,A=0;A<N;A++)E+=t.ALPHABET_STRING.indexOf(this.decodeRowResult.charAt(A));if(this.decodeRowResult.charAt(N)!==t.ALPHABET_STRING.charAt(E%43))throw new Yr;this.decodeRowResult=this.decodeRowResult.substring(0,N)}if(this.decodeRowResult.length===0)throw new Oe;var C;this.extendedMode?C=t.decodeExtended(this.decodeRowResult):C=this.decodeRowResult;var T=(d[1]+d[0])/2,S=x+w/2;return new Ts(C,null,0,[new mt(T,n),new mt(S,n)],wt.CODE_39,new Date().getTime())},t.findAsteriskPattern=function(n,r){for(var a=n.getSize(),i=n.getNextSet(0),o=0,l=i,c=!1,u=r.length,d=i;d<a;d++)if(n.get(d)!==c)r[o]++;else{if(o===u-1){if(this.toNarrowWidePattern(r)===t.ASTERISK_ENCODING&&n.isRange(Math.max(0,l-Math.floor((d-l)/2)),l,!1))return[l,d];l+=r[0]+r[1],r.copyWithin(0,2,2+o-1),r[o-1]=0,r[o]=0,o--}else o++;r[o]=1,c=!c}throw new Oe},t.toNarrowWidePattern=function(n){var r,a,i=n.length,o=0,l;do{var c=2147483647;try{for(var u=(r=void 0,Pj(n)),d=u.next();!d.done;d=u.next()){var h=d.value;h<c&&h>o&&(c=h)}}catch(g){r={error:g}}finally{try{d&&!d.done&&(a=u.return)&&a.call(u)}finally{if(r)throw r.error}}o=c,l=0;for(var f=0,m=0,x=0;x<i;x++){var h=n[x];h>o&&(m|=1<<i-1-x,l++,f+=h)}if(l===3){for(var x=0;x<i&&l>0;x++){var h=n[x];if(h>o&&(l--,h*2>=f))return-1}return m}}while(l>3);return-1},t.patternToChar=function(n){for(var r=0;r<t.CHARACTER_ENCODINGS.length;r++)if(t.CHARACTER_ENCODINGS[r]===n)return t.ALPHABET_STRING.charAt(r);if(n===t.ASTERISK_ENCODING)return"*";throw new Oe},t.decodeExtended=function(n){for(var r=n.length,a="",i=0;i<r;i++){var o=n.charAt(i);if(o==="+"||o==="$"||o==="%"||o==="/"){var l=n.charAt(i+1),c="\0";switch(o){case"+":if(l>="A"&&l<="Z")c=String.fromCharCode(l.charCodeAt(0)+32);else throw new We;break;case"$":if(l>="A"&&l<="Z")c=String.fromCharCode(l.charCodeAt(0)-64);else throw new We;break;case"%":if(l>="A"&&l<="E")c=String.fromCharCode(l.charCodeAt(0)-38);else if(l>="F"&&l<="J")c=String.fromCharCode(l.charCodeAt(0)-11);else if(l>="K"&&l<="O")c=String.fromCharCode(l.charCodeAt(0)+16);else if(l>="P"&&l<="T")c=String.fromCharCode(l.charCodeAt(0)+43);else if(l==="U")c="\0";else if(l==="V")c="@";else if(l==="W")c="`";else if(l==="X"||l==="Y"||l==="Z")c="�";else throw new We;break;case"/":if(l>="A"&&l<="O")c=String.fromCharCode(l.charCodeAt(0)-32);else if(l==="Z")c=":";else throw new We;break}a+=c,i++}else a+=o}return a},t.ALPHABET_STRING="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%",t.CHARACTER_ENCODINGS=[52,289,97,352,49,304,112,37,292,100,265,73,328,25,280,88,13,268,76,28,259,67,322,19,274,82,7,262,70,22,385,193,448,145,400,208,133,388,196,168,162,138,42],t.ASTERISK_ENCODING=148,t})(ls),EXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
926t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Rj=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},i8=(function(e){EXe(t,e);function t(){var n=e.call(this)||this;return n.decodeRowResult="",n.counters=new Int32Array(6),n}return t.prototype.decodeRow=function(n,r,a){var i,o,l,c,u=this.findAsteriskPattern(r),d=r.getNextSet(u[1]),h=r.getSize(),f=this.counters;f.fill(0),this.decodeRowResult="";var m,x;do{t.recordPattern(r,d,f);var g=this.toPattern(f);if(g<0)throw new Oe;m=this.patternToChar(g),this.decodeRowResult+=m,x=d;try{for(var y=(i=void 0,Rj(f)),b=y.next();!b.done;b=y.next()){var v=b.value;d+=v}}catch(A){i={error:A}}finally{try{b&&!b.done&&(o=y.return)&&o.call(y)}finally{if(i)throw i.error}}d=r.getNextSet(d)}while(m!=="*");this.decodeRowResult=this.decodeRowResult.substring(0,this.decodeRowResult.length-1);var w=0;try{for(var _=Rj(f),k=_.next();!k.done;k=_.next()){var v=k.value;w+=v}}catch(A){l={error:A}}finally{try{k&&!k.done&&(c=_.return)&&c.call(_)}finally{if(l)throw l.error}}if(d===h||!r.get(d))throw new Oe;if(this.decodeRowResult.length<2)throw new Oe;this.checkChecksums(this.decodeRowResult),this.decodeRowResult=this.decodeRowResult.substring(0,this.decodeRowResult.length-2);var j=this.decodeExtended(this.decodeRowResult),N=(u[1]+u[0])/2,E=x+w/2;return new Ts(j,null,0,[new mt(N,n),new mt(E,n)],wt.CODE_93,new Date().getTime())},t.prototype.findAsteriskPattern=function(n){var r=n.getSize(),a=n.getNextSet(0);this.counters.fill(0);for(var i=this.counters,o=a,l=!1,c=i.length,u=0,d=a;d<r;d++)if(n.get(d)!==l)i[u]++;else{if(u===c-1){if(this.toPattern(i)===t.ASTERISK_ENCODING)return new Int32Array([o,d]);o+=i[0]+i[1],i.copyWithin(0,2,2+u-1),i[u-1]=0,i[u]=0,u--}else u++;i[u]=1,l=!l}throw new Oe},t.prototype.toPattern=function(n){var r,a,i=0;try{for(var o=Rj(n),l=o.next();!l.done;l=o.next()){var c=l.value;i+=c}}catch(x){r={error:x}}finally{try{l&&!l.done&&(a=o.return)&&a.call(o)}finally{if(r)throw r.error}}for(var u=0,d=n.length,h=0;h<d;h++){var f=Math.round(n[h]*9/i);if(f<1||f>4)return-1;if((h&1)===0)for(var m=0;m<f;m++)u=u<<1|1;else u<<=f}return u},t.prototype.patternToChar=function(n){for(var r=0;r<t.CHARACTER_ENCODINGS.length;r++)if(t.CHARACTER_ENCODINGS[r]===n)return t.ALPHABET_STRING.charAt(r);throw new Oe},t.prototype.decodeExtended=function(n){for(var r=n.length,a="",i=0;i<r;i++){var o=n.charAt(i);if(o>="a"&&o<="d"){if(i>=r-1)throw new We;var l=n.charAt(i+1),c="\0";switch(o){case"d":if(l>="A"&&l<="Z")c=String.fromCharCode(l.charCodeAt(0)+32);else throw new We;break;case"a":if(l>="A"&&l<="Z")c=String.fromCharCode(l.charCodeAt(0)-64);else throw new We;break;case"b":if(l>="A"&&l<="E")c=String.fromCharCode(l.charCodeAt(0)-38);else if(l>="F"&&l<="J")c=String.fromCharCode(l.charCodeAt(0)-11);else if(l>="K"&&l<="O")c=String.fromCharCode(l.charCodeAt(0)+16);else if(l>="P"&&l<="T")c=String.fromCharCode(l.charCodeAt(0)+43);else if(l==="U")c="\0";else if(l==="V")c="@";else if(l==="W")c="`";else if(l>="X"&&l<="Z")c="�";else throw new We;break;case"c":if(l>="A"&&l<="O")c=String.fromCharCode(l.charCodeAt(0)-32);else if(l==="Z")c=":";else throw new We;break}a+=c,i++}else a+=o}return a},t.prototype.checkChecksums=function(n){var r=n.length;this.checkOneChecksum(n,r-2,20),this.checkOneChecksum(n,r-1,15)},t.prototype.checkOneChecksum=function(n,r,a){for(var i=1,o=0,l=r-1;l>=0;l--)o+=i*t.ALPHABET_STRING.indexOf(n.charAt(l)),++i>a&&(i=1);if(n.charAt(r)!==t.ALPHABET_STRING[o%47])throw new Yr},t.ALPHABET_STRING="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*",t.CHARACTER_ENCODINGS=[276,328,324,322,296,292,290,336,274,266,424,420,418,404,402,394,360,356,354,308,282,344,332,326,300,278,436,434,428,422,406,410,364,358,310,314,302,468,466,458,366,374,430,294,474,470,306,350],t.ASTERISK_ENCODING=t.CHARACTER_ENCODINGS[47],t})(ls),AXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
926t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),TXe=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,i=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},OXe=function(e,t,n){if(n||arguments.length===2)for(var r=0,a=t.length,i;r<a;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},IXe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},o8=(function(e){AXe(t,e);function t(){var n=e.apply(this,OXe([],TXe(arguments),!1))||this;return n.narrowLineWidth=-1,n}return t.prototype.decodeRow=function(n,r,a){var i,o,l=this.decodeStart(r),c=this.decodeEnd(r),u=new Kt;t.decodeMiddle(r,l[1],c[0],u);var d=u.toString(),h=null;a!=null&&(h=a.get(On.ALLOWED_LENGTHS)),h==null&&(h=t.DEFAULT_ALLOWED_LENGTHS);var f=d.length,m=!1,x=0;try{for(var g=IXe(h),y=g.next();!y.done;y=g.next()){var b=y.value;if(f===b){m=!0;break}b>x&&(x=b)}}catch(_){i={error:_}}finally{try{y&&!y.done&&(o=g.return)&&o.call(g)}finally{if(i)throw i.error}}if(!m&&f>x&&(m=!0),!m)throw new We;var v=[new mt(l[1],n),new mt(c[0],n)],w=new Ts(d,null,0,v,wt.ITF,new Date().getTime());return w},t.decodeMiddle=function(n,r,a,i){var o=new Int32Array(10),l=new Int32Array(5),c=new Int32Array(5);for(o.fill(0),l.fill(0),c.fill(0);r<a;){ls.recordPattern(n,r,o);for(var u=0;u<5;u++){var d=2*u;l[u]=o[d],c[u]=o[d+1]}var h=t.decodeDigit(l);i.append(h.toString()),h=this.decodeDigit(c),i.append(h.toString()),o.forEach(function(f){r+=f})}},t.prototype.decodeStart=function(n){var r=t.skipWhiteSpace(n),a=t.findGuardPattern(n,r,t.START_PATTERN);return this.narrowLineWidth=(a[1]-a[0])/4,this.validateQuietZone(n,a[0]),a},t.prototype.validateQuietZone=function(n,r){var a=this.narrowLineWidth*10;a=a<r?a:r;for(var i=r-1;a>0&&i>=0&&!n.get(i);i--)a--;if(a!==0)throw new Oe},t.skipWhiteSpace=function(n){var r=n.getSize(),a=n.getNextSet(0);if(a===r)throw new Oe;return a},t.prototype.decodeEnd=function(n){n.reverse();try{var r=t.skipWhiteSpace(n),a=void 0;try{a=t.findGuardPattern(n,r,t.END_PATTERN_REVERSED[0])}catch(o){o instanceof Oe&&(a=t.findGuardPattern(n,r,t.END_PATTERN_REVERSED[1]))}this.validateQuietZone(n,a[0]);var i=a[0];return a[0]=n.getSize()-a[1],a[1]=n.getSize()-i,a}finally{n.reverse()}},t.findGuardPattern=function(n,r,a){var i=a.length,o=new Int32Array(i),l=n.getSize(),c=!1,u=0,d=r;o.fill(0);for(var h=r;h<l;h++)if(n.get(h)!==c)o[u]++;else{if(u===i-1){if(ls.patternMatchVariance(o,a,t.MAX_INDIVIDUAL_VARIANCE)<t.MAX_AVG_VARIANCE)return[d,h];d+=o[0]+o[1],Fn.arraycopy(o,2,o,0,u-1),o[u-1]=0,o[u]=0,u--}else u++;o[u]=1,c=!c}throw new Oe},t.decodeDigit=function(n){for(var r=t.MAX_AVG_VARIANCE,a=-1,i=t.PATTERNS.length,o=0;o<i;o++){var l=t.PATTERNS[o],c=ls.patternMatchVariance(n,l,t.MAX_INDIVIDUAL_VARIANCE);c<r?(r=c,a=o):c===r&&(a=-1)}if(a>=0)return a%10;throw new Oe},t.PATTERNS=[Int32Array.from([1,1,2,2,1]),Int32Array.from([2,1,1,1,2]),Int32Array.from([1,2,1,1,2]),Int32Array.from([2,2,1,1,1]),Int32Array.from([1,1,2,1,2]),Int32Array.from([2,1,2,1,1]),Int32Array.from([1,2,2,1,1]),Int32Array.from([1,1,1,2,2]),Int32Array.from([2,1,1,2,1]),Int32Array.from([1,2,1,2,1]),Int32Array.from([1,1,3,3,1]),Int32Array.from([3,1,1,1,3]),Int32Array.from([1,3,1,1,3]),Int32Array.from([3,3,1,1,1]),Int32Array.from([1,1,3,1,3]),Int32Array.from([3,1,3,1,1]),Int32Array.from([1,3,3,1,1]),Int32Array.from([1,1,1,3,3]),Int32Array.from([3,1,1,3,1]),Int32Array.from([1,3,1,3,1])],t.MAX_AVG_VARIANCE=.38,t.MAX_INDIVIDUAL_VARIANCE=.5,t.DEFAULT_ALLOWED_LENGTHS=[6,8,10,12,14],t.START_PATTERN=Int32Array.from([1,1,1,1]),t.END_PATTERN_REVERSED=[Int32Array.from([1,1,2]),Int32Array.from([1,1,3])],t})(ls),PXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
926t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),RXe=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,i=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},DXe=function(e,t,n){if(n||arguments.length===2)for(var r=0,a=t.length,i;r<a;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},df=(function(e){PXe(t,e);function t(){var n=e.apply(this,DXe([],RXe(arguments),!1))||this;return n.decodeRowStringBuffer="",n}return t.findStartGuardPattern=function(n){for(var r=!1,a,i=0,o=Int32Array.from([0,0,0]);!r;){o=Int32Array.from([0,0,0]),a=t.findGuardPattern(n,i,!1,this.START_END_PATTERN,o);var l=a[0];i=a[1];var c=l-(i-l);c>=0&&(r=n.isRange(c,l,!1))}return a},t.checkChecksum=function(n){return t.checkStandardUPCEANChecksum(n)},t.checkStandardUPCEANChecksum=function(n){var r=n.length;if(r===0)return!1;var a=parseInt(n.charAt(r-1),10);return t.getStandardUPCEANChecksum(n.substring(0,r-1))===a},t.getStandardUPCEANChecksum=function(n){for(var r=n.length,a=0,i=r-1;i>=0;i-=2){var o=n.charAt(i).charCodeAt(0)-48;if(o<0||o>9)throw new We;a+=o}a*=3;for(var i=r-2;i>=0;i-=2){var o=n.charAt(i).charCodeAt(0)-48;if(o<0||o>9)throw new We;a+=o}return(1e3-a)%10},t.decodeEnd=function(n,r){return t.findGuardPattern(n,r,!1,t.START_END_PATTERN,new Int32Array(t.START_END_PATTERN.length).fill(0))},t.findGuardPatternWithoutCounters=function(n,r,a,i){return this.findGuardPattern(n,r,a,i,new Int32Array(i.length))},t.findGuardPattern=function(n,r,a,i,o){var l=n.getSize();r=a?n.getNextUnset(r):n.getNextSet(r);for(var c=0,u=r,d=i.length,h=a,f=r;f<l;f++)if(n.get(f)!==h)o[c]++;else{if(c===d-1){if(ls.patternMatchVariance(o,i,t.MAX_INDIVIDUAL_VARIANCE)<t.MAX_AVG_VARIANCE)return Int32Array.from([u,f]);u+=o[0]+o[1];for(var m=o.slice(2,o.length),x=0;x<c-1;x++)o[x]=m[x];o[c-1]=0,o[c]=0,c--}else c++;o[c]=1,h=!h}throw new Oe},t.decodeDigit=function(n,r,a,i){this.recordPattern(n,a,r);for(var o=this.MAX_AVG_VARIANCE,l=-1,c=i.length,u=0;u<c;u++){var d=i[u],h=ls.patternMatchVariance(r,d,t.MAX_INDIVIDUAL_VARIANCE);h<o&&(o=h,l=u)}if(l>=0)return l;throw new Oe},t.MAX_AVG_VARIANCE=.48,t.MAX_INDIVIDUAL_VARIANCE=.7,t.START_END_PATTERN=Int32Array.from([1,1,1]),t.MIDDLE_PATTERN=Int32Array.from([1,1,1,1,1]),t.END_PATTERN=Int32Array.from([1,1,1,1,1,1]),t.L_PATTERNS=[Int32Array.from([3,2,1,1]),Int32Array.from([2,2,2,1]),Int32Array.from([2,1,2,2]),Int32Array.from([1,4,1,1]),Int32Array.from([1,1,3,2]),Int32Array.from([1,2,3,1]),Int32Array.from([1,1,1,4]),Int32Array.from([1,3,1,2]),Int32Array.from([1,2,1,3]),Int32Array.from([3,1,1,2])],t})(ls),MXe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},$Xe=(function(){function e(){this.CHECK_DIGIT_ENCODINGS=[24,20,18,17,12,6,3,10,9,5],this.decodeMiddleCounters=Int32Array.from([0,0,0,0]),this.decodeRowStringBuffer=""}return e.prototype.decodeRow=function(t,n,r){var a=this.decodeRowStringBuffer,i=this.decodeMiddle(n,r,a),o=a.toString(),l=e.parseExtensionString(o),c=[new mt((r[0]+r[1])/2,t),new mt(i,t)],u=new Ts(o,null,0,c,wt.UPC_EAN_EXTENSION,new Date().getTime());return l!=null&&u.putAllMetadata(l),u},e.prototype.decodeMiddle=function(t,n,r){var a,i,o=this.decodeMiddleCounters;o[0]=0,o[1]=0,o[2]=0,o[3]=0;for(var l=t.getSize(),c=n[1],u=0,d=0;d<5&&c<l;d++){var h=df.decodeDigit(t,o,c,df.L_AND_G_PATTERNS);r+=String.fromCharCode(48+h%10);try{for(var f=(a=void 0,MXe(o)),m=f.next();!m.done;m=f.next()){var x=m.value;c+=x}}catch(y){a={error:y}}finally{try{m&&!m.done&&(i=f.return)&&i.call(f)}finally{if(a)throw a.error}}h>=10&&(u|=1<<4-d),d!==4&&(c=t.getNextSet(c),c=t.getNextUnset(c))}if(r.length!==5)throw new Oe;var g=this.determineCheckDigit(u);if(e.extensionChecksum(r.toString())!==g)throw new Oe;return c},e.extensionChecksum=function(t){for(var n=t.length,r=0,a=n-2;a>=0;
926a-=2)r+=t.charAt(a).charCodeAt(0)-48;r*=3;for(var a=n-1;a>=0;a-=2)r+=t.charAt(a).charCodeAt(0)-48;return r*=3,r%10},e.prototype.determineCheckDigit=function(t){for(var n=0;n<10;n++)if(t===this.CHECK_DIGIT_ENCODINGS[n])return n;throw new Oe},e.parseExtensionString=function(t){if(t.length!==5)return null;var n=e.parseExtension5String(t);return n==null?null:new Map([[jr.SUGGESTED_PRICE,n]])},e.parseExtension5String=function(t){var n;switch(t.charAt(0)){case"0":n="£";break;case"5":n="$";break;case"9":switch(t){case"90000":return null;case"99991":return"0.00";case"99990":return"Used"}n="";break;default:n="";break}var r=parseInt(t.substring(1)),a=(r/100).toString(),i=r%100,o=i<10?"0"+i:i.toString();return n+a+"."+o},e})(),LXe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},FXe=(function(){function e(){this.decodeMiddleCounters=Int32Array.from([0,0,0,0]),this.decodeRowStringBuffer=""}return e.prototype.decodeRow=function(t,n,r){var a=this.decodeRowStringBuffer,i=this.decodeMiddle(n,r,a),o=a.toString(),l=e.parseExtensionString(o),c=[new mt((r[0]+r[1])/2,t),new mt(i,t)],u=new Ts(o,null,0,c,wt.UPC_EAN_EXTENSION,new Date().getTime());return l!=null&&u.putAllMetadata(l),u},e.prototype.decodeMiddle=function(t,n,r){var a,i,o=this.decodeMiddleCounters;o[0]=0,o[1]=0,o[2]=0,o[3]=0;for(var l=t.getSize(),c=n[1],u=0,d=0;d<2&&c<l;d++){var h=df.decodeDigit(t,o,c,df.L_AND_G_PATTERNS);r+=String.fromCharCode(48+h%10);try{for(var f=(a=void 0,LXe(o)),m=f.next();!m.done;m=f.next()){var x=m.value;c+=x}}catch(g){a={error:g}}finally{try{m&&!m.done&&(i=f.return)&&i.call(f)}finally{if(a)throw a.error}}h>=10&&(u|=1<<1-d),d!==1&&(c=t.getNextSet(c),c=t.getNextUnset(c))}if(r.length!==2)throw new Oe;if(parseInt(r.toString())%4!==u)throw new Oe;return c},e.parseExtensionString=function(t){return t.length!==2?null:new Map([[jr.ISSUE_NUMBER,parseInt(t)]])},e})(),BXe=(function(){function e(){}return e.decodeRow=function(t,n,r){var a=df.findGuardPattern(n,r,!1,this.EXTENSION_START_PATTERN,new Int32Array(this.EXTENSION_START_PATTERN.length).fill(0));try{var i=new $Xe;return i.decodeRow(t,n,a)}catch{var o=new FXe;return o.decodeRow(t,n,a)}},e.EXTENSION_START_PATTERN=Int32Array.from([1,1,2]),e})(),UXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),ss=(function(e){UXe(t,e);function t(){var n=e.call(this)||this;n.decodeRowStringBuffer="",t.L_AND_G_PATTERNS=t.L_PATTERNS.map(function(l){return Int32Array.from(l)});for(var r=10;r<20;r++){for(var a=t.L_PATTERNS[r-10],i=new Int32Array(a.length),o=0;o<a.length;o++)i[o]=a[a.length-o-1];t.L_AND_G_PATTERNS[r]=i}return n}return t.prototype.decodeRow=function(n,r,a){var i=t.findStartGuardPattern(r),o=a==null?null:a.get(On.NEED_RESULT_POINT_CALLBACK);if(o!=null){var l=new mt((i[0]+i[1])/2,n);o.foundPossibleResultPoint(l)}var c=this.decodeMiddle(r,i,this.decodeRowStringBuffer),u=c.rowOffset,d=c.resultString;if(o!=null){var h=new mt(u,n);o.foundPossibleResultPoint(h)}var f=t.decodeEnd(r,u);if(o!=null){var m=new mt((f[0]+f[1])/2,n);o.foundPossibleResultPoint(m)}var x=f[1],g=x+(x-f[0]);if(g>=r.getSize()||!r.isRange(x,g,!1))throw new Oe;var y=d.toString();if(y.length<8)throw new We;if(!t.checkChecksum(y))throw new Yr;var b=(i[1]+i[0])/2,v=(f[1]+f[0])/2,w=this.getBarcodeFormat(),_=[new mt(b,n),new mt(v,n)],k=new Ts(y,null,0,_,w,new Date().getTime()),j=0;try{var N=BXe.decodeRow(n,r,f[1]);k.putMetadata(jr.UPC_EAN_EXTENSION,N.getText()),k.putAllMetadata(N.getResultMetadata()),k.addResultPoints(N.getResultPoints()),j=N.getText().length}catch{}var E=a==null?null:a.get(On.ALLOWED_EAN_EXTENSIONS);if(E!=null){var A=!1;for(var C in E)if(j.toString()===C){A=!0;break}if(!A)throw new Oe}return w===wt.EAN_13||wt.UPC_A,k},t.checkChecksum=function(n){return t.checkStandardUPCEANChecksum(n)},t.checkStandardUPCEANChecksum=function(n){var r=n.length;if(r===0)return!1;var a=parseInt(n.charAt(r-1),10);return t.getStandardUPCEANChecksum(n.substring(0,r-1))===a},t.getStandardUPCEANChecksum=function(n){for(var r=n.length,a=0,i=r-1;i>=0;
926i-=2){var o=n.charAt(i).charCodeAt(0)-48;if(o<0||o>9)throw new We;a+=o}a*=3;for(var i=r-2;i>=0;i-=2){var o=n.charAt(i).charCodeAt(0)-48;if(o<0||o>9)throw new We;a+=o}return(1e3-a)%10},t.decodeEnd=function(n,r){return t.findGuardPattern(n,r,!1,t.START_END_PATTERN,new Int32Array(t.START_END_PATTERN.length).fill(0))},t})(df),zXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),l8=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},l2=(function(e){zXe(t,e);function t(){var n=e.call(this)||this;return n.decodeMiddleCounters=Int32Array.from([0,0,0,0]),n}return t.prototype.decodeMiddle=function(n,r,a){var i,o,l,c,u=this.decodeMiddleCounters;u[0]=0,u[1]=0,u[2]=0,u[3]=0;for(var d=n.getSize(),h=r[1],f=0,m=0;m<6&&h<d;m++){var x=ss.decodeDigit(n,u,h,ss.L_AND_G_PATTERNS);a+=String.fromCharCode(48+x%10);try{for(var g=(i=void 0,l8(u)),y=g.next();!y.done;y=g.next()){var b=y.value;h+=b}}catch(k){i={error:k}}finally{try{y&&!y.done&&(o=g.return)&&o.call(g)}finally{if(i)throw i.error}}x>=10&&(f|=1<<5-m)}a=t.determineFirstDigit(a,f);var v=ss.findGuardPattern(n,h,!0,ss.MIDDLE_PATTERN,new Int32Array(ss.MIDDLE_PATTERN.length).fill(0));h=v[1];for(var m=0;m<6&&h<d;m++){var x=ss.decodeDigit(n,u,h,ss.L_PATTERNS);a+=String.fromCharCode(48+x);try{for(var w=(l=void 0,l8(u)),_=w.next();!_.done;_=w.next()){var b=_.value;h+=b}}catch(N){l={error:N}}finally{try{_&&!_.done&&(c=w.return)&&c.call(w)}finally{if(l)throw l.error}}}return{rowOffset:h,resultString:a}},t.prototype.getBarcodeFormat=function(){return wt.EAN_13},t.determineFirstDigit=function(n,r){for(var a=0;a<10;a++)if(r===this.FIRST_DIGIT_ENCODINGS[a])return n=String.fromCharCode(48+a)+n,n;throw new Oe},t.FIRST_DIGIT_ENCODINGS=[0,11,13,14,19,25,28,21,22,26],t})(ss),WXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),c8=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},u8=(function(e){WXe(t,e);function t(){var n=e.call(this)||this;return n.decodeMiddleCounters=Int32Array.from([0,0,0,0]),n}return t.prototype.decodeMiddle=function(n,r,a){var i,o,l,c,u=this.decodeMiddleCounters;u[0]=0,u[1]=0,u[2]=0,u[3]=0;for(var d=n.getSize(),h=r[1],f=0;f<4&&h<d;f++){var m=ss.decodeDigit(n,u,h,ss.L_PATTERNS);a+=String.fromCharCode(48+m);try{for(var x=(i=void 0,c8(u)),g=x.next();!g.done;g=x.next()){var y=g.value;h+=y}}catch(_){i={error:_}}finally{try{g&&!g.done&&(o=x.return)&&o.call(x)}finally{if(i)throw i.error}}}var b=ss.findGuardPattern(n,h,!0,ss.MIDDLE_PATTERN,new Int32Array(ss.MIDDLE_PATTERN.length).fill(0));h=b[1];for(var f=0;f<4&&h<d;f++){var m=ss.decodeDigit(n,u,h,ss.L_PATTERNS);a+=String.fromCharCode(48+m);try{for(var v=(l=void 0,c8(u)),w=v.next();!w.done;w=v.next()){var y=w.value;h+=y}}catch(j){l={error:j}}finally{try{w&&!w.done&&(c=v.return)&&c.call(v)}finally{if(l)throw l.error}}}return{rowOffset:h,resultString:a}},t.prototype.getBarcodeFormat=function(){return wt.EAN_8},t})(ss),KXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
926t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),HXe=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,i=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},VXe=function(e,t,n){if(n||arguments.length===2)for(var r=0,a=t.length,i;r<a;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},d8=(function(e){KXe(t,e);function t(){var n=e.apply(this,VXe([],HXe(arguments),!1))||this;return n.ean13Reader=new l2,n}return t.prototype.getBarcodeFormat=function(){return wt.UPC_A},t.prototype.decode=function(n,r){return this.maybeReturnResult(this.ean13Reader.decode(n))},t.prototype.decodeRow=function(n,r,a){return this.maybeReturnResult(this.ean13Reader.decodeRow(n,r,a))},t.prototype.decodeMiddle=function(n,r,a){return this.ean13Reader.decodeMiddle(n,r,a)},t.prototype.maybeReturnResult=function(n){var r=n.getText();if(r.charAt(0)==="0"){var a=new Ts(r.substring(1),null,null,n.getResultPoints(),wt.UPC_A);return n.getResultMetadata()!=null&&a.putAllMetadata(n.getResultMetadata()),a}else throw new Oe},t.prototype.reset=function(){this.ean13Reader.reset()},t})(ss),qXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),GXe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},h8=(function(e){qXe(t,e);function t(){var n=e.call(this)||this;return n.decodeMiddleCounters=new Int32Array(4),n}return t.prototype.decodeMiddle=function(n,r,a){var i,o,l=this.decodeMiddleCounters.map(function(y){return y});l[0]=0,l[1]=0,l[2]=0,l[3]=0;for(var c=n.getSize(),u=r[1],d=0,h=0;h<6&&u<c;h++){var f=t.decodeDigit(n,l,u,t.L_AND_G_PATTERNS);a+=String.fromCharCode(48+f%10);try{for(var m=(i=void 0,GXe(l)),x=m.next();!x.done;x=m.next()){var g=x.value;u+=g}}catch(y){i={error:y}}finally{try{x&&!x.done&&(o=m.return)&&o.call(m)}finally{if(i)throw i.error}}f>=10&&(d|=1<<5-h)}return t.determineNumSysAndCheckDigit(new Kt(a),d),u},t.prototype.decodeEnd=function(n,r){return t.findGuardPatternWithoutCounters(n,r,!0,t.MIDDLE_END_PATTERN)},t.prototype.checkChecksum=function(n){return ss.checkChecksum(t.convertUPCEtoUPCA(n))},t.determineNumSysAndCheckDigit=function(n,r){for(var a=0;a<=1;a++)for(var i=0;i<10;i++)if(r===this.NUMSYS_AND_CHECK_DIGIT_PATTERNS[a][i]){n.insert(0,"0"+a),n.append("0"+i);return}throw Oe.getNotFoundInstance()},t.prototype.getBarcodeFormat=function(){return wt.UPC_E},t.convertUPCEtoUPCA=function(n){var r=n.slice(1,7).split("").map(function(o){return o.charCodeAt(0)}),a=new Kt;a.append(n.charAt(0));var i=r[5];switch(i){case 0:case 1:case 2:a.appendChars(r,0,2),a.append(i),a.append("0000"),a.appendChars(r,2,3);break;case 3:a.appendChars(r,0,3),a.append("00000"),a.appendChars(r,3,2);break;case 4:a.appendChars(r,0,4),a.append("00000"),a.append(r[4]);break;default:a.appendChars(r,0,5),a.append("0000"),a.append(i);break}return n.length>=8&&a.append(n.charAt(7)),a.toString()},t.MIDDLE_END_PATTERN=Int32Array.from([1,1,1,1,1,1]),t.NUMSYS_AND_CHECK_DIGIT_PATTERNS=[Int32Array.from([56,52,50,49,44,38,35,42,41,37]),Int32Array.from([7,11,13,14,19,25,28,21,22,1])],t})(ss),YXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
926t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),f8=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},Dj=(function(e){YXe(t,e);function t(n){var r=e.call(this)||this,a=n==null?null:n.get(On.POSSIBLE_FORMATS),i=[];return a!=null&&(a.indexOf(wt.EAN_13)>-1&&i.push(new l2),a.indexOf(wt.UPC_A)>-1&&i.push(new d8),a.indexOf(wt.EAN_8)>-1&&i.push(new u8),a.indexOf(wt.UPC_E)>-1&&i.push(new h8)),i.length===0&&(i.push(new l2),i.push(new d8),i.push(new u8),i.push(new h8)),r.readers=i,r}return t.prototype.decodeRow=function(n,r,a){var i,o;try{for(var l=f8(this.readers),c=l.next();!c.done;c=l.next()){var u=c.value;try{var d=u.decodeRow(n,r,a),h=d.getBarcodeFormat()===wt.EAN_13&&d.getText().charAt(0)==="0",f=a==null?null:a.get(On.POSSIBLE_FORMATS),m=f==null||f.includes(wt.UPC_A);if(h&&m){var x=d.getRawBytes(),g=new Ts(d.getText().substring(1),x,x?x.length:null,d.getResultPoints(),wt.UPC_A);return g.putAllMetadata(d.getResultMetadata()),g}return d}catch{}}}catch(y){i={error:y}}finally{try{c&&!c.done&&(o=l.return)&&o.call(l)}finally{if(i)throw i.error}}throw new Oe},t.prototype.reset=function(){var n,r;try{for(var a=f8(this.readers),i=a.next();!i.done;i=a.next()){var o=i.value;o.reset()}}catch(l){n={error:l}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}},t})(ls),ZXe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),XXe=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,i=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},JXe=function(e,t,n){if(n||arguments.length===2)for(var r=0,a=t.length,i;r<a;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},QXe=(function(e){ZXe(t,e);function t(){var n=e.apply(this,JXe([],XXe(arguments),!1))||this;return n.CODA_BAR_CHAR_SET={nnnnnww:"0",nnnnwwn:"1",nnnwnnw:"2",wwnnnnn:"3",nnwnnwn:"4",wnnnnwn:"5",nwnnnnw:"6",nwnnwnn:"7",nwwnnnn:"8",wnnwnnn:"9",nnnwwnn:"-",nnwwnnn:"$",wnnnwnw:":",wnwnnnw:"/",wnwnwnn:".",nnwwwww:"+",nnwwnwn:"A",nwnwnnw:"B",nnnwnww:"C",nnnwwwn:"D"},n}return t.prototype.decodeRow=function(n,r,a){var i=this.getValidRowData(r);if(!i)throw new Oe;var o=this.codaBarDecodeRow(i.row);if(!o)throw new Oe;return new Ts(o,null,0,[new mt(i.left,n),new mt(i.right,n)],wt.CODABAR,new Date().getTime())},t.prototype.getValidRowData=function(n){var r=n.toArray(),a=r.indexOf(!0);if(a===-1)return null;var i=r.lastIndexOf(!0);if(i<=a)return null;r=r.slice(a,i+1);for(var o=[],l=r[0],c=1,u=1;u<r.length;u++)r[u]===l?c++:(l=r[u],o.push(c),c=1);return o.push(c),o.length<23&&(o.length+1)%8!==0?null:{row:o,left:a,right:i}},t.prototype.codaBarDecodeRow=function(n){for(var r=[],a=Math.ceil(n.reduce(function(c,u){return(c+u)/2},0));n.length>0;){var i=n.splice(0,8).splice(0,7),o=i.map(function(c){return c<a?"n":"w"}).join("");if(this.CODA_BAR_CHAR_SET[o]===void 0)return null;r.push(this.CODA_BAR_CHAR_SET[o])}var l=r.join("");return this.validCodaBarString(l)?l:null},t.prototype.validCodaBarString=function(n){var r=/^[A-D].{1,}[A-D]$/;return r.test(n)},t})(ls),eJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
926t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),tJe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},Gu=(function(e){eJe(t,e);function t(){var n=e.call(this)||this;return n.decodeFinderCounters=new Int32Array(4),n.dataCharacterCounters=new Int32Array(8),n.oddRoundingErrors=new Array(4),n.evenRoundingErrors=new Array(4),n.oddCounts=new Array(Math.trunc(n.dataCharacterCounters.length/2)),n.evenCounts=new Array(Math.trunc(n.dataCharacterCounters.length/2)),n}return t.prototype.getDecodeFinderCounters=function(){return this.decodeFinderCounters},t.prototype.getDataCharacterCounters=function(){return this.dataCharacterCounters},t.prototype.getOddRoundingErrors=function(){return this.oddRoundingErrors},t.prototype.getEvenRoundingErrors=function(){return this.evenRoundingErrors},t.prototype.getOddCounts=function(){return this.oddCounts},t.prototype.getEvenCounts=function(){return this.evenCounts},t.prototype.parseFinderValue=function(n,r){for(var a=0;a<r.length;a++)if(ls.patternMatchVariance(n,r[a],t.MAX_INDIVIDUAL_VARIANCE)<t.MAX_AVG_VARIANCE)return a;throw new Oe},t.count=function(n){return mn.sum(new Int32Array(n))},t.increment=function(n,r){for(var a=0,i=r[0],o=1;o<n.length;o++)r[o]>i&&(i=r[o],a=o);n[a]++},t.decrement=function(n,r){for(var a=0,i=r[0],o=1;o<n.length;o++)r[o]<i&&(i=r[o],a=o);n[a]--},t.isFinderPattern=function(n){var r,a,i=n[0]+n[1],o=i+n[2]+n[3],l=i/o;if(l>=t.MIN_FINDER_PATTERN_RATIO&&l<=t.MAX_FINDER_PATTERN_RATIO){var c=Number.MAX_SAFE_INTEGER,u=Number.MIN_SAFE_INTEGER;try{for(var d=tJe(n),h=d.next();!h.done;h=d.next()){var f=h.value;f>u&&(u=f),f<c&&(c=f)}}catch(m){r={error:m}}finally{try{h&&!h.done&&(a=d.return)&&a.call(d)}finally{if(r)throw r.error}}return u<10*c}return!1},t.MAX_AVG_VARIANCE=.2,t.MAX_INDIVIDUAL_VARIANCE=.45,t.MIN_FINDER_PATTERN_RATIO=9.5/12,t.MAX_FINDER_PATTERN_RATIO=12.5/14,t})(ls),Fv=(function(){function e(t,n){this.value=t,this.checksumPortion=n}return e.prototype.getValue=function(){return this.value},e.prototype.getChecksumPortion=function(){return this.checksumPortion},e.prototype.toString=function(){return this.value+"("+this.checksumPortion+")"},e.prototype.equals=function(t){if(!(t instanceof e))return!1;var n=t;return this.value===n.value&&this.checksumPortion===n.checksumPortion},e.prototype.hashCode=function(){return this.value^this.checksumPortion},e})(),GG=(function(){function e(t,n,r,a,i){this.value=t,this.startEnd=n,this.resultPoints=new Array,this.resultPoints.push(new mt(r,i)),this.resultPoints.push(new mt(a,i))}return e.prototype.getValue=function(){return this.value},e.prototype.getStartEnd=function(){return this.startEnd},e.prototype.getResultPoints=function(){return this.resultPoints},e.prototype.equals=function(t){if(!(t instanceof e))return!1;var n=t;return this.value===n.value},e.prototype.hashCode=function(){return this.value},e})(),nJe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},Ah=(function(){function e(){}return e.getRSSvalue=function(t,n,r){var a,i,o=0;try{for(var l=nJe(t),c=l.next();!c.done;c=l.next()){var u=c.value;o+=u}}catch(v){a={error:v}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(a)throw a.error}}for(var d=0,h=0,f=t.length,m=0;m<f-1;m++){var x=void 0;for(x=1,h|=1<<m;x<t[m];x++,h&=~(1<<m)){var g=e.combins(o-x-1,f-m-2);if(r&&h===0&&o-x-(f-m-1)>=f-m-1&&(g-=e.combins(o-x-(f-m),f-m-2)),f-m-1>1){for(var y=0,b=o-x-(f-m-2);b>n;b--)y+=e.combins(o-x-b-1,f-m-3);g-=y*(f-1-m)}else o-x>n&&g--;d+=g}o-=x}return d},e.combins=function(t,n){var r=0,a=0;t-n>n?(a=n,r=t-n):(a=t-n,r=n);for(var i=1,o=1,l=t;l>r;l--)i*=l,o<=a&&(i=Math.trunc(i/o),o++);for(;o<=a;)i=Math.trunc(i/o),o++;return i},e})(),rJe=(function(){function e(){}return e.buildBitArray=function(t){var n=t.length*2-1;t[t.length-1].getRightChar()===null&&(n-=1);for(var r=12*n,a=new ks(r),i=0,o=t[0],l=o.getRightChar().getValue(),c=11;c>=0;--c)(l&1<<c)!==0&&a.set(i),i++;for(var c=1;c<t.length;++c){for(var u=t[c],d=u.getLeftChar().getValue(),h=11;h>=0;--h)(d&1<<h)!==0&&a.set(i),i++;if(u.getRightChar()!==null)for(var f=u.getRightChar().getValue(),h=11;h>=0;--h)(f&1<<h)!==0&&a.set(i),i++}return a},e})(),Fu=(function(){function e(t,n){this.decodedInformation=t||null,this.finished=!!n}return e.prototype.getDecodedInformation=function(){return this.decodedInformation},e.prototype.isFinished=function(){return this.finished},e})(),Rl;(function(e){e[e.NUMERIC=0]="NUMERIC",e[e.ALPHA=1]="ALPHA",e[e.ISO_IEC_646=2]="ISO_IEC_646"})(Rl||(Rl={}));var sJe=(function(){function e(){this.position=0,this.encoding=Rl.NUMERIC}return e.prototype.getPosition=function(){return this.position},e.prototype.setPosition=function(t){this.position=t},e.prototype.incrementPosition=function(t){this.position+=t},e.prototype.isAlpha=function(){return this.encoding===Rl.ALPHA}
926,e.prototype.isNumeric=function(){return this.encoding===Rl.NUMERIC},e.prototype.isIsoIec646=function(){return this.encoding===Rl.ISO_IEC_646},e.prototype.setNumeric=function(){this.encoding=Rl.NUMERIC},e.prototype.setAlpha=function(){this.encoding=Rl.ALPHA},e.prototype.setIsoIec646=function(){this.encoding=Rl.ISO_IEC_646},e})(),iT=(function(){function e(t){this.newPosition=t}return e.prototype.getNewPosition=function(){return this.newPosition},e})(),aJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),lo=(function(e){aJe(t,e);function t(n,r){var a=e.call(this,n)||this;return a.value=r,a}return t.prototype.getValue=function(){return this.value},t.prototype.isFNC1=function(){return this.value===t.FNC1},t.FNC1="$",t})(iT),iJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Bu=(function(e){iJe(t,e);function t(n,r,a){var i=e.call(this,n)||this;return i.newString=r,a===void 0?(i.remaining=!1,i.remainingValue=0):(i.remaining=!0,i.remainingValue=a),i}return t.prototype.getNewString=function(){return this.newString},t.prototype.isRemaining=function(){return this.remaining},t.prototype.getRemainingValue=function(){return this.remainingValue},t})(iT),oJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),hh=(function(e){oJe(t,e);function t(n,r,a){var i=e.call(this,n)||this;if(r<0||r>10||a<0||a>10)throw new We;return i.firstDigit=r,i.secondDigit=a,i}return t.prototype.getFirstDigit=function(){return this.firstDigit},t.prototype.getSecondDigit=function(){return this.secondDigit},t.prototype.getValue=function(){return this.firstDigit*10+this.secondDigit},t.prototype.isFirstDigitFNC1=function(){return this.firstDigit===t.FNC1},t.prototype.isSecondDigitFNC1=function(){return this.secondDigit===t.FNC1},t.FNC1=10,t})(iT),lJe=(function(){function e(){}return e.fixed=function(t,n){return function(r){return e.process
926FixedAI(t,n,r)}},e.variable=function(t,n){return function(r){return e.processVariableAI(t,n,r)}},e.parseFieldsInGeneralPurpose=function(t){if(!t)return null;if(t.length<2)throw new Oe;var n=t.substring(0,2),r=this.TWO_DIGIT_DATA_LENGTH.get(n);if(r)return r(t);if(t.length<3)throw new Oe;var a=t.substring(0,3),i=this.THREE_DIGIT_DATA_LENGTH.get(a);if(i)return i(t);var o=this.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH.get(a);if(o)return o(t);if(t.length<4)throw new Oe;var l=t.substring(0,4),c=this.FOUR_DIGIT_DATA_LENGTH.get(l);if(c)return c(t);throw new Oe},e.processFixedAI=function(t,n,r){if(r.length<t)throw new Oe;var a=r.substring(0,t);if(r.length<t+n)throw new Oe;var i=r.substring(t,t+n),o=r.substring(t+n),l="("+a+")"+i,c=e.parseFieldsInGeneralPurpose(o);return c===null?l:l+c},e.processVariableAI=function(t,n,r){var a=r.substring(0,t),i;r.length<t+n?i=r.length:i=t+n;var o=r.substring(t,i),l=r.substring(i),c="("+a+")"+o,u=e.parseFieldsInGeneralPurpose(l);return u===null?c:c+u},e.TWO_DIGIT_DATA_LENGTH=(function(){var t=new Map;t.set("00",e.fixed(2,18)),t.set("01",e.fixed(2,14)),t.set("02",e.fixed(2,14)),t.set("10",e.variable(2,20)),t.set("11",e.fixed(2,6)),t.set("12",e.fixed(2,6)),t.set("13",e.fixed(2,6)),t.set("15",e.fixed(2,6)),t.set("16",e.fixed(2,6)),t.set("17",e.fixed(2,6)),t.set("20",e.fixed(2,2)),t.set("21",e.variable(2,20)),t.set("22",e.variable(2,29)),t.set("30",e.variable(2,8)),t.set("37",e.variable(2,8));for(var n=90;n<=99;n++)t.set(String(n),e.variable(2,30));return t})(),e.THREE_DIGIT_DATA_LENGTH=new Map([["235",e.variable(3,28)],["240",e.variable(3,30)],["241",e.variable(3,30)],["242",e.variable(3,6)],["243",e.variable(3,20)],["250",e.variable(3,30)],["251",e.variable(3,30)],["253",e.variable(3,30)],["254",e.variable(3,20)],["255",e.variable(3,25)],["400",e.variable(3,30)],["401",e.variable(3,30)],["402",e.fixed(3,17)],["403",e.variable(3,30)],["410",e.fixed(3,13)],["411",e.fixed(3,13)],["412",e.fixed(3,13)],["413",e.fixed(3,13)],["414",e.fixed(3,13)],["415",e.fixed(3,13)],["416",e.fixed(3,13)],["417",e.fixed(3,13)],["420",e.variable(3,20)],["421",e.variable(3,15)],["422",e.fixed(3,3)],["423",e.variable(3,15)],["424",e.fixed(3,3)],["425",e.variable(3,15)],["426",e.fixed(3,3)],["427",e.variable(3,3)],["710",e.variable(3,20)],["711",e.variable(3,20)],["712",e.variable(3,20)],["713",e.variable(3,20)],["714",e.variable(3,20)],["715",e.variable(3,20)]]),e.THREE_DIGIT_PLUS_DIGIT_DATA_LENGTH=(function(){for(var t=new Map,n=310;n<=316;n++)t.set(String(n),e.fixed(4,6));for(var n=320;n<=337;n++)t.set(String(n),e.fixed(4,6));for(var n=340;n<=357;n++)t.set(String(n),e.fixed(4,6));for(var n=360;n<=369;n++)t.set(String(n),e.fixed(4,6));return t.set("390",e.variable(4,15)),t.set("391",e.variable(4,18)),t.set("392",e.variable(4,15)),t.set("393",e.variable(4,18)),t.set("394",e.fixed(4,4)),t.set("395",e.fixed(4,6)),t.set("703",e.variable(4,30)),t.set("723",e.variable(4,30)),t})(),e.FOUR_DIGIT_DATA_LENGTH=(function(){var t=new Map;return t.set("4300",e.variable(4,35)),t.set("4301",e.variable(4,35)),t.set("4302",e.variable(4,70)),t.set("4303",e.variable(4,70)),t.set("4304",e.variable(4,70)),t.set("4305",e.variable(4,70)),t.set("4306",e.variable(4,70)),t.set("4307",e.fixed(4,2)),t.set("4308",e.variable(4,30)),t.set("4309",e.fixed(4,20)),t.set("4310",e.variable(4,35)),t.set("4311",e.variable(4,35)),t.set("4312",e.variable(4,70)),t.set("4313",e.variable(4,70)),t.set("4314",e.variable(4,70)),t.set("4315",e.variable(4,70)),t.set("4316",e.variable(4,70)),t.set("4317",e.fixed(4,2)),t.set("4318",e.variable(4,20)),t.set("4319",e.variable(4,30)),t.set("4320",e.variable(4,35)),t.set("4321",e.fixed(4,1)),t.set("4322",e.fixed(4,1)),t.set("4323",e.fixed(4,1)),t.set("4324",e.fixed(4,10)),t.set("4325",e.fixed(4,10)),t.set("4326",e.fixed(4,6)),t.set("7001",e.fixed(4,13)),t.set("7002",e.variable(4,30)),t.set("7003",e.fixed(4,10)),t.set("7004",e.variable(4,4)),t.set("7005",e.variable(4,12)),t.set("7006",e.fixed(4,6)),t.set("7007",e.variable(4,12)),t.set("7008",e.variable(4,3)),t.set("7009",e.variable(4,10)),t.set("7010",e.variable(4,2)),t.set("7011",e.variable(4,10)),t.set("7020",e.variable(4,20)),t.set("7021",e.variable(4,20)),t.set("7022",e.variable(4,20)),t.set("7023",e.variable(4,30)),t.set("7040",e.fixed(4,4)),t.set("7240",e.variable(4,20)),t.set("8001",e.fixed(4,14)),t.set("8002",e.variable(4,20)),t.set("8003",e.variable(4,30)),t.set("8004",e.variable(4,30)),t.set("8005",e.fixed(4,6)),t.set("8006",e.fixed(4,18)),t.set("8007",e.variable(4,34)),t.set("8008",e.variable(4,12)),t.set("8009",e.variable(4,50)),t.set("8010",e.variable(4,30)),t.set("8011",e.variable(4,12)),t.set("8012",e.variable(4,20)),t.set("8013",e.variable(4,25)),t.set("8017",e.fixed(4,18)),t.set("8018",e.fixed(4,18)),t.set("8019",e.variable(4,10)),t.set("8020",e.variable(4,25)),t.set("8026",e.fixed(4,18)),t.set("8100",e.fixed(4,6)),t.set("8101",e.fixed(4,10)),t.set("8102",e.fixed(4,2)),t.set("8110",e.variable(4,70)),t.set("8111",e.fixed(4,4)),t.set("8112",e.variable(4,70)),t.set("8200",e.variable(4,70)),t})(),e}
926)(),Wy=(function(){function e(t){this.current=new sJe,this.buffer=new Kt,this.information=t}return e.prototype.decodeAllCodes=function(t,n){var r=n,a=null;do{var i=this.decodeGeneralPurposeField(r,a),o=lJe.parseFieldsInGeneralPurpose(i.getNewString());if(o!==null&&t.append(o),i.isRemaining()?a=""+i.getRemainingValue():a=null,r===i.getNewPosition())break;r=i.getNewPosition()}while(!0);return t.toString()},e.prototype.isStillNumeric=function(t){if(t+7>this.information.getSize())return t+4<=this.information.getSize();for(var n=t;n<t+3;++n)if(this.information.get(n))return!0;return this.information.get(t+3)},e.prototype.decodeNumeric=function(t){if(t+7>this.information.getSize()){var n=this.extractNumericValueFromBitArray(t,4);return n===0?new hh(this.information.getSize(),hh.FNC1,hh.FNC1):new hh(this.information.getSize(),n-1,hh.FNC1)}var r=this.extractNumericValueFromBitArray(t,7),a=Math.trunc((r-8)/11),i=(r-8)%11;return new hh(t+7,a,i)},e.prototype.extractNumericValueFromBitArray=function(t,n){return e.extractNumericValueFromBitArray(this.information,t,n)},e.extractNumericValueFromBitArray=function(t,n,r){for(var a=0,i=0;i<r;++i)t.get(n+i)&&(a|=1<<r-i-1);return a},e.prototype.decodeGeneralPurposeField=function(t,n){this.buffer.setLengthToZero(),n!==null&&this.buffer.append(n),this.current.setPosition(t);var r=this.parseBlocks();return r!==null&&r.isRemaining()?new Bu(this.current.getPosition(),this.buffer.toString(),r.getRemainingValue()):new Bu(this.current.getPosition(),this.buffer.toString())},e.prototype.parseBlocks=function(){var t=!1,n;do{var r=this.current.getPosition();this.current.isAlpha()?(n=this.parseAlphaBlock(),t=n.isFinished()):this.current.isIsoIec646()?(n=this.parseIsoIec646Block(),t=n.isFinished()):(n=this.parseNumericBlock(),t=n.isFinished());var a=r!==this.current.getPosition();if(!a&&!t)break}while(!t);return n.getDecodedInformation()},e.prototype.parseNumericBlock=function(){for(;this.isStillNumeric(this.current.getPosition());){var t=this.decodeNumeric(this.current.getPosition());if(this.current.setPosition(t.getNewPosition()),t.isFirstDigitFNC1()){var n=void 0;return t.isSecondDigitFNC1()?n=new Bu(this.current.getPosition(),this.buffer.toString()):n=new Bu(this.current.getPosition(),this.buffer.toString(),t.getSecondDigit()),new Fu(n,!0)}if(this.buffer.append(""+t.getFirstDigit()),t.isSecondDigitFNC1()){var n=new Bu(this.current.getPosition(),this.buffer.toString());return new Fu(n,!0)}this.buffer.append(""+t.getSecondDigit())}return this.isNumericToAlphaNumericLatch(this.current.getPosition())&&(this.current.setAlpha(),this.current.incrementPosition(4)),new Fu},e.prototype.parseIsoIec646Block=function(){for(;this.isStillIsoIec646(this.current.getPosition());){var t=this.decodeIsoIec646(this.current.getPosition());if(this.current.setPosition(t.getNewPosition()),t.isFNC1()){var n=new Bu(this.current.getPosition(),this.buffer.toString());return new Fu(n,!0)}this.buffer.append(t.getValue())}return this.isAlphaOr646ToNumericLatch(this.current.getPosition())?(this.current.incrementPosition(3),this.current.setNumeric()):this.isAlphaTo646ToAlphaLatch(this.current.getPosition())&&(this.current.getPosition()+5<this.information.getSize()?this.current.incrementPosition(5):this.current.setPosition(this.information.getSize()),this.current.setAlpha()),new Fu},e.prototype.parseAlphaBlock=function(){for(;this.isStillAlpha(this.current.getPosition());){var t=this.decodeAlphanumeric(this.current.getPosition());if(this.current.setPosition(t.getNewPosition()),t.isFNC1()){var n=new Bu(this.current.getPosition(),this.buffer.toString());return new Fu(n,!0)}this.buffer.append(t.getValue())}return this.isAlphaOr646ToNumericLatch(this.current.getPosition())?(this.current.incrementPosition(3),this.current.setNumeric()):this.isAlphaTo646ToAlphaLatch(this.current.getPosition())&&(this.current.getPosition()+5<this.information.getSize()?this.current.incrementPosition(5):this.current.setPosition(this.information.getSize()),this.current.setIsoIec646()),new Fu},e.prototype.isStillIsoIec646=function(t){if(t+5>this.information.getSize())return!1;var n=this.extractNumericValueFromBitArray(t,5);if(n>=5&&n<16)return!0;
926if(t+7>this.information.getSize())return!1;var r=this.extractNumericValueFromBitArray(t,7);if(r>=64&&r<116)return!0;if(t+8>this.information.getSize())return!1;var a=this.extractNumericValueFromBitArray(t,8);return a>=232&&a<253},e.prototype.decodeIsoIec646=function(t){var n=this.extractNumericValueFromBitArray(t,5);if(n===15)return new lo(t+5,lo.FNC1);if(n>=5&&n<15)return new lo(t+5,String.fromCharCode(48+n-5));var r=this.extractNumericValueFromBitArray(t,7);if(r>=64&&r<90)return new lo(t+7,String.fromCharCode(r+1));if(r>=90&&r<116)return new lo(t+7,String.fromCharCode(r+7));var a=this.extractNumericValueFromBitArray(t,8),i;switch(a){case 232:i="!";break;case 233:i='"';break;case 234:i="%";break;case 235:i="&";break;case 236:i="'";break;case 237:i="(";break;case 238:i=")";break;case 239:i="*";break;case 240:i="+";break;case 241:i=",";break;case 242:i="-";break;case 243:i=".";break;case 244:i="/";break;case 245:i=":";break;case 246:i=";";break;case 247:i="<";break;case 248:i="=";break;case 249:i=">";break;case 250:i="?";break;case 251:i="_";break;case 252:i=" ";break;default:throw new We}return new lo(t+8,i)},e.prototype.isStillAlpha=function(t){if(t+5>this.information.getSize())return!1;var n=this.extractNumericValueFromBitArray(t,5);if(n>=5&&n<16)return!0;if(t+6>this.information.getSize())return!1;var r=this.extractNumericValueFromBitArray(t,6);return r>=16&&r<63},e.prototype.decodeAlphanumeric=function(t){var n=this.extractNumericValueFromBitArray(t,5);if(n===15)return new lo(t+5,lo.FNC1);if(n>=5&&n<15)return new lo(t+5,String.fromCharCode(48+n-5));var r=this.extractNumericValueFromBitArray(t,6);if(r>=32&&r<58)return new lo(t+6,String.fromCharCode(r+33));var a;switch(r){case 58:a="*";break;case 59:a=",";break;case 60:a="-";break;case 61:a=".";break;case 62:a="/";break;default:throw new Gf("Decoding invalid alphanumeric value: "+r)}return new lo(t+6,a)},e.prototype.isAlphaTo646ToAlphaLatch=function(t){if(t+1>this.information.getSize())return!1;for(var n=0;n<5&&n+t<this.information.getSize();++n)if(n===2){if(!this.information.get(t+2))return!1}else if(this.information.get(t+n))return!1;return!0},e.prototype.isAlphaOr646ToNumericLatch=function(t){if(t+3>this.information.getSize())return!1;for(var n=t;n<t+3;++n)if(this.information.get(n))return!1;return!0},e.prototype.isNumericToAlphaNumericLatch=function(t){if(t+1>this.information.getSize())return!1;for(var n=0;n<4&&n+t<this.information.getSize();++n)if(this.information.get(t+n))return!1;return!0},e})(),YG=(function(){function e(t){this.information=t,this.generalDecoder=new Wy(t)}return e.prototype.getInformation=function(){return this.information},e.prototype.getGeneralDecoder=function(){return this.generalDecoder},e})(),cJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),go=(function(e){cJe(t,e);function t(n){return e.call(this,n)||this}return t.prototype.encodeCompressedGtin=function(n,r){n.append("(01)");var a=n.length();n.append("9"),this.encodeCompressedGtinWithoutAI(n,r,a)},t.prototype.encodeCompressedGtinWithoutAI=function(n,r,a){for(var i=0;i<4;++i){var o=this.getGeneralDecoder().extractNumericValueFromBitArray(r+10*i,10);o<100&&n.append("0"),o<10&&n.append("0"),n.append(""+o)}t.appendCheckDigit(n,a)},t.appendCheckDigit=function(n,r){for(var a=0,i=0;i<13;i++){var o=n.charAt(i+r).charCodeAt(0)-48;a+=(i&1)===0?3*o:o}a=10-a%10,a===10&&(a=0),n.append(""+a)},t.GTIN_SIZE=40,t})(YG),uJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
926t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),dJe=(function(e){uJe(t,e);function t(n){return e.call(this,n)||this}return t.prototype.parseInformation=function(){var n=new Kt;n.append("(01)");var r=n.length(),a=this.getGeneralDecoder().extractNumericValueFromBitArray(t.HEADER_SIZE,4);return n.append(""+a),this.encodeCompressedGtinWithoutAI(n,t.HEADER_SIZE+4,r),this.getGeneralDecoder().decodeAllCodes(n,t.HEADER_SIZE+44)},t.HEADER_SIZE=4,t})(go),hJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),fJe=(function(e){hJe(t,e);function t(n){return e.call(this,n)||this}return t.prototype.parseInformation=function(){var n=new Kt;return this.getGeneralDecoder().decodeAllCodes(n,t.HEADER_SIZE)},t.HEADER_SIZE=5,t})(YG),mJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Ky=(function(e){mJe(t,e);function t(n){return e.call(this,n)||this}return t.prototype.encodeCompressedWeight=function(n,r,a){var i=this.getGeneralDecoder().extractNumericValueFromBitArray(r,a);this.addWeightCode(n,i);for(var o=this.checkWeight(i),l=1e5,c=0;c<5;++c)o<l&&n.append("0"),l=Math.trunc(l/10);n.append(""+o)},t})(go),pJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),ZG=(function(e){pJe(t,e);function t(n){return e.call(this,n)||this}return t.prototype.parseInformation=function(){if(this.getInformation().getSize()!==t.HEADER_SIZE+Ky.GTIN_SIZE+t.WEIGHT_SIZE)throw new Oe;var n=new Kt;return this.encodeCompressedGtin(n,t.HEADER_SIZE),this.encodeCompressedWeight(n,t.HEADER_SIZE+Ky.GTIN_SIZE,t.WEIGHT_SIZE),n.toString()},t.HEADER_SIZE=5,t.WEIGHT_SIZE=15,t})(Ky),xJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),gJe=(function(e){xJe(t,e);function t(n){return e.call(this,n)||this}return t.prototype.addWeightCode=function(n,r){n.append("(3103)")},t.prototype.checkWeight=function(n){return n},t})(ZG),yJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),bJe=(function(e){yJe(t,e);function t(n){return e.call(this,n)||this}return t.prototype.addWeightCode=function(n,r){r<1e4?n.append("(3202)"):n.append("(3203)")},t.prototype.checkWeight=function(n){return n<1e4?n:n-1e4},t})(ZG),vJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
926t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),wJe=(function(e){vJe(t,e);function t(n){return e.call(this,n)||this}return t.prototype.parseInformation=function(){if(this.getInformation().getSize()<t.HEADER_SIZE+go.GTIN_SIZE)throw new Oe;var n=new Kt;this.encodeCompressedGtin(n,t.HEADER_SIZE);var r=this.getGeneralDecoder().extractNumericValueFromBitArray(t.HEADER_SIZE+go.GTIN_SIZE,t.LAST_DIGIT_SIZE);n.append("(392"),n.append(""+r),n.append(")");var a=this.getGeneralDecoder().decodeGeneralPurposeField(t.HEADER_SIZE+go.GTIN_SIZE+t.LAST_DIGIT_SIZE,null);return n.append(a.getNewString()),n.toString()},t.HEADER_SIZE=8,t.LAST_DIGIT_SIZE=2,t})(go),_Je=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),kJe=(function(e){_Je(t,e);function t(n){return e.call(this,n)||this}return t.prototype.parseInformation=function(){if(this.getInformation().getSize()<t.HEADER_SIZE+go.GTIN_SIZE)throw new Oe;var n=new Kt;this.encodeCompressedGtin(n,t.HEADER_SIZE);var r=this.getGeneralDecoder().extractNumericValueFromBitArray(t.HEADER_SIZE+go.GTIN_SIZE,t.LAST_DIGIT_SIZE);n.append("(393"),n.append(""+r),n.append(")");var a=this.getGeneralDecoder().extractNumericValueFromBitArray(t.HEADER_SIZE+go.GTIN_SIZE+t.LAST_DIGIT_SIZE,t.FIRST_THREE_DIGITS_SIZE);a<100&&n.append("0"),a<10&&n.append("0"),n.append(""+a);var i=this.getGeneralDecoder().decodeGeneralPurposeField(t.HEADER_SIZE+go.GTIN_SIZE+t.LAST_DIGIT_SIZE+t.FIRST_THREE_DIGITS_SIZE,null);return n.append(i.getNewString()),n.toString()},t.HEADER_SIZE=8,t.LAST_DIGIT_SIZE=2,t.FIRST_THREE_DIGITS_SIZE=10,t})(go),jJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Ac=(function(e){jJe(t,e);function t(n,r,a){var i=e.call(this,n)||this;return i.dateCode=a,i.firstAIdigits=r,i}return t.prototype.parseInformation=function(){if(this.getInformation().getSize()!==t.HEADER_SIZE+t.GTIN_SIZE+t.WEIGHT_SIZE+t.DATE_SIZE)throw new Oe;var n=new Kt;return this.encodeCompressedGtin(n,t.HEADER_SIZE),this.encodeCompressedWeight(n,t.HEADER_SIZE+t.GTIN_SIZE,t.WEIGHT_SIZE),this.encodeCompressedDate(n,t.HEADER_SIZE+t.GTIN_SIZE+t.WEIGHT_SIZE),n.toString()},t.prototype.encodeCompressedDate=function(n,r){var a=this.getGeneralDecoder().extractNumericValueFromBitArray(r,t.DATE_SIZE);if(a!==38400){n.append("("),n.append(this.dateCode),n.append(")");var i=a%32;a=Math.trunc(a/32);var o=a%12+1;a=Math.trunc(a/12);var l=a;l<10&&n.append("0"),n.append(""+l),o<10&&n.append("0"),n.append(""+o),i<10&&n.append("0"),n.append(""+i)}},t.prototype.addWeightCode=function(n,r){n.append("("),n.append(this.firstAIdigits),n.append(""+Math.trunc(r/1e5)),n.append(")")},t.prototype.checkWeight=function(n){return n%1e5},t.HEADER_SIZE=8,t.WEIGHT_SIZE=20,t.DATE_SIZE=16,t})(Ky);function NJe(e){if(e.get(1))return new dJe(e);
926if(!e.get(2))return new fJe(e);var t=Wy.extractNumericValueFromBitArray(e,1,4);switch(t){case 4:return new gJe(e);case 5:return new bJe(e)}var n=Wy.extractNumericValueFromBitArray(e,1,5);switch(n){case 12:return new wJe(e);case 13:return new kJe(e)}var r=Wy.extractNumericValueFromBitArray(e,1,7);switch(r){case 56:return new Ac(e,"310","11");case 57:return new Ac(e,"320","11");case 58:return new Ac(e,"310","13");case 59:return new Ac(e,"320","13");case 60:return new Ac(e,"310","15");case 61:return new Ac(e,"320","15");case 62:return new Ac(e,"310","17");case 63:return new Ac(e,"320","17")}throw new Gf("unknown decoder: "+e)}var Hy=(function(){function e(t,n,r){this.leftChar=t,this.rightChar=n,this.finderPattern=r}return e.prototype.getLeftChar=function(){return this.leftChar},e.prototype.getRightChar=function(){return this.rightChar},e.prototype.getFinderPattern=function(){return this.finderPattern},e.prototype.mustBeLast=function(){return this.rightChar===null},e.prototype.toString=function(){return"[ "+this.leftChar+", "+this.rightChar+" : "+(this.finderPattern===null?"null":this.finderPattern.getValue())+" ]"},e.equals=function(t,n){return n===null?t===null:n instanceof e?(t.leftChar===null?n.leftChar===null:t.leftChar.equals(n.leftChar))&&(t.rightChar===null?n.rightChar===null:t.rightChar.equals(n.rightChar))&&(t.finderPattern===null?n.finderPattern===null:t.finderPattern.equals(n.finderPattern)):!1},e.prototype.hashCode=function(){return e.hashNotNull(this.leftChar)^e.hashNotNull(this.rightChar)^e.hashNotNull(this.finderPattern)},e.hashNotNull=function(t){return t===null?0:t.hashCode()},e})(),SJe=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,i=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},CJe=function(e,t,n){if(n||arguments.length===2)for(var r=0,a=t.length,i;r<a;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},EJe=(function(){function e(t,n){this.pairs=CJe([],SJe(t),!1),this.rowNumber=n}return e.prototype.getPairs=function(){return this.pairs},e.prototype.getRowNumber=function(){return this.rowNumber},e.prototype.isEquivalent=function(t){return e.listEquals(this.getPairs(),t)},e.prototype.toString=function(){return"{ "+this.pairs+" }"},e.equals=function(t,n){return t===null?n===null:n instanceof e?e.listEquals(t.pairs,n.getPairs()):!1},e.listEquals=function(t,n){return t.length!==n.length?!1:t.every(function(r,a){var i=n[a];return Hy.equals(r,i)})},e})(),AJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),m8=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,i=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},p8=function(e,t,n){if(n||arguments.length===2)for(var r=0,a=t.length,i;r<a;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},fh=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},x8=(function(e){AJe(t,e);function t(){var n=e.apply(this,p8([],m8(arguments),!1))||this;return n.pairs=new Array(t.MAX_PAIRS),n.rows=new Array,n.startEnd=[0,0],n.startFromEven=!1,n}return t.prototype.decodeRow=function(n,r,a){this.startFromEven=!1;try{return t.constructResult(this.decodeRow2pairs(n,r))}catch(i){if(!(i instanceof Oe))throw i}return this.startFromEven=!0,t.constructResult(this.decodeRow2pairs(n,r))},t.prototype.reset=function(){this.pairs.length=0,this.rows.length=0},t.prototype.decodeRow2pairs=function(n,r){this.pairs.length=0;for(var a=!1;!a;)try{this.pairs.push(this.retrieveNextPair(r,this.pairs,n))}catch(l){if(l instanceof Oe){if(this.pairs.length===0)throw l;a=!0}else throw l}if(this.checkChecksum()&&t.isValidSequence(this.pairs,!0))return this.pairs;var i=this.rows.length>0;if(this.storeRow(n),i){var o=this.checkRowsBoolean(!1);if(o!==null||(o=this.checkRowsBoolean(!0),o!==null))return o}throw new Oe},t.prototype.checkRowsBoolean=function(n){if(this.rows.length>25)return this.rows.length=0,null;this.pairs.length=0,n&&this.rows.reverse();var r=null;try{r=this.checkRows(new Array,0)}catch(a){if(!(a instanceof Oe))throw a}return n&&this.rows.reverse(),r},t.prototype.checkRows=function(n,r){for(var a,i=r;i<this.rows.length;i++){var o=this.rows[i];(a=this.pairs).push.apply(a,p8([],m8(o.getPairs()),!1));var l=o.getPairs().length;if(t.isValidSequence(this.pairs,!1)){if(this.checkChecksum())return this.pairs;n.push(o);try{return this.checkRows(n,i+1)}catch(c){if(c instanceof Oe)n.pop(),this.pairs.splice(this.pairs.length-l,l);else throw c}}else this.pairs.splice(this.pairs.length-l,l)}throw new Oe},t.isValidSequence=function(n,r){var a,i;try{for(var o=fh(t.FINDER_PATTERN_SEQUENCES),l=o.next();!l.done;l=o.next()){var c=l.value,u=r?n.length===c.length:n.length<=c.length;if(u){for(var d=!0,h=0;h<n.length;h++)if(n[h].getFinderPattern().getValue()!==c[h]){d=!1;break}if(d)return!0}}}catch(f){a={error:f}}finally{try{l&&!l.done&&(i=o.return)&&i.call(o)}finally{if(a)throw a.error}}return!1},t.mayFollow=function(n,r){var a,i;if(n.length===0)return!0;try{for(var o=fh(this.FINDER_PATTERN_SEQUENCES),l=o.next();!l.done;l=o.next()){var c=l.value;if(n.length+1<=c.length){for(var u=n.length;u<c.length;u++)if(c[u]===r){for(var d=!0,h=0;h<n.length;h++){var f=c[u-h-1],m=n[n.length-h-1].getFinderPattern().getValue();if(f!==m){d=!1;break}}if(d)return!0}}}}catch(x){a={error:x}}finally{try{l&&!l.done&&(i=o.return)&&i.call(o)}finally{if(a)throw a.error}}return!1},t.prototype.storeRow=function(n){for(var r=0,a=!1,i=!1;r<this.rows.length;){var o=this.rows[r];if(o.getRowNumber()>n){i=o.isEquivalent(this.pairs);break}a=o.isEquivalent(this.pairs),r++}i||a||t.isPartialRow(this.pairs,this.rows)||(this.rows.splice(r,0,new EJe(this.pairs,n)),this.removePartialRows(this.pairs,this.rows))},t.prototype.removePartialRows=function(n,r){for(var a,i,o=r.length-1;o>=0;o--){var l=r[o];if(l.getPairs().length!==n.length){var c=!0,u=function(x){if(!n.some(function(g){return Hy.equals(x,g)}))return c=!1,"break"};try{for(var d=(a=void 0,fh(l.getPairs())),h=d.next();!h.done;h=d.next()){var f=h.value,m=u(f);if(m==="break")break}}catch(x){a={error:x}}finally{try{h&&!h.done&&(i=d.return)&&i.call(d)}finally{if(a)throw a.error}}c&&r.splice(o,1)}}},t.isPartialRow=function(n,r){var a,i,o,l,c,u;try{for(var d=fh(r),h=d.next();!h.done;h=d.next()){var f=h.value,m=!0;try{for(var x=(o=void 0,fh(n)),g=x.next();!g.done;g=x.next()){var y=g.value,b=!1;try{for(var v=(c=void 0,fh(f.getPairs())),w=v.next();!w.done;w=v.next()){var _=w.value;if(Hy.equals(y,_)){b=!0;break}}}catch(k){c={error:k}}finally{try{w&&!w.done&&(u=v.return)&&u.call(v)}finally{if(c)throw c.error}}if(!b){m=!1;break}}}catch(k){o={error:k}}finally{try{g&&!g.done&&(l=x.return)&&l.call(x)}finally{if(o)throw o.error}}if(m)return!0}}catch(k){a={error:k}}finally{try{h&&!h.done&&(i=d.return)&&i.call(d)}finally{if(a)throw a.error}}return!1},t.prototype.getRows=function(){return this.rows},t.constructResult=function(n){var r=rJe.buildBitArray(n),a=NJe(r),i=a.parseInformation(),o=n[0].getFinderPattern().getResultPoints(),l=n[n.length-1].getFinderPattern().getResultPoints(),c=[o[0],o[1],l[0],l[1]];return new Ts(i,null,null,c,wt.RSS_EXPANDED,null)},t.prototype.checkChecksum=function(){var n=this.pairs[0],r=n.getLeftChar(),a=n.getRightChar();if(a===null)return!1;for(var i=a.getChecksumPortion(),o=2,l=1;l<this.pairs.length;++l){var c=this.pairs[l];i+=c.getLeftChar().getChecksumPortion(),o++;var u=c.getRightChar();u!==null&&(i+=u.getChecksumPortion(),o++)}i%=211;var d=211*(o-4)+i;return d===r.getValue()},t.getNextSecondBar=function(n,r){var a=0;return n.get(r)?(a=n.getNextUnset(r),a=n.getNextSet(a)):(a=n.getNextSet(r),a=n.getNextUnset(a)),a},t.prototype.retrieveNextPair=function(n,r,a){var i=r.length%2===0;this.startFromEven&&(i=!i);var o=null,l=null,c=!0,u=-1;do if(this.findNextPair(n,r,u),o=this.parseFoundFinderPattern(n,a,i,r),o===null)u=t.getNextSecondBar(n,this.startEnd[0]);else try{l=this.decodeDataCharacter(n,o,i,!0),c=!1}catch(h){if(h instanceof Oe)u=t.getNextSecondBar(n,this.startEnd[0]);else throw h}while(c);if(r.length>0&&r[r.length-1].mustBeLast())throw new Oe;var d=null;try{d=this.decodeDataCharacter(n,o,i,!1)}catch(h){if(h instanceof Oe)d=null;else throw h}return new Hy(l,d,o)},t.prototype.findNextPair=function(n,r,a){var i=this.getDecodeFinderCounters();i[0]=0,i[1]=0,i[2]=0,i[3]=0;
926var o=n.getSize(),l=0;if(a>=0)l=a;else if(r.length===0)l=0;else{var c=r[r.length-1];l=c.getFinderPattern().getStartEnd()[1]}var u=r.length%2!==0;this.startFromEven&&(u=!u);for(var d=!1;l<o&&(d=!n.get(l),!!d);)l++;for(var h=0,f=l,m=l;m<o;m++)if(n.get(m)!==d)i[h]++;else{if(h===3){if(u&&t.reverseCounters(i),t.isFinderPattern(i)){this.startEnd[0]=f,this.startEnd[1]=m;return}u&&t.reverseCounters(i),f+=i[0]+i[1],i[0]=i[2],i[1]=i[3],i[2]=0,i[3]=0,h--}else h++;i[h]=1,d=!d}throw new Oe},t.reverseCounters=function(n){for(var r=n.length,a=0;a<Math.trunc(r/2);++a){var i=n[a];n[a]=n[r-a-1],n[r-a-1]=i}},t.prototype.parseFoundFinderPattern=function(n,r,a,i){var o=0,l=0,c=0;if(a){for(var u=this.startEnd[0]-1;u>=0&&!n.get(u);)u--;u++,o=this.startEnd[0]-u,l=u,c=this.startEnd[1]}else l=this.startEnd[0],c=n.getNextUnset(this.startEnd[1]+1),o=c-this.startEnd[1];var d=this.getDecodeFinderCounters();Fn.arraycopy(d,0,d,1,d.length-1),d[0]=o;var h=0;try{h=this.parseFinderValue(d,t.FINDER_PATTERNS)}catch(w){if(w instanceof Oe)return null;throw w}if(!t.mayFollow(i,h))return null;if(i.length>0){var f=i[i.length-1],m=f.getFinderPattern().getStartEnd()[0],x=f.getFinderPattern().getStartEnd()[1],g=x-m,y=g/t.FINDER_PATTERN_MODULES*t.DATA_CHARACTER_MODULES,b=x+2*y*(1-t.MAX_FINDER_PATTERN_DISTANCE_VARIANCE),v=x+2*y*(1+t.MAX_FINDER_PATTERN_DISTANCE_VARIANCE);if(l<b||l>v)return null}return new GG(h,[l,c],l,c,r)},t.prototype.decodeDataCharacter=function(n,r,a,i){for(var o=this.getDataCharacterCounters(),l=0;l<o.length;l++)o[l]=0;if(i)t.recordPatternInReverse(n,r.getStartEnd()[0],o);else{t.recordPattern(n,r.getStartEnd()[1],o);for(var c=0,u=o.length-1;c<u;c++,u--){var d=o[c];o[c]=o[u],o[u]=d}}var h=17,f=mn.sum(new Int32Array(o))/h,m=(r.getStartEnd()[1]-r.getStartEnd()[0])/15;if(Math.abs(f-m)/m>.3)throw new Oe;for(var x=this.getOddCounts(),g=this.getEvenCounts(),y=this.getOddRoundingErrors(),b=this.getEvenRoundingErrors(),c=0;c<o.length;c++){var v=1*o[c]/f,w=Math.trunc(v+.5);if(w<1){if(v<.3)throw new Oe;w=1}else if(w>8){if(v>8.7)throw new Oe;w=8}var _=Math.trunc(c/2);(c&1)===0?(x[_]=w,y[_]=v-w):(g[_]=w,b[_]=v-w)}this.adjustOddEvenCounts(h);for(var k=4*r.getValue()+(a?0:2)+(i?0:1)-1,j=0,N=0,c=x.length-1;c>=0;c--){if(t.isNotA1left(r,a,i)){var E=t.WEIGHTS[k][2*c];N+=x[c]*E}j+=x[c]}for(var A=0,c=g.length-1;c>=0;c--)if(t.isNotA1left(r,a,i)){var E=t.WEIGHTS[k][2*c+1];A+=g[c]*E}var C=N+A;if((j&1)!==0||j>13||j<4)throw new Oe;var T=Math.trunc((13-j)/2),S=t.SYMBOL_WIDEST[T],O=9-S,R=Ah.getRSSvalue(x,S,!0),I=Ah.getRSSvalue(g,O,!1),$=t.EVEN_TOTAL_SUBSET[T],P=t.GSUM[T],F=R*$+I+P;return new Fv(F,C)},t.isNotA1left=function(n,r,a){return!(n.getValue()===0&&r&&a)},t.prototype.adjustOddEvenCounts=function(n){var r=mn.sum(new Int32Array(this.getOddCounts())),a=mn.sum(new Int32Array(this.getEvenCounts())),i=!1,o=!1;r>13?o=!0:r<4&&(i=!0);var l=!1,c=!1;a>13?c=!0:a<4&&(l=!0);var u=r+a-n,d=(r&1)===1,h=(a&1)===0;if(u===1)if(d){if(h)throw new Oe;o=!0}else{if(!h)throw new Oe;c=!0}else if(u===-1)if(d){if(h)throw new Oe;i=!0}else{if(!h)throw new Oe;l=!0}else if(u===0){if(d){if(!h)throw new Oe;r<a?(i=!0,c=!0):(o=!0,l=!0)}else if(h)throw new Oe}else throw new Oe;if(i){if(o)throw new Oe;t.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(o&&t.decrement(this.getOddCounts(),this.getOddRoundingErrors()),l){if(c)throw new Oe;t.increment(this.getEvenCounts(),this.getOddRoundingErrors())}c&&t.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())},t.SYMBOL_WIDEST=[7,5,4,3,1],t.EVEN_TOTAL_SUBSET=[4,20,52,104,204],t.GSUM=[0,348,1388,2948,3988],t.FINDER_PATTERNS=[Int32Array.from([1,8,4,1]),Int32Array.from([3,6,4,1]),Int32Array.from([3,4,6,1]),Int32Array.from([3,2,8,1]),Int32Array.from([2,6,5,1]),Int32Array.from([2,2,9,1])],t.WEIGHTS=[[1,3,9,27,81,32,96,77],[20,60,180,118,143,7,21,63],[189,145,13,39,117,140,209,205],[193,157,49,147,19,57,171,91],[62,186,136,197,169,85,44,132],[185,133,188,142,4,12,36,108],[113,128,173,97,80,29,87,50],[150,28,84,41,123,158,52,156],[46,138,203,187,139,206,196,166],[76,17,51,153,37,111,122,155],[43,129,176,106,107,110,119,146],[16,48,144,10,30,90,59,177],[109,116,137,200,178,112,125,164],[70,210,208,202,184,130,179,115],[134,191,151,31,93,68,204,190],[148,22,66,198,172,94,71,2],[6,18,54,162,64,192,154,40],[120,149,25,75,14,42,126,167],[79,26,78,23,69,207,199,175],[103,98,83,38,114,131,182,124],[161,61,183,127,170,88,53,159],[55,165,73,8,24,72,5,15],[45,135,194,160,58,174,100,89]],t.FINDER_PAT_A=0,t.FINDER_PAT_B=1,t.FINDER_PAT_C=2,t.FINDER_PAT_D=3,t.FINDER_PAT_E=4,t.FINDER_PAT_F=5,t.FINDER_PATTERN_SEQUENCES=[[t.FINDER_PAT_A,t.FINDER_PAT_A],[t.FINDER_PAT_A,t.FINDER_PAT_B,t.FINDER_PAT_B],[t.FINDER_PAT_A,t.FINDER_PAT_C,t.FINDER_PAT_B,t.FINDER_PAT_D],[t.FINDER_PAT_A,t.FINDER_PAT_E,t.FINDER_PAT_B,t.FINDER_PAT_D,t.FINDER_PAT_C],[t.FINDER_PAT_A,t.FINDER_PAT_E,t.FINDER_PAT_B,t.FINDER_PAT_D,t.FINDER_PAT_D,t.FINDER_PAT_F],[t.FINDER_PAT_A,t.FINDER_PAT_E,t.FINDER_PAT_B,t.FINDER_PAT_D,t.FINDER_PAT_E,t.FINDER_PAT_F,t.FINDER_PAT_F],[t.FINDER_PAT_A,t.FINDER_PAT_A,t.FINDER_PAT_B,t.FINDER_PAT_B,t.FINDER_PAT_C,t.FINDER_PAT_C,t.FINDER_PAT_D,t.FINDER_PAT_D],[t.FINDER_PAT_A,t.FINDER_PAT_A,t.FINDER_PAT_B,t.FINDER_PAT_B,t.FINDER_PAT_C,t.FINDER_PAT_C,t.FINDER_PAT_D,t.FINDER_PAT_E,t.FINDER_PAT_E],[t.FINDER_PAT_A,t.FINDER_PAT_A,t.FINDER_PAT_B,t.FINDER_PAT_B,t.FINDER_PAT_C,t.FINDER_PAT_C,t.FINDER_PAT_D,t.FINDER_PAT_E,t.FINDER_PAT_F,t.FINDER_PAT_F],[t.FINDER_PAT_A,t.FINDER_PAT_A,t.FINDER_PAT_B,t.FINDER_PAT_B,t.FINDER_PAT_C,t.FINDER_PAT_D,t.FINDER_PAT_D,t.FINDER_PAT_E,t.FINDER_PAT_E,t.FINDER_PAT_F,t.FINDER_PAT_F]],t.MAX_PAIRS=11,t.FINDER_PATTERN_MODULES=15,t.DATA_CHARACTER_MODULES=17,t.MAX_FINDER_PATTERN_DISTANCE_VARIANCE=.1,t})(Gu),TJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
926t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),OJe=(function(e){TJe(t,e);function t(n,r,a){var i=e.call(this,n,r)||this;return i.count=0,i.finderPattern=a,i}return t.prototype.getFinderPattern=function(){return this.finderPattern},t.prototype.getCount=function(){return this.count},t.prototype.incrementCount=function(){this.count++},t})(Fv),IJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),PJe=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,i=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},RJe=function(e,t,n){if(n||arguments.length===2)for(var r=0,a=t.length,i;r<a;r++)(i||!(r in t))&&(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))},Mj=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},g8=(function(e){IJe(t,e);function t(){var n=e.apply(this,RJe([],PJe(arguments),!1))||this;return n.possibleLeftPairs=[],n.possibleRightPairs=[],n}return t.prototype.decodeRow=function(n,r,a){var i,o,l,c,u=this.decodePair(r,!1,n,a);t.addOrTally(this.possibleLeftPairs,u),r.reverse();var d=this.decodePair(r,!0,n,a);t.addOrTally(this.possibleRightPairs,d),r.reverse();try{for(var h=Mj(this.possibleLeftPairs),f=h.next();!f.done;f=h.next()){var m=f.value;if(m.getCount()>1)try{for(var x=(l=void 0,Mj(this.possibleRightPairs)),g=x.next();!g.done;g=x.next()){var y=g.value;if(y.getCount()>1&&t.checkChecksum(m,y))return t.constructResult(m,y)}}catch(b){l={error:b}}finally{try{g&&!g.done&&(c=x.return)&&c.call(x)}finally{if(l)throw l.error}}}}catch(b){i={error:b}}finally{try{f&&!f.done&&(o=h.return)&&o.call(h)}finally{if(i)throw i.error}}throw new Oe},t.addOrTally=function(n,r){var a,i;if(r!==null){var o=!1;try{for(var l=Mj(n),c=l.next();!c.done;c=l.next()){var u=c.value;if(u.getValue()===r.getValue()){u.incrementCount(),o=!0;break}}}catch(d){a={error:d}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(a)throw a.error}}o||n.push(r)}},t.prototype.reset=function(){this.possibleLeftPairs.length=0,this.possibleRightPairs.length=0},t.constructResult=function(n,r){for(var a=4537077*n.getValue()+r.getValue(),i=String(a),o=new Kt,l=13-i.length;l>0;l--)o.append("0");o.append(i);for(var c=0,l=0;l<13;l++){var u=o.charAt(l).charCodeAt(0)-48;c+=(l&1)===0?3*u:u}c=10-c%10,c===10&&(c=0),o.append(c.toString());var d=n.getFinderPattern().getResultPoints(),h=r.getFinderPattern().getResultPoints();return new Ts(o.toString(),null,0,[d[0],d[1],h[0],h[1]],wt.RSS_14,new Date().getTime())},t.checkChecksum=function(n,r){var a=(n.getChecksumPortion()+16*r.getChecksumPortion())%79,i=9*n.getFinderPattern().getValue()+r.getFinderPattern().getValue();return i>72&&i--,i>8&&i--,a===i},t.prototype.decodePair=function(n,r,a,i){try{var o=this.findFinderPattern(n,r),l=this.parseFoundFinderPattern(n,a,r,o),c=i==null?null:i.get(On.NEED_RESULT_POINT_CALLBACK);if(c!=null){var u=(o[0]+o[1]-1)/2;r&&(u=n.getSize()-1-u),c.foundPossibleResultPoint(new mt(u,a))}var d=this.decodeDataCharacter(n,l,!0),h=this.decodeDataCharacter(n,l,!1);return new OJe(1597*d.getValue()+h.getValue(),d.getChecksumPortion()+4*h.getChecksumPortion(),l)}catch(f){if(f instanceof Oe)return null;throw f}},t.prototype.decodeDataCharacter=function(n,r,a){for(var i=this.getDataCharacterCounters(),o=0;o<i.length;o++)i[o]=0;if(a)ls.recordPatternInReverse(n,r.getStartEnd()[0],i);else{ls.recordPattern(n,r.getStartEnd()[1],i);for(var l=0,c=i.length-1;l<c;l++,c--){var u=i[l];i[l]=i[c],i[c]=u}}
926for(var d=a?16:15,h=mn.sum(new Int32Array(i))/d,f=this.getOddCounts(),m=this.getEvenCounts(),x=this.getOddRoundingErrors(),g=this.getEvenRoundingErrors(),l=0;l<i.length;l++){var y=i[l]/h,b=Math.floor(y+.5);b<1?b=1:b>8&&(b=8);var v=Math.floor(l/2);(l&1)===0?(f[v]=b,x[v]=y-b):(m[v]=b,g[v]=y-b)}this.adjustOddEvenCounts(a,d);for(var w=0,_=0,l=f.length-1;l>=0;l--)_*=9,_+=f[l],w+=f[l];for(var k=0,j=0,l=m.length-1;l>=0;l--)k*=9,k+=m[l],j+=m[l];var N=_+3*k;if(a){if((w&1)!==0||w>12||w<4)throw new Oe;var E=(12-w)/2,A=t.OUTSIDE_ODD_WIDEST[E],C=9-A,T=Ah.getRSSvalue(f,A,!1),S=Ah.getRSSvalue(m,C,!0),O=t.OUTSIDE_EVEN_TOTAL_SUBSET[E],R=t.OUTSIDE_GSUM[E];return new Fv(T*O+S+R,N)}else{if((j&1)!==0||j>10||j<4)throw new Oe;var E=(10-j)/2,A=t.INSIDE_ODD_WIDEST[E],C=9-A,T=Ah.getRSSvalue(f,A,!0),S=Ah.getRSSvalue(m,C,!1),I=t.INSIDE_ODD_TOTAL_SUBSET[E],R=t.INSIDE_GSUM[E];return new Fv(S*I+T+R,N)}},t.prototype.findFinderPattern=function(n,r){var a=this.getDecodeFinderCounters();a[0]=0,a[1]=0,a[2]=0,a[3]=0;for(var i=n.getSize(),o=!1,l=0;l<i&&(o=!n.get(l),r!==o);)l++;for(var c=0,u=l,d=l;d<i;d++)if(n.get(d)!==o)a[c]++;else{if(c===3){if(Gu.isFinderPattern(a))return[u,d];u+=a[0]+a[1],a[0]=a[2],a[1]=a[3],a[2]=0,a[3]=0,c--}else c++;a[c]=1,o=!o}throw new Oe},t.prototype.parseFoundFinderPattern=function(n,r,a,i){for(var o=n.get(i[0]),l=i[0]-1;l>=0&&o!==n.get(l);)l--;l++;var c=i[0]-l,u=this.getDecodeFinderCounters(),d=new Int32Array(u.length);Fn.arraycopy(u,0,d,1,u.length-1),d[0]=c;var h=this.parseFinderValue(d,t.FINDER_PATTERNS),f=l,m=i[1];return a&&(f=n.getSize()-1-f,m=n.getSize()-1-m),new GG(h,[l,i[1]],f,m,r)},t.prototype.adjustOddEvenCounts=function(n,r){var a=mn.sum(new Int32Array(this.getOddCounts())),i=mn.sum(new Int32Array(this.getEvenCounts())),o=!1,l=!1,c=!1,u=!1;n?(a>12?l=!0:a<4&&(o=!0),i>12?u=!0:i<4&&(c=!0)):(a>11?l=!0:a<5&&(o=!0),i>10?u=!0:i<4&&(c=!0));var d=a+i-r,h=(a&1)===(n?1:0),f=(i&1)===1;if(d===1)if(h){if(f)throw new Oe;l=!0}else{if(!f)throw new Oe;u=!0}else if(d===-1)if(h){if(f)throw new Oe;o=!0}else{if(!f)throw new Oe;c=!0}else if(d===0){if(h){if(!f)throw new Oe;a<i?(o=!0,u=!0):(l=!0,c=!0)}else if(f)throw new Oe}else throw new Oe;if(o){if(l)throw new Oe;Gu.increment(this.getOddCounts(),this.getOddRoundingErrors())}if(l&&Gu.decrement(this.getOddCounts(),this.getOddRoundingErrors()),c){if(u)throw new Oe;Gu.increment(this.getEvenCounts(),this.getOddRoundingErrors())}u&&Gu.decrement(this.getEvenCounts(),this.getEvenRoundingErrors())},t.OUTSIDE_EVEN_TOTAL_SUBSET=[1,10,34,70,126],t.INSIDE_ODD_TOTAL_SUBSET=[4,20,48,81],t.OUTSIDE_GSUM=[0,161,961,2015,2715],t.INSIDE_GSUM=[0,336,1036,1516],t.OUTSIDE_ODD_WIDEST=[8,6,4,3,1],t.INSIDE_ODD_WIDEST=[2,4,6,8],t.FINDER_PATTERNS=[Int32Array.from([3,8,2,1]),Int32Array.from([3,5,5,1]),Int32Array.from([3,3,7,1]),Int32Array.from([3,1,9,1]),Int32Array.from([2,7,4,1]),Int32Array.from([2,5,6,1]),Int32Array.from([2,3,8,1]),Int32Array.from([1,5,7,1]),Int32Array.from([1,3,9,1])],t})(Gu),DJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Wm=(function(e){DJe(t,e);function t(n){var r=e.call(this)||this;r.readers=[];var a=n?n.get(On.POSSIBLE_FORMATS):null,i=n&&n.get(On.ASSUME_CODE_39_CHECK_DIGIT)!==void 0,o=n&&n.get(On.ENABLE_CODE_39_EXTENDED_MODE)!==void 0;return a&&((a.includes(wt.EAN_13)||a.includes(wt.UPC_A)||a.includes(wt.EAN_8)||a.includes(wt.UPC_E))&&r.readers.push(new Dj(n)),a.includes(wt.CODE_39)&&r.readers.push(new a8(i,o)),a.includes(wt.CODE_93)&&r.readers.push(new i8),a.includes(wt.CODE_128)&&r.readers.push(new s8),a.includes(wt.ITF)&&r.readers.push(new o8),a.includes(wt.CODABAR)&&r.readers.push(new QXe),a.includes(wt.RSS_14)&&r.readers.push(new g8),a.includes(wt.RSS_EXPANDED)&&(console.warn("RSS Expanded reader IS NOT ready for production yet! use at your own risk."),r.readers.push(new x8))),r.readers.length===0&&(r.readers.push(new Dj(n)),r.readers.push(new a8),r.readers.push(new i8),r.readers.push(new Dj(n)),r.readers.push(new s8),r.readers.push(new o8),r.readers.push(new g8),r.readers.push(new x8)),r}return t.prototype.decodeRow=function(n,r,a){for(var i=0;i<this.readers.length;i++)try{return this.readers[i].decodeRow(n,r,a)}catch{}throw new Oe}
926,t.prototype.reset=function(){this.readers.forEach(function(n){return n.reset()})},t})(ls),MJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();(function(e){MJe(t,e);function t(n,r){return n===void 0&&(n=500),e.call(this,new Wm(r),n,r)||this}return t})(Vf);var y8=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},Sn=(function(){function e(t,n,r){this.ecCodewords=t,this.ecBlocks=[n],r&&this.ecBlocks.push(r)}return e.prototype.getECCodewords=function(){return this.ecCodewords},e.prototype.getECBlocks=function(){return this.ecBlocks},e})(),bn=(function(){function e(t,n){this.count=t,this.dataCodewords=n}return e.prototype.getCount=function(){return this.count},e.prototype.getDataCodewords=function(){return this.dataCodewords},e})(),$Je=(function(){function e(t,n,r,a,i,o){var l,c;this.versionNumber=t,this.symbolSizeRows=n,this.symbolSizeColumns=r,this.dataRegionSizeRows=a,this.dataRegionSizeColumns=i,this.ecBlocks=o;var u=0,d=o.getECCodewords(),h=o.getECBlocks();try{for(var f=y8(h),m=f.next();!m.done;m=f.next()){var x=m.value;u+=x.getCount()*(x.getDataCodewords()+d)}}catch(g){l={error:g}}finally{try{m&&!m.done&&(c=f.return)&&c.call(f)}finally{if(l)throw l.error}}this.totalCodewords=u}return e.prototype.getVersionNumber=function(){return this.versionNumber},e.prototype.getSymbolSizeRows=function(){return this.symbolSizeRows},e.prototype.getSymbolSizeColumns=function(){return this.symbolSizeColumns},e.prototype.getDataRegionSizeRows=function(){return this.dataRegionSizeRows},e.prototype.getDataRegionSizeColumns=function(){return this.dataRegionSizeColumns},e.prototype.getTotalCodewords=function(){return this.totalCodewords},e.prototype.getECBlocks=function(){return this.ecBlocks},e.getVersionForDimensions=function(t,n){var r,a;if((t&1)!==0||(n&1)!==0)throw new We;try{for(var i=y8(e.VERSIONS),o=i.next();!o.done;o=i.next()){var l=o.value;if(l.symbolSizeRows===t&&l.symbolSizeColumns===n)return l}}catch(c){r={error:c}}finally{try{o&&!o.done&&(a=i.return)&&a.call(i)}finally{if(r)throw r.error}}throw new We},e.prototype.toString=function(){return""+this.versionNumber},e.buildVersions=function(){return[new e(1,10,10,8,8,new Sn(5,new bn(1,3))),new e(2,12,12,10,10,new Sn(7,new bn(1,5))),new e(3,14,14,12,12,new Sn(10,new bn(1,8))),new e(4,16,16,14,14,new Sn(12,new bn(1,12))),new e(5,18,18,16,16,new Sn(14,new bn(1,18))),new e(6,20,20,18,18,new Sn(18,new bn(1,22))),new e(7,22,22,20,20,new Sn(20,new bn(1,30))),new e(8,24,24,22,22,new Sn(24,new bn(1,36))),new e(9,26,26,24,24,new Sn(28,new bn(1,44))),new e(10,32,32,14,14,new Sn(36,new bn(1,62))),new e(11,36,36,16,16,new Sn(42,new bn(1,86))),new e(12,40,40,18,18,new Sn(48,new bn(1,114))),new e(13,44,44,20,20,new Sn(56,new bn(1,144))),new e(14,48,48,22,22,new Sn(68,new bn(1,174))),new e(15,52,52,24,24,new Sn(42,new bn(2,102))),new e(16,64,64,14,14,new Sn(56,new bn(2,140))),new e(17,72,72,16,16,new Sn(36,new bn(4,92))),new e(18,80,80,18,18,new Sn(48,new bn(4,114))),new e(19,88,88,20,20,new Sn(56,new bn(4,144))),new e(20,96,96,22,22,new Sn(68,new bn(4,174))),new e(21,104,104,24,24,new Sn(56,new bn(6,136))),new e(22,120,120,18,18,new Sn(68,new bn(6,175))),new e(23,132,132,20,20,new Sn(62,new bn(8,163))),new e(24,144,144,22,22,new Sn(62,new bn(8,156),new bn(2,155))),new e(25,8,18,6,16,new Sn(7,new bn(1,5))),new e(26,8,32,6,14,new Sn(11,new bn(1,10))),new e(27,12,26,10,24,new Sn(14,new bn(1,16))),new e(28,12,36,10,16,new Sn(18,new bn(1,22))),new e(29,16,36,14,16,new Sn(24,new bn(1,32))),new e(30,16,48,14,22,new Sn(28,
926new bn(1,49)))]},e.VERSIONS=e.buildVersions(),e})(),LJe=(function(){function e(t){var n=t.getHeight();if(n<8||n>144||(n&1)!==0)throw new We;this.version=e.readVersion(t),this.mappingBitMatrix=this.extractDataRegion(t),this.readMappingMatrix=new _i(this.mappingBitMatrix.getWidth(),this.mappingBitMatrix.getHeight())}return e.prototype.getVersion=function(){return this.version},e.readVersion=function(t){var n=t.getHeight(),r=t.getWidth();return $Je.getVersionForDimensions(n,r)},e.prototype.readCodewords=function(){var t=new Int8Array(this.version.getTotalCodewords()),n=0,r=4,a=0,i=this.mappingBitMatrix.getHeight(),o=this.mappingBitMatrix.getWidth(),l=!1,c=!1,u=!1,d=!1;do if(r===i&&a===0&&!l)t[n++]=this.readCorner1(i,o)&255,r-=2,a+=2,l=!0;else if(r===i-2&&a===0&&(o&3)!==0&&!c)t[n++]=this.readCorner2(i,o)&255,r-=2,a+=2,c=!0;else if(r===i+4&&a===2&&(o&7)===0&&!u)t[n++]=this.readCorner3(i,o)&255,r-=2,a+=2,u=!0;else if(r===i-2&&a===0&&(o&7)===4&&!d)t[n++]=this.readCorner4(i,o)&255,r-=2,a+=2,d=!0;else{do r<i&&a>=0&&!this.readMappingMatrix.get(a,r)&&(t[n++]=this.readUtah(r,a,i,o)&255),r-=2,a+=2;while(r>=0&&a<o);r+=1,a+=3;do r>=0&&a<o&&!this.readMappingMatrix.get(a,r)&&(t[n++]=this.readUtah(r,a,i,o)&255),r+=2,a-=2;while(r<i&&a>=0);r+=3,a+=1}while(r<i||a<o);if(n!==this.version.getTotalCodewords())throw new We;return t},e.prototype.readModule=function(t,n,r,a){return t<0&&(t+=r,n+=4-(r+4&7)),n<0&&(n+=a,t+=4-(a+4&7)),this.readMappingMatrix.set(n,t),this.mappingBitMatrix.get(n,t)},e.prototype.readUtah=function(t,n,r,a){var i=0;return this.readModule(t-2,n-2,r,a)&&(i|=1),i<<=1,this.readModule(t-2,n-1,r,a)&&(i|=1),i<<=1,this.readModule(t-1,n-2,r,a)&&(i|=1),i<<=1,this.readModule(t-1,n-1,r,a)&&(i|=1),i<<=1,this.readModule(t-1,n,r,a)&&(i|=1),i<<=1,this.readModule(t,n-2,r,a)&&(i|=1),i<<=1,this.readModule(t,n-1,r,a)&&(i|=1),i<<=1,this.readModule(t,n,r,a)&&(i|=1),i},e.prototype.readCorner1=function(t,n){var r=0;return this.readModule(t-1,0,t,n)&&(r|=1),r<<=1,this.readModule(t-1,1,t,n)&&(r|=1),r<<=1,this.readModule(t-1,2,t,n)&&(r|=1),r<<=1,this.readModule(0,n-2,t,n)&&(r|=1),r<<=1,this.readModule(0,n-1,t,n)&&(r|=1),r<<=1,this.readModule(1,n-1,t,n)&&(r|=1),r<<=1,this.readModule(2,n-1,t,n)&&(r|=1),r<<=1,this.readModule(3,n-1,t,n)&&(r|=1),r},e.prototype.readCorner2=function(t,n){var r=0;return this.readModule(t-3,0,t,n)&&(r|=1),r<<=1,this.readModule(t-2,0,t,n)&&(r|=1),r<<=1,this.readModule(t-1,0,t,n)&&(r|=1),r<<=1,this.readModule(0,n-4,t,n)&&(r|=1),r<<=1,this.readModule(0,n-3,t,n)&&(r|=1),r<<=1,this.readModule(0,n-2,t,n)&&(r|=1),r<<=1,this.readModule(0,n-1,t,n)&&(r|=1),r<<=1,this.readModule(1,n-1,t,n)&&(r|=1),r},e.prototype.readCorner3=function(t,n){var r=0;return this.readModule(t-1,0,t,n)&&(r|=1),r<<=1,this.readModule(t-1,n-1,t,n)&&(r|=1),r<<=1,this.readModule(0,n-3,t,n)&&(r|=1),r<<=1,this.readModule(0,n-2,t,n)&&(r|=1),r<<=1,this.readModule(0,n-1,t,n)&&(r|=1),r<<=1,this.readModule(1,n-3,t,n)&&(r|=1),r<<=1,this.readModule(1,n-2,t,n)&&(r|=1),r<<=1,this.readModule(1,n-1,t,n)&&(r|=1),r},e.prototype.readCorner4=function(t,n){var r=0;return this.readModule(t-3,0,t,n)&&(r|=1),r<<=1,this.readModule(t-2,0,t,n)&&(r|=1),r<<=1,this.readModule(t-1,0,t,n)&&(r|=1),r<<=1,this.readModule(0,n-2,t,n)&&(r|=1),r<<=1,this.readModule(0,n-1,t,n)&&(r|=1),r<<=1,this.readModule(1,n-1,t,n)&&(r|=1),r<<=1,this.readModule(2,n-1,t,n)&&(r|=1),r<<=1,this.readModule(3,n-1,t,n)&&(r|=1),r},e.prototype.extractDataRegion=function(t){var n=this.version.getSymbolSizeRows(),r=this.version.getSymbolSizeColumns();if(t.getHeight()!==n)throw new Ct("Dimension of bitMatrix must match the version size");for(var a=this.version.getDataRegionSizeRows(),i=this.version.getDataRegionSizeColumns(),o=n/a|0,l=r/i|0,c=o*a,u=l*i,d=new _i(u,c),h=0;h<o;++h)for(var f=h*a,m=0;m<l;++m)for(var x=m*i,g=0;g<a;++g)for(var y=h*(a+2)+1+g,b=f+g,v=0;v<i;++v){var w=m*(i+2)+1+v;if(t.get(w,y)){var _=x+v;d.set(_,b)}}return d},e})(),b8=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},FJe=(function(){function e(t,n){this.numDataCodewords=t,this.co
926dewords=n}return e.getDataBlocks=function(t,n){var r,a,i,o,l=n.getECBlocks(),c=0,u=l.getECBlocks();try{for(var d=b8(u),h=d.next();!h.done;h=d.next()){var f=h.value;c+=f.getCount()}}catch(R){r={error:R}}finally{try{h&&!h.done&&(a=d.return)&&a.call(d)}finally{if(r)throw r.error}}var m=new Array(c),x=0;try{for(var g=b8(u),y=g.next();!y.done;y=g.next())for(var f=y.value,b=0;b<f.getCount();b++){var v=f.getDataCodewords(),w=l.getECCodewords()+v;m[x++]=new e(v,new Uint8Array(w))}}catch(R){i={error:R}}finally{try{y&&!y.done&&(o=g.return)&&o.call(g)}finally{if(i)throw i.error}}for(var _=m[0].codewords.length,k=_-l.getECCodewords(),j=k-1,N=0,b=0;b<j;b++)for(var E=0;E<x;E++)m[E].codewords[b]=t[N++];for(var A=n.getVersionNumber()===24,C=A?8:x,E=0;E<C;E++)m[E].codewords[k-1]=t[N++];for(var T=m[0].codewords.length,b=k;b<T;b++)for(var E=0;E<x;E++){var S=A?(E+8)%x:E,O=A&&S>7?b-1:b;m[S].codewords[O]=t[N++]}if(N!==t.length)throw new Ct;return m},e.prototype.getNumDataCodewords=function(){return this.numDataCodewords},e.prototype.getCodewords=function(){return this.codewords},e})(),oT=(function(){function e(t){this.bytes=t,this.byteOffset=0,this.bitOffset=0}return e.prototype.getBitOffset=function(){return this.bitOffset},e.prototype.getByteOffset=function(){return this.byteOffset},e.prototype.readBits=function(t){if(t<1||t>32||t>this.available())throw new Ct(""+t);var n=0,r=this.bitOffset,a=this.byteOffset,i=this.bytes;if(r>0){var o=8-r,l=t<o?t:o,c=o-l,u=255>>8-l<<c;n=(i[a]&u)>>c,t-=l,r+=l,r===8&&(r=0,a++)}if(t>0){for(;t>=8;)n=n<<8|i[a]&255,a++,t-=8;if(t>0){var c=8-t,u=255>>c<<c;n=n<<t|(i[a]&u)>>c,r+=t}}return this.bitOffset=r,this.byteOffset=a,n},e.prototype.available=function(){return 8*(this.bytes.length-this.byteOffset)-this.bitOffset},e})(),ts;(function(e){e[e.PAD_ENCODE=0]="PAD_ENCODE",e[e.ASCII_ENCODE=1]="ASCII_ENCODE",e[e.C40_ENCODE=2]="C40_ENCODE",e[e.TEXT_ENCODE=3]="TEXT_ENCODE",e[e.ANSIX12_ENCODE=4]="ANSIX12_ENCODE",e[e.EDIFACT_ENCODE=5]="EDIFACT_ENCODE",e[e.BASE256_ENCODE=6]="BASE256_ENCODE"})(ts||(ts={}));var BJe=(function(){function e(){}return e.decode=function(t){var n=new oT(t),r=new Kt,a=new Kt,i=new Array,o=ts.ASCII_ENCODE;do if(o===ts.ASCII_ENCODE)o=this.decodeAsciiSegment(n,r,a);else{switch(o){case ts.C40_ENCODE:this.decodeC40Segment(n,r);break;case ts.TEXT_ENCODE:this.decodeTextSegment(n,r);break;case ts.ANSIX12_ENCODE:this.decodeAnsiX12Segment(n,r);break;case ts.EDIFACT_ENCODE:this.decodeEdifactSegment(n,r);break;case ts.BASE256_ENCODE:this.decodeBase256Segment(n,r,i);break;default:throw new We}o=ts.ASCII_ENCODE}while(o!==ts.PAD_ENCODE&&n.available()>0);return a.length()>0&&r.append(a.toString()),new qf(t,r.toString(),i.length===0?null:i,null)},e.decodeAsciiSegment=function(t,n,r){var a=!1;do{var i=t.readBits(8);if(i===0)throw new We;if(i<=128)return a&&(i+=128),n.append(String.fromCharCode(i-1)),ts.ASCII_ENCODE;if(i===129)return ts.PAD_ENCODE;if(i<=229){var o=i-130;o<10&&n.append("0"),n.append(""+o)}else switch(i){case 230:return ts.C40_ENCODE;case 231:return ts.BASE256_ENCODE;case 232:n.append("�");break;case 233:case 234:break;case 235:a=!0;break;case 236:n.append("[)>�05�"),r.insert(0,"��");break;case 237:n.append("[)>�06�"),r.insert(0,"��");break;case 238:return ts.ANSIX12_ENCODE;case 239:return ts.TEXT_ENCODE;case 240:return ts.EDIFACT_ENCODE;case 241:break;default:if(i!==254||t.available()!==0)throw new We;break}}while(t.available()>0);return ts.ASCII_ENCODE},e.decodeC40Segment=function(t,n){var r=!1,a=[],i=0;do{if(t.available()===8)return;var o=t.readBits(8);if(o===254)return;this.parseTwoBytes(o,t.readBits(8),a);for(var l=0;l<3;l++){var c=a[l];switch(i){case 0:if(c<3)i=c+1;else if(c<this.C40_BASIC_SET_CHARS.length){var u=this.C40_BASIC_SET_CHARS[c];r?(n.append(String.fromCharCode(u.charCodeAt(0)+128)),r=!1):n.append(u)}else throw new We;break;case 1:r?(n.append(String.fromCharCode(c+128)),r=!1):n.append(String.fromCharCode(c)),i=0;break;case 2:if(c<this.C40_SHIFT2_SET_CHARS.length){var u=this.C40_SHIFT2_SET_CHARS[c];r?(n.append(String.fromCharCode(u.charCodeAt(0)+128)),r=!1):n.append(u)}else switch(c){case 27:n.append("�");break;case 30:r=!0;break;default:throw new We}i=0;break;case 3:r?(n.append(String.fromCharCode(c+224)),r=!1):n.append(String.fromCharCode(c+96)),i=0;break;default:throw new We}}}while(t.available()>0)},e.decodeTextSegment=function(t,n){var r=!1,a=[],i=0;do{if(t.available()===8)return;var o=t.readBits(8);if(o===254)return;this.parseTwoBytes(o,t.readBits(8),a);for(var l=0;l<3;l++){var c=a[l];switch(i){case 0:if(c<3)i=c+1;else if(c<this.TEXT_BASIC_SET_CHARS.length){var u=this.TEXT_BASIC_SET_CHARS[c];r?(n.append(String.fromCharCode(u.charCodeAt(0)+128)),r=!1):n.append(u)}else throw new We;break;case 1:r?(n.append(String.fromCharCode(c+128)),r=!1):n.append(String.fromCharCode(c)),i=0;break;case 2:if(c<this.TEXT_SHIFT2_SET_CHARS.length){var u=this.TEXT_SHIFT2_SET_CHARS[c];r?(n.append(String.fromCharCode(u.charCodeAt(0)+128)),r=!1):n.append(u)}else switch(c){case 27:n.append("�");break;case 30:r=!0;break;default:throw new We}i=0;break;case 3:if(c<this.TEXT_SHIFT3_SET_CHARS.length){var u=this.TEXT_SHIFT3_SET_CHARS[c];r?(n.append(String.fromCharCode(u.charCodeAt(0)+128)),r=!1):n.append(u),i=0}else throw new We;break;default:throw new We}}}while(t.available()>0)},e.decodeAnsiX12Segment=function(t,n){var r=[];do{if(t.available()===8)return;var a=t.readBits(8);if(a===254)return;this.parseTwoBytes(a,t.readBits(8),r);for(var i=0;i<3;i++){var o=r[i];switch(o){case 0:n.append("\r");break;case 1:n.append("*");break;case 2:n.append(">");break;case 3:n.append(" ");break;default:if(o<14)n.append(String.fromCharCode(o+44));else if(o<40)n.append(String.fromCharCode(o+51));else throw new We;break}}}while(t.available()>0)},e.parseTwoBytes=function(t,n,r){var a=(t<<8)+n-1,i=Math.floor(a/1600);r[0]=i,a-=i*1600,i=Math.floor(a/40),r[1]=i,r[2]=a-i*40},e.decodeEdifactSegment=function(t,n){do{if(t.available()<=16)return;for(var r=0;r<4;r++){var a=t.readBits(6);if(a===31){var i=8-t.getBitOffset();i!==8&&t.readBits(i);return}(a&32)===0&&(a|=64),n.append(String.fromCharCode(a))}}while(t.available()>0)},e.decodeBase256Segment=function(t,n,r){var a=1+t.getByteOffset(),i=this.unrandomize255State(t.readBits(8),a++),o;if(i===0?o=t.available()/8|0:i<250?o=i:o=250*(i-249)+this.unrandomize255State(t.readBits(8),a++),o<0)throw new We;for(var l=new Uint8Array(o),c=0;c<o;c++){if(t.available()<8)throw new We;l[c]=this.unrandomize255State(t.readBits(8),a++)}r.push(l);try{n.append(ri.decode(l,tn.ISO88591))}catch(u){throw new Gf("Platform does not support required encoding: "+u.message)}},e.unrandomize255State=function(t,n){var r=149*n%255+1,a=t-r;return a>=0?a:a+256},e.C40_BASIC_SET_CHARS=["*","*","*"," ","0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"],e.C40_SHIFT2_SET_CHARS=["!",'"',"#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","@","[","\\","]","^","_"],e.TEXT_BASIC_SET_CHARS=["*","*","*"," ","0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"],e.TEXT_SHIFT2_SET_CHARS=e.C40_SHIFT2_SET_CHARS,e.TEXT_SHIFT3_SET_CHARS=["`","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","{","|","}","~","�"],e})(),UJe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);
926if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},zJe=(function(){function e(){this.rsDecoder=new Yf(ra.DATA_MATRIX_FIELD_256)}return e.prototype.decode=function(t){var n,r,a=new LJe(t),i=a.getVersion(),o=a.readCodewords(),l=FJe.getDataBlocks(o,i),c=0;try{for(var u=UJe(l),d=u.next();!d.done;d=u.next()){var h=d.value;c+=h.getNumDataCodewords()}}catch(w){n={error:w}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}for(var f=new Uint8Array(c),m=l.length,x=0;x<m;x++){var g=l[x],y=g.getCodewords(),b=g.getNumDataCodewords();this.correctErrors(y,b);for(var v=0;v<b;v++)f[v*m+x]=y[v]}return BJe.decode(f)},e.prototype.correctErrors=function(t,n){var r=new Int32Array(t);try{this.rsDecoder.decode(r,t.length-n)}catch{throw new Yr}for(var a=0;a<n;a++)t[a]=r[a]},e})(),WJe=(function(){function e(t){this.image=t,this.rectangleDetector=new i2(this.image)}return e.prototype.detect=function(){var t=this.rectangleDetector.detect(),n=this.detectSolid1(t);if(n=this.detectSolid2(n),n[3]=this.correctTopRight(n),!n[3])throw new Oe;n=this.shiftToModuleCenter(n);var r=n[0],a=n[1],i=n[2],o=n[3],l=this.transitionsBetween(r,o)+1,c=this.transitionsBetween(i,o)+1;(l&1)===1&&(l+=1),(c&1)===1&&(c+=1),4*l<7*c&&4*c<7*l&&(l=c=Math.max(l,c));var u=e.sampleGrid(this.image,r,a,i,o,l,c);return new Bw(u,[r,a,i,o])},e.shiftPoint=function(t,n,r){var a=(n.getX()-t.getX())/(r+1),i=(n.getY()-t.getY())/(r+1);return new mt(t.getX()+a,t.getY()+i)},e.moveAway=function(t,n,r){var a=t.getX(),i=t.getY();return a<n?a-=1:a+=1,i<r?i-=1:i+=1,new mt(a,i)},e.prototype.detectSolid1=function(t){var n=t[0],r=t[1],a=t[3],i=t[2],o=this.transitionsBetween(n,r),l=this.transitionsBetween(r,a),c=this.transitionsBetween(a,i),u=this.transitionsBetween(i,n),d=o,h=[i,n,r,a];return d>l&&(d=l,h[0]=n,h[1]=r,h[2]=a,h[3]=i),d>c&&(d=c,h[0]=r,h[1]=a,h[2]=i,h[3]=n),d>u&&(h[0]=a,h[1]=i,h[2]=n,h[3]=r),h},e.prototype.detectSolid2=function(t){var n=t[0],r=t[1],a=t[2],i=t[3],o=this.transitionsBetween(n,i),l=e.shiftPoint(r,a,(o+1)*4),c=e.shiftPoint(a,r,(o+1)*4),u=this.transitionsBetween(l,n),d=this.transitionsBetween(c,i);return u<d?(t[0]=n,t[1]=r,t[2]=a,t[3]=i):(t[0]=r,t[1]=a,t[2]=i,t[3]=n),t},e.prototype.correctTopRight=function(t){var n=t[0],r=t[1],a=t[2],i=t[3],o=this.transitionsBetween(n,i),l=this.transitionsBetween(r,i),c=e.shiftPoint(n,r,(l+1)*4),u=e.shiftPoint(a,r,(o+1)*4);o=this.transitionsBetween(c,i),l=this.transitionsBetween(u,i);var d=new mt(i.getX()+(a.getX()-r.getX())/(o+1),i.getY()+(a.getY()-r.getY())/(o+1)),h=new mt(i.getX()+(n.getX()-r.getX())/(l+1),i.getY()+(n.getY()-r.getY())/(l+1));if(!this.isValid(d))return this.isValid(h)?h:null;if(!this.isValid(h))return d;var f=this.transitionsBetween(c,d)+this.transitionsBetween(u,d),m=this.transitionsBetween(c,h)+this.transitionsBetween(u,h);return f>m?d:h},e.prototype.shiftToModuleCenter=function(t){var n=t[0],r=t[1],a=t[2],i=t[3],o=this.transitionsBetween(n,i)+1,l=this.transitionsBetween(a,i)+1,c=e.shiftPoint(n,r,l*4),u=e.shiftPoint(a,r,o*4);o=this.transitionsBetween(c,i)+1,l=this.transitionsBetween(u,i)+1,(o&1)===1&&(o+=1),(l&1)===1&&(l+=1);var d=(n.getX()+r.getX()+a.getX()+i.getX())/4,h=(n.getY()+r.getY()+a.getY()+i.getY())/4;n=e.moveAway(n,d,h),r=e.moveAway(r,d,h),a=e.moveAway(a,d,h),i=e.moveAway(i,d,h);var f,m;return c=e.shiftPoint(n,r,l*4),c=e.shiftPoint(c,i,o*4),f=e.shiftPoint(r,n,l*4),f=e.shiftPoint(f,a,o*4),u=e.shiftPoint(a,i,l*4),u=e.shiftPoint(u,r,o*4),m=e.shiftPoint(i,a,l*4),m=e.shiftPoint(m,n,o*4),[c,f,u,m]},e.prototype.isValid=function(t){return t.getX()>=0&&t.getX()<this.image.getWidth()&&t.getY()>0&&t.getY()<this.image.getHeight()},e.sampleGrid=function(t,n,r,a,i,o,l){var c=Uw.getInstance();return c.sampleGrid(t,o,l,.5,.5,o-.5,.5,o-.5,l-.5,.5,l-.5,n.getX(),n.getY(),i.getX(),i.getY(),a.getX(),a.getY(),r.getX(),r.getY())},e.prototype.transitionsBetween=function(t,n){var r=Math.trunc(t.getX()),a=Math.trunc(t.getY()),i=Math.trunc(n.getX()),o=Math.trunc(n.getY()),l=Math.abs(o-a)>Math.abs(i-r);if(l){var c=r;r=a,a=c,c=i,i=o,o=c}for(var u=Math.abs(i-r),d=Math.abs(o-a),h=-u/2,f=a<o?1:-1,m=r<i?1:-1,x=0,g=this.image.get(l?a:r,l?r:a),y=r,b=a;y!==i;y+=m){var v=this.image.get(l?b:y,l?y:b);if(v!==g&&(x++,g=v),h+=d,h>0){if(b===o)break;b+=f,h-=u}}return x},e})(),c2=(function(){function e(){this.decoder=new zJe}return e.prototype.decode=function(t,n){n===void 0&&(n=null);var r,a;if(n!=null&&n.has(On.PURE_BARCODE)){var i=e.extractPureBits(t.getBlackMatrix());r=this.decoder.decode(i),a=e.NO_POINTS}else{var o=new WJe(t.getBlackMatrix()).detect();r=this.decoder.decode(o.getBits()),a=o.getPoints()}var l=r.getRawBytes(),c=new Ts(r.getText(),l,8*l.length,a,wt.DATA_MATRIX,Fn.currentTimeMillis()),u=r.getByteSegments();u!=null&&c.putMetadata(jr.BYTE_SEGMENTS,u);var d=r.getECLevel();return d!=null&&c.putMetadata(jr.ERROR_CORRECTION_LEVEL,d),c},e.prototype.reset=function(){},e.extractPureBits=function(t){var n=t.getTopLeftOnBit(),r=t.getBottomRightOnBit();if(n==null||r==null)throw new Oe;var a=this.moduleSize(n,t),i=n[1],o=r[1],l=n[0],c=r[0],u=(c-l+1)/a,d=(o-i+1)/
926a;if(u<=0||d<=0)throw new Oe;var h=a/2;i+=h,l+=h;for(var f=new _i(u,d),m=0;m<d;m++)for(var x=i+m*a,g=0;g<u;g++)t.get(l+g*a,x)&&f.set(g,m);return f},e.moduleSize=function(t,n){for(var r=n.getWidth(),a=t[0],i=t[1];a<r&&n.get(a,i);)a++;if(a===r)throw new Oe;var o=a-t[0];if(o===0)throw new Oe;return o},e.NO_POINTS=[],e})(),KJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();(function(e){KJe(t,e);function t(n){return n===void 0&&(n=500),e.call(this,new c2,n)||this}return t})(Vf);var Th;(function(e){e[e.L=0]="L",e[e.M=1]="M",e[e.Q=2]="Q",e[e.H=3]="H"})(Th||(Th={}));var u2=(function(){function e(t,n,r){this.value=t,this.stringValue=n,this.bits=r,e.FOR_BITS.set(r,this),e.FOR_VALUE.set(t,this)}return e.prototype.getValue=function(){return this.value},e.prototype.getBits=function(){return this.bits},e.fromString=function(t){switch(t){case"L":return e.L;case"M":return e.M;case"Q":return e.Q;case"H":return e.H;default:throw new co(t+"not available")}},e.prototype.toString=function(){return this.stringValue},e.prototype.equals=function(t){if(!(t instanceof e))return!1;var n=t;return this.value===n.value},e.forBits=function(t){if(t<0||t>=e.FOR_BITS.size)throw new Ct;return e.FOR_BITS.get(t)},e.FOR_BITS=new Map,e.FOR_VALUE=new Map,e.L=new e(Th.L,"L",1),e.M=new e(Th.M,"M",0),e.Q=new e(Th.Q,"Q",3),e.H=new e(Th.H,"H",2),e})(),HJe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},XG=(function(){function e(t){this.errorCorrectionLevel=u2.forBits(t>>3&3),this.dataMask=t&7}return e.numBitsDiffering=function(t,n){return Zt.bitCount(t^n)},e.decodeFormatInformation=function(t,n){var r=e.doDecodeFormatInformation(t,n);return r!==null?r:e.doDecodeFormatInformation(t^e.FORMAT_INFO_MASK_QR,n^e.FORMAT_INFO_MASK_QR)},e.doDecodeFormatInformation=function(t,n){var r,a,i=Number.MAX_SAFE_INTEGER,o=0;try{for(var l=HJe(e.FORMAT_INFO_DECODE_LOOKUP),c=l.next();!c.done;c=l.next()){var u=c.value,d=u[0];if(d===t||d===n)return new e(u[1]);var h=e.numBitsDiffering(t,d);h<i&&(o=u[1],i=h),t!==n&&(h=e.numBitsDiffering(n,d),h<i&&(o=u[1],i=h))}}catch(f){r={error:f}}finally{try{c&&!c.done&&(a=l.return)&&a.call(l)}finally{if(r)throw r.error}}return i<=3?new e(o):null},e.prototype.getErrorCorrectionLevel=function(){return this.errorCorrectionLevel},e.prototype.getDataMask=function(){return this.dataMask},e.prototype.hashCode=function(){return this.errorCorrectionLevel.getBits()<<3|this.dataMask},e.prototype.equals=function(t){if(!(t instanceof e))return!1;var n=t;return this.errorCorrectionLevel===n.errorCorrectionLevel&&this.dataMask===n.dataMask},e.FORMAT_INFO_MASK_QR=21522,e.FORMAT_INFO_DECODE_LOOKUP=[Int32Array.from([21522,0]),Int32Array.from([20773,1]),Int32Array.from([24188,2]),Int32Array.from([23371,3]),Int32Array.from([17913,4]),Int32Array.from([16590,5]),Int32Array.from([20375,6]),Int32Array.from([19104,7]),Int32Array.from([30660,8]),Int32Array.from([29427,9]),Int32Array.from([32170,10]),Int32Array.from([30877,11]),Int32Array.from([26159,12]),Int32Array.from([25368,13]),Int32Array.from([27713,14]),Int32Array.from([26998,15]),Int32Array.from([5769,16]),Int32Array.from([5054,17]),Int32Array.from([7399,18]),Int32Array.from([6608,19]),Int32Array.from([1890,20]),Int32Array.from([597,21]),Int32Array.from([3340,22]),Int32Array.from([2107,23]),Int32Array.from([13663,24]),Int32Array.from([12392,25]),Int32Array.from([16177,26]),Int32Array.from([14854,27]),Int32Array.from([9396,28]),Int32Array.from([8579,29]),Int32Array.from([11994,30]),Int32Array.from([11245,31])],e})(),VJe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);
926if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},we=(function(){function e(t){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];this.ecCodewordsPerBlock=t,this.ecBlocks=n}return e.prototype.getECCodewordsPerBlock=function(){return this.ecCodewordsPerBlock},e.prototype.getNumBlocks=function(){var t,n,r=0,a=this.ecBlocks;try{for(var i=VJe(a),o=i.next();!o.done;o=i.next()){var l=o.value;r+=l.getCount()}}catch(c){t={error:c}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return r},e.prototype.getTotalECCodewords=function(){return this.ecCodewordsPerBlock*this.getNumBlocks()},e.prototype.getECBlocks=function(){return this.ecBlocks},e})(),Q=(function(){function e(t,n){this.count=t,this.dataCodewords=n}return e.prototype.getCount=function(){return this.count},e.prototype.getDataCodewords=function(){return this.dataCodewords},e})(),qJe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},xd=(function(){function e(t,n){for(var r,a,i=[],o=2;o<arguments.length;o++)i[o-2]=arguments[o];this.versionNumber=t,this.alignmentPatternCenters=n,this.ecBlocks=i;var l=0,c=i[0].getECCodewordsPerBlock(),u=i[0].getECBlocks();try{for(var d=qJe(u),h=d.next();!h.done;h=d.next()){var f=h.value;l+=f.getCount()*(f.getDataCodewords()+c)}}catch(m){r={error:m}}finally{try{h&&!h.done&&(a=d.return)&&a.call(d)}finally{if(r)throw r.error}}this.totalCodewords=l}return e.prototype.getVersionNumber=function(){return this.versionNumber},e.prototype.getAlignmentPatternCenters=function(){return this.alignmentPatternCenters},e.prototype.getTotalCodewords=function(){return this.totalCodewords},e.prototype.getDimensionForVersion=function(){return 17+4*this.versionNumber},e.prototype.getECBlocksForLevel=function(t){return this.ecBlocks[t.getValue()]},e.getProvisionalVersionForDimension=function(t){if(t%4!==1)throw new We;try{return this.getVersionForNumber((t-17)/4)}catch{throw new We}},e.getVersionForNumber=function(t){if(t<1||t>40)throw new Ct;return e.VERSIONS[t-1]},e.decodeVersionInformation=function(t){for(var n=Number.MAX_SAFE_INTEGER,r=0,a=0;a<e.VERSION_DECODE_INFO.length;a++){var i=e.VERSION_DECODE_INFO[a];if(i===t)return e.getVersionForNumber(a+7);var o=XG.numBitsDiffering(t,i);o<n&&(r=a+7,n=o)}return n<=3?e.getVersionForNumber(r):null},e.prototype.buildFunctionPattern=function(){var t=this.getDimensionForVersion(),n=new _i(t);n.setRegion(0,0,9,9),n.setRegion(t-8,0,8,9),n.setRegion(0,t-8,9,8);for(var r=this.alignmentPatternCenters.length,a=0;a<r;a++)for(var i=this.alignmentPatternCenters[a]-2,o=0;o<r;o++)a===0&&(o===0||o===r-1)||a===r-1&&o===0||n.setRegion(this.alignmentPatternCenters[o]-2,i,5,5);return n.setRegion(6,9,1,t-17),n.setRegion(9,6,t-17,1),this.versionNumber>6&&(n.setRegion(t-11,0,3,6),n.setRegion(0,t-11,6,3)),n},e.prototype.toString=function(){return""+this.versionNumber},e.VERSION_DECODE_INFO=Int32Array.from([31892,34236,39577,42195,48118,51042,55367,58893,63784,68472,70749,76311,79154,84390,87683,92361,96236,102084,102881,110507,110734,117786,119615,126325,127568,133589,136944,141498,145311,150283,152622,158308,161089,167017]),e.VERSIONS=[new e(1,new Int32Array(0),new we(7,new Q(1,19)),new we(10,new Q(1,16)),new we(13,new Q(1,13)),new we(17,new Q(1,9))),new e(2,Int32Array.from([6,18]),new we(10,new Q(1,34)),new we(16,new Q(1,28)),new we(22,new Q(1,22)),new we(28,new Q(1,16))),new e(3,Int32Array.from([6,22]),new we(15,new Q(1,55)),new we(26,new Q(1,44)),new we(18,new Q(2,17)),new we(22,new Q(2,13))),new e(4,Int32Array.from([6,26]),new we(20,new Q(1,80)),new we(18,new Q(2,32)),new we(26,new Q(2,24)),new we(16,new Q(4,9))),new e(5,Int32Array.from([6,30]),new we(26,new Q(1,108)),new we(24,new Q(2,43)),new we(18,new Q(2,15),new Q(2,16)),new we(22,new Q(2,11),new Q(2,12))),new e(6,Int32Array.from([6,34]),new we(18,new Q(2,68)),new we(16,new Q(4,27)),new we(24,new Q(4,19)),new we(28,new Q(4,15))),new e(7,Int32Array.from([6,22,38]),new we(20,new Q(2,78)),new we(18,new Q(4,31)),new we(18,new Q(2,14),new Q(4,15)),new we(26,new Q(4,13),new Q(1,14))),new e(8,Int32Array.from([6,24,42]),new we(24,new Q(2,97)),new we(22,new Q(2,38),new Q(2,39)),new we(22,new Q(4,18),new Q(2,19)),new we(26,new Q(4,14),new Q(2,15))),new e(9,Int32Array.from([6,26,46]),new we(30,new Q(2,116)),new we(22,new Q(3,36),new Q(2,37)),new we(20,new Q(4,16),new Q(4,17)),new we(24,new Q(4,12),new Q(4,13))),new e(10,Int32Array.from([6,28,50]),new we(18,new Q(2,68),new Q(2,69)),new we(26,new Q(4,43),new Q(1,44)),new we(24,new Q(6,19),new Q(2,20)),new we(28,new Q(6,15),new Q(2,16))),new e(11,Int32Array.from([6,30,54]),new we(20,new Q(4,81)),new we(30,new Q(1,50),new Q(4,51)),new we(28,new Q(4,22),new Q(4,23)),new we(24,new Q(3,12),new Q(8,13))),new e(12,Int32Array.from([6,32,58]),new we(24,new Q(2,92),new Q(2,93)),new we(22,new Q(6,36),new Q(2,37)),new we(26,new Q(4,20),new Q(6,21)),new we(28,new Q(7,14),new Q(4,15))),new e(13,Int32Array.from([6,34,62]),new we(26,new Q(4,107)),new we(22,new Q(8,37),new Q(1,38)),new we(24,new Q(8,20),new Q(4,21)),new we(22,new Q(12,11),new Q(4,12))),new e(14,Int32Array.from([6,26,46,66]),new we(30,new Q(3,115),new Q(1,116)),new we(24,new Q(4,40),new Q(5,41)),new we(20,new Q(11,16),new Q(5,17)),new we(24,new Q(11,12),new Q(5,13))),new e(15,Int32Array.from([6,26,48,70]),new we(22,new Q(5,87),new Q(1,88)),new we(24,new Q(5,41),new Q(5,42)),new we(30,new Q(5,24),new Q(7,25)),new we(24,new Q(11,12),new Q(7,13))),new e(16,Int32Array.from([6,26,50,74]),new we(24,new Q(5,98),new Q(1,99)),new we(28,new Q(7,45),new Q(3,46)),new we(24,new Q(15,19),new Q(2,20)),new we(30,new Q(3,15),new Q(13,16))),new e(17,Int32Array.from([6,30,54,78]),new we(28,new Q(1,107),new Q(5,108)),new we(28,new Q(10,46),new Q(1,47)),new we(28,new Q(1,22),new Q(15,23)),new we(28,new Q(2,14),new Q(17,15))),new e(18,Int32Array.from([6,30,56,82]),new we(30,new Q(5,120),new Q(1,121)),new we(26,new Q(9,43),new Q(4,44)),new we(28,new Q(17,22),new Q(1,23)),new we(28,new Q(2,14),new Q(19,15))),new e(19,Int32Array.from([6,30,58,86]),new we(28,new Q(3,113),new Q(4,114)),new we(26,new Q(3,44),new Q(11,45)),new we(26,new Q(17,21),new Q(4,22)),new we(26,new Q(9,13),new Q(16,14))),new e(20,Int32Array.from([6,34,62,90]),new we(28,new Q(3,107),new Q(5,108)),new we(26,new Q(3,41),new Q(13,42)),new we(30,new Q(15,24),new Q(5,25)),new we(28,new Q(15,15),new Q(10,16))),new e(21,Int32Array.from([6,28,50,72,94]),new we(28,new Q(4,116),new Q(4,117)),new we(26,new Q(17,42)),new we(28,new Q(17,22),new Q(6,23)),new we(30,new Q(19,16),new Q(6,17))),new e(22,Int32Array.from([6,26,50,74,98]),new we(28,new Q(2,111),new Q(7,112)),new we(28,new Q(17,46)),new we(30,new Q(7,24),new Q(16,25)),new we(24,new Q(34,13))),new e(23,Int32Array.from([6,30,54,78,102]),new we(30,new Q(4,121),new Q(5,122)),new we(28,new Q(4,47),new Q(14,48)),new we(30,new Q(11,24),new Q(14,25)),new we(30,new Q(16,15),new Q(14,16))),new e(24,Int32Array.from([6,28,54,80,106]),new we(30,new Q(6,117),new Q(4,118)),new we(28,new Q(6,45),new Q(14,46)),new we(30,new Q(11,24),new Q(16,25)),new we(30,new Q(30,16),new Q(2,17))),new e(25,Int32Array.from([6,32,58,84,110]),new we(26,new Q(8,106),new Q(4,107)),new we(28,new Q(8,47),new Q(13,48)),new we(30,new Q(7,24),new Q(22,25)),new we(30,new Q(22,15),new Q(13,16))),new e(26,Int32Array.from([6,30,58,86,114]),new we(28,new Q(10,114),new Q(2,115)),new we(28,new Q(19,46),new Q(4,47)),new we(28,new Q(28,22),new Q(6,23)),new we(30,new Q(33,16),new Q(4,17))),new e(27,Int32Array.from([6,34,62,90,118]),new we(30,new Q(8,122),new Q(4,123)),new we(28,new Q(22,45),new Q(3,46)),new we(30,new Q(8,23),new Q(26,24)),new we(30,new Q(12,15),new Q(28,16))),new e(28,Int32Array.from([6,26,50,74,98,122]),new we(30,new Q(3,117),new Q(10,118)),new we(28,new Q(3,45),new Q(23,46)),new we(30,new Q(4,24),new Q(31,25)),new we(30,new Q(11,15),new Q(31,16))),new e(29,Int32Array.from([6,30,54,78,102,126]),new we(30,new Q(7,116),new Q(7,117)),new we(28,new Q(21,45),new Q(7,46)),new we(30,new Q(1,23),new Q(37,24)),new we(30,new Q(19,15),new Q(26,16))),new e(30,Int32Array.from([6,26,52,78,104,130]),new we(30,new Q(5,115),new Q(10,116)),new we(28,new Q(19,47),new Q(10,48)),new we(30,new Q(15,24),new Q(25,25)),new we(30,new Q(23,15),new Q(25,16))),new e(31,Int32Array.from([6,30,56,82,108,134]),new we(30,new Q(13,115),new Q(3,116)),new we(28,new Q(2,46),new Q(29,47)),new we(30,new Q(42,24),new Q(1,25)),new we(30,new Q(23,15),new Q(28,16))),new e(32,Int32Array.from([6,34,60,86,112,138]),new we(30,new Q(17,115)),new we(28,new Q(10,46),new Q(23,47)),new we(30,new Q(10,24),new Q(35,25)),new we(30,new Q(19,15),new Q(35,16))),new e(33,Int32Array.from([6,30,58,86,114,142]),new we(30,new Q(17,115),new Q(1,116)),new we(28,new Q(14,46),new Q(21,47)),new we(30,new Q(29,24),new Q(19,25)),new we(30,new Q(11,15),new Q(46,16))),new e(34,Int32Array.from([6,34,62,90,118,146]),new we(30,new Q(13,115),new Q(6,116)),new we(28,new Q(14,46),new Q(23,47)),new we(30,new Q(44,24),new Q(7,25)),new we(30,new Q(59,16),new Q(1,17))),new e(35,Int32Array.from([6,30,54,78,102,126,150]),new we(30,new Q(12,121),new Q(7,122)),new we(28,new Q(12,47),new Q(26,48)),new we(30,new Q(39,24),new Q(14,25)),new we(30,new Q(22,15),new Q(41,16))),new e(36,Int32Array.from([6,24,50,76,102,128,154]),new we(30,new Q(6,121),new Q(14,122)),new we(28,new Q(6,47),new Q(34,48)),new we(30,new Q(46,24),new Q(10,25)),new we(30,new Q(2,15),new Q(64,16))),new e(37,Int32Array.from([6,28,54,80,106,132,158]),new we(30,new Q(17,122),new Q(4,123)),new we(28,new Q(29,46),new Q(14,47)),new we(30,new Q(49,24),new Q(10,25)),new we(30,new Q(24,15),new Q(46,16))),new e(38,Int32Array.from([6,32,58,84,110,136,162]),new we(30,new Q(4,122),new Q(18,123)),new we(28,new Q(13,46),new Q(32,47)),new we(30,new Q(48,24),new Q(14,25)),new we(30,new Q(42,15),new Q(32,16))),new e(39,Int32Array.from([6,26,54,82,110,138,166]),new we(30,new Q(20,117),new Q(4,118)),new we(28,new Q(40,47),new Q(7,48)),new we(30,new Q(43,24),new Q(22,25)),new we(30,new Q(10,15),new Q(67,16))),new e(40,Int32Array.from([6,30,58,86,114,142,170]),new we(30,new Q(19,118),new Q(6,119)),new we(28,new Q(18,47),new Q(31,48)),new we(30,new Q(34,24),new Q(34,25)),new we(30,new Q(20,15),new Q(61,16)))],e})(),gs;(function(e){e[e.DATA_MASK_000=0]="DATA_MASK_000",e[e.DATA_MASK_001=1]="DATA_MASK_001",e[e.DATA_MASK_010=2]="DATA_MASK_010",e[e.DATA_MASK_011=3]="DATA_MASK_011",e[e.DATA_MASK_100=4]="DATA_MASK_100",e[e.DATA_MASK_101=5]="DATA_MASK_101",e[e.DATA_MASK_110=6]="DATA_MASK_110",e[e.DATA_MASK_111=7]="DATA_MASK_111"})(gs||(gs={}));var v8=(function(){function e(t,n){this.value=t,this.isMasked=n}return e.prototype.unmaskBitMatrix=function(t,n){for(var r=0;r<n;r++)for(var a=0;a<n;a++)this.isMasked(r,a)&&t.flip(a,r)},e.values=new Map([[gs.DATA_MASK_000,new e(gs.DATA_MASK_000,function(t,n){return(t+n&1)===0})],[gs.DATA_MASK_001,new e(gs.DATA_MASK_001,function(t,n){return(t&1)===0})],[gs.DATA_MASK_010,new e(gs.DATA_MASK_010,function(t,n){return n%3===0})],[gs.DATA_MASK_011,new e(gs.DATA_MASK_011,function(t,n){return(t+n)%3===0})],[gs.DATA_MASK_100,new e(gs.DATA_MASK_100,function(t,n){return(Math.floor(t/2)+Math.floor(n/3)&1)===0})],[gs.DATA_MASK_101,new e(gs.DATA_MASK_101,function(t,n){return t*n%6===0})],[gs.DATA_MASK_110,new e(gs.DATA_MASK_110,function(t,n){return t*n%6<3})],[gs.DATA_MASK_111,new e(gs.DATA_MASK_111,function(t,n){return(t+n+t*n%3&1)===0})]]),e})(),GJe=(function(){function e(t){var n=t.getHeight();if(n<21||(n&3)!==1)throw new We;this.bitMatrix=t}return e.prototype.readFormatInformation=function(){if(this.parsedFormatInfo!==null&&this.parsedFormatInfo!==void 0)return this.parsedFormatInfo;for(var t=0,n=0;n<6;n++)t=this.copyBit(n,8,t);t=this.copyBit(7,8,t),t=this.copyBit(8,8,t),t=this.copyBit(8,7,t);for(var r=5;r>=0;r--)t=this.copyBit(8,r,t);for(var a=this.bitMatrix.getHeight(),i=0,o=a-7,r=a-1;r>=o;r--)i=this.copyBit(8,r,i);for(var n=a-8;n<a;n++)i=this.copyBit(n,8,i);if(this.parsedFormatInfo=XG.decodeFormatInformation(t,i),this.parsedFormatInfo!==null)return this.parsedFormatInfo;throw new We},e.prototype.readVersion=function(){if(this.parsedVersion!==null&&this.parsedVersion!==void 0)return this.parsedVersion;var t=this.bitMatrix.getHeight(),n=Math.floor((t-17)/4);if(n<=6)return xd.getVersionForNumber(n);for(var r=0,a=t-11,i=5;i>=0;i--)for(var o=t-9;o>=a;o--)r=this.copyBit(o,i,r);var l=xd.decodeVersionInformation(r);if(l!==null&&l.getDimensionForVersion()===t)return this.parsedVersion=l,l;r=0;for(var o=5;o>=0;o--)for(var i=t-9;i>=a;i--)r=this.copyBit(o,i,r);if(l=xd.decodeVersionInformation(r),l!==null&&l.getDimensionForVersion()===t)return this.parsedVersion=l,l;throw new We},e.prototype.copyBit=function(t,n,r){var a=this.isMirror?this.bitMatrix.get(n,t):this.bitMatrix.get(t,n);return a?r<<1|1:r<<1},e.prototype.readCodewords=function(){var t=this.readFormatInformation(),n=this.readVersion(),r=v8.values.get(t.getDataMask()),a=this.bitMatrix.getHeight();r.unmaskBitMatrix(this.bitMatrix,a);for(var i=n.buildFunctionPattern(),o=!0,l=new Uint8Array(n.getTotalCodewords()),c=0,u=0,d=0,h=a-1;h>0;h-=2){h===6&&h--;for(var f=0;f<a;f++)for(var m=o?a-1-f:f,x=0;x<2;x++)i.get(h-x,m)||(d++,u<<=1,this.bitMatrix.get(h-x,m)&&(u|=1),d===8&&(l[c++]=u,d=0,u=0));o=!o}if(c!==n.getTotalCodewords())throw new We;return l},e.prototype.remask=function(){if(this.parsedFormatInfo!==null){var t=v8.values.get(this.parsedFormatInfo.getDataMask()),n=this.bitMatrix.getHeight();t.unmaskBitMatrix(this.bitMatrix,n)}},e.prototype.setMirror=function(t){this.parsedVersion=null,this.parsedFormatInfo=null,this.isMirror=t},e.prototype.mirror=function(){for(var t=this.bitMatrix,n=0,r=t.getW
926idth();n<r;n++)for(var a=n+1,i=t.getHeight();a<i;a++)t.get(n,a)!==t.get(a,n)&&(t.flip(a,n),t.flip(n,a))},e})(),w8=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},YJe=(function(){function e(t,n){this.numDataCodewords=t,this.codewords=n}return e.getDataBlocks=function(t,n,r){var a,i,o,l;if(t.length!==n.getTotalCodewords())throw new Ct;var c=n.getECBlocksForLevel(r),u=0,d=c.getECBlocks();try{for(var h=w8(d),f=h.next();!f.done;f=h.next()){var m=f.value;u+=m.getCount()}}catch(O){a={error:O}}finally{try{f&&!f.done&&(i=h.return)&&i.call(h)}finally{if(a)throw a.error}}var x=new Array(u),g=0;try{for(var y=w8(d),b=y.next();!b.done;b=y.next())for(var m=b.value,v=0;v<m.getCount();v++){var w=m.getDataCodewords(),_=c.getECCodewordsPerBlock()+w;x[g++]=new e(w,new Uint8Array(_))}}catch(O){o={error:O}}finally{try{b&&!b.done&&(l=y.return)&&l.call(y)}finally{if(o)throw o.error}}for(var k=x[0].codewords.length,j=x.length-1;j>=0;){var N=x[j].codewords.length;if(N===k)break;j--}j++;for(var E=k-c.getECCodewordsPerBlock(),A=0,v=0;v<E;v++)for(var C=0;C<g;C++)x[C].codewords[v]=t[A++];for(var C=j;C<g;C++)x[C].codewords[E]=t[A++];for(var T=x[0].codewords.length,v=E;v<T;v++)for(var C=0;C<g;C++){var S=C<j?v:v+1;x[C].codewords[S]=t[A++]}return x},e.prototype.getNumDataCodewords=function(){return this.numDataCodewords},e.prototype.getCodewords=function(){return this.codewords},e})(),Mi;(function(e){e[e.TERMINATOR=0]="TERMINATOR",e[e.NUMERIC=1]="NUMERIC",e[e.ALPHANUMERIC=2]="ALPHANUMERIC",e[e.STRUCTURED_APPEND=3]="STRUCTURED_APPEND",e[e.BYTE=4]="BYTE",e[e.ECI=5]="ECI",e[e.KANJI=6]="KANJI",e[e.FNC1_FIRST_POSITION=7]="FNC1_FIRST_POSITION",e[e.FNC1_SECOND_POSITION=8]="FNC1_SECOND_POSITION",e[e.HANZI=9]="HANZI"})(Mi||(Mi={}));var Qn=(function(){function e(t,n,r,a){this.value=t,this.stringValue=n,this.characterCountBitsForVersions=r,this.bits=a,e.FOR_BITS.set(a,this),e.FOR_VALUE.set(t,this)}return e.forBits=function(t){var n=e.FOR_BITS.get(t);if(n===void 0)throw new Ct;return n},e.prototype.getCharacterCountBits=function(t){var n=t.getVersionNumber(),r;return n<=9?r=0:n<=26?r=1:r=2,this.characterCountBitsForVersions[r]},e.prototype.getValue=function(){return this.value},e.prototype.getBits=function(){return this.bits},e.prototype.equals=function(t){if(!(t instanceof e))return!1;var n=t;return this.value===n.value},e.prototype.toString=function(){return this.stringValue},e.FOR_BITS=new Map,e.FOR_VALUE=new Map,e.TERMINATOR=new e(Mi.TERMINATOR,"TERMINATOR",Int32Array.from([0,0,0]),0),e.NUMERIC=new e(Mi.NUMERIC,"NUMERIC",Int32Array.from([10,12,14]),1),e.ALPHANUMERIC=new e(Mi.ALPHANUMERIC,"ALPHANUMERIC",Int32Array.from([9,11,13]),2),e.STRUCTURED_APPEND=new e(Mi.STRUCTURED_APPEND,"STRUCTURED_APPEND",Int32Array.from([0,0,0]),3),e.BYTE=new e(Mi.BYTE,"BYTE",Int32Array.from([8,16,16]),4),e.ECI=new e(Mi.ECI,"ECI",Int32Array.from([0,0,0]),7),e.KANJI=new e(Mi.KANJI,"KANJI",Int32Array.from([8,10,12]),8),e.FNC1_FIRST_POSITION=new e(Mi.FNC1_FIRST_POSITION,"FNC1_FIRST_POSITION",Int32Array.from([0,0,0]),5),e.FNC1_SECOND_POSITION=new e(Mi.FNC1_SECOND_POSITION,"FNC1_SECOND_POSITION",Int32Array.from([0,0,0]),9),e.HANZI=new e(Mi.HANZI,"HANZI",Int32Array.from([8,10,12]),13),e})(),ZJe=(function(){function e(){}return e.decode=function(t,n,r,a){var i=new oT(t),o=new Kt,l=new Array,c=-1,u=-1;try{var d=null,h=!1,f=void 0;do{if(i.available()<4)f=Qn.TERMINATOR;else{var m=i.readBits(4);f=Qn.forBits(m)}switch(f){case Qn.TERMINATOR:break;case Qn.FNC1_FIRST_POSITION:case Qn.FNC1_SECOND_POSITION:h=!0;break;case Qn.STRUCTURED_APPEND:if(i.available()<16)throw new We;c=i.readBits(8),u=i.readBits(8);break;case Qn.ECI:var x=e.parseECIValue(i);if(d=as.getCharacterSetECIByValue(x),d===null)throw new We;break;case Qn.HANZI:var g=i.readBits(4),y=i.readBits(f.getCharacterCountBits(n));g===e.GB2312_SUBSET&&e.decodeHanziSegment(i,o,y);break;default:var b=i.readBits(f.getCharacterCountBits(n));switch(f){case Qn.NUMERIC:e.decodeNumericSegment(i,o,b);break;case Qn.ALPHANUMERIC:e.decodeAlphanumericSegment(i,o,b,h);break;case Qn.BYTE:e.decodeByteSegment(i,o,b,d,l,a);break;case Qn.KANJI:e.decodeKanjiSegment(i,o,b);break;default:throw new We}break}}while(f!==Qn.TERMINATOR)}catch{throw new We}return new qf(t,o.toString(),l.length===0?null:l,r===null?null:r.toString(),c,u)},e.decodeHanziSegment=function(t,n,r){if(r*13>t.available())throw new We;for(var a=new Uint8Array(2*r),i=0;r>0;){var o=t.readBits(13),l=o/96<<8&4294967295|o%96;l<959?l+=41377:l+=42657,a[i]=l>>8&255,a[i+1]=l&255,i+=2,r--}try{n.append(ri.decode(a,tn.GB2312))}catch(c){throw new We(c)}},e.decodeKanjiSegment=function(t,n,r){if(r*13>t.available())throw new We;for(var a=new Uint8Array(2*r),i=0;r>0;){var o=t.readBits(13),l=o/192<<8&4294967295|o%192;l<7936?l+=33088:l+=49472,a[i]=l>>8,a[i+1]=l,i+=2,r--}try{n.append(ri.decode(a,tn.SHIFT_JIS))}catch(c){throw new We(c)}},e.decodeByteSegment=function(t,n,r,a,i,o){if(8*r>t.available())throw new We;for(var l=new Uint8Array(r),c=0;c<r;c++)l[c]=t.readBits(8);var u;a===null?u=tn.guessEncoding(l,o):u=a.getName();try{n.append(ri.decode(l,u))}catch(d){throw new We(d)}i.push(l)},e.toAlphaNumericChar=function(t){if(t>=e.ALPHANUMERIC_CHARS.length)throw new We;return e.ALPHANUMERIC_CHARS[t]},e.decodeAlphanumericSegment=function(t,n,r,a){for(var i=n.length();r>1;){if(t.available()<11)throw new We;var o=t.readBits(11);n.append(e.toAlphaNumericChar(Math.floor(o/45))),n.append(e.toAlphaNumericChar(o%45)),r-=2}if(r===1){if(t.available()<6)throw new We;n.append(e.toAlphaNumericChar(t.readBits(6)))}if(a)for(var l=i;l<n.length();l++)n.charAt(l)==="%"&&(l<n.length()-1&&n.charAt(l+1)==="%"?n.deleteCharAt(l+1):n.setCharAt(l,"�"))},e.decodeNumericSegment=function(t,n,r){for(;r>=3;){if(t.available()<10)throw new We;var a=t.readBits(10);if(a>=1e3)throw new We;n.append(e.toAlphaNumericChar(Math.floor(a/100))),n.append(e.toAlphaNumericChar(Math.floor(a/10)%10)),n.append(e.toAlphaNumericChar(a%10)),r-=3}if(r===2){if(t.available()<7)throw new We;var i=t.readBits(7);if(i>=100)throw new We;n.append(e.toAlphaNumericChar(Math.floor(i/10))),n.append(e.toAlphaNumericChar(i%10))}else if(r===1){if(t.available()<4)throw new We;var o=t.readBits(4);if(o>=10)throw new We;n.append(e.toAlphaNumericChar(o))}},e.parseECIValue=function(t){var n=t.readBits(8);if((n&128)===0)return n&127;if((n&192)===128){var r=t.readBits(8);return(n&63)<<8&4294967295|r}if((n&224)===192){var a=t.readBits(16);return(n&31)<<16&4294967295|a}throw new We},e.ALPHANUMERIC_CHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:",e.GB2312_SUBSET=1,e})(),JG=(function(){function e(t){this.mirrored=t}return e.prototype.isMirrored=function(){return this.mirrored},e.prototype.applyMirroredCorrection=function(t){if(!(!this.mirrored||t===null||t.length<3)){var n=t[0];t[0]=t[2],t[2]=n}},e})(),_8=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);
926if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},XJe=(function(){function e(){this.rsDecoder=new Yf(ra.QR_CODE_FIELD_256)}return e.prototype.decodeBooleanArray=function(t,n){return this.decodeBitMatrix(_i.parseFromBooleanArray(t),n)},e.prototype.decodeBitMatrix=function(t,n){var r=new GJe(t),a=null;try{return this.decodeBitMatrixParser(r,n)}catch(o){a=o}try{r.remask(),r.setMirror(!0),r.readVersion(),r.readFormatInformation(),r.mirror();var i=this.decodeBitMatrixParser(r,n);return i.setOther(new JG(!0)),i}catch(o){throw a!==null?a:o}},e.prototype.decodeBitMatrixParser=function(t,n){var r,a,i,o,l=t.readVersion(),c=t.readFormatInformation().getErrorCorrectionLevel(),u=t.readCodewords(),d=YJe.getDataBlocks(u,l,c),h=0;try{for(var f=_8(d),m=f.next();!m.done;m=f.next()){var x=m.value;h+=x.getNumDataCodewords()}}catch(j){r={error:j}}finally{try{m&&!m.done&&(a=f.return)&&a.call(f)}finally{if(r)throw r.error}}var g=new Uint8Array(h),y=0;try{for(var b=_8(d),v=b.next();!v.done;v=b.next()){var x=v.value,w=x.getCodewords(),_=x.getNumDataCodewords();this.correctErrors(w,_);for(var k=0;k<_;k++)g[y++]=w[k]}}catch(j){i={error:j}}finally{try{v&&!v.done&&(o=b.return)&&o.call(b)}finally{if(i)throw i.error}}return ZJe.decode(g,l,c,n)},e.prototype.correctErrors=function(t,n){var r=new Int32Array(t);try{this.rsDecoder.decode(r,t.length-n)}catch{throw new Yr}for(var a=0;a<n;a++)t[a]=r[a]},e})(),JJe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),QJe=(function(e){JJe(t,e);function t(n,r,a){var i=e.call(this,n,r)||this;return i.estimatedModuleSize=a,i}return t.prototype.aboutEquals=function(n,r,a){if(Math.abs(r-this.getY())<=n&&Math.abs(a-this.getX())<=n){var i=Math.abs(n-this.estimatedModuleSize);return i<=1||i<=this.estimatedModuleSize}return!1},t.prototype.combineEstimate=function(n,r,a){var i=(this.getX()+r)/2,o=(this.getY()+n)/2,l=(this.estimatedModuleSize+a)/2;return new t(i,o,l)},t})(mt),eQe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},tQe=(function(){function e(t,n,r,a,i,o,l){this.image=t,this.startX=n,this.startY=r,this.width=a,this.height=i,this.moduleSize=o,this.resultPointCallback=l,this.possibleCenters=[],this.crossCheckStateCount=new Int32Array(3)}return e.prototype.find=function(){for(var t=this.startX,n=this.height,r=this.width,a=t+r,i=this.startY+n/2,o=new Int32Array(3),l=this.image,c=0;c<n;c++){var u=i+((c&1)===0?Math.floor((c+1)/2):-Math.floor((c+1)/2));o[0]=0,o[1]=0,o[2]=0;for(var d=t;d<a&&!l.get(d,u);)d++;for(var h=0;d<a;){if(l.get(d,u))if(h===1)o[1]++;else if(h===2){if(this.foundPatternCross(o)){var f=this.handlePossibleCenter(o,u,d);if(f!==null)return f}o[0]=o[2],o[1]=1,o[2]=0,h=1}else o[++h]++;else h===1&&h++,o[h]++;d++}if(this.foundPatternCross(o)){var f=this.handlePossibleCenter(o,u,a);if(f!==null)return f}}if(this.possibleCenters.length!==0)return this.possibleCenters[0];throw new Oe},e.centerFromEnd=function(t,n){return n-t[2]-t[1]/2},e.prototype.foundPatternCross=function(t){for(var n=this.moduleSize,r=n/2,a=0;a<3;a++)if(Math.abs(n-t[a])>=r)return!1;return!0},e.prototype.crossCheckVertical=function(t,n,r,a){var i=this.image,o=i.getHeight(),l=this.crossCheckStateCount;l[0]=0,l[1]=0,l[2]=0;for(var c=t;c>=0&&i.get(n,c)&&l[1]<=r;)l[1]++,c--;if(c<0||l[1]>r)return NaN;for(;c>=0&&!i.get(n,c)&&l[0]<=r;)l[0]++,c--;if(l[0]>r)return NaN;for(c=t+1;c<o&&i.get(n,c)&&l[1]<=r;)l[1]++,c++;if(c===o||l[1]>r)return NaN;for(;c<o&&!i.get(n,c)&&l[2]<=r;)l[2]++,c++;if(l[2]>r)return NaN;var u=l[0]+l[1]+l[2];return 5*Math.abs(u-a)>=2*a?NaN:this.foundPatternCross(l)?e.centerFromEnd(l,c):NaN},e.prototype.handlePossibleCenter=function(t,n,r){var a,i,o=t[0]+t[1]+t[2],l=e.centerFromEnd(t,r),c=this.crossCheckVertical(n,l,2*t[1],o);if(!isNaN(c)){var u=(t[0]+t[1]+t[2])/3;try{for(var d=eQe(this.possibleCenters),h=d.next();!h.done;h=d.next()){var f=h.value;
926if(f.aboutEquals(u,c,l))return f.combineEstimate(c,l,u)}}catch(x){a={error:x}}finally{try{h&&!h.done&&(i=d.return)&&i.call(d)}finally{if(a)throw a.error}}var m=new QJe(l,c,u);this.possibleCenters.push(m),this.resultPointCallback!==null&&this.resultPointCallback!==void 0&&this.resultPointCallback.foundPossibleResultPoint(m)}return null},e})(),nQe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),rQe=(function(e){nQe(t,e);function t(n,r,a,i){var o=e.call(this,n,r)||this;return o.estimatedModuleSize=a,o.count=i,i===void 0&&(o.count=1),o}return t.prototype.getEstimatedModuleSize=function(){return this.estimatedModuleSize},t.prototype.getCount=function(){return this.count},t.prototype.aboutEquals=function(n,r,a){if(Math.abs(r-this.getY())<=n&&Math.abs(a-this.getX())<=n){var i=Math.abs(n-this.estimatedModuleSize);return i<=1||i<=this.estimatedModuleSize}return!1},t.prototype.combineEstimate=function(n,r,a){var i=this.count+1,o=(this.count*this.getX()+r)/i,l=(this.count*this.getY()+n)/i,c=(this.count*this.estimatedModuleSize+a)/i;return new t(o,l,c,i)},t})(mt),sQe=(function(){function e(t){this.bottomLeft=t[0],this.topLeft=t[1],this.topRight=t[2]}return e.prototype.getBottomLeft=function(){return this.bottomLeft},e.prototype.getTopLeft=function(){return this.topLeft},e.prototype.getTopRight=function(){return this.topRight},e})(),Tm=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},aQe=(function(){function e(t,n){this.image=t,this.resultPointCallback=n,this.possibleCenters=[],this.crossCheckStateCount=new Int32Array(5),this.resultPointCallback=n}return e.prototype.getImage=function(){return this.image},e.prototype.getPossibleCenters=function(){return this.possibleCenters},e.prototype.find=function(t){var n=t!=null&&t.get(On.TRY_HARDER)!==void 0,r=t!=null&&t.get(On.PURE_BARCODE)!==void 0,a=this.image,i=a.getHeight(),o=a.getWidth(),l=Math.floor(3*i/(4*e.MAX_MODULES));(l<e.MIN_SKIP||n)&&(l=e.MIN_SKIP);for(var c=!1,u=new Int32Array(5),d=l-1;d<i&&!c;d+=l){u.fill(0);for(var h=0,f=0;f<o;f++)if(a.get(f,d))(h&1)===1&&h++,u[h]++;else if((h&1)===0)if(h===4)if(e.foundPatternCross(u)){var m=this.handlePossibleCenter(u,d,f,r);if(m===!0)if(l=2,this.hasSkipped===!0)c=this.haveMultiplyConfirmedCenters();else{var x=this.findRowSkip();x>u[2]&&(d+=x-u[2]-l,f=o-1)}else{u[0]=u[2],u[1]=u[3],u[2]=u[4],u[3]=1,u[4]=0,h=3;continue}h=0,u.fill(0)}else u[0]=u[2],u[1]=u[3],u[2]=u[4],u[3]=1,u[4]=0,h=3;else u[++h]++;else u[h]++;if(e.foundPatternCross(u)){var m=this.handlePossibleCenter(u,d,o,r);m===!0&&(l=u[0],this.hasSkipped&&(c=this.haveMultiplyConfirmedCenters()))}}var g=this.selectBestPatterns();return mt.orderBestPatterns(g),new sQe(g)},e.centerFromEnd=function(t,n){return n-t[4]-t[3]-t[2]/2},e.foundPatternCross=function(t){for(var n=0,r=0;r<5;r++){var a=t[r];if(a===0)return!1;n+=a}if(n<7)return!1;var i=n/7,o=i/2;return Math.abs(i-t[0])<o&&Math.abs(i-t[1])<o&&Math.abs(3*i-t[2])<3*o&&Math.abs(i-t[3])<o&&Math.abs(i-t[4])<o},e.prototype.getCrossCheckStateCount=function(){return this.crossCheckStateCount.fill(0),this.crossCheckStateCount},e.prototype.crossCheckDiagonal=function(t,n,r,a){for(var i=this.getCrossCheckStateCount(),o=0,l=this.image;t>=o&&n>=o&&l.get(n-o,t-o);)i[2]++,o++;if(t<o||n<o)return!1;for(;t>=o&&n>=o&&!l.get(n-o,t-o)&&i[1]<=r;)i[1]++,o++;if(t<o||n<o||i[1]>r)return!1;for(;t>=o&&n>=o&&l.get(n-o,t-o)&&i[0]<=r;)i[0]++,o++;if(i[0]>r)return!1;var c=l.getHeight(),u=l.getWidth();for(o=1;t+o<c&&n+o<u&&l.get(n+o,t+o);)i[2]++,o++;if(t+o>=c||n+o>=u)return!1;for(;t+o<c&&n+o<u&&!l.get(n+o,t+o)&&i[3]<r;)i[3]++,o++;if(t+o>=c||n+o>=u||i[3]>=r)return!1;for(;t+o<c&&n+o<u&&l.get(n+o,t+o)&&i[4]<r;)i[4]++,o++;if(i[4]>=r)return!1;var d=i[0]+i[1]+i[2]+i[3]+i[4];return Math.abs(d-a)<2*a&&e.foundPatternCross(i)},e.prototype.crossCheckVertical=function(t,n,r,a){for(var i=this.image,o=i.getHeight(),l=this.getCrossCheckStateCount(),c=t;c>=0&&i.get(n,c);)l[2]++,c--;if(c<0)return NaN;for(;c>=0&&!i.get(n,c)&&l[1]<=r;)l[1]++,c--;if(c<0||l[1]>r)return NaN;for(;c>=0&&i.get(n,c)&&l[0]<=r;)l[0]++,c--;if(l[0]>r)return NaN;for(c=t+1;c<o&&i.get(n,c);)l[2]++,c++;if(c===o)return NaN;for(;c<o&&!i.get(n,c)&&l[3]<r;)l[3]++,c++;if(c===o||l[3]>=r)return NaN;for(;c<o&&i.get(n,c)&&l[4]<r;)l[4]++,c++;if(l[4]>=r)return NaN;var u=l[0]+l[1]+l[2]+l[3]+l[4];return 5*Math.abs(u-a)>=2*a?NaN:e.foundPatternCross(l)?e.centerFromEnd(l,c):NaN},e.prototype.crossCheckHorizontal=function(t,n,r,a){for(var i=this.image,o=i.getWidth(),l=this.getCrossCheckStateCount(),c=t;c>=0&&i.get(c,n);)l[2]++,c--;if(c<0)return NaN;for(;c>=0&&!i.get(c,n)&&l[1]<=r;)l[1]++,c--;if(c<0||l[1]>r)return NaN;for(;c>=0&&i.get(c,n)&&l[0]<=r;)l[0]++,c--;if(l[0]>r)return NaN;for(c=t+1;c<o&&i.get(c,n);)l[2]++,c++;if(c===o)return NaN;for(;c<o&&!i.get(c,n)&&l[3]<r;)l[3]++,c++;if(c===o||l[3]>=r)return NaN;for(;c<o&&i.get(c,n)&&l[4]<r;)l[4]++,c++;if(l[4]>=r)return NaN;var u=l[0]+l[1]+l[2]+l[3]+l[4];return 5*Math.abs(u-a)>=a?NaN:e.foundPatternCross(l)?e.centerFromEnd(l,c):NaN},e.prototype.handlePossibleCenter=function(t,n,r,a){var i=t[0]+t[1]+t[2]+t[3]+t[4],o=e.centerFromEnd(t,r),l=this.crossCheckVertical(n,Math.floor(o),t[2],i);if(!isNaN(l)&&(o=this.crossCheckHorizontal(Math.floor(o),Math.floor(l),t[2],i),!isNaN(o)&&(!a||this.crossCheckDiagonal(Math.floor(l),Math.floor(o),t[2],i)))){for(var c=i/7,u=!1,d=this.possibleCenters,h=0,f=d.length;h<f;h++){var m=d[h];if(m.aboutEquals(c,l,o)){d[h]=m.combineEstimate(l,o,c),u=!0;break}}if(!u){var x=new rQe(o,l,c);d.push(x),this.resultPointCallback!==null&&this.resultPointCallback!==void 0&&this.resultPointCallback.foundPossibleResultPoint(x)}return!0}return!1},e.prototype.findRowSkip=function(){var t,n,r=this.possibleCenters.length;if(r<=1)return 0;var a=null;try{for(var i=Tm(this.possibleCenters),o=i.next();!o.done;o=i.next()){var l=o.value;if(l.getCount()>=e.CENTER_QUORUM)if(a==null)a=l;else return this.hasSkipped=!0,Math.floor((Math.abs(a.getX()-l.getX())-Math.abs(a.getY()-l.getY()))/2)}}catch(c){t={error:c}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return 0},e.prototype.haveMultiplyConfirmedCenters=function(){var t,n,r,a,i=0,o=0,l=this.possibleCenters.length;try{for(var c=Tm(this.possibleCenters),u=c.next();!u.done;u=c.next()){var d=u.value;d.getCount()>=e.CENTER_QUORUM&&(i++,o+=d.getEstimatedModuleSize())}}catch(g){t={error:g}}finally{try{u&&!u.done&&(n=c.return)&&n.call(c)}finally{if(t)throw t.error}}if(i<3)return!1;var h=o/l,f=0;try{for(var m=Tm(this.possibleCenters),x=m.next();!x.done;x=m.next()){var d=x.value;f+=Math.abs(d.getEstimatedModuleSize()-h)}}catch(g){r={error:g}}finally{try{x&&!x.done&&(a=m.return)&&a.call(m)}finally{if(r)throw r.error}}return f<=.05*o},e.prototype.selectBestPatterns=function(){var t,n,r,a,i=this.possibleCenters.length;if(i<3)throw new Oe;var o=this.possibleCenters,l;if(i>3){var c=0,u=0;try{for(var d=Tm(this.possibleCenters),h=d.next();!h.done;h=d.next()){var f=h.value,m=f.getEstimatedModuleSize();c+=m,u+=m*m}}catch(k){t={error:k}}finally{try{h&&!h.done&&(n=d.return)&&n.call(d)}finally{if(t)throw t.error}}l=c/i;var x=Math.sqrt(u/i-l*l);o.sort(function(k,j){var N=Math.abs(j.getEstimatedModuleSize()-l),E=Math.abs(k.getEstimatedModuleSize()-l);return N<E?-1:N>E?1:0});for(var g=Math.max(.2*l,x),y=0;y<o.length&&o.length>3;y++){var b=o[y];Math.abs(b.getEstimatedModuleSize()-l)>g&&(o.splice(y,1),y--)}}if(o.length>3){var c=0;try{for(var v=Tm(o),w=v.next();!w.done;w=v.next()){var _=w.value;c+=_.getEstimatedModuleSize()}}catch(j){r={error:j}}finally{try{w&&!w.done&&(a=v.return)&&a.call(v)}finally{if(r)throw r.error}}l=c/o.length,o.sort(function(j,N){if(N.getCount()===j.getCount()){var E=Math.abs(N.getEstimatedModuleSize()-l),A=Math.abs(j.getEstimatedModuleSize()-l);return E<A?1:E>A?-1:0}else return N.getCount()-j.getCount()}),o.splice(3)}return[o[0],o[1],o[2]]},e.CENTER_QUORUM=2,e.MIN_SKIP=3,e.MAX_MODULES=57,e})(),iQe=(function(){function e(t){this.image=t}return e.prototype.getImage=function(){return this.image},e.prototype.getResultPointCallback=function(){return this.resultPointCallback},e.prototype.detect=function(t){this.resultPointCallback=t==null?null:t.get(On.NEED_RESULT_POINT_CALLBACK);var n=new aQe(this.image,this.resultPointCallback),r=n.find(t);return this.processFinderPatternInfo(r)}
926,e.prototype.processFinderPatternInfo=function(t){var n=t.getTopLeft(),r=t.getTopRight(),a=t.getBottomLeft(),i=this.calculateModuleSize(n,r,a);if(i<1)throw new Oe("No pattern found in proccess finder.");var o=e.computeDimension(n,r,a,i),l=xd.getProvisionalVersionForDimension(o),c=l.getDimensionForVersion()-7,u=null;if(l.getAlignmentPatternCenters().length>0)for(var d=r.getX()-n.getX()+a.getX(),h=r.getY()-n.getY()+a.getY(),f=1-3/c,m=Math.floor(n.getX()+f*(d-n.getX())),x=Math.floor(n.getY()+f*(h-n.getY())),g=4;g<=16;g<<=1)try{u=this.findAlignmentInRegion(i,m,x,g);break}catch(w){if(!(w instanceof Oe))throw w}var y=e.createTransform(n,r,a,u,o),b=e.sampleGrid(this.image,y,o),v;return u===null?v=[a,n,r]:v=[a,n,r,u],new Bw(b,v)},e.createTransform=function(t,n,r,a,i){var o=i-3.5,l,c,u,d;return a!==null?(l=a.getX(),c=a.getY(),u=o-3,d=u):(l=n.getX()-t.getX()+r.getX(),c=n.getY()-t.getY()+r.getY(),u=o,d=o),aT.quadrilateralToQuadrilateral(3.5,3.5,o,3.5,u,d,3.5,o,t.getX(),t.getY(),n.getX(),n.getY(),l,c,r.getX(),r.getY())},e.sampleGrid=function(t,n,r){var a=Uw.getInstance();return a.sampleGridWithTransform(t,r,r,n)},e.computeDimension=function(t,n,r,a){var i=mn.round(mt.distance(t,n)/a),o=mn.round(mt.distance(t,r)/a),l=Math.floor((i+o)/2)+7;switch(l&3){case 0:l++;break;case 2:l--;break;case 3:throw new Oe("Dimensions could be not found.")}return l},e.prototype.calculateModuleSize=function(t,n,r){return(this.calculateModuleSizeOneWay(t,n)+this.calculateModuleSizeOneWay(t,r))/2},e.prototype.calculateModuleSizeOneWay=function(t,n){var r=this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(t.getX()),Math.floor(t.getY()),Math.floor(n.getX()),Math.floor(n.getY())),a=this.sizeOfBlackWhiteBlackRunBothWays(Math.floor(n.getX()),Math.floor(n.getY()),Math.floor(t.getX()),Math.floor(t.getY()));return isNaN(r)?a/7:isNaN(a)?r/7:(r+a)/14},e.prototype.sizeOfBlackWhiteBlackRunBothWays=function(t,n,r,a){var i=this.sizeOfBlackWhiteBlackRun(t,n,r,a),o=1,l=t-(r-t);l<0?(o=t/(t-l),l=0):l>=this.image.getWidth()&&(o=(this.image.getWidth()-1-t)/(l-t),l=this.image.getWidth()-1);var c=Math.floor(n-(a-n)*o);return o=1,c<0?(o=n/(n-c),c=0):c>=this.image.getHeight()&&(o=(this.image.getHeight()-1-n)/(c-n),c=this.image.getHeight()-1),l=Math.floor(t+(l-t)*o),i+=this.sizeOfBlackWhiteBlackRun(t,n,l,c),i-1},e.prototype.sizeOfBlackWhiteBlackRun=function(t,n,r,a){var i=Math.abs(a-n)>Math.abs(r-t);if(i){var o=t;t=n,n=o,o=r,r=a,a=o}for(var l=Math.abs(r-t),c=Math.abs(a-n),u=-l/2,d=t<r?1:-1,h=n<a?1:-1,f=0,m=r+d,x=t,g=n;x!==m;x+=d){var y=i?g:x,b=i?x:g;if(f===1===this.image.get(y,b)){if(f===2)return mn.distance(x,g,t,n);f++}if(u+=c,u>0){if(g===a)break;g+=h,u-=l}}return f===2?mn.distance(r+d,a,t,n):NaN},e.prototype.findAlignmentInRegion=function(t,n,r,a){var i=Math.floor(a*t),o=Math.max(0,n-i),l=Math.min(this.image.getWidth()-1,n+i);if(l-o<t*3)throw new Oe("Alignment top exceeds estimated module size.");var c=Math.max(0,r-i),u=Math.min(this.image.getHeight()-1,r+i);if(u-c<t*3)throw new Oe("Alignment bottom exceeds estimated module size.");var d=new tQe(this.image,o,c,l-o,u-c,t,this.resultPointCallback);return d.find()},e})(),d2=(function(){function e(){this.decoder=new XJe}return e.prototype.getDecoder=function(){return this.decoder},e.prototype.decode=function(t,n){var r,a;if(n!=null&&n.get(On.PURE_BARCODE)!==void 0){var i=e.extractPureBits(t.getBlackMatrix());r=this.decoder.decodeBitMatrix(i,n),a=e.NO_POINTS}else{var o=new iQe(t.getBlackMatrix()).detect(n);r=this.decoder.decodeBitMatrix(o.getBits(),n),a=o.getPoints()}r.getOther()instanceof JG&&r.getOther().applyMirroredCorrection(a);var l=new Ts(r.getText(),r.getRawBytes(),void 0,a,wt.QR_CODE,void 0),c=r.getByteSegments();c!==null&&l.putMetadata(jr.BYTE_SEGMENTS,c);var u=r.getECLevel();return u!==null&&l.putMetadata(jr.ERROR_CORRECTION_LEVEL,u),r.hasStructuredAppend()&&(l.putMetadata(jr.STRUCTURED_APPEND_SEQUENCE,r.getStructuredAppendSequenceNumber()),l.putMetadata(jr.STRUCTURED_APPEND_PARITY,r.getStructuredAppendParity())),l},e.prototype.reset=function(){},e.extractPureBits=function(t){var n=t.getTopLeftOnBit(),r=t.getBottomRightOnBit();if(n===null||r===null)throw new Oe;var a=this.moduleSize(n,t),i=n[1],o=r[1],l=n[0],c=r[0];if(l>=c||i>=o)throw new Oe;if(o-i!==c-l&&(c=l+(o-i),c>=t.getWidth()))throw new Oe;
926var u=Math.round((c-l+1)/a),d=Math.round((o-i+1)/a);if(u<=0||d<=0)throw new Oe;if(d!==u)throw new Oe;var h=Math.floor(a/2);i+=h,l+=h;var f=l+Math.floor((u-1)*a)-c;if(f>0){if(f>h)throw new Oe;l-=f}var m=i+Math.floor((d-1)*a)-o;if(m>0){if(m>h)throw new Oe;i-=m}for(var x=new _i(u,d),g=0;g<d;g++)for(var y=i+Math.floor(g*a),b=0;b<u;b++)t.get(l+Math.floor(b*a),y)&&x.set(b,g);return x},e.moduleSize=function(t,n){for(var r=n.getHeight(),a=n.getWidth(),i=t[0],o=t[1],l=!0,c=0;i<a&&o<r;){if(l!==n.get(i,o)){if(++c===5)break;l=!l}i++,o++}if(i===a||o===r)throw new Oe;return(i-t[0])/7},e.NO_POINTS=new Array,e})(),k8=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},j8=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,i=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},oQe=(function(){function e(t){this.versionIndicator=t>>2&7,this.dataMask=t&3}return e.computeBCHFormatWord=function(t){for(var n=t<<10,r=4;r>=0;r--)n>>r+10&1&&(n^=e.BCH_GENERATOR<<r);return t<<10|n&1023},e.buildLookupTable=function(){for(var t=[],n=0;n<32;n++){var r=e.computeBCHFormatWord(n),a=r^e.FORMAT_INFO_MASK_MICRO_QR;t.push([a,n])}return t},e.numBitsDiffering=function(t,n){return Zt.bitCount(t^n)},e.decodeFormatInformation=function(t){var n,r,a,i;try{for(var o=k8(e.FORMAT_INFO_DECODE_LOOKUP),l=o.next();!l.done;l=o.next()){var c=j8(l.value,2),u=c[0],d=c[1];if(u===t)return new e(d)}}catch(b){n={error:b}}finally{try{l&&!l.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}var h=Number.MAX_SAFE_INTEGER,f=0;try{for(var m=k8(e.FORMAT_INFO_DECODE_LOOKUP),x=m.next();!x.done;x=m.next()){var g=j8(x.value,2),u=g[0],d=g[1],y=e.numBitsDiffering(t,u);y<h&&(h=y,f=d)}}catch(b){a={error:b}}finally{try{x&&!x.done&&(i=m.return)&&i.call(m)}finally{if(a)throw a.error}}return h<=3?new e(f):null},e.prototype.getVersionIndicator=function(){return this.versionIndicator},e.prototype.getDataMask=function(){return this.dataMask},e.prototype.getMicroQRVersionNumber=function(){return this.versionIndicator===0?1:this.versionIndicator<=2?2:this.versionIndicator<=4?3:4},e.prototype.getECLevelLabel=function(){switch(this.versionIndicator){case 0:return null;case 1:case 3:case 5:return"L";case 2:case 4:case 6:return"M";case 7:return"Q";default:return null}},e.FORMAT_INFO_MASK_MICRO_QR=17477,e.BCH_GENERATOR=1335,e.FORMAT_INFO_DECODE_LOOKUP=e.buildLookupTable(),e})(),lQe=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,i=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},QG=(function(){function e(t,n,r){this.versionNumber=t,this.versionIndicator=n,this.ecBlocks=r;var a=r,i=a.getECBlocks()[0];this.totalCodewords=i.getCount()*(i.getDataCodewords()+a.getECCodewordsPerBlock())}return e.prototype.getVersionNumber=function(){return this.versionNumber},e.prototype.getVersionIndicator=function(){return this.versionIndicator},e.prototype.getDimensionForVersion=function(){return 9+2*this.versionNumber},e.prototype.getTotalCodewords=function(){return this.totalCodewords},e.prototype.getNumDataCodewords=function(){return this.ecBlocks.getECBlocks()[0].getDataCodewords()},e.prototype.getNumECCodewords=function(){return this.totalCodewords-this.getNumDataCodewords()},e.prototype.getECBlocks=function(){return this.ecBlocks},e.prototype.getECLevelLabel=function(){return e.VERSION_INFO[this.versionIndicator][1]},e.prototype.getModeIndicatorBits=function(){return e.MODE_INDICATOR_BITS[this.versionNumber-1]},e.prototype.buildFunctionPattern=function(){var t=this.getDimensionForVersion(),n=new _i(t);return n.setRegion(0,0,9,9),t>9&&(n.setRegion(9,0,t-9,1),n.setRegion(0,9,1,t-9)),n},e.getVersionForIndicator=function(t){if(t<0||t>7)throw new We;var n=lQe(e.VERSION_INFO[t],1),r=n[0];return new e(r,t,e.EC_BLOCKS[t])},e.getVersionForDimension=function(t){switch(t){case 11:return e.getVersionForIndicator(0);case 13:return e.getVersionForIndicator(1);case 15:return e.getVersionForIndicator(3);case 17:return e.getVersionForIndicator(5);default:throw new We}},e.prototype.toString=function(){return"M"+this.versionNumber},e.VERSION_INFO=[[1,null],[2,"L"],[2,"M"],[3,"L"],[3,"M"],[4,"L"],[4,"M"],[4,"Q"]],e.EC_BLOCKS=[new we(2,new Q(1,3)),new we(5,new Q(1,5)),new we(6,new Q(1,4)),new we(6,new Q(1,11)),new we(8,new Q(1,9)),new we(8,new Q(1,16)),new we(10,new Q(1,14)),new we(14,new Q(1,10))],e.MODE_INDICATOR_BITS=[0,1,2,3],e})(),cQe=(function(){function e(t,n){this.maskIndex=t,this.isMasked=n}return e.forIndex=function(t){if(t<0||t>=e.MASKS.length)throw new Error("Invalid Micro QR mask index: "+t);return e.MASKS[t]},e.prototype.unmaskBitMatrix=function(t,n){for(var r=0;r<n;r++)for(var a=0;a<n;a++)this.isMasked(r,a)&&t.flip(a,r)},e.MASKS=[new e(0,function(t,n){return(t&1)===0}),new e(1,function(t,n){return(Math.floor(t/2)+Math.floor(n/3))%2===0}),new e(2,function(t,n){var r=t*n;
926return((r&1)+r%3)%2===0}),new e(3,function(t,n){return((t+n&1)+t*n%3)%2===0})],e})(),uQe=(function(){function e(t){this.bitMatrix=t,this.parsedFormatInfo=null,this.parsedVersion=null;var n=t.getHeight();if(n<11||n>17||n%2!==1)throw new We}return e.prototype.readFormatInformation=function(){if(this.parsedFormatInfo!==null)return this.parsedFormatInfo;for(var t=0,n=1;n<=8;n++)t=this.copyBit(n,8,t);for(var r=7;r>=1;r--)t=this.copyBit(8,r,t);var a=oQe.decodeFormatInformation(t);if(a!==null)return this.parsedFormatInfo=a,this.parsedVersion=QG.getVersionForIndicator(a.getVersionIndicator()),a;throw new We},e.prototype.copyBit=function(t,n,r){return this.bitMatrix.get(t,n)?r<<1|1:r<<1},e.prototype.readCodewords=function(){var t=this.readFormatInformation(),n=this.parsedVersion,r=cQe.forIndex(t.getDataMask()),a=this.bitMatrix.getHeight();r.unmaskBitMatrix(this.bitMatrix,a);for(var i=n.buildFunctionPattern(),o=n.getNumDataCodewords(),l=n.getVersionNumber()===1||n.getVersionNumber()===3,c=!0,u=new Uint8Array(n.getTotalCodewords()),d=0,h=0,f=0,m=a-1;m>0;m-=2){for(var x=0;x<a;x++)for(var g=c?a-1-x:x,y=0;y<2;y++){var b=m-y;if(!i.get(b,g)){f++,h<<=1,this.bitMatrix.get(b,g)&&(h|=1);var v=l&&d===o-1,w=v?4:8;f===w&&(u[d++]=v?h<<4&255:h&255,f=0,h=0)}}c=!c}if(d!==n.getTotalCodewords())throw new We;return u},e})(),N8=(function(){function e(){}return e.decode=function(t,n,r){var a=new oT(t),i=new Kt,o=[],l=n.getVersionNumber(),c=n.getModeIndicatorBits();try{for(;;){var u=void 0;if(c===0)u=e.MODE_NUMERIC;else{if(a.available()<c)break;var d=a.readBits(c);u=e.decodeMode(d,l)}var h=e.charCountBits(u,l);if(a.available()<h)break;var f=a.readBits(h);if(f===0)break;switch(u){case e.MODE_NUMERIC:e.decodeNumeric(a,i,f);break;case e.MODE_ALPHA:e.decodeAlphanumeric(a,i,f);break;case e.MODE_BYTE:e.decodeByte(a,i,o,f,r);break;case e.MODE_KANJI:e.decodeKanji(a,i,f);break;default:throw new We}}}catch(m){throw m instanceof We?m:new We}return new qf(t,i.toString(),o.length===0?null:o,n.getECLevelLabel(),-1,-1)},e.decodeMode=function(t,n){switch(n){case 2:return t===0?e.MODE_NUMERIC:e.MODE_ALPHA;case 3:switch(t){case 0:return e.MODE_NUMERIC;case 1:return e.MODE_ALPHA;case 2:return e.MODE_BYTE;case 3:return e.MODE_KANJI}break;case 4:switch(t){case 0:return e.MODE_NUMERIC;case 1:return e.MODE_ALPHA;case 2:return e.MODE_BYTE;case 4:return e.MODE_KANJI}break}throw new We},e.charCountBits=function(t,n){switch(t){case e.MODE_NUMERIC:return n+2;case e.MODE_ALPHA:return n+1;case e.MODE_BYTE:return n+1;case e.MODE_KANJI:return n;default:throw new We}},e.decodeNumeric=function(t,n,r){for(var a=r;a>=3;){if(t.available()<10)throw new We;var i=t.readBits(10);if(i>=1e3)throw new We;n.append(e.toChar(Math.floor(i/100))),n.append(e.toChar(Math.floor(i/10)%10)),n.append(e.toChar(i%10)),a-=3}if(a===2){if(t.available()<7)throw new We;var o=t.readBits(7);if(o>=100)throw new We;n.append(e.toChar(Math.floor(o/10))),n.append(e.toChar(o%10))}else if(a===1){if(t.available()<4)throw new We;var l=t.readBits(4);if(l>=10)throw new We;n.append(e.toChar(l))}},e.decodeAlphanumeric=function(t,n,r){for(var a=r;a>1;){if(t.available()<11)throw new We;var i=t.readBits(11);n.append(e.toAlphaNum(Math.floor(i/45))),n.append(e.toAlphaNum(i%45)),a-=2}if(a===1){if(t.available()<6)throw new We;n.append(e.toAlphaNum(t.readBits(6)))}},e.decodeByte=function(t,n,r,a,i){if(8*a>t.available())throw new We;for(var o=new Uint8Array(a),l=0;l<a;l++)o[l]=t.readBits(8)&255;var c=tn.guessEncoding(o,i);try{n.append(ri.decode(o,c))}catch{throw new We}r.push(o)},e.decodeKanji=function(t,n,r){if(13*r>t.available())throw new We;for(var a=new Uint8Array(2*r),i=0,o=0;o<r;o++){var l=t.readBits(13),c=Math.floor(l/192)<<8|l%192;c+=c<7936?33088:49472,a[i++]=c>>8&255,a[i++]=c&255}try{n.append(ri.decode(a,tn.SHIFT_JIS))}catch{throw new We}},e.toChar=function(t){if(t>=e.ALPHANUMERIC_CHARS.length)throw new We;return e.ALPHANUMERIC_CHARS[t]},e.toAlphaNum=function(t){if(t>=e.ALPHANUMERIC_CHARS.length)throw new We;return e.ALPHANUMERIC_CHARS[t]},e.ALPHANUMERIC_CHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:",e.MODE_NUMERIC=0,e.MODE_ALPHA=1,e.MODE_BYTE=2,e.MODE_KANJI=3,e})(),dQe=(function(){function e(){this.rsDecoder=new Yf(ra.QR_CODE_FIELD_256)}return e.prototype.decodeBitMatrix=function(t,n){var r=new uQe(t),a=r.readFormatInformation(),i=QG.getVersionForIndicator(a.getVersionIndicator()),o=r.readCodewords(),l=i.getNumDataCodewords();return i.getNumECCodewords(),i.getVersionNumber()===1||this.correctErrors(o,l),N8.decode(o.subarray(0,l),i,n??null)},e.prototype.correctErrors=function(t,n){var r=new Int32Array(t);try{this.rsDecoder.decode(r,t.length-n)}catch{throw new Yr}for(var a=0;a<n;a++)t[a]=r[a]&255},e})(),hQe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
926t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),fQe=(function(e){hQe(t,e);function t(n,r,a,i){i===void 0&&(i=1);var o=e.call(this,n,r)||this;return o.estimatedModuleSize=a,o.count=i,o}return t.prototype.getEstimatedModuleSize=function(){return this.estimatedModuleSize},t.prototype.getCount=function(){return this.count},t.prototype.aboutEquals=function(n,r,a){if(Math.abs(r-this.getY())<=n&&Math.abs(a-this.getX())<=n){var i=Math.abs(n-this.estimatedModuleSize);return i<=1||i<=this.estimatedModuleSize}return!1},t.prototype.combineEstimate=function(n,r,a){var i=this.count+1,o=(this.count*this.getX()+r)/i,l=(this.count*this.getY()+n)/i,c=(this.count*this.estimatedModuleSize+a)/i;return new t(o,l,c,i)},t})(mt),mQe=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,i=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},pQe=(function(){function e(t){this.image=t}return e.prototype.detect=function(t){var n;this.resultPointCallback=t!=null&&(n=t.get(On.NEED_RESULT_POINT_CALLBACK))!==null&&n!==void 0?n:null;var r=this.findFinderPattern(t);return this.processFinderPattern(r)},e.prototype.findFinderPattern=function(t){for(var n=this.image,r=n.getHeight(),a=n.getWidth(),i=t!=null&&t.get(On.TRY_HARDER)!==void 0,o=i?1:Math.max(1,Math.floor(r/64)),l=new Int32Array(5),c=[],u=o-1;u<r;u+=o){l.fill(0);for(var d=0,h=0;h<a;h++)if(n.get(h,u))(d&1)===1&&d++,l[d]++;else if((d&1)===0)if(d===4){if(this.foundPatternCross(l)){var f=this.handlePossibleCenter(l,u,h,c);if(f){l.fill(0),d=0;continue}}l[0]=l[2],l[1]=l[3],l[2]=l[4],l[3]=1,l[4]=0,d=3;continue}else l[++d]++;else l[d]++;this.foundPatternCross(l)&&this.handlePossibleCenter(l,u,a,c)}if(c.length===0)throw new Oe("No Micro QR finder pattern found.");return c.sort(function(m,x){return x.getCount()-m.getCount()}),c[0]},e.prototype.foundPatternCross=function(t){for(var n=0,r=0;r<5;r++){var a=t[r];if(a===0)return!1;n+=a}if(n<7)return!1;var i=n/7,o=i/2;return Math.abs(i-t[0])<o&&Math.abs(i-t[1])<o&&Math.abs(3*i-t[2])<3*o&&Math.abs(i-t[3])<o&&Math.abs(i-t[4])<o},e.prototype.handlePossibleCenter=function(t,n,r,a){var i=t[0]+t[1]+t[2]+t[3]+t[4],o=this.centerFromEnd(t,r),l=this.crossCheckVertical(n,Math.floor(o),t[2],i);if(isNaN(l))return!1;for(var c=(t[0]+t[1]+t[2]+t[3]+t[4])/7,u=0;u<a.length;u++){var d=a[u];if(d.aboutEquals(c,l,o))return a[u]=d.combineEstimate(l,o,c),!0}return a.push(new fQe(o,l,c)),this.resultPointCallback!==null&&this.resultPointCallback.foundPossibleResultPoint(a[a.length-1]),!1},e.prototype.centerFromEnd=function(t,n){return n-t[4]-t[3]-t[2]/2},e.prototype.crossCheckVertical=function(t,n,r,a){for(var i=this.image,o=i.getHeight(),l=new Int32Array(5),c=t;c>=0&&i.get(n,c);)l[2]++,c--;if(c<0)return NaN;for(;c>=0&&!i.get(n,c)&&l[1]<=a;)l[1]++,c--;if(c<0||l[1]>a)return NaN;for(;c>=0&&i.get(n,c)&&l[0]<=a;)l[0]++,c--;if(l[0]>a)return NaN;for(c=t+1;c<o&&i.get(n,c);)l[2]++,c++;if(c===o)return NaN;for(;c<o&&!i.get(n,c)&&l[3]<a;)l[3]++,c++;if(c===o||l[3]>=a)return NaN;for(;c<o&&i.get(n,c)&&l[4]<a;)l[4]++,c++;if(l[4]>=a)return NaN;var u=l[0]+l[1]+l[2]+l[3]+l[4];return 5*Math.abs(u-a)>=2*a?NaN:this.foundPatternCross(l)?this.centerFromEnd(l,c):NaN},e.prototype.processFinderPattern=function(t){var n=t.getX(),r=t.getY(),a=t.getEstimatedModuleSize();if(a<1)throw new Oe("Module size too small.");var i=this.determineDimension(n,r,a);if(i===null)throw new Oe("Cannot determine Micro QR symbol dimension.");var o=i.dim,l=i.orientation,c=(o-7)*a,u=[c,0,-c,0][l],d=[0,c,0,-c][l],h=[0,-c,0,c][l],f=[c,0,-c,0][l],m=n+u,x=r+d,g=n+h,y=r+f,b=e.createTransform(n,r,m,x,g,y,o),v=e.sampleGrid(this.image,b,o),w=[new mt(n,r),new mt(m,x),new mt(g,y)];return new Bw(v,w)},e.prototype.determineDimension=function(t,n,r){for(var a=[[5,-3,1,0,-3,5,0,1],[3,5,0,1,-5,-3,-1,0],[-5,3,-1,0,3,-5,0,-1],[-3,-5,0,-1,5,3,1,0]],i=null,o=0;o<4;o++){var l=mQe(a[o],8),c=l[0],u=l[1],d=l[2],h=l[3],f=l[4],m=l[5],x=l[6],g=l[7],y=this.probeTimingLine(t+c*r,n+u*r,d,h,r),b=this.probeTimingLine(t+f*r,n+m*r,x,g,r);if(y!==null&&b!==null){var v=this.snapDimension(y,b);
926if(v!==null)return{dim:v,orientation:o}}else if(i===null&&(y!==null||b!==null)){var v=this.snapDimension(y,b);v!==null&&(i={dim:v,orientation:o})}}return i},e.prototype.snapDimension=function(t,n){if(t===null)return n;if(n===null||t===n)return t;var r=Math.round((t+n)/2),a=[11,13,15,17].reduce(function(i,o){return Math.abs(o-r)<Math.abs(i-r)?o:i});return a},e.prototype.probeTimingLine=function(t,n,r,a,i){for(var o=0,l=0;l<10;l++){var c=8+l,u=Math.round(t+r*l*i),d=Math.round(n+a*l*i);if(u<0||u>=this.image.getWidth()||d<0||d>=this.image.getHeight())break;var h=this.image.get(u,d),f=c%2===0;if(h!==f)break;f&&o++}if(o<2)return null;var m=8+2*o-1;if(m===11||m===13||m===15||m===17)return m;var x=[11,13,15,17].reduce(function(g,y){return Math.abs(y-m)<Math.abs(g-m)?y:g});return Math.abs(x-m)<=2?x:null},e.createTransform=function(t,n,r,a,i,o,l){var c=l-3.5;return aT.quadrilateralToQuadrilateral(3.5,3.5,c,3.5,3.5,c,c,c,t,n,r,a,i,o,r+(i-t),a+(o-n))},e.sampleGrid=function(t,n,r){var a=Uw.getInstance();return a.sampleGridWithTransform(t,r,r,n)},e})(),S8=(function(){function e(){this.decoder=new dQe}return e.prototype.decode=function(t,n){var r,a;if(n!=null&&n.get(On.PURE_BARCODE)!==void 0){var i=t.getBlackMatrix();r=this.decoder.decodeBitMatrix(i,n??void 0),a=[]}else{var o=new pQe(t.getBlackMatrix()),l=o.detect(n??void 0);a=l.getPoints(),r=this.decoder.decodeBitMatrix(l.getBits(),n??void 0)}var c=new Ts(r.getText(),r.getRawBytes(),r.getNumBits(),a,wt.MICRO_QR_CODE,Fn.currentTimeMillis()),u=r.getByteSegments();u!==null&&c.putMetadata(jr.BYTE_SEGMENTS,u);var d=r.getECLevel();return d!==null&&c.putMetadata(jr.ERROR_CORRECTION_LEVEL,d),c},e.prototype.reset=function(){},e})(),xQe=(function(){function e(t){this.bitMatrix=t}return e.prototype.readCodewords=function(){for(var t=new Uint8Array(144),n=this.bitMatrix.getHeight(),r=this.bitMatrix.getWidth(),a=0;a<n;a++)for(var i=e.BITNR[a],o=0;o<r;o++){var l=i[o];l>=0&&this.bitMatrix.get(o,a)&&(t[Math.floor(l/6)]|=1<<5-l%6)}return t},e.BITNR=[[121,120,127,126,133,132,139,138,145,144,151,150,157,156,163,162,169,168,175,174,181,180,187,186,193,192,199,198,-2,-2],[123,122,129,128,135,134,141,140,147,146,153,152,159,158,165,164,171,170,177,176,183,182,189,188,195,194,201,200,816,-3],[125,124,131,130,137,136,143,142,149,148,155,154,161,160,167,166,173,172,179,178,185,184,191,190,197,196,203,202,818,817],[283,282,277,276,271,270,265,264,259,258,253,252,247,246,241,240,235,234,229,228,223,222,217,216,211,210,205,204,819,-3],[285,284,279,278,273,272,267,266,261,260,255,254,249,248,243,242,237,236,231,230,225,224,219,218,213,212,207,206,821,820],[287,286,281,280,275,274,269,268,263,262,257,256,251,250,245,244,239,238,233,232,227,226,221,220,215,214,209,208,822,
926-3],[289,288,295,294,301,300,307,306,313,312,319,318,325,324,331,330,337,336,343,342,349,348,355,354,361,360,367,366,824,823],[291,290,297,296,303,302,309,308,315,314,321,320,327,326,333,332,339,338,345,344,351,350,357,356,363,362,369,368,825,-3],[293,292,299,298,305,304,311,310,317,316,323,322,329,328,335,334,341,340,347,346,353,352,359,358,365,364,371,370,827,826],[409,408,403,402,397,396,391,390,79,78,-2,-2,13,12,37,36,2,-1,44,43,109,108,385,384,379,378,373,372,828,-3],[411,410,405,404,399,398,393,392,81,80,40,-2,15,14,39,38,3,-1,-1,45,111,110,387,386,381,380,375,374,830,829],[413,412,407,406,401,400,395,394,83,82,41,-3,-3,-3,-3,-3,5,4,47,46,113,112,389,388,383,382,377,376,831,-3],[415,414,421,420,427,426,103,102,55,54,16,-3,-3,-3,-3,-3,-3,-3,20,19,85,84,433,432,439,438,445,444,833,832],[417,416,423,422,429,428,105,104,57,56,-3,-3,-3,-3,-3,-3,-3,-3,22,21,87,86,435,434,441,440,447,446,834,-3],[419,418,425,424,431,430,107,106,59,58,-3,-3,-3,-3,-3,-3,-3,-3,-3,23,89,88,437,436,443,442,449,448,836,835],[481,480,475,474,469,468,48,-2,30,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,0,53,52,463,462,457,456,451,450,837,-3],[483,482,477,476,471,470,49,-1,-2,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-2,-1,465,464,459,458,453,452,839,838],[485,484,479,478,473,472,51,50,31,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,1,-2,42,467,466,461,460,455,454,840,-3],[487,486,493,492,499,498,97,96,61,60,-3,-3,-3,-3,-3,-3,-3,-3,-3,26,91,90,505,504,511,510,517,516,842,841],[489,488,495,494,501,500,99,98,63,62,-3,-3,-3,-3,-3,-3,-3,-3,28,27,93,92,507,506,513,512,519,518,843,-3],[491,490,497,496,503,502,101,100,65,64,17,-3,-3,-3,-3,-3,-3,-3,18,29,95,94,509,508,515,514,521,520,845,844],[559,558,553,552,547,546,541,540,73,72,32,-3,-3,-3,-3,-3,-3,10,67,66,115,114,535,534,529,528,523,522,846,-3],[561,560,555,554,549,548,543,542,75,74,-2,-1,7,6,35,34,11,-2,69,68,117,116,537,536,531,530,525,524,848,847],[563,562,557,556,551,550,545,544,77,76,-2,33,9,8,25,24,-1,-2,71,70,119,118,539,538,533,532,527,526,849,-3],[565,564,571,570,577,576,583,582,589,588,595,594,601,600,607,606,613,612,619,618,625,624,631,630,637,636,643,642,851,850],[567,566,573,572,579,578,585,584,591,590,597,596,603,602,609,608,615,614,621,620,627,626,633,632,639,638,645,644,852,-3],[569,568,575,574,581,580,587,586,593,592,599,598,605,604,611,610,617,616,623,622,629,628,635,634,641,640,647,646,854,853],[727,726,721,720,715,714,709,708,703,702,697,696,691,690,685,684,679,678,673,672,667,666,661,660,655,654,649,648,855,-3],[729,728,723,722,717,716,711,710,705,704,699,698,693,692,687,686,681,680,675,674,669,668,663,662,657,656,651,650,857,856],[731,730,725,724,719,718,713,712,707,706,701,700,695,694,689,688,683,682,677,676,671,670,665,664,659,658,653,652,858,-3],[733,732,739,738,745,744,751,750,757,756,763,762,769,768,775,774,781,780,787,786,793,792,799,798,805,804,811,810,860,859],[735,734,741,740,747,746,753,752,759,758,765,764,771,770,777,776,783,782,789,788,795,794,801,800,807,806,813,812,861,-3],[737,736,743,742,749,748,755,754,761,760,767,766,773,772,779,778,785,784,791,790,797,796,803,802,809,808,815,814,863,862]],e})(),gQe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},yQe=(function(){function e(){}return e.decode=function(t,n){var r=[];switch(n){case 2:case 3:{var a=void 0;if(n===2){var i=e.getPostCode2(t),o=e.getPostCode2Length(t);if(o>10)throw We.getFormatInstance();a=String(i).padStart(o,"0")}else a=e.getPostCode3(t);var l=String(e.getCountry(t)).padStart(3,"0"),c=String(e.getServiceClass(t)).padStart(3,"0"),u=e.getMessage(t,10,84);r.push(u),r.join("").startsWith("[)>"+e.RS+"01"+e.GS)?(r.splice(0,r.length),r.push(u.substring(0,9)),r.push(a+e.GS+l+e.GS+c+e.GS),r.push(u.substring(9))):(r.splice(0,r.length),r.push(a+e.GS+l+e.GS+c+e.GS),r.push(u));break}case 4:r.push(e.getMessage(t,1,93));break;case 5:r.push(e.getMessage(t,1,77));break}return new qf(t,r.join(""),null,String(n))},e.getBit=function(t,n){return t--,(n[Math.floor(t/6)]&1<<5-t%6)===0?0:1},e.getInt=function(t,n){for(var r=0,a=0;a<n.length;a++)r+=e.getBit(n[a],t)<<n.length-a-1;return r},e.getCountry=function(t){return e.getInt(t,e.COUNTRY_BYTES)},e.getServiceClass=function(t){return e.getInt(t,e.SERVICE_CLASS_BYTES)},e.getPostCode2Length=function(t){return e.getInt(t,e.POSTCODE_2_LENGTH_BYTES)},e.getPostCode2=function(t){return e.getInt(t,e.POSTCODE_2_BYTES)},e.getPostCode3=function(t){var n,r,a=[];try{for(var i=gQe(e.POSTCODE_3_BYTES),o=i.next();!o.done;o=i.next()){var l=o.value;a.push(e.SETS[0].charAt(e.getInt(t,l)))}}catch(c){n={error:c}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return a.join("")}
926,e.getMessage=function(t,n,r){for(var a=[],i=-1,o=0,l=0,c=n;c<n+r;c++){var u=e.SETS[o].charAt(t[c]);switch(u){case e.LATCHA:o=0,i=-1;break;case e.LATCHB:o=1,i=-1;break;case e.SHIFTA:case e.SHIFTB:case e.SHIFTC:case e.SHIFTD:case e.SHIFTE:l=o,o=u.charCodeAt(0)-e.SHIFTA.charCodeAt(0),i=1;break;case e.TWOSHIFTA:l=o,o=0,i=2;break;case e.THREESHIFTA:l=o,o=0,i=3;break;case e.NS:{var d=(t[++c]<<24)+(t[++c]<<18)+(t[++c]<<12)+(t[++c]<<6)+t[++c];a.push(String(d).padStart(9,"0"));break}case e.LOCK:i=-1;break;default:a.push(u)}i--===0&&(o=l)}for(;a.length>0&&a[a.length-1]===e.PAD;)a.pop();return a.join("")},e.SHIFTA="ï¿°",e.SHIFTB="￱",e.SHIFTC="￲",e.SHIFTD="￳",e.SHIFTE="ï¿´",e.TWOSHIFTA="￵",e.THREESHIFTA="ï¿¶",e.LATCHA="ï¿·",e.LATCHB="￸",e.LOCK="",e.ECI="",e.NS="ï¿»",e.PAD="",e.FS="�",e.GS="�",e.RS="�",e.COUNTRY_BYTES=[53,54,43,44,45,46,47,48,37,38],e.SERVICE_CLASS_BYTES=[55,56,57,58,59,60,49,50,51,52],e.POSTCODE_2_LENGTH_BYTES=[39,40,41,42,31,32],e.POSTCODE_2_BYTES=[33,34,35,36,25,26,27,28,29,30,19,20,21,22,23,24,13,14,15,16,17,18,7,8,9,10,11,12,1,2],e.POSTCODE_3_BYTES=[[39,40,41,42,31,32],[33,34,35,36,25,26],[27,28,29,30,19,20],[21,22,23,24,13,14],[15,16,17,18,7,8],[9,10,11,12,1,2]],e.SETS=["\rABCDEFGHIJKLMNOPQRSTUVWXYZ"+e.ECI+e.FS+e.GS+e.RS+e.NS+" "+e.PAD+`"#$%&'()*+,-./0123456789:`+e.SHIFTB+e.SHIFTC+e.SHIFTD+e.SHIFTE+e.LATCHB,"`abcdefghijklmnopqrstuvwxyz"+e.ECI+e.FS+e.GS+e.RS+e.NS+"{"+e.PAD+"}~�;<=>?[\\]^_ ,./:@!|"+e.PAD+e.TWOSHIFTA+e.THREESHIFTA+e.PAD+e.SHIFTA+e.SHIFTC+e.SHIFTD+e.SHIFTE+e.LATCHA,"ÃÃÃÃÃà ÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃ"+e.ECI+e.FS+e.GS+e.RS+e.NS+"ÃÃÃÃꬱ²³µ¹º¼½¾Â ÂÂÂÂ"+e.LATCHA+" "+e.LOCK+e.SHIFTD+e.SHIFTE+e.LATCHB,"à áâãäåæçèéêëìÃîïðñòóôõö÷øùú"+e.ECI+e.FS+e.GS+e.RS+e.NS+"ûüýþÿ¡¨«¯°´·¸»¿ÂÂÂÂÂÂÂÂÂÂÂ"+e.LATCHA+" "+e.SHIFTC+e.LOCK+e.SHIFTE+e.LATCHB,`\0������\x07\b 927\v\f\r�������������`+e.ECI+e.PAD+e.PAD+"\x1B"+e.NS+e.FS+e.GS+e.RS+"� ¢£¤¥¦§©Â®¶ÂÂÂÂÂÂÂÂÂÂ"+e.LATCHA+" "+e.SHIFTC+e.SHIFTD+e.LOCK+e.LATCHB],e})(),bQe=(function(){function e(){this.rsDecoder=new Yf(ra.MAXICODE_FIELD_64)}return e.prototype.decode=function(t,n){var r=new xQe(t),a=r.readCodewords(),i=this.correctErrors(a,0,10,10,e.ALL),o=a[0]&15,l;switch(o){case 2:case 3:case 4:i+=this.correctErrors(a,20,84,40,e.EVEN),i+=this.correctErrors(a,20,84,40,e.ODD),l=new Uint8Array(94);break;case 5:i+=this.correctErrors(a,20,68,56,e.EVEN),i+=this.correctErrors(a,20,68,56,e.ODD),l=new Uint8Array(78);break;default:throw We.getFormatInstance()}for(var c=0;c<10;c++)l[c]=a[c];for(var c=0;c<l.length-10;c++)l[c+10]=a[c+20];var u=yQe.decode(l,o);return u.setErrorsCorrected(i),u},e.prototype.correctErrors=function(t,n,r,a,i){for(var o=r+a,l=i===e.ALL?1:2,c=new Int32Array(Math.floor(o/l)),u=0;u<o;u++)(i===e.ALL||u%2===i-1)&&(c[Math.floor(u/l)]=t[u+n]&255);var d=0;try{d=this.rsDecoder.decodeWithECCount(c,Math.floor(a/l))}catch(h){throw h instanceof zm?Yr.getChecksumInstance():h}for(var u=0;u<r;u++)(i===e.ALL||u%2===i-1)&&(t[u+n]=c[Math.floor(u/l)]);return d},e.ALL=0,e.EVEN=1,e.ODD=2,e})(),C8=(function(){function e(){this.decoder=new bQe}return e.prototype.decode=function(t,n){n===void 0&&(n=null);var r=e.extractPureBits(t.getBlackMatrix()),a=this.decoder.decode(r,n),i=new Ts(a.getText(),a.getRawBytes(),8*a.getRawBytes().length,e.NO_POINTS,wt.MAXICODE,Fn.currentTimeMillis());i.putMetadata(jr.ERRORS_CORRECTED,a.getErrorsCorrected());var o=a.getECLevel();return o!=null&&i.putMetadata(jr.ERROR_CORRECTION_LEVEL,o),i},e.prototype.reset=function(){},e.extractPureBits=function(t){var n=t.getEnclosingRectangle();if(n==null)throw new Oe;for(var r=n[0],a=n[1],i=n[2],o=n[3],l=new _i(e.MATRIX_WIDTH,e.MATRIX_HEIGHT),c=0;c<e.MATRIX_HEIGHT;c++)for(var u=a+Math.min(Math.floor((c*o+o/2)/e.MATRIX_HEIGHT),o-1),d=0;d<e.MATRIX_WIDTH;d++){var h=r+Math.min(Math.floor((d*i+i/2+(c&1)*Math.floor(i/2))/e.MATRIX_WIDTH),i-1);t.get(h,u)&&l.set(d,c)}return l},e.NO_POINTS=[],e.MATRIX_WIDTH=30,e.MATRIX_HEIGHT=33,e})(),vQe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);
927if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},dn=(function(){function e(){}return e.prototype.PDF417Common=function(){},e.getBitCountSum=function(t){return mn.sum(t)},e.toIntArray=function(t){var n,r;if(t==null||!t.length)return e.EMPTY_INT_ARRAY;var a=new Int32Array(t.length),i=0;try{for(var o=vQe(t),l=o.next();!l.done;l=o.next()){var c=l.value;a[i++]=c}}catch(u){n={error:u}}finally{try{l&&!l.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return a},e.getCodeword=function(t){var n=is.binarySearch(e.SYMBOL_TABLE,t&262143);return n<0?-1:(e.CODEWORD_TABLE[n]-1)%e.NUMBER_OF_CODEWORDS},e.NUMBER_OF_CODEWORDS=929,e.MAX_CODEWORDS_IN_BARCODE=e.NUMBER_OF_CODEWORDS-1,e.MIN_ROWS_IN_BARCODE=3,e.MAX_ROWS_IN_BARCODE=90,e.MODULES_IN_CODEWORD=17,e.MODULES_IN_STOP_PATTERN=18,e.BARS_IN_MODULE=8,e.EMPTY_INT_ARRAY=new Int32Array([]),e
vendor: 18,272 bytes, line 927
927.SYMBOL_TABLE=Int32Array.from([66142,66170,66206,66236,66290,66292,66350,66382,66396,66454,66470,66476,66594,66600,66614,66626,66628,66632,66640,66654,66662,66668,66682,66690,66718,66720,66748,66758,66776,66798,66802,66804,66820,66824,66832,66846,66848,66876,66880,66936,66950,66956,66968,66992,67006,67022,67036,67042,67044,67048,67062,67118,67150,67164,67214,67228,67256,67294,67322,67350,67366,67372,67398,67404,67416,67438,67474,67476,67490,67492,67496,67510,67618,67624,67650,67656,67664,67678,67686,67692,67706,67714,67716,67728,67742,67744,67772,67782,67788,67800,67822,67826,67828,67842,67848,67870,67872,67900,67904,67960,67974,67992,68016,68030,68046,68060,68066,68068,68072,68086,68104,68112,68126,68128,68156,68160,68216,68336,68358,68364,68376,68400,68414,68448,68476,68494,68508,68536,68546,68548,68552,68560,68574,68582,68588,68654,68686,68700,68706,68708,68712,68726,68750,68764,68792,68802,68804,68808,68816,68830,68838,68844,68858,68878,68892,68920,68976,68990,68994,68996,69e3,69008,69022,69024,69052,69062,69068,69080,69102,69106,69108,69142,69158,69164,69190,69208,69230,69254,69260,69272,69296,69310,69326,69340,69386,69394,69396,69410,69416,69430,69442,69444,69448,69456,69470,69478,69484,69554,69556,69666,69672,69698,69704,69712,69726,69754,69762,69764,69776,69790,69792,69820,69830,69836,69848,69870,69874,69876,69890,69918,69920,69948,69952,70008,70022,70040,70064,70078,70094,70108,70114,70116,70120,70134,70152,70174,70176,70264,70384,70412,70448,70462,70496,70524,70542,70556,70584,70594,70600,70608,70622,70630,70636,70664,70672,70686,70688,70716,70720,70776,70896,71136,71180,71192,71216,71230,71264,71292,71360,71416,71452,71480,71536,71550,71554,71556,71560,71568,71582,71584,71612,71622,71628,71640,71662,71726,71732,71758,71772,71778,71780,71784,71798,71822,71836,71864,71874,71880,71888,71902,71910,71916,71930,71950,71964,71992,72048,72062,72066,72068,72080,72094,72096,72124,72134,72140,72152,72174,72178,72180,72206,72220,72248,72304,72318,72416,72444,72456,72464,72478,72480,72508,72512,72568,72588,72600,72624,72638,72654,72668,72674,72676,72680,72694,72726,72742,72748,72774,72780,72792,72814,72838,72856,72880,72894,72910,72924,72930,72932,72936,72950,72966,72972,72984,73008,73022,73056,73084,73102,73116,73144,73156,73160,73168,73182,73190,73196,73210,73226,73234,73236,73250,73252,73256,73270,73282,73284,73296,73310,73318,73324,73346,73348,73352,73360,73374,73376,73404,73414,73420,73432,73454,73498,73518,73522,73524,73550,73564,73570,73572,73576,73590,73800,73822,73858,73860,73872,73886,73888,73916,73944,73970,73972,73992,74014,74016,74044,74048,74104,74118,74136,74160,74174,74210,74212,74216,74230,74244,74256,74270,74272,74360,74480,74502,74508,74544,74558,74592,74620,74638,74652,74680,74690,74696,74704,74726,74732,74782,74784,74812,74992,75232,75288,75326,75360,75388,75456,75512,75576,75632,75646,75650,75652,75664,75678,75680,75708,75718,75724,75736,75758,75808,75836,75840,75896,76016,76256,76736,76824,76848,76862,76896,76924,76992,77048,77296,77340,77368,77424,77438,77536,77564,77572,77576,77584,77600,77628,77632,77688,77702,77708,77720,77744,77758,77774,77788,77870,77902,77916,77922,77928,77966,77980,78008,78018,78024,78032,78046,78060,78074,78094,78136,78192,78206,78210,78212,78224,78238,78240,78268,78278,78284,78296,78322,78324,78350,78364,78448,78462,78560,78588,78600,78622,78624,78652,78656,78712,78726,78744,78768,78782,78798,78812,78818,78820,78824,78838,78862,78876,78904,78960,78974,79072,79100,79296,79352,79368,79376,79390,79392,79420,79424,79480,79600,79628,79640,79664,79678,79712,79740,79772,79800,79810,79812,79816,79824,79838,79846,79852,79894,79910,79916,79942,79948,79960,79982,79988,80006,80024,80048,80062,80078,80092,80098,80100,80104,80134,80140,80176,80190,80224,80252,80270,80284,80312,80328,80336,80350,80358,80364,80378,80390,80396,80408,80432,80446,80480,80508,80576,80632,80654,80668,80696,80752,80766,80776,80784,80798,80800,80828,80844,80856,80878,80882,80884,80914,80916,80930,80932,80936,80950,80962,80968,80976,80990,80998,81004,81026,81028,81040,81054,81056,81084,81094,81100,81112,81134,81154,81156,81160,81168,81182,81184,81212,81216,81272,81286,81292,81304,81328,81342,81358,81372,81380,81384,81398,81434,81454,81458,81460,81486,81500,81506,81508,81512,81526,81550,81564,81592,81602,81604,81608,81616,81630,81638,81644,81702,81708,81722,81734,81740,81752,81774,81778,81780,82050,82078,82080,82108,82180,82184,82192,82206,82208,82236,82240,82296,82316,82328,82352,82366,82402,82404,82408,82440,82448,82462,82464,82492,82496,82552,82672,82694,82700,82712,82736,82750,82784,82812,82830,82882,82884,82888,82896,82918,82924,82952,82960,82974,82976,83004,83008,83064,83184,83424,83468,83480,83504,83518,83552,83580,83648,83704,83740,83768,83824,83838,83842,83844,83848,83856,83872,83900,83910,83916,83928,83950,83984,84e3,84028,84032,84088,84208,84448,84928,85040,85054,85088,85116,85184,85240,85488,85560,85616,85630,85728,85756,85764,85768,85776,85790,85792,85820,85824,85880,85894,85900,85912,85936,85966,85980,86048,86080,86136,86256,86496,86976,88160,88188,88256,88312,88560,89056,89200,89214,89312,89340,89536,89592,89608,89616,89632,89664,89720,89840,89868,89880,89904,89952,89980,89998,90012,90040,90190,90204,90254,90268,90296,90306,90308,90312,90334,90382,90396,90424,90480,90494,90500,90504,90512,90526,90528,90556,90566,90572,90584,90610,90612,90638,90652,90680,90736,90750,90848,90876,90884,90888,90896,90910,90912,90940,90944,91e3,91014,91020,91032,91056,91070,91086,91100,91106,91108,91112,91126,91150,91164,91192,91248,91262,91360,91388,91584,91640,91664,91678,91680,91708,91712,91768,91888,91928,91952,91966,92e3,92028,92046,92060,92088,92098,92100,92104,92112,92126,92134,92140,92188,92216,92272,92384,92412,92608,92664,93168,93200,93214,93216,93244,93248,93304,93424,93664,93720,93744,93758,93792,93820,93888,93944,93980,94008,94064,94078,94084,94088,94096,94110,94112,94140,94150,94156,94168,94246,94252,94278,94284,94296,94318,94342,94348,94360,94384,94398,94414,94428,94440,94470,94476,94488,94512,94526,94560,94588,94606,94620,94648,94658,94660,94664,94672,94686,94694,94700,94714,94726,94732,94744,94768,94782,94816,94844,94912,94968,94990,95004,95032,95088,95102,95112,95120,95134,95136,95164,95180,95192,95214,95218,95220,95244,95256,95280,95294,95328,95356,95424,95480,95728,95758,95772,95800,95856,95870,95968,95996,96008,96016,96030,96032,96060,96064,96120,96152,96176,96190,96220,96226,96228,96232,96290,96292,96296,96310,96322,96324,96328,96336,96350,96358,96364,96386,96388,96392,96400,96414,96416,96444,96454,96460,96472,96494,96498,96500,96514,96516,96520,96528,96542,96544,96572,96576,96632,96646,96652,96664,96688,96702,96718,96732,96738,96740,96744,96758,96772,96776,96784,96798,96800,96828,96832,96888,97008,97030,97036,97048,97072,97086,97120,97148,97166,97180,97208,97220,97224,97232,97246,97254,97260,97326,97330,97332,97358,97372,97378,97380,97384,97398,97422,97436,97464,97474,97476,97480,97488,97502,97510,97516,97550,97564,97592,97648,97666,97668,97672,97680,97694,97696,97724,97734,97740,97752,97774,97830,97836,97850,97862,97868,97880,97902,97906,97908,97926,97932,97944,97968,97998,98012,98018,98020,98024,98038,98618,98674,98676,98838,98854,98874,98892,98904,98926,98930,98932,98968,99006,99042,99044,99048,99062,99166,99194,99246,99286,99350,99366,99372,99386,99398,99416,99438,99442,99444,99462,99504,99518,99534,99548,99554,99556,99560,99574,99590,99596,99608,99632,99646,99680,99708,99726,99740,99768,99778,99780,99784,99792,99806,99814,99820,99834,99858,99860,99874,99880,99894,99906,99920,99934,99962,99970,99972,99976,99984,99998,1e5,100028,100038,100044,100056,100078,100082,100084,100142,100174,100188,100246,100262,100268,100306,100308,100390,100396,100410,100422,100428,100440,100462,100466,100468,100486,100504,100528,100542,100558,100572,100578,100580,100584,100598,100620,100656,100670,100704,100732,100750,100792,100802,100808,100816,100830,100838,100844,100858,100888,100912,100926,100960,100988,101056,101112,101148,101176,101232,101246,101250,101252,101256,101264,101278,101280,101308,101318,101324,101336,101358,101362,101364,101410,101412,101416,101430,101442,101448,101456,101470,101478,101498,101506,101508,101520,101534,101536,101564,101580,101618,101620,101636,101640,101648,101662,101664,101692,101696,101752,101766,101784,101838,101858,101860,101864,101934,101938,101940,101966,101980,101986,101988,101992,102030,102044,102072,102082,102084,102088,102096,102138,102166,102182,102188,102214,102220,102232,102254,102282,102290,102292,102306,102308,102312,102326,102444,102458,102470,102476,102488,102514,102516,102534,102552,102576,102590,102606,102620,102626,102632,102646,102662,102668,102704,102718,102752,102780,102798,102812,102840,102850,102856,102864,102878,102886,102892,102906,102936,102974,103008,103036,103104,103160,103224,103280,103294,103298,103300,103312,103326,103328,103356,103366,103372,103384,103406,103410,103412,103472,103486,103520,103548,103616,103672,103920,103992,104048,104062,104160,104188,104194,104196,104200,104208,104224,104252,104256,104312,104326,104332,104344,104368,104382,104398,104412,104418,104420,104424,104482,104484,104514,104520,104528,104542,104550,104570,104578,104580,104592,104606,104608,104636,104652,104690,104692,104706,104712,104734,104736,104764,104768,104824,104838,104856,104910,104930,104932,104936,104968,104976,104990,104992,105020,105024,105080,105200,105240,105278,105312,105372,105410,105412,105416,105424,105446,105518,105524,105550,105564,105570,105572,105576,105614,105628,105656,105666,105672,105680,105702,105722,105742,105756,105784,105840,105854,105858,105860,105864,105872,105888,105932,105970,105972,106006,106022,106028,106054,106060,106072,106100,106118,106124,106136,106160,106174,106190,106210,106212,106216,106250,106258,106260,106274,106276,106280,106306,106308,106312,106320,106334,106348,106394,106414,106418,106420,106566,106572,106610,106612,106630,106636,106648,106672,106686,106722,106724,106728,106742,106758,106764,106776,106800,106814,106848,106876,106894,106908,106936,106946,106948,106952,106960,106974,106982,106988,107032,107056,107070,107104,107132,107200,107256,107292,107320,107376,107390,107394,107396,107400,107408,107422,107424,107452,107462,107468,107480,107502,107506,107508,107544,107568,107582,107616,107644,107712,107768,108016,108060,108088,108144,108158,108256,108284,108290,108292,108296,108304,108318,108320,108348,108352,108408,108422,108428,108440,108464,108478,108494,108508,108514,108516,108520,108592,108640,108668,108736,108792,109040,109536,109680,109694,109792,109820,110016,110072,110084,110088,110096,110112,110140,110144,110200,110320,110342,110348,110360,110384,110398,110432,110460,110478,110492,110520,110532,110536,110544,110558,110658,110686,110714,110722,110724,110728,110736,110750,110752,110780,110796,110834,110836,110850,110852,110856,110864,110878,110880,110908,110912,110968,110982,111e3,111054,111074,111076,111080,111108,111112,111120,111134,111136,111164,111168,111224,111344,111372,111422,111456,111516,111554,111556,111560,111568,111590,111632,111646,111648,111676,111680,111736,111856,112096,112152,112224,112252,112320,112440,112514,112516,112520,112528,112542,112544,112588,112686,112718,112732,112782,112796,112824,112834,112836,112840,112848,112870,112890,112910,112924,112952,113008,113022,113026,113028,113032,113040,113054,113056,113100,113138,113140,113166,113180,113208,113264,113278,113376,113404,113416,113424,113440,113468,113472,113560,113614,113634,113636,113640,113686,113702,113708,113734,113740,113752,113778,113780,113798,113804,113816,113840,113854,113870,113890,113892,113896,113926,113932,113944,113968,113982,114016,114044,114076,114114,114116,114120,114128,114150,114170,114194,114196,114210,114212,114216,114242,114244,114248,114256,114270,114278,114306,114308,114312,114320,114334,114336,114364,114380,114420,114458,114478,114482,114484,114510,114524,114530,114532,114536,114842,114866,114868,114970,114994,114996,115042,115044,115048,115062,115130,115226,115250,115252,115278,115292,115298,115300,115304,115318,115342,115394,115396,115400,115408,115422,115430,115436,115450,115478,115494,115514,115526,115532,115570,115572,115738,115758,115762,115764,115790,115804,115810,115812,115816,115830,115854,115868,115896,115906,115912,115920,115934,115942,115948,115962,115996,116024,116080,116094,116098,116100,116104,116112,116126,116128,116156,116166,116172,116184,116206,116210,116212,116246,116262,116268,116282,116294,116300,116312,116334,116338,116340,116358,116364,116376,116400,116414,116430,116444,116450,116452,116456,116498,116500,116514,116520,116534,116546,116548,116552,116560,116574,116582,116588,116602,116654,116694,116714,116762,116782,116786,116788,116814,116828,116834,116836,116840,116854,116878,116892,116920,116930,116936,116944,116958,116966,116972,116986,117006,117048,117104,117118,117122,117124,117136,117150,117152,117180,117190,117196,117208,117230,117234,117236,117304,117360,117374,117472,117500,117506,117508,117512,117520,117536,117564,117568,117624,117638,117644,117656,117680,117694,117710,117724,117730,117732,117736,117750,117782,117798,117804,117818,117830,117848,117874,117876,117894,117936,117950,117966,117986,117988,117992,118022,118028,118040,118064,118078,118112,118140,118172,118210,118212,118216,118224,118238,118246,118266,118306,118312,118338,118352,118366,118374,118394,118402,118404,118408,118416,118430,118432,118460,118476,118514,118516,118574,118578,118580,118606,118620,118626,118628,118632,118678,118694,118700,118730,118738,118740,118830,118834,118836,118862,118876,118882,118884,118888,118902,118926,118940,118968,118978,118980,118984,118992,119006,119014,119020,119034,119068,119096,119152,119166,119170,119172,119176,119184,119198,119200,119228,119238,119244,119256,119278,119282,119284,119324,119352,119408,119422,119520,119548,119554,119556,119560,119568,119582,119584,119612,119616,119672,119686,119692,119704,119728,119742,119758,119772,119778,119780,119784,119798,119920,119934,120032,120060,120256,120312,120324,120328,120336,120352,120384,120440,120560,120582,120588,120600,120624,120638,120672,120700,120718,120732,120760,120770,120772,120776,120784,120798,120806,120812,120870,120876,120890,120902,120908,120920,120946,120948,120966,120972,120984,121008,121022,121038,121058,121060,121064,121078,121100,121112,121136,121150,121184,121212,121244,121282,121284,121288,121296,121318,121338,121356,121368,121392,121406,121440,121468,121536,121592,121656,121730,121732,121736,121744,121758,121760,121804,121842,121844,121890,121922,121924,121928,121936,121950,121958,121978,121986,121988,121992,122e3,122014,122016,122044,122060,122098,122100,122116,122120,122128,122142,122144,122172,122176,122232,122246,122264,122318,122338,122340,122344,122414,122418,122420,122446,122460,122466,122468,122472,122510,122524,122552,122562,122564,122568,122576,122598,122618,122646,122662,122668,122694,122700,122712,122738,122740,122762,122770,122772,122786,122788,122792,123018,123026,123028,123042,123044,123048,123062,123098,123146,123154,123156,123170,123172,123176,123190,123202,123204,123208,123216,123238,123244,123258,123290,123314,123316,123402,123410,123412,123426,123428,123432,123446,123458,123464,123472,123486,123494,123500,123514,123522,123524,123528,123536,123552,123580,123590,123596,123608,123630,123634,123636,123674,123698,123700,123740,123746,123748,123752,123834,123914,123922,123924,123938,123944,123958,123970,123976,123984,123998,124006,124012,124026,124034,124036,124048,124062,124064,124092,124102,124108,124120,124142,124146,124148,124162,124164,124168,124176,124190,124192,124220,124224,124280,124294,124300,124312,124336,124350,124366,124380,124386,124388,124392,124406,124442,124462,124466,124468,124494,124508,124514,124520,124558,124572,124600,124610,124612,124616,124624,124646,124666,124694,124710,124716,124730,124742,124748,124760,124786,124788,124818,124820,124834,124836,124840,124854,124946,124948,124962,124964,124968,124982,124994,124996,125e3,125008,125022,125030,125036,125050,125058,125060,125064,125072,125086,125088,125116,125126,125132,125144,125166,125170,125172,125186,125188,125192,125200,125216,125244,125248,125304,125318,125324,125336,125360,125374,125390,125404,125410,125412,125416,125430,125444,125448,125456,125472,125504,125560,125680,125702,125708,125720,125744,125758,125792,125820,125838,125852,125880,125890,125892,125896,125904,125918,125926,125932,125978,125998,126002,126004,126030,126044,126050,126052,126056,126094,126108,126136,126146,126148,126152,126160,126182,126202,126222,126236,126264,126320,126334,126338,126340,126344,126352,126366,126368,126412,126450,126452,126486,126502,126508,126522,126534,126540,126552,126574,126578,126580,126598,126604,126616,126640,126654,126670,126684,126690,126692,126696,126738,126754,126756,126760,126774,126786,126788,126792,126800,126814,126822,126828,126842,126894,126898,126900,126934,127126,127142,127148,127162,127178,127186,127188,127254,127270,127276,127290,127302,127308,127320,127342,127346,127348,127370,127378,127380,127394,127396,127400,127450,127510,127526,127532,127546,127558,127576,127598,127602,127604,127622,127628,127640,127664,127678,127694,127708,127714,127716,127720,127734,127754,127762,127764,127778,127784,127810,127812,127816,127824,127838,127846,127866,127898,127918,127922,127924,128022,128038,128044,128058,128070,128076,128088,128110,128114,128116,128134,128140,128152,128176,128190,128206,128220,128226,128228,128232,128246,128262,128268,128280,128304,128318,128352,128380,128398,128412,128440,128450,128452,128456,128464,128478,128486,128492,128506,128522,128530,128532,128546,128548,128552,128566,128578,128580,128584,128592,128606,128614,128634,128642,128644,128648,128656,128670,128672,128700,128716,128754,128756,128794,128814,128818,128820,128846,128860,128866,128868,128872,128886,128918,128934,128940,128954,128978,128980,129178,129198,129202,129204,129238,129258,129306,129326,129330,129332,129358,129372,129378,129380,129384,129398,129430,129446,129452,129466,129482,129490,129492,129562,129582,129586,129588,129614,129628,129634,129636,129640,129654,129678,129692,129720,129730,129732,129736,129744,129758,129766,129772,129814,129830,129836,129850,129862,129868,129880,129902,129906,129908,129930,129938,129940,129954,129956,129960,129974,130010]),
927e
vendor: 12,861 bytes, line 927
927.CODEWORD_TABLE=Int32Array.from([2627,1819,2622,2621,1813,1812,2729,2724,2723,2779,2774,2773,902,896,908,868,865,861,859,2511,873,871,1780,835,2493,825,2491,842,837,844,1764,1762,811,810,809,2483,807,2482,806,2480,815,814,813,812,2484,817,816,1745,1744,1742,1746,2655,2637,2635,2626,2625,2623,2628,1820,2752,2739,2737,2728,2727,2725,2730,2785,2783,2778,2777,2775,2780,787,781,747,739,736,2413,754,752,1719,692,689,681,2371,678,2369,700,697,694,703,1688,1686,642,638,2343,631,2341,627,2338,651,646,643,2345,654,652,1652,1650,1647,1654,601,599,2322,596,2321,594,2319,2317,611,610,608,606,2324,603,2323,615,614,612,1617,1616,1614,1612,616,1619,1618,2575,2538,2536,905,901,898,909,2509,2507,2504,870,867,864,860,2512,875,872,1781,2490,2489,2487,2485,1748,836,834,832,830,2494,827,2492,843,841,839,845,1765,1763,2701,2676,2674,2653,2648,2656,2634,2633,2631,2629,1821,2638,2636,2770,2763,2761,2750,2745,2753,2736,2735,2733,2731,1848,2740,2738,2786,2784,591,588,576,569,566,2296,1590,537,534,526,2276,522,2274,545,542,539,548,1572,1570,481,2245,466,2242,462,2239,492,485,482,2249,496,494,1534,1531,1528,1538,413,2196,406,2191,2188,425,419,2202,415,2199,432,430,427,1472,1467,1464,433,1476,1474,368,367,2160,365,2159,362,2157,2155,2152,378,377,375,2166,372,2165,369,2162,383,381,379,2168,1419,1418,1416,1414,385,1411,384,1423,1422,1420,1424,2461,802,2441,2439,790,786,783,794,2409,2406,2403,750,742,738,2414,756,753,1720,2367,2365,2362,2359,1663,693,691,684,2373,680,2370,702,699,696,704,1690,1687,2337,2336,2334,2332,1624,2329,1622,640,637,2344,634,2342,630,2340,650,648,645,2346,655,653,1653,1651,1649,1655,2612,2597,2595,2571,2568,2565,2576,2534,2529,2526,1787,2540,2537,907,904,900,910,2503,2502,2500,2498,1768,2495,1767,2510,2508,2506,869,866,863,2513,876,874,1782,2720,2713,2711,2697,2694,2691,2702,2672,2670,2664,1828,2678,2675,2647,2646,2644,2642,1823,2639,1822,2654,2652,2650,2657,2771,1855,2765,2762,1850,1849,2751,2749,2747,2754,353,2148,344,342,336,2142,332,2140,345,1375,1373,306,2130,299,2128,295,2125,319,314,311,2132,1354,1352,1349,1356,262,257,2101,253,2096,2093,274,273,267,2107,263,2104,280,278,275,1316,1311,1308,1320,1318,2052,202,2050,2044,2040,219,2063,212,2060,208,2055,224,221,2066,1260,1258,1252,231,1248,229,1266,1264,1261,1268,155,1998,153,1996,1994,1991,1988,165,164,2007,162,2006,159,2003,2e3,172,171,169,2012,166,2010,1186,1184,1182,1179,175,1176,173,1192,1191,1189,1187,176,1194,1193,2313,2307,2305,592,589,2294,2292,2289,578,572,568,2297,580,1591,2272,2267,2264,1547,538,536,529,2278,525,2275,547,544,541,1574,1571,2237,2235,2229,1493,2225,1489,478,2247,470,2244,465,2241,493,488,484,2250,498,495,1536,1533,1530,1539,2187,2186,2184,2182,1432,2179,1430,2176,1427,414,412,2197,409,2195,405,2193,2190,426,424,421,2203,418,2201,431,429,1473,1471,1469,1466,434,1477,1475,2478,2472,2470,2459,2457,2454,2462,803,2437,2432,2429,1726,2443,2440,792,789,785,2401,2399,2393,1702,2389,1699,2411,2408,2405,745,741,2415,758,755,1721,2358,2357,2355,2353,1661,2350,1660,2347,1657,2368,2366,2364,2361,1666,690,687,2374,683,2372,701,698,705,1691,1689,2619,2617,2610,2608,2605,2613,2593,2588,2585,1803,2599,2596,2563,2561,2555,1797,2551,1795,2573,2570,2567,2577,2525,2524,2522,2520,1786,2517,1785,2514,1783,2535,2533,2531,2528,1788,2541,2539,906,903,911,2721,1844,2715,2712,1838,1836,2699,2696,2693,2703,1827,1826,1824,2673,2671,2669,2666,1829,2679,2677,1858,1857,2772,1854,1853,1851,1856,2766,2764,143,1987,139,1986,135,133,131,1984,128,1983,125,1981,138,137,136,1985,1133,1132,1130,112,110,1974,107,1973,104,1971,1969,122,121,119,117,1977,114,1976,124,1115,1114,1112,1110,1117,1116,84,83,1953,81,1952,78,1950,1948,1945,94,93,91,1959,88,1958,85,1955,99,97,95,1961,1086,1085,1083,1081,1078,100,1090,1089,1087,1091,49,47,1917,44,1915,1913,1910,1907,59,1926,56,1925,53,1922,1919,66,64,1931,61,1929,1042,1040,1038,71,1035,70,1032,68,1048,1047,1045,1043,1050,1049,12,10,1869,1867,1864,1861,21,1880,19,1877,1874,1871,28,1888,25,1886,22,1883,982,980,977,974,32,30,991,989,987,984,34,995,994,992,2151,2150,2147,2146,2144,356,355,354,2149,2139,2138,2136,2134,1359,343,341,338,2143,335,2141,348,347,346,1376,1374,2124,2123,2121,2119,1326,2116,1324,310,308,305,2131,302,2129,298,2127,320,318,316,313,2133,322,321,1355,1353,1351,1357,2092,2091,2089,2087,1276,2084,1274,2081,1271,259,2102,256,2100,252,2098,2095,272,269,2108,266,2106,281,279,277,1317,1315,1313,1310,282,1321,1319,2039,2037,2035,2032,1203,2029,1200,1197,207,2053,205,2051,201,2049,2046,2043,220,218,2064,215,2062,211,2059,228,226,223,2069,1259,1257,1254,232,1251,230,1267,1265,1263,2316,2315,2312,2311,2309,2314,2304,2303,2301,2299,1593,2308,2306,590,2288,2287,2285,2283,1578,2280,1577,2295,2293,2291,579,577,574,571,2298,582,581,1592,2263,2262,2260,2258,1545,2255,1544,2252,1541,2273,2271,2269,2266,1550,535,532,2279,528,2277,546,543,549,1575,1573,2224,2222,2220,1486,2217,1485,2214,1482,1479,2238,2236,2234,2231,1496,2228,1492,480,477,2248,473,2246,469,2243,490,487,2251,497,1537,1535,1532,2477,2476,2474,2479,2469,2468,2466,2464,1730,2473,2471,2453,2452,2450,2448,1729,2445,1728,2460,2458,2456,2463,805,804,2428,2427,2425,2423,1725,2420,1724,2417,1722,2438,2436,2434,2431,1727,2444,2442,793,791,788,795,2388,2386,2384,1697,2381,1696,2378,1694,1692,2402,2400,2398,2395,1703,2392,1701,2412,2410,2407,751,748,744,2416,759,757,1807,2620,2618,1806,1805,2611,2609,2607,2614,1802,1801,1799,2594,2592,2590,2587,1804,2600,2598,1794,1793,1791,1789,2564,2562,2560,2557,1798,2554,1796,2574,2572,2569,2578,1847,1846,2722,1843,1842,1840,1845,2716,2714,1835,1834,1832,1830,1839,1837,2700,2698,2695,2704,1817,1811,1810,897,862,1777,829,826,838,1760,1758,808,2481,1741,1740,1738,1743,2624,1818,2726,2776,782,740,737,1715,686,679,695,1682,1680,639,628,2339,647,644,1645,1643,1640,1648,602,600,597,595,2320,593,2318,609,607,604,1611,1610,1608,1606,613,1615,1613,2328,926,924,892,886,899,857,850,2505,1778,824,823,821,819,2488,818,2486,833,831,828,840,1761,1759,2649,2632,2630,2746,2734,2732,2782,2781,570,567,1587,531,527,523,540,1566,1564,476,467,463,2240,486,483,1524,1521,1518,1529,411,403,2192,399,2189,423,416,1462,1457,1454,428,1468,1465,2210,366,363,2158,360,2156,357,2153,376,373,370,2163,1410,1409,1407,1405,382,1402,380,1417,1415,1412,1421,2175,2174,777,774,771,784,732,725,722,2404,743,1716,676,674,668,2363,665,2360,685,1684,1681,626,624,622,2335,620,2333,617,2330,641,635,649,1646,1644,1642,2566,928,925,2530,2527,894,891,888,2501,2499,2496,858,856,854,851,1779,2692,2668,2665,2645,2643,2640,2651,2768,2759,2757,2744,2743,2741,2748,352,1382,340,337,333,1371,1369,307,300,296,2126,315,312,1347,1342,1350,261,258,250,2097,246,2094,271,268,264,1306,1301,1298,276,1312,1309,2115,203,2048,195,2045,191,2041,213,209,2056,1246,1244,1238,225,1234,222,1256,1253,1249,1262,2080,2079,154,1997,150,1995,147,1992,1989,163,160,2004,156,2001,1175,1174,1172,1170,1167,170,1164,167,1185,1183,1180,1177,174,1190,1188,2025,2024,2022,587,586,564,559,556,2290,573,1588,520,518,512,2268,508,2265,530,1568,1565,461,457,2233,450,2230,446,2226,479,471,489,1526,1523,1520,397,395,2185,392,2183,389,2180,2177,410,2194,402,422,1463,1461,1459,1456,1470,2455,799,2433,2430,779,776,773,2397,2394,2390,734,728,724,746,1717,2356,2354,2351,2348,1658,677,675,673,670,667,688,1685,1683,2606,2589,2586,2559,2556,2552,927,2523,2521,2518,2515,1784,2532,895,893,890,2718,2709,2707,2689,2687,2684,2663,2662,2660,2658,1825,2667,2769,1852,2760,2758,142,141,1139,1138,134,132,129,126,1982,1129,1128,1126,1131,113,111,108,105,1972,101,1970,120,118,115,1109,1108,1106,1104,123,1113,1111,82,79,1951,75,1949,72,1946,92,89,86,1956,1077,1076,1074,1072,98,1069,96,1084,1082,1079,1088,1968,1967,48,45,1916,42,1914,39,1911,1908,60,57,54,1923,50,1920,1031,1030,1028,1026,67,1023,65,1020,62,1041,1039,1036,1033,69,1046,1044,1944,1943,1941,11,9,1868,7,1865,1862,1859,20,1878,16,1875,13,1872,970,968,966,963,29,960,26,23,983,981,978,975,33,971,31,990,988,985,1906,1904,1902,993,351,2145,1383,331,330,328,326,2137,323,2135,339,1372,1370,294,293,291,289,2122,286,2120,283,2117,309,303,317,1348,1346,1344,245,244,242,2090,239,2088,236,2085,2082,260,2099,249,270,1307,1305,1303,1300,1314,189,2038,186,2036,183,2033,2030,2026,206,198,2047,194,216,1247,1245,1243,1240,227,1237,1255,2310,2302,2300,2286,2284,2281,565,563,561,558,575,1589,2261,2259,2256,2253,1542,521,519,517,514,2270,511,533,1569,1567,2223,2221,2218,2215,1483,2211,1480,459,456,453,2232,449,474,491,1527,1525,1522,2475,2467,2465,2451,2449,2446,801,800,2426,2424,2421,2418,1723,2435,780,778,775,2387,2385,2382,2379,1695,2375,1693,2396,735,733,730,727,749,1718,2616,2615,2604,2603,2601,2584,2583,2581,2579,1800,2591,2550,2549,2547,2545,1792,2542,1790,2558,929,2719,1841,2710,2708,1833,1831,2690,2688,2686,1815,1809,1808,1774,1756,1754,1737,1736,1734,1739,1816,1711,1676,1674,633,629,1638,1636,1633,1641,598,1605,1604,1602,1600,605,1609,1607,2327,887,853,1775,822,820,1757,1755,1584,524,1560,1558,468,464,1514,1511,1508,1519,408,404,400,1452,1447,1444,417,1458,1455,2208,364,361,358,2154,1401,1400,1398,1396,374,1393,371,1408,1406,1403,1413,2173,2172,772,726,723,1712,672,669,666,682,1678,1675,625,623,621,618,2331,636,632,1639,1637,1635,920,918,884,880,889,849,848,847,846,2497,855,852,1776,2641,2742,2787,1380,334,1367,1365,301,297,1340,1338,1335,1343,255,251,247,1296,1291,1288,265,1302,1299,2113,204,196,192,2042,1232,1230,1224,214,1220,210,1242,1239,1235,1250,2077,2075,151,148,1993,144,1990,1163,1162,1160,1158,1155,161,1152,157,1173,1171,1168,1165,168,1181,1178,2021,2020,2018,2023,585,560,557,1585,516,509,1562,1559,458,447,2227,472,1516,1513,1510,398,396,393,390,2181,386,2178,407,1453,1451,1449,1446,420,1460,2209,769,764,720,712,2391,729,1713,664,663,661,659,2352,656,2349,671,1679,1677,2553,922,919,2519,2516,885,883,881,2685,2661,2659,2767,2756,2755,140,1137,1136,130,127,1125,1124,1122,1127,109,106,102,1103,1102,1100,1098,116,1107,1105,1980,80,76,73,1947,1068,1067,1065,1063,90,1060,87,1075,1073,1070,1080,1966,1965,46,43,40,1912,36,1909,1019,1018,1016,1014,58,1011,55,1008,51,1029,1027,1024,1021,63,1037,1034,1940,1939,1937,1942,8,1866,4,1863,1,1860,956,954,952,949,946,17,14,969,967,964,961,27,957,24,979,976,972,1901,1900,1898,1896,986,1905,1903,350,349,1381,329,327,324,1368,1366,292,290,287,284,2118,304,1341,1339,1337,1345,243,240,237,2086,233,2083,254,1297,1295,1293,1290,1304,2114,190,187,184,2034,180,2031,177,2027,199,1233,1231,1229,1226,217,1223,1241,2078,2076,584,555,554,552,550,2282,562,1586,507,506,504,502,2257,499,2254,515,1563,1561,445,443,441,2219,438,2216,435,2212,460,454,475,1517,1515,1512,2447,798,797,2422,2419,770,768,766,2383,2380,2376,721,719,717,714,731,1714,2602,2582,2580,2548,2546,2543,923,921,2717,2706,2705,2683,2682,2680,1771,1752,1750,1733,1732,1731,1735,1814,1707,1670,1668,1631,1629,1626,1634,1599,1598,1596,1594,1603,1601,2326,1772,1753,1751,1581,1554,1552,1504,1501,1498,1509,1442,1437,1434,401,1448,1445,2206,1392,1391,1389,1387,1384,359,1399,1397,1394,1404,2171,2170,1708,1672,1669,619,1632,1630,1628,1773,1378,1363,1361,1333,1328,1336,1286,1281,1278,248,1292,1289,2111,1218,1216,1210,197,1206,193,1228,1225,1221,1236,2073,2071,1151,1150,1148,1146,152,1143,149,1140,145,1161,1159,1156,1153,158,1169,1166,2017,2016,2014,2019,1582,510,1556,1553,452,448,1506,1500,394,391,387,1443,1441,1439,1436,1450,2207,765,716,713,1709,662,660,657,1673,1671,916,914,879,878,877,882,1135,1134,1121,1120,1118,1123,1097,1096,1094,1092,103,1101,1099,1979,1059,1058,1056,1054,77,1051,74,1066,1064,1061,1071,1964,1963,1007,1006,1004,1002,999,41,996,37,1017,1015,1012,1009,52,1025,1022,1936,1935,1933,1938,942,940,938,935,932,5,2,955,953,950,947,18,943,15,965,962,958,1895,1894,1892,1890,973,1899,1897,1379,325,1364,1362,288,285,1334,1332,1330,241,238,234,1287,1285,1283,1280,1294,2112,188,185,181,178,2028,1219,1217,1215,1212,200,1209,1227,2074,2072,583,553,551,1583,505,503,500,513,1557,1555,444,442,439,436,2213,455,451,1507,1505,1502,796,763,762,760,767,711,710,708,706,2377,718,715,1710,2544,917,915,2681,1627,1597,1595,2325,1769,1749,1747,1499,1438,1435,2204,1390,1388,1385,1395,2169,2167,1704,1665,1662,1625,1623,1620,1770,1329,1282,1279,2109,1214,1207,1222,2068,2065,1149,1147,1144,1141,146,1157,1154,2013,2011,2008,2015,1579,1549,1546,1495,1487,1433,1431,1428,1425,388,1440,2205,1705,658,1667,1664,1119,1095,1093,1978,1057,1055,1052,1062,1962,1960,1005,1003,1e3,997,38,1013,1010,1932,1930,1927,1934,941,939,936,933,6,930,3,951,948,944,1889,1887,1884,1881,959,1893,1891,35,1377,1360,1358,1327,1325,1322,1331,1277,1275,1272,1269,235,1284,2110,1205,1204,1201,1198,182,1195,179,1213,2070,2067,1580,501,1551,1548,440,437,1497,1494,1490,1503,761,709,707,1706,913,912,2198,1386,2164,2161,1621,1766,2103,1208,2058,2054,1145,1142,2005,2002,1999,2009,1488,1429,1426,2200,1698,1659,1656,1975,1053,1957,1954,1001,998,1924,1921,1918,1928,937,934,931,1879,1876,1873,1870,945,1885,1882,1323,1273,1270,2105,1202,1199,1196,1211,2061,2057,1576,1543,1540,1484,1481,1478,1491,1700]),
927e})(),wQe=(function(){function e(t,n){this.bits=t,this.points=n}return e.prototype.getBits=function(){return this.bits},e.prototype.getPoints=function(){return this.points},e})(),_Qe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);
927if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},kQe=(function(){function e(){}return e.detectMultiple=function(t,n,r){var a=t.getBlackMatrix(),i=e.detect(r,a);return i.length||(a=a.clone(),a.rotate180(),i=e.detect(r,a)),new wQe(a,i)},e.detect=function(t,n){for(var r,a,i=new Array,o=0,l=0,c=!1;o<n.getHeight();){var u=e.findVertices(n,o,l);if(u[0]==null&&u[3]==null){if(!c)break;c=!1,l=0;try{for(var d=(r=void 0,_Qe(i)),h=d.next();!h.done;h=d.next()){var f=h.value;f[1]!=null&&(o=Math.trunc(Math.max(o,f[1].getY()))),f[3]!=null&&(o=Math.max(o,Math.trunc(f[3].getY())))}}catch(m){r={error:m}}finally{try{h&&!h.done&&(a=d.return)&&a.call(d)}finally{if(r)throw r.error}}o+=e.ROW_STEP;continue}if(c=!0,i.push(u),!t)break;u[2]!=null?(l=Math.trunc(u[2].getX()),o=Math.trunc(u[2].getY())):(l=Math.trunc(u[4].getX()),o=Math.trunc(u[4].getY()))}return i},e.findVertices=function(t,n,r){var a=t.getHeight(),i=t.getWidth(),o=new Array(8);return e.copyToResult(o,e.findRowsWithPattern(t,a,i,n,r,e.START_PATTERN),e.INDEXES_START_PATTERN),o[4]!=null&&(r=Math.trunc(o[4].getX()),n=Math.trunc(o[4].getY())),e.copyToResult(o,e.findRowsWithPattern(t,a,i,n,r,e.STOP_PATTERN),e.INDEXES_STOP_PATTERN),o},e.copyToResult=function(t,n,r){for(var a=0;a<r.length;a++)t[r[a]]=n[a]},e.findRowsWithPattern=function(t,n,r,a,i,o){for(var l=new Array(4),c=!1,u=new Int32Array(o.length);a<n;a+=e.ROW_STEP){var d=e.findGuardPattern(t,i,a,r,!1,o,u);if(d!=null){for(;a>0;){var h=e.findGuardPattern(t,i,--a,r,!1,o,u);if(h!=null)d=h;else{a++;break}}l[0]=new mt(d[0],a),l[1]=new mt(d[1],a),c=!0;break}}var f=a+1;if(c){for(var m=0,h=Int32Array.from([Math.trunc(l[0].getX()),Math.trunc(l[1].getX())]);f<n;f++){var d=e.findGuardPattern(t,h[0],f,r,!1,o,u);if(d!=null&&Math.abs(h[0]-d[0])<e.MAX_PATTERN_DRIFT&&Math.abs(h[1]-d[1])<e.MAX_PATTERN_DRIFT)h=d,m=0;else{if(m>e.SKIPPED_ROW_COUNT_MAX)break;m++}}f-=m+1,l[2]=new mt(h[0],f),l[3]=new mt(h[1],f)}return f-a<e.BARCODE_MIN_HEIGHT&&is.fill(l,null),l},e.findGuardPattern=function(t,n,r,a,i,o,l){is.fillWithin(l,0,l.length,0);for(var c=n,u=0;t.get(c,r)&&c>0&&u++<e.MAX_PIXEL_DRIFT;)c--;for(var d=c,h=0,f=o.length,m=i;d<a;d++){var x=t.get(d,r);if(x!==m)l[h]++;else{if(h===f-1){if(e.patternMatchVariance(l,o,e.MAX_INDIVIDUAL_VARIANCE)<e.MAX_AVG_VARIANCE)return new Int32Array([c,d]);c+=l[0]+l[1],Fn.arraycopy(l,2,l,0,h-1),l[h-1]=0,l[h]=0,h--}else h++;l[h]=1,m=!m}}return h===f-1&&e.patternMatchVariance(l,o,e.MAX_INDIVIDUAL_VARIANCE)<e.MAX_AVG_VARIANCE?new Int32Array([c,d-1]):null},e.patternMatchVariance=function(t,n,r){for(var a=t.length,i=0,o=0,l=0;l<a;l++)i+=t[l],o+=n[l];if(i<o)return 1/0;var c=i/o;r*=c;for(var u=0,d=0;d<a;d++){var h=t[d],f=n[d]*c,m=h>f?h-f:f-h;if(m>r)return 1/0;u+=m}return u/i},e.INDEXES_START_PATTERN=Int32Array.from([0,4,1,5]),e.INDEXES_STOP_PATTERN=Int32Array.from([6,2,7,3]),e.MAX_AVG_VARIANCE=.42,e.MAX_INDIVIDUAL_VARIANCE=.8,e.START_PATTERN=Int32Array.from([8,1,1,1,1,1,1,3]),e.STOP_PATTERN=Int32Array.from([7,1,1,3,1,1,1,2,1]),e.MAX_PIXEL_DRIFT=3,e.MAX_PATTERN_DRIFT=5,e.SKIPPED_ROW_COUNT_MAX=25,e.ROW_STEP=5,e.BARCODE_MIN_HEIGHT=10,e})(),jQe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},od=(function(){function e(t,n){if(n.length===0)throw new Ct;this.field=t;var r=n.length;if(r>1&&n[0]===0){for(var a=1;a<r&&n[a]===0;)a++;a===r?this.coefficients=new Int32Array([0]):(this.coefficients=new Int32Array(r-a),Fn.arraycopy(n,a,this.coefficients,0,this.coefficients.length))}else this.coefficients=n}return e.prototype.getCoefficients=function(){return this.coefficients},e.prototype.getDegree=function(){return this.coefficients.length-1},e.prototype.isZero=function(){return this.coefficients[0]===0},e.prototype.getCoefficient=function(t){return this.coefficients[this.coefficients.length-1-t]},e.prototype.evaluateAt=function(t){var n,r;if(t===0)return this.getCoefficient(0);if(t===1){var a=0;try{for(var i=jQe(this.coefficients),o=i.next();!o.done;o=i.next()){var l=o.value;a=this.field.add(a,l)}}catch(h){n={error:h}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return a}for(var c=this.coefficients[0],u=this.coefficients.length,d=1;d<u;d++)c=this.field.add(this.field.multiply(t,c),this.coefficients[d]);return c},e.prototype.add=function(t){if(!this.field.equals(t.field))throw new Ct("ModulusPolys do n
927ot have same ModulusGF field");if(this.isZero())return t;if(t.isZero())return this;var n=this.coefficients,r=t.coefficients;if(n.length>r.length){var a=n;n=r,r=a}var i=new Int32Array(r.length),o=r.length-n.length;Fn.arraycopy(r,0,i,0,o);for(var l=o;l<r.length;l++)i[l]=this.field.add(n[l-o],r[l]);return new e(this.field,i)},e.prototype.subtract=function(t){if(!this.field.equals(t.field))throw new Ct("ModulusPolys do not have same ModulusGF field");return t.isZero()?this:this.add(t.negative())},e.prototype.multiply=function(t){return t instanceof e?this.multiplyOther(t):this.multiplyScalar(t)},e.prototype.multiplyOther=function(t){if(!this.field.equals(t.field))throw new Ct("ModulusPolys do not have same ModulusGF field");if(this.isZero()||t.isZero())return new e(this.field,new Int32Array([0]));for(var n=this.coefficients,r=n.length,a=t.coefficients,i=a.length,o=new Int32Array(r+i-1),l=0;l<r;l++)for(var c=n[l],u=0;u<i;u++)o[l+u]=this.field.add(o[l+u],this.field.multiply(c,a[u]));return new e(this.field,o)},e.prototype.negative=function(){for(var t=this.coefficients.length,n=new Int32Array(t),r=0;r<t;r++)n[r]=this.field.subtract(0,this.coefficients[r]);return new e(this.field,n)},e.prototype.multiplyScalar=function(t){if(t===0)return new e(this.field,new Int32Array([0]));if(t===1)return this;for(var n=this.coefficients.length,r=new Int32Array(n),a=0;a<n;a++)r[a]=this.field.multiply(this.coefficients[a],t);return new e(this.field,r)},e.prototype.multiplyByMonomial=function(t,n){if(t<0)throw new Ct;if(n===0)return new e(this.field,new Int32Array([0]));for(var r=this.coefficients.length,a=new Int32Array(r+t),i=0;i<r;i++)a[i]=this.field.multiply(this.coefficients[i],n);return new e(this.field,a)},e.prototype.toString=function(){for(var t=new Kt,n=this.getDegree();n>=0;n--){var r=this.getCoefficient(n);r!==0&&(r<0?(t.append(" - "),r=-r):t.length()>0&&t.append(" + "),(n===0||r!==1)&&t.append(r),n!==0&&(n===1?t.append("x"):(t.append("x^"),t.append(n))))}return t.toString()},e})(),NQe=(function(){function e(){}return e.prototype.add=function(t,n){return(t+n)%this.modulus},e.prototype.subtract=function(t,n){return(this.modulus+t-n)%this.modulus},e.prototype.exp=function(t){return this.expTable[t]},e.prototype.log=function(t){if(t===0)throw new Ct;return this.logTable[t]},e.prototype.inverse=function(t){if(t===0)throw new qG;return this.expTable[this.modulus-this.logTable[t]-1]},e.prototype.multiply=function(t,n){return t===0||n===0?0:this.expTable[(this.logTable[t]+this.logTable[n])%(this.modulus-1)]},e.prototype.getSize=function(){return this.modulus},e.prototype.equals=function(t){return t===this},e})(),SQe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),CQe=(function(e){SQe(t,e);function t(n,r){var a=e.call(this)||this;a.modulus=n,a.expTable=new Int32Array(n),a.logTable=new Int32Array(n);for(var i=1,o=0;o<n;o++)a.expTable[o]=i,i=i*r%n;for(var o=0;o<n-1;o++)a.logTable[a.expTable[o]]=o;return a.zero=new od(a,new Int32Array([0])),a.one=new od(a,new Int32Array([1])),a}return t.prototype.getZero=function(){return this.zero},t.prototype.getOne=function(){return this.one},t.prototype.buildMonomial=function(n,r){if(n<0)throw new Ct;if(r===0)return this.zero;var a=new Int32Array(n+1);return a[0]=r,new od(this,a)},t.PDF417_GF=new t(dn.NUMBER_OF_CODEWORDS,3),t})(NQe),EQe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},AQe=(function(){function e(){this.field=CQe.PDF417_GF}return e.prototype.decode=function(t,n,r){for(var a,i,o=new od(this.field,t),l=new Int32Array(n),c=!1,u=n;u>0;u--){var d=o.evaluateAt(this.field.exp(u));l[n-u]=d,d!==0&&(c=!0)}if(!c)return 0;var h=this.field.getOne();if(r!=null)try{for(var f=EQe(r),m=f.next();!m.done;m=f.next()){var x=m.value,g=this.field.exp(t.length-1-x),y=new od(this.field,new Int32Array([this.field.subtract(0,g),1]));h=h.multiply(y)}}catch(E){a={error:E}}finally{try{m&&!m.done&&(i=f.return)&&i.call(f)}finally{if(a)throw a.error}}for(var b=new od(this.field,l),v=this.runEuclideanAlgorithm(this.field.buildMonomial(n,1),b,n),w=v[0],_=v[1],k=this.findErrorLocations(w),j=this.findErrorMagnitudes(_,w,k),u=0;u<k.length;u++){var N=t.length-1-this.field.log(k[u]);if(N<0)throw Yr.getChecksumInstance();t[N]=this.field.subtract(t[N],j[u])}return k.length},e.prototype.runEuclideanAlgorithm=function(t,n,r){if(t.getDegree()<n.getDegree()){var a=t;t=n,n=a}for(var i=t,o=n,l=this.field.getZero(),c=this.field.getOne();o.getDegree()>=Math.round(r/2);){var u=i,d=l;if(i=o,l=c,i.isZero())throw Yr.getChecksumInstance();o=u;for(var h=this.field.getZero(),f=i.getCoefficient(i.getDegree()),m=this.field.inverse(f);o.getDegree()>=i.getDegree()&&!o.isZero();){var x=o.getDegree()-i.getDegree(),g=this.field.multiply(o.getCoefficient(o.getDegree()),m);h=h.add(this.field.buildMonomial(x,g)),o=o.subtract(i.multiplyByMonomial(x,g))}c=h.multiply(l).subtract(d).negative()}var y=c.getCoefficient(0);if(y===0)throw Yr.getChecksumInstance();var b=this.field.inverse(y),v=c.multiply(b),w=o.multiply(b);return[v,w]},e.prototype.findErrorLocations=function(t){for(var n=t.getDegree(),r=new Int32Array(n),a=0,i=1;i<this.field.getSize()&&a<n;i++)t.evaluateAt(i)===0&&(r[a]=this.field.inverse(i),a++);if(a!==n)throw Yr.getChecksumInstance();return r},e.prototype.findErrorMagnitudes=function(t,n,r){for(var a=n.getDegree(),i=new Int32Array(a),o=1;o<=a;o++)i[a-o]=this.field.multiply(o,n.getCoefficient(o));for(var l=new od(this.field,i),c=r.length,u=new Int32Array(c),o=0;o<c;o++){var d=this.field.inverse(r[o]),h=this.field.subtract(0,t.evaluateAt(d)),f=this.field.inverse(l.evaluateAt(d));u[o]=this.field.multiply(h,f)}return u},e})(),h2=(function(){function e(t,n,r,a,i){t instanceof e?this.constructor_2(t):this.constructor_1(t,n,r,a,i)}return e.prototype.constructor_1=function(t,n,r,a,i){var o=n==null||r==null,l=a==null||i==null;if(o&&l)throw new Oe;o?(n=new mt(0,a.getY()),r=new mt(0,i.getY())):l&&(a=new mt(t.getWidth()-1,n.getY()),i=new mt(t.getWidth()-1,r.getY())),this.image=t,this.topLeft=n,this.bottomLeft=r,this.topRight=a,this.bottomRight=i,this.minX=Math.trunc(Math.min(n.getX(),r.getX())),this.maxX=Math.trunc(Math.max(a.getX(),i.getX())),this.minY=Math.trunc(Math.min(n.getY(),a.getY())),this.maxY=Math.trunc(Math.max(r.getY(),i.getY()))},e.prototype.constructor_2=function(t){this.image=t.image,this.topLeft=t.getTopLeft(),this.bottomLeft=t.getBottomLeft(),this.topRight=t.getTopRight(),this.bottomRight=t.getBottomRight(),this.minX=t.getMinX(),this.maxX=t.getMaxX(),this.minY=t.getMinY(),this.maxY=t.getMaxY()},e.merge=function(t,n){return t==null?n:n==null?t:new e(t.image,t.topLeft,t.bottomLeft,n.topRight,n.bottomRight)},e.prototype.addMissingRows=function(t,n,r){var a=this.topLeft,i=this.bottomLeft,o=this.topRight,l=this.bottomRight;if(t>0){var c=r?this.topLeft:this.topRight,u=Math.trunc(c.getY()-t);u<0&&(u=0);var d=new mt(c.getX(),u);r?a=d:o=d}if(n>0){var h=r?this.bottomLeft:this.bottomRight,f=Math.trunc(h.getY()+n);f>=this.image.getHeight()&&(f=this.image.getHeight()-1);var m=new mt(h.getX(),f);r?i=m:l=m}return new e(this.image,a,i,o,l)},e.prototype.getMinX=function(){return this.minX},e.prototype.getMaxX=function(){return this.maxX},e.prototype.getMinY=function(){return this.minY},e.prototype.getMaxY=function(){return this.maxY},e.prototype.getTopLeft=function(){return this.topLeft},e.prototype.getTopRight=function(){return this.topRight},e.prototype.getBottomLeft=function(){return this.bottomLeft},e.prototype.getBottomRight=function(){return this.bottomRight},e})(),TQe=(function(){function e(t,n,r,a){this.columnCount=t,this.errorCorrectionLevel=a,this.rowCountUpperPart=n,this.rowCountLowerPart=r,this.rowCount=n+r}return e.prototype.getColumnCount=function(){return this.columnCount},e.prototype.getErrorCorrectionLevel=function(){return this.errorCorrectionLevel},e.prototype.getRowCount=function(){return this.rowCount},e.prototype.getRowCountUpperPart=function(){return this.rowCountUpperPart},e.prototype.getRowCountLowerPart=function(){return this.rowCountLowerPart},e})(),lT=(function(){function e(){this.buffer=""}return e.form=function(t,n){var r=-1;function a(o,l,c,u,d,h){if(o==="%%")return"%";if(n[++r]!==void 0){o=u?parseInt(u.substr(1)):void 0;var f=d?parseInt(d.substr(1)):void 0,m;switch(h){case"s":m=n[r];break;case"c":m=n[r][0];break;case"f":m=parseFloat(n[r]).toFixed(o);break;case"p":m=parseFloat(n[r]).toPrecision(o);break;case"e":m=parseFloat(n[r]).toExponential(o);break;case"x":m=parseInt(n[r]).toString(f||16);break;case"d":m=parseFloat(parseInt(n[r],f||10).toPrecision(o)).toFixed(0);break}m=typeof m=="object"?JSON.stringify(m):(+m).toString(f);for(var x=parseInt(c),g=c&&c[0]+""=="0"?"0":" ";m.length<x;)m=l!==void 0?m+g:g+m;return m}}var i=/%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;return t.replace(i,a)},e.prototype.format=function(t){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];this.buffer+=e.form(t,n)},e.prototype.toString=function(){return this.buffer},e})(),OQe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);
927if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},eY=(function(){function e(t){this.boundingBox=new h2(t),this.codewords=new Array(t.getMaxY()-t.getMinY()+1)}return e.prototype.getCodewordNearby=function(t){var n=this.getCodeword(t);if(n!=null)return n;for(var r=1;r<e.MAX_NEARBY_DISTANCE;r++){var a=this.imageRowToCodewordIndex(t)-r;if(a>=0&&(n=this.codewords[a],n!=null)||(a=this.imageRowToCodewordIndex(t)+r,a<this.codewords.length&&(n=this.codewords[a],n!=null)))return n}return null},e.prototype.imageRowToCodewordIndex=function(t){return t-this.boundingBox.getMinY()},e.prototype.setCodeword=function(t,n){this.codewords[this.imageRowToCodewordIndex(t)]=n},e.prototype.getCodeword=function(t){return this.codewords[this.imageRowToCodewordIndex(t)]},e.prototype.getBoundingBox=function(){return this.boundingBox},e.prototype.getCodewords=function(){return this.codewords},e.prototype.toString=function(){var t,n,r=new lT,a=0;try{for(var i=OQe(this.codewords),o=i.next();!o.done;o=i.next()){var l=o.value;if(l==null){r.format("%3d: | %n",a++);continue}r.format("%3d: %3d|%3d%n",a++,l.getRowNumber(),l.getValue())}}catch(c){t={error:c}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(t)throw t.error}}return r.toString()},e.MAX_NEARBY_DISTANCE=5,e})(),IQe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},PQe=function(e,t){var n=typeof Symbol=="function"&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),a,i=[],o;try{for(;(t===void 0||t-- >0)&&!(a=r.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i},Km=(function(){function e(){this.values=new Map}return e.prototype.setValue=function(t){t=Math.trunc(t);var n=this.values.get(t);n==null&&(n=0),n++,this.values.set(t,n)},e.prototype.getValue=function(){var t,n,r=-1,a=new Array,i=function(h,f){var m={getKey:function(){return h},getValue:function(){return f}};m.getValue()>r?(r=m.getValue(),a=[],a.push(m.getKey())):m.getValue()===r&&a.push(m.getKey())};try{for(var o=IQe(this.values.entries()),l=o.next();!l.done;l=o.next()){var c=PQe(l.value,2),u=c[0],d=c[1];i(u,d)}}catch(h){t={error:h}}finally{try{l&&!l.done&&(n=o.return)&&n.call(o)}finally{if(t)throw t.error}}return dn.toIntArray(a)},e.prototype.getConfidence=function(t){return this.values.get(t)},e})(),RQe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),$j=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},E8=(function(e){RQe(t,e);function t(n,r){var a=e.call(this,n)||this;return a._isLeft=r,a}return t.prototype.setRowNumbers=function(){var n,r;try{for(var a=$j(this.getCodewords()),i=a.next();!i.done;i=a.next()){var o=i.value;o!=null&&o.setRowNumberAsRowIndicatorColumn()}}catch(l){n={error:l}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}},t.prototype.adjustCompleteIndicatorColumnRowNumbers=function(n){var r=this.getCodewords();this.setRowNumbers(),this.removeIncorrectCodewords(r,n);for(var a=this.getBoundingBox(),i=this._isLeft?a.getTopLeft():a.getTopRight(),o=this._isLeft?a.getBottomLeft():a.getBottomRight(),l=this.imageRowToCodewordIndex(Math.trunc(i.getY())),c=this.imageRowToCodewordIndex(Math.trunc(o.getY())),u=-1,d=1,h=0,f=l;f<c;f++)if(r[f]!=null){var m=r[f],x=m.getRowNumber()-u;if(x===0)h++;else if(x===1)d=Math.max(d,h),h=1,u=m.getRowNumber();else if(x<0||m.getRowNumber()>=n.getRowCount()||x>f)r[f]=null;else{var g=void 0;d>2?g=(d-2)*x:g=x;for(var y=g>=f,b=1;b<=g&&!y;b++)y=r[f-b]!=null;y?r[f]=null:(u=m.getRowNumber(),h=1)}}},t.prototype.getRowHeights=function(){var n,r,a=this.getBarcodeMetadata();if(a==null)return null;this.adjustIncompleteIndicatorColumnRowNumbers(a);var i=new Int32Array(a.getRowCount());try{for(var o=$j(this.getCodewords()),l=o.next();!l.done;l=o.next()){var c=l.value;if(c!=null){var u=c.getRowNumber();if(u>=i.length)continue;i[u]++}}}catch(d){n={error:d}}finally{try{l&&!l.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}return i},t.prototype.adjustIncompleteIndicatorColumnRowNumbers=function(n){for(var r=this.getBoundingBox(),a=this._isLeft?r.getTopLeft():r.getTopRight(),i=this._isLeft?r.getBottomLeft():r.getBottomRight(),o=this.imageRowToCodewordIndex(Math.trunc(a.getY())),l=this.imageRowToCodewordIndex(Math.trunc(i.getY())),c=this.getCodewords(),u=-1,d=o;d<l;d++)if(c[d]!=null){var h=c[d];h.setRowNumberAsRowIndicatorColumn();var f=h.getRowNumber()-u;f===0||(f===1?u=h.getRowNumber():h.getRowNumber()>=n.getRowCount()?c[d]=null:u=h.getRowNumber())}},t.prototype.getBarcodeMetadata=function(){var n,r,a=this.getCodewords(),i=new Km,o=new Km,l=new Km,c=new Km;try{for(var u=$j(a),d=u.next();!d.done;d=u.next()){var h=d.value;if(h!=null){h.setRowNumberAsRowIndicatorColumn();var f=h.getValue()%30,m=h.getRowNumber();switch(this._isLeft||(m+=2),m%3){case 0:o.setValue(f*3+1);break;case 1:c.setValue(f/3),l.setValue(f%3);break;case 2:i.setValue(f+1);break}}}}catch(g){n={error:g}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}if(i.getValue().length===0||o.getValue().length===0||l.getValue().length===0||c.getValue().length===0||i.getValue()[0]<1||o.getValue()[0]+l.getValue()[0]<dn.MIN_ROWS_IN_BARCODE||o.getValue()[0]+l.getValue()[0]>dn.MAX_ROWS_IN_BARCODE)return null;var x=new TQe(i.getValue()[0],o.getValue()[0],l.getValue()[0],c.getValue()[0]);return this.removeIncorrectCodewords(a,x),x},t.prototype.removeIncorrectCodewords=function(n,r){for(var a=0;a<n.length;a++){var i=n[a];if(n[a]!=null){var o=i.getValue()%30,l=i.getRowNumber();if(l>r.getRowCount()){n[a]=null;continue}switch(this._isLeft||(l+=2),l%3){case 0:o*3+1!==r.getRowCountUpperPart()&&(n[a]=null);break;case 1:(Math.trunc(o/3)!==r.getErrorCorrectionLevel()||o%3!==r.getRowCountLowerPart())&&(n[a]=null);break;case 2:o+1!==r.getColumnCount()&&(n[a]=null);break}}}},t.prototype.isLeft=function(){return this._isLeft},t.prototype.toString=function(){return"IsLeft: "+this._isLeft+` 928`+e.prototype.toString.call(this)},t})(eY),DQe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);
928if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},MQe=(function(){function e(t,n){this.ADJUST_ROW_NUMBER_SKIP=2,this.barcodeMetadata=t,this.barcodeColumnCount=t.getColumnCount(),this.boundingBox=n,this.detectionResultColumns=new Array(this.barcodeColumnCount+2)}return e.prototype.getDetectionResultColumns=function(){this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[0]),this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[this.barcodeColumnCount+1]);var t=dn.MAX_CODEWORDS_IN_BARCODE,n;do n=t,t=this.adjustRowNumbersAndGetCount();while(t>0&&t<n);return this.detectionResultColumns},e.prototype.adjustIndicatorColumnRowNumbers=function(t){t!=null&&t.adjustCompleteIndicatorColumnRowNumbers(this.barcodeMetadata)},e.prototype.adjustRowNumbersAndGetCount=function(){var t=this.adjustRowNumbersByRow();if(t===0)return 0;for(var n=1;n<this.barcodeColumnCount+1;n++)for(var r=this.detectionResultColumns[n].getCodewords(),a=0;a<r.length;a++)r[a]!=null&&(r[a].hasValidRowNumber()||this.adjustRowNumbers(n,a,r));return t},e.prototype.adjustRowNumbersByRow=function(){this.adjustRowNumbersFromBothRI();var t=this.adjustRowNumbersFromLRI();return t+this.adjustRowNumbersFromRRI()},e.prototype.adjustRowNumbersFromBothRI=function(){if(!(this.detectionResultColumns[0]==null||this.detectionResultColumns[this.barcodeColumnCount+1]==null)){for(var t=this.detectionResultColumns[0].getCodewords(),n=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords(),r=0;r<t.length;r++)if(t[r]!=null&&n[r]!=null&&t[r].getRowNumber()===n[r].getRowNumber())for(var a=1;a<=this.barcodeColumnCount;a++){var i=this.detectionResultColumns[a].getCodewords()[r];i!=null&&(i.setRowNumber(t[r].getRowNumber()),i.hasValidRowNumber()||(this.detectionResultColumns[a].getCodewords()[r]=null))}}},e.prototype.adjustRowNumbersFromRRI=function(){if(this.detectionResultColumns[this.barcodeColumnCount+1]==null)return 0;for(var t=0,n=this.detectionResultColumns[this.barcodeColumnCount+1].getCodewords(),r=0;r<n.length;r++)if(n[r]!=null)for(var a=n[r].getRowNumber(),i=0,o=this.barcodeColumnCount+1;o>0&&i<this.ADJUST_ROW_NUMBER_SKIP;o--){var l=this.detectionResultColumns[o].getCodewords()[r];l!=null&&(i=e.adjustRowNumberIfValid(a,i,l),l.hasValidRowNumber()||t++)}return t},e.prototype.adjustRowNumbersFromLRI=function(){if(this.detectionResultColumns[0]==null)return 0;for(var t=0,n=this.detectionResultColumns[0].getCodewords(),r=0;r<n.length;r++)if(n[r]!=null)for(var a=n[r].getRowNumber(),i=0,o=1;o<this.barcodeColumnCount+1&&i<this.ADJUST_ROW_NUMBER_SKIP;o++){var l=this.detectionResultColumns[o].getCodewords()[r];l!=null&&(i=e.adjustRowNumberIfValid(a,i,l),l.hasValidRowNumber()||t++)}return t},e.adjustRowNumberIfValid=function(t,n,r){return r==null||r.hasValidRowNumber()||(r.isValidRowNumber(t)?(r.setRowNumber(t),n=0):++n),n},e.prototype.adjustRowNumbers=function(t,n,r){var a,i;if(this.detectionResultColumns[t-1]!=null){var o=r[n],l=this.detectionResultColumns[t-1].getCodewords(),c=l;this.detectionResultColumns[t+1]!=null&&(c=this.detectionResultColumns[t+1].getCodewords());var u=new Array(14);u[2]=l[n],u[3]=c[n],n>0&&(u[0]=r[n-1],u[4]=l[n-1],u[5]=c[n-1]),n>1&&(u[8]=r[n-2],u[10]=l[n-2],u[11]=c[n-2]),n<r.length-1&&(u[1]=r[n+1],u[6]=l[n+1],u[7]=c[n+1]),n<r.length-2&&(u[9]=r[n+2],u[12]=l[n+2],u[13]=c[n+2]);try{for(var d=DQe(u),h=d.next();!h.done;h=d.next()){var f=h.value;if(e.adjustRowNumber(o,f))return}}catch(m){a={error:m}}finally{try{h&&!h.done&&(i=d.return)&&i.call(d)}finally{if(a)throw a.error}}}},e.adjustRowNumber=function(t,n){return n==null?!1:n.hasValidRowNumber()&&n.getBucket()===t.getBucket()?(t.setRowNumber(n.getRowNumber()),!0):!1},e.prototype.getBarcodeColumnCount=function(){return this.barcodeColumnCount},e.prototype.getBarcodeRowCount=function(){return this.barcodeMetadata.getRowCount()},e.prototype.getBarcodeECLevel=function(){return this.barcodeMetadata.getErrorCorrectionLevel()},e.prototype.setBoundingBox=function(t){this.boundingBox=t},e.prototype.getBoundingBox=function(){return this.boundingBox},e.prototype.setDetectionResultColumn=function(t,n){this.detectionResultColumns[t]=n},e.prototype.getDetectionResultColumn=function(t){return this.detectionResultColumns[t]},e.prototype.toString=function(){var t=this.detectionResultColumns[0];t==null&&(t=this.detectionResultColumns[this.barcodeColumnCount+1]);for(var n=new lT,r=0;r<t.getCodewords().length;r++){n.format("CW %3d:",r);for(var a=0;a<this.barcodeColumnCount+2;a++){if(this.detectionResultColumns[a]==null){n.format(" | ");continue}var i=this.detectionResultColumns[a].getCodewords()[r];if(i==null){n.format(" | ");continue}n.format(" %3d|%3d",i.getRowNumber(),i.getValue())}n.format("%n")}return n.toString()},e})(),$Qe=(function(){function e(t,n,r,a){this.rowNumber=e.BARCODE_ROW_UNKNOWN,this.startX=Math.trunc(t),this.endX=Math.trunc(n),this.bucket=Math.trunc(r),this.value=Math.trunc(a)}return e.prototype.hasValidRowNumber=function(){return this.isValidRowNumber(this.rowNumber)},e.prototype.isValidRowNumber=function(t){return t!==e.BARCODE_ROW_UNKNOWN&&this.bucket===t%3*3},e.prototype.setRowNumberAsRowIndicatorColumn=function(){this.rowNumber=Math.trunc(Math.trunc(this.value/30)*3+Math.trunc(this.bucket/3))},e.prototype.getWidth=function(){return this.endX-this.startX},e.prototype.getStartX=function(){return this.startX},e.prototype.getEndX=function(){return this.endX},e.prototype.getBucket=function(){return this.bucket},e.prototype.getValue=function(){return this.value},e.prototype.getRowNumber=function(){return this.rowNumber},e.prototype.setRowNumber=function(t){this.rowNumber=t},e.prototype.toString=function(){return this.rowNumber+"|"+this.value},e.BARCODE_ROW_UNKNOWN=-1,e})(),LQe=(function(){function e(){}return e.initialize=function(){for(var t=0;t<dn.SYMBOL_TABLE.length;t++)for(var n=dn.SYMBOL_TABLE[t],r=n&1,a=0;a<dn.BARS_IN_MODULE;a++){for(var i=0;(n&1)===r;)i+=1,n>>=1;r=n&1,e.RATIOS_TABLE[t]||(e.RATIOS_TABLE[t]=new Array(dn.BARS_IN_MODULE)),e.RATIOS_TABLE[t][dn.BARS_IN_MODULE-a-1]=Math.fround(i/dn.MODULES_IN_CODEWORD)}this.bSymbolTableReady=!0},e.getDecodedValue=function(t){var n=e.getDecodedCodewordValue(e.sampleBitCounts(t));return n!==-1?n:e.getClosestDecodedValue(t)},e.sampleBitCounts=function(t){for(var n=mn.sum(t),r=new Int32Array(dn.BARS_IN_MODULE),a=0,i=0,o=0;o<dn.MODULES_IN_CODEWORD;o++){var l=n/(2*dn.MODULES_IN_CODEWORD)+o*n/dn.MODULES_IN_CODEWORD;i+t[a]<=l&&(i+=t[a],a++),r[a]++}return r},e.getDecodedCodewordValue=function(t){var n=e.getBitValue(t);return dn.getCodeword(n)===-1?-1:n},e.getBitValue=function(t){for(var n=0,r=0;r<t.length;r++)for(var a=0;a<t[r];a++)n=n<<1|(r%2===0?1:0);return Math.trunc(n)},e.getClosestDecodedValue=function(t){var n=mn.sum(t),r=new Array(dn.BARS_IN_MODULE);if(n>1)for(var a=0;a<r.length;a++)r[a]=Math.fround(t[a]/n);var i=a2.MAX_VALUE,o=-1;this.bSymbolTableReady||e.initialize();for(var l=0;l<e.RATIOS_TABLE.length;l++){for(var c=0,u=e.RATIOS_TABLE[l],d=0;d<dn.BARS_IN_MODULE;d++){var h=Math.fround(u[d]-r[d]);if(c+=Math.fround(h*h),c>=i)break}c<i&&(i=c,o=dn.SYMBOL_TABLE[l])}return o},e.bSymbolTableReady=!1,e.RATIOS_TABLE=new Array(dn.SYMBOL_TABLE.length).map(function(t){return new Array(dn.BARS_IN_MODULE)}),e})(),FQe=(function(){function e(){this.segmentCount=-1,this.fileSize=-1,this.timestamp=-1,this.checksum=-1}return e.prototype.getSegmentIndex=function(){return this.segmentIndex},e.prototype.setSegmentIndex=function(t){this.segmentIndex=t},e.prototype.getFileId=function(){return this.fileId},e.prototype.setFileId=function(t){this.fileId=t},e.prototype.getOptionalData=function(){return this.optionalData},e.prototype.setOptionalData=function(t){this.optionalData=t},e.prototype.isLastSegment=function(){return this.lastSegment},e.prototype.setLastSegment=function(t){this.lastSegment=t},e.prototype.getSegmentCount=function(){return this.segmentCount},e.prototype.setSegmentCount=function(t){this.segmentCount=t},e.prototype.getSender=function(){return this.sender||null},e.prototype.setSender=function(t){this.sender=t},e.prototype.getAddressee=function(){return this.addressee||null},e.prototype.setAddressee=function(t){this.addressee=t},e.prototype.getFileName=function(){return this.fileName},e.prototype.setFileName=function(t){this.fileName=t},e.prototype.getFileSize=function(){return this.fileSize},e.prototype.setFileSize=function(t){this.fileSize=t},e.prototype.getChecksum=function(){return this.checksum},e.prototype.setChecksum=function(t){this.checksum=t},e.prototype.getTimestamp=function(){return this.timestamp},e.prototype.setTimestamp=function(t){this.timestamp=t},e})(),A8=(function(){function e(){}return e.parseLong=function(t,n){return n===void 0&&(n=void 0),parseInt(t,n)},e})(),BQe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
928t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),UQe=(function(e){BQe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.kind="NullPointerException",t})(ui),zQe=(function(){function e(){}return e.prototype.writeBytes=function(t){this.writeBytesOffset(t,0,t.length)},e.prototype.writeBytesOffset=function(t,n,r){if(t==null)throw new UQe;if(n<0||n>t.length||r<0||n+r>t.length||n+r<0)throw new rT;if(r===0)return;for(var a=0;a<r;a++)this.write(t[n+a])},e.prototype.flush=function(){},e.prototype.close=function(){},e})(),WQe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),KQe=(function(e){WQe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t})(ui),HQe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),VQe=(function(e){HQe(t,e);function t(n){n===void 0&&(n=32);var r=e.call(this)||this;if(r.count=0,n<0)throw new Ct("Negative initial size: "+n);return r.buf=new Uint8Array(n),r}return t.prototype.ensureCapacity=function(n){n-this.buf.length>0&&this.grow(n)},t.prototype.grow=function(n){var r=this.buf.length,a=r<<1;if(a-n<0&&(a=n),a<0){if(n<0)throw new KQe;a=Zt.MAX_VALUE}this.buf=is.copyOfUint8Array(this.buf,a)},t.prototype.write=function(n){this.ensureCapacity(this.count+1),this.buf[this.count]=n,this.count+=1},t.prototype.writeBytesOffset=function(n,r,a){if(r<0||r>n.length||a<0||r+a-n.length>0)throw new rT;this.ensureCapacity(this.count+a),Fn.arraycopy(n,r,this.buf,this.count,a),this.count+=a},t.prototype.writeTo=function(n){n.writeBytesOffset(this.buf,0,this.count)},t.prototype.reset=function(){this.count=0},t.prototype.toByteArray=function(){return is.copyOfUint8Array(this.buf,this.count)},t.prototype.size=function(){return this.count},t.prototype.toString=function(n){return n?typeof n=="string"?this.toString_string(n):this.toString_number(n):this.toString_void()},t.prototype.toString_void=function(){return new String(this.buf).toString()},t.prototype.toString_string=function(n){return new String(this.buf).toString()},t.prototype.toString_number=function(n){return new String(this.buf).toString()},t.prototype.close=function(){},t})(zQe),Dn;(function(e){e[e.ALPHA=0]="ALPHA",e[e.LOWER=1]="LOWER",e[e.MIXED=2]="MIXED",e[e.PUNCT=3]="PUNCT",e[e.ALPHA_SHIFT=4]="ALPHA_SHIFT",e[e.PUNCT_SHIFT=5]="PUNCT_SHIFT"})(Dn||(Dn={}));function tY(){if(typeof window<"u")return window.BigInt||null;if(typeof globalThis<"u")return globalThis.BigInt||null;if(typeof self<"u")return self.BigInt||null;throw new Error("Can't search globals for BigInt!")}var yy;function Dc(e){if(typeof yy>"u"&&(yy=tY()),yy===null)throw new Error("BigInt is not supported!");return yy(e)}function qQe(){var e=[];e[0]=Dc(1);var t=Dc(900);e[1]=t;for(var n=2;n<16;n++)e[n]=e[n-1]*t;return e}var GQe=(function(){function e(){}return e.decode=function(t,n){var r=new Kt(""),a=as.ISO8859_1;r.enableDecoding(a);for(var i=1,o=t[i++],l=new FQe;i<t[0];){switch(o){case e.TEXT_COMPACTION_MODE_LATCH:i=e.textCompaction(t,i,r);break;case e.BYTE_COMPACTION_MODE_LATCH:case e.BYTE_COMPACTION_MODE_LATCH_6:i=e.byteCompaction(o,t,a,i,r);break;case e.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:r.append(t[i++]);break;case e.NUMERIC_COMPACTION_MODE_LATCH:i=e.numericCompaction(t,i,r);break;case e.ECI_CHARSET:as.getCharacterSetECIByValue(t[i++]);break;case e.ECI_GENERAL_PURPOSE:i+=2;break;case e.ECI_USER_DEFINED:i++;break;case e.BEGIN_MACRO_PDF417_CONTROL_BLOCK:i=e.decodeMacroBlock(t,i,l);break;case e.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case e.MACRO_PDF417_TERMINATOR:throw new We;default:i--,i=e.textCompaction(t,i,r);break}if(i<t.length)o=t[i++];else throw We.getFormatInstance()}if(r.length()===0)throw We.getFormatInstance();var c=new qf(null,r.toString(),null,n);return c.setOther(l),c},e.decodeMacroBlock=function(t,n,r){if(n+e.NUMBER_OF_SEQUENCE_CODEWORDS>t[0])throw We.getFormatInstance();for(var a=new Int32Array(e.NUMBER_OF_SEQUENCE_CODEWORDS),i=0;i<e.NUMBER_OF_SEQUENCE_CODEWORDS;i++,n++)a[i]=t[n];r.setSegmentIndex(Zt.parseInt(e.decodeBase900toBase10(a,e.NUMBER_OF_SEQUENCE_CODEWORDS)));var o=new Kt;n=e.textCompaction(t,n,o),r.setFileId(o.toString());var l=-1;for(t[n]===e.BEGIN_MACRO_PDF417_OPTIONAL_FIELD&&(l=n+1);n<t[0];)switch(t[n]){case e.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:switch(n++,t[n]){case e.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME:var c=new Kt;n=e.textCompaction(t,n+1,c),r.setFileName(c.toString());break;case e.MACRO_PDF417_OPTIONAL_FIELD_SENDER:var u=new Kt;n=e.textCompaction(t,n+1,u),r.setSender(u.toString());break;case e.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE:var d=new Kt;n=e.textCompaction(t,n+1,d),r.setAddressee(d.toString());break;case e.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT:var h=new Kt;n=e.numericCompaction(t,n+1,h),r.setSegmentCount(Zt.parseInt(h.toString()));break;case e.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP:var f=new Kt;n=e.numericCompaction(t,n+1,f),r.setTimestamp(A8.parseLong(f.toString()));break;case e.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM:var m=new Kt;n=e.numericCompaction(t,n+1,m),r.setChecksum(Zt.parseInt(m.toString()));break;case e.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE:var x=new Kt;n=e.numericCompaction(t,n+1,x),r.setFileSize(A8.parseLong(x.toString()));break;default:throw We.getFormatInstance()}break;case e.MACRO_PDF417_TERMINATOR:n++,r.setLastSegment(!0);break;default:throw We.getFormatInstance()}if(l!==-1){var g=n-l;r.isLastSegment()&&g--,r.setOptionalData(is.copyOfRange(t,l,l+g))}return n},e.textCompaction=function(t,n,r){for(var a=new Int32Array((t[0]-n)*2),i=new Int32Array((t[0]-n)*2),o=0,l=!1;n<t[0]&&!l;){var c=t[n++];if(c<e.TEXT_COMPACTION_MODE_LATCH)a[o]=c/30,a[o+1]=c%30,o+=2;else switch(c){case e.TEXT_COMPACTION_MODE_LATCH:a[o++]=e.TEXT_COMPACTION_MODE_LATCH;break;case e.BYTE_COMPACTION_MODE_LATCH:case e.BYTE_COMPACTION_MODE_LATCH_6:case e.NUMERIC_COMPACTION_MODE_LATCH:case e.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case e.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case e.MACRO_PDF417_TERMINATOR:n--,l=!0;break;case e.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:a[o]=e.MODE_SHIFT_TO_BYTE_COMPACTION_MODE,c=t[n++],i[o]=c,o++;break}}return e.decodeTextCompaction(a,i,o,r),n},e.decodeTextCompaction=function(t,n,r,a){for(var i=Dn.ALPHA,o=Dn.ALPHA,l=0;l<r;){var c=t[l],u="";switch(i){case Dn.ALPHA:if(c<26)u=String.fromCharCode(65+c);else switch(c){case 26:u=" ";break;case e.LL:i=Dn.LOWER;break;case e.ML:i=Dn.MIXED;break;case e.PS:o=i,i=Dn.PUNCT_SHIFT;break;case e.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:a.append(n[l]);break;case e.TEXT_COMPACTION_MODE_LATCH:i=Dn.ALPHA;break}break;case Dn.LOWER:if(c<26)u=String.fromCharCode(97+c);else switch(c){case 26:u=" ";break;case e.AS:o=i,i=Dn.ALPHA_SHIFT;break;case e.ML:i=Dn.MIXED;break;case e.PS:o=i,i=Dn.PUNCT_SHIFT;break;case e.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:a.append(n[l]);break;case e.TEXT_COMPACTION_MODE_LATCH:i=Dn.ALPHA;break}break;case Dn.MIXED:if(c<e.PL)u=e.MIXED_CHARS[c];else switch(c){case e.PL:i=Dn.PUNCT;break;case 26:u=" ";break;case e.LL:i=Dn.LOWER;break;case e.AL:i=Dn.ALPHA;break;case e.PS:o=i,i=Dn.PUNCT_SHIFT;break;case e.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:a.append(n[l]);break;case e.TEXT_COMPACTION_MODE_LATCH:i=Dn.ALPHA;break}break;case Dn.PUNCT:if(c<e.PAL)u=e.PUNCT_CHARS[c];else switch(c){case e.PAL:i=Dn.ALPHA;break;case e.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:a.append(n[l]);break;case e.TEXT_COMPACTION_MODE_LATCH:i=Dn.ALPHA;break}break;case Dn.ALPHA_SHIFT:if(i=o,c<26)u=String.fromCharCode(65+c);else switch(c){case 26:u=" ";break;case e.TEXT_COMPACTION_MODE_LATCH:i=Dn.ALPHA;break}break;case Dn.PUNCT_SHIFT:if(i=o,c<e.PAL)u=e.PUNCT_CHARS[c];else switch(c){case e.PAL:i=Dn.ALPHA;break;case e.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:a.append(n[l]);break;case e.TEXT_COMPACTION_MODE_LATCH:i=Dn.ALPHA;break}break}u!==""&&a.append(u),l++}},e.byteCompaction=function(t,n,r,a,i){var o=new VQe,l=0,c=0,u=!1;switch(t){case e.BYTE_COMPACTION_MODE_LATCH:for(var d=new Int32Array(6),h=n[a++];a<n[0]&&!u;)switch(d[l++]=h,c=900*c+h,h=n[a++],h){case e.TEXT_COMPACTION_MODE_LATCH:case e.BYTE_COMPACTION_MODE_LATCH:case e.NUMERIC_COMPACTION_MODE_LATCH:case e.BYTE_COMPACTION_MODE_LATCH_6:case e.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case e.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case e.MACRO_PDF417_TERMINATOR:a--,u=!0;break;default:if(l%5===0&&l>0){for(var f=0;f<6;++f)o.write(Number(Dc(c)>>Dc(8*(5-f))));c=0,l=0}break}a===n[0]&&h<e.TEXT_COMPACTION_MODE_LATCH&&(d[l++]=h);for(var m=0;m<l;m++)o.write(d[m]);break;case e.BYTE_COMPACTION_MODE_LATCH_6:for(;a<n[0]&&!u;){var x=n[a++];if(x<e.TEXT_COMPACTION_MODE_LATCH)l++,c=900*c+x;else switch(x){case e.TEXT_COMPACTION_MODE_LATCH:case e.BYTE_COMPACTION_MODE_LATCH:case e.NUMERIC_COMPACTION_MODE_LATCH:case e.BYTE_COMPACTION_MODE_LATCH_6:case e.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case e.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case e.MACRO_PDF417_TERMINATOR:a--,u=!0;break}if(l%5===0&&l>0){for(var f=0;f<6;++f)o.write(Number(Dc(c)>>Dc(8*(5-f))));c=0,l=0}}break}return i.append(ri.decode(o.toByteArray(),r)),a},e.numericCompaction=function(t,n,r){for(var a=0,i=!1,o=new Int32Array(e.MAX_NUMERIC_CODEWORDS);n<t[0]&&!i;){var l=t[n++];if(n===t[0]&&(i=!0),l<e.TEXT_COMPACTION_MODE_LATCH)o[a]=l,a++;else switch(l){case e.TEXT_COMPACTION_MODE_LATCH:case e.BYTE_COMPACTION_MODE_LATCH:case e.BYTE_COMPACTION_MODE_LATCH_6:case e.BEGIN_MACRO_PDF417_CONTROL_BLOCK:case e.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:case e.MACRO_PDF417_TERMINATOR:n--,i=!0;break}(a%e.MAX_NUMERIC_CODEWORDS===0||l===e.NUMERIC_COMPACTION_MODE_LATCH||i)&&a>0&&(r.append(e.decodeBase900toBase10(o,a)),a=0)}return n},e.decodeBase900toBase10=function(t,n){for(var r=Dc(0),a=0;a<n;a++)r+=e.EXP900[n-a-1]*Dc(t[a]);var i=r.toString();if(i.charAt(0)!=="1")throw new We;return i.substring(1)},e.TEXT_COMPACTION_MODE_LATCH=900,e.BYTE_COMPACTION_MODE_LATCH=901,e.NUMERIC_COMPACTION_MODE_LATCH=902,e.BYTE_COMPACTION_MODE_LATCH_6=924,e.ECI_USER_DEFINED=925,e.ECI_GENERAL_PURPOSE=926,e.ECI_CHARSET=927,e.BEGIN_MACRO_PDF417_CONTROL_BLOCK=928,e.BEGIN_MACRO_PDF417_OPTIONAL_FIELD=923,e.MACRO_PDF417_TERMINATOR=922,e.MODE_SHIFT_TO_BYTE_COMPACTION_MODE=913,e.MAX_NUMERIC_CODEWORDS=15,e.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME=0,e.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT=1,e.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP=2,e.MACRO_PDF417_OPTIONAL_FIELD_SENDER=3,e.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE=4,e.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE=5,e.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM=6,e.PL=25,e.LL=27,e.AS=27,e.ML=28,e.AL=28,e.PS=29,e.PAL=29,e.PUNCT_CHARS=`;<>@[\\]_\`~!\r ,: 929-.$/"|*()?{}'`,e.MIXED_CHARS="0123456789&\r ,:#-.$/+%*=^",e.EXP900=tY()?qQe():[],e.NUMBER_OF_SEQUENCE_CODEWORDS=2,e})(),Om=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);
929if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},YQe=(function(){function e(){}return e.decode=function(t,n,r,a,i,o,l){for(var c=new h2(t,n,r,a,i),u=null,d=null,h,f=!0;;f=!1){if(n!=null&&(u=e.getRowIndicatorColumn(t,c,n,!0,o,l)),a!=null&&(d=e.getRowIndicatorColumn(t,c,a,!1,o,l)),h=e.merge(u,d),h==null)throw Oe.getNotFoundInstance();var m=h.getBoundingBox();if(f&&m!=null&&(m.getMinY()<c.getMinY()||m.getMaxY()>c.getMaxY()))c=m;else break}h.setBoundingBox(c);var x=h.getBarcodeColumnCount()+1;h.setDetectionResultColumn(0,u),h.setDetectionResultColumn(x,d);for(var g=u!=null,y=1;y<=x;y++){var b=g?y:x-y;if(h.getDetectionResultColumn(b)===void 0){var v=void 0;b===0||b===x?v=new E8(c,b===0):v=new eY(c),h.setDetectionResultColumn(b,v);for(var w=-1,_=w,k=c.getMinY();k<=c.getMaxY();k++){if(w=e.getStartColumn(h,b,k,g),w<0||w>c.getMaxX()){if(_===-1)continue;w=_}var j=e.detectCodeword(t,c.getMinX(),c.getMaxX(),g,w,k,o,l);j!=null&&(v.setCodeword(k,j),_=w,o=Math.min(o,j.getWidth()),l=Math.max(l,j.getWidth()))}}}return e.createDecoderResult(h)},e.merge=function(t,n){if(t==null&&n==null)return null;var r=e.getBarcodeMetadata(t,n);if(r==null)return null;var a=h2.merge(e.adjustBoundingBox(t),e.adjustBoundingBox(n));return new MQe(r,a)},e.adjustBoundingBox=function(t){var n,r;if(t==null)return null;var a=t.getRowHeights();if(a==null)return null;var i=e.getMax(a),o=0;try{for(var l=Om(a),c=l.next();!c.done;c=l.next()){var u=c.value;if(o+=i-u,u>0)break}}catch(m){n={error:m}}finally{try{c&&!c.done&&(r=l.return)&&r.call(l)}finally{if(n)throw n.error}}for(var d=t.getCodewords(),h=0;o>0&&d[h]==null;h++)o--;for(var f=0,h=a.length-1;h>=0&&(f+=i-a[h],!(a[h]>0));h--);for(var h=d.length-1;f>0&&d[h]==null;h--)f--;return t.getBoundingBox().addMissingRows(o,f,t.isLeft())},e.getMax=function(t){var n,r,a=-1;try{for(var i=Om(t),o=i.next();!o.done;o=i.next()){var l=o.value;a=Math.max(a,l)}}catch(c){n={error:c}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}return a},e.getBarcodeMetadata=function(t,n){var r;if(t==null||(r=t.getBarcodeMetadata())==null)return n==null?null:n.getBarcodeMetadata();var a;return n==null||(a=n.getBarcodeMetadata())==null?r:r.getColumnCount()!==a.getColumnCount()&&r.getErrorCorrectionLevel()!==a.getErrorCorrectionLevel()&&r.getRowCount()!==a.getRowCount()?null:r},e.getRowIndicatorColumn=function(t,n,r,a,i,o){for(var l=new E8(n,a),c=0;c<2;c++)for(var u=c===0?1:-1,d=Math.trunc(Math.trunc(r.getX())),h=Math.trunc(Math.trunc(r.getY()));h<=n.getMaxY()&&h>=n.getMinY();h+=u){var f=e.detectCodeword(t,0,t.getWidth(),a,d,h,i,o);f!=null&&(l.setCodeword(h,f),a?d=f.getStartX():d=f.getEndX())}return l},e.adjustCodewordCount=function(t,n){var r=n[0][1],a=r.getValue(),i=t.getBarcodeColumnCount()*t.getBarcodeRowCount()-e.getNumberOfECCodeWords(t.getBarcodeECLevel());if(a.length===0){if(i<1||i>dn.MAX_CODEWORDS_IN_BARCODE)throw Oe.getNotFoundInstance();r.setValue(i)}else a[0]!==i&&r.setValue(i)},e.createDecoderResult=function(t){var n=e.createBarcodeMatrix(t);e.adjustCodewordCount(t,n);for(var r=new Array,a=new Int32Array(t.getBarcodeRowCount()*t.getBarcodeColumnCount()),i=[],o=new Array,l=0;l<t.getBarcodeRowCount();l++)for(var c=0;c<t.getBarcodeColumnCount();c++){var u=n[l][c+1].getValue(),d=l*t.getBarcodeColumnCount()+c;u.length===0?r.push(d):u.length===1?a[d]=u[0]:(o.push(d),i.push(u))}for(var h=new Array(i.length),f=0;f<h.length;f++)h[f]=i[f];return e.createDecoderResultFromAmbiguousValues(t.getBarcodeECLevel(),a,dn.toIntArray(r),dn.toIntArray(o),h)},e.createDecoderResultFromAmbiguousValues=function(t,n,r,a,i){for(var o=new Int32Array(a.length),l=100;l-- >0;){for(var c=0;c<o.length;c++)n[a[c]]=i[c][o[c]];try{return e.decodeCodewords(n,t,r)}catch(d){var u=d instanceof Yr;if(!u)throw d}if(o.length===0)throw Yr.getChecksumInstance();for(var c=0;c<o.length;c++)if(o[c]<i[c].length-1){o[c]++;break}else if(o[c]=0,c===o.length-1)throw Yr.getChecksumInstance()}throw Yr.getChecksumInstance()},e.createBarcodeMatrix=function(t){for(var n,r,a,i,o=Array.from({length:t.getBarcodeRowCount()},function(){return new Array(t.getBarcodeColumnCount()+2)}),l=0;l<o.length;l++)for(var c=0;c<o[l].length;c++)o[l][c]=new Km;var u=0;try{for(var d=Om(t.getDetectionResultColumns()),h=d.next();!h.done;h=d.next()){var f=h.value;if(f!=null)try{for(var m=(a=void 0,Om(f.getCodewords())),x=m.next();!x.done;x=m.next()){var g=x.value;if(g!=null){var y=g.getRowNumber();if(y>=0){if(y>=o.length)continue;o[y][u].setValue(g.getValue())}}}}catch(b){a={error:b}}finally{try{x&&!x.done&&(i=m.return)&&i.call(m)}finally{if(a)throw a.error}}u++}}catch(b){n={error:b}}finally{try{h&&!h.done&&(r=d.return)&&r.call(d)}finally{if(n)throw n.error}}return o}
929,e.isValidBarcodeColumn=function(t,n){return n>=0&&n<=t.getBarcodeColumnCount()+1},e.getStartColumn=function(t,n,r,a){var i,o,l=a?1:-1,c=null;if(e.isValidBarcodeColumn(t,n-l)&&(c=t.getDetectionResultColumn(n-l).getCodeword(r)),c!=null)return a?c.getEndX():c.getStartX();if(c=t.getDetectionResultColumn(n).getCodewordNearby(r),c!=null)return a?c.getStartX():c.getEndX();if(e.isValidBarcodeColumn(t,n-l)&&(c=t.getDetectionResultColumn(n-l).getCodewordNearby(r)),c!=null)return a?c.getEndX():c.getStartX();for(var u=0;e.isValidBarcodeColumn(t,n-l);){n-=l;try{for(var d=(i=void 0,Om(t.getDetectionResultColumn(n).getCodewords())),h=d.next();!h.done;h=d.next()){var f=h.value;if(f!=null)return(a?f.getEndX():f.getStartX())+l*u*(f.getEndX()-f.getStartX())}}catch(m){i={error:m}}finally{try{h&&!h.done&&(o=d.return)&&o.call(d)}finally{if(i)throw i.error}}u++}return a?t.getBoundingBox().getMinX():t.getBoundingBox().getMaxX()},e.detectCodeword=function(t,n,r,a,i,o,l,c){i=e.adjustCodewordStartColumn(t,n,r,a,i,o);var u=e.getModuleBitCount(t,n,r,a,i,o);if(u==null)return null;var d,h=mn.sum(u);if(a)d=i+h;else{for(var f=0;f<u.length/2;f++){var m=u[f];u[f]=u[u.length-1-f],u[u.length-1-f]=m}d=i,i=d-h}if(!e.checkCodewordSkew(h,l,c))return null;var x=LQe.getDecodedValue(u),g=dn.getCodeword(x);return g===-1?null:new $Qe(i,d,e.getCodewordBucketNumber(x),g)},e.getModuleBitCount=function(t,n,r,a,i,o){for(var l=i,c=new Int32Array(8),u=0,d=a?1:-1,h=a;(a?l<r:l>=n)&&u<c.length;)t.get(l,o)===h?(c[u]++,l+=d):(u++,h=!h);return u===c.length||l===(a?r:n)&&u===c.length-1?c:null},e.getNumberOfECCodeWords=function(t){return 2<<t},e.adjustCodewordStartColumn=function(t,n,r,a,i,o){for(var l=i,c=a?-1:1,u=0;u<2;u++){for(;(a?l>=n:l<r)&&a===t.get(l,o);){if(Math.abs(i-l)>e.CODEWORD_SKEW_SIZE)return i;l+=c}c=-c,a=!a}return l},e.checkCodewordSkew=function(t,n,r){return n-e.CODEWORD_SKEW_SIZE<=t&&t<=r+e.CODEWORD_SKEW_SIZE},e.decodeCodewords=function(t,n,r){if(t.length===0)throw We.getFormatInstance();var a=1<<n+1,i=e.correctErrors(t,r,a);e.verifyCodewordCount(t,a);var o=GQe.decode(t,""+n);return o.setErrorsCorrected(i),o.setErasures(r.length),o},e.correctErrors=function(t,n,r){if(n!=null&&n.length>r/2+e.MAX_ERRORS||r<0||r>e.MAX_EC_CODEWORDS)throw Yr.getChecksumInstance();return e.errorCorrection.decode(t,r,n)},e.verifyCodewordCount=function(t,n){if(t.length<4)throw We.getFormatInstance();var r=t[0];if(r>t.length)throw We.getFormatInstance();if(r===0)if(n<t.length)t[0]=t.length-n;else throw We.getFormatInstance()},e.getBitCountForCodeword=function(t){for(var n=new Int32Array(8),r=0,a=n.length-1;!((t&1)!==r&&(r=t&1,a--,a<0));)n[a]++,t>>=1;return n},e.getCodewordBucketNumber=function(t){return t instanceof Int32Array?this.getCodewordBucketNumber_Int32Array(t):this.getCodewordBucketNumber_number(t)},e.getCodewordBucketNumber_number=function(t){return e.getCodewordBucketNumber(e.getBitCountForCodeword(t))},e.getCodewordBucketNumber_Int32Array=function(t){return(t[0]-t[2]+t[4]-t[6]+9)%9},e.toString=function(t){for(var n=new lT,r=0;r<t.length;r++){n.format("Row %2d: ",r);for(var a=0;a<t[r].length;a++){var i=t[r][a];i.getValue().length===0?n.format(" ",null):n.format("%4d(%2d)",i.getValue()[0],i.getConfidence(i.getValue()[0]))}n.format("%n")}return n.toString()},e.CODEWORD_SKEW_SIZE=2,e.MAX_ERRORS=3,e.MAX_EC_CODEWORDS=512,e.errorCorrection=new AQe,e})(),ZQe=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},f2=(function(){function e(){}return e.prototype.decode=function(t,n){n===void 0&&(n=null);var r=e.decode(t,n,!1);if(r==null||r.length===0||r[0]==null)throw Oe.getNotFoundInstance();return r[0]},e.prototype.decodeMultiple=function(t,n){n===void 0&&(n=null);try{return e.decode(t,n,!0)}catch(r){throw r instanceof We||r instanceof Yr?Oe.getNotFoundInstance():r}},e.decode=function(t,n,r){var a,i,o=new Array,l=kQe.detectMultiple(t,n,r);try{for(var c=ZQe(l.getPoints()),u=c.next();!u.done;u=c.next()){var d=u.value,h=YQe.decode(l.getBits(),d[4],d[5],d[6],d[7],e.getMinCodewordWidth(d),e.getMaxCodew
929ordWidth(d)),f=new Ts(h.getText(),h.getRawBytes(),void 0,d,wt.PDF_417);f.putMetadata(jr.ERROR_CORRECTION_LEVEL,h.getECLevel());var m=h.getOther();m!=null&&f.putMetadata(jr.PDF417_EXTRA_METADATA,m),o.push(f)}}catch(x){a={error:x}}finally{try{u&&!u.done&&(i=c.return)&&i.call(c)}finally{if(a)throw a.error}}return o.map(function(x){return x})},e.getMaxWidth=function(t,n){return t==null||n==null?0:Math.trunc(Math.abs(t.getX()-n.getX()))},e.getMinWidth=function(t,n){return t==null||n==null?Zt.MAX_VALUE:Math.trunc(Math.abs(t.getX()-n.getX()))},e.getMaxCodewordWidth=function(t){return Math.floor(Math.max(Math.max(e.getMaxWidth(t[0],t[4]),e.getMaxWidth(t[6],t[2])*dn.MODULES_IN_CODEWORD/dn.MODULES_IN_STOP_PATTERN),Math.max(e.getMaxWidth(t[1],t[5]),e.getMaxWidth(t[7],t[3])*dn.MODULES_IN_CODEWORD/dn.MODULES_IN_STOP_PATTERN)))},e.getMinCodewordWidth=function(t){return Math.floor(Math.min(Math.min(e.getMinWidth(t[0],t[4]),e.getMinWidth(t[6],t[2])*dn.MODULES_IN_CODEWORD/dn.MODULES_IN_STOP_PATTERN),Math.min(e.getMinWidth(t[1],t[5]),e.getMinWidth(t[7],t[3])*dn.MODULES_IN_CODEWORD/dn.MODULES_IN_STOP_PATTERN)))},e.prototype.reset=function(){},e})(),XQe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),T8=(function(e){XQe(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.kind="ReaderException",t})(ui),O8=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},JQe=(function(){function e(){}return e.prototype.decode=function(t,n){return this.hints!==n&&this.setHints(n),this.decodeInternal(t)},e.prototype.decodeWithState=function(t){return(this.readers===null||this.readers===void 0)&&this.setHints(null),this.decodeInternal(t)},e.prototype.setHints=function(t){this.hints=t;var n=t!=null&&t.get(On.TRY_HARDER)!==void 0,r=t==null?null:t.get(On.POSSIBLE_FORMATS),a=new Array;if(r!=null){var i=r.some(function(o){return o===wt.UPC_A||o===wt.UPC_E||o===wt.EAN_13||o===wt.EAN_8||o===wt.CODABAR||o===wt.CODE_39||o===wt.CODE_93||o===wt.CODE_128||o===wt.ITF||o===wt.RSS_14||o===wt.RSS_EXPANDED});i&&!n&&a.push(new Wm(t)),r.includes(wt.QR_CODE)&&a.push(new d2),r.includes(wt.MICRO_QR_CODE)&&a.push(new S8),r.includes(wt.DATA_MATRIX)&&a.push(new c2),r.includes(wt.AZTEC)&&a.push(new o2),r.includes(wt.PDF_417)&&a.push(new f2),r.includes(wt.MAXICODE)&&a.push(new C8),i&&n&&a.push(new Wm(t))}a.length===0&&(n||a.push(new Wm(t)),a.push(new d2),a.push(new S8),a.push(new c2),a.push(new o2),a.push(new f2),a.push(new C8),n&&a.push(new Wm(t))),this.readers=a},e.prototype.reset=function(){var t,n;if(this.readers!==null)try{for(var r=O8(this.readers),a=r.next();!a.done;a=r.next()){var i=a.value;i.reset()}}catch(o){t={error:o}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(t)throw t.error}}},e.prototype.decodeInternal=function(t){var n,r;if(this.readers===null)throw new T8("No readers where selected, nothing can be read.");try{for(var a=O8(this.readers),i=a.next();!i.done;i=a.next()){var o=i.value;try{return o.decode(t,this.hints)}catch(l){if(l instanceof T8)continue;console.warn("MultiFormatReader: non-ReaderException from reader:",l);continue}}}catch(l){n={error:l}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}throw new Oe("No MultiFormat Readers were able to detect the code.")},e})(),QQe=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
929t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();(function(e){QQe(t,e);function t(n,r){n===void 0&&(n=null),r===void 0&&(r=500);var a=new JQe;return a.setHints(n),e.call(this,a,r)||this}return Object.defineProperty(t.prototype,"hints",{set:function(n){this._hints=n||null,this.reader.setHints(n)},enumerable:!1,configurable:!0}),t.prototype.decodeBitmap=function(n){try{return this.reader.decodeWithState(n)}finally{this.reader.reset()}},t})(Vf);var eet=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();(function(e){eet(t,e);function t(n){return n===void 0&&(n=500),e.call(this,new f2,n)||this}return t})(Vf);var tet=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();(function(e){tet(t,e);function t(n){return n===void 0&&(n=500),e.call(this,new d2,n)||this}return t})(Vf);var Qo;(function(e){e[e.ERROR_CORRECTION=0]="ERROR_CORRECTION",e[e.CHARACTER_SET=1]="CHARACTER_SET",e[e.DATA_MATRIX_SHAPE=2]="DATA_MATRIX_SHAPE",e[e.DATA_MATRIX_COMPACT=3]="DATA_MATRIX_COMPACT",e[e.MIN_SIZE=4]="MIN_SIZE",e[e.MAX_SIZE=5]="MAX_SIZE",e[e.MARGIN=6]="MARGIN",e[e.PDF417_COMPACT=7]="PDF417_COMPACT",e[e.PDF417_COMPACTION=8]="PDF417_COMPACTION",e[e.PDF417_DIMENSIONS=9]="PDF417_DIMENSIONS",e[e.AZTEC_LAYERS=10]="AZTEC_LAYERS",e[e.QR_VERSION=11]="QR_VERSION",e[e.GS1_FORMAT=12]="GS1_FORMAT",e[e.FORCE_C40=13]="FORCE_C40"})(Qo||(Qo={}));var nY=(function(){function e(t){this.field=t,this.cachedGenerators=[],this.cachedGenerators.push(new Qc(t,Int32Array.from([1])))}return e.prototype.buildGenerator=function(t){var n=this.cachedGenerators;if(t>=n.length)for(var r=n[n.length-1],a=this.field,i=n.length;i<=t;i++){var o=r.multiply(new Qc(a,Int32Array.from([1,a.exp(i-1+a.getGeneratorBase())])));n.push(o),r=o}return n[t]},e.prototype.encode=function(t,n){if(n===0)throw new Ct("No error correction bytes");var r=t.length-n;if(r<=0)throw new Ct("No data bytes provided");var a=this.buildGenerator(n),i=new Int32Array(r);Fn.arraycopy(t,0,i,0,r);var o=new Qc(this.field,i);o=o.multiplyByMonomial(n,1);for(var l=o.divide(a)[1],c=l.getCoefficients(),u=n-c.length,d=0;d<u;d++)t[r+d]=0;Fn.arraycopy(c,0,t,r+u,c.length)},e})(),Hm=(function(){function e(){}return e.applyMaskPenaltyRule1=function(t){return e.applyMaskPenaltyRule1Internal(t,!0)+e.applyMaskPenaltyRule1Internal(t,!1)},e.applyMaskPenaltyRule2=function(t){for(var n=0,r=t.getArray(),a=t.getWidth(),i=t.getHeight(),o=0;o<i-1;o++)for(var l=r[o],c=0;c<a-1;c++){var u=l[c];u===l[c+1]&&u===r[o+1][c]&&u===r[o+1][c+1]&&n++}return e.N2*n},e.applyMaskPenaltyRule3=function(t){for(var n=0,r=t.getArray(),a=t.getWidth(),i=t.getHeight(),o=0;o<i;o++)for(var l=0;l<a;l++){var c=r[o];l+6<a&&c[l]===1&&c[l+1]===0&&c[l+2]===1&&c[l+3]===1&&c[l+4]===1&&c[l+5]===0&&c[l+6]===1&&(e.isWhiteHorizontal(c,l-4,l)||e.isWhiteHorizontal(c,l+7,l+11))&&n++,o+6<i&&r[o][l]===1&&r[o+1][l]===0&&r[o+2][l]===1&&r[o+3][l]===1&&r[o+4][l]===1&&r[o+5][l]===0&&r[o+6][l]===1&&(e.isWhiteVertical(r,l,o-4,o)||e.isWhiteVertical(r,l,o+7,o+11))&&n++}return n*e.N3},e.isWhiteHorizontal=function(t,n,r){n=Math.max(n,0),r=Math.min(r,t.length);for(var a=n;a<r;a++)if(t[a]===1)return!1;return!0},e.isWhiteVertical=function(t,n,r,a){r=Math.max(r,0),a=Math.min(a,t.length);for(var i=r;i<a;i++)if(t[i][n]===1)return!1;return!0},e.applyMaskPenaltyRule4=function(t){for(var n=0,r=t.getArray(),a=t.getWidth(),i=t.getHeight(),o=0;o<i;o++)for(var l=r[o],c=0;c<a;c++)l[c]===1&&n++;
929var u=t.getHeight()*t.getWidth(),d=Math.floor(Math.abs(n*2-u)*10/u);return d*e.N4},e.getDataMaskBit=function(t,n,r){var a,i;switch(t){case 0:a=r+n&1;break;case 1:a=r&1;break;case 2:a=n%3;break;case 3:a=(r+n)%3;break;case 4:a=Math.floor(r/2)+Math.floor(n/3)&1;break;case 5:i=r*n,a=(i&1)+i%3;break;case 6:i=r*n,a=(i&1)+i%3&1;break;case 7:i=r*n,a=i%3+(r+n&1)&1;break;default:throw new Ct("Invalid mask pattern: "+t)}return a===0},e.applyMaskPenaltyRule1Internal=function(t,n){for(var r=0,a=n?t.getHeight():t.getWidth(),i=n?t.getWidth():t.getHeight(),o=t.getArray(),l=0;l<a;l++){for(var c=0,u=-1,d=0;d<i;d++){var h=n?o[l][d]:o[d][l];h===u?c++:(c>=5&&(r+=e.N1+(c-5)),c=1,u=h)}c>=5&&(r+=e.N1+(c-5))}return r},e.N1=3,e.N2=3,e.N3=40,e.N4=10,e})(),net=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},ret=(function(){function e(t,n){this.width=t,this.height=n;for(var r=new Array(n),a=0;a!==n;a++)r[a]=new Uint8Array(t);this.bytes=r}return e.prototype.getHeight=function(){return this.height},e.prototype.getWidth=function(){return this.width},e.prototype.get=function(t,n){return this.bytes[n][t]},e.prototype.getArray=function(){return this.bytes},e.prototype.setNumber=function(t,n,r){this.bytes[n][t]=r},e.prototype.setBoolean=function(t,n,r){this.bytes[n][t]=r?1:0},e.prototype.clear=function(t){var n,r;try{for(var a=net(this.bytes),i=a.next();!i.done;i=a.next()){var o=i.value;is.fill(o,t)}}catch(l){n={error:l}}finally{try{i&&!i.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}},e.prototype.equals=function(t){if(!(t instanceof e))return!1;var n=t;if(this.width!==n.width||this.height!==n.height)return!1;for(var r=0,a=this.height;r<a;++r)for(var i=this.bytes[r],o=n.bytes[r],l=0,c=this.width;l<c;++l)if(i[l]!==o[l])return!1;return!0},e.prototype.toString=function(){for(var t=new Kt,n=0,r=this.height;n<r;++n){for(var a=this.bytes[n],i=0,o=this.width;i<o;++i)switch(a[i]){case 0:t.append(" 0");break;case 1:t.append(" 1");break;default:t.append(" ");break}t.append(` 930`)}return t.toString()},e})(),m2=(function(){function e(){this.maskPattern=-1}return e.prototype.getMode=function(){return this.mode},e.prototype.getECLevel=function(){return this.ecLevel},e.prototype.getVersion=function(){return this.version},e.prototype.getMaskPattern=function(){return this.maskPattern},e.prototype.getMatrix=function(){return this.matrix},e.prototype.toString=function(){var t=new Kt;return t.append(`<< 931`),t.append(" mode: "),t.append(this.mode?this.mode.toString():"null"),t.append(` 932 ecLevel: `),t.append(this.ecLevel?this.ecLevel.toString():"null"),t.append(` 933 version: `),t.append(this.version?this.version.toString():"null"),t.append(` 934 maskPattern: `),t.append(this.maskPattern.toString()),this.matrix?(t.append(` 935 matrix: 936`),t.append(this.matrix.toString())):t.append(` 937 matrix: null 938`),t.append(`>> 939`),t.toString()},e.prototype.setMode=function(t){this.mode=t},e.prototype.setECLevel=function(t){this.ecLevel=t},e.prototype.setVersion=function(t){this.version=t},e.prototype.setMaskPattern=function(t){this.maskPattern=t}
939,e.prototype.setMatrix=function(t){this.matrix=t},e.isValidMaskPattern=function(t){return t>=0&&t<e.NUM_MASK_PATTERNS},e.NUM_MASK_PATTERNS=8,e})(),set=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Jn=(function(e){set(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.kind="WriterException",t})(ui),I8=(function(){function e(){}return e.clearMatrix=function(t){t.clear(255)},e.buildMatrix=function(t,n,r,a,i){e.clearMatrix(i),e.embedBasicPatterns(r,i),e.embedTypeInfo(n,a,i),e.maybeEmbedVersionInfo(r,i),e.embedDataBits(t,a,i)},e.embedBasicPatterns=function(t,n){e.embedPositionDetectionPatternsAndSeparators(n),e.embedDarkDotAtLeftBottomCorner(n),e.maybeEmbedPositionAdjustmentPatterns(t,n),e.embedTimingPatterns(n)},e.embedTypeInfo=function(t,n,r){var a=new ks;e.makeTypeInfoBits(t,n,a);for(var i=0,o=a.getSize();i<o;++i){var l=a.get(a.getSize()-1-i),c=e.TYPE_INFO_COORDINATES[i],u=c[0],d=c[1];if(r.setBoolean(u,d,l),i<8){var h=r.getWidth()-i-1,f=8;r.setBoolean(h,f,l)}else{var h=8,f=r.getHeight()-7+(i-8);r.setBoolean(h,f,l)}}},e.maybeEmbedVersionInfo=function(t,n){if(!(t.getVersionNumber()<7)){var r=new ks;e.makeVersionInfoBits(t,r);for(var a=17,i=0;i<6;++i)for(var o=0;o<3;++o){var l=r.get(a);a--,n.setBoolean(i,n.getHeight()-11+o,l),n.setBoolean(n.getHeight()-11+o,i,l)}}},e.embedDataBits=function(t,n,r){for(var a=0,i=-1,o=r.getWidth()-1,l=r.getHeight()-1;o>0;){for(o===6&&(o-=1);l>=0&&l<r.getHeight();){for(var c=0;c<2;++c){var u=o-c;if(e.isEmpty(r.get(u,l))){var d=void 0;a<t.getSize()?(d=t.get(a),++a):d=!1,n!==255&&Hm.getDataMaskBit(n,u,l)&&(d=!d),r.setBoolean(u,l,d)}}l+=i}i=-i,l+=i,o-=2}if(a!==t.getSize())throw new Jn("Not all bits consumed: "+a+"/"+t.getSize())},e.findMSBSet=function(t){return 32-Zt.numberOfLeadingZeros(t)},e.calculateBCHCode=function(t,n){if(n===0)throw new Ct("0 polynomial");var r=e.findMSBSet(n);for(t<<=r-1;e.findMSBSet(t)>=r;)t^=n<<e.findMSBSet(t)-r;return t},e.makeTypeInfoBits=function(t,n,r){if(!m2.isValidMaskPattern(n))throw new Jn("Invalid mask pattern");var a=t.getBits()<<3|n;r.appendBits(a,5);var i=e.calculateBCHCode(a,e.TYPE_INFO_POLY);r.appendBits(i,10);var o=new ks;if(o.appendBits(e.TYPE_INFO_MASK_PATTERN,15),r.xor(o),r.getSize()!==15)throw new Jn("should not happen but we got: "+r.getSize())},e.makeVersionInfoBits=function(t,n){n.appendBits(t.getVersionNumber(),6);var r=e.calculateBCHCode(t.getVersionNumber(),e.VERSION_INFO_POLY);if(n.appendBits(r,12),n.getSize()!==18)throw new Jn("should not happen but we got: "+n.getSize())},e.isEmpty=function(t){return t===255},e.embedTimingPatterns=function(t){for(var n=8;n<t.getWidth()-8;++n){var r=(n+1)%2;e.isEmpty(t.get(n,6))&&t.setNumber(n,6,r),e.isEmpty(t.get(6,n))&&t.setNumber(6,n,r)}},e.embedDarkDotAtLeftBottomCorner=function(t){if(t.get(8,t.getHeight()-8)===0)throw new Jn;t.setNumber(8,t.getHeight()-8,1)},e.embedHorizontalSeparationPattern=function(t,n,r){for(var a=0;a<8;++a){if(!e.isEmpty(r.get(t+a,n)))throw new Jn;r.setNumber(t+a,n,0)}},e.embedVerticalSeparationPattern=function(t,n,r){for(var a=0;a<7;++a){if(!e.isEmpty(r.get(t,n+a)))throw new Jn;r.setNumber(t,n+a,0)}},e.embedPositionAdjustmentPattern=function(t,n,r){for(var a=0;a<5;++a)for(var i=e.POSITION_ADJUSTMENT_PATTERN[a],o=0;o<5;++o)r.setNumber(t+o,n+a,i[o])},e.embedPositionDetectionPattern=function(t,n,r){for(var a=0;a<7;++a)for(var i=e.POSITION_DETECTION_PATTERN[a],o=0;o<7;++o)r.setNumber(t+o,n+a,i[o])},e.embedPositionDetectionPatternsAndSeparators=function(t){var n=e.POSITION_DETECTION_PATTERN[0].length;e.embedPositionDetectionPattern(0,0,t),e.embedPositionDetectionPattern(t.getWidth()-n,0,t),e.embedPositionDetectionPattern(0,t.getWidth()-n,t);var r=8;e.embedHorizontalSeparationPattern(0,r-1,t),e.embedHorizontalSeparationPattern(t.getWidth()-r,r-1,t),e.embedHorizontalSeparationPattern(0,t.getWidth()-r,t);var a=7;e.embedVerticalSeparationPattern(a,0,t),e.embedVerticalSeparationPattern(t.getHeight()-a-1,0,t),e.embedVerticalSeparationPattern(a,t.getHeight()-a,t)},e.maybeEmbedPositionAdjustmentPatterns=function(t,n){if(!(t.getVersionNumber()<2))for(var r=t.getVersionNumber()-1,a=e.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE[r],i=0,o=a.length;i!==o;i++){var l=a[i];if(l>=0)for(var c=0;c!==o;c++){var u=a[c];u>=0&&e.isEmpty(n.get(u,l))&&e.embedPositionAdjustmentPattern(u-2,l-2,n)}}},e.POSITION_DETECTION_PATTERN=Array.from([Int32Array.from([1,1,1,1,1,1,1]),Int32Array.from([1,0,0,0,0,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,1,1,1,0,1]),Int32Array.from([1,0,0,0,0,0,1]),Int32Array.from([1,1,1,1,1,1,1])]),e.POSITION_ADJUSTMENT_PATTERN=Array.from([Int32Array.from([1,1,1,1,1]),Int32Array.from([1,0,0,0,1]),Int32Array.from([1,0,1,0,1]),Int32Array.from([1,0,0,0,1]),Int32Array.from([1,1,1,1,1])]),e.POSITION_ADJUSTMENT_PATTERN_COORDINATE_TABLE=Array.from([Int32Array.from([-1,-1,-1,-1,-1,-1,-1]),Int32Array.from([6,18,-1,-1,-1,-1,-1]),Int32Array.from([6,22,-1,-1,-1,-1,-1]),Int32Array.from([6,26,-1,-1,-1,-1,-1]),Int32Array.from([6,30,-1,-1,-1,-1,-1]),Int32Array.from([6,34,-1,-1,-1,-1,-1]),Int32Array.from([6,22,38,-1,-1,-1,-1]),Int32Array.from([6,24,42,-1,-1,-1,-1]),Int32Array.from([6,26,46,-1,-1,-1,-1]),Int32Array.from([6,28,50,-1,-1,-1,-1]),Int32Array.from([6,30,54,-1,-1,-1,-1]),Int32Array.from([6,32,58,-1,-1,-1,-1]),Int32Array.from([6,34,62,-1,-1,-1,-1]),Int32Array.from([6,26,46,66,-1,-1,-1]),Int32Array.from([6,26,48,70,-1,-1,-1]),Int32Array.from([6,26,50,74,-1,-1,-1]),Int32Array.from([6,30,54,78,-1,-1,-1]),Int32Array.from([6,30,56,82,-1,-1,-1]),Int32Array.from([6,30,58,86,-1,-1,-1]),Int32Array.from([6,34,62,90,-1,-1,-1]),Int32Array.from([6,28,50,72,94,-1,-1]),Int32Array.from([6,26,50,74,98,-1,-1]),Int32Array.from([6,30,54,78,102,-1,-1]),Int32Array.from([6,28,54,80,106,-1,-1]),Int32Array.from([6,32,58,84,110,-1,-1]),Int32Array.from([6,30,58,86,114,-1,-1]),Int32Array.from([6,34,62,90,118,-1,-1]),Int32Array.from([6,26,50,74,98,122,-1]),Int32Array.from([6,30,54,78,102,126,-1]),Int32Array.from([6,26,52,78,104,130,-1]),Int32Array.from([6,30,56,82,108,134,-1]),Int32Array.from([6,34,60,86,112,138,-1]),Int32Array.from([6,30,58,86,114,142,-1]),Int32Array.from([6,34,62,90,118,146,-1]),Int32Array.from([6,30,54,78,102,126,150]),Int32Array.from([6,24,50,76,102,128,154]),Int32Array.from([6,28,54,80,106,132,158]),Int32Array.from([6,32,58,84,110,136,162]),Int32Array.from([6,26,54,82,110,138,166]),Int32Array.from([6,30,58,86,114,142,170])]),e.TYPE_INFO_COORDINATES=Array.from([Int32Array.from([8,0]),Int32Array.from([8,1]),Int32Array.from([8,2]),Int32Array.from([8,3]),Int32Array.from([8,4]),Int32Array.from([8,5]),Int32Array.from([8,7]),Int32Array.from([8,8]),Int32Array.from([7,8]),Int32Array.from([5,8]),Int32Array.from([4,8]),Int32Array.from([3,8]),Int32Array.from([2,8]),Int32Array.from([1,8]),Int32Array.from([0,8])]),e.VERSION_INFO_POLY=7973,e.TYPE_INFO_POLY=1335,e.TYPE_INFO_MASK_PATTERN=21522,e})(),aet=(function(){function e(t,n){this.dataBytes=t,this.errorCorrectionBytes=n}return e.prototype.getDataBytes=function(){return this.dataBytes},e.prototype.getErrorCorrectionBytes=function(){return this.errorCorrectionBytes},e})(),P8=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);
939if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},iet=(function(){function e(){}return e.calculateMaskPenalty=function(t){return Hm.applyMaskPenaltyRule1(t)+Hm.applyMaskPenaltyRule2(t)+Hm.applyMaskPenaltyRule3(t)+Hm.applyMaskPenaltyRule4(t)},e.encode=function(t,n,r){r===void 0&&(r=null);var a=e.DEFAULT_BYTE_MODE_ENCODING,i=r!==null&&r.get(Qo.CHARACTER_SET)!==void 0;i&&(a=r.get(Qo.CHARACTER_SET).toString());var o=this.chooseMode(t,a),l=new ks;if(o===Qn.BYTE&&(i||e.DEFAULT_BYTE_MODE_ENCODING!==a)){var c=as.getCharacterSetECIByName(a);c!==void 0&&this.appendECI(c,l)}this.appendModeInfo(o,l);var u=new ks;this.appendBytes(t,o,u,a);var d;if(r!==null&&r.get(Qo.QR_VERSION)!==void 0){var h=Number.parseInt(r.get(Qo.QR_VERSION).toString(),10);d=xd.getVersionForNumber(h);var f=this.calculateBitsNeeded(o,l,u,d);if(!this.willFit(f,d,n))throw new Jn("Data too big for requested version")}else d=this.recommendVersion(n,o,l,u);var m=new ks;m.appendBitArray(l);var x=o===Qn.BYTE?u.getSizeInBytes():t.length;this.appendLengthInfo(x,d,o,m),m.appendBitArray(u);var g=d.getECBlocksForLevel(n),y=d.getTotalCodewords()-g.getTotalECCodewords();this.terminateBits(y,m);var b=this.interleaveWithECBytes(m,d.getTotalCodewords(),y,g.getNumBlocks()),v=new m2;v.setECLevel(n),v.setMode(o),v.setVersion(d);var w=d.getDimensionForVersion(),_=new ret(w,w),k=this.chooseMaskPattern(b,n,d,_);return v.setMaskPattern(k),I8.buildMatrix(b,n,d,k,_),v.setMatrix(_),v},e.recommendVersion=function(t,n,r,a){var i=this.calculateBitsNeeded(n,r,a,xd.getVersionForNumber(1)),o=this.chooseVersion(i,t),l=this.calculateBitsNeeded(n,r,a,o);return this.chooseVersion(l,t)},e.calculateBitsNeeded=function(t,n,r,a){return n.getSize()+t.getCharacterCountBits(a)+r.getSize()},e.getAlphanumericCode=function(t){return t<e.ALPHANUMERIC_TABLE.length?e.ALPHANUMERIC_TABLE[t]:-1},e.chooseMode=function(t,n){if(n===void 0&&(n=null),as.SJIS.getName()===n&&this.isOnlyDoubleByteKanji(t))return Qn.KANJI;for(var r=!1,a=!1,i=0,o=t.length;i<o;++i){var l=t.charAt(i);if(e.isDigit(l))r=!0;else if(this.getAlphanumericCode(l.charCodeAt(0))!==-1)a=!0;else return Qn.BYTE}return a?Qn.ALPHANUMERIC:r?Qn.NUMERIC:Qn.BYTE},e.isOnlyDoubleByteKanji=function(t){var n;try{n=ri.encode(t,as.SJIS)}catch{return!1}var r=n.length;if(r%2!==0)return!1;for(var a=0;a<r;a+=2){var i=n[a]&255;if((i<129||i>159)&&(i<224||i>235))return!1}return!0},e.chooseMaskPattern=function(t,n,r,a){for(var i=Number.MAX_SAFE_INTEGER,o=-1,l=0;l<m2.NUM_MASK_PATTERNS;l++){I8.buildMatrix(t,n,r,l,a);var c=this.calculateMaskPenalty(a);c<i&&(i=c,o=l)}return o},e.chooseVersion=function(t,n){for(var r=1;r<=40;r++){var a=xd.getVersionForNumber(r);if(e.willFit(t,a,n))return a}throw new Jn("Data too big")},e.willFit=function(t,n,r){var a=n.getTotalCodewords(),i=n.getECBlocksForLevel(r),o=i.getTotalECCodewords(),l=a-o,c=(t+7)/8;return l>=c},e.terminateBits=function(t,n){var r=t*8;if(n.getSize()>r)throw new Jn("data bits cannot fit in the QR Code"+n.getSize()+" > "+r);for(var a=0;a<4&&n.getSize()<r;++a)n.appendBit(!1);var i=n.getSize()&7;if(i>0)for(var a=i;a<8;a++)n.appendBit(!1);for(var o=t-n.getSizeInBytes(),a=0;a<o;++a)n.appendBits((a&1)===0?236:17,8);if(n.getSize()!==r)throw new Jn("Bits size does not equal capacity")},e.getNumDataBytesAndNumECBytesForBlockID=function(t,n,r,a,i,o){if(a>=r)throw new Jn("Block ID too large");var l=t%r,c=r-l,u=Math.floor(t/r),d=u+1,h=Math.floor(n/r),f=h+1,m=u-h,x=d-f;if(m!==x)throw new Jn("EC bytes mismatch");if(r!==c+l)throw new Jn("RS blocks mismatch");if(t!==(h+m)*c+(f+x)*l)throw new Jn("Total bytes mismatch");a<c?(i[0]=h,o[0]=m):(i[0]=f,o[0]=x)},e.interleaveWithECBytes=function(t,n,r,a){var i,o,l,c;if(t.getSizeInBytes()!==r)throw new Jn("Number of bits and data bytes does not match");for(var u=0,d=0,h=0,f=new Array,m=0;m<a;++m){var x=new Int32Array(1),g=new Int32Array(1);e.getNumDataBytesAndNumECBytesForBlockID(n,r,a,m,x,g);var y=x[0],b=new Uint8Array(y);t.toBytes(8*u,b,0,y);var v=e.generateECBytes(b,g[0]);f.push(new aet(b,v)),d=Math.max(d,y),h=Math.max(h,v.length),u+=x[0]}if(r!==u)throw new Jn("Data bytes does not match offset");for(var w=new ks,m=0;m<d;++m)try{for(var _=(i=void 0,P8(f)),k=_.next();!k.done;k=_.next()){var j=k.value,b=j.getDataBytes();m<b.length&&w.appendBits(b[m],8)}}catch(C){i={error:C}}
939finally{try{k&&!k.done&&(o=_.return)&&o.call(_)}finally{if(i)throw i.error}}for(var m=0;m<h;++m)try{for(var N=(l=void 0,P8(f)),E=N.next();!E.done;E=N.next()){var j=E.value,v=j.getErrorCorrectionBytes();m<v.length&&w.appendBits(v[m],8)}}catch(C){l={error:C}}finally{try{E&&!E.done&&(c=N.return)&&c.call(N)}finally{if(l)throw l.error}}if(n!==w.getSizeInBytes())throw new Jn("Interleaving error: "+n+" and "+w.getSizeInBytes()+" differ.");return w},e.generateECBytes=function(t,n){for(var r=t.length,a=new Int32Array(r+n),i=0;i<r;i++)a[i]=t[i]&255;new nY(ra.QR_CODE_FIELD_256).encode(a,n);for(var o=new Uint8Array(n),i=0;i<n;i++)o[i]=a[r+i];return o},e.appendModeInfo=function(t,n){n.appendBits(t.getBits(),4)},e.appendLengthInfo=function(t,n,r,a){var i=r.getCharacterCountBits(n);if(t>=1<<i)throw new Jn(t+" is bigger than "+((1<<i)-1));a.appendBits(t,i)},e.appendBytes=function(t,n,r,a){switch(n){case Qn.NUMERIC:e.appendNumericBytes(t,r);break;case Qn.ALPHANUMERIC:e.appendAlphanumericBytes(t,r);break;case Qn.BYTE:e.append8BitBytes(t,r,a);break;case Qn.KANJI:e.appendKanjiBytes(t,r);break;default:throw new Jn("Invalid mode: "+n)}},e.getDigit=function(t){return t.charCodeAt(0)-48},e.isDigit=function(t){var n=e.getDigit(t);return n>=0&&n<=9},e.appendNumericBytes=function(t,n){for(var r=t.length,a=0;a<r;){var i=e.getDigit(t.charAt(a));if(a+2<r){var o=e.getDigit(t.charAt(a+1)),l=e.getDigit(t.charAt(a+2));n.appendBits(i*100+o*10+l,10),a+=3}else if(a+1<r){var o=e.getDigit(t.charAt(a+1));n.appendBits(i*10+o,7),a+=2}else n.appendBits(i,4),a++}},e.appendAlphanumericBytes=function(t,n){for(var r=t.length,a=0;a<r;){var i=e.getAlphanumericCode(t.charCodeAt(a));if(i===-1)throw new Jn;if(a+1<r){var o=e.getAlphanumericCode(t.charCodeAt(a+1));if(o===-1)throw new Jn;n.appendBits(i*45+o,11),a+=2}else n.appendBits(i,6),a++}},e.append8BitBytes=function(t,n,r){var a;try{a=ri.encode(t,r)}catch(c){throw new Jn(c)}for(var i=0,o=a.length;i!==o;i++){var l=a[i];n.appendBits(l,8)}},e.appendKanjiBytes=function(t,n){var r;try{r=ri.encode(t,as.SJIS)}catch(h){throw new Jn(h)}for(var a=r.length,i=0;i<a;i+=2){var o=r[i]&255,l=r[i+1]&255,c=o<<8&4294967295|l,u=-1;if(c>=33088&&c<=40956?u=c-33088:c>=57408&&c<=60351&&(u=c-49472),u===-1)throw new Jn("Invalid byte sequence");var d=(u>>8)*192+(u&255);n.appendBits(d,13)}},e.appendECI=function(t,n){n.appendBits(Qn.ECI.getBits(),4),n.appendBits(t.getValue(),8)},e.ALPHANUMERIC_TABLE=Int32Array.from([-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,36,-1,-1,-1,37,38,-1,-1,-1,-1,39,40,-1,41,42,43,0,1,2,3,4,5,6,7,8,9,44,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,-1]),e.DEFAULT_BYTE_MODE_ENCODING=as.UTF8.getName(),e})(),oet=(function(){function e(){}return e.prototype.encode=function(t,n,r,a,i){if(t.length===0)throw new Ct("Found empty contents");if(n!==wt.QR_CODE)throw new Ct("Can only encode QR_CODE, but got "+n);if(r<0||a<0)throw new Ct("Requested dimensions are too small: ".concat(r,"x").concat(a));var o=u2.L,l=e.QUIET_ZONE_SIZE;i!==null&&(i.get(Qo.ERROR_CORRECTION)!==void 0&&(o=u2.fromString(i.get(Qo.ERROR_CORRECTION).toString())),i.get(Qo.MARGIN)!==void 0&&(l=Number.parseInt(i.get(Qo.MARGIN).toString(),10)));var c=iet.encode(t,o,i);return e.renderResult(c,r,a,l)},e.renderResult=function(t,n,r,a){var i=t.getMatrix();if(i===null)throw new Gf;for(var o=i.getWidth(),l=i.getHeight(),c=o+a*2,u=l+a*2,d=Math.max(n,c),h=Math.max(r,u),f=Math.min(Math.floor(d/c),Math.floor(h/u)),m=Math.floor((d-o*f)/2),x=Math.floor((h-l*f)/2),g=new _i(d,h),y=0,b=x;y<l;y++,b+=f)for(var v=0,w=m;v<o;v++,w+=f)i.get(v,y)===1&&g.setRegion(w,b,f,f);return g},e.QUIET_ZONE_SIZE=4,e})(),cet=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
939t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();(function(e){cet(t,e);function t(n,r,a,i,o,l,c,u){var d=e.call(this,l,c)||this;if(d.yuvData=n,d.dataWidth=r,d.dataHeight=a,d.left=i,d.top=o,i+l>r||o+c>a)throw new Ct("Crop rectangle does not fit within image data.");return u&&d.reverseHorizontal(l,c),d}return t.prototype.getRow=function(n,r){if(n<0||n>=this.getHeight())throw new Ct("Requested row is outside the image: "+n);var a=this.getWidth();(r==null||r.length<a)&&(r=new Uint8ClampedArray(a));var i=(n+this.top)*this.dataWidth+this.left;return Fn.arraycopy(this.yuvData,i,r,0,a),r},t.prototype.getMatrix=function(){var n=this.getWidth(),r=this.getHeight();if(n===this.dataWidth&&r===this.dataHeight)return this.yuvData;var a=n*r,i=new Uint8ClampedArray(a),o=this.top*this.dataWidth+this.left;if(n===this.dataWidth)return Fn.arraycopy(this.yuvData,o,i,0,a),i;for(var l=0;l<r;l++){var c=l*n;Fn.arraycopy(this.yuvData,o,i,c,n),o+=this.dataWidth}return i},t.prototype.isCropSupported=function(){return!0},t.prototype.crop=function(n,r,a,i){return new t(this.yuvData,this.dataWidth,this.dataHeight,this.left+n,this.top+r,a,i,!1)},t.prototype.renderThumbnail=function(){for(var n=this.getWidth()/t.THUMBNAIL_SCALE_FACTOR,r=this.getHeight()/t.THUMBNAIL_SCALE_FACTOR,a=new Int32Array(n*r),i=this.yuvData,o=this.top*this.dataWidth+this.left,l=0;l<r;l++){for(var c=l*n,u=0;u<n;u++){var d=i[o+u*t.THUMBNAIL_SCALE_FACTOR]&255;a[c+u]=4278190080|d*65793}o+=this.dataWidth*t.THUMBNAIL_SCALE_FACTOR}return a},t.prototype.getThumbnailWidth=function(){return this.getWidth()/t.THUMBNAIL_SCALE_FACTOR},t.prototype.getThumbnailHeight=function(){return this.getHeight()/t.THUMBNAIL_SCALE_FACTOR},t.prototype.reverseHorizontal=function(n,r){for(var a=this.yuvData,i=0,o=this.top*this.dataWidth+this.left;i<r;i++,o+=this.dataWidth)for(var l=o+n/2,c=o,u=o+n-1;c<l;c++,u--){var d=a[c];a[c]=a[u],a[u]=d}},t.prototype.invert=function(){return new sT(this)},t.THUMBNAIL_SCALE_FACTOR=2,t})(Fw);var uet=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();(function(e){uet(t,e);function t(n,r,a,i,o,l,c){var u=e.call(this,r,a)||this;if(u.dataWidth=i,u.dataHeight=o,u.left=l,u.top=c,n.BYTES_PER_ELEMENT===4){for(var d=r*a,h=new Uint8ClampedArray(d),f=0;f<d;f++){var m=n[f],x=m>>16&255,g=m>>7&510,y=m&255;h[f]=(x+g+y)/4&255}u.luminances=h}else u.luminances=n;if(i===void 0&&(u.dataWidth=r),o===void 0&&(u.dataHeight=a),l===void 0&&(u.left=0),c===void 0&&(u.top=0),u.left+r>u.dataWidth||u.top+a>u.dataHeight)throw new Ct("Crop rectangle does not fit within image data.");return u}return t.prototype.getRow=function(n,r){if(n<0||n>=this.getHeight())throw new Ct("Requested row is outside the image: "+n);var a=this.getWidth();(r==null||r.length<a)&&(r=new Uint8ClampedArray(a));var i=(n+this.top)*this.dataWidth+this.left;return Fn.arraycopy(this.luminances,i,r,0,a),r},t.prototype.getMatrix=function(){var n=this.getWidth(),r=this.getHeight();if(n===this.dataWidth&&r===this.dataHeight)return this.luminances;var a=n*r,i=new Uint8ClampedArray(a),o=this.top*this.dataWidth+this.left;if(n===this.dataWidth)return Fn.arraycopy(this.luminances,o,i,0,a),i;for(var l=0;l<r;l++){var c=l*n;Fn.arraycopy(this.luminances,o,i,c,n),o+=this.dataWidth}return i},t.prototype.isCropSupported=function(){return!0},t.prototype.crop=function(n,r,a,i){return new t(this.luminances,a,i,this.dataWidth,this.dataHeight,this.left+n,this.top+r)},t.prototype.invert=function(){return new sT(this)},t})(Fw);var det=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
939t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),het=(function(e){det(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.forName=function(n){return this.getCharacterSetECIByName(n)},t})(as),fet=(function(){function e(){}return e.ISO_8859_1=as.ISO8859_1,e})(),p2,met=301,pet=function(e,t){for(var n=1,r=0;r<255;r++)t[r]=n,e[n]=r,n*=2,n>=256&&(n^=met);return{LOG:e,ALOG:t}};p2=pet([],[]),p2.LOG;p2.ALOG;var R8;(function(e){e[e.FORCE_NONE=0]="FORCE_NONE",e[e.FORCE_SQUARE=1]="FORCE_SQUARE",e[e.FORCE_RECTANGLE=2]="FORCE_RECTANGLE"})(R8||(R8={}));var D8=129,rY=230,xet=231,get=235,yet=236,bet=237,vet=238,wet=239,_et=240,Lj=254,ket=254,M8="[)>�05�",$8="[)>�06�",L8="��",An=0,Rs=1,ka=2,ns=3,ys=4,Xs=5,jet=(function(){function e(){}return e.prototype.getEncodingMode=function(){return An},e.prototype.encode=function(t){var n=yo.determineConsecutiveDigitCount(t.getMessage(),t.pos);if(n>=2)t.writeCodeword(this.encodeASCIIDigits(t.getMessage().charCodeAt(t.pos),t.getMessage().charCodeAt(t.pos+1))),t.pos+=2;else{var r=t.getCurrentChar(),a=yo.lookAheadTest(t.getMessage(),t.pos,this.getEncodingMode());if(a!==this.getEncodingMode())switch(a){case Xs:t.writeCodeword(xet),t.signalEncoderChange(Xs);return;case Rs:t.writeCodeword(rY),t.signalEncoderChange(Rs);return;case ns:t.writeCodeword(vet),t.signalEncoderChange(ns);break;case ka:t.writeCodeword(wet),t.signalEncoderChange(ka);break;case ys:t.writeCodeword(_et),t.signalEncoderChange(ys);break;default:throw new Error("Illegal mode: "+a)}else yo.isExtendedASCII(r)?(t.writeCodeword(get),t.writeCodeword(r-128+1),t.pos++):(t.writeCodeword(r+1),t.pos++)}},e.prototype.encodeASCIIDigits=function(t,n){if(yo.isDigit(t)&&yo.isDigit(n)){var r=(t-48)*10+(n-48);return r+130}throw new Error("not digits: "+t+n)},e})(),Net=(function(){function e(){}return e.prototype.getEncodingMode=function(){return Xs},e.prototype.encode=function(t){var n=new Kt;for(n.append(0);t.hasMoreCharacters();){var r=t.getCurrentChar();n.append(r),t.pos++;var a=yo.lookAheadTest(t.getMessage(),t.pos,this.getEncodingMode());if(a!==this.getEncodingMode()){t.signalEncoderChange(An);break}}var i=n.length()-1,o=1,l=t.getCodewordCount()+i+o;t.updateSymbolInfo(l);var c=t.getSymbolInfo().getDataCapacity()-l>0;if(t.hasMoreCharacters()||c)if(i<=249)n.setCharAt(0,tn.getCharAt(i));else if(i<=1555)n.setCharAt(0,tn.getCharAt(Math.floor(i/250)+249)),n.insert(1,tn.getCharAt(i%250));else throw new Error("Message length not in valid ranges: "+i);for(var u=0,r=n.length();u<r;u++)t.writeCodeword(this.randomize255State(n.charAt(u).charCodeAt(0),t.getCodewordCount()+1))},e.prototype.randomize255State=function(t,n){var r=149*n%255+1,a=t+r;return a<=255?a:a-256},e})(),cT=(function(){function e(){}return e.prototype.getEncodingMode=function(){return Rs},e.prototype.encodeMaximal=function(t){for(var n=new Kt,r=0,a=t.pos,i=0;t.hasMoreCharacters();){var o=t.getCurrentChar();t.pos++,r=this.encodeChar(o,n),n.length()%3===0&&(a=t.pos,i=n.length())}if(i!==n.length()){var l=Math.floor(n.length()/3*2),c=Math.floor(t.getCodewordCount()+l+1);t.updateSymbolInfo(c);var u=t.getSymbolInfo().getDataCapacity()-c,d=Math.floor(n.length()%3);(d===2&&u!==2||d===1&&(r>3||u!==1))&&(t.pos=a)}n.length()>0&&t.writeCodeword(rY),this.handleEOD(t,n)},e.prototype.encode=function(t){for(var n=new Kt;t.hasMoreCharacters();){var r=t.getCurrentChar();t.pos++;var a=this.encodeChar(r,n),i=Math.floor(n.length()/3)*2,o=t.getCodewordCount()+i;t.updateSymbolInfo(o);var l=t.getSymbolInfo().getDataCapacity()-o;if(!t.hasMoreCharacters()){var c=new Kt;for(n.length()%3===2&&l!==2&&(a=this.backtrackOneCharacter(t,n,c,a));n.length()%3===1&&(a>3||l!==1);)a=this.backtrackOneCharacter(t,n,c,a);break}var u=n.length();if(u%3===0){var d=yo.lookAheadTest(t.getMessage(),t.pos,this.getEncodingMode());if(d!==this.getEncodingMode()){t.signalEncoderChange(An);break}}}this.handleEOD(t,n)},e.prototype.backtrackOneCharacter=function(t,n,r,a){var i=n.length(),o=n.toString().substring(0,i-a);n.setLengthToZero(),n.append(o),t.pos--;var l=t.getCurrentChar();return a=this.encodeChar(l,r),t.resetSymbolInfo(),a},e.prototype.writeNextTriplet=function(t,n){t.writeCodewords(this.encodeToCodewords(n.toString()));var r=n.toString().substring(3);n.setLengthToZero(),n.append(r)},e.prototype.handleEOD=function(t,n){var r=Math.floor(n.length()/3*2),a=n.length()%3,i=t.getCodewordCount()+r;t.updateSymbolInfo(i);var o=t.getSymbolInfo().getDataCapacity()-i;
939if(a===2){for(n.append("\0");n.length()>=3;)this.writeNextTriplet(t,n);t.hasMoreCharacters()&&t.writeCodeword(Lj)}else if(o===1&&a===1){for(;n.length()>=3;)this.writeNextTriplet(t,n);t.hasMoreCharacters()&&t.writeCodeword(Lj),t.pos--}else if(a===0){for(;n.length()>=3;)this.writeNextTriplet(t,n);(o>0||t.hasMoreCharacters())&&t.writeCodeword(Lj)}else throw new Error("Unexpected case. Please report!");t.signalEncoderChange(An)},e.prototype.encodeChar=function(t,n){if(t===32)return n.append(3),1;if(t>=48&&t<=57)return n.append(t-48+4),1;if(t>=65&&t<=90)return n.append(t-65+14),1;if(t<32)return n.append(0),n.append(t),2;if(t<=47)return n.append(1),n.append(t-33),2;if(t<=64)return n.append(1),n.append(t-58+15),2;if(t<=95)return n.append(1),n.append(t-91+22),2;if(t<=127)return n.append(2),n.append(t-96),2;n.append("".concat(1,"�"));var r=2;return r+=this.encodeChar(t-128,n),r},e.prototype.encodeToCodewords=function(t){var n=1600*t.charCodeAt(0)+40*t.charCodeAt(1)+t.charCodeAt(2)+1,r=n/256,a=n%256,i=new Kt;return i.append(r),i.append(a),i.toString()},e})(),Cet=(function(){function e(){}return e.prototype.getEncodingMode=function(){return ys},e.prototype.encode=function(t){for(var n=new Kt;t.hasMoreCharacters();){var r=t.getCurrentChar();this.encodeChar(r,n),t.pos++;var a=n.length();if(a>=4){t.writeCodewords(this.encodeToCodewords(n.toString()));var i=n.toString().substring(4);n.setLengthToZero(),n.append(i);var o=yo.lookAheadTest(t.getMessage(),t.pos,this.getEncodingMode());if(o!==this.getEncodingMode()){t.signalEncoderChange(An);break}}}n.append(tn.getCharAt(31)),this.handleEOD(t,n)},e.prototype.handleEOD=function(t,n){try{var r=n.length();if(r===0)return;if(r===1){t.updateSymbolInfo();var a=t.getSymbolInfo().getDataCapacity()-t.getCodewordCount(),i=t.getRemainingCharacters();if(i>a&&(t.updateSymbolInfo(t.getCodewordCount()+1),a=t.getSymbolInfo().getDataCapacity()-t.getCodewordCount()),i<=a&&a<=2)return}if(r>4)throw new Error("Count must not exceed 4");var o=r-1,l=this.encodeToCodewords(n.toString()),c=!t.hasMoreCharacters(),u=c&&o<=2;if(o<=2){t.updateSymbolInfo(t.getCodewordCount()+o);var a=t.getSymbolInfo().getDataCapacity()-t.getCodewordCount();a>=3&&(u=!1,t.updateSymbolInfo(t.getCodewordCount()+l.length))}u?(t.resetSymbolInfo(),t.pos-=o):t.writeCodewords(l)}finally{t.signalEncoderChange(An)}},e.prototype.encodeChar=function(t,n){t>=32&&t<=63?n.append(t):t>=64&&t<=94?n.append(tn.getCharAt(t-64)):yo.illegalCharacter(tn.getCharAt(t))},e.prototype.encodeToCodewords=function(t){var n=t.length;if(n===0)throw new Error("StringBuilder must not be empty");var r=t.charAt(0).charCodeAt(0),a=n>=2?t.charAt(1).charCodeAt(0):0,i=n>=3?t.charAt(2).charCodeAt(0):0,o=n>=4?t.charAt(3).charCodeAt(0):0,l=(r<<18)+(a<<12)+(i<<6)+o,c=l>>16&255,u=l>>8&255,d=l&255,h=new Kt;return h.append(c),n>=2&&h.append(u),n>=3&&h.append(d),h.toString()},e})(),Eet=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Aet=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},vn=(function(){function e(t,n,r,a,i,o,l,c){l===void 0&&(l=0),c===void 0&&(c=0),this.rectangular=t,this.dataCapacity=n,this.errorCodewords=r,this.matrixWidth=a,this.matrixHeight=i,this.dataRegions=o,this.rsBlockData=l,this.rsBlockError=c}return e.lookup=function(t,n,r,a,i){var o,l;n===void 0&&(n=0),r===void 0&&(r=null),a===void 0&&(a=null),i===void 0&&(i=!0);try{for(var c=Aet(Oet),u=c.next();!u.done;u=c.next()){var d=u.value;if(!(n===1&&d.rectangular)&&!(n===2&&!d.rectangular)&&!(r!=null&&(d.getSymbolWi
939dth()<r.getWidth()||d.getSymbolHeight()<r.getHeight()))&&!(a!=null&&(d.getSymbolWidth()>a.getWidth()||d.getSymbolHeight()>a.getHeight()))&&t<=d.dataCapacity)return d}}catch(h){o={error:h}}finally{try{u&&!u.done&&(l=c.return)&&l.call(c)}finally{if(o)throw o.error}}if(i)throw new Error("Can't find a symbol arrangement that matches the message. Data codewords: "+t);return null},e.prototype.getHorizontalDataRegions=function(){switch(this.dataRegions){case 1:return 1;case 2:case 4:return 2;case 16:return 4;case 36:return 6;default:throw new Error("Cannot handle this number of data regions")}},e.prototype.getVerticalDataRegions=function(){switch(this.dataRegions){case 1:case 2:return 1;case 4:return 2;case 16:return 4;case 36:return 6;default:throw new Error("Cannot handle this number of data regions")}},e.prototype.getSymbolDataWidth=function(){return this.getHorizontalDataRegions()*this.matrixWidth},e.prototype.getSymbolDataHeight=function(){return this.getVerticalDataRegions()*this.matrixHeight},e.prototype.getSymbolWidth=function(){return this.getSymbolDataWidth()+this.getHorizontalDataRegions()*2},e.prototype.getSymbolHeight=function(){return this.getSymbolDataHeight()+this.getVerticalDataRegions()*2},e.prototype.getCodewordCount=function(){return this.dataCapacity+this.errorCodewords},e.prototype.getInterleavedBlockCount=function(){return this.rsBlockData?this.dataCapacity/this.rsBlockData:1},e.prototype.getDataCapacity=function(){return this.dataCapacity},e.prototype.getErrorCodewords=function(){return this.errorCodewords},e.prototype.getDataLengthForInterleavedBlock=function(t){return this.rsBlockData},e.prototype.getErrorLengthForInterleavedBlock=function(t){return this.rsBlockError},e})(),Tet=(function(e){Eet(t,e);function t(){return e.call(this,!1,1558,620,22,22,36,-1,62)||this}return t.prototype.getInterleavedBlockCount=function(){return 10},t.prototype.getDataLengthForInterleavedBlock=function(n){return n<=8?156:155},t})(vn),Oet=[new vn(!1,3,5,8,8,1),new vn(!1,5,7,10,10,1),new vn(!0,5,7,16,6,1),new vn(!1,8,10,12,12,1),new vn(!0,10,11,14,6,2),new vn(!1,12,12,14,14,1),new vn(!0,16,14,24,10,1),new vn(!1,18,14,16,16,1),new vn(!1,22,18,18,18,1),new vn(!0,22,18,16,10,2),new vn(!1,30,20,20,20,1),new vn(!0,32,24,16,14,2),new vn(!1,36,24,22,22,1),new vn(!1,44,28,24,24,1),new vn(!0,49,28,22,14,2),new vn(!1,62,36,14,14,4),new vn(!1,86,42,16,16,4),new vn(!1,114,48,18,18,4),new vn(!1,144,56,20,20,4),new vn(!1,174,68,22,22,4),new vn(!1,204,84,24,24,4,102,42),new vn(!1,280,112,14,14,16,140,56),new vn(!1,368,144,16,16,16,92,36),new vn(!1,456,192,18,18,16,114,48),new vn(!1,576,224,20,20,16,144,56),new vn(!1,696,272,22,22,16,174,68),new vn(!1,816,336,24,24,16,136,56),new vn(!1,1050,408,18,18,36,175,68),new vn(!1,1304,496,20,20,36,163,62),new Tet],Iet=(function(){function e(t){this.msg=t,this.pos=0,this.skipAtEnd=0;for(var n=t.split("").map(function(l){return l.charCodeAt(0)}),r=new Kt,a=0,i=n.length;a<i;a++){var o=String.fromCharCode(n[a]&255);if(o==="?"&&t.charAt(a)!=="?")throw new Error("Message contains characters outside ISO-8859-1 encoding.");r.append(o)}this.msg=r.toString(),this.shape=0,this.codewords=new Kt,this.newEncoding=-1}return e.prototype.setSymbolShape=function(t){this.shape=t},e.prototype.setSizeConstraints=function(t,n){this.minSize=t,this.maxSize=n},e.prototype.getMessage=function(){return this.msg},e.prototype.setSkipAtEnd=function(t){this.skipAtEnd=t},e.prototype.getCurrentChar=function(){return this.msg.charCodeAt(this.pos)},e.prototype.getCurrent=function(){return this.msg.charCodeAt(this.pos)},e.prototype.getCodewords=function(){return this.codewords},e.prototype.writeCodewords=function(t){this.codewords.append(t)},e.prototype.writeCodeword=function(t){this.codewords.append(t)},e.prototype.getCodewordCount=function(){return this.codewords.length()},e.prototype.getNewEncoding=function(){return this.newEncoding},e.prototype.signalEncoderChange=function(t){this.newEncoding=t},e.prototype.resetEncoderSignal=function(){this.newEncoding=-1},e.prototype.hasMoreCharacters=function(){return this.pos<this.getTotalMessageCharCount()},e.prototype.getTotalMessageCharCount=function(){return this.msg.length-this.skipAtEnd},e.prototype.getRemainingCharacters=function(){return this.getTotalMessageCharCount()-this.pos},e.prototype.getSymbolInfo=function(){return this.symbolInfo},e.prototype.updateSymbolInfo=function(t){t===void 0&&(t=this.getCodewordCount()),(this.symbolInfo==null||t>this.symbolInfo.getDataCapacity())&&(this.symbolInfo=vn.lookup(t,this.shape,this.minSize,this.maxSize,!0))},e.prototype.resetSymbolInfo=function(){this.symbolInfo=null},e})(),Pet=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}
939t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Ret=(function(e){Pet(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.getEncodingMode=function(){return ns},t.prototype.encode=function(n){for(var r=new Kt;n.hasMoreCharacters();){var a=n.getCurrentChar();n.pos++,this.encodeChar(a,r);var i=r.length();if(i%3===0){this.writeNextTriplet(n,r);var o=yo.lookAheadTest(n.getMessage(),n.pos,this.getEncodingMode());if(o!==this.getEncodingMode()){n.signalEncoderChange(An);break}}}this.handleEOD(n,r)},t.prototype.encodeChar=function(n,r){switch(n){case 13:r.append(0);break;case 42:r.append(1);break;case 62:r.append(2);break;case 32:r.append(3);break;default:n>=48&&n<=57?r.append(n-48+4):n>=65&&n<=90?r.append(n-65+14):yo.illegalCharacter(tn.getCharAt(n));break}return 1},t.prototype.handleEOD=function(n,r){n.updateSymbolInfo();var a=n.getSymbolInfo().getDataCapacity()-n.getCodewordCount(),i=r.length();n.pos-=i,(n.getRemainingCharacters()>1||a>1||n.getRemainingCharacters()!==a)&&n.writeCodeword(ket),n.getNewEncoding()<0&&n.signalEncoderChange(An)},t})(cT),Det=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Met=(function(e){Det(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.getEncodingMode=function(){return ka},t.prototype.encodeChar=function(n,r){if(n===32)return r.append(3),1;if(n>=48&&n<=57)return r.append(n-48+4),1;if(n>=97&&n<=122)return r.append(n-97+14),1;if(n<32)return r.append(0),r.append(n),2;if(n<=47)return r.append(1),r.append(n-33),2;if(n<=64)return r.append(1),r.append(n-58+15),2;if(n>=91&&n<=95)return r.append(1),r.append(n-91+22),2;if(n===96)return r.append(2),r.append(0),2;if(n<=90)return r.append(2),r.append(n-65+1),2;if(n<=127)return r.append(2),r.append(n-123+27),2;r.append("".concat(1,"�"));var a=2;return a+=this.encodeChar(n-128,r),a},t})(cT),yo=(function(){function e(){}return e.randomize253State=function(t){var n=149*t%253+1,r=D8+n;return r<=254?r:r-254},e.encodeHighLevel=function(t,n,r,a,i){n===void 0&&(n=0),r===void 0&&(r=null),a===void 0&&(a=null),i===void 0&&(i=!1);var o=new cT,l=[new jet,o,new Met,new Ret,new Cet,new Net],c=new Iet(t);c.setSymbolShape(n),c.setSizeConstraints(r,a),t.startsWith(M8)&&t.endsWith(L8)?(c.writeCodeword(yet),c.setSkipAtEnd(2),c.pos+=M8.length):t.startsWith($8)&&t.endsWith(L8)&&(c.writeCodeword(bet),c.setSkipAtEnd(2),c.pos+=$8.length);var u=An;for(i&&(o.encodeMaximal(c),u=c.getNewEncoding(),c.resetEncoderSignal());c.hasMoreCharacters();)l[u].encode(c),c.getNewEncoding()>=0&&(u=c.getNewEncoding(),c.resetEncoderSignal());var d=c.getCodewordCount();c.updateSymbolInfo();var h=c.getSymbolInfo().getDataCapacity();d<h&&u!==An&&u!==Xs&&u!==ys&&c.writeCodeword("þ");var f=c.getCodewords();for(f.length()<h&&f.append(D8);f.length()<h;)f.append(this.randomize253State(f.length()+1));return c.getCodewords().toString()},e.lookAheadTest=function(t,n,r){var a=this.lookAheadTestIntern(t,n,r);if(r===ns&&a===ns){for(var i=Math.min(n+3,t.length),o=n;o<i;o++)if(!this.isNativeX12(t.charCodeAt(o)))return An}else if(r===ys&&a===ys){for(var i=Math.min(n+4,t.length),o=n;o<i;o++)if(!this.isNativeEDIFACT(t.charCodeAt(o)))return An}return a},e.lookAheadTestIntern=function(t,n,r){if(n>=t.length)return r;var a;r===An?a=[0,1,1,1,1,1.25]:(a=[1,2,2,2,2,2.25],a[r]=0);for(var i=0,o=new Uint8Array(6),l=[];;){if(n+i===t.length){is.fill(o,0),is.fill(l,0);var c=this.findMinimums(a,l,Zt.MAX_VALUE,o),u=this.getMinimumCount(o);if(l[An]===c)return An;if(u===1){if(o[Xs]>0)return Xs;if(o[ys]>0)return ys;if(o[ka]>0)return ka;if(o[ns]>0)return ns}return Rs}var d=t.charCodeAt(n+i);if(i++,this.isDigit(d)?a[An]+=.5:this.isExtendedASCII(d)?(a[An]=Math.ceil(a[An]),a[An]+=2):(a[An]=Math.ceil(a[An]),a[An]++),this.isNativeC40(d)?a[Rs]+=2/3:this.isExtendedASCII(d)?a[Rs]+=8/3:a[Rs]+=4/3,this.isNativeText(d)?a[ka]+=2/3:this.isExtendedASCII(d)?a[ka]+=8/3:a[ka]+=4/3,this.isNativeX12(d)?a[ns]+=2/3:this.isExtendedASCII(d)?a[ns]+=13/3:a[ns]+=10/3,this.isNativeEDIFACT(d)?a[ys]+=3/4:this.isExtendedASCII(d)?a[ys]+=17/4:a[ys]+=13/4,this.isSpecialB256(d)?a[Xs]+=4:a[Xs]++,i>=4){if(is.fill(o,0),is.fill(l,0),this.findMinimums(a,l,Zt.MAX_VALUE,o),l[An]<this.min(l[Xs],l[Rs],l[ka],l[ns],l[ys]))return An;if(l[Xs]<l[An]||l[Xs]+1<this.min(l[Rs],l[ka],l[ns],l[ys]))return Xs;if(l[ys]+1<this.min(l[Xs],l[Rs],l[ka],l[ns],l[An]))return ys;if(l[ka]+1<this.min(l[Xs],l[Rs],l[ys],l[ns],l[An]))return ka;if(l[ns]+1<this.min(l[Xs],l[Rs],l[ys],l[ka],l[An]))return ns;if(l[Rs]+1<this.min(l[An],l[Xs],l[ys],l[ka])){if(l[Rs]<l[ns])return Rs;if(l[Rs]===l[ns]){for(var h=n+i+1;h<t.length;){var f=t.charCodeAt(h);if(this.isX12TermSep(f))return ns;if(!this.isNativeX12(f))break;h++}return Rs}}}}},e.min=function(t,n,r,a,i){var o=Math.min(t,Math.min(n,Math.min(r,a)));return i===void 0?o:Math.min(o,i)},e.findMinimums=function(t,n,r,a){for(var i=0;i<6;i++){var o=n[i]=Math.ceil(t[i]);r>o&&(r=o,is.fill(a,0)),r===o&&(a[i]=a[i]+1)}return r},e.getMinimumCount=function(t){for(var n=0,r=0;r<6;r++)n+=t[r];return n||0},e.isDigit=function(t){return t>=48&&t<=57},e.isExtendedASCII=function(t){return t>=128&&t<=255},e.isNativeC40=function(t){return t===32||t>=48&&t<=57||t>=65&&t<=90},e.isNativeText=function(t){return t===32||t>=48&&t<=57||t>=97&&t<=122},e.isNativeX12=function(t){return this.isX12TermSep(t)||t===32||t>=48&&t<=57||t>=65&&t<=90},e.isX12TermSep=function(t){return t===13||t===42||t===62},e.isNativeEDIFACT=function(t){return t>=32&&t<=94},e.isSpecialB256=function(t){return!1},e.determineConsecutiveDigitCount=function(t,n){n===void 0&&(n=0);for(var r=t.length,a=n;a<r&&this.isDigit(t.charCodeAt(a));)a++;return a-n},e.illegalCharacter=function(t){var n=Zt.toHexString(t.charCodeAt(0));throw n="0000".substring(0,4-n.length)+n,new Error("Illegal character: "+t+" (0x"+n+")")},e})(),Fj=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);
939if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},F8=(function(){function e(t){this.charset=t,this.name=t.name}return e.prototype.canEncode=function(t){try{return ri.encode(t,this.charset)!=null}catch{return!1}},e})(),$et=(function(){function e(t,n,r){var a,i,o,l,c,u;this.ENCODERS=["IBM437","ISO-8859-2","ISO-8859-3","ISO-8859-4","ISO-8859-5","ISO-8859-6","ISO-8859-7","ISO-8859-8","ISO-8859-9","ISO-8859-10","ISO-8859-11","ISO-8859-13","ISO-8859-14","ISO-8859-15","ISO-8859-16","windows-1250","windows-1251","windows-1252","windows-1256","Shift_JIS"].map(function(A){return new F8(het.forName(A))}),this.encoders=[];var d=[];d.push(new F8(fet.ISO_8859_1));for(var h=n!=null&&n.name.startsWith("UTF"),f=0;f<t.length;f++){var m=!1;try{for(var x=(a=void 0,Fj(d)),g=x.next();!g.done;g=x.next()){var y=g.value,b=t.charAt(f),v=b.charCodeAt(0);if(v===r||y.canEncode(b)){m=!0;break}}}catch(A){a={error:A}}finally{try{g&&!g.done&&(i=x.return)&&i.call(x)}finally{if(a)throw a.error}}if(!m)try{for(var w=(o=void 0,Fj(this.ENCODERS)),_=w.next();!_.done;_=w.next()){var y=_.value;if(y.canEncode(t.charAt(f))){d.push(y),m=!0;break}}}catch(A){o={error:A}}finally{try{_&&!_.done&&(l=w.return)&&l.call(w)}finally{if(o)throw o.error}}m||(h=!0)}if(d.length===1&&!h)this.encoders=[d[0]];else{this.encoders=[];var k=0;try{for(var j=Fj(d),N=j.next();!N.done;N=j.next()){var y=N.value;this.encoders[k++]=y}}catch(A){c={error:A}}finally{try{N&&!N.done&&(u=j.return)&&u.call(j)}finally{if(c)throw c.error}}}var E=-1;if(n!=null){for(var f=0;f<this.encoders.length;f++)if(this.encoders[f]!=null&&n.name===this.encoders[f].name){E=f;break}}this.priorityEncoderIndex=E}return e.prototype.length=function(){return this.encoders.length},e.prototype.getCharsetName=function(t){if(!(t<this.length()))throw new Error("index must be less than length");return this.encoders[t].name},e.prototype.getCharset=function(t){if(!(t<this.length()))throw new Error("index must be less than length");return this.encoders[t].charset},e.prototype.getECIValue=function(t){return this.encoders[t].charset.getValueIdentifier()},e.prototype.getPriorityEncoderIndex=function(){return this.priorityEncoderIndex},e.prototype.canEncode=function(t,n){if(!(n<this.length()))throw new Error("index must be less than length");return!0},e.prototype.encode=function(t,n){if(!(n<this.length()))throw new Error("index must be less than length");return ri.encode(tn.getCharAt(t),this.encoders[n].name)},e})(),Let=3,Fet=(function(){function e(t,n,r){this.fnc1=r;var a=new $et(t,n,r);if(a.length()===1)for(var i=0;i<this.bytes.length;i++){var o=t.charAt(i).charCodeAt(0);this.bytes[i]=o===r?1e3:o}else this.bytes=this.encodeMinimally(t,a,r)}return e.prototype.getFNC1Character=function(){return this.fnc1},e.prototype.length=function(){return this.bytes.length},e.prototype.haveNCharacters=function(t,n){if(t+n-1>=this.bytes.length)return!1;for(var r=0;r<n;r++)if(this.isECI(t+r))return!1;return!0},e.prototype.charAt=function(t){if(t<0||t>=this.length())throw new Error(""+t);if(this.isECI(t))throw new Error("value at "+t+" is not a character but an ECI");return this.isFNC1(t)?this.fnc1:this.bytes[t]},e.prototype.subSequence=function(t,n){if(t<0||t>n||n>this.length())throw new Error(""+t);for(var r=new Kt,a=t;a<n;a++){if(this.isECI(a))throw new Error("value at "+a+" is not a character but an ECI");r.append(this.charAt(a))}return r.toString()},e.prototype.isECI=function(t){if(t<0||t>=this.length())throw new Error(""+t);return this.bytes[t]>255&&this.bytes[t]<=999},e.prototype.isFNC1=function(t){if(t<0||t>=this.length())throw new Error(""+t);return this.bytes[t]===1e3},e.prototype.getECIValue=function(t){if(t<0||t>=this.length())throw new Error(""+t);if(!this.isECI(t))throw new Error("value at "+t+" is not an ECI but a character");return this.bytes[t]-256},e.prototype.addEdge=function(t,n,r){(t[n][r.encoderIndex]==null||t[n][r.encoderIndex].cachedTotalSize>r.cachedTotalSize)&&(t[n][r.encoderIndex]=r)},e.prototype.addEdges=function(t,n,r,a,i,o){var l=t.charAt(a).charCo
939deAt(0),c=0,u=n.length();n.getPriorityEncoderIndex()>=0&&(l===o||n.canEncode(l,n.getPriorityEncoderIndex()))&&(c=n.getPriorityEncoderIndex(),u=c+1);for(var d=c;d<u;d++)(l===o||n.canEncode(l,d))&&this.addEdge(r,a+1,new B8(l,n,d,i,o))},e.prototype.encodeMinimally=function(t,n,r){var a=t.length,i=new B8[a+1][n.length()];this.addEdges(t,n,i,0,null,r);for(var o=1;o<=a;o++){for(var l=0;l<n.length();l++)i[o][l]!=null&&o<a&&this.addEdges(t,n,i,o,i[o][l],r);for(var l=0;l<n.length();l++)i[o-1][l]=null}for(var c=-1,u=Zt.MAX_VALUE,l=0;l<n.length();l++)if(i[a][l]!=null){var d=i[a][l];d.cachedTotalSize<u&&(u=d.cachedTotalSize,c=l)}if(c<0)throw new Error('Failed to encode "'+t+'"');for(var h=[],f=i[a][c];f!=null;){if(f.isFNC1())h.unshift(1e3);else for(var m=n.encode(f.c,f.encoderIndex),o=m.length-1;o>=0;o--)h.unshift(m[o]&255);var x=f.previous===null?0:f.previous.encoderIndex;x!==f.encoderIndex&&h.unshift(256+n.getECIValue(f.encoderIndex)),f=f.previous}for(var g=[],o=0;o<g.length;o++)g[o]=h[o];return g},e})(),B8=(function(){function e(t,n,r,a,i){this.c=t,this.encoderSet=n,this.encoderIndex=r,this.previous=a,this.fnc1=i,this.c=t===i?1e3:t;var o=this.isFNC1()?1:n.encode(t,r).length,l=a===null?0:a.encoderIndex;l!==r&&(o+=Let),a!=null&&(o+=a.cachedTotalSize),this.cachedTotalSize=o}return e.prototype.isFNC1=function(){return this.c===1e3},e})(),Bet=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),U8;(function(e){e[e.ASCII=0]="ASCII",e[e.C40=1]="C40",e[e.TEXT=2]="TEXT",e[e.X12=3]="X12",e[e.EDF=4]="EDF",e[e.B256=5]="B256"})(U8||(U8={}));(function(e){Bet(t,e);function t(n,r,a,i,o){var l=e.call(this,n,r,a)||this;return l.shape=i,l.macroId=o,l}return t.prototype.getMacroId=function(){return this.macroId},t.prototype.getShapeHint=function(){return this.shape},t})(Fet);var Uet=(function(){function e(){}return e.prototype.isCompact=function(){return this.compact},e.prototype.setCompact=function(t){this.compact=t},e.prototype.getSize=function(){return this.size},e.prototype.setSize=function(t){this.size=t},e.prototype.getLayers=function(){return this.layers},e.prototype.setLayers=function(t){this.layers=t},e.prototype.getCodeWords=function(){return this.codeWords},e.prototype.setCodeWords=function(t){this.codeWords=t},e.prototype.getMatrix=function(){return this.matrix}
939,e.prototype.setMatrix=function(t){this.matrix=t},e})(),z8=(function(){function e(){}return e.singletonList=function(t){return[t]},e.min=function(t,n){return t.sort(n)[0]},e})(),zet=(function(){function e(t){this.previous=t}return e.prototype.getPrevious=function(){return this.previous},e})(),Wet=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),uT=(function(e){Wet(t,e);function t(n,r,a){var i=e.call(this,n)||this;return i.value=r,i.bitCount=a,i}return t.prototype.appendTo=function(n,r){n.appendBits(this.value,this.bitCount)},t.prototype.add=function(n,r){return new t(this,n,r)},t.prototype.addBinaryShift=function(n,r){return console.warn("addBinaryShift on SimpleToken, this simply returns a copy of this token"),new t(this,n,r)},t.prototype.toString=function(){var n=this.value&(1<<this.bitCount)-1;return n|=1<<this.bitCount,"<"+Zt.toBinaryString(n|1<<this.bitCount).substring(1)+">"},t})(zet),Ket=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,a){r.__proto__=a}||function(r,a){for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(r[i]=a[i])},e(t,n)};return function(t,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),Het=(function(e){Ket(t,e);function t(n,r,a){var i=e.call(this,n,0,0)||this;return i.binaryShiftStart=r,i.binaryShiftByteCount=a,i}return t.prototype.appendTo=function(n,r){for(var a=0;a<this.binaryShiftByteCount;a++)(a===0||a===31&&this.binaryShiftByteCount<=62)&&(n.appendBits(31,5),this.binaryShiftByteCount>62?n.appendBits(this.binaryShiftByteCount-31,16):a===0?n.appendBits(Math.min(this.binaryShiftByteCount,31),5):n.appendBits(this.binaryShiftByteCount-31,5)),n.appendBits(r[this.binaryShiftStart+a],8)},t.prototype.addBinaryShift=function(n,r){return new t(this,n,r)},t.prototype.toString=function(){return"<"+this.binaryShiftStart+"::"+(this.binaryShiftStart+this.binaryShiftByteCount-1)+">"},t})(uT);function Vet(e,t,n){return new Het(e,t,n)}function Im(e,t,n){return new uT(e,t,n)}var qet=["UPPER","LOWER","DIGIT","MIXED","PUNCT"],eu=0,Bv=1,Hi=2,sY=3,el=4,Get=new uT(null,0,0),Bj=[Int32Array.from([0,(5<<16)+28,(5<<16)+30,(5<<16)+29,656318]),Int32Array.from([(9<<16)+480+14,0,(5<<16)+30,(5<<16)+29,656318]),Int32Array.from([(4<<16)+14,(9<<16)+448+28,0,(9<<16)+448+29,932798]),Int32Array.from([(5<<16)+29,(5<<16)+28,656318,0,(5<<16)+30]),Int32Array.from([(5<<16)+31,656380,656382,656381,0])],Yet=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};function Zet(e){var t,n;try{for(var r=Yet(e),a=r.next();!a.done;a=r.next()){var i=a.value;is.fill(i,-1)}}catch(o){t={error:o}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(t)throw t.error}}return e[eu][el]=0,e[Bv][el]=0,e[Bv][eu]=28,e[sY][el]=0,e[Hi][el]=0,e[Hi][eu]=15,e}var aY=Zet(is.createInt32Array(6,6)),Xet=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},Jet=(function(){function e(t,n,r,a){this.token=t,this.mode=n,this.binaryShiftByteCount=r,this.bitCount=a}return e.prototype.getMode=function(){return this.mode},e.prototype.getToken=function(){return this.token},e.prototype.getBinaryShiftByteCount=function(){return this.binaryShiftByteCount},e.prototype.getBitCount=function(){return this.bitCount},e.prototype.latchAndAppend=function(t,n){var r=this.bitCount,a=this.token;if(t!==this.mode){var i=Bj[this.mode][t];a=Im(a,i&65535,i>>16),r+=i>>16}var o=t===Hi?4:5;return a=Im(a,n,o),new e(a,t,0,r+o)},e.prototype.shiftAndAppend=function(t,n){var r=this.token,a=this.mode===
939Hi?4:5;return r=Im(r,aY[this.mode][t],a),r=Im(r,n,5),new e(r,this.mode,0,this.bitCount+a+5)},e.prototype.addBinaryShiftChar=function(t){var n=this.token,r=this.mode,a=this.bitCount;if(this.mode===el||this.mode===Hi){var i=Bj[r][eu];n=Im(n,i&65535,i>>16),a+=i>>16,r=eu}var o=this.binaryShiftByteCount===0||this.binaryShiftByteCount===31?18:this.binaryShiftByteCount===62?9:8,l=new e(n,r,this.binaryShiftByteCount+1,a+o);return l.binaryShiftByteCount===2078&&(l=l.endBinaryShift(t+1)),l},e.prototype.endBinaryShift=function(t){if(this.binaryShiftByteCount===0)return this;var n=this.token;return n=Vet(n,t-this.binaryShiftByteCount,this.binaryShiftByteCount),new e(n,this.mode,0,this.bitCount)},e.prototype.isBetterThanOrEqualTo=function(t){var n=this.bitCount+(Bj[this.mode][t.mode]>>16);return this.binaryShiftByteCount<t.binaryShiftByteCount?n+=e.calculateBinaryShiftCost(t)-e.calculateBinaryShiftCost(this):this.binaryShiftByteCount>t.binaryShiftByteCount&&t.binaryShiftByteCount>0&&(n+=10),n<=t.bitCount},e.prototype.toBitArray=function(t){for(var n,r,a=[],i=this.endBinaryShift(t.length).token;i!==null;i=i.getPrevious())a.unshift(i);var o=new ks;try{for(var l=Xet(a),c=l.next();!c.done;c=l.next()){var u=c.value;u.appendTo(o,t)}}catch(d){n={error:d}}finally{try{c&&!c.done&&(r=l.return)&&r.call(l)}finally{if(n)throw n.error}}return o},e.prototype.toString=function(){return tn.format("%s bits=%d bytes=%d",qet[this.mode],this.bitCount,this.binaryShiftByteCount)},e.calculateBinaryShiftCost=function(t){return t.binaryShiftByteCount>62?21:t.binaryShiftByteCount>31?20:t.binaryShiftByteCount>0?10:0},e.INITIAL_STATE=new e(Get,eu,0,0),e})();function Qet(e){var t=tn.getCharCode(" "),n=tn.getCharCode("."),r=tn.getCharCode(",");e[eu][t]=1;for(var a=tn.getCharCode("Z"),i=tn.getCharCode("A"),o=i;o<=a;o++)e[eu][o]=o-i+2;e[Bv][t]=1;for(var l=tn.getCharCode("z"),c=tn.getCharCode("a"),o=c;o<=l;o++)e[Bv][o]=o-c+2;e[Hi][t]=1;for(var u=tn.getCharCode("9"),d=tn.getCharCode("0"),o=d;o<=u;o++)e[Hi][o]=o-d+2;e[Hi][r]=12,e[Hi][n]=13;for(var h=["\0"," ","�","�","�","�","�","�","\x07","\b"," ",` 940`,"\v","\f","\r","\x1B","�","�","�","�","@","\\","^","_","`","|","~","�"],f=0;f<h.length;f++)e[sY][tn.getCharCode(h[f])]=f;for(var m=["\0","\r","\0","\0","\0","\0","!","'","#","$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","?","[","]","{","}"],f=0;f<m.length;f++)tn.getCharCode(m[f])>0&&(e[el][tn.getCharCode(m[f])]=f);return e}var Uj=Qet(is.createInt32Array(5,256)),by=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},ett=(function(){function e(t){this.text=t}return e.prototype.encode=function(){for(var t=tn.getCharCode(" "),n=tn.getCharCode(` 941`),r=z8.singletonList(Jet.INITIAL_STATE),a=0;a<this.text.length;a++){var i=void 0,o=a+1<this.text.length?this.text[a+1]:0;switch(this.text[a]){case tn.getCharCode("\r"):i=o===n?2:0;break;case tn.getCharCode("."):i=o===t?3:0;break;case tn.getCharCode(","):i=o===t?4:0;break;case tn.getCharCode(":"):i=o===t?5:0;break;default:i=0}i>0?(r=e.updateStateListForPair(r,a,i),a++):r=this.updateStateListForChar(r,a)}var l=z8.min(r,function(c,u){return c.getBitCount()-u.getBitCount()});return l.toBitArray(this.text)},e.prototype.updateStateListForChar=function(t,n){var r,a,i=[];try{for(var o=by(t),l=o.next();!l.done;l=o.next()){var c=l.value;this.updateStateForChar(c,n,i)}}catch(u){r={error:u}}finally{try{l&&!l.done&&(a=o.return)&&a.call(o)}finally{if(r)throw r.error}}return e.simplifyStates(i)},e.prototype.updateStateForChar=function(t,n,r){for(var a=this.text[n]&255,i=Uj[t.getMode()][a]>0,o=null,l=0;l<=el;l++){var c=Uj[l][a];if(c>0){if(o==null&&(o=t.endBinaryShift(n)),!i||l===t.getMode()||l===Hi){var u=o.latchAndAppend(l,c);r.push(u)}if(!i&&aY[t.getMode()][l]>=0){var d=o.shiftAndAppend(l,c);r.push(d)}}}if(t.getBinaryShiftByteCount()>0||Uj[t.getMode()][a]===0){var h=t.addBinaryShiftChar(n);
941r.push(h)}},e.updateStateListForPair=function(t,n,r){var a,i,o=[];try{for(var l=by(t),c=l.next();!c.done;c=l.next()){var u=c.value;this.updateStateForPair(u,n,r,o)}}catch(d){a={error:d}}finally{try{c&&!c.done&&(i=l.return)&&i.call(l)}finally{if(a)throw a.error}}return this.simplifyStates(o)},e.updateStateForPair=function(t,n,r,a){var i=t.endBinaryShift(n);if(a.push(i.latchAndAppend(el,r)),t.getMode()!==el&&a.push(i.shiftAndAppend(el,r)),r===3||r===4){var o=i.latchAndAppend(Hi,16-r).latchAndAppend(Hi,1);a.push(o)}if(t.getBinaryShiftByteCount()>0){var l=t.addBinaryShiftChar(n).addBinaryShiftChar(n+1);a.push(l)}},e.simplifyStates=function(t){var n,r,a,i,o=[];try{for(var l=by(t),c=l.next();!c.done;c=l.next()){var u=c.value,d=!0,h=function(y){if(y.isBetterThanOrEqualTo(u))return d=!1,"break";u.isBetterThanOrEqualTo(y)&&(o=o.filter(function(b){return b!==y}))};try{for(var f=(a=void 0,by(o)),m=f.next();!m.done;m=f.next()){var x=m.value,g=h(x);if(g==="break")break}}catch(y){a={error:y}}finally{try{m&&!m.done&&(i=f.return)&&i.call(f)}finally{if(a)throw a.error}}d&&o.push(u)}}catch(y){n={error:y}}finally{try{c&&!c.done&&(r=l.return)&&r.call(l)}finally{if(n)throw n.error}}return o},e})(),ttt=function(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};(function(){function e(){}return e.encodeBytes=function(t){return e.encode(t,e.DEFAULT_EC_PERCENT,e.DEFAULT_AZTEC_LAYERS)},e.encode=function(t,n,r){var a=new ett(t).encode(),i=Zt.truncDivision(a.getSize()*n,100)+11,o=a.getSize()+i,l,c,u,d,h;if(r!==e.DEFAULT_AZTEC_LAYERS){if(l=r<0,c=Math.abs(r),c>(l?e.MAX_NB_BITS_COMPACT:e.MAX_NB_BITS))throw new Ct(tn.format("Illegal value %s for layers",r));u=e.totalBitsInLayer(c,l),d=e.WORD_SIZE[c];var f=u-u%d;if(h=e.stuffBits(a,d),h.getSize()+i>f)throw new Ct("Data to large for user specified layer");if(l&&h.getSize()>d*64)throw new Ct("Data to large for user specified layer")}else{d=0,h=null;for(var m=0;;m++){if(m>e.MAX_NB_BITS)throw new Ct("Data too large for an Aztec code");if(l=m<=3,c=l?m+1:m,u=e.totalBitsInLayer(c,l),!(o>u)){(h==null||d!==e.WORD_SIZE[c])&&(d=e.WORD_SIZE[c],h=e.stuffBits(a,d));var f=u-u%d;if(!(l&&h.getSize()>d*64)&&h.getSize()+i<=f)break}}}var x=e.generateCheckWords(h,u,d),g=h.getSize()/d,y=e.generateModeMessage(l,c,g),b=(l?11:14)+c*4,v=new Int32Array(b),w;if(l){w=b;for(var m=0;m<v.length;m++)v[m]=m}else{w=b+1+2*Zt.truncDivision(Zt.truncDivision(b,2)-1,15);for(var _=Zt.truncDivision(b,2),k=Zt.truncDivision(w,2),m=0;m<_;m++){var j=m+Zt.truncDivision(m,15);v[_-m-1]=k-j-1,v[_+m]=k+j+1}}for(var N=new _i(w),m=0,E=0;m<c;m++){for(var A=(c-m)*4+(l?9:12),C=0;C<A;C++)for(var T=C*2,S=0;S<2;S++)x.get(E+T+S)&&N.set(v[m*2+S],v[m*2+C]),x.get(E+A*2+T+S)&&N.set(v[m*2+C],v[b-1-m*2-S]),x.get(E+A*4+T+S)&&N.set(v[b-1-m*2-S],v[b-1-m*2-C]),x.get(E+A*6+T+S)&&N.set(v[b-1-m*2-C],v[m*2+S]);E+=A*8}if(e.drawModeMessage(N,l,w,y),l)e.drawBullsEye(N,Zt.truncDivision(w,2),5);else{e.drawBullsEye(N,Zt.truncDivision(w,2),7);for(var m=0,C=0;m<Zt.truncDivision(b,2)-1;m+=15,C+=16)for(var S=Zt.truncDivision(w,2)&1;S<w;S+=2)N.set(Zt.truncDivision(w,2)-C,S),N.set(Zt.truncDivision(w,2)+C,S),N.set(S,Zt.truncDivision(w,2)-C),N.set(S,Zt.truncDivision(w,2)+C)}var O=new Uet;return O.setCompact(l),O.setSize(w),O.setLayers(c),O.setCodeWords(g),O.setMatrix(N),O},e.drawBullsEye=function(t,n,r){for(var a=0;a<r;a+=2)for(var i=n-a;i<=n+a;i++)t.set(i,n-a),t.set(i,n+a),t.set(n-a,i),t.set(n+a,i);t.set(n-r,n-r),t.set(n-r+1,n-r),t.set(n-r,n-r+1),t.set(n+r,n-r),t.set(n+r,n-r+1),t.set(n+r,n+r-1)},e.generateModeMessage=function(t,n,r){var a=new ks;return t?(a.appendBits(n-1,2),a.appendBits(r-1,6),a=e.generateCheckWords(a,28,4)):(a.appendBits(n-1,5),a.appendBits(r-1,11),a=e.generateCheckWords(a,40,4)),a},e.drawModeMessage=function(t,n,r,a){var i=Zt.truncDivision(r,2);if(n)for(var o=0;o<7;o++){var l=i-3+o;a.get(o)&&t.set(l,i-5),a.get(o+7)&&t.set(i+5,l),a.get(20-o)&&t.set(l,i+5),a.get(27-o)&&t.set(i-5,l)}else for(var o=0;o<10;o++){var l=i-5+o+Zt.truncDivision(o,5);a.get(o)&&t.set(l,i-7),a.get(o+10)&&t.set(i+7,l),a.get(29-o)&&t.set(l,i+7),a.get(39-o)&&t.set(i-7,l)}},e.generateCheckWords=function(t,n,r){var a,i,o=t.getSize()/r,l=new nY(e.getGF(r)),c=Zt.truncDivision(n,r),u=e.bitsToWords(t,r,c);l.encode(u,c-o);var d=n%r,h=new ks;h.appendBits(0,d);try{for(var f=ttt(Array.from(u)),m=f.next();!m.done;m=f.next()){var x=m.value;h.appendBits(x,r)}}catch(g){a={error:g}}finally{try{m&&!m.done&&(i=f.return)&&i.call(f)}finally{if(a)throw a.error}}return h},e.bitsToWords=function(t,n,r){var a=new Int32Array(r),i,o;for(i=0,o=t.getSize()/n;i<o;i++){for(var l=0,c=0;c<n;c++)l|=t.get(i*n+c)?1<<n-c-1:0;a[i]=l}return a},e.getGF=function(t){switch(t){case 4:return ra.AZTEC_PARAM;case 6:return ra.AZTEC_DATA_6;case 8:return ra.AZTEC_DATA_8;case 10:return ra.AZTEC_DATA_10;case 12:return ra.AZTEC_DATA_12;default:throw new Ct("Unsupported word size "+t)}},e.stuffBits=function(t,n){for(var r=new ks,a=t.getSize(),i=(1<<n)-2,o=0;o<a;o+=n){for(var l=0,c=0;c<n;c++)(o+c>=a||t.get(o+c))&&(l|=1<<n-1-c);(l&i)===i?(r.appendBits(l&i,n),o--):(l&i)===0?(r.appendBits(l|1,n),o--):r.appendBits(l,n)}return r},e.totalBitsInLayer=function(t,n){return((n?88:112)+16*t)*t},e.DEFAULT_EC_PERCENT=33,e.DEFAULT_AZTEC_LAYERS=0,e.MAX_NB_BITS=32,e.MAX_NB_BITS_COMPACT=4,e.WORD_SIZE=Int32Array.from([4,6,6,8,8,8,8,8,8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,12,12,12,12,12,12,12,12,12,12]),e})();function ntt(e,t,n=216){const r=new Map,a=new oet().encode(t,wt.QR_CODE,n,n,r),i=a.getWidth(),o=a.getHeight(),l=typeof window<"u"&&window.devicePixelRatio||1;e.width=i*l,e.height=o*l,e.style.width=`${n}px`,e.style.height=`${n}px`;const c=e.getContext("2d");if(c){c.scale(l,l),c.fillStyle="#FFFFFF",c.fillRect(0,0,i,o),c.fillStyle="#0C111D";for(let u=0;u<o;u++)for(let d=0;d<i;d++)a.get(d,u)&&c.fillRect(d,u,1,1)}}const rtt=3e4;function stt(){const e=p.useRef(null),[t,n]=p.useState(!1),[r,a]=p.useState("loading"),[i,o]=p.useState(null);return p.useEffect(()=>{if(!t)return;let l=!1;async function c(){try{const{code:d}=await UZe();if(l)return;e.current&&ntt(e.current,zZe(d)),a("ready"),o(null)}catch(d){if(l)return;const h=d;a("error"),o((h==null?void 0:h.status)===403?"Linking the mobile app is available on a paid plan.":`Couldn't create a code â ${(h==null?void 0:h.message)||h}`)}}c();const u=window.setInterval(c,rtt);return()=>{l=!0,window.clearInterval(u)}},[t]),s.jsxs("div",{children:[s.jsx("h2",{className:"text-base font-semibold text-text-primary mb-3",children:"Mobile app"}),s.jsx(V,{children:s.jsxs("div",{className:"p-4 flex items-start gap-3",children:[s.jsx("div",{className:"w-9 h-9 rounded-md bg-surface-sunken text-text-secondary flex items-center justify-center shrink-0",children:s.jsx(mF,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Link a device"}),s.jsx("div",{className:"text-xs text-text-secondary",children:"Open Gadjet on your phone,
941choose âLink a deviceâ, and scan this code to sign in â no password needed."}),t&&s.jsxs("div",{className:"mt-4 flex flex-col items-start gap-2",children:[s.jsx("div",{className:"rounded-lg border border-outline-faint bg-surface p-3",children:s.jsx("canvas",{ref:e,className:r==="ready"?"":"opacity-30"})}),r==="loading"&&s.jsx("div",{className:"text-xs text-text-secondary",children:"Generatingâ¦"}),r==="error"&&s.jsx("div",{className:"text-xs text-text-error",children:i}),r==="ready"&&s.jsx("div",{className:"text-xs text-text-secondary",children:"Code refreshes automatically. Keep this open while you scan."})]})]}),s.jsx("div",{className:"shrink-0",children:s.jsx(W,{onClick:()=>{a("loading"),o(null),n(l=>!l)},intent:t?"neutral":"brand",variant:t?"outline":"solid",size:"sm",children:t?"Hide code":"Link a device"})})]})})]})}function att(){const[e,t]=p.useState(null),[n,r]=p.useState(null),[a,i]=p.useState(""),[o,l]=p.useState(!1),[c,u]=p.useState(null),[d,h]=p.useState(null),[f,m]=p.useState(!1);p.useEffect(()=>{K.getMe().then(v=>{t(v),i(v.display_name??"")}).catch(v=>r(String((v==null?void 0:v.message)||v)))},[]);const x=(((e==null?void 0:e.display_name)||(e==null?void 0:e.email)||"??").split(/[\s._@-]+/).filter(Boolean).slice(0,2).map(v=>{var w;return(w=v[0])==null?void 0:w.toUpperCase()}).join("")||"??").slice(0,2),g=((e==null?void 0:e.display_name)??"")===a.trim();async function y(){if(!(!e||g)){l(!0),u(null);try{const v=await K.updateMe({display_name:a.trim()||null});t(v),i(v.display_name??""),u("Saved"),window.setTimeout(()=>u(null),2e3)}catch(v){u(`Couldn't save â ${(v==null?void 0:v.message)||v}`)}finally{l(!1)}}}async function b(){if(e!=null&&e.email){m(!0),h(null);try{await iC(e.email),h("Reset link sent â check your inbox.")}catch(v){h(`Couldn't send â ${(v==null?void 0:v.message)||v}`)}finally{m(!1)}}}return s.jsxs("div",{className:"space-y-8",children:[n&&s.jsx(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:n}),s.jsxs(V,{children:[s.jsx(mh,{label:"Profile picture",children:s.jsx(KG,{url:(e==null?void 0:e.avatar_url)??null,initials:x,shape:"circle",onPick:async v=>{const{avatar_url:w}=await K.uploadAvatar(v);t(_=>_&&{..._,avatar_url:w}),ai()},onRemove:async()=>{await K.removeAvatar(),t(v=>v&&{...v,avatar_url:null}),ai()}})}),s.jsx(zj,{}),s.jsx(mh,{label:"Email",children:s.jsx("div",{className:"text-sm text-text-secondary",children:(e==null?void 0:e.email)??"â"})}),s.jsx(zj,{}),s.jsx(mh,{label:"Full name",align:"start",children:s.jsxs("div",{className:"flex flex-col items-end gap-1 min-w-0",children:[s.jsx(Re,{type:"text",value:a,onChange:v=>i(v.target.value),placeholder:"Your name",maxLength:100,inputSize:"sm",className:"w-64 max-w-full"}),s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[c&&s.jsx("span",{className:c.startsWith("Saved")?"text-text-success":"text-text-error",children:c}),s.jsx(W,{onClick:y,disabled:o||g||!e,intent:"brand",size:"sm",children:o?"Savingâ¦":"Save"})]})]})})]}),s.jsxs("div",{children:[s.jsx("h2",{className:"text-base font-semibold text-text-primary mb-3",children:"Appearance"}),s.jsx(V,{children:s.jsx(mh,{label:"Theme",children:s.jsx(itt,{})})})]}),s.jsxs("div",{children:[s.jsx("h2",{className:"text-base font-semibold text-text-primary mb-3",children:"Chat"}),s.jsxs(V,{children:[s.jsx(mh,{label:"Response style",align:"start",children:s.jsx(ott,{me:e,onChange:t})}),s.jsx(zj,{}),s.jsx(mh,{label:"Custom instructions",align:"start",children:s.jsx(ltt,{me:e,onChange:t})})]})]}),s.jsxs("div",{children:[s.jsx("h2",{className:"text-base font-semibold text-text-primary mb-3",children:"Connected accounts"}),s.jsx(V,{children:s.jsxs("div",{className:"p-4 flex items-center gap-3",children:[s.jsx("div",{className:"w-9 h-9 rounded-md bg-surface-sunken text-text-secondary flex items-center justify-center",children:s.jsx(m6,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Password"}),s.jsx("div",{className:"text-xs text-text-secondary",children:"Password login is enabled â we'll email you a reset link to change it."})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[d&&s.jsx("span",{className:"text-xs "+(d.startsWith("
941Couldn't")?"text-text-error":"text-text-success"),children:d}),s.jsx("span",{className:"text-xs font-medium text-text-success bg-surface-successSubtle border border-outline-success px-2 py-0.5 rounded-full",children:"Enabled"}),s.jsx(W,{onClick:b,disabled:f||!(e!=null&&e.email),intent:"neutral",variant:"outline",size:"sm",children:f?"Sendingâ¦":"Send reset email"})]})]})})]}),s.jsx(stt,{}),s.jsxs("div",{children:[s.jsx("h2",{className:"text-base font-semibold text-text-primary mb-3",children:"Session"}),s.jsx(V,{children:s.jsxs("div",{className:"p-4 flex items-center gap-3",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-success-500 shrink-0"}),s.jsx("div",{className:"flex-1 min-w-0",children:s.jsx("div",{className:"text-sm text-text-primary",children:"Current session on this device"})}),s.jsxs(W,{onClick:()=>wf(),intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(W2,{className:"w-3.5 h-3.5"})," Sign out"]})]})})]})]})}function itt(){const e=u6();return s.jsxs(Pa,{value:e,onValueChange:t=>{rZ(t==="dark"?"dark":"light")},size:"sm",children:[s.jsx(Ln,{value:"light",children:"Light"}),s.jsx(Ln,{value:"dark",children:"Dark"})]})}function ott({me:e,onChange:t}){const[n,r]=p.useState(!1),[a,i]=p.useState(null),o=(e==null?void 0:e.chat_style)??"default";async function l(c){if(e&&!(c!=="default"&&c!=="minimal"&&c!=="detailed")&&c!==o){r(!0),i(null);try{const u=await K.updateMe({chat_style:c});t({...e,chat_style:u.chat_style??c}),ai(),i("Saved"),window.setTimeout(()=>i(null),2e3)}catch(u){i(`Couldn't save â ${(u==null?void 0:u.message)||u}`)}finally{r(!1)}}}return s.jsxs("div",{className:"flex flex-col items-end gap-1 min-w-0",children:[s.jsxs(Pa,{value:o,onValueChange:l,size:"sm",disabled:!e||n,children:[s.jsx(Ln,{value:"default",children:"Default"}),s.jsx(Ln,{value:"minimal",children:"Minimal"}),s.jsx(Ln,{value:"detailed",children:"Detailed"})]}),s.jsx("p",{className:"text-xs text-text-secondary text-right max-w-xs",children:"How Gadjet talks to you in every chat, across every store. Minimal executes and stops; detailed adds analysis without being asked."}),a&&s.jsx("span",{className:"text-xs "+(a.startsWith("Saved")?"text-text-success":"text-text-error"),children:a})]})}const W8=2e3;function ltt({me:e,onChange:t}){const[n,r]=p.useState(""),[a,i]=p.useState(!1),[o,l]=p.useState(null);p.useEffect(()=>{r((e==null?void 0:e.chat_instructions)??"")},[e==null?void 0:e.id,e==null?void 0:e.chat_instructions]);const c=((e==null?void 0:e.chat_instructions)??"")===n.trim();async function u(){if(!(!e||c)){i(!0),l(null);try{const d=await K.updateMe({chat_instructions:n.trim()||null});t({...e,chat_instructions:d.chat_instructions??null}),ai(),l("Saved"),window.setTimeout(()=>l(null),2e3)}catch(d){l(`Couldn't save â ${(d==null?void 0:d.message)||d}`)}finally{i(!1)}}}return s.jsxs("div",{className:"flex flex-col items-end gap-1 min-w-0 w-full max-w-md",children:[s.jsx(Ui,{value:n,onChange:d=>r(d.target.value),placeholder:"Standing rules for how Gadjet talks to you â e.g. always pair SKU with title, never recap.",rows:4,inputSize:"sm",maxLength:W8,disabled:!e||a}),s.jsxs("div",{className:"flex items-center gap-2 text-xs w-full justify-end",children:[s.jsxs("span",{className:"text-text-tertiary",children:[n.trim().length,"/",W8]}),o&&s.jsx("span",{className:o.startsWith("Saved")?"text-text-success":"text-text-error",children:o}),s.jsx(W,{onClick:u,disabled:a||c||!e,intent:"brand",size:"sm",children:a?"Savingâ¦":"Save"})]}),s.jsx("p",{className:"text-xs text-text-secondary text-right",children:"Follows you across every chat and every store. Does not change how Gadjet talks to anyone else on the same store."})]})}function mh({label:e,children:t,align:n="center"}){return s.jsxs("div",{className:"p-4 flex gap-4 "+(n==="start"?"items-start":"items-center"),children:[s.jsx("div",{className:"w-32 shrink-0 text-sm font-medium text-text-primary",children:e}),s.jsx("div",{className:"flex-1 min-w-0 flex justify-end",children:t})]})}function zj(){return s.jsx("div",{className:"border-t border-outline-faint"})}const ctt={missing_bank_fields:"Please fill in all the bank fields.",bad_account_number:"That account number doesn't look right.",recipient_creation_failed:"We couldn't verify those bank details with our payment provider. Double-check them and try again.",no_account:"Payout details are available on seller accounts."};function utt(){const[e,t]=p.useState(null),[n,r]=p.useState([]),[a,i]=p.useState(!0),[o,l]=
941p.useState(null),[c,u]=p.useState(!1),[d,h]=p.useState(""),[f,m]=p.useState(""),[x,g]=p.useState(""),[y,b]=p.useState(""),[v,w]=p.useState(!1),[_,k]=p.useState(null),[j,N]=p.useState(0);p.useEffect(()=>{let C=!0;return i(!0),l(null),Promise.all([Us.bankAccount(),Us.banks()]).then(([T,S])=>{C&&(t(T.bankAccount),r(Array.isArray(S==null?void 0:S.banks)?S.banks:[]),T.bankAccount||u(!0))}).catch(T=>C&&l(T.message)).finally(()=>C&&i(!1)),()=>{C=!1}},[j]);async function E(){var C;w(!0),k(null);try{const T=((C=n.find(S=>S.code===f))==null?void 0:C.name)??"";await Us.saveBankAccount({accountHolder:d.trim(),bankName:T,bankCode:f,accountNumber:x.trim(),accountType:y||void 0}),u(!1),g(""),N(S=>S+1)}catch(T){const S=T instanceof Error?T.message:String(T);k(ctt[S]??S)}finally{w(!1)}}if(a)return s.jsx("div",{className:"text-xs text-text-tertiary",children:"Loadingâ¦"});const A=d.trim()&&f&&/^\d{4,20}$/.test(x.trim());return s.jsxs("div",{className:"space-y-6",children:[o&&s.jsx(V,{padding:"md",variant:"sunken",children:s.jsxs("p",{className:"text-sm text-text-warning",children:["Couldn't load payout details (",o,")."]})}),s.jsxs(V,{padding:"lg",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(z2,{className:"h-4 w-4 text-text-secondary"}),s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Bank account for payouts"})]}),s.jsx("p",{className:"mt-1 text-sm text-text-secondary",children:"Where we send affiliate cash withdrawals. We never store your full account number â only the last 4 digits, plus a secure token from our payment provider."}),e&&!c?s.jsxs("div",{className:"mt-4 space-y-3",children:[s.jsxs("div",{className:"rounded-md border border-outline-subtle bg-surface-subtle p-3 text-sm",children:[s.jsx("div",{className:"font-medium text-text-primary",children:e.account_holder}),s.jsxs("div",{className:"text-text-secondary",children:[e.bank_name," ···· ",e.account_number_last4,e.account_type?` · ${e.account_type}`:""]}),s.jsx("div",{className:"mt-1",children:e.payout_ready?s.jsxs("span",{className:"inline-flex items-center gap-1 text-body-xs font-medium text-text-success",children:[s.jsx(fn,{className:"h-3.5 w-3.5"})," Ready for payouts"]}):s.jsx("span",{className:"text-body-xs text-text-warning",children:"Not yet verified"})})]}),s.jsx(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",onClick:()=>u(!0),children:"Replace bank account"})]}):s.jsxs("div",{className:"mt-4 space-y-3",children:[s.jsx(vy,{label:"Account holder",children:s.jsx("input",{type:"text",value:d,onChange:C=>h(C.target.value),placeholder:"As it appears on the account",className:"w-full rounded border border-outline-subtle bg-surface px-2 py-1.5 text-sm"})}),s.jsx(vy,{label:"Bank",children:s.jsxs("select",{value:f,onChange:C=>m(C.target.value),className:"w-full rounded border border-outline-subtle bg-surface px-2 py-1.5 text-sm",children:[s.jsx("option",{value:"",children:"Select a bankâ¦"}),n.map(C=>s.jsx("option",{value:C.code,children:C.name},C.code))]})}),s.jsx(vy,{label:"Account number",children:s.jsx("input",{type:"text",inputMode:"numeric",value:x,onChange:C=>g(C.target.value.replace(/[^\d]/g,"")),placeholder:"Digits only",className:"w-full rounded border border-outline-subtle bg-surface px-2 py-1.5 text-sm"})}),s.jsx(vy,{label:"Account type (optional)",children:s.jsxs("select",{value:y,onChange:C=>b(C.target.value),className:"w-full rounded border border-outline-subtle bg-surface px-2 py-1.5 text-sm",children:[s.jsx("option",{value:"",children:"â"}),s.jsx("option",{value:"savings",children:"Savings"}),s.jsx("option",{value:"current",children:"Current"}),s.jsx("option",{value:"cheque",children:"Cheque"})]})}),_&&s.jsx("p",{className:"text-body-xs text-text-error",children:_}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(W,{type:"button",intent:"brand",size:"sm",disabled:!A||v,onClick:E,children:[v?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):null,"Save bank account"]}),e&&s.jsx(W,{type:"button",intent:"neutral",variant:"ghost",size:"sm",disabled:v,onClick:()=>{u(!1),k(null)},children:"Cancel"})]})]})]}),s.jsxs("p",{className:"text-body-xs text-text-tertiary",children:["Manage your affiliate balance and request withdrawals on the"," ",s.jsx(st,{to:"/earn",className:"text-text-brand hover:underline",children:"Earn page"}),"."]})]})}function vy({label:e,children:t}){return s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-body-xs font-medium text-text-secondary",children:e}),t]})}function dtt(){const[e,t]=p.useState(null),[n,r]=p.useState(null),[a,i]=p.useState(!1),[o,l]=
941p.useState(null);p.useEffect(()=>{K.getMe().then(t).catch(d=>r(String((d==null?void 0:d.message)||d)))},[]);const c=!(e!=null&&e.email_opt_out);async function u(d){if(e){i(!0),l(null);try{const h=await K.updateMe({email_opt_out:!d});t({...e,email_opt_out:!!h.email_opt_out}),l(d?"Subscribed.":"Unsubscribed from non-essential email."),window.setTimeout(()=>l(null),2500)}catch(h){l(`Couldn't save â ${(h==null?void 0:h.message)||h}`)}finally{i(!1)}}}return s.jsxs("div",{className:"space-y-6",children:[n&&s.jsx(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:n}),s.jsx(V,{children:s.jsxs("div",{className:"p-4 flex items-center gap-3",children:[s.jsx("div",{className:"w-9 h-9 rounded-md bg-surface-sunken text-text-secondary flex items-center justify-center",children:s.jsx(p6,{className:"w-4 h-4"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Product & account email"}),s.jsx("div",{className:"text-xs text-text-secondary",children:"Tips, summaries, and non-essential updates. Billing and security email always send."})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[o&&s.jsx("span",{className:"text-xs "+(o.startsWith("Couldn't")?"text-text-error":"text-text-success"),children:o}),s.jsx(N3,{checked:c,disabled:a||!e,onCheckedChange:d=>u(d)})]})]})})]})}const K8=250,htt=1500;function ftt(e,t=htt){const n=Math.round(Number(e)*100),r=Math.round(Number(t)*100);if(!Number.isFinite(n)||!Number.isFinite(r))return 0;const a=n-r;return a<K8?0:Math.floor(a/K8)}function Tc(e){return new Intl.NumberFormat("en-ZA",{style:"currency",currency:"ZAR",minimumFractionDigits:2,maximumFractionDigits:2}).format(e)}function mtt(e){if(e.included_monthly==null)return"Included images: unlimited";const t=e.remaining_included??0;return t<=0?`Included this month: all ${e.included_monthly} used`:`Included this month: ${t} of ${e.included_monthly} left`}function ptt(){const[e,t]=p.useState(null),[n,r]=p.useState(null),[a,i]=p.useState({kind:"idle"}
941),[o,l]=p.useState(0),[c,u]=p.useState(!1),[d,h]=p.useState(!1),[f,m]=p.useState(null),[x,g]=p.useState(null),y=p.useRef(null),b=p.useRef(!1),v=p.useCallback(async()=>{const C=await K.billingImagePacks();return t(C),b.current||(b.current=!0,l(ftt(C.grant_balance_zar,C.reserve_zar))),C},[]);p.useEffect(()=>{let C=!0;return v().then(T=>{C&&(y.current=T.pack_remaining)}).catch(T=>{C&&r(String((T==null?void 0:T.message)||T))}),()=>{C=!1}},[v]);const w=p.useCallback(async()=>{try{const C=await v(),T=y.current;if(T!=null&&C.pack_remaining>T){y.current=C.pack_remaining;const S=C.packs.find(O=>O.id===(a.kind==="waiting"||a.kind==="opening"?a.packId:""));return i({kind:"done",label:S?`${S.images} images`:"Image pack"}),window.dispatchEvent(new CustomEvent("gadjet:chat-saved")),!0}}catch{}return!1},[a,v]);p.useEffect(()=>{if(a.kind!=="waiting"&&a.kind!=="opening")return;let C=!1;const T=()=>{C||w()};window.addEventListener("focus",T);const S=setInterval(()=>{C||w()},5e3),O=setTimeout(()=>{C=!0,clearInterval(S)},180*1e3);return()=>{C=!0,window.removeEventListener("focus",T),clearInterval(S),clearTimeout(O)}},[a,w]);async function _(C){if(!(a.kind==="opening"||a.kind==="waiting")){i({kind:"opening",packId:C.id});try{const T=window.location.pathname+window.location.search,{authorization_url:S}=await K.billingImagePackCheckout(C.id,T);window.open(S,"_blank","noopener,noreferrer"),i({kind:"waiting",packId:C.id})}catch(T){i({kind:"error",message:T instanceof Error?T.message:"Couldn't start checkout"})}}}async function k(){if(!e||o<1||d)return;const C=o*e.zar_per_image;if(!(e.grant_balance_zar-C<e.reserve_zar&&!c)){h(!0),m(null),g(null);try{const S=await K.billingConvertGrantToImages(o,c);g(`Moved ${Tc(S.cost_zar)} into ${S.images.toLocaleString("en-US")} images.`),u(!1),b.current=!1;const O=await v();y.current=O.pack_remaining,window.dispatchEvent(new CustomEvent("gadjet:chat-saved"))}catch(S){m(S instanceof Error?S.message:"Couldn't move credits")}finally{h(!1)}}}if(n)return s.jsx(V,{className:"p-6",children:s.jsx("p",{className:"text-xs text-text-error",children:n})});if(!e)return s.jsx(V,{className:"p-6",children:s.jsx("p",{className:"text-xs text-text-tertiary",children:"Loading image balanceâ¦"})});if(!e.image_studio_enabled)return null;const j=o>0?o*e.zar_per_image:0,N=e.grant_balance_zar-j,E=o>0&&N<e.reserve_zar,A=wr();return s.jsxs(V,{className:"p-6 space-y-5",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Image packs"}),s.jsx("p",{className:"mt-1 text-xs text-text-secondary",children:"Included images reset with your plan. Bought images, and images you move across from chat credits, stay until you use them. Making an image does not spend chat credits."})]}),s.jsxs("div",{className:"text-xs text-text-secondary space-y-1",children:[s.jsx("div",{children:mtt(e)}),s.jsxs("div",{children:["Bought images: ",e.pack_remaining.toLocaleString("en-US")]})]}),a.kind==="done"&&s.jsx("div",{className:"rounded-lg border border-outline-success bg-surface-successSubtle px-4 py-3 text-sm text-text-success",children:s.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[s.jsx(Xt,{className:"w-4 h-4"}),a.label," added."]})}),!A&&a.kind!=="done"&&s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2",children:e.packs.map(C=>{const T=(a.kind==="opening"||a.kind==="waiting")&&a.packId===C.id,S=(a.kind==="opening"||a.kind==="waiting")&&a.packId!==C.id;return s.jsxs("button",{type:"button",onClick:()=>_(C),disabled:T||S,className:B("flex flex-col items-center justify-center rounded-lg border px-3 py-3 text-center transition-colors","border-outline-subtle bg-surface hover:border-intent-neutral hover:bg-surface-inverse hover:text-text-inverse","disabled:opacity-50 disabled:cursor-not-allowed",C.recommended&&"border-intent-neutral"),children:[s.jsx("div",{className:"text-base font-semibold tabular-nums",children:T?s.jsx(_e,{className:"w-4 h-4 animate-spin"}):Tc(C.priceZar)}),s.jsxs("div",{className:"text-body-xs mt-0.5",children:[C.images.toLocaleString("en-US")," images"]}),s.jsx("div",{className:"text-body-xs text-text-secondary mt-0.5",children:C.hint})]},C.id)})}),a.kind==="waiting"&&s.jsxs("div",{className:"text-xs text-text-secondary flex items-center gap-1.5",children:[s.jsx(Qt,{className:"w-3 h-3"}),"Complete payment in the Paystack tab. Images land here within a few seconds â"," ",s.jsx("button",{type:"button",onClick:()=>w(),className:"underline underline-offset-2",children:"check now"}),"."]}),a.kind==="error"&&s.jsx("div",{className:"text-xs text-text-error bg-surface-errorSubtle border border-outline-error roun
941ded px-3 py-2",children:a.message}),s.jsxs("div",{className:"border-t border-outline-subtle pt-4 space-y-3",children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Move chat credits"}),s.jsxs("p",{className:"text-xs text-text-secondary",children:[Tc(e.zar_per_image)," of chat credits becomes one image, the same price as the 2,000-image pack. Chat credits left behind still expire at renewal. We suggest keeping ",Tc(e.reserve_zar)," for chat. You have ",Tc(e.grant_balance_zar)," now."]}),s.jsxs("label",{className:"block text-xs text-text-secondary",children:["Images to add",s.jsx("input",{type:"number",min:0,step:1,value:o||"",onChange:C=>{const T=Math.max(0,Math.floor(Number(C.target.value)||0));l(T),u(!1)},className:"mt-1 w-full rounded-lg border border-outline-subtle bg-surface px-3 py-2 text-sm text-text-primary"})]}),o>0&&s.jsxs("p",{className:"text-xs text-text-secondary",children:[Tc(j)," of chat credits â ",o.toLocaleString("en-US")," images. Chat credits left: ",Tc(Math.max(0,N)),"."]}),E&&s.jsxs("label",{className:"flex items-start gap-2 text-xs text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:c,onChange:C=>u(C.target.checked),className:"mt-0.5"}),"Leave less than ",Tc(e.reserve_zar)," of chat credits."]}),s.jsx("button",{type:"button",onClick:k,disabled:d||o<1||N<0||E&&!c,className:"rounded-lg border border-outline-subtle px-3 py-2 text-sm font-medium hover:border-intent-neutral disabled:opacity-50",children:d?"Movingâ¦":"Move credits"}),x&&s.jsx("p",{className:"text-xs text-text-success",children:x}),f&&s.jsx("p",{className:"text-xs text-text-error",children:f})]})]})}function iY(e){switch(e){case"active":return"Active";case"past_due":return"Payment failed";case"pending":return"Not started";case"cancelled":return"Cancelled";case"non_renewing":return"Ends this period";case"not_applicable":return"Billed separately";default:return e||"Unknown"}}function xtt(e){return e==="agency"||e==="internal_gadjet"||e==="demo"}const gtt=fi,Wj=["Africa/Johannesburg","UTC","Europe/London","Europe/Berlin","America/New_York","America/Los_Angeles","Asia/Dubai","Asia/Singapore","Australia/Sydney"],ytt=["ZAR","USD","EUR","GBP"],btt="Africa/Johannesburg",vtt="ZAR",wtt=[{key:"primary",label:"Primary"},{key:"accent",label:"Accent"},{key:"bg",label:"Background"},{key:"surface",label:"Surface"},{key:"text",label:"Text"},{key:"muted",label:"Muted"},{key:"cta",label:"Button"},{key:"ctaText",label:"Button text"}],_tt={logo:"Generated from your logo",product:"Generated from your products",house:"Default theme",manual:"Customised"};function ktt({canEdit:e}){var C;const[t,n]=p.useState(!0),[r,a]=p.useState(null),[i,o]=p.useState(null),[l,c]=p.useState(null),[u,d]=p.useState(null),[h,f]=p.useState(null),[m,x]=p.useState(!1),[g,y]=p.useState(null),[b,v]=p.useState(null);function w(T){o(T.palette),c(T.type),d(T.theme),f(T.source),x(!1)}p.useEffect(()=>{let T=!0;return K.getBrandKit().then(S=>{T&&(a(S.options),w(S.brand_kit))}).catch(S=>
941T&&v(String((S==null?void 0:S.message)||S))).finally(()=>T&&n(!1)),()=>{T=!1}},[]);function _(T,S){o(O=>O&&{...O,[T]:S.toUpperCase()}),x(!0)}function k(T){const S=r==null?void 0:r.themes.find(O=>O.id===T);S&&(o(S.palette),d(T),x(!0))}function j(T){const S=r==null?void 0:r.pairings.find(O=>O.id===T);S&&(c({heading:S.heading,body:S.body}),x(!0))}async function N(){if(!(!i||!l)){y("save"),v(null);try{const T=await K.saveBrandKit({palette:i,type:l,theme:u});a(T.options),w(T.brand_kit)}catch(T){v(String((T==null?void 0:T.message)||T))}finally{y(null)}}}async function E(){y("derive"),v(null);try{const T=await K.deriveBrandKit();a(T.options),w(T.brand_kit)}catch(T){v(String((T==null?void 0:T.message)||T))}finally{y(null)}}const A=((C=r==null?void 0:r.pairings.find(T=>T.heading===(l==null?void 0:l.heading)&&T.body===(l==null?void 0:l.body)))==null?void 0:C.id)??"";return s.jsxs(V,{className:"p-6 space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Brand kit"}),s.jsxs("p",{className:"text-xs text-text-secondary mt-0.5",children:["Colours and fonts used to generate your ads and listing images.",h&&s.jsxs("span",{className:"ml-1 text-text-tertiary",children:["· ",_tt[h]??h]})]})]}),e&&s.jsxs(W,{variant:"outline",intent:"neutral",size:"sm",disabled:g!==null||t,onClick:E,children:[g==="derive"?s.jsx(_e,{className:"w-3.5 h-3.5 animate-spin"}):s.jsx(pa,{className:"w-3.5 h-3.5"}),"Regenerate"]})]}),t?s.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-secondary py-2",children:[s.jsx(_e,{className:"w-4 h-4 animate-spin"})," Loading brand kitâ¦"]}):!i||!l?s.jsx("div",{className:"text-xs text-intent-error",children:b||"Couldn't load the brand kit."}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:wtt.map(T=>s.jsxs("div",{className:"space-y-1",children:[s.jsx("label",{className:"text-xs text-text-secondary",children:T.label}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"color",value:i[T.key],disabled:!e,onChange:S=>_(T.key,S.target.value),className:"w-8 h-8 rounded border border-outline-subtle bg-transparent p-0.5 disabled:opacity-60","aria-label":T.label}),s.jsx(Re,{type:"text",value:i[T.key],disabled:!e,onChange:S=>_(T.key,S.target.value),className:"font-mono text-xs",maxLength:7})]})]},T.key))}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-1",children:[s.jsx("label",{className:"text-xs text-text-secondary",children:"Start from a theme"}),s.jsxs(Tt,{value:u??"",disabled:!e,onChange:T=>k(T.target.value),children:[s.jsx("option",{value:"",children:"Custom"}),r==null?void 0:r.themes.map(T=>s.jsx("option",{value:T.id,children:T.label},T.id))]})]}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("label",{className:"text-xs text-text-secondary",children:"Fonts"}),s.jsxs(Tt,{value:A,disabled:!e,onChange:T=>j(T.target.value),children:[!A&&s.jsx("option",{value:"",children:"Custom"}),r==null?void 0:r.pairings.map(T=>s.jsx("option",{value:T.id,children:T.label},T.id))]})]})]}),b&&s.jsx("div",{className:"text-xs text-intent-error",children:b}),e?s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(W,{intent:"brand",size:"sm",disabled:!m||g!==null,onClick:N,children:[g==="save"?s.jsx(_e,{className:"w-3.5 h-3.5 animate-spin"}):s.jsx(ko,{className:"w-3.5 h-3.5"}),"Save brand kit"]}),s.jsxs("span",{className:"text-xs text-text-tertiary flex items-center gap-1",children:[s.jsx(Ht,{className:"w-3 h-3"})," Used by the Ads & Image studios"]})]}):s.jsx("div",{className:"text-xs text-text-secondary",children:"Only the workspace owner can change the brand kit."})]})]})}const jtt={original:"Original (as-is)",cutout:"White background",angle:"Angle shot",lifestyle:"Lifestyle shot"},Ntt=["original","cutout","angle","lifestyle"];function Stt({canEdit:e}){const[t,n]=p.useState(!0),[r,a]=p.useState([]),[i,o]=p.useState(!1),[l,c]=p.useState(!1),[u,d]=p.useState(null);p.useEffect(()=>{let v=!0;return K.getListingImagePreset().then(w=>
941v&&a(w.listing_image_preset.shots)).catch(w=>v&&d(String((w==null?void 0:w.message)||w))).finally(()=>v&&n(!1)),()=>{v=!1}},[]);function h(v){a(v),o(!0)}function f(v,w){h(r.map((_,k)=>k===v?{mode:w,prompt:w==="angle"||w==="lifestyle"?_.prompt??"":void 0}:_))}function m(v,w){h(r.map((_,k)=>k===v?{..._,prompt:w}:_))}function x(v,w){const _=v+w;if(_<0||_>=r.length)return;const k=[...r];[k[v],k[_]]=[k[_],k[v]],h(k)}function g(v){h(r.filter((w,_)=>_!==v))}function y(){h([...r,{mode:"angle",prompt:""}])}async function b(){c(!0),d(null);try{const v=r.map(_=>_.mode==="angle"||_.mode==="lifestyle"?{mode:_.mode,prompt:(_.prompt||"").trim()}:{mode:_.mode}),w=await K.saveListingImagePreset(v);a(w.listing_image_preset.shots),o(!1)}catch(v){d(String((v==null?void 0:v.message)||v))}finally{c(!1)}}return s.jsxs(V,{className:"p-6 space-y-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Listing image preset"}),s.jsx("p",{className:"text-xs text-text-secondary mt-0.5",children:'The set of shots "Generate from preset" produces in the Create Listings image step â one tap makes them all from your main photo.'})]}),t?s.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-secondary py-2",children:[s.jsx(_e,{className:"w-4 h-4 animate-spin"})," Loading presetâ¦"]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"space-y-2",children:r.map((v,w)=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:"w-5 text-xs text-text-tertiary",children:[w+1,"."]}),s.jsx(Tt,{value:v.mode,disabled:!e,onChange:_=>f(w,_.target.value),className:"w-44 text-xs",children:Ntt.map(_=>s.jsx("option",{value:_,children:jtt[_]},_))}),v.mode==="angle"||v.mode==="lifestyle"?s.jsx(Re,{type:"text",value:v.prompt??"",disabled:!e,onChange:_=>m(w,_.target.value),placeholder:v.mode==="angle"?"e.g. 3/4 front-right":"e.g. on a kitchen counter",className:"flex-1 text-xs",maxLength:200}):s.jsx("span",{className:"flex-1 text-xs text-text-tertiary",children:"No description needed"}),e&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>x(w,-1),disabled:w===0,title:"Move up",className:"text-text-tertiary hover:text-text-primary disabled:opacity-30",children:"â"}),s.jsx("button",{type:"button",onClick:()=>x(w,1),disabled:w===r.length-1,title:"Move down",className:"text-text-tertiary hover:text-text-primary disabled:opacity-30",children:"â"}),s.jsx("button",{type:"button",onClick:()=>g(w),title:"Remove",className:"text-text-tertiary hover:text-intent-error",children:s.jsx(us,{className:"w-3.5 h-3.5"})})]})]},w))}),e&&s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs(W,{variant:"outline",intent:"neutral",size:"sm",disabled:l||r.length>=8,onClick:y,children:[s.jsx(In,{className:"w-3.5 h-3.5"})," Add shot"]}),s.jsxs(W,{variant:"solid",intent:"brand",size:"sm",disabled:l||!i||r.length===0,onClick:b,children:[l?s.jsx(_e,{className:"w-3.5 h-3.5 animate-spin"}):s.jsx(ko,{className:"w-3.5 h-3.5"}),"Save preset"]})]}),u&&s.jsx("div",{className:"text-xs text-intent-error",children:u}),!e&&s.jsx("div",{className:"text-xs text-text-secondary",children:"Only the workspace owner can edit the preset."})]})]})}function Ctt({account:e,onUpdate:t}){var y;const[n,r]=p.useState(e.business_name),[a,i]=p.useState(!1),[o,l]=p.useState(null),[c,u]=p.useState(null),d=e.my_role==="owner",{openConnectStore:h}=d0(),f=((y=gtt[e.account_type])==null?void 0:y.maxSellers)??null,m=f!==null&&e.seller_count>=f,x=n.trim()!==e.business_name&&n.trim().length>0;async function g(){i(!0),u(null);try{await K.updateAccount({business_name:n.trim()}),t({...e,business_name:n.trim()}),l(Date.now())}catch(b){u(String((b==null?void 0:b.message)||b))}finally{i(!1)}}return s.jsxs("div",{className:"space-y-6",children:[s.jsxs(V,{className:"p-6 space-y-3",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Workspace logo"}),s.jsx(KG,{url:e.logo_url,initials:(e.business_name||"W").slice(0,1).toUpperCase(),shape:"square",disabled:!d,onPick:async b=>{const{logo_url:v}=await K.uploadLogo(b);t({...e,logo_url:v})},onRemove:async()=>{await K.removeLogo(),t({...e,logo_url:null})}}),!d&&s.jsx("div",{className:"text-xs text-text-secondary",children:"Only the workspace owner can change the logo."})]}),s.jsx(ktt,{canEdit:d}),s.jsx(Stt,{canEdit:d}),s.jsxs(V,{className:"p-6 space-y-4",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Worksp
941ace name"}),s.jsx("p",{className:"text-xs text-text-secondary",children:"The name your teammates see in the sidebar and on invites."}),s.jsx(Re,{type:"text",value:n,onChange:b=>r(b.target.value),disabled:!d||a,maxLength:200}),!d&&s.jsx("div",{className:"text-xs text-text-secondary",children:"Only the workspace owner can rename."}),c&&s.jsxs("div",{className:"text-xs text-text-error flex items-center gap-1",children:[s.jsx(yt,{className:"w-3 h-3"})," ",c]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs(W,{onClick:g,disabled:!d||!x||a,intent:"brand",size:"sm",children:[s.jsx(ko,{className:"w-3 h-3"})," ",a?"Savingâ¦":"Save"]}),o&&Date.now()-o<4e3&&s.jsxs("span",{className:"text-xs text-text-success flex items-center gap-1",children:[s.jsx(fn,{className:"w-3 h-3"})," saved"]})]})]}),s.jsx(Ett,{account:e,onUpdate:t,canEdit:d}),s.jsxs(V,{className:"p-6 space-y-2",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Workspace details"}),s.jsx(ph,{label:"Plan",value:qtt(e.account_type)}),s.jsx(ph,{label:"Status",value:e.status}),s.jsx(ph,{label:"Subscription",value:iY(e.subscription_status)}),s.jsx(ph,{label:"Members",value:String(e.member_count)}),s.jsx(ph,{label:"Stores",value:`${e.seller_count} of ${f===null?"Unlimited":f}`}),d&&s.jsx("div",{className:"pt-1",children:s.jsxs(W,{variant:"outline",intent:"neutral",size:"sm",onClick:()=>h(),children:[s.jsx(In,{className:"w-3.5 h-3.5"}),m?"Upgrade to add more stores":"Connect another store"]})}),s.jsx(ph,{label:"Created",value:e.created_at?cn(e.created_at):"â"})]})]})}function Ett({account:e,onUpdate:t,canEdit:n}){const r=e.home_timezone||btt,a=e.base_currency||vtt,[i,o]=p.useState(r),[l,c]=p.useState(a),[u,d]=p.useState(!1),[h,f]=p.useState(null),[m,x]=p.useState(null),g=Wj.includes(r)?Wj:[r,...Wj],y=i!==r||l!==a;async function b(){d(!0),x(null);try{const v=await K.updateAccount({home_timezone:i,base_currency:l});t({...e,home_timezone:v.home_timezone,base_currency:v.base_currency}),f(Date.now())}catch(v){x(String((v==null?void 0:v.message)||v))}finally{d(!1)}}return s.jsxs(V,{className:"p-6 space-y-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Region"}),s.jsx("p",{className:"mt-1 text-xs text-text-secondary",children:"The timezone and currency used for date windows and totals in your reports and digests."})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("label",{className:"block space-y-1",children:[s.jsx("span",{className:"text-xs font-medium text-text-secondary",children:"Timezone"}),s.jsx(Tt,{value:i,onChange:v=>o(v.target.value),disabled:!n||u,inputSize:"sm",children:g.map(v=>s.jsx("option",{value:v,children:v},v))})]}),s.jsxs("label",{className:"block space-y-1",children:[s.jsx("span",{className:"text-xs font-medium text-text-secondary",children:"Base currency"}),s.jsx(Tt,{value:l,onChange:v=>c(v.target.value),disabled:!n||u,inputSize:"sm",children:ytt.map(v=>s.jsx("option",{value:v,children:v},v))})]})]}),!n&&s.jsx("div",{className:"text-xs text-text-secondary",children:"Only the workspace owner can change these."}),m&&s.jsxs("div",{className:"text-xs text-text-error flex items-center gap-1",children:[s.jsx(yt,{className:"w-3 h-3"})," ",m]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs(W,{onClick:b,disabled:!n||!y||u,intent:"brand",size:"sm",children:[s.jsx(ko,{className:"w-3 h-3"})," ",u?"Savingâ¦":"Save"]}),h&&Date.now()-h<4e3&&s.jsxs("span",{className:"text-xs text-text-success flex items-center gap-1",children:[s.jsx(fn,{className:"w-3 h-3"})," saved"]})]})]})}function Att({myUserId:e,myRole:t}){const[n,r]=p.useState(null),[a,i]=p.useState(null),[o,l]=p.useState(!1),[c,u]=p.useState(null),d=t==="owner"||t==="admin",h=t==="owner";async function f(){try{r(await K.listMembers())}catch(g){i(String((g==null?void 0:g.message)||g))}}p.useEffect(()=>{f()},[]),p.useEffect(()=>{h&&K.sellers().then(u).catch(()=>u([]))},[h]);const m=((c==null?void 0:c.length)??0)>1;function x(g){r(y=>y&&y.map(b=>b.user_id===g.user_id?g:b))}return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Team members"}),d&&s.jsxs(W,{onClick:()=>l(!0),intent:"brand",size:"sm",children:[s.jsx(q2,{className:"w-3 h-3"})," Invite teammate"]})]}),o&&d&&s.jsx($tt,{onDone:()=>{l(!1),f()}}),a&&s.jsx(V,{className:"p-3 text-xs text-text-error bg-surface-errorSubtle border-outline-error",children:a}),n===null&&!a&&s.jsx("div",{className:"text-xs text-text-tertiary",children:"Loading membersâ¦"}),d&&s.jsx(Mtt,{onInvited:f}),h&&s.jsx(Ott,{onError:i}),n&&n.length>0&&s.jsx(V,{className:"divide-y divide-outline-faint",children:n.map(g=>s.jsx(Itt,{member:g,isMe:g.user_id===e,canManage:h,sellers:m?c:null,onChanged:x,onRemoved:f,onError:i},g.user_id))})]})}const Ttt=[{key:"member",label:"Members"},{key:"viewer",label:"Viewers"}];function Ott({onError:e}){const[t,n]=p.useState(!1),[r,a]=p.useState(null),[i,o]=p.useState({}),[l,c]=p.useState("{}"),[u,d]=p.useState("member"),[h,f]=p.useState(!1);p.useEffect(()=>{!t||r!==null||K.getAccountNavRoleAccess().then(w=>
941{a(w.surfaces),o(w.overrides||{}),c(JSON.stringify(w.overrides||{}))}).catch(w=>e(String((w==null?void 0:w.message)||w)))},[t,r,e]);const m=JSON.stringify(i)!==l;function x(w){var _;return((_=i[u])==null?void 0:_[w])===!1}function g(w){o(_=>{const k={..._[u]||{}};k[w]===!1?delete k[w]:k[w]=!1;const j={..._};return Object.keys(k).length?j[u]=k:delete j[u],j})}async function y(){f(!0);try{const w=await K.saveAccountNavRoleAccess(i);o(w.overrides||{}),c(JSON.stringify(w.overrides||{}))}catch(w){e(String((w==null?void 0:w.message)||w))}finally{f(!1)}}const b=(r??[]).filter(w=>w.roleVisible),v=[];for(const w of["top","seller"]){const _=b.filter(k=>k.group===w);_.length&&v.push({group:w,items:_})}return s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("button",{type:"button",onClick:()=>n(w=>!w),className:"w-full flex items-center justify-between px-4 py-3 text-left",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Default access by role"}),s.jsx("div",{className:"text-body-xs text-text-secondary",children:"Hide surfaces for all members or all viewers. Override per person below."})]}),t?s.jsx(t0,{className:"w-4 h-4 text-text-tertiary shrink-0"}):s.jsx(Pn,{className:"w-4 h-4 text-text-tertiary shrink-0"})]}),t&&s.jsx("div",{className:"px-4 pb-3 border-t border-outline-faint pt-3 space-y-3",children:r===null?s.jsxs("div",{className:"text-xs text-text-tertiary flex items-center gap-1.5",children:[s.jsx(_e,{className:"w-3 h-3 animate-spin"})," Loadingâ¦"]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex gap-1",children:Ttt.map(w=>s.jsx("button",{type:"button",onClick:()=>d(w.key),className:B("px-3 py-1 rounded-md text-xs font-medium border",u===w.key?"bg-surface-brandSubtle text-text-brand border-outline-brand":"bg-surface border-outline-subtle text-text-secondary"),children:w.label},w.key))}),v.map(({group:w,items:_})=>s.jsxs("div",{children:[s.jsx("div",{className:"text-body-xs font-medium text-text-tertiary mb-1",children:oY[w]??w}),s.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:_.map(k=>{const j=x(k.key);return s.jsxs("button",{type:"button",onClick:()=>g(k.key),className:B("flex items-center justify-between gap-2 px-2 py-1.5 rounded-md border text-xs text-left",j?"bg-surface-subtle border-outline-subtle text-text-tertiary":"bg-surface border-outline-subtle text-text-primary"),children:[s.jsx("span",{className:"truncate",children:k.label}),s.jsx("span",{className:B("shrink-0 text-body-xs font-medium",j?"text-text-tertiary":"text-text-success"),children:j?"Hidden":"Visible"})]},k.key)})})]},w)),s.jsx("div",{className:"flex items-center gap-2 pt-1",children:s.jsxs(W,{onClick:y,disabled:!m||h,intent:"brand",size:"sm",children:[h?s.jsx(_e,{className:"w-3 h-3 animate-spin"}):s.jsx(ko,{className:"w-3 h-3"}),"Save defaults"]})})]})})]})}function Itt({member:e,isMe:t,canManage:n,sellers:r,onChanged:a,onRemoved:i,onError:o}){const[l,c]=p.useState(!1),[u,d]=p.useState(!1),[h,f]=p.useState(!1),m=n&&!t&&e.role!=="owner",x=m&&!!r&&r.length>1,g=n&&!t&&(e.role==="member"||e.role==="viewer");async function y(_){c(!0);try{a(await K.updateMember(e.user_id,{role:_}))}catch(k){o(String((k==null?void 0:k.message)||k))}finally{c(!1)}}async function b(_){c(!0);try{a(await K.updateMember(e.user_id,{allowed_seller_slugs:_})),d(!1)}catch(k){o(String((k==null?void 0:k.message)||k))}finally{c(!1)}}async function v(){if(window.confirm(`Remove ${e.email} from the workspace?`)){c(!0);try{await K.removeMember(e.user_id),i()}catch(_){o(String((_==null?void 0:_.message)||_))}finally{c(!1)}}}const w=e.allowed_seller_slugs==null?"All stores":`${e.allowed_seller_slugs.length} store${e.allowed_seller_slugs.length===1?"":"s"}`;return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-3 px-4 py-3",children:[s.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-sunken text-text-secondary flex items-center justify-center text-xs font-medium",children:(e.display_name||e.email).slice(0,1).toUpperCase()}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-sm text-text-primary truncate",children:[e.display_name||e.email,t&&s.jsx("span",{className:"ml-2 text-body-xs text-text-tertiary",children:"(you)"})]}),s.jsx("div",{className:"text-xs text-text-secondary truncate",children:e.email}),s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3",children:[x&&s.jsxs("button",{onClick:()=>d(_=>!_),className:"mt-0.5 text-body-xs text-text-tertiary hover:text-text-secondary",children:["Stores: ",w," · edit"]}),g&&s.jsx("button",{onClick:()=>f(_=>!_),className:"mt-0.5 text-body-xs text-text-tertiary hover:text-text-secondary",children:"Surface access · edit"})]})]}),m?s.jsxs(Tt,{value:e.role,onChange:_=>y(_.target.value),disabled:l,inputSize:"sm",className:"w-auto",children:[s.jsx("option",{value:"admin",children:"Admin"}),s.jsx("option",{value:"member",children:"Member"}),s.jsx("option",{value:"viewer",children:"Viewer"})]}):s.jsx(Rtt,{role:e.role}),m&&s.jsx("button",{onClick:v,disabled:l,className:"text-xs text-text-tertiary hover:text-text-error disabled:opacity-50",title:"Remove member",children:s.jsx(us,{className:"w-3.5 h-3.5"})})]}),x&&u&&s.jsx(Dtt,{member:e,sellers:r,busy:l,onSave:b,onCancel:()=>d(!1)}),g&&h&&s.jsx(Ptt,{member:e,onError:o,onClose:()=>f(!1)})]})}const oY={top:"Surfaces",seller:"Per-store sections"};function Ptt({member:e,onError:t,onClose:n}){const[r,a]=p.useState(null),[i,o]=p.useState({}),[l,c]=p.useState({}),[u,d]=p.useState(new Set),[h,f]=p.useState(!1);function m(w,_,k){const j={};for(const N of w){if(!N.roleVisible)continue;const E=!_.has(N.key);j[N.key]=N.key in k?k[N.key]:E}return j}p.useEffect(()=>{let w=!0;return K.getMemberNavAccess(e.user_id).then(_=>{if(!w)return;const k=new Set(_.roleDefaultHidden||[]),j=m(_.surfaces,k,_.overrides||{});a(_.surfaces),d(k),o(j),c({...j})}).catch(_=>t(String((_==null?void 0:_.message)||_))),()=>{w=!1}},[e.user_id,t]);const x=r!==null&&JSON.stringify(i)!==JSON.stringify(l);function g(w){o(_=>({..._,[w]:!_[w]}))}async function y(){f(!0);try{const w={};for(const j of r??[]){if(!j.roleVisible)continue;const N=!u.has(j.key);i[j.key]!==N&&(w[j.key]=i[j.key])}const _=await K.saveMemberNavAccess(e.user_id,w),k=m(r??[],u,_.overrides||{});o(k),c({...k}),n()}catch(w){t(String((w==null?void 0:w.message)||w))}finally{f(!1)}}const b=(r??[]).filter(w=>w.roleVisible),v=[];for(const w of["top","seller"]){const _=b.filter(k=>k.group===w);_.length&&v.push({group:w,items:_})}return s.jsx("div",{className:"px-4 pb-3 pt-2 bg-surface-subtle border-t border-outline-faint space-y-3",children:r===null?s.jsxs("div",{className:"text-xs text-text-tertiary flex items-center gap-1.5",children:[s.jsx(_e,{className:"w-3 h-3 animate-spin"})," Loading surfacesâ¦"]}):s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"text-body-xs text-text-secondary",children:["Surfaces ",e.display_name||e.email," can see. Toggle one off to hide it; surfaces your role defaults hide can be toggled back on for this person. Hidden surfaces are blocked if visited directly."]}),v.map(({group:w,items:_})=>s.jsxs("div",{children:[s.jsx("div",{className:"text-body-xs font-medium text-text-tertiary mb-1",children:oY[w]??w}),s.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:_.map(k=>{const j=i[k.key],N=!u.has(k.key),E=j!==N;return s.jsxs("button",{type:"button",onClick:()=>g(k.key),className:B("flex items-center justify-between gap-2 px-2 py-1.5 rounded-md border text-xs text-left",j?"bg-surface border-outline-subtle text-text-primary":"bg-surface-subtle border-outline-subtle text-text-tertiary"),children:[s.jsxs("span",{className:"truncate",children:[k.label,E&&s.jsx("span",{className:"text-text-brand",children:" · exception"})]}),s.jsx("span",{className:B("shrink-0 text-body-xs font-medium",j?"text-text-success":"text-text-tertiary"),children:j?"Visible":"Hidden"})]},k.key)})})]},w)),s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsxs(W,{onClick:y,disabled:!x||h,intent:"brand",size:"sm",children:[h?s.jsx(_e,{className:"w-3 h-3 animate-spin"}):s.jsx(ko,{className:"w-3 h-3"}),"Save"]}),s.jsx(W,{onClick:n,disabled:h,intent:"neutral",variant:"outline",size:"sm",children:"Cancel"})]})]})})}function Rtt({role:e}){return s.jsx("span",{className:B("text-body-xs font-medium px-2 py-0.5 rounded border",e==="owner"&&"bg-surface-brandSubtle text-text-brand border-outline-brand",e==="admin"&&"bg-surface-infoSubtle text-text-info border-outline-info",e==="member"&&"bg-surface-subtle text-text-body border-outline-subtle",e==="viewer"&&"bg-surface-subtle text-text-secondary border-outline-subtle"),children:e})}function Dtt({member:e,sellers:t,busy:n,onSave:r,onCancel:a}){const[i,o]=p.useState(e.allowed_seller_slugs==null?"all":"specific"),[l,c]=p.useState(new Set(e.allowed_seller_slugs??t.map(h=>h.slug)));function u(h){c(f=>{const m=new Set(f);return m.has(h)?m.delete(h):m.add(h),m})}const d=i==="specific"&&l.size===0;return s.jsxs("div",{className:"px-4 pb-3 pt-2 bg-surface-subtle border-t border-outline-faint space-y-2",children:[s.jsxs("div",{className:"text-xs text-text-secondary",children:["Which stores can ",e.display_name||e.email," access?"]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm text-text-body",children:[s.jsx("input",{type:"radio",checked:i==="all",onChange:()=>o("all"),disabled:n}),"All stores"]}),s.jsxs("label",{className:"flex items-center gap-2 text-sm text-text-body",children:[s.jsx("input",{type:"radio",checked:i==="specific",onChange:()=>o("specific"),disabled:n}),"Specific stores"]}),i==="specific"&&s.jsx("div",{className:"pl-6 space-y-1 max-h-48 overflow-y-auto",children:t.map(h=>s.jsxs("label",{className:"flex items-center gap-2 text-sm text-text-body",children:[s.jsx("input",{type:"checkbox",checked:l.has(h.slug),onChange:()=>u(h.slug),disabled:n}),h.display_name]},h.slug))}),s.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[s.jsx(W,{onClick:()=>r(i==="all"?null:Array.from(l)),disabled:n||d,intent:"brand",size:"sm",children:n?"Savingâ¦":"Save access"}),s.jsx(W,{onClick:a,variant:"link",intent:"neutral",size:"sm",children:"Cancel"}),d&&s.jsx("span",{className:"text-body-xs text-text-tertiary",children:"Pick at least one store, or choose All."})]})]})}
941function Mtt({onInvited:e}){const[t,n]=p.useState(null),[r,a]=p.useState(null),[i,o]=p.useState({}),[l,c]=p.useState(null);p.useEffect(()=>{K.listStoreUsers().then(n).catch(()=>n([]))},[]);async function u(h){a(h.id),c(null);try{await K.inviteMember({email:h.email,role:"member",invitee_name:h.name}),o(f=>({...f,[h.id]:!0})),e()}catch(f){c(`Couldn't invite ${h.name}: ${String((f==null?void 0:f.message)||f)}`)}finally{a(null)}}async function d(h){a(h.id);try{await K.dismissStoreUser(h.id),n(f=>f&&f.filter(m=>m.id!==h.id))}catch(f){c(String((f==null?void 0:f.message)||f))}finally{a(null)}}return!t||t.length===0?null:s.jsxs(V,{className:"p-4 space-y-3",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"People on your Takealot store"}),s.jsxs("p",{className:"text-xs text-text-tertiary mt-0.5",children:[t.length===1?"This person has":"These people have"," access to your Takealot account but no Gadjet login yet. Nothing is sent until you invite them."]})]}),l&&s.jsxs("div",{className:"text-xs text-text-error flex items-center gap-1",children:[s.jsx(yt,{className:"w-3 h-3"})," ",l]}),s.jsx("div",{className:"divide-y divide-outline-faint",children:t.map(h=>s.jsxs("div",{className:"flex items-center gap-3 py-2 first:pt-0 last:pb-0",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"text-xs font-medium text-text-primary truncate",children:h.name}),h.is_account_owner&&s.jsx("span",{className:"text-body-xs px-1.5 py-0.5 rounded bg-surface-brandSubtle text-text-brand",children:"Account owner"}),!h.is_account_owner&&h.is_main_contact&&s.jsx("span",{className:"text-body-xs px-1.5 py-0.5 rounded bg-surface-subtle text-text-secondary",children:"Main contact"})]}),s.jsxs("div",{className:"text-body-xs text-text-tertiary truncate",children:[h.email,h.job_title?` · ${h.job_title}`:"",h.stores.length>1?` · ${h.stores.length} stores`:""]})]}),i[h.id]?s.jsxs("span",{className:"text-xs text-text-success flex items-center gap-1 shrink-0",children:[s.jsx(fn,{className:"w-3 h-3"})," Invited"]}):s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[s.jsx(W,{onClick:()=>u(h),disabled:r!==null,intent:"brand",size:"sm",children:r===h.id?"Sendingâ¦":"Invite"}),s.jsx(W,{onClick:()=>d(h),disabled:r!==null,variant:"link",intent:"neutral",size:"sm",children:"Hide"})]})]},h.id))})]})}function $tt({onDone:e}){const[t,n]=p.useState(""),[r,a]=p.useState("member"),[i,o]=p.useState(!1),[l,c]=p.useState(null),[u,d]=p.useState(null),[h,f]=p.useState(!1);async function m(){o(!0),d(null);try{const x=await K.inviteMember({email:t.trim(),role:r});c({link:x.invite_link,sent:x.invite_email_sent,reason:x.invite_email_skip_reason})}catch(x){d(String((x==null?void 0:x.message)||x))}finally{o(!1)}}return s.jsxs(V,{className:"p-4 space-y-3 bg-surface-subtle",children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary",children:"Invite a teammate"}),!l&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex gap-2",children:[s.jsx(Re,{type:"email",placeholder:"[email protected]",value:t,onChange:x=>n(x.target.value),disabled:i,inputSize:"sm",className:"flex-1"}),s.jsxs(Tt,{value:r,onChange:x=>a(x.target.value),disabled:i,inputSize:"sm",className:"w-auto",children:[s.jsx("option",{value:"admin",children:"Admin"}),s.jsx("option",{value:"member",children:"Member"}),s.jsx("option",{value:"viewer",children:"Viewer"})]})]}),u&&s.jsxs("div",{className:"text-xs text-text-error flex items-center gap-1",children:[s.jsx(yt,{className:"w-3 h-3"})," ",u]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(W,{onClick:m,disabled:!t.includes("@")||i,intent:"brand",size:"sm",children:i?"Sendingâ¦":"Send invite"}),s.jsx(W,{onClick:e,variant:"link",intent:"neutral",size:"sm",children:"Cancel"})]})]}),l&&s.jsxs("div",{className:"space-y-2 text-xs text-text-body",children:[s.jsx("div",{children:l.sent?s.jsx("span",{className:"text-text-success",children:"â Email sent."}):s.jsxs("span",{className:"text-text-warning",children:["Email not sent (",l.reason,"). Share the link manually:"]})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("code",{className:"flex-1 text-body-xs font-mono bg-surface border border-outline-subtle rounded px-2 py-1.5 break-all",children:l.link}),s.jsxs("button",{onClick:()=>{navigator.clipboard.writeText(l.link),f(!0),setTimeout(()=>f(!1),2e3)},className:"text-xs text-text-secondary hover:text-text-body flex items-center gap-1 px-2 py-1 rounded border border-outline-subtle hover:bg-surface-sunken",children:[h?s.jsx(fn,{className:"w-3 h-3"}):s.jsx(bi,{className:"w-3 h-3"}),h?"Copied":"Copy"]})]}),s.jsx(W,{onClick:e,variant:"link",intent:"brand",size:"sm",className:"mt-2",children:"Done"})]})]})}function Ltt({account:e}){const[t,n]=p.useState(null),[r,a]=p.useState(null),[i,o]=p.useState(null),l=e.billing_program==="complimentary_under_100k",c=xtt(e.account_type)||e.subscription_status==="not_applicable"||(t==null?void 0:t.kind)==="included";return p.useEffect(()=>{K.billingUsageSummary().then(n).catch(u=>a(String((u==null?void 0:u.message)||u))),K.billingUsageBreakdown().then(o).catch(()=>{})},[]),s.jsxs("div",{className:"space-y-6",children:[s.jsxs(V,{className:"p-6 space-y-5",children:[s.jsxs("div",{className:"flex items-baseline justify-between",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:c?"Chat":l?"Free plan":"Monthly credits"}),s.jsx("span",{className:B("text-body-xs font-medium px-2 py-1 rounded border",c||l||e.subscription_status==="active"?"bg-surface-successSubtle text-text-success border-outline-success":e.subscription_status==="past_due"?"bg-surface-warningSubtle text-text-warning border-outline-warning":"bg-surface-subtle text-text-secondary border-outline-subtle"),children:c?"Included in retainer":l?"Free plan":iY(e.subscription_status)})]}),!t&&!r&&s.jsx("div",{className:"text-xs text-text-tertiary",children:"Loadingâ¦"}),r&&s.jsx("div",{className:"text-xs text-text-error",children:r}),c&&s.jsx("div",{className:"text-xs text-text-secondary",children:"Chat, reports and tool runs are included in your managed retainer. There is no monthly credit meter and nothing to top up."}),!c&&l&&s.jsx("div",{className:"text-xs text-text-secondary",children:"Your workspace is free while last monthâs Takealot GMV stays under R100,000. Chat is pay-as-you-go â buy credits when you need them. Dashboards, sync, Image Studio and Market Explorer use the Starter allowances."}),!c&&!l&&(t==null?void 0:t.kind)==="no_cycle"&&s.jsx("div",{className:"text-xs text-text-secondary",children:"Your subscription hasnât started yet. Connect your Takealot store â if last-30-day sales are under R100k you land on the Free plan. Chat stays pay-as-you-go until you buy credits."}),!c&&(t==null?void 0:t.kind)==="cycle"&&s.jsx(Vtt,{usage:t})]}),s.jsx(Wtt,{account:e,usage:t,included:c}),!c&&s.jsx(Btt,{account:e,complimentary:l}),!c&&(i==null?void 0:i.kind)==="cycle"&&s.jsx(Ktt,{breakdown:i}),!c&&s.jsxs(V,{className:"p-6 space-y-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Buy more credits"}),s.jsx("p",{className:"mt-1 text-xs text-text-secondary",children:"Pick a top-up pack â you'll be redirected to Paystack to pay, then back here. Credits land within seconds."})]}),s.jsx(vq,{context:"billing",returnTo:"/settings/workspace/billing"})]}),!c&&s.jsx(ptt,{}),s.jsx(ztt,{})]})}const Ftt=["starter","business","empire"],H8=Ftt.map((e,t)=>({id:e,label:fi[e].displayName,price:fi[e].priceZar,credits:fi[e].monthlyGrantZar,sellers:fi[e].maxSellers,users:fi[e].maxUsers,rank:t+1}));function Btt({account:e,complimentary:t=!1}
941){const[n,r]=p.useState(null),[a,i]=p.useState(!1),[o,l]=p.useState(null),c=H8.find(h=>h.id===e.account_type);if(!c||!t&&e.subscription_status!=="active")return null;async function u(h){i(!0),l(null);try{const f=await K.initiateSubscription(h),m=f.manage_url||f.authorization_url;if(!m)throw new Error("Couldn't start checkout.");window.open(m,"_blank","noopener,noreferrer")}catch(f){l(String((f==null?void 0:f.message)||f))}finally{i(!1)}}async function d(h){i(!0),l(null);try{const f=await K.billingChangePlan(h);if(f.authorization_url){window.location.assign(f.authorization_url);return}window.location.reload()}catch(f){l(String((f==null?void 0:f.message)||f)),i(!1),r(null)}}return t?s.jsxs(V,{className:"p-6 space-y-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Move to a paid plan"}),s.jsx("p",{className:"mt-1 text-xs text-text-secondary",children:"Free is one Takealot store and no monthly chat grant. Pick Starter, Business or Empire â leftover top-up credits stay."})]}),o&&s.jsxs("div",{className:"text-xs text-text-error flex items-start gap-1",children:[s.jsx(yt,{className:"w-3 h-3 mt-0.5 shrink-0"})," ",o]}),s.jsx(nB,{highlight:"business",busy:a,onPick:h=>void u(h)})]}):s.jsxs(V,{className:"p-6 space-y-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Change plan"}),s.jsx("p",{className:"mt-1 text-xs text-text-secondary",children:"Need more credits or more stores? Move up a tier â the new plan starts immediately on your card on file."})]}),o&&s.jsxs("div",{className:"text-xs text-text-error flex items-start gap-1",children:[s.jsx(yt,{className:"w-3 h-3 mt-0.5 shrink-0"})," ",o]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:H8.map(h=>{const f=h.id===e.account_type,m=h.rank<c.rank,x=n===h.id;return s.jsxs("div",{className:B("rounded border p-4 space-y-2 transition",f?"border-success-300 bg-surface-successSubtle":"border-outline-subtle bg-surface"),children:[s.jsxs("div",{className:"flex items-baseline justify-between",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary",children:h.label}),f&&s.jsx("span",{className:"text-[10px] uppercase tracking-wide font-medium text-text-success bg-surface-successSubtle px-1.5 py-0.5 rounded",children:"Current"})]}),s.jsxs("div",{className:"text-xs text-text-body",children:[s.jsxs("span",{className:"text-base font-semibold text-text-primary",children:["R",h.price.toLocaleString()]}),s.jsx("span",{className:"text-text-secondary",children:" / month"})]}),s.jsxs("ul",{className:"text-[11px] text-text-secondary space-y-0.5",children:[s.jsxs("li",{children:["R",h.credits.toLocaleString()," included credits/mo"]}),s.jsxs("li",{children:["Up to ",h.sellers," store",h.sellers>1?"s":""]}),s.jsxs("li",{children:["Up to ",h.users," users"]}),h.sellers>1&&s.jsx("li",{children:"Cross-store reports & global overview"})]}),s.jsx("div",{className:"pt-1",children:f?s.jsx("div",{className:"text-[11px] text-text-secondary italic",children:"You're here"}):m?s.jsxs("div",{className:"text-[11px] text-text-secondary",children:["Want to step down?"," ",s.jsx("a",{href:"mailto:[email protected]",className:"text-text-body underline",children:"message us"})]}):x?s.jsxs("div",{className:"flex gap-2",children:[s.jsxs(W,{onClick:()=>d(h.id),disabled:a,intent:"brand",size:"sm",children:[a?s.jsx(_e,{className:"w-3 h-3 animate-spin"}):s.jsx(fn,{className:"w-3 h-3"}),"Confirm"]}),s.jsx(W,{onClick:()=>r(null),disabled:a,size:"sm",children:"Cancel"})]}):s.jsx(W,{onClick:()=>r(h.id),intent:"brand",size:"sm",children:"Upgrade"})})]},h.id)})}),s.jsx("div",{className:"text-[11px] text-text-secondary leading-relaxed",children:"Note: upgrading creates a new Paystack subscription on the new plan and disables the old one. There may be a brief overlap on your Paystack statement during the switchover."})]})}function Utt(e,t){return[{key:"number",label:"Number",render:n=>s.jsx("span",{className:"font-mono text-text-primary",children:n.invoice_number})},{key:"date",label:"Date",getValue:n=>n.issued_at,render:n=>s.jsx("span",{className:"text-text-body",children:cn(n.issued_at)})},{key:"reason",label:"Reason",render:n=>s.jsx("span",{className:"text-text-body",children:n.reason==="monthly_subscription"?"Subscription":n.reason==="courier_collection"?"Courier collections":"Top-up"})},{key:"total",label:"Total",align:"right",getValue:n=>Number(n.total_zar),render:n=>s.jsxs("span",{className:"text-text-primary",children:["R",Number(n.total_zar).toFixed(2)]})},{key:"pdf",label:"PDF",align:"right",render:n=>n.pdf_url?s.jsxs("button",{type:"button",onClick:()=>e(n.id),disabled:t===n.id,className:"text-text-brand hover:underline disabled:opacity-50 inline-flex items-center gap-1",children:[t===n.id?s.jsx(_e,{className:"w-3 h-3 animate-spin"}):s.jsx(Qt,{className:"w-3 h-3"}),"Download"]}):s.jsx("span",{className:"text-text-tertiary",children:"Renderingâ¦"})}]}function ztt(){const[e,t]=p.useState(null),[n,r]=p.useState(null),[a,i]=p.useState(null);p.useEffect(()=>{K.billingInvoices().then(l=>{if(l.kind==="ok"){t(l.invoices);return}t([]),l.kind==="not_applicable"?r("Invoices are only listed on a seller workspace."):l.kind==="no_account"&&r("No workspace is linked to this login yet.")}).catch(l=>r(String((l==null?void 0:l.message)||l)))},[]);async function o(l){i(l);try{const{pdf_url:c}=await K.billingInvoicePdfUrl(l);window.open(c,"_blank","noopener,noreferrer")}catch(c){r(String((c==null?void 0:c.message)||c))}finally{i(null)}}return s.jsxs(V,{className:"p-6 space-y-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Invoices"}),s.jsx("p",{className:"mt-1 text-xs text-text-secondary",children:"Tax invoices for every Paystack charge â monthly subscription plus any top-ups. Issued automatically the moment payment clears."})]}),n&&s.jsx("div",{className:"text-xs text-text-error",children:n}),!n&&s.jsx(dt,{rows:e,columns:Utt(o,a),getRowKey:l=>l.id,paginate:!1,persist:!1,tableClassName:"text-xs",empty:{title:"No invoices yet.",hint:"You'll see one here within minutes of your first payment."}})]})}function Wtt({account:e,usage:t,included:n=!1}){const[r,a]=p.useState(!1),[i,o]=p.useState(null),l=e.subscription_status,c=!n&&(l==="active"||l==="past_due"),u=(t==null?void 0:t.kind)==="cycle"?t.cycle.renews_at:null;async function d(){o(null),a(!0);try{const{link:f}=await K.billingManageSubscription();window.open(f,"_blank","noopener,noreferrer")}catch(f){o(String((f==null?void 0:f.message)||f))}finally{a(!1)}}async function h(){o(null),a(!0);try{const f=await K.initiateSubscription(),m=f.manage_url||f.authorization_url;if(!m)throw new Error("Couldn't start checkout.");window.open(m,"_blank","noopener,noreferrer")}catch(f){o(String((f==null?void 0:f.message)||f))}finally{a(!1)}}return s.jsxs(V,{className:"p-6 space-y-4",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Subscription"}),s.jsx("p",{className:"mt-1 text-xs text-text-secondary",children:n?"Billed as a managed retainer â chat cost is included, not metered.":e.billing_program==="complimentary_under_100k"?"Free plan â no monthly fee. Chat is pay-as-you-go.":`R${Number(e.monthly_grant_zar??499)}/month â includes R${Number(e.monthly_grant_zar??499)} of monthly chat credits.`})]}),u&&c&&s.jsxs("div",{className:"text-xs text-text-secondary",children:["Next renewal:"," ",s.jsx("span",{className:"font-medium text-text-primary",children:cn(u)})]}),l==="past_due"&&!n&&s.jsx("div",{className:"text-xs text-text-warning bg-surface-warningSubtle border border-outline-warning rounded-md px-3 py-2",children:"Last payment failed. Update your card on Paystack to resume â topping up does not restart your subscription."}),c&&s.jsxs("div",{children:[s.jsxs(W,{type:"button",onClick:d,disabled:r,intent:"neutral",variant:"solid",size:"sm",children:[r?s.jsx(_e,{className:"w-3 h-3 animate-spin"}):s.jsx(Qt,{className:"w-3 h-3"}),"Manage on Paystack"]}),s.jsx("p",{className:"mt-2 text-body-xs text-text-tertiary",children:"Update card, view invoices, or cancel. Opens in a new tab."})]}),!c&&!n&&s.jsxs("div",{className:"space-y-3",children:[s.jsx("div",{className:"text-xs text-text-secondary",children:l==="pending"&&e.billing_program==="complimentary_under_100k"?"You're on the Free plan. Buy credits to use chat, or pick a paid plan for a monthly grant and more stores.":l==="pending"?"Your subscription hasn't started yet. Connect your store â under R100k last month lands you on Free.":l==="cancelled"?e.cancelled_at?`Cancelled â ended ${cn(e.cancelled_at)}. Data is kept; automations have stopped.`:"Your plan has ended. Data is kept; automations have stopped.":l==="non_renewing"?e.current_period_end?`Active until ${cn(e.current_period_end)}, then it will not renew.`:"This subscription will not renew.":"No active subscription yet. Start one to begin getting monthly credits."}),(l==="pending"||l==="cancelled")&&e.billing_program!=="complimentary_under_100k"&&s.jsxs("div",{children:[s.jsxs(W,{type:"button",onClick:h,disabled:r,intent:"brand",variant:"solid",size:"sm",children:[r?s.jsx(_e,{className:"w-3 h-3 animate-spin"}):s.jsx(Qt,{className:"w-3 h-3"}),l==="cancelled"?"Restart plan":"Start subscription"]}),s.jsx("p",{className:"mt-2 text-body-xs text-text-tertiary",children:"Opens Paystack checkout in a new tab."})]})]}),i&&s.jsx("div",{className:"text-xs text-text-error bg-surface-errorSubtle border border-outline-error roun
941ded-md px-3 py-2",children:i})]})}function Ktt({breakdown:e}){return e.by_surface.length>0||e.top_skills.length>0||e.top_chats.length>0||e.daily.length>0?s.jsxs(V,{className:"p-6 space-y-6",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Where this month's credits went"}),e.by_surface.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"text-xs text-text-secondary uppercase tracking-wide",children:"By type"}),e.by_surface.map(n=>s.jsx(Kj,{label:n.surface==="skill"?"Skills":"Chat",pct:n.pct},n.surface))]}),e.top_skills.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"text-xs text-text-secondary uppercase tracking-wide",children:"Top skills"}),e.top_skills.map(n=>s.jsx(Kj,{label:n.skill_name,pct:n.pct},n.skill_name))]}),e.top_chats.length>0&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"text-xs text-text-secondary uppercase tracking-wide",children:"Top chats"}),e.top_chats.map(n=>s.jsx(Kj,{label:n.title,sublabel:n.scope||void 0,pct:n.pct},n.chat_id))]}),e.daily.length>1&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("div",{className:"text-xs text-text-secondary uppercase tracking-wide",children:"Daily spend"}),s.jsx(Htt,{data:e.daily})]})]}):null}function Kj({label:e,sublabel:t,pct:n}){return s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-baseline justify-between text-sm",children:[s.jsxs("div",{className:"min-w-0 truncate",children:[s.jsx("span",{className:"text-text-primary",children:e}),t&&s.jsx("span",{className:"ml-2 text-xs text-text-tertiary",children:t})]}),s.jsxs("span",{className:"text-xs text-text-secondary font-medium tabular-nums",children:[n,"%"]})]}),s.jsx("div",{className:"h-1.5 w-full rounded-full bg-surface-sunken overflow-hidden",children:s.jsx("div",{className:"h-full rounded-full bg-brand-500",style:{width:`${Math.min(100,n)}%`}})})]})}function Htt({data:e}){const t=Math.max(...e.map(n=>n.pct),1);return s.jsx("div",{className:"flex items-end gap-0.5 h-16",children:e.map(n=>s.jsx("div",{title:`${n.date}: ${n.pct}%`,className:"flex-1 bg-surface-brandSubtle hover:bg-brand-500 rounded-sm transition-colors",style:{height:`${Math.max(4,n.pct/t*100)}%`}},n.date))})}function Vtt({usage:e}){const t=e.grant.remaining_pct,n=e.grant.used_pct,r=e.topup.balance_pct_of_grant,a=e.pacing.label,i=t>25?"bg-success-500":t>10?"bg-warning-500":"bg-error-500",o=a==="burning fast"?"text-text-warning":a==="tracking light"?"text-text-success":"text-text-secondary";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex items-baseline justify-between",children:[s.jsxs("div",{className:"text-4xl font-semibold text-text-primary",children:[t,"%"]}),s.jsx("div",{className:"text-xs text-text-secondary",children:"remaining"})]}),s.jsxs("div",{children:[s.jsx("div",{className:"h-2 w-full rounded-full bg-surface-sunken overflow-hidden",children:s.jsx("div",{className:B("h-full rounded-full transition-all",i),style:{width:`${Math.min(100,n)}%`}})}),s.jsxs("div",{className:"mt-2 text-xs text-text-secondary flex items-center justify-between",children:[s.jsxs("span",{children:["Renews in ",e.cycle.days_remaining," ",e.cycle.days_remaining===1?"day":"days"]}),s.jsx("span",{className:o,children:a})]})]}),r>0&&s.jsxs("div",{className:"mt-2 pt-3 border-t border-outline-faint flex items-baseline justify-between text-sm",children:[s.jsxs("div",{children:[s.jsxs("span",{className:"text-text-primary font-medium",children:["+",r,"%"]}),s.jsx("span",{className:"ml-2 text-xs text-text-secondary",children:"extra runway"})]}),s.jsx("span",{className:"text-body-xs text-text-tertiary",children:"rolls over"})]})]})}function ph({label:e,value:t}){return s.jsxs("div",{className:"flex items-center justify-between text-sm py-1 border-b border-outline-faint last:border-0",children:[s.jsx("span",{className:"text-text-secondary",children:e}),s.jsx("span",{className:"text-text-primary font-medium",children:t})]})}function qtt(e){return e==="starter"?"Starter":e==="business"?"Business":e==="empire"?"Empire":e==="agency"?"Agency":e==="internal_gadjet"?"Gadjet internal":e==="demo"?"Demo":e}const Gtt=new Intl.NumberFormat("en-ZA",{style:"currency",currency:"ZAR",maximumFractionDigits:2});function Uu(e){return Gtt.format(e)}function Ytt({open:e,onOpenChange:t,account:n,onAdjusted:r}){const[a,i]=p.useState("topup"),[o,l]=p.useState(""),[c,u]=p.useState(""),[d,h]=p.useState("form"),[f,m]=p.useState(!1),[x,g]=p.useState(null);if(p.useEffect(()=>{e||(i("topup"),l(""),u(""),h("form"),m(!1),g(null))},[e]),!n)return null;const y=Number(o),b=o.trim()!==""&&Number.isFinite(y)&&y!==0,v=c.trim().length>0&&c.trim().length<=500,w=b&&v,_=a==="topup"?n.topup_balance_zar:n.grant_balance_zar,k=_+(y||0),j=b&&k<0;async function N(){if(n){m(!0),g(null);try{const C=await oe(`/api/admin/accounts/${n.id}/credits/adjust`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({amount_zar:y,bucket:a,note:c.trim()})});if(!C.ok){const T=await C.json().catch(()=>({}));throw new Error((T==null?void 0:T.message)||(T==null?void 0:T.error)||`HTTP ${C.status}`)}r(),t(!1)}catch(C){const T=C;g((T==null?void 0:T.message)||"Failed to adjust credits."),h("form")}finally{m(!1)}}}const E=y>0?"Add":"Deduct",A=Math.abs(y||0);return s.jsx(js,{open:e,onOpenChange:t,children:s.jsxs(Ns,{size:"md",children:[s.jsxs(La,{children:[s.jsx(ma,{children:"Adjust credits"}),s.jsxs(hc,{children:["Account: ",s.jsx("span",{className:"font-medium",children:n.name})]})]}),d==="form"?s.jsxs(s.Fragment,{children:[s.jsx(Oa,{children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium uppercase tracking-wide text-text-secondary",children:"Bucket"}),s.jsxs("div",{className:"mt-1 flex gap-2",children:[s.jsxs("button",{type:"button",onClick:()=>
941i("topup"),className:`flex-1 rounded-md border px-3 py-2 text-sm transition-colors ${a==="topup"?"border-outline-brand bg-surface-brandSubtle text-text-brand":"border-outline-subtle bg-surface text-text-body hover:bg-surface-subtle"}`,children:[s.jsx("div",{className:"font-medium",children:"Topup"}),s.jsxs("div",{className:"mt-0.5 text-xs text-text-secondary",children:[Uu(n.topup_balance_zar)," â rolls over"]})]}),s.jsxs("button",{type:"button",onClick:()=>i("grant"),className:`flex-1 rounded-md border px-3 py-2 text-sm transition-colors ${a==="grant"?"border-outline-brand bg-surface-brandSubtle text-text-brand":"border-outline-subtle bg-surface text-text-body hover:bg-surface-subtle"}`,children:[s.jsx("div",{className:"font-medium",children:"Grant"}),s.jsxs("div",{className:"mt-0.5 text-xs text-text-secondary",children:[Uu(n.grant_balance_zar)," â resets monthly"]})]})]})]}),s.jsxs("div",{children:[s.jsx("label",{htmlFor:"adjust-amount",className:"text-xs font-medium uppercase tracking-wide text-text-secondary",children:"Amount (ZAR) â negative to claw back"}),s.jsx("input",{id:"adjust-amount",type:"number",step:"0.01",value:o,onChange:C=>l(C.target.value),placeholder:"e.g. 500 or -100",className:"mt-1 w-full rounded-md border border-outline-subtle bg-surface px-3 py-2 text-sm outline-none focus:border-outline-brand focus-visible:shadow-focus",autoFocus:!0}),b?s.jsxs("div",{className:`mt-1 text-xs ${j?"text-text-error":"text-text-secondary"}`,children:[a==="topup"?"Topup":"Grant"," balance:"," ",Uu(_)," â"," ",Uu(k),j?" (rejected â would go below zero)":""]}):null]}),s.jsxs("div",{children:[s.jsx("label",{htmlFor:"adjust-note",className:"text-xs font-medium uppercase tracking-wide text-text-secondary",children:"Reason (required, shown on ledger)"}),s.jsx("textarea",{id:"adjust-note",value:c,onChange:C=>u(C.target.value),rows:3,maxLength:500,placeholder:"e.g. goodwill credit for outage on 2026-05-22",className:"mt-1 w-full resize-none rounded-md border border-outline-subtle bg-surface px-3 py-2 text-sm outline-none focus:border-outline-brand focus-visible:shadow-focus"}),s.jsxs("div",{className:"mt-0.5 text-right text-xs text-text-tertiary",children:[c.trim().length," / 500"]})]}),x?s.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-outline-error bg-surface-errorSubtle px-3 py-2 text-sm text-text-error",children:[s.jsx(yt,{className:"mt-0.5 h-4 w-4 shrink-0"}),s.jsx("span",{children:x})]}):null]})}),s.jsxs(da,{children:[s.jsx(W,{type:"button",intent:"neutral",variant:"outline",onClick:()=>t(!1),disabled:f,children:"Cancel"}),s.jsx(W,{type:"button",intent:"brand",variant:"solid",disabled:!w||j||f,onClick:()=>h("confirm"),children:"Review"})]})]}):s.jsxs(s.Fragment,{children:[s.jsx(Oa,{children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("p",{className:"text-sm text-text-body",children:["Confirm: ",s.jsx("strong",{children:E})," ",Uu(A)," of"," ",s.jsx("strong",{children:a})," credit"," ",y>0?"to":"from"," ",s.jsx("strong",{children:n.name}),"."]}),s.jsxs("div",{className:"rounded-md border border-outline-subtle bg-surface-subtle px-3 py-2 text-xs text-text-secondary",children:[s.jsxs("div",{children:["Reason: ",s.jsx("span",{className:"text-text-body",children:c.trim()})]}),s.jsxs("div",{className:"mt-1",children:[a==="topup"?"Topup":"Grant"," balance:"," ",Uu(_)," â"," ",s.jsx("strong",{className:"text-text-primary",children:Uu(k)})]})]}),s.jsx("p",{className:"text-xs text-text-tertiary",children:"This writes a credit_ledger row with reason=manual_adjust and records you as the actor. No Paystack charge, no invoice."}),x?s.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-outline-error bg-surface-errorSubtle px-3 py-2 text-sm text-text-error",children:[s.jsx(yt,{className:"mt-0.5 h-4 w-4 shrink-0"}),s.jsx("span",{children:x})]}):null]})}),s.jsxs(da,{children:[s.jsx(W,{type:"button",intent:"neutral",variant:"outline",onClick:()=>h("form"),disabled:f,children:"Back"}),s.jsxs(W,{type:"button",intent:y<0?"destructive":"brand",variant:"solid",onClick:N,disabled:f,children:[f?s.jsx(_e,{className:"h-3.5 w-3.5 animate-spin"}):null,"Confirm ",E.toLowerCase()]})]})]})]})})}const Ztt=new Intl.NumberFormat("en-ZA",{style:"currency",currency:"ZAR",maximumFractionDigits:2});function Oc(e){return e==null||!Number.isFinite(e)?"â":Ztt.format(e)}
941function Xtt(e){try{return new Date(e).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return e}}function Hj({children:e}){return s.jsx("div",{className:"px-4 py-2 border-b border-outline-faint text-xs font-medium uppercase tracking-wider text-text-secondary",children:e})}function lY({userId:e,open:t,onOpenChange:n}){const r=Lt(),a=r.kind==="ready"&&r.me.role==="super_admin",[i,o]=p.useState(null),[l,c]=p.useState(!1),[u,d]=p.useState(null),[h,f]=p.useState(null),[m,x]=p.useState(0),g=p.useCallback(()=>x(y=>y+1),[]);return p.useEffect(()=>{if(!t||!e)return;let y=!1;return c(!0),d(null),o(null),oe(`/api/admin/users/${e}/ai-usage`).then(async b=>{if(!b.ok){const v=await b.json().catch(()=>({}));throw new Error((v==null?void 0:v.message)||(v==null?void 0:v.error)||`HTTP ${b.status}`)}return b.json()}).then(b=>{y||o(b)}).catch(b=>{y||d((b==null?void 0:b.message)||"Failed to load AI usage.")}).finally(()=>{y||c(!1)}),()=>{y=!0}},[t,e,m]),s.jsxs(Cr,{open:t,onOpenChange:n,children:[s.jsxs(mr,{side:"right",size:"xl",children:[s.jsxs(Er,{children:[s.jsx(xr,{children:(i==null?void 0:i.user.display_name)||(i==null?void 0:i.user.email)||"AI usage"}),i!=null&&i.user.email?s.jsxs(Mr,{className:"mt-0.5 font-mono",children:[i.user.email," · ",i.user.role]}):s.jsx(Mr,{className:"sr-only",children:"Per-user AI usage breakdown â tokens, cost, and recent activity."})]}),s.jsx(pr,{className:"p-4 space-y-4",children:l?s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"}),"Loading usageâ¦"]}):u?s.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-outline-error bg-surface-errorSubtle px-3 py-2 text-sm text-text-error",children:[s.jsx(yt,{className:"mt-0.5 h-4 w-4 shrink-0"}),s.jsx("span",{children:u})]}):i?s.jsxs("div",{className:"space-y-4",children:[s.jsxs(dr,{children:[s.jsx(Ye,{label:"MTD spend",value:Oc(i.mtd.billable_zar),hint:`${i.mtd.calls.toLocaleString()} calls`}),s.jsx(Ye,{label:"MTD USD cost",value:i.mtd.cost_usd!=null?`$${i.mtd.cost_usd.toFixed(2)}`:"â",hint:"Anthropic raw"}),s.jsx(Ye,{label:"30d spend",value:Oc(i.last30.billable_zar),hint:`${i.last30.calls.toLocaleString()} calls`}),s.jsx(Ye,{label:"30d ops debug",value:Oc(i.impersonatedSpend30d.billable_zar),hint:`${i.impersonatedSpend30d.calls.toLocaleString()} Run-as calls`})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsx(Hj,{children:"Accounts & balances"}),s.jsx(dt,{rows:i.accounts,columns:[{key:"account",label:"Account",render:y=>s.jsx("span",{className:"text-text-primary",children:y.account_name})},{key:"plan",label:"Plan",render:y=>s.jsx("span",{className:"text-text-secondary",children:y.account_type})},{key:"subStatus",label:"Sub status",render:y=>s.jsx("span",{className:"text-text-secondary",children:y.subscription_status})},{key:"grant",label:"Grant",align:"right",render:y=>s.jsx("span",{className:"font-mono",children:Oc(y.grant_balance_zar)})},{key:"topup",label:"Topup",align:"right",render:y=>s.jsx("span",{className:"font-mono",children:Oc(y.topup_balance_zar)})},...a?[{key:"action",label:"Action",align:"right",stopRowClick:!0,render:y=>s.jsxs(W,{type:"button",intent:"brand",variant:"outline",size:"sm",onClick:()=>f(y),children:[s.jsx(In,{className:"h-3 w-3"}),"Adjust"]})}]:[]],getRowKey:y=>y.id,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No account memberships â internal user (no billing)."}})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsx(Hj,{children:"Top skills (last 30 days)"}),s.jsx(dt,{rows:i.topSkills,columns:[{key:"skill",label:"Skill",render:y=>s.jsx("span",{className:"font-mono text-xs text-text-primary",children:y.skill_name})},{key:"calls",label:"Calls",align:"right",render:y=>y.calls.toLocaleString()},{key:"total",label:"Total",align:"right",render:y=>s.jsx("span",{className:"font-mono",children:Oc(y.billable_zar)})},{key:"perCall",label:"Per call",align:"right",render:y=>{const b=y.calls>0?y.billable_zar/y.calls:0;return s.jsx("span",{className:"font-mono text-text-secondary",children:Oc(b)})}}],getRowKey:y=>y.skill_name,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No skill invocations in this window."}})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsx(Hj,{children:"Recent ledger (last 30 rows)"}),s.jsx(dt,{rows:i.recentLedger,columns:[{key:"when",label:"When",render:y=>s.jsx("span",{className:"text-text-secondary",children:Xtt(y.created_at)})},{key:"account",label:"Account",render:y=>s.jsx("span",{className:"text-text-secondary",children:y.account_name||"â"})},{key:"reason",label:"Reason",render:y=>s.jsx("span",{className:"text-text-secondary",children:y.reason})},{key:"bucket",label:"Bucket",render:y=>s.jsx("span",{className:"text-text-secondary",children:y.bucket})},{key:"delta",label:"Î ZAR",align:"right",render:y=>s.jsxs("span",{className:`font-mono ${y.delta_zar<0?"text-text-error":"text-text-success"}`,children:[y.delta_zar>0?"+":"",Oc(y.delta_zar)]})}],getRowKey:y=>`${y.created_at}-${y.account_id}-${y.reason}-${y.bucket}-${y.delta_zar}`,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No ledger activity yet."}})]})]}):null})]}),s.jsx(Ytt,{open:!!h,onOpenChange:y=>{y||f(null)},account:h?{id:h.id,name:h.account_name,grant_balance_zar:h.grant_balance_zar,topup_balance_zar:h.topup_balance_zar}:null,onAdjusted:g})]})}const Jtt=1800*1e3;function V8(e){if(!e)return!1;const t=new Date(e).getTime();return Number.isNaN(t)?!1:Date.now()-t<Jtt}function Qtt(e){if(!e)return"â";const t=new Date(e).getTime();if(Number.isNaN(t))return e;const n=Date.now()-t;if(n<6e4)return"just now";const r=Math.floor(n/6e4);if(r<60)return`${r}m ago`;const a=Math.floor(r/60);if(a<24)return`${a}h ago`;const i=Math.floor(a/24);return i<30?`${i}d ago`:new Date(e).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}const ent=new Intl.NumberFormat("en-ZA",{style:"currency",currency:"ZAR",maximumFractionDigits:0});function tnt(e){return!e||e<.5?"â":ent.format(e)}function q8(e){if(!e)return"â";try{return new Date(e).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}catch{return e}}function G8(e){return e==="starter"?"Starter":e==="business"?"Business":e==="empire"?"Empire":e==="agency"?"Agency":e==="internal_gadjet"?"Gadjet internal":e==="demo"?"Demo":e}function Y8(e){return e==="super_admin"?"Super admin":e==="am"?"AM":e==="content_creator"?"Content":e==="seller_user"?"Seller":e}function Vj(e){switch(e){case"super_admin":return"bg-surface-brandSubtle text-text-brand border-outline-brand";case"am":return"bg-surface-infoSubtle text-text-info border-outline-info";case"content_creator":return"bg-surface-warningSubtle text-text-warning border-outline-warning";case"seller_user":return"bg-surface-successSubtle text-text-success border-outline-success";default:return"bg-surface-subtle text-text-body border-outline-subtle"}}function nnt({embedded:e=!1}={}){var S;
941const t=Lt(),n=Rt(),r=mC(),[a,i]=p.useState([]),[o,l]=p.useState(null),[c,u]=p.useState(!0),[d,h]=p.useState(null),[f,m]=p.useState(null),[x,g]=p.useState(null),[y,b]=p.useState(null),[v,w]=p.useState(!1);function _(O){b(O),w(!0)}p.useEffect(()=>{e||t.kind==="ready"&&t.me.role!=="super_admin"&&n("/",{replace:!0})},[t,n,e]);const k=p.useCallback(async()=>{u(!0),h(null);try{const[O,R]=await Promise.all([oe("/api/admin/users"),oe("/api/admin/dashboard")]);if(!O.ok){const $=await O.json().catch(()=>({}));throw new Error(($==null?void 0:$.message)||($==null?void 0:$.error)||`HTTP ${O.status}`)}const I=await O.json();if(i(I.users),R.ok){const P=(await R.json()).kpis;l({online_now:P.online_now,wau:P.wau,new_signups_7d:P.new_signups_7d,paying_accounts:P.paying_accounts,awaiting_first_sync:P.awaiting_first_sync,low_balance:P.low_balance})}}catch(O){const R=O;h((R==null?void 0:R.message)||"Failed to load users.")}finally{u(!1)}},[]);p.useEffect(()=>{k()},[k]);const j=Id(a,p.useCallback(O=>[O.email,O.display_name,O.role,(O.plans??[]).map(G8).join(" ")],[]),{urlKey:"q"}),N=p.useMemo(()=>a.filter(O=>V8(O.last_seen_at)).length,[a]);async function E(O,R){if(O.role!==R){g(O.id),h(null);try{const I=await oe(`/api/admin/users/${O.id}/role`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({role:R})});if(!I.ok){const P=await I.json().catch(()=>({}));throw new Error((P==null?void 0:P.message)||(P==null?void 0:P.error)||`HTTP ${I.status}`)}const $=await I.json();i(P=>P.map(F=>F.id===O.id?{...F,role:$.user.role,display_name:$.user.display_name??F.display_name}:F))}catch(I){const $=I;h(($==null?void 0:$.message)||"Failed to update role.")}finally{g(null)}}}async function A(O){if(!(f||r)&&O.role!=="super_admin"){m(O.id),h(null);try{await Gce(O.id),n("/",{replace:!0})}catch(R){const I=R;h((I==null?void 0:I.message)||"Failed to start impersonation.")}finally{m(null)}}}const C=t.kind==="ready"?t.me.id:null,T=[{key:"name",label:"Name",sortable:!0,sticky:!0,getValue:O=>O.display_name,render:O=>O.display_name||s.jsx("span",{className:"text-text-tertiary",children:"â"})},{key:"email",label:"Email",sortable:!0,getValue:O=>O.email,render:O=>s.jsx("span",{className:"font-mono text-xs",children:O.email})},{key:"role",label:"Role",sortable:!0,getValue:O=>O.role,stopRowClick:!0,render:O=>{const R=C===O.id;return s.jsxs(s.Fragment,{children:[O.role==="super_admin"||R||!O.email.toLowerCase().endsWith("@gadjet.co.za")?s.jsx("span",{className:`inline-flex items-center rounded-md border px-2 py-0.5 text-xs font-medium ${Vj(O.role)}`,children:Y8(O.role)}):O.role==="am"||O.role==="content_creator"?s.jsxs("select",{className:`rounded-md border px-2 py-0.5 text-xs font-medium ${Vj(O.role)}`,value:O.role,disabled:!!x||!!r,onChange:I=>E(O,I.target.value),children:[s.jsx("option",{value:"am",children:"AM"}),s.jsx("option",{value:"content_creator",children:"Content"})]}):s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx("span",{className:`inline-flex items-center rounded-md border px-2 py-0.5 text-xs font-medium ${Vj(O.role)}`,children:Y8(O.role)}),s.jsx(W,{type:"button",intent:"neutral",variant:"outline",size:"sm",disabled:!!x||!!r,onClick:()=>E(O,"content_creator"),children:"Make Content"})]}),x===O.id&&s.jsx(_e,{className:"ml-1 inline h-3 w-3 animate-spin text-text-tertiary"})]})}},{key:"plan",label:"Plan",render:O=>O.plans&&O.plans.length>0?s.jsx("span",{className:"flex flex-wrap gap-1",children:O.plans.map(R=>s.jsx("span",{className:"inline-flex items-center rounded-md border border-outline-subtle bg-surface-subtle px-2 py-0.5 text-xs font-medium text-text-body",children:G8(R)},R))}):s.jsx("span",{className:"text-text-tertiary",children:"â"})},{key:"created",label:"Created",sortable:!0,getValue:O=>O.created_at,render:O=>s.jsx("span",{className:"text-text-secondary",children:q8(O.created_at)})},{key:"signin",label:"Last sign-in",sortable:!0,getValue:O=>O.last_sign_in_at,render:O=>s.jsx("span",{className:"text-text-secondary",children:q8(O.last_sign_in_at)})},{key:"lastseen",label:"Last seen",sortable:!0,getValue:O=>O.last_seen_at,render:O=>V8(O.last_seen_at)?s.jsx(x6,{tone:"success",children:s.jsx("span",{className:"font-medium text-text-success",children:"Online"})}):s.jsx("span",{className:"text-text-secondary",children:Qtt(O.last_seen_at)})},{key:"chats",label:"Chats 7d",sortable:!0,align:"right",getValue:O=>O.chats_7d,render:O=>s.jsx("span",{className:`font-mono text-xs ${O.chats_7d>0?"text-text-primary":"text-text-tertiary"}`,children:O.chats_7d>0?O.chats_7d:"â"})},{key:"spend",label:"Spend (MTD)",sortable:!0,align:"right",getValue:O=>O.mtd_billable_zar,render:O=>s.jsx("span",{className:`font-mono text-xs ${O.mtd_billable_zar>0?"text-text-primary":"text-text-tertiary"}`,children:tnt(O.mtd_billable_zar)})},{key:"action",label:"Action",align:"right",stopRowClick:!0,render:O=>{const R=C===O.id;return O.role==="super_admin"||R?s.jsx("span",{className:"text-xs text-text-tertiary",children:R?"y
941ou":"â"}):s.jsxs(W,{type:"button",onClick:()=>A(O),disabled:!!f||!!r,intent:"warning",variant:"outline",size:"sm",children:[f===O.id?s.jsx(_e,{className:"h-3 w-3 animate-spin"}):s.jsx(al,{className:"h-3 w-3"}),"Run as"]})}}];return!e&&t.kind==="ready"&&t.me.role!=="super_admin"?null:s.jsxs(s.Fragment,{children:[!e&&s.jsx(Pt,{crumbs:[{label:"Users"}],actions:s.jsxs(W,{type:"button",onClick:k,intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(vi,{className:"h-3.5 w-3.5"})," Refresh"]})}),s.jsxs("div",{className:e?"":"flex-1 overflow-auto p-4 md:p-6",children:[s.jsxs("div",{className:"mb-4 flex flex-wrap gap-3",children:[s.jsxs(V,{className:"px-4 py-3 flex items-center gap-3 min-w-[8rem]",children:[s.jsxs("span",{className:"relative inline-flex h-2.5 w-2.5",children:[s.jsx("span",{className:"absolute inline-flex h-full w-full rounded-full bg-success-500 opacity-60 animate-ping"}),s.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-success-500"})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-2xl font-semibold text-text-primary leading-none",children:(o==null?void 0:o.online_now)??N}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"Online now"})]})]}),s.jsxs(V,{className:"px-4 py-3 min-w-[8rem]",children:[s.jsx("div",{className:"text-2xl font-semibold text-text-primary leading-none",children:(o==null?void 0:o.wau)??"â"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"Active 7d"})]}),s.jsxs(V,{className:"px-4 py-3 min-w-[8rem]",children:[s.jsx("div",{className:"text-2xl font-semibold text-text-primary leading-none",children:(o==null?void 0:o.new_signups_7d)??"â"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"New signups 7d"})]}),s.jsxs(V,{className:"px-4 py-3 min-w-[8rem]",children:[s.jsx("div",{className:"text-2xl font-semibold text-text-primary leading-none",children:(o==null?void 0:o.paying_accounts)??"â"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"Paying accounts"})]}),s.jsxs(V,{className:"px-4 py-3 min-w-[8rem]",children:[s.jsx("div",{className:"text-2xl font-semibold text-text-primary leading-none",children:(o==null?void 0:o.awaiting_first_sync)??"â"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"Awaiting first sync"})]}),s.jsxs(V,{className:"px-4 py-3 min-w-[8rem]",children:[s.jsx("div",{className:"text-2xl font-semibold text-text-primary leading-none",children:(o==null?void 0:o.low_balance)??"â"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"Low balance (< R50)"})]})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"border-b border-outline-subtle px-4 py-3 flex items-center gap-3",children:[s.jsx(Ni,{value:j.q,onChange:j.setQ,placeholder:"Filter by name, email, role, or plan",className:"flex-1 min-w-0"}),s.jsxs("span",{className:"text-xs text-text-secondary shrink-0",children:[((S=j.filtered)==null?void 0:S.length)??0," of ",a.length]})]}),d&&s.jsxs("div",{className:"bg-surface-errorSubtle border-b border-outline-error px-4 py-2 text-sm text-text-error flex items-center gap-2",children:[s.jsx(yt,{className:"h-4 w-4 shrink-0"}),s.jsx("span",{className:"flex-1 min-w-0 truncate",children:d})]}),r&&s.jsxs("div",{className:"bg-surface-warningSubtle border-b border-outline-warning px-4 py-2 text-xs text-text-warning",children:["You're already viewing as ",s.jsx("strong",{children:r.target.display_name||r.target.email}),". Exit the current session before starting a new one."]}),s.jsx(dt,{rows:j.filtered,columns:T,getRowKey:O=>O.id,loading:c,empty:{title:"No users match."},onRowClick:O=>_(O.id)})]})]}),s.jsx(lY,{userId:y,open:v,onOpenChange:w})]})}function qj(e){if(!e)return"â";const t=new Date(e).getTime();if(Number.isNaN(t))return e;const n=Date.now()-t;if(n<6e4)return"just now";const r=Math.floor(n/6e4);if(r<60)return`${r}m ago`;const a=Math.floor(r/60);if(a<24)return`${a}h ago`;const i=Math.floor(a/24);return i<30?`${i}d ago`:new Date(e).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}function Gj(e){switch(e){case"super_admin":return"bg-surface-brandSubtle text-text-brand border-outline-brand";case"am":return"bg-surface-infoSubtle text-text-info border-outline-info";case"seller_user":return"bg-surface-successSubtle text-text-success border-outline-success";default:return"bg-surface-subtle text-text-body border-outline-subtle"}}function zu({label:e,value:t,hint:n}){return s.jsxs(V,{className:"px-4 py-3 min-w-[8rem]",children:[s.jsx("div",{className:"text-2xl font-semibold text-text-primary leading-none",children:t}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:e}),n&&s.jsx("div",{className:"text-[10px] text-text-tertiary mt-0.5",children:n})]})}function rnt({points:e}){if(!e.length)return null;const t=220,n=40,r=Math.max(1,...e.map(o=>o.active)),a=t/Math.max(1,e.length-1),i=e.map((o,l)=>`${l===0?"M":"L"} ${(l*a).toFixed(1)} ${(n-o.active/r*(n-4)-2).toFixed(1)}`).join(" ");
941return s.jsx("svg",{width:t,height:n,className:"text-text-brand",children:s.jsx("path",{d:i,fill:"none",stroke:"currentColor",strokeWidth:1.5})})}function snt({embedded:e=!1}={}){const t=Lt(),n=Rt(),[r,a]=p.useState(null),[i,o]=p.useState(!0),[l,c]=p.useState(null);p.useEffect(()=>{e||t.kind==="ready"&&t.me.role!=="super_admin"&&n("/",{replace:!0})},[t,n,e]);const u=p.useCallback(async()=>{o(!0),c(null);try{const m=await oe("/api/admin/dashboard");if(!m.ok){const x=await m.json().catch(()=>({}));throw new Error((x==null?void 0:x.message)||(x==null?void 0:x.error)||`HTTP ${m.status}`)}a(await m.json())}catch(m){const x=m;c((x==null?void 0:x.message)||"Failed to load dashboard.")}finally{o(!1)}},[]);if(p.useEffect(()=>{u()},[u]),!e&&t.kind==="ready"&&t.me.role!=="super_admin")return null;const d=r==null?void 0:r.kpis,h=r==null?void 0:r.presence,f=r==null?void 0:r.engagement;return s.jsxs(s.Fragment,{children:[!e&&s.jsx(Pt,{crumbs:[{label:"Dashboard"}],actions:s.jsxs(W,{type:"button",onClick:u,intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(vi,{className:"h-3.5 w-3.5"})," Refresh"]})}),s.jsxs("div",{className:e?"space-y-6":"flex-1 overflow-auto p-4 md:p-6 space-y-6",children:[l&&s.jsxs("div",{className:"bg-surface-errorSubtle border border-outline-error px-4 py-2 rounded-md text-sm text-text-error flex items-center gap-2",children:[s.jsx(yt,{className:"h-4 w-4 shrink-0"}),s.jsx("span",{className:"flex-1 min-w-0 truncate",children:l})]}),i&&!r?s.jsx("div",{className:"flex items-center justify-center py-12 text-text-tertiary",children:s.jsx(_e,{className:"h-5 w-5 animate-spin"})}):d&&h&&f&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap gap-3",children:[s.jsxs(V,{className:"px-4 py-3 flex items-center gap-3 min-w-[8rem]",children:[s.jsxs("span",{className:"relative inline-flex h-2.5 w-2.5",children:[s.jsx("span",{className:"absolute inline-flex h-full w-full rounded-full bg-success-500 opacity-60 animate-ping"}),s.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-success-500"})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-2xl font-semibold text-text-primary leading-none",children:d.online_now}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"Online now"})]})]}),s.jsx(zu,{label:"DAU",value:d.dau,hint:"last 24h"}),s.jsx(zu,{label:"WAU",value:d.wau,hint:"last 7d"}),s.jsx(zu,{label:"MAU",value:d.mau,hint:"last 30d"}),s.jsx(zu,{label:"New signups",value:d.new_signups_7d,hint:"last 7d"}),s.jsx(zu,{label:"Paying accounts",value:d.paying_accounts,hint:"active subs"}),s.jsx(zu,{label:"Awaiting first sync",value:d.awaiting_first_sync}),s.jsx(zu,{label:"Low balance",value:d.low_balance,hint:"< R50"})]}),s.jsxs("section",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[s.jsxs(V,{className:"p-4",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsx("h2",{className:"text-sm font-medium text-text-primary",children:"Presence â 30-day active users"}),s.jsx(rnt,{points:h.dau_30d})]}),s.jsxs("div",{className:"text-xs text-text-secondary",children:[d.dau," today · ",d.wau," this week · ",d.mau," this month"]})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsx("div",{className:"px-4 py-3 border-b border-outline-subtle",children:s.jsxs("h2",{className:"text-sm font-medium text-text-primary",children:["Online now (",h.online_now.length,")"]})}),s.jsx("div",{className:"max-h-80 overflow-y-auto",children:s.jsx(dt,{rows:h.online_now,columns:[{key:"name",label:"Name",render:m=>m.display_name||s.jsx("span",{className:"text-text-tertiary",children:"â"})},{key:"email",label:"Email",render:m=>s.jsx("span",{className:"font-mono text-xs text-text-secondary",children:m.email})},{key:"role",label:"Role",render:m=>s.jsx("span",{className:`inline-flex items-center rounded-md border px-2 py-0.5 text-[10px] font-medium ${Gj(m.role)}`,children:m.role})},{key:"lastSeen",label:"Last seen",render:m=>s.jsx("span",{className:"text-xs text-text-secondary",children:qj(m.last_seen_at)})}],getRowKey:m=>m.id,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No-one in the app right now."}})})]})]}),s.jsxs("section",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[s.jsxs(V,{className:"overflow-hidden",children:[s.jsx("div",{className:"px-4 py-3 border-b border-outline-subtle",children:s.jsx("h2",{className:"text-sm font-medium text-text-primary",children:"Top users (last 7 days)"})}),s.jsx(dt,{rows:f.top_users_7d,columns:[{key:"user",label:"User",render:m=>s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-text-primary",children:m.display_name||m.email}),m.display_name&&s.jsx("div",{className:"text-xs text-text-tertiary font-mono",children:m.email})]})},{key:"role",label:"Role",render:m=>s.jsx("span",{className:`inline-flex items-center rounded-md border px-2 py-0.5 text-[10px] font-medium ${Gj(m.role)}`,children:m.role})},{key:"chats",label:"Chats",align:"right",render:m=>s.jsx("span",{className:"font-mono text-xs",children:m.chats_7d})}
941,{key:"rounds",label:"Rounds",align:"right",render:m=>s.jsx("span",{className:"font-mono text-xs text-text-secondary",children:m.messages_7d})}],getRowKey:m=>m.id,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No activity in window."}})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsx("div",{className:"px-4 py-3 border-b border-outline-subtle",children:s.jsx("h2",{className:"text-sm font-medium text-text-primary",children:"Top skills (last 7 days)"})}),s.jsx(dt,{rows:f.top_skills_7d,columns:[{key:"skill",label:"Skill",render:m=>s.jsx("span",{className:"font-mono text-xs",children:m.skill_name})},{key:"calls",label:"Calls",align:"right",render:m=>s.jsx("span",{className:"font-mono text-xs",children:m.calls})},{key:"users",label:"Users",align:"right",render:m=>s.jsx("span",{className:"font-mono text-xs text-text-secondary",children:m.users})}],getRowKey:m=>m.skill_name,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No skills invoked in window."}})]})]}),s.jsx("section",{children:s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-4 py-3 border-b border-outline-subtle flex items-center justify-between",children:[s.jsx("h2",{className:"text-sm font-medium text-text-primary",children:"Recent logins (last 25)"}),s.jsxs("span",{className:"text-xs text-text-tertiary",children:["avg ",f.avg_chats_per_wau," chats/WAU"]})]}),s.jsx(dt,{rows:h.login_feed,columns:[{key:"user",label:"User",render:m=>s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-text-primary",children:m.display_name||m.email}),m.display_name&&s.jsx("div",{className:"text-xs text-text-tertiary font-mono",children:m.email})]})},{key:"role",label:"Role",render:m=>s.jsx("span",{className:`inline-flex items-center rounded-md border px-2 py-0.5 text-[10px] font-medium ${Gj(m.role)}`,children:m.role})},{key:"signedIn",label:"Signed in",render:m=>s.jsx("span",{className:"text-xs text-text-secondary",children:qj(m.last_sign_in_at)})}],getRowKey:m=>m.id,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No recent logins."}})]})}),s.jsxs("div",{className:"text-xs text-text-tertiary",children:["Updated ",r&&qj(r.generated_at)," · cached 60s"]})]})]})]})}const Pm=new Set(["demo","internal_gadjet","agency","internal"]),ant=[{value:"7d",label:"7 days"},{value:"30d",label:"30 days"},{value:"90d",label:"90 days"},{value:"mtd",label:"MTD"}],int=new Intl.NumberFormat("en-ZA",{style:"currency",currency:"ZAR",maximumFractionDigits:0}),ont=new Intl.NumberFormat("en-ZA",{style:"currency",currency:"ZAR",maximumFractionDigits:2});function El(e,t=!1){return e==null||!Number.isFinite(e)?"â":(t?ont:int).format(e)}function lnt(e){return e==null||!Number.isFinite(e)?"â":`$${e.toFixed(2)}`}function Yj(e,t){if(!Number.isFinite(t)||t===0)return e>0?{text:"new",positive:!0}:null;const n=(e-t)/t*100;if(!Number.isFinite(n))return null;const r=Math.round(n);return r===0?{text:"0%",positive:!1}:{text:`${r>0?"+":""}${r}%`,positive:r>=0}}function wy({children:e,sub:t}){return s.jsxs("div",{className:"flex items-baseline justify-between",children:[s.jsx("h3",{className:"text-xs font-semibold uppercase tracking-wide text-text-secondary",children:e}),t?s.jsx("span",{className:"text-xs text-text-tertiary",children:t}):null]})}function cnt(e){switch(e){case"super_admin":return"bg-surface-brandSubtle text-text-brand border-outline-brand";case"am":return"bg-surface-infoSubtle text-text-info border-outline-info";case"seller_user":return"bg-surface-successSubtle text-text-success border-outline-success";default:return"bg-surface-subtle text-text-body border-outline-subtle"}}function unt({embedded:e=!1}={}){const t=Lt(),n=Rt(),[r,a]=p.useState(null),[i,o]=p.useState(!0),[l,c]=p.useState(null),[u,d]=p.useState("30d"),[h,f]=p.useState(null),[m,x]=p.useState(!1);p.useEffect(()=>{e||t.kind==="ready"&&t.me.role!=="super_admin"&&n("/",{replace:!0})},[t,n,e]);const g=p.useCallback(async()=>{o(!0),c(null);try{const N=await oe(`/api/admin/ai-spend?window=${u}`);if(!N.ok){const A=await N.json().catch(()=>({}));throw new Error((A==null?void 0:A.message)||(A==null?void 0:A.error)||`HTTP ${N.status}`)}const E=await N.json();a(E)}catch(N){const E=N;c((E==null?void 0:E.message)||"Failed to load AI spend.")}finally{o(!1)}},[u]);p.useEffect(()=>{g()},[g]);const y=p.useMemo(()=>r!=null&&r.byAccountType?[...r.byAccountType].sort((E,A)=>{const C=Pm.has(E.account_type)?1:0,T=Pm.has(A.account_type)?1:0;return C!==T?C-T:A.billable_zar-E.billable_zar}):[],[r]);function b(N){f(N),x(!0)}if(!e&&t.kind==="ready"&&t.me.role!=="super_admin")return null;const v=r==null?void 0:r.kpis,w=v?v.billable_zar-v.debited_zar:0,_=v?v.prior_billable_zar-v.prior_debited_zar:0,k=Math.max(1,...y.map(N=>N.billable_zar)),j=Math.max(1,...((r==null?void 0:r.bySkill)??[]).map(N=>N.billable_zar));return s.jsxs(s.Fragment,{children:[!e&&s.jsx(Pt,{crumbs:[{label:"AI Spend"}],actions:s.jsxs(W,{type:"button",onClick:g,intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(vi,{className:"h-3.5 w-3.5"})," Refresh"]})}),s.jsxs("div",{className:e?"flex flex-col gap-5":"flex-1 overflow-auto p-4 md:p-6 flex flex-col gap-5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-xs uppercase tracking-wide text-text-secondary",children:"Window"}),s.jsx("div",{className:"inline-flex rounded-md border border-outline-subtle overflow-hidden",children:ant.map(N=>s.jsx("button",{type:"button",onClick:()=>
941d(N.value),className:`px-3 py-1 text-xs font-medium transition-colors ${u===N.value?"bg-surface-inverse text-text-inverse":"bg-surface text-text-secondary hover:bg-surface-subtle"}`,children:N.label},N.value))})]}),l&&s.jsxs("div",{className:"rounded-md border border-outline-error bg-surface-errorSubtle px-3 py-2 text-sm text-text-error flex items-center gap-2",children:[s.jsx(yt,{className:"h-4 w-4 shrink-0"}),s.jsx("span",{children:l})]}),i||!v?s.jsxs("div",{className:"flex items-center gap-2 text-sm text-text-secondary",children:[s.jsx(_e,{className:"h-4 w-4 animate-spin"}),"Loadingâ¦"]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 gap-3 md:grid-cols-4",children:[s.jsx(Ye,{label:"Anthropic cost (USD)",value:lnt(v.cost_usd),hint:"Raw API charge",deltaIsBadWhenUp:!0}),s.jsx(Ye,{label:"Billable (ZAR)",value:El(v.billable_zar),hint:`${v.calls.toLocaleString()} calls`,delta:Yj(v.billable_zar,v.prior_billable_zar),deltaIsBadWhenUp:!0}),s.jsx(Ye,{label:"Credits debited (ZAR)",value:El(v.debited_zar),hint:"Recovered from metered users",delta:Yj(v.debited_zar,v.prior_debited_zar),deltaIsBadWhenUp:!1}),s.jsx(Ye,{label:"Unbilled spend (ZAR)",value:El(w),hint:"Subsidy bill",delta:Yj(w,_),deltaIsBadWhenUp:!0})]}),v.impersonated_zar>0?s.jsxs("div",{className:"rounded-md border border-outline-warning bg-surface-warningSubtle px-3 py-2 text-xs text-text-warning",children:[s.jsx("strong",{children:El(v.impersonated_zar,!0)}),' spent in this window via super-admin "Run as" sessions (',v.impersonated_calls.toLocaleString()," calls). Not debited from any seller â Gadjet eats it."]}):null,s.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2",children:[s.jsxs(V,{className:"overflow-hidden",children:[s.jsx("div",{className:"px-4 py-3 border-b border-outline-subtle",children:s.jsx(wy,{sub:"Free-chat types marked *",children:"By account type"})}),s.jsx(dt,{rows:y,columns:[{key:"type",label:"Type",render:N=>s.jsxs(s.Fragment,{children:[N.account_type,Pm.has(N.account_type)?s.jsxs("span",{className:"text-text-warning",title:"Free-chat / subsidy",children:[" ","*"]}):null]})},{key:"users",label:"Users",align:"right",render:N=>s.jsx("span",{className:"text-text-secondary",children:N.users.toLocaleString()})},{key:"billable",label:"Billable",align:"right",render:N=>s.jsx("span",{className:"font-mono",children:El(N.billable_zar)})},{key:"share",label:"Share",className:"w-32",render:N=>{const E=Pm.has(N.account_type),A=N.billable_zar/k*100;return s.jsx("div",{className:"h-2 w-full rounded bg-surface-subtle overflow-hidden",children:s.jsx("div",{className:`h-full ${E?"bg-warning-400":"bg-brand-500"}`,style:{width:`${A}%`}})})}}],getRowKey:N=>N.account_type,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No data."}})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsx("div",{className:"px-4 py-3 border-b border-outline-subtle",children:s.jsx(wy,{children:"By surface & model"})}),s.jsx(dt,{rows:(r==null?void 0:r.bySurfaceModel)??[],columns:[{key:"surface",label:"Surface",render:N=>N.surface},{key:"model",label:"Model",render:N=>s.jsx("span",{className:"font-mono text-xs",children:N.model})},{key:"calls",label:"Calls",align:"right",render:N=>s.jsx("span",{className:"text-text-secondary",children:N.calls.toLocaleString()})},{key:"billable",label:"Billable",align:"right",render:N=>s.jsx("span",{className:"font-mono",children:El(N.billable_zar)})}],getRowKey:N=>`${N.surface}-${N.model}`,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No data."}})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsx("div",{className:"px-4 py-3 border-b border-outline-subtle",children:s.jsx(wy,{sub:"Top 15",children:"Top skills"})}),s.jsx(dt,{rows:(r==null?void 0:r.bySkill)??[],columns:[{key:"skill",label:"Skill",render:N=>{const E=N.billable_zar/j*100;return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"font-mono text-xs",children:N.skill_name}),s.jsx("div",{className:"mt-1 h-1 w-full max-w-[160px] rounded bg-surface-subtle overflow-hidden",children:s.jsx("div",{className:"h-full bg-brand-500",style:{width:`${E}%`}})})]})}},{key:"calls",label:"Calls",align:"right",className:"align-top",render:N=>s.jsx("span",{className:"text-text-secondary",children:N.calls.toLocaleStr
941ing()})},{key:"total",label:"Total",align:"right",className:"align-top",render:N=>s.jsx("span",{className:"font-mono",children:El(N.billable_zar)})},{key:"perCall",label:"Per call",align:"right",className:"align-top",render:N=>{const E=N.calls>0?N.billable_zar/N.calls:0;return s.jsx("span",{className:"font-mono text-text-secondary",children:El(E,!0)})}}],getRowKey:N=>N.skill_name,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No data."}})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsx("div",{className:"px-4 py-3 border-b border-outline-subtle",children:s.jsx(wy,{sub:"Click a row â drill-down",children:"Top users"})}),s.jsx(dt,{rows:(r==null?void 0:r.byUser)??[],columns:[{key:"user",label:"User",render:N=>s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"font-medium text-text-primary",children:N.display_name||N.email}),s.jsx("div",{className:"font-mono text-[11px] text-text-tertiary",children:N.email})]})},{key:"type",label:"Type",render:N=>{const E=Pm.has(N.account_type);return s.jsxs("div",{className:"flex flex-col gap-0.5 items-start",children:[s.jsx("span",{className:`inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium ${cnt(N.role)}`,children:N.role}),s.jsxs("span",{className:"text-[11px] text-text-secondary",children:[N.account_type,E?"*":""]})]})}},{key:"calls",label:"Calls",align:"right",className:"align-top",render:N=>s.jsx("span",{className:"text-text-secondary",children:N.calls.toLocaleString()})},{key:"billable",label:"Billable",align:"right",className:"align-top",render:N=>s.jsx("span",{className:"font-mono",children:El(N.billable_zar)})}],getRowKey:N=>N.user_id,paginate:!1,persist:!1,tableClassName:"text-body-sm",empty:{title:"No data."},onRowClick:N=>b(N.user_id)})]})]})]})]}),s.jsx(lY,{userId:h,open:m,onOpenChange:x})]})}function Zj(e){if(!e)return"â";try{return new Date(e).toLocaleString()}catch{return e}}function dnt({embedded:e=!1}={}){const t=Lt(),n=Rt(),[r,a]=p.useState(null),[i,o]=p.useState(!0),[l,c]=p.useState(null),[u,d]=p.useState(null),[h,f]=p.useState(""),[m,x]=p.useState(!1),[g,y]=p.useState(""),[b,v]=p.useState("");p.useEffect(()=>{e||t.kind==="ready"&&t.me.role!=="super_admin"&&n("/",{replace:!0})},[t,n,e]);const w=p.useCallback(async()=>{o(!0),c(null);try{const C=await oe("/api/admin/lockout");if(!C.ok){const T=await C.json().catch(()=>({}));throw new Error((T==null?void 0:T.message)||(T==null?void 0:T.error)||`HTTP ${C.status}`)}a(await C.json())}catch(C){c((C==null?void 0:C.message)||"Failed to load lockout state.")}finally{o(!1)}},[]);p.useEffect(()=>{w()},[w]);async function _(C){if(C&&!m){c("Tick the confirmation box before enabling a global lockout.");return}d("global"),c(null);try{const T=await oe("/api/admin/lockout/global",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:C,reason:C?h:null})});if(!T.ok){const S=await T.json().catch(()=>({}));throw new Error((S==null?void 0:S.message)||(S==null?void 0:S.error)||`HTTP ${T.status}`)}x(!1),C||f(""),await w()}catch(T){c((T==null?void 0:T.message)||"Failed to update global lockout.")}finally{d(null)}}async function k(C){const T=await oe("/api/admin/users");if(!T.ok)return null;const O=(await T.json()).users.find(R=>R.email.toLowerCase()===C.toLowerCase());return(O==null?void 0:O.id)??null}async function j(C,T,S){d(T),c(null);try{let O=T;if(T.includes("@")){const I=await k(T);if(!I)throw new Error("No user with that email.");O=I}const R=await oe(`/api/admin/lockout/user/${O}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:C,reason:S})});if(!R.ok){const I=await R.json().catch(()=>({}));throw new Error((I==null?void 0:I.message)||(I==null?void 0:I.error)||`HTTP ${R.status}`)}y(""),v(""),await w()}catch(O){c((O==null?void 0:O.message)||"Failed to update user lockout.")}finally{d(null)}}const N=!!(r!=null&&r.global.enabled),E=(r==null?void 0:r.locked_users.length)??0,A=p.useMemo(()=>(r==null?void 0:r.audit)??[],[r]);return!e&&t.kind==="ready"&&t.me.role!=="super_admin"?null:s.jsxs(s.Fragment,{children:[!e&&s.jsx(Pt,{crumbs:[{label:"Emergency lockout"}],actions:s.jsxs(W,{type:"button",onClick:w,intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(vi,{className:"h-3.5 w-3.5"})," Refresh"]})}),s.jsxs("div",{className:e?"space-y-6":"flex-1 overflow-auto p-4 md:p-6 space-y-6",children:[l&&s.jsxs("div",{className:"rounded-md bg-surface-errorSubtle border border-outline-error px-4 py-2 text-sm text-text-error flex items-center gap-2",children:[s.jsx(yt,{className:"h-4 w-4 shrink-0"}),l]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-4 py-3 border-b border-outline-subtle flex items-center gap-2",children:[s.jsx(Bl,{className:"h-4 w-4 text-text-secondary"}),s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Global lockout"}),s.jsx("span",{className:"ml-auto text-xs px-2 py-0.5 rounded-full border "+(N?"bg-surface-errorSubtle text-text-error border-outline-error":"bg-surface-successSubtle text-text-success border-outline-success"),children:N?"ACTIVE":"off"})]}),s.jsxs("div",{className:"p-4 space-y-3",children:[s.jsxs("p",{className:"text-sm text-text-secondary",children:["Blocks every non-super-admin from using Gadjet. Use for emergencie
941s only. Reversible by clicking ",s.jsx("em",{children:"Disable"})," below."]}),N?s.jsxs("div",{className:"rounded-md bg-surface-errorSubtle border border-outline-error p-3 text-sm text-text-error",children:[s.jsx("div",{className:"font-medium",children:"Global lockout is active."}),(r==null?void 0:r.global.reason)&&s.jsxs("div",{className:"mt-1 italic",children:['"',r.global.reason,'"']}),s.jsxs("div",{className:"mt-1 text-xs text-text-error",children:["Set at ",Zj((r==null?void 0:r.global.set_at)??null)]})]}):null,!N&&s.jsxs(s.Fragment,{children:[s.jsx("label",{className:"block text-xs font-medium text-text-body",children:"Reason (shown to locked users)"}),s.jsx(Re,{type:"text",value:h,onChange:C=>f(C.target.value),placeholder:"e.g. Emergency maintenance â back shortly",maxLength:500,inputSize:"sm"}),s.jsxs("label",{className:"flex items-start gap-2 text-sm text-text-body cursor-pointer",children:[s.jsx(ei,{checked:m,onCheckedChange:C=>x(C===!0),className:"mt-0.5"}),s.jsx("span",{children:"I understand this will sign every non-super-admin out of Gadjet until I disable it."})]})]}),s.jsx("div",{className:"pt-2",children:N?s.jsxs(W,{type:"button",disabled:u==="global",onClick:()=>_(!1),intent:"success",variant:"solid",size:"md",children:[u==="global"?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):s.jsx(HT,{className:"h-4 w-4"}),"Disable global lockout"]}):s.jsxs(W,{type:"button",disabled:u==="global"||!m,onClick:()=>_(!0),intent:"destructive",variant:"solid",size:"md",children:[u==="global"?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):s.jsx(Bl,{className:"h-4 w-4"}),"Enable global lockout"]})})]})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-4 py-3 border-b border-outline-subtle flex items-center gap-2",children:[s.jsx(Bl,{className:"h-4 w-4 text-text-secondary"}),s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Lock a specific user"}),s.jsxs("span",{className:"ml-auto text-xs text-text-secondary",children:[E," currently locked"]})]}),s.jsxs("div",{className:"p-4 space-y-3",children:[s.jsx("label",{className:"block text-xs font-medium text-text-body",children:"User email"}),s.jsx(Re,{type:"email",value:g,onChange:C=>y(C.target.value),placeholder:"[email protected]",inputSize:"sm"}),s.jsx("label",{className:"block text-xs font-medium text-text-body",children:"Reason"}),s.jsx(Re,{type:"text",value:b,onChange:C=>v(C.target.value),placeholder:"Optional â visible to the user",maxLength:500,inputSize:"sm"}),s.jsxs(W,{type:"button",disabled:u===g||!g.trim(),onClick:()=>j(!0,g.trim(),b||null),intent:"destructive",variant:"solid",size:"md",children:[u===g?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):s.jsx(Bl,{className:"h-4 w-4"}),"Lock this user"]})]}),E>0&&s.jsxs("div",{className:"border-t border-outline-subtle",children:[s.jsx("div",{className:"px-4 py-2 text-xs font-medium text-text-secondary bg-surface-subtle",children:"Currently locked"}),s.jsx("ul",{className:"divide-y divide-outline-faint",children:r==null?void 0:r.locked_users.map(C=>s.jsxs("li",{className:"px-4 py-2 flex items-center gap-3 text-sm",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:C.display_name||C.email}),s.jsxs("div",{className:"text-xs text-text-secondary truncate",children:[C.email," · ",C.role," · locked ",Zj(C.locked_at)]}),C.lockout_reason&&s.jsxs("div",{className:"text-xs text-text-secondary italic truncate",children:['"',C.lockout_reason,'"']})]}),s.jsxs(W,{type:"button",disabled:u===C.id,onClick:()=>j(!1,C.id,null),intent:"neutral",variant:"outline",size:"sm",children:[u===C.id?s.jsx(_e,{className:"h-3 w-3 animate-spin"}):s.jsx(HT,{className:"h-3 w-3"}),"Unlock"]})]},C.id))})]})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsx("div",{className:"px-4 py-3 border-b border-outline-subtle",children:s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Recent lockout activity"})}),i?s.jsx("div",{className:"p-6 flex justify-center",children:s.jsx(_e,{className:"h-4 w-4 animate-spin text-text-tertiary"})}):A.length===0?s.jsx("div",{className:"p-6 text-sm text-text-secondary text-center",children:"No activity yet."}):s.jsx("ul",{className:"divide-y divide-outline-faint",children:A.map(C=>s.jsxs("li",{className:"px-4 py-2 text-sm flex items-baseline gap-3",children:[s.jsx("span",{className:"text-xs text-text-secondary shrink-0 w-40",children:Zj(C.acted_at)}),s.jsx("span",{className:"font-medium text-text-primary shrink-0",children:C.scope==="global"?"GLOBAL":"user"}),s.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded shrink-0 "+(C.enabled?"bg-surface-errorSubtle text-text-error":"bg-surface-successSubtle text-text-success"),children:C.enabled?"locked":"unlocked"}),C.reason&&s.jsxs("span",{className:"text-text-secondary italic truncate",children:['"',C.reason,'"']}
941)]},C.id))})]})]})]})}const Z8=[{key:"super_admin",label:"Super admin"},{key:"am",label:"AM"},{key:"seller_user",label:"Seller"},{key:"content_creator",label:"Content"}],X8={top:"Top-level surfaces",seller:"Per-seller sub-surfaces"};function J8(e,t){const n={};for(const r of e){const a=t[r.key]??{};n[r.key]={super_admin:a.super_admin??r.defaults.super_admin,am:a.am??r.defaults.am,seller_user:a.seller_user??r.defaults.seller_user,content_creator:a.content_creator??r.defaults.content_creator}}return n}function hnt({embedded:e=!1}={}){const t=Lt(),n=Rt(),[r,a]=p.useState([]),[i,o]=p.useState({}),[l,c]=p.useState({}),[u,d]=p.useState(!0),[h,f]=p.useState(!1),[m,x]=p.useState(null),[g,y]=p.useState(!1),[b,v]=p.useState([]),[w,_]=p.useState(""),[k,j]=p.useState({}),[N,E]=p.useState({}),[A,C]=p.useState(!1),[T,S]=p.useState(!1);p.useEffect(()=>{e||t.kind==="ready"&&t.me.role!=="super_admin"&&n("/",{replace:!0})},[t,n,e]);const O=p.useCallback(async()=>{d(!0),x(null);try{const G=await oe("/api/admin/nav-access");if(!G.ok){const L=await G.json().catch(()=>({}));throw new Error((L==null?void 0:L.message)||(L==null?void 0:L.error)||`HTTP ${G.status}`)}const te=await G.json(),re=J8(te.surfaces,te.overrides??{});a(te.surfaces),o(re),c(re)}catch(G){x((G==null?void 0:G.message)||"Failed to load nav access.")}finally{d(!1)}},[]);p.useEffect(()=>{O()},[O]);const R=p.useMemo(()=>JSON.stringify(i)!==JSON.stringify(l),[i,l]);function I(G,te){y(!1),o(re=>({...re,[G]:{...re[G],[te]:!re[G][te]}}))}function $(){y(!1);const G={};for(const te of r)G[te.key]={...te.defaults};o(G)}function P(){y(!1),o(l)}async function F(){f(!0),x(null);try{const G=await oe("/api/admin/nav-access",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({matrix:i})});if(!G.ok){const L=await G.json().catch(()=>({}));throw new Error((L==null?void 0:L.message)||(L==null?void 0:L.error)||`HTTP ${G.status}`)}const te=await G.json(),re=J8(r,te.overrides??{});o(re),c(re),y(!0),ai()}catch(G){x((G==null?void 0:G.message)||"Failed to save nav access.")}finally{f(!1)}}p.useEffect(()=>{(async()=>{try{const G=await oe("/api/admin/users");if(!G.ok)return;const te=await G.json();v(te.users??[])}catch{}})()},[]);const Z=p.useMemo(()=>b.find(G=>G.id===w)??null,[b,w]),D=p.useMemo(()=>JSON.stringify(k)!==JSON.stringify(N),[k,N]);async function H(G){if(_(G),S(!1),j({}),E({}),!!G){C(!0),x(null);try{const te=await oe(`/api/admin/nav-access/user/${G}`);if(!te.ok){const L=await te.json().catch(()=>({}));throw new Error((L==null?void 0:L.message)||(L==null?void 0:L.error)||`HTTP ${te.status}`)}const re=await te.json();j(re.overrides??{}),E(re.overrides??{})}catch(te){x((te==null?void 0:te.message)||"Failed to load user overrides.")}finally{C(!1)}}}function Y(G,te){S(!1),j(re=>{const L={...re};return te==="inherit"?delete L[G]:L[G]=te==="show",L})}async function M(){if(w){C(!0),x(null);try{const G=await oe(`/api/admin/nav-access/user/${w}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({overrides:k})});if(!G.ok){const re=await G.json().catch(()=>({}));throw new Error((re==null?void 0:re.message)||(re==null?void 0:re.error)||`HTTP ${G.status}`)}const te=await G.json();j(te.overrides??{}),E(te.overrides??{}),S(!0),t.kind==="ready"&&t.me.id===w&&ai()}catch(G){x((G==null?void 0:G.message)||"Failed to save user overrides.")}finally{C(!1)}}}const z=p.useMemo(()=>{const G=["top","seller"],te=new Map;for(const L of r)te.has(L.group)||te.set(L.group,[]),te.get(L.group).push(L);return Array.from(te.keys()).sort((L,q)=>G.indexOf(L)-G.indexOf(q)).map(L=>({group:L,items:te.get(L)}))},[r]);return!e&&t.kind==="ready"&&t.me.role!=="super_admin"?null:s.jsxs(s.Fragment,{children:[!e&&s.jsx(Pt,{crumbs:[{label:"Navigation access"}]}),s.jsxs("div",{className:e?"space-y-6":"flex-1 overflow-auto p-4 md:p-6 space-y-6",children:[s.jsx("p",{className:"text-sm text-text-secondary",children:"Control which left-nav surfaces each user type can see. Defaults match today's behaviour â only changes are stored. A hidden surface is also blocked by direct URL (the page redirects), but this is a UI gate, not a data-security boundary. Changes apply to each user on their next load."}),m&&s.jsxs("div",{className:"rounded-md bg-surface-errorSubtle border border-outline-error px-4 py-2 text-sm text-text-error flex items-center gap-2",children:[s.jsx(yt,{className:"h-4 w-4 shrink-0"}),m]}),u?s.jsx("div",{className:"p-6 flex justify-center",children:s.jsx(_e,{className:"h-4 w-4 animate-spin text-text-tertiary"})}):s.jsxs(s.Fragment,{children:[z.map(({group:G,items:te})=>s.jsxs(V,{className:"overflow-hidden",children:[s.jsx("div",{className:"px-4 py-3 border-b border-outline-subtle",children:s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:X8[G]??G})}),s.jsxs("table",{className:"w-full text-sm",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"text-xs text-text-secondary bg-surface-subtle",children:[s.jsx("th",{className:"text-left font-medium px-4 py-2",children:"Surface"}),Z8.map(re=>s.jsx("th",{className:"font-medium px-4 py-2 text-center w-28",children:re.label},re.key))]})}),s.jsx("tbody",{className:"divide-y divide-outline-faint",children:te.map(re=>{const L=i[re.key];return L?s.jsxs("tr",{children:[s.jsxs("td",{className:"px-4 py-2.5",children:[s.jsx("div",{className:"font-medium text-text-primary",children:re.label}),s.jsx("div",{className:"text-xs text-text-tertiary",children:re.key})]}),Z8.map(q=>{const me=L[q.key],ee=me!==re.defaults[q.key];return s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsxs("div",{className:"inline-flex items-center justify-center relative",children:[s.jsx(ei,{checked:me,onCheckedChange:()=>I(re.key,q.key),"aria-label":`${re.label} visible to ${q.label}`}),ee&&s.jsx("span",{className:"absolute -right-3 top-1/2 -translate-y-1/2 w-1.5 h-1.5 rounded-full bg-brand-500",title:"Differs from default"})]})},q.key)})]},re.key):null})})]})]},G)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(W,{type:"button",onClick:F,disabled:!R||h,intent:"brand",variant:"solid",size:"md",children:[h?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):s.jsx(ko,{className:"h-4 w-4"}),"Save changes"]}),s.jsx(W,{type:"button",onClick:P,disabled:!R||h,intent:"neutral",variant:"outline",size:"md",children:"Revert"}),s.jsxs(W,{type:"button",onClick:$,disabled:h,intent:"neutral",variant:"ghost",size:"md",children:[s.jsx(_o,{className:"h-3.5 w-3.5"})," Reset all to defaults"]}),g&&!R&&s.jsx("span",{className:"text-xs text-text-success ml-1",children:"Saved."}),s.jsxs("span",{className:"ml-auto text-xs text-text-tertiary flex items-center gap-1.5",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500"})," differs from default"]})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-4 py-3 border-b border-outline-subtle",children:[s.jsx("h2",{className:"text-sm font-semibold text-text-primary",children:"Per-user overrides"}),s.jsx("p",{className:"mt-1 text-xs text-text-secondary",children:'Show or hide individual surfaces for one specific user, on top of their role above. "Inherit" follows the role matrix. This is the building block for giving a secondary user limited access.'})]}),s.jsxs("div",{className:"p-4 space-y-4",children:[s.jsxs("div",{className:"max-w-md",children:[s.jsx("label",{className:"block text-xs font-medium text-text-body mb-1",children:"User"}),s.jsxs("select",{value:w,onChange:G=>H(G.target.value),className:"w-full text-sm px-2 py-1.5 rounded-md border border-outline-subtle bg-surface-subtle focus:bg-surface focus:outline-none focus:border-outline-brand focus-visible:shadow-focus",children:[s.jsx("option",{value:"",children:"Select a userâ¦"}),b.map(G=>s.jsx("option",{value:G.id,children:(G.display_name||G.email)+` · ${G.role}`},G.id))]})]}),Z&&A&&s.jsx("div",{className:"flex justify-center py-4",children:s.jsx(_e,{className:"h-4 w-4 animate-spin text-text-tertiary"})}),Z&&!A&&s.jsxs(s.Fragment,{children:[z.map(({group:G,items:te})=>s.jsxs("div",{children:[s.jsx("div",{className:"text-xs font-medium text-text-secondary mb-1",children:X8[G]??G}),s.jsx("div",{className:"rounded-md border border-outline-faint divide-y divide-outline-faint",children:te.map(re=>{var ee;const L=k[re.key],q=L===void 0?"inherit":L?"show":"hide",me=(ee=l[re.key])==null?void 0:ee[Z.role];return s.jsxs("div",{className:"flex items-center gap-3 px-3 py-2",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-sm text-text-primary truncate",children:re.label}),s.jsxs("div",{className:"text-xs text-text-tertiary",children:["inherits: ",me?"shown":"hidden"]})]}),s.jsxs("select",{value:q,onChange:ne=>Y(re.key,ne.target.value),className:"text-xs px-2 py-1 rounded-md border border-outline-subtle bg-surface-subtle focus:bg-surface focus:outline-none focus:border-outline-brand focus-visible:shadow-focus",children:[s.jsx("option",{value:"inherit",children:"Inherit"}),s.jsx("option",{value:"show",children:"Show"}),s.jsx("option",{value:"hide",children:"Hide"})]})]},re.key)})})]},G)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs(W,{type:"button",onClick:M,disabled:!D||A,intent:"brand",variant:"solid",size:"md",children:[A?s.jsx(_e,{className:"h-4 w-4 animate-spin"}):s.jsx(ko,{className:"h-4 w-4"}),"Save user overrides"]}),s.jsx(W,{type:"button",onClick:()=>{j(N),S(!1)},disabled:!D||A,intent:"neutral",variant:"outline",size:"md",children:"Revert"}),T&&!D&&s.jsx("span",{className:"text-xs text-text-success ml-1",children:"Saved."})]})]})]})]})]})]})]})}const fnt=[{id:"reports",label:"Account reports",icon:il,tint:Ve[1].tint,text:Ve[1].text},{id:"sales",label:"Sales & revenue",icon:Xi,tint:Ve[2].tint,text:Ve[2].text},{id:"inventory",label:"Inventory & replen",icon:Si,tint:Ve[3].tint,text:Ve[3].text},{id:"returns",label:"Returns",icon:vd,tint:Ve[4].tint,text:Ve[4].text},{id:"listings",label:"Listings & catalogue",icon:Gv,tint:Ve[5].tint,text:Ve[5].text},{id:"pricing",label:"Pricing & fees",icon:ane,tint:Ve[6].tint,text:Ve[6].text},{id:"intel",label:"Market & competitive intel",icon:Pne,tint:Ve[1].tint,text:Ve[1].text},{id:"workflow",label:"AM workflow & signals",icon:xf,tint:Ve[2].tint,text:Ve[2].text},{id:"payouts",label:"Payouts & finance",icon:tx,tint:Ve[3].tint,text:Ve[3].text},{id:"admin",label:"Admin & lifecycle",icon:dp,tint:Ve[5].tint,text:Ve[5].text},{id:"eng",label:"Engineering & ops",icon:xF,tint:"bg-surface-sunken",text:"text-text-body"},{id:"uncategorized",label:"Other",icon:Qv,tint:"bg-surface-sunken",text:"text-text-secondary"}],mnt={"monthly-account-rollup":"reports","quarterly-account-rollup":"reports","weekly-payout-rollup":"reports","weekly-am-digest":"reports","qbr-builder":"reports","welcome-pack":"reports","am-handover-pack":"reports","market-intel-pack":"reports","portfolio-overview":"reports","my-week":"reports","sales-velocity":"sales","whats-selling":"sales","wishlist-demand":"intel","abc-classification":"sales","margin-audit":"sales","seasonality-map":"sales","demand-forecast":"sales","promo-effectiveness":"sales","price-elasticity":"sales","new-arrival-ramp":"sales","seller-comparison":"sales","stockout-risk":"inventory","overstock-flush":"inventory","replen-plan":"inventory","dc-allocation-plan":"inventory","inbou
941nd-receive-audit":"inventory","find-bundle-candidates":"inventory","returns-report":"returns","return-rate-spike":"returns","return-reason-deepdive":"returns","return-coaching":"returns","damaged-in-transit":"returns","review-vs-returns":"returns","fraud-return-flags":"returns","listing-quality-audit":"listings","listing-suppression-watch":"listings","pdp-variant-audit":"listings","variant-consolidation":"listings","attribute-completion":"listings","category-mismatch":"listings","title-rewrite":"listings","normalize-skus":"listings","image-gap":"listings","brainstorm-variants":"listings","new-product-ideas":"listings","taxonomy-mapper":"listings","product-buybox-lookup":"pricing","buybox-watch":"pricing","competitive-pricing":"pricing","pricing-strategy-advisor":"pricing","packaging-cost-audit":"pricing","fee-shock-detector":"pricing","competitor-scan":"intel","share-of-shelf":"intel","category-rank-snapshot":"intel","brand-share-snapshot":"intel","category-demand-pulse":"intel","keyword-rank-tracker":"intel","search-share-of-voice":"intel","whitespace-keywords":"intel","autocomplete-expansion":"intel","trending-watch":"intel","customer-language-miner":"intel","ppc-opportunity-finder":"intel","sponsored-ad-intel":"intel","ads-watchdog":"intel","ad-performance-report":"intel","review-themes":"intel","review-sentiment":"intel","at-risk-seller":"workflow","call-prep-brief":"workflow","action-list":"workflow","anomaly-scan":"workflow","api-health-check":"workflow","payout-explainer":"payouts","payout-statement-pdf":"payouts","vat-export":"payouts","balance-mismatch":"payouts","cash-flow-projection":"payouts","onboard-seller":"admin","offboard-seller":"admin","pause-seller":"admin","tier-upgrade":"admin","seller-user-invite":"admin","publish-welcome-pack-tasks":"admin","run-sync":"eng",migration:"eng","dataset-snapshot":"eng","audit-trail":"eng","debug-api-error":"eng","schema-tour":"eng","takealot-api":"eng","event-gateway":"eng"},pnt=[{id:"all",label:"All"},{id:"am",label:"AM"},{id:"seller",label:"Seller"},{id:"admin",label:"Admin only"},{id:"eng",label:"Engineering"}];function xnt(e,t){if(t==="all")return!0;const n=e.audience??[];return t==="seller"?n.includes("seller_user"):t==="am"?n.includes("am"):t==="eng"?e.voice==="engineer":n.includes("super_admin")&&!n.includes("am")&&!n.includes("seller_user")}function gnt({embedded:e=!1}={}){const[t,n]=p.useState(null),[r,a]=p.useState(null),[i,o]=p.useState(null),[l,c]=p.useState(null),[u,d]=p.useState(""),[h,f]=p.useState(()=>localStorage.getItem("skills:density")||"rows"),[m,x]=p.useState("all"),[g,y]=p.useState(()=>{try{const R=localStorage.getItem("skills:collapsed");return R?new Set(JSON.parse(R)):new Set}catch{return new Set}}),b=Rt(),v=Lt(),w=v.kind==="ready"?v.me.role:null,_=v.kind==="ready"&&v.me.role==="super_admin";p.useEffect(()=>{localStorage.setItem("skills:density",h)},[h]),p.useEffect(()=>{localStorage.setItem("skills:collapsed",JSON.stringify([...g]))},[g]);async function k(){try{n(await K.listSkills())}catch(R){c(String((R==null?void 0:R.message)||R))}try{o(await K.getSkillCronStatus())}catch{o(null)}try{a(await K.sellers())}catch{a([])}}p.useEffect(()=>{k()},[]);async function j(){const R=window.prompt("New skill slug (lowercase, hyphens, e.g. weekly-summary):");if(R)try{const I=await K.createSkill({name:R});b(`/skills/${I.name}`)}catch(I){c(String((I==null?void 0:I.message)||I))}}const N=p.useMemo(()=>{if(!t)return null;const R=u.trim().toLowerCase();return t.filter(I=>!(!xnt(I,m)||R&&!`${I.name} ${I.title||""} ${I.description||""}`.toLowerCase().includes(R)))},[t,u,m]),E=p.useMemo(()=>{if(!N)return null;const R=new Map;for(const I of N){const $=mnt[I.name]||"uncategorized",P=R.get($)??[];P.push(I),R.set($,P)}for(const I of R.values())I.sort(($,P)=>($.title||$.name).localeCompare(P.title||P.name));return fnt.filter(I=>R.has(I.id)).map(I=>({...I,skills:R.get(I.id)}))},[N]);function A(R){y(I=>{const $=new Set(I);return $.has(R)?$.delete(R):$.add(R),$})}const C=(t==null?void 0:t.length)??0,T=(N==null?void 0:N.length)??0,S=u.trim()!==""||m!=="all",O=_?s.jsxs("button",{onClick:j,className:"text-xs text-text-body hover:text-text-primary flex items-center gap-1 px-2 py-1 rounded-md border border-outline-subtle hover:bg-surface-subtle",children:[s.jsx(In,{className:"w-3 h-3"})," Add skill"]}):null;return s.jsxs(s.Fragment,{children:[!e&&s.jsx(Pt,{crumbs:[{label:"Skills"}],actions:O}),s.jsx("div",{className:e?"":"flex-1 overflow-y-auto bg-surface-subtle/30",children:s.jsxs("div",{className:e?"space-y-6":"w-full px-4 md:px-6 py-6 space-y-6",children:[e?O&&s.jsx("div",{className:"flex justify-end",children:O}):s.jsxs("div",{children:[s.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-text-primary",children:"Skills"}),s.jsx("p",{className:"mt-1 text-sm text-text-secondary max-w-2xl",children:"Skills provide additional guidance to the agent."})]}),i&&!i.enabled&&i.scheduled.length>0&&s.jsxs(V,{className:"p-4 text-sm text-text-warning bg-surface-warningSubtle border-outline-warning flex items-start gap-3",children:[s.jsx(zn,{className:"w-4 h-4 shrink-0 mt-0.5 text-text-warning"}),s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"font-medium",children:["Cron runner is OFF â ",i.scheduled.length," skill",i.scheduled.length===1?"":"s"," scheduled but nothing is firing."]}),s.jsx("ul",{className:"text-xs text-text-warning space-y-0.5",children:i.scheduled.map(R=>s.jsxs("li",{children:[s.jsx("code",{className:"font-mono",children:R.name}),s.jsxs("span",{className:"text-text-warning",children:[" · ",R.cron_schedule]})]},R.name))}),s.jsxs("div",{className:"text-xs text-text-warning pt-1",children:["Set ",s.jsx("code",{className:"font-mono",children:"SKILL_CRON_ENABLED=true"})," on the Render web service to enable."]})]})]}),l&&s.jsxs(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error flex items-start gap-2",children:[s.jsx(yt,{className:"w-4 h-4 shrink-0 mt-0.5"}),s.jsx("div",{children:l})]}),t&&t.length>0&&s.jsx(ynt,{query:u,onQuery:d,audienceTab:m,onAudienceTab:x,density:h,onDensity:f,totalCount:C,filteredCount:T,hasFilter:S}),t===null&&!l&&s.jsx("div",{className:"text-xs text-text-tertiary",children:"Loadingâ¦"}),(t==null?void 0:t.length)===0&&s.jsxs(V,{className:"p-8 text-center",children:[s.jsx(Qv,{className:"w-8 h-8 mx-auto text-text-tertiary mb-3"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"No skills yet."}),_&&s.jsx("button",{onClick:j,className:"mt-3 text-xs text-text-brand hover:text-text-brand",children:"Add your first skill"})]}),E&&E.length===0&&t&&t.length>0&&s.jsxs(V,{className:"p-8 text-center",children:[s.jsx(Fa,{className:"w-8 h-8 mx-auto text-text-tertiary mb-3"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"No skills match your filter."}),s.jsx("button",{onClick:()=>{d(""),x("all")},className:"mt-3 text-xs text-text-brand hover:text-text-brand",children:"Clear filters"})]}),E&&E.map(R=>s.jsx(bnt,{category:R,skills:R.skills,collapsed:g.has(R.id),onToggle:()=>A(R.id),density:h,sellers:r,role:w},R.id))]})})]})}
941function ynt({query:e,onQuery:t,audienceTab:n,onAudienceTab:r,density:a,onDensity:i,totalCount:o,filteredCount:l,hasFilter:c}){return s.jsx("div",{className:"sticky top-0 z-20 -mx-4 md:-mx-6 px-4 md:px-6 py-3 bg-surface-subtle/80 backdrop-blur border-b border-outline-subtle/70",children:s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(pc,{fieldClassName:"min-w-[240px] flex-1",type:"search",value:e,onChange:u=>t(u.target.value),placeholder:"Search skillsâ¦",inputSize:"sm",reserveEnd:!0,end:e?s.jsx("button",{type:"button",onClick:()=>t(""),className:"absolute right-2 top-1/2 z-[1] -translate-y-1/2 text-text-tertiary hover:text-text-secondary",title:"Clear search",children:s.jsx(Bn,{className:"w-3.5 h-3.5"})}):null}),s.jsx("div",{className:"flex items-center gap-1 rounded-md border border-outline-subtle bg-surface p-0.5",children:pnt.map(u=>s.jsx("button",{onClick:()=>r(u.id),className:`text-xs px-2 py-1 rounded ${n===u.id?"bg-surface-inverse text-text-inverse":"text-text-secondary hover:text-text-primary"}`,children:u.label},u.id))}),s.jsxs("div",{className:"flex items-center rounded-md border border-outline-subtle bg-surface p-0.5",children:[s.jsx("button",{onClick:()=>i("rows"),className:`p-1 rounded ${a==="rows"?"bg-surface-inverse text-text-inverse":"text-text-secondary hover:text-text-primary"}`,title:"Compact rows",children:s.jsx(Mre,{className:"w-3.5 h-3.5"})}),s.jsx("button",{onClick:()=>i("cards"),className:`p-1 rounded ${a==="cards"?"bg-surface-inverse text-text-inverse":"text-text-secondary hover:text-text-primary"}`,title:"Cards",children:s.jsx(gf,{className:"w-3.5 h-3.5"})})]}),s.jsx("div",{className:"text-xs text-text-secondary ml-auto",children:c?`${l} of ${o}`:`${o} skills`})]})})}function bnt({category:e,skills:t,collapsed:n,onToggle:r,density:a,sellers:i,role:o}){const l=e.icon;return s.jsxs("section",{children:[s.jsxs("button",{onClick:r,className:"w-full flex items-center gap-2.5 py-2 group",children:[s.jsx("span",{className:`w-7 h-7 rounded-md flex items-center justify-center ${e.tint}`,children:s.jsx(l,{className:`w-4 h-4 ${e.text}`})}),s.jsx("span",{className:"text-sm font-semibold text-text-primary",children:e.label}),s.jsx("span",{className:"text-xs text-text-tertiary font-medium",children:t.length}),s.jsx(Pn,{className:`w-4 h-4 text-text-tertiary ml-1 transition-transform ${n?"-rotate-90":""}`})]}),!n&&(a==="rows"?s.jsx("div",{className:"rounded-lg border border-outline-subtle bg-surface overflow-hidden divide-y divide-outline-faint",children:t.map(c=>s.jsx(vnt,{skill:c,sellers:i,role:o},c.name))}):s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:t.map(c=>s.jsx(wnt,{skill:c,sellers:i,role:o},c.name))}))]})}function vnt({skill:e,sellers:t,role:n}){return s.jsxs("div",{className:"flex items-start gap-3 px-3 py-2.5 hover:bg-surface-subtle transition group",children:[s.jsxs(st,{to:`/skills/${e.name}`,className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[s.jsx("span",{className:"font-medium text-text-primary text-sm truncate",children:e.title||e.name}),s.jsxs("code",{className:"font-mono text-body-xs px-1.5 py-0.5 rounded bg-surface-subtle border border-outline-subtle text-text-secondary shrink-0",children:["/",e.name]})]}),s.jsx("p",{className:"mt-0.5 text-xs text-text-secondary line-clamp-1",children:e.description||s.jsx("span",{className:"italic text-text-tertiary",children:"No description"})})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1 text-body-xs shrink-0 pt-0.5",children:[s.jsx(uY,{skill:e}),s.jsx(cY,{skill:e,sellers:t,role:n})]})]})}function wnt({skill:e,sellers:t,role:n}){return s.jsxs("div",{className:"group rounded-xl border border-outline-subtle bg-surface p-4 hover:border-outline hover:shadow-sm transition",children:[s.jsxs(st,{to:`/skills/${e.name}`,className:"block",children:[s.jsx("div",{className:"font-semibold text-text-primary text-sm",children:e.title||e.name}),s.jsx("p",{className:"mt-1 text-xs text-text-secondary line-clamp-2 min-h-[2.4em]",children:e.description||s.jsx("span",{className:"italic text-text-tertiary",children:"No description"})})]}),s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-1.5 text-body-xs",children:[s.jsxs("code",{className:"font-mono px-1.5 py-0.5 rounded bg-surface-subtle border border-outline-subtle text-text-body",children:["/",e.name]}),s.jsx(uY,{skill:e}),s.jsx("span",{className:"ml-auto",children:s.jsx(cY,{skill:e,sellers:t,role:n})})]})]})}const Q8="gadjet:agent:lastSellerSlug";function cY({skill:e,sellers:t,role:n}
941){const r=Rt(),[a,i]=p.useState(!1),[o,l]=p.useState(""),c=p.useRef(null);p.useEffect(()=>{if(!a)return;function w(k){var j;(j=c.current)!=null&&j.contains(k.target)||i(!1)}function _(k){k.key==="Escape"&&i(!1)}return document.addEventListener("mousedown",w),document.addEventListener("keydown",_),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",_)}},[a]);const u=n==="seller_user",d=!u,h=p.useMemo(()=>(t??[]).filter(w=>w.status!=="offboarded"),[t]),f=typeof window<"u"?localStorage.getItem(Q8):null,m=p.useMemo(()=>{const w=[...h];if(f){const _=w.findIndex(k=>k.slug===f);if(_>0){const[k]=w.splice(_,1);w.unshift(k)}}return w},[h,f]),x=p.useMemo(()=>{const w=o.trim().toLowerCase();return w?m.filter(_=>_.display_name.toLowerCase().includes(w)||_.slug.toLowerCase().includes(w)):m},[m,o]);if(e.enabled===!1)return null;async function g(w){i(!1);try{localStorage.setItem(Q8,w);const _=await K.createChat(w);sessionStorage.setItem(`gadjet:seed:${_.id}`,`/${e.name}`),r(`/sellers/${w}/chats/${_.id}`)}catch(_){console.error("Run skill failed",_)}}function y(){i(!1);const w=`/${e.name}`;r(`/agent/new?prompt=${encodeURIComponent(w)}`)}function b(w){if(w.preventDefault(),w.stopPropagation(),u&&h.length===1){g(h[0].slug);return}i(_=>!_)}const v=t===null;return s.jsxs("div",{ref:c,className:"relative",children:[s.jsxs("button",{onClick:b,title:`Run /${e.name}`,className:"text-body-xs px-2 py-0.5 rounded-md border border-outline-subtle text-text-body hover:bg-surface-inverse hover:text-text-inverse hover:border-intent-neutral transition flex items-center gap-1 font-medium",children:[s.jsx(bd,{className:"w-3 h-3"})," Run"]}),a&&s.jsxs("div",{className:"absolute right-0 top-full mt-1 z-30 w-72 rounded-md border border-outline-subtle bg-surface shadow-lg overflow-hidden",children:[s.jsx("div",{className:"px-3 py-2 border-b border-outline-faint",children:s.jsxs("div",{className:"text-body-xs font-medium text-text-secondary",children:["Run ",s.jsxs("code",{className:"font-mono text-text-body",children:["/",e.name]})," ","forâ¦"]})}),h.length>4&&s.jsx("div",{className:"p-2 border-b border-outline-faint",children:s.jsx(Re,{value:o,onChange:w=>l(w.target.value),placeholder:"Search sellersâ¦",inputSize:"sm",autoFocus:!0})}),s.jsxs("div",{className:"max-h-72 overflow-y-auto py-1",children:[d&&!o.trim()&&s.jsxs("button",{onClick:y,className:"w-full text-left px-3 py-1.5 text-sm hover:bg-surface-sunken flex items-center gap-2",children:[s.jsx(R2,{className:"w-3.5 h-3.5 text-text-tertiary shrink-0"}),s.jsx("span",{className:"text-text-body",children:"Workspace (no seller)"})]}),d&&!o.trim()&&x.length>0&&s.jsx("div",{className:"my-1 border-t border-outline-faint"}),v&&s.jsx("div",{className:"text-xs text-text-tertiary px-3 py-2",children:"Loading sellersâ¦"}),!v&&x.length===0&&s.jsx("div",{className:"text-xs text-text-tertiary px-3 py-2",children:"No sellers match."}),x.map(w=>s.jsxs("button",{onClick:()=>g(w.slug),className:"w-full text-left px-3 py-1.5 text-sm hover:bg-surface-sunken flex items-center justify-between gap-2",children:[s.jsx("span",{className:"truncate text-text-body",children:w.display_name}),f===w.slug&&s.jsx("span",{className:"text-body-xs text-text-tertiary shrink-0",children:"last"})]},w.slug))]})]})]})}function uY({skill:e}){return s.jsxs(s.Fragment,{children:[e.enabled===!1&&s.jsx(_n,{tone:"neutral",title:"This skill is disabled and won't appear in pickers.",children:"disabled"}),e.side_effects==="external_writes"&&s.jsx(_n,{tone:"error",title:"Writes to Takealot or other external systems. Super admin only.",children:"ext writes"}),e.side_effects==="internal_writes"&&s.jsx(_n,{tone:"warning",title:"Writes to the local registry.",children:"writes"}),e.cost==="expensive"&&s.jsx(_n,{tone:"brand",title:"Pulls a lot of data or runs many sub-skills.",children:"$$$"}),e.cron_schedule&&s.jsx(_n,{tone:"info",title:`Runs on schedule: ${e.cron_schedule}`,children:"cron"})]})}const _nt=[{key:"label",label:"Door",sticky:!0,sortable:!1},{key:"live",label:"Live",sortable:!1},{key:"shipsHow",label:"Ships how",sortable:!1},{key:"onlyThisDoor",label:"Only this door",sortable:!1},{key:"next",label:"Next one thing",sortable:!1},{key:"blockedOn",label:"Blocked on",sortable:!1}],knt=[{key:"label",label:"Door",sticky:!0,sortable:!1},{key:"lag",label:"Lag",sortable:!1},{key:"health",label:"Health",sortable:!1},{key:"compat",label:"Compat floor",sortable:!1},{key:"storeLast",label:"Store last",sortable:!1},{key:"wau",label:"WAU / primary",sortable:!1}];function jnt({embedded:e=!1}={}){const t=Lt(),n=Rt(),[r,a]=p.useState(null),[i,o]=p.useState(!0),[l,c]=p.useState(null);p.useEffect(()=>{e||t.kind==="ready"&&t.me.role!=="super_admin"&&n("/",{replace:!0})},[t,n,e]);const u=p.useCallback(async()=>{o(!0),c(null);try{const d=await oe("/api/admin/surfaces");if(!d.ok){const h=await d.json().catch(()=>({}));throw new Error((h==null?void 0:h.message)||(h==null?void 0:h.error)||`HTTP ${d.status}`)}a(await d.json())}catch(d){const h=d;c((h==null?void 0:h.message)||"Failed to load surfaces.")}finally{o(!1)}},[]);return p.useEffect(()=>{u()},[u]),!e&&t.kind==="ready"&&t.me.role!=="super_admin"?null:s.jsxs(s.Fragment,{children:[!e&&s.jsx(Pt,{crumbs:[{label:"Surfaces"}],actions:s.jsxs(W,{type:"button",onClick:u,intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(vi,{className:"h-3.5 w-3.5"})," Refresh"]})}),s.jsxs("div",{className:e?"space-y-6":"flex-1 overflow-auto p-4 md:p-6 space-y-6",children:[e&&s.jsx("div",{className:"flex justify-end",children:s.jsxs(W,{type:"button",onClick:u,intent:"neutral",variant:"outline",size:"sm",children:[s.jsx(vi,{className:"h-3.5 w-3.5"})," Refresh"]})}),l&&s.jsxs("div",{className:"bg-surface-errorSubtle border border-outline-error px-4 py-2 rounded-md text-sm text-text-error flex items-center gap-2",children:[s.jsx(yt,{className:"h-4 w-4 shrink-0"}),s.jsx("span",{className:"flex-1 min-w-0 truncate",children:l})]}),i&&!r?s.jsx("div",{className:"flex items-center justify-center py-12 text-text-tertiary",children:s.jsx(_e,{className:"h-5 w-5 animate-spin"})}):r&&s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"text-sm text-text-secondary",children:["One product, three doors. Capability ships on merge; package versions need a store. ",s.jsx("span",{className:"text-text-tertiary",children:"? means we cannot see it yet."})]}),s.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:r.north_star.map(d=>s.jsxs(V,{className:"p-4",children:[s.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-text-tertiary",children:d.label}),s.jsx("p",{className:"mt-1.5 text-sm text-text-secondary",children:d.line})]},d.id))}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-4 py-3 border-b border-outline-subtle",children:[s.jsx("h2",{className:"text-sm font-medium text-text-primary",children:"Decision"}),s.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:"Live, how
941it ships, door-only work, next one thing, blocked on"})]}),s.jsx(dt,{rows:r.doors,columns:_nt,getRowKey:d=>d.id,paginate:!1,persist:!1,density:"comfortable"})]}),s.jsxs(V,{className:"overflow-hidden",children:[s.jsxs("div",{className:"px-4 py-3 border-b border-outline-subtle",children:[s.jsx("h2",{className:"text-sm font-medium text-text-primary",children:"Ops"}),s.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:"Fill Lag and Compat first once a door has installs"})]}),s.jsx(dt,{rows:r.doors,columns:knt,getRowKey:d=>d.id,paginate:!1,persist:!1,density:"comfortable"})]}),s.jsxs(V,{className:"p-4 space-y-3",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-sm font-medium text-text-primary",children:"Shared API / auth"}),s.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:"All three doors stand on this. Never copy onto every door."})]}),s.jsxs("dl",{className:"grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-3 text-sm",children:[s.jsx(Wu,{label:"Live SHA",value:r.shared.liveSha}),s.jsx(Wu,{label:"Breaking change in flight?",value:r.shared.breaking}),s.jsx(Wu,{label:"Force-upgrade / kill-switch",value:r.shared.forceUpgrade}),s.jsx(Wu,{label:"Floors this would strand",value:r.shared.floors}),s.jsx(Wu,{label:"Auth",value:r.shared.auth}),s.jsx(Wu,{label:"Door-only APIs",value:r.shared.doorApis}),s.jsx(Wu,{label:"Last migration",value:r.shared.lastMigration,className:"md:col-span-2"})]}),s.jsxs("p",{className:"text-xs text-text-tertiary",children:["Generated ",new Date(r.generated_at).toLocaleString()]})]})]})]})]})}function Wu({label:e,value:t,className:n}){return s.jsxs("div",{className:n,children:[s.jsx("dt",{className:"text-xs font-medium uppercase tracking-wide text-text-tertiary",children:e}),s.jsx("dd",{className:"mt-0.5 text-text-secondary",children:t})]})}const dY=[{key:"dashboard",label:"Dashboard",icon:s.jsx(Kh,{className:"w-4 h-4"})},{key:"surfaces",label:"Surfaces",icon:s.jsx(j2,{className:"w-4 h-4"})},{key:"scheduled",label:"Scheduled tasks",icon:s.jsx(pu,{className:"w-4 h-4"})},{key:"users",label:"Users",icon:s.jsx(Xp,{className:"w-4 h-4"})},{key:"ai-spend",label:"AI Spend",icon:s.jsx(eF,{className:"w-4 h-4"})},{key:"lockout",label:"Lockout",icon:s.jsx(Bl,{className:"w-4 h-4"})},{key:"nav",label:"Navigation",icon:s.jsx(tre,{className:"w-4 h-4"})},{key:"skills",label:"Skills",icon:s.jsx(Qv,{className:"w-4 h-4"})}];function Nnt(e){var t;return((t=dY.find(n=>n.key===e))==null?void 0:t.label)??"Admin"}function Snt(e){return e==="surfaces"?"Versions and open work across web, extension, and mobile.":"Cross-tenant administration for the Gadjet team."}function Cnt({tool:e}){switch(e){case"surfaces":return s.jsx(jnt,{embedded:!0});case"scheduled":return s.jsx(Eq,{embedded:!0});case"users":return s.jsx(nnt,{embedded:!0});case"ai-spend":return s.jsx(unt,{embedded:!0});case"lockout":return s.jsx(dnt,{embedded:!0});case"nav":return s.jsx(hnt,{embedded:!0});case"skills":return s.jsx(gnt,{embedded:!0});case"dashboard":default:return s.jsx(snt,{embedded:!0})}}function Ent(){const e=Lt(),t=Ba(),n=Rt(),[r,a]=p.useState(null),[i,o]=p.useState(null);p.useEffect(()=>{K.account().then(a).catch(C=>o(String((C==null?void 0:C.message)||C)))},[]);const c=t.pathname.replace(/^\/settings\/?/,"").split("/").filter(Boolean),u=c[0]??"",d=e.kind==="ready"?e.me.role:null,h=e.kind==="ready"?e.me.id:"",f=d==="super_admin",m=d==="super_admin"||d==="am",x=(r==null?void 0:r.kind)==="customer",g=e.kind==="ready"&&Kc(e.me.nav_visibility,"earn"),y=u==="stores"?c[1]??null:null,[b,v]=p.useState(null),[w,_]=p.useState(null);p.useEffect(()=>{if(!y){v(null);return}v(null),_(null),K.seller(y).then(v).catch(C=>_(String((C==null?void 0:C.message)||C)))},[y]),p.useEffect(()=>{if(u!==""||e.kind!=="ready"||r===null&&!i)return;const C=(r==null?void 0:r.kind)==="customer"?"/settings/workspace":f?"/settings/admin/dashboard":"/settings/profile";n(C,{replace:!0})},[u,e.kind,r,i,f,n]);const k=[{key:"profile",label:"Profile",icon:s.jsx(f6,{className:"w-4 h-4"}),to:"/settings/profile",end:!0},{key:"notifications",label:"Notifications",icon:s.jsx(Z6,{className:"w-4 h-4"}),to:"/settings/notifications"}];x&&(k.push({key:"ws-general",label:"General",icon:s.jsx(dp,{className:"w-4 h-4"}),to:"/settings/workspace",end:!0}
941,{key:"ws-members",label:"Members",icon:s.jsx(Xp,{className:"w-4 h-4"}),to:"/settings/workspace/members"}),wr()||k.push({key:"ws-billing",label:"Billing",icon:s.jsx(tx,{className:"w-4 h-4"}),to:"/settings/workspace/billing"}),g&&k.push({key:"ws-payouts",label:"Payouts",icon:s.jsx(P2,{className:"w-4 h-4"}),to:"/settings/workspace/payouts"})),f&&k.push(...dY.map(C=>({key:`admin-${C.key}`,label:C.label,icon:C.icon,to:`/settings/admin/${C.key}`}))),y&&(m&&k.push({key:"store-managed",label:"Managed Account",icon:s.jsx(xf,{className:"w-4 h-4"}),to:`/settings/stores/${y}/managed`}),k.push({key:"store-general",label:"Store",icon:s.jsx(dp,{className:"w-4 h-4"}),to:`/settings/stores/${y}`,end:!0},{key:"store-integrations",label:"Integrations",icon:s.jsx(hF,{className:"w-4 h-4"}),to:`/settings/stores/${y}/integrations`},{key:"store-billing",label:"Invoicing",icon:s.jsx(Are,{className:"w-4 h-4"}),to:`/settings/stores/${y}/billing`},{key:"store-danger",label:"Danger zone",icon:s.jsx(zn,{className:"w-4 h-4"}),to:`/settings/stores/${y}/danger`}));let j="Settings",N,E=[{label:"Settings"}],A=s.jsx(_y,{});if(u==="profile")j="Profile",N="Manage your personal account and sign-in.",E=[{label:"Settings"},{label:"Profile"}],A=s.jsx(att,{});else if(u==="notifications")j="Notifications",N="Choose which email you receive from Gadjet.",E=[{label:"Settings"},{label:"Notifications"}],A=s.jsx(dtt,{});else if(u==="workspace"){E=[{label:"Settings"},{label:"Workspace"}];const C=c[1]??"general";!r&&!i?(j="Workspace",A=s.jsx(_y,{})):(r==null?void 0:r.kind)!=="customer"?(j="Workspace",A=s.jsx(Ant,{account:r})):C==="members"?(j="Members",N="Invite teammates and manage their access.",E.push({label:"Members"}),A=s.jsx(Att,{myUserId:h,myRole:r.my_role})):C==="billing"?(j="Billing",E.push({label:"Billing"}),wr()?(N="Billing is not available in the iPhone app.",A=s.jsx("p",{className:"text-sm text-text-secondary",children:Hc})):(N="Credits, plan, top-ups and invoices.",A=s.jsx(Ltt,{account:r}))):C==="payouts"&&g?(j="Payouts",N="Bank details for affiliate cash withdrawals.",E.push({label:"Payouts"}),A=s.jsx(utt,{})):(j="General",N="Your workspace name and details.",E.push({label:"General"}),A=s.jsx(Ctt,{account:r,onUpdate:a}))}else if(u==="stores"){const C=c[2]??"general",T=(b==null?void 0:b.display_name)??y??"Store";j=T,E=[{label:"Settings"},{label:"Stores"},{label:T}],y?w?A=s.jsx(Xj,{msg:w}):b?(N={general:"Configuration and lifecycle.",integrations:"Connected marketplaces and keys.",billing:"Business, VAT and banking details printed on your claim invoices.",managed:"Account facts, contacts, billing, and portal credentials â AM only.",credentials:"Portal logins the AM team operates on the seller's behalf.",danger:"Sensitive lifecycle actions â convert off managed, pause, offboard."}[C],A=s.jsx(SWe,{seller:b,tab:C,onSellerChange:v,isAdminRole:m,isSuperAdmin:f})):A=s.jsx(_y,{}):A=s.jsx(Xj,{msg:"No store selected."})}else if(u==="admin")if(E=[{label:"Settings"},{label:"Admin"}],e.kind!=="ready")j="Admin",A=s.jsx(_y,{});else if(!f)j="Admin",A=s.jsx(Xj,{msg:"Admin tools are restricted to the Gadjet super-admin team."});else{const C=c[1]??"dashboard";j=Nnt(C),N=Snt(C),E.push({label:j}),A=s.jsx(Cnt,{tool:C})}return s.jsx(Jze,{crumbs:E,items:k,title:j,subtitle:N,children:A})}function _y(){return s.jsx("div",{className:"text-xs text-text-tertiary",children:"Loadingâ¦"})}function Xj({msg:e}){return s.jsx(V,{className:"p-4 text-sm text-text-error bg-surface-errorSubtle border-outline-error",children:e})}function Ant({account:e}){return(e==null?void 0:e.kind)==="internal"?s.jsxs(V,{className:"p-6",children:[s.jsx("h2",{className:"text-base font-semibold text-text-primary",children:"You're on the Gadjet team"}),s.jsxs("p",{className:"mt-2 text-sm text-text-secondary",children:["Workspace settings (billing, members) live per-customer. As a"," ",e.role,", you act on customer accounts but don't have a workspace of your own here."]})]}):s.jsx(V,{className:"p-6 text-sm text-text-secondary",children:"Your workspace hasn't been set up yet. If you just signed up, hop back to the chat and follow the prompts to subscribe."})}function dT({className:e}){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 18 18",xmlns:"http://www.w3.org/2000/svg",className:e,children:[s.jsx("path",{fill:"#4285F4",d:"M17.64 9.205c0-.639-.057-1.252-.164-1.841H9v3.481h4.844a4.14 4.14 0 0 1-1.796 2.717v2.258h2.908c1.702-1.567 2.684-3.875 2.684-6.615z"}),s.jsx("path",{fill:"#34A853",d:"M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.836.86-3.048.86-2.344 0-4.328-1.583-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18z"}),s.jsx("path",{fill:"#FBBC05",d:"M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.997 8.997 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332z"}),s.jsx("path",{fill:"#EA4335",d:"M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 7.29C4.672 5.163 6.656 3.58 9 3.58z"})]})}function Tnt(){const e=Rt(),[t,n]=p.useState(""),[r,a]=p.useState(""),[i,o]=p.useState(null),[l,c]=p.useState(null);async function u(h){h.preventDefault(),c(null),o("email");try{await sC(t.trim(),r),e("/",{replace:!0})}catch(f){c(Ont(f)),o(null)}}async function d(){c(null),o("google");try{await l0()}catch(h){c((h==null?void 0:h.message)||"Sign-in failed."),o(null)}}return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface-subtle p-6",children:s.jsxs("div",{className:"w-full max-w-sm bg-surface rounded-2xl shadow-sm border border-outline-subtle p-8",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-brandSubtle text-text-brand flex items-center justify-center",children:s.jsx(Ht,{className:"w-4 h-4"})}),s.jsx("span",{className:"font-semibold text-text-primary",children:"Gadjet AI"})]}),s.jsx("h1",{className:"text-xl font-semibold text-text-primary mb-1",children:"Sign in"}),s.jsx("p",{className:"text-sm text-text-secondary mb-6",children:"Welcome back. Use your account to continue."}),s.jsxs("form",{onSubmit:u,className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-body block mb-1",children:"Email"}),s.jsx(Re,{type:"email",required:!0,autoComplete:"email",value:t,onChange:h=>n(h.target.value),disabled:i!==null})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between items-center mb-1",children:[s.jsx("label",{className:"text-xs font-medium text-text-body",children:"Password"}),s.jsx(st,{to:"/forgot-password",className:"text-xs text-text-brand hover:underline",children:"Forgot?"})]}),s.jsx(Re,{type:"password",required:!0,autoComplete:"current-password",value:r,onChange:h=>a(h.target.value),disabled:i!==null})]}),s.jsxs(W,{type:"submit",disabled:i!==null,size:"lg",className:"w-full",children:[i==="email"&&s.jsx(_e,{className:"w-4 h-4 animate-spin"}),i==="email"?"Signing inâ¦":"Sign in"]})]}),s.jsxs("div",{className:"my-5 flex items-center gap-3 text-body-xs text-text-tertiary",children:[s.jsx("div",{className:"flex-1 h-px bg-surface-sunken"}),s.jsx("span",{children:"or"}),s.jsx("div",{className:"flex-1 h-px bg-surface-sunken"})]}),s.jsxs(W,{onClick:d,disabled:i!==null,intent:"neutral",variant:"outline",size:"lg",className:"w-full",children:[i==="google"?s.jsx(_e,{className:"w-4 h-4 animate-spin text-text-secondary"}):s.jsx(dT,{}),s.jsx("span",{className:"font-medium",children:i==="google"?"Redirectingâ¦":"Continue with Google"})]}),l&&s.jsx("p",{className:"mt-4 text-xs text-text-error bg-surface-errorSubtle border border-outline-error roun
941ded p-2",children:l}),!wr()&&s.jsxs("p",{className:"mt-6 text-xs text-text-secondary text-center",children:["New here?"," ",s.jsx(st,{to:"/signup",className:"text-text-brand font-medium hover:underline",children:"Create an account"})]})]})})}function Ont(e){const t=(e==null?void 0:e.message)||String(e);return/email not confirmed/i.test(t)?"Please confirm your email first â check your inbox for the link we sent.":/invalid login credentials/i.test(t)?"Email or password is incorrect.":t}function Int(){const e=p.useRef(null),t=p.useRef(null),n=p.useRef(null),r=p.useRef(!1),[a,i]=p.useState("idle"),[o,l]=p.useState(null);function c(){var h,f;(h=n.current)==null||h.call(n),n.current=null,(f=t.current)==null||f.getTracks().forEach(m=>m.stop()),t.current=null,e.current&&(e.current.srcObject=null)}async function u(h){if(r.current)return;const f=WZe(h);if(f){r.current=!0,c(),i("claiming");try{const m=await KZe(f);await HZe(m),i("done"),window.setTimeout(()=>{window.location.href="/"},600)}catch(m){const x=m;l((x==null?void 0:x.code)==="invalid_or_expired"||(x==null?void 0:x.status)===401?"That code has expired. Generate a fresh one on the web app and scan again.":`Couldn't link this device â ${(x==null?void 0:x.message)||x}`),i("error"),r.current=!1}}}async function d(){l(null),i("scanning");try{const h=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:"environment"}},audio:!1});t.current=h,e.current&&(e.current.srcObject=h,await e.current.play());const f=window.BarcodeDetector;if(f)try{const y=new f({formats:["qr_code"]});let b=!1;n.current=()=>{b=!0};const v=async()=>{if(!b){try{const w=await y.detect(e.current);w&&w.length>0&&u(w[0].rawValue)}catch{}window.setTimeout(v,120)}};v();return}catch{}const{BrowserMultiFormatReader:m}=await Yl(async()=>{const{BrowserMultiFormatReader:y}=await import("./index-C5PPNdDI.js");return{BrowserMultiFormatReader:y}},__vite__mapDeps([7,1,2])),g=await new m().decodeFromStream(h,e.current,y=>{y&&u(y.getText())});n.current=()=>g.stop()}catch(h){const f=h;l((f==null?void 0:f.message)||"Couldn't access the camera. Check the browser's permissions."),i("error"),c()}}return p.useEffect(()=>()=>c(),[]),s.jsx("div",{className:"min-h-screen bg-surface-subtle flex flex-col items-center justify-center p-6",children:s.jsxs("div",{className:"w-full max-w-sm space-y-4",children:[s.jsxs("div",{className:"text-center space-y-1",children:[s.jsx("div",{className:"w-10 h-10 rounded-lg bg-intent-brand text-text-inverse flex items-center justify-center mx-auto",children:s.jsx(mF,{className:"w-5 h-5"})}),s.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:"Link this device"}),s.jsx("p",{className:"text-sm text-text-secondary",children:"Scan the QR code from Gadjet on the web (Settings â Profile â Mobile app) to sign in here."})]}),s.jsxs("div",{className:"relative aspect-square rounded-xl overflow-hidden bg-black flex items-center justify-center",children:[s.jsx("video",{ref:e,playsInline:!0,muted:!0,className:a==="scanning"?"w-full h-full object-cover":"hidden"}),a!=="scanning"&&s.jsxs("div",{className:"text-center p-6 text-text-inverse/80 text-sm space-y-2",children:[a==="claiming"&&s.jsxs(s.Fragment,{children:[s.jsx(_e,{className:"w-8 h-8 mx-auto animate-spin"}),s.jsx("div",{children:"Linkingâ¦"})]}),a==="done"&&s.jsxs(s.Fragment,{children:[s.jsx(Xt,{className:"w-8 h-8 mx-auto text-text-success"}),s.jsx("div",{children:"Linked! Opening Gadjetâ¦"})]}),(a==="idle"||a==="error")&&s.jsxs(s.Fragment,{children:[s.jsx(up,{className:"w-8 h-8 mx-auto opacity-60"}),s.jsx("div",{children:"Camera off"})]})]})]}),o&&s.jsx("div",{className:"text-sm text-text-error text-center",children:o}),a!=="claiming"&&a!=="done"&&s.jsxs(W,{onClick:d,intent:"brand",variant:"solid",className:"w-full",children:[s.jsx(up,{className:"w-4 h-4"}),a==="scanning"?"Scanningâ¦":a==="error"?"Try again":"Start camera"]}),s.jsx("div",{className:"text-center",children:s.jsx("a",{href:"/signin",className:"text-xs text-text-secondary underline",children:"Sign in with a password instead"})})]})})}function e6(){return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface-subtle p-6",children:s.jsxs("div",{className:"w-full max-w-sm bg-surface rounded-2xl shadow-sm border border-outline-subtle p-8 text-center space-y-3",children:[s.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-brandSubtle text-text-brand flex items-center justify-center mx-auto",children:s.jsx(Ht,{className:"w-4 h-4"})}),s.jsx("h1",{className:"text-xl font-semibold text-text-primary",children:"Finish setup on the web"}),s.jsx("p",{className:"text-sm text-text-secondary",children:Hc})]})})}function Vm(){const e=xu();return e.kind==="loading"?s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface-subtle",children:s.jsx(_e,{className:"w-5 h-5 text-text-tertiary animate-spin"})}):e.kind==="anonymous"?s.jsx(Pnt,{}):s.jsx(Rnt,{})}function Pnt(){const e=Rt(),[t,n]=p.useState(""),[r,a]=p.useState(""),[i,o]=p.useState(""),[l,c]=p.useState(null),[u,d]=p.useState(null);async function h(m){if(m.preventDefault(),d(null),r.length<8){d("Password must be at least 8 characters.");return}if(r!==i){d("Passwords don't match.");return}c("email");try{await aC(t.trim(),r),aZ(),e("/",{replace:!0})}catch(x){d(Dnt(x)),c(null)}}async function f(){d(null),c("google");try{iZ(),await l0()}catch(m){oZ(),d((m==null?void 0:m.message)||"Sign-up failed."),c(null)}}return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface-subtle p-6",children:s.jsxs("div",{className:"w-full max-w-sm bg-surface rounded-2xl shadow-sm border border-outline-subtle p-8",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-brandSubtle text-text-brand flex items-center justify-center",children:s.jsx(Ht,{className:"w-4 h-4"})}),s.jsx("span",{className:"font-semibold text-text-primary",children:"Gadjet AI"})]}),s.jsx("h1",{className:"text-xl font-semibold text-text-primary mb-1",children:"Create your account"}),s.jsx("p",{className:"text-sm text-text-secondary mb-6",children:"Sign up to connect your Takealot store and start using Gadjet AI."}),s.jsxs("form",{onSubmit:h,className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-body block mb-1",children:"Email"}),s.jsx(Re,{type:"email",required:!0,autoComplete:"email",value:t,onChange:m=>n(m.target.value),disabled:l!==null})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-body block mb-1",children:"Password"}),s.jsx(Re,{type:"password",required:!0,minLength:8,autoComplete:"new-password",value:r,onChange:m=>a(m.target.value),disabled:l!==null}),s.jsx("p",{className:"text-body-xs text-text-tertiary mt-1",children:"At least 8 characters."})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-body block mb-1",children:"Confirm password"}),s.jsx(Re,{type:"password",required:!0,minLength:8,autoComplete:"new-password",value:i,onChange:m=>o(m.target.value),disabled:l!==null})]}),s.jsxs(W,{type:"submit",disabled:l!==null,size:"lg",className:"w-full",children:[l==="email"&&s.jsx(_e,{className:"w-4 h-4 animate-spin"}),l==="email"?"Creating accountâ¦":"Create account"]})]}),s.jsxs("div",{className:"my-5 flex items-center gap-3 text-body-xs text-text-tertiary",children:[s.jsx("div",{className:"flex-1 h-px bg-surface-sunken"}),s.jsx("span",{children:"or"}),s.jsx("div",{className:"flex-1 h-px bg-surface-sunken"})]}),s.jsxs(W,{onClick:f,disabled:l!==null,intent:"neutral",variant:"outline",size:"lg",className:"w-full",children:[l==="google"?s.jsx(_e,{className:"w-4 h-4 animate-spin text-text-secondary"}):s.jsx(dT,{}),s.jsx("span",{className:"font-medium",children:l==="google"?"Redirectingâ¦":"Sign up with Google"})]}),u&&s.jsx("p",{className:"mt-4 text-xs text-text-error bg-surface-errorSubtle border border-outline-error roun
941ded p-2",children:u}),s.jsxs("p",{className:"mt-6 text-xs text-text-secondary text-center",children:["Already have an account?"," ",s.jsx(st,{to:"/signin",className:"text-text-brand font-medium hover:underline",children:"Sign in"})]})]})})}function Rnt(){const e=xu(),t=Rt(),{openConnectStore:n}=d0(),r=e.kind==="authenticated"?e.user.email:null,[a,i]=p.useState(!1);p.useEffect(()=>{e.kind==="authenticated"&&sZ(e.user.id)},[e]);async function o(){i(!0);try{await wf(),t("/signin",{replace:!0})}catch{i(!1)}}return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface-subtle p-6",children:s.jsxs("div",{className:"w-full max-w-md bg-surface rounded-2xl shadow-sm border border-outline-subtle p-8",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-brandSubtle text-text-brand flex items-center justify-center",children:s.jsx(Ht,{className:"w-4 h-4"})}),s.jsx("span",{className:"font-semibold text-text-primary",children:"Gadjet AI"})]}),s.jsx("h1",{className:"text-xl font-semibold text-text-primary mb-2",children:"Welcome aboard"}),s.jsxs("p",{className:"text-sm text-text-secondary mb-1",children:["Signed in as ",s.jsx("span",{className:"font-medium text-text-primary",children:r??"â"}),"."]}),s.jsxs("p",{className:"text-sm text-text-secondary mb-6",children:["The next step is to connect your Takealot store and start your"," ",s.jsxs("span",{className:"font-medium",children:["R",zc(fi.starter.priceZar),"/mo"]})," plan."]}),s.jsx(W,{onClick:()=>n(),className:"w-full",children:"Connect your store"}),s.jsxs("p",{className:"mt-3 text-center text-xs text-text-tertiary",children:["Trouble connecting? Email"," ",s.jsx("a",{href:"mailto:[email protected]",className:"underline",children:"[email protected]"})]}),s.jsx("button",{onClick:o,disabled:a,className:"mt-6 w-full text-xs text-text-secondary hover:text-text-brand hover:underline disabled:opacity-50",children:a?"Signing outâ¦":"Sign out and use a different account"})]})})}function Dnt(e){const t=(e==null?void 0:e.message)||String(e);return/already registered|already exists/i.test(t)?"An account with this email already exists. Try signing in instead.":/invalid email/i.test(t)?"That email doesn't look right.":/weak password|password should be/i.test(t)?"Password is too weak â try at least 8 characters with a mix.":/rate limit|too many/i.test(t)?"Too many sign-up attempts. Wait a minute and try again, or use Google sign-up.":t}function Mnt(){const[e,t]=p.useState(""),[n,r]=p.useState(!1),[a,i]=p.useState(!1),[o,l]=p.useState(null);async function c(u){u.preventDefault(),l(null),r(!0);try{await iC(e.trim()),i(!0)}catch(d){l((d==null?void 0:d.message)||"Something went wrong. Try again.")}finally{r(!1)}}return a?s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface-subtle p-6",children:s.jsxs("div",{className:"w-full max-w-sm bg-surface rounded-2xl shadow-sm border border-outline-subtle p-8 text-center",children:[s.jsx(Xt,{className:"w-10 h-10 text-intent-success mx-auto mb-3"}),s.jsx("h1",{className:"text-xl font-semibold text-text-primary mb-1",children:"Reset link sent"}),s.jsxs("p",{className:"text-sm text-text-secondary mb-4",children:["If an account exists for ",s.jsx("span",{className:"font-medium",children:e}),", you'll get a reset link shortly. Check your inbox (and spam)."]}),s.jsx(st,{to:"/signin",className:"text-xs text-text-brand hover:underline",children:"Back to sign-in"})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface-subtle p-6",children:s.jsxs("div",{className:"w-full max-w-sm bg-surface rounded-2xl shadow-sm border border-outline-subtle p-8",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-brandSubtle text-text-brand flex items-center justify-center",children:s.jsx(Ht,{className:"w-4 h-4"})}),s.jsx("span",{className:"font-semibold text-text-primary",children:"Gadjet AI"})]}),s.jsx("h1",{className:"text-xl font-semibold text-text-primary mb-1",children:"Reset your password"}),s.jsx("p",{className:"text-sm text-text-secondary mb-6",children:"Enter the email on your account. We'll send a link to set a new password."}),s.jsxs("form",{onSubmit:c,className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-body block mb-1",children:"Email"}),s.jsx(Re,{type:"email",required:!0,autoComplete:"email",value:e,onCh
941ange:u=>t(u.target.value),disabled:n})]}),s.jsxs(W,{type:"submit",disabled:n,size:"lg",className:"w-full",children:[n&&s.jsx(_e,{className:"w-4 h-4 animate-spin"}),n?"Sendingâ¦":"Send reset link"]})]}),o&&s.jsx("p",{className:"mt-4 text-xs text-text-error bg-surface-errorSubtle border border-outline-error rounded p-2",children:o}),s.jsx("p",{className:"mt-6 text-xs text-text-secondary text-center",children:s.jsx(st,{to:"/signin",className:"text-text-brand font-medium hover:underline",children:"Back to sign-in"})})]})})}function Vy(){const e=Rt(),[t,n]=p.useState(""),[r,a]=p.useState(""),[i,o]=p.useState(!1),[l,c]=p.useState(!1),[u,d]=p.useState(null);async function h(f){if(f.preventDefault(),d(null),t.length<8){d("Password must be at least 8 characters.");return}if(t!==r){d("Passwords don't match.");return}o(!0);try{await YF(t),c(!0),setTimeout(()=>e("/",{replace:!0}),1500)}catch(m){d((m==null?void 0:m.message)||"Couldn't update password."),o(!1)}}return l?s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface-subtle p-6",children:s.jsxs("div",{className:"w-full max-w-sm bg-surface rounded-2xl shadow-sm border border-outline-subtle p-8 text-center",children:[s.jsx(Xt,{className:"w-10 h-10 text-intent-success mx-auto mb-3"}),s.jsx("h1",{className:"text-xl font-semibold text-text-primary mb-1",children:"Password updated"}),s.jsx("p",{className:"text-sm text-text-secondary",children:"Signing you inâ¦"})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface-subtle p-6",children:s.jsxs("div",{className:"w-full max-w-sm bg-surface rounded-2xl shadow-sm border border-outline-subtle p-8",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-brandSubtle text-text-brand flex items-center justify-center",children:s.jsx(Ht,{className:"w-4 h-4"})}),s.jsx("span",{className:"font-semibold text-text-primary",children:"Gadjet AI"})]}),s.jsx("h1",{className:"text-xl font-semibold text-text-primary mb-1",children:"Set a new password"}),s.jsx("p",{className:"text-sm text-text-secondary mb-6",children:"Choose something memorable."}),s.jsxs("form",{onSubmit:h,className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-body block mb-1",children:"New password"}),s.jsx(Re,{type:"password",required:!0,minLength:8,autoComplete:"new-password",value:t,onChange:f=>n(f.target.value),disabled:i}),s.jsx("p",{className:"text-body-xs text-text-tertiary mt-1",children:"At least 8 characters."})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-body block mb-1",children:"Confirm password"}),s.jsx(Re,{type:"password",required:!0,minLength:8,autoComplete:"new-password",value:r,onChange:f=>a(f.target.value),disabled:i})]}),s.jsxs(W,{type:"submit",disabled:i,size:"lg",className:"w-full",children:[i&&s.jsx(_e,{className:"w-4 h-4 animate-spin"}),i?"Updatingâ¦":"Set password"]})]}),u&&s.jsx("p",{className:"mt-4 text-xs text-text-error bg-surface-errorSubtle border border-outline-error rounded p-2",children:u}),s.jsx("p",{className:"mt-6 text-xs text-text-secondary text-center",children:s.jsx(st,{to:"/signin",className:"text-text-brand font-medium hover:underline",children:"Back to sign-in"})})]})})}function qy(){const e=xu(),{token:t=""}=jn();return e.kind==="loading"?s.jsx($nt,{}):e.kind==="anonymous"?s.jsx(Lnt,{token:t}):s.jsx(Fnt,{token:t,email:e.user.email||""})}function $nt(){return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface-subtle",children:s.jsx(_e,{className:"w-5 h-5 text-text-tertiary animate-spin"})})}function Lnt({token:e}){const t=Rt(),[n,r]=p.useState("signin"),[a,i]=p.useState(""),[o,l]=p.useState(""),[c,u]=p.useState(""),[d,h]=p.useState(null),[f,m]=p.useState(null);async function x(y){if(y.preventDefault(),m(null),n==="signup"){if(o.length<8){m("Password must be at least 8 characters.");return}if(o!==c){m("Passwords don't match.");return}}h("email");try{n==="signup"?await aC(a.trim(),o):await sC(a.trim(),o),t(`/invite/${e}`,{replace:!0})}catch(b){m(Bnt(b)),h(null)}}async function g(){m(null),h("google");try{await l0(`/invite/${e}`)}catch(y){m((y==null?void 0:y.message)||"Sign-in failed."),h(null)}}return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface-subtle p-6",children:s.jsxs("div",{className:"w-full max-w-sm bg-surface rounded-2xl shadow-sm border border-outline-subtle p-8",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[s.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-brandSubtle text-text-brand flex items-center justify-center",children:s.jsx(Ht,{className:"w-4 h-4"})}),s.jsx("span",{className:"font-semibold text-text-primary",children:"Gadjet AI"})]}),s.jsx("h1",{className:"text-xl font-semibold text-text-primary mb-1",children:"You've been invited"}),s.jsx("p",{className:"text-sm text-text-secondary mb-6",children:"Sign in to accept. Use the email address the invite was sent to."}),s.jsxs("div",{className:"flex gap-2 mb-4 text-xs",children:[s.jsx("button",{type:"button",onClick:()=>r("signin"),className:`flex-1 px-3 py-1.5 rounded-lg border ${n==="signin"?"border-brand-400 bg-surface-brandSubtle text-text-brand":"border-outline-subtle text-text-secondary hover:bg-surface-subtle"}`,disabled:d!==null,children:"I have an account"}),s.jsx("button",{type:"button",onClick:()=>r("signup"),className:`flex-1 px-3 py-1.5 rounded-lg border ${n==="signup"?"border-brand-400 bg-surface-brandSubtle text-text-brand":"border-outline-subtle text-text-secondary hover:bg-surface-subtle"}`,disabled:d!==null,children:"Create account"})]}),s.jsxs("form",{onSubmit:x,className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-body block mb-1",children:"Email"}),s.jsx(Re,{type:"email",required:!0,autoComplete:"email",value:a,onChange:y=>i(y.target.value),disabled:d!==null})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-body block mb-1",children:"Password"}),s.jsx(Re,{type:"password",required:!0,autoComplete:n==="signup"?"new-password":"current-password",value:o,onChange:y=>l(y.target.value),disabled:d!==null})]}),n==="signup"&&s.jsxs("div",{children:[s.jsx("label",{className:"text-xs font-medium text-text-body block mb-1",children:"Confirm password"}),s.jsx(Re,{type:"password",required:!0,autoComplete:"new-password",value:c,onChange:y=>u(y.target.value),disabled:d!==null})]}),f&&s.jsx("p",{className:"text-xs text-text-error bg-surface-errorSubtle border border-outline-error roun
941ded-lg px-3 py-2",children:f}),s.jsxs(W,{type:"submit",disabled:d!==null,intent:"brand",size:"lg",className:"w-full",children:[d==="email"&&s.jsx(_e,{className:"w-3.5 h-3.5 animate-spin"}),n==="signup"?"Create account":"Sign in"]})]}),s.jsxs("div",{className:"flex items-center gap-2 my-4",children:[s.jsx("div",{className:"flex-1 h-px bg-surface-sunken"}),s.jsx("span",{className:"text-xs text-text-tertiary",children:"or"}),s.jsx("div",{className:"flex-1 h-px bg-surface-sunken"})]}),s.jsxs(W,{type:"button",onClick:g,disabled:d!==null,intent:"neutral",variant:"outline",size:"lg",className:"w-full",children:[d==="google"?s.jsx(_e,{className:"w-3.5 h-3.5 animate-spin"}):s.jsx(dT,{className:"w-4 h-4"}),"Continue with Google"]}),s.jsxs("p",{className:"text-xs text-text-secondary mt-6 text-center",children:["Already signed in?"," ",s.jsx(st,{to:"/",className:"text-text-brand hover:underline",children:"Go to app"})]})]})})}function Fnt({token:e,email:t}){const n=Rt(),[r,a]=p.useState({kind:"consuming"});return p.useEffect(()=>{let i=!1;return(async()=>{try{const o=await K.acceptInvite(e);if(i)return;ai(),a({kind:"done",sellerSlug:o.seller_slug});const l=o.seller_slug?`/sellers/${o.seller_slug}`:"/";setTimeout(()=>n(l,{replace:!0}),1200)}catch(o){if(i)return;a({kind:"error",message:(o==null?void 0:o.message)||"Could not accept this invite.",code:o==null?void 0:o.code})}})(),()=>{i=!0}},[e,n]),s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface-subtle p-6",children:s.jsxs("div",{className:"w-full max-w-sm bg-surface rounded-2xl shadow-sm border border-outline-subtle p-8 text-center",children:[s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsx("div",{className:"w-10 h-10 rounded-full bg-surface-brandSubtle text-text-brand flex items-center justify-center",children:s.jsx(Ht,{className:"w-5 h-5"})})}),r.kind==="consuming"&&s.jsxs(s.Fragment,{children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary mb-1",children:"Accepting your inviteâ¦"}),s.jsx("p",{className:"text-sm text-text-secondary",children:"Hang tight, this only takes a second."}),s.jsx(_e,{className:"w-5 h-5 text-text-tertiary animate-spin mx-auto mt-4"})]}),r.kind==="done"&&s.jsxs(s.Fragment,{children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary mb-1",children:"You're in."}),s.jsx("p",{className:"text-sm text-text-secondary",children:r.sellerSlug?"Taking you to your storeâ¦":"Taking you to the appâ¦"})]}),r.kind==="error"&&s.jsxs(s.Fragment,{children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary mb-1",children:"Couldn't accept this invite"}),s.jsx("p",{className:"text-sm text-text-body bg-surface-warningSubtle border border-outline-warning rounded-lg px-3 py-2 my-3",children:r.message}),r.code==="wrong_email"?s.jsxs("p",{className:"text-xs text-text-secondary mb-4",children:["You're signed in as ",s.jsx("span",{className:"font-medium",children:t}),". Sign out and back in with the email the invite was sent to."]}):s.jsxs("p",{className:"text-xs text-text-secondary mb-4",children:["If you think this is wrong, contact"," ",s.jsx("a",{href:"mailto:[email protected]",className:"text-text-brand hover:underline",children:"[email protected]"}),"."]}),s.jsx(st,{to:"/",className:"inline-block px-3 py-1.5 rounded-lg border border-outline text-sm text-text-body hover:bg-surface-subtle",children:"Go to app"})]})]})})}function Bnt(e){const t=String((e==null?void 0:e.message)||e||"Sign-in failed.");return/Invalid login credentials/i.test(t)?"Wrong email or password.":/User already registered/i.test(t)?'An account with this email already exists â switch to "I have an account".':/Email rate limit exceeded/i.test(t)?"Too many attempts. Wait a minute and try again.":t}const zw=98,hY=[{id:"pricing",label:"Pricing"},{id:"stock",label:"Stock"},{id:"ads",label:"Ads"},{id:"listings",label:"Listings"},{id:"fees",label:"Fees and profit"},{id:"orders",label:"Orders and returns"}],fY=[{id:"under_250k",label:"Under R250k"},{id:"over_250k",label:"R250k or more"},{id:"unsure",label:"Not sure"}],mY=[{id:"software",label:"Software"},{id:"agency",label:"Agency"}],pY=[{id:"call",label:"Call"},{id:"info",label:"Send info"}],Unt=new Set(hY.map(e=>e.id)),znt=new Set(fY.map(e=>e.id)),Wnt=new Set(mY.map(e=>e.id)),Knt=new Set(pY.map(e=>e.id));function Hnt(e){return e==="under_250k"?"software":e==="over_250k"?"agency":null}function Vnt(e){const t=String(e??"").trim().replace(/\s+/g," ");return!t||t.length>80?null:t}function qnt(e){return String(e??"").trim().toLowerCase()||null}function Gnt(e){const t=String(e??"").trim();if(!t)return null;const n=t.startsWith("+"),r=t.replace(/\D/g,"");return r?r.startsWith("27")&&r.length>=11?`+${r}`:r.startsWith("0")&&r.length===10?`+27${r.slice(1)}`:n?`+${r}`:r:null}function Ynt(e){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)}function Zs(e,t){return{ok:!1,field:e,message:t}}function Znt(e){const t=e&&typeof e=="object"?e:{},n=Vnt(t.promoter_name);if(!n)return Zs("promoter_name","Enter your name first.");const r=String(t.name??"").trim().replace(/\s+/g," ");
941if(!r)return Zs("name","Name is required.");if(r.length>200)return Zs("name","Name is too long.");const a=String(t.business_name??"").trim().replace(/\s+/g," ");if(!a)return Zs("business_name","Business name is required.");if(a.length>200)return Zs("business_name","Business name is too long.");const i=qnt(t.email);if(i&&(i.length>320||!Ynt(i)))return Zs("email","Enter a valid email.");const o=Gnt(t.phone);if(o&&o.length>32)return Zs("phone","Phone number is too long.");const l=String(t.monthly_turnover??"");if(!znt.has(l))return Zs("monthly_turnover","Pick a turnover.");const c=String(t.lead_type??"");if(!Wnt.has(c))return Zs("lead_type","Pick Software or Agency.");const u=String(t.next_step??"");if(!Knt.has(u))return Zs("next_step","Pick a next step.");if(u==="call"&&!o)return Zs("phone","A call needs a phone number.");if(u==="call"&&!i)return Zs("email","A call needs an email.");if(u==="info"&&!i)return Zs("email","Send info needs an email.");const d=Array.isArray(t.pain_points)?t.pain_points:[],h=[];for(const x of d){const g=String(x);if(!Unt.has(g))return Zs("pain_points","Unknown pain point.");h.includes(g)||h.push(g)}let f=String(t.pain_other??"").trim().replace(/\s+/g," ");return f.length>200?Zs("pain_other","That note is too long."):(f||(f=null),t.consent!==!0?Zs("consent","Consent is required."):{ok:!0,value:{promoter_name:n,name:r,business_name:a,email:i,phone:o,monthly_turnover:l,lead_type:c,pain_points:h,pain_other:f,next_step:u,consent:!0}})}const hT="gadjet:summit-promoter",xY="gadjet:summit-outbox";function Xnt(){var e;try{return((e=localStorage.getItem(hT))==null?void 0:e.trim())??""}catch{return""}}function Jnt(e){localStorage.setItem(hT,e.trim())}function Qnt(){localStorage.removeItem(hT)}function qm(){try{const e=localStorage.getItem(xY),t=e?JSON.parse(e):[];return Array.isArray(t)?t:[]}catch{return[]}}function Gy(e){localStorage.setItem(xY,JSON.stringify(e))}async function ert(e){try{const t=await fetch(`/api/event-captures?promoter_name=${encodeURIComponent(e)}`);
941if(!t.ok)return null;const n=await t.json();return{today_count:Number(n.today_count)||0,target:Number(n.target)||zw,recent:Array.isArray(n.recent)?n.recent:[]}}catch{return null}}async function x2(e,t={}){let n;try{n=await fetch(t.id?`/api/event-captures/${t.id}`:"/api/event-captures",{method:t.id?"PATCH":"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,force:t.force===!0})})}catch{return{ok:!1,kind:"offline"}}const r=await n.json().catch(()=>({}));return n.status===409&&r.existing?{ok:!1,kind:"duplicate",existing:r.existing}:n.status===502||n.status===503||n.status===504?{ok:!1,kind:"offline"}:n.ok?{ok:!0,capture:r.capture,today_count:Number(r.today_count)||0,target:Number(r.target)||zw}:{ok:!1,kind:"invalid",field:typeof r.field=="string"?r.field:null,message:typeof r.message=="string"?r.message:"Could not save that lead."}}async function trt(){const e=qm(),t=[];for(const n of e){if(n.duplicate){t.push(n);continue}const r=await x2(n.payload);if(!r.ok){if(r.kind==="duplicate"){t.push({...n,duplicate:r.existing});continue}if(r.kind==="offline"){t.push(n);continue}}}return Gy(t),t}const t6={name:"",business_name:"",phone:"",email:"",monthly_turnover:"",lead_type:"",pain_points:[],pain_other_open:!1,pain_other:"",next_step:"",consent:!1};function nrt(e,t){return{promoter_name:t,name:e.name,business_name:e.business_name,email:e.email,phone:e.phone,monthly_turnover:e.monthly_turnover,lead_type:e.lead_type,pain_points:e.pain_points,pain_other:e.pain_other_open?e.pain_other:null,next_step:e.next_step,consent:!0}}function n6(e){return{name:e.name,business_name:e.business_name,email:e.email??"",phone:e.phone??"",monthly_turnover:e.monthly_turnover,lead_type:e.lead_type,pain_points:e.pain_points??[],pain_other_open:!!e.pain_other,pain_other:e.pain_other??"",next_step:e.next_step,consent:!0}}function Jj(e){const t=new Date(e);return Number.isNaN(t.getTime())?"":new Intl.DateTimeFormat("en-ZA",{timeZone:"Africa/Johannesburg",hour:"2-digit",minute:"2-digit"}).format(t)}function rrt(){const[e,t]=p.useState(Xnt),[n,r]=p.useState(""),[a,i]=p.useState(t6),[o,l]=p.useState(0),[c,u]=p.useState(zw),[d,h]=p.useState([]),[f,m]=p.useState(qm),[x,g]=p.useState(null),[y,b]=p.useState(null),[v,w]=p.useState(null),[_,k]=p.useState(null),[j,N]=p.useState(null),[E,A]=p.useState(!1),C=p.useRef(null),T=f.filter(Y=>Y.payload.promoter_name===e),S=p.useCallback(async Y=>{const M=await ert(Y);M&&(l(M.today_count),u(M.target),h(M.recent))},[]),O=p.useCallback(async()=>{const Y=await trt();return m(Y),Y},[]);p.useEffect(()=>{if(!e)return;let Y=!1;(async()=>(await O(),Y||await S(e)))();const M=()=>{O().then(()=>S(e))};return window.addEventListener("online",M),()=>{Y=!0,window.removeEventListener("online",M)}},[e,S,O]);function R(){i(t6),g(null),b(null),w(null),k(null),window.setTimeout(()=>{var Y;return(Y=C.current)==null?void 0:Y.focus()},0)}function I(Y){var M;g(Y.id),b(null),i(n6(Y)),w(null),k(null),N(null),(M=C.current)==null||M.focus()}function $(Y){var M;g(null),b(Y.localId),i(n6(Y.payload)),w(null),k(null),(M=C.current)==null||M.focus()}async function P(Y=!1){if(!e||E)return;const M=nrt(a,e);if(!a.consent){k("Tick that they are happy for Gadjet to contact them.");return}const z=Znt(M);if(!z.ok){k(z.message);return}if(A(!0),k(null),N(null),y){const te=qm().map(q=>q.localId===y?{...q,payload:M,duplicate:null}:q);Gy(te),m(te),A(!1),R();const L=(await O()).some(q=>q.localId===y);N(L?"Updated on this phone. It will send when you are back online.":"Updated."),await S(e);return}const G=await x2(M,{id:x,force:Y});if(A(!1),G.ok){l(G.today_count),u(G.target),N(x?"Updated.":`Saved · ${G.today_count} today`),R(),await S(e);return}if(G.kind==="duplicate"){w(G.existing);return}if(G.kind==="offline"){if(x){k("You are offline, so this edit was not saved. Try again when you are back.");return}const re=[{localId:crypto.randomUUID(),payload:M,duplicate:null},...qm()];Gy(re),m(re),N("Saved on this phone. It will send when you are back online."),R();return}k((G.kind==="invalid",G.message))}function F(Y){const M=qm().filter(z=>z.localId!==Y);Gy(M),m(M)}async function Z(Y){const M=await x2(Y.payload,{force:!0});if(!M.ok){k(M.kind==="invalid"||M.kind==="error"?M.message:"Still offline.");return}F(Y.localId),l(M.today_count),await S(e)}if(!e)return s.jsx(srt,{draftName:n,setDraftName:r,onContinue:()=>{const Y=n.trim().replace(/\s+/g," ");Y&&(Jnt(Y),t(Y))}});const D=Math.min(100,Math.round(o/Math.max(c,1)*100)),H=!!(x||y);return s.jsxs("div",{className:"min-h-screen bg-surface-subtle text-text-primary",children:[s.jsx("header",{className:"sticky top-0 z-10 border-b border-outline-subtle bg-surface px-4 py-3",children:s.jsxs("div",{className:"mx-auto flex max-w-md items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("p",{className:"text-3xl font-semibold leading-none",children:[o,s.jsxs("span",{className:"text-lg font-medium text-text-secondary",children:[" of ",c]})]}),s.jsxs("p",{className:"mt-1 text-sm text-text-secondary",children:["Your leads today · ",e]}),s.jsx("div",{className:"mt-2 h-2 overflow-hidden rounded-full bg-surface-subtle",children:s.jsx("div",{className:"h-full rounded-full bg-brand-500",style:{width:`${D}%`}})}),T.length>0&&s.jsxs("p",{className:"mt-2 text-sm text-text-warning",children:[T.length," waiting to send"]})]}),s.jsx("button",{type:"button",className:"shrink-0 text-sm font-medium text-text-brand",onClick:()=>{Qnt(),t(""),N(null),R()},children:"Switch"})]})}
941),s.jsxs("main",{className:"mx-auto max-w-md space-y-5 px-4 py-4 pb-36",children:[j&&s.jsx("p",{className:"rounded-md border border-outline-success bg-surface-successSubtle px-3 py-2 text-sm text-text-success",children:j}),s.jsx(ky,{label:"Name",children:s.jsx(Re,{ref:C,value:a.name,autoComplete:"name",enterKeyHint:"next",onChange:Y=>i({...a,name:Y.target.value})})}),s.jsx(ky,{label:"Business name",children:s.jsx(Re,{value:a.business_name,autoComplete:"organization",onChange:Y=>i({...a,business_name:Y.target.value})})}),s.jsx(ky,{label:"Phone",children:s.jsx(Re,{value:a.phone,type:"tel",inputMode:"tel",autoComplete:"tel",onChange:Y=>i({...a,phone:Y.target.value})})}),s.jsx(ky,{label:"Email",children:s.jsx(Re,{value:a.email,type:"email",inputMode:"email",autoComplete:"email",onChange:Y=>i({...a,email:Y.target.value})})}),s.jsx(Qj,{label:"Monthly turnover",options:fY,value:a.monthly_turnover,onChange:Y=>i({...a,monthly_turnover:Y,lead_type:Hnt(Y)??""})}),s.jsx(Qj,{label:"Lead",options:mY,value:a.lead_type,onChange:Y=>i({...a,lead_type:Y})}),s.jsxs("fieldset",{children:[s.jsx("legend",{className:"mb-2 text-sm font-medium",children:"What takes their time"}),s.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[hY.map(Y=>{const M=a.pain_points.includes(Y.id);return s.jsx(g2,{on:M,label:Y.label,onClick:()=>i({...a,pain_points:M?a.pain_points.filter(z=>z!==Y.id):[...a.pain_points,Y.id]})},Y.id)}),s.jsx(g2,{on:a.pain_other_open,label:"Something else",onClick:()=>i({...a,pain_other_open:!a.pain_other_open,pain_other:a.pain_other_open?"":a.pain_other})})]}),a.pain_other_open&&s.jsx(Re,{className:"mt-2",placeholder:"Short note",value:a.pain_other,onChange:Y=>i({...a,pain_other:Y.target.value})})]}),s.jsx(Qj,{label:"Next step",options:pY,value:a.next_step,onChange:Y=>i({...a,next_step:Y})}),s.jsxs("button",{type:"button",role:"checkbox","aria-checked":a.consent,onClick:()=>i({...a,consent:!a.consent}),className:B("flex min-h-11 w-full items-start gap-3 rounded-md border px-4 py-3 text-left text-body-lg",a.consent?"border-outline-brand bg-surface-brandSubtle text-text-brand":"border-outline bg-surface"),children:[s.jsx("span",{className:B("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border",a.consent?"border-outline-brand bg-brand-500 text-text-inverse":"border-outline"),"aria-hidden":!0,children:a.consent?"â":""}),s.jsx("span",{children:"Happy for Gadjet to contact them about arranging that meeting."})]}),T.length>0&&s.jsxs("section",{className:"space-y-2",children:[s.jsx("h2",{className:"text-sm font-medium",children:"Waiting to send"}),T.map(Y=>s.jsxs("div",{className:"rounded-md border border-outline bg-surface px-3 py-2 text-sm",children:[s.jsx("p",{className:"font-medium",children:Y.payload.name}),s.jsx("p",{className:"text-text-secondary",children:Y.payload.business_name}),Y.duplicate?s.jsxs("p",{className:"mt-1 text-text-warning",children:["Already captured by ",Y.duplicate.promoter_name," at ",Jj(Y.duplicate.created_at),"."]}):s.jsx("p",{className:"mt-1 text-text-secondary",children:"On this phone"}),s.jsxs("div",{className:"mt-2 flex gap-3",children:[s.jsx("button",{type:"button",className:"font-medium text-text-brand",onClick:()=>$(Y),children:"Edit"}),Y.duplicate&&s.jsx("button",{type:"button",className:"font-medium text-text-brand",onClick:()=>Z(Y),children:"Save anyway"}),s.jsx("button",{type:"button",className:"font-medium text-text-secondary",onClick:()=>F(Y.localId),children:"Discard"})]})]},Y.localId))]}),d.length>0&&s.jsxs("section",{className:"space-y-2",children:[s.jsx("h2",{className:"text-sm font-medium",children:"Your recent leads"}),d.map(Y=>s.jsxs("button",{type:"button",onClick:()=>I(Y),className:"block w-full rounded-md border border-outline bg-surface px-3 py-2 text-left",children:[s.jsx("span",{className:"block text-sm font-medium",children:Y.name}),s.jsxs("span",{className:"block text-sm text-text-secondary",children:[Y.business_name," · ",Jj(Y.created_at)]})]},Y.id))]})]}),s.jsx("footer",{className:"fixed inset-x-0 bottom-0 border-t border-outline-subtle bg-surface px-4 py-3",children:s.jsxs("div",{className:"mx-auto max-w-md
941space-y-2",children:[v&&s.jsxs("p",{className:"text-sm text-text-warning",children:["Already captured by ",v.promoter_name," at ",Jj(v.created_at),"."]}),_&&s.jsx("p",{className:"text-sm text-text-error",children:_}),s.jsxs("div",{className:"flex gap-2",children:[H&&s.jsx(W,{type:"button",intent:"neutral",variant:"outline",className:"flex-1",onClick:R,children:"Cancel"}),v?s.jsxs(s.Fragment,{children:[s.jsx(W,{type:"button",intent:"neutral",variant:"outline",className:"flex-1",onClick:()=>w(null),children:"Discard"}),s.jsx(W,{type:"button",className:"flex-1",disabled:E,onClick:()=>P(!0),children:"Save anyway"})]}):s.jsx(W,{type:"button",className:"flex-1",disabled:E,onClick:()=>P(!1),children:E?"Saving":H?"Update":"Save"})]})]})})]})}function srt({draftName:e,setDraftName:t,onContinue:n}){return s.jsx("div",{className:"flex min-h-screen items-center justify-center bg-surface-subtle px-4",children:s.jsxs("form",{className:"w-full max-w-sm rounded-2xl border border-outline-subtle bg-surface p-6 shadow-sm",onSubmit:r=>{r.preventDefault(),n()},children:[s.jsx("p",{className:"text-sm font-medium text-text-secondary",children:"Takealot Summit"}),s.jsx("h1",{className:"mt-1 text-xl font-semibold",children:"Your name"}),s.jsxs("p",{className:"mt-2 text-sm text-text-secondary",children:["So each lead is tagged with who collected it. Today's target is ",zw,"."]}),s.jsx("label",{className:"mt-4 block text-sm font-medium",htmlFor:"summit-name",children:"Name"}),s.jsx(Re,{id:"summit-name",className:"mt-1",autoFocus:!0,autoComplete:"name",value:e,onChange:r=>t(r.target.value)}),s.jsx(W,{type:"submit",className:"mt-4 w-full",disabled:!e.trim(),children:"Continue"})]})})}function ky({label:e,children:t}){return s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-sm font-medium",children:e}),t]})}function Qj({label:e,options:t,value:n,onChange:r}){return s.jsxs("fieldset",{children:[s.jsx("legend",{className:"mb-2 text-sm font-medium",children:e}),s.jsx("div",{className:"grid gap-2",children:t.map(a=>s.jsx(g2,{on:n===a.id,label:a.label,onClick:()=>r(a.id)},a.id))})]})}function g2({on:e,label:t,onClick:n}){return s.jsx("button",{type:"button","aria-pressed":e,onClick:n,className:B("min-h-11 rounded-md border px-3 text-left text-body-lg font-medium",e?"border-outline-brand bg-surface-brandSubtle text-text-brand":"border-outline bg-surface text-text-primary"),children:t})}function art(){return s.jsxs(ld,{children:[s.jsx(He,{path:"/sellers/:slug/overview",element:s.jsx(UH,{})}),s.jsx(He,{path:"/sellers/:slug/monthly-report",element:s.jsx(s$e,{})}),s.jsx(He,{path:"*",element:s.jsx(Vv,{})})]})}function irt(){const{slug:e=""}=jn(),{search:t}=Ba();return s.jsx(Yt,{to:`/overview/${e}${t}`,replace:!0})}function ort(){const{slug:e=""}=jn();return s.jsx(Yt,{to:`/settings/stores/${e}`,replace:!0})}function lrt(){if(Wc())return s.jsx(art,{});const{pathname:e}=Ba(),t=xu();if(e==="/summit"||e==="/summit/")return s.jsx(rrt,{});if(t.kind==="loading")return s.jsx(Vv,{});if(t.kind==="anonymous"){const n=wd.isNativePlatform()?"/link":"/signin";return s.jsxs(ld,{children:[s.jsx(He,{path:"/",element:s.jsx(Yt,{to:n,replace:!0})}),s.jsx(He,{path:"/signin",element:s.jsx(Tnt,{})}),s.jsx(He,{path:"/signup",element:wr()?s.jsx(Yt,{to:n,replace:!0}):s.jsx(Vm,{})}),s.jsx(He,{path:"/forgot-password",element:s.jsx(Mnt,{})}),s.jsx(He,{path:"/reset-password",element:s.jsx(Vy,{})}),s.jsx(He,{path:"/invite/:token",element:s.jsx(qy,{})}),s.jsx(He,{path:"/connect/amazon",element:s.jsx(NN,{})}),s.jsx(He,{path:"/connect/amazon/complete",element:s.jsx(CN,{})}),s.jsx(He,{path:"/link",element:s.jsx(Int,{})}),s.jsx(He,{path:"*",element:s.jsx(Yt,{to:n,replace:!0})})]})}return s.jsx(Jle,{children:s.jsx(CKe,{children:s.jsx(urt,{})})})}function crt({me:e}){const t=e.me.lockout_scope,n=e.me.lockout_reason,r=t==="global"?"Gadjet is temporarily unavailable":"Your account is locked",a=t==="global"?"We've taken the workspace offline for emergency maintenance. We'll be back shortly.":"Access to your Gadjet account has been suspended. Please contact [email protected] if you believe this is a mistake.";return s.jsx("div",{className:"min-h-screen flex items-center justify-center bg-surface-subtle px-4",children:s.jsxs("div",{className:"max-w-md w-full bg-surface border border-outline-subtle rounded-lg shadow-sm p-8 text-center",children:[s.jsx("div",{className:"mx-auto w-12 h-12 rounded-full bg-surface-errorSubtle border border-outline-error flex items-center justify-center mb-4",children:s.jsx(Bl,{className:"w-5 h-5 text-text-error"})}),s.jsx("h1",{className:"text-xl font-semibold text-text-primary mb-2",children:r}),s.jsx("p",{className:"text-sm text-text-body mb-4",children:a}),n&&s.jsxs("p",{className:"text-sm text-text-secondary italic mb-4",children:['"',n,'"']}),s.jsxs("div",{className:"flex flex-col gap-2 mt-6",children:[s.jsx("button",{onClick:()=>e.refresh(),className:"text-sm font-medium text-text-body border border-outline rounded-md px-4 py-2 hover:bg-surface-subtle",children:"Check again"}),s.jsx("button",{onClick:async()=>{await wf(),window.location.href="/signin"},className:"text-sm font-medium text-text-secondary hover:text-text-body",children:"Sign out"})]})]})})}function urt(){var h;const e=Lt(),t=Rt(),n=Ba();if(p.useEffect(()=>{if(n.pathname==="/connect/amazon"||n.pathname==="/connect/amazon/complete")return;let f=!1,m=!1;try{f=!!sessionStorage.getItem("gadjet:amazonOAuthComplete"),m=!!sessionStorage.getItem("gadjet:amazonAppstore")}catch{}f?t("/connect/amazon/complete",{replace:!0}):m&&t("/connect/amazon",{replace:!0})},[n.pathname,t]),e.kind==="loading")return s.jsx(Vv,{});if(e.kind==="error")return s.jsxs(ld,{children:[s.jsx(He,{path:"/signup",element:wr()?s.jsx(e6,{}):s.jsx(Vm,{})}),s.jsx(He,{path:"/reset-password",element:s.jsx(Vy,{})}),s.jsx(He,{path:"/invite/:token",element:s.jsx(qy,{})}),s.jsx(He,{path:"/connect/amazon",element:s.jsx(NN,{})}),s.jsx(He,{path:"/connect/amazon/complete",element:s.jsx(CN,{})}),s.jsx(He,{path:"*",element:s.jsx(Yt,{to:"/signup",replace:!0})})]});if(e.me.is_locked_out)return s.jsx(crt,{me:e});const r=e.me.role==="seller_user"&&!e.me.has_sellers;if(r&&wr())return s.jsx(e6,{});if(r)return s.jsxs(ld,{children:[s.jsx(He,{path:"/",element:s.jsx(Vm,{})}),s.jsx(He,{path:"/signup",element:s.jsx(Vm,{})}),s.jsx(He,{path:"/reset-password",element:s.jsx(Vy,{})}),s.jsx(He,{path:"/invite/:token",element:s.jsx(qy,{})}),s.jsx(He,{path:"*",element:s.jsx(Yt,{to:"/",replace:!0})})]});const a=e.me.role==="seller_user",i=((h=e.me.allowed_slugs)==null?void 0:h[0])??null,o=a||e.me.role==="content_creator"&&!!i,l=i?`/overview/${i}`:"/dashboards",c=i?`/sellers/${i}/chats`:"/dashboards",u=i?cC(i):"/dashboards",d=!!e.me.is_demo_mode;return s.jsxs(ld,{children:[s.jsx(He,{path:"/signup",element:wr()?s.jsx(Yt,{to:o?l:"/agent",replace:!0}):s.jsx(Vm,{})}),s.jsx(He,{path:"/reset-password",element:s.jsx(Vy,{})}),s.jsx(He,{path:"/invite/:token",element:s.jsx(qy,{})}),s.jsx(He,{path:"/connect/amazon",element:s.jsx(NN,{})}),s.jsx(He,{path:"/connect/amazon/complete",element:s.jsx(CN,{})}),s.jsxs(He,{element:s.jsx(jye,{}),children:[s.jsx(He,{index:!0,element:s.jsx(Yt,{to:o?l:"/agent",replace:!0})}),o?s.jsxs(s.Fragment,{children:[s.jsx(He,{path:"/agent",element:s.jsx(Yt,{to:c,replace:!0})}),s.jsx(He,{path:"/agent/new",element:s.jsx(Yt,{to:u,replace:!0})}),s.jsx(He,{path:"/agent/:chatId",element:s.jsx(Yt,{to:c,replace:!0})})]}):s.jsxs(s.Fragment,{children:[s.jsx(He,{path:"/agent",element:s.jsx(P$,{})}),s.jsx(He,{path:"/agent/:chatId",element:s.jsx(P$,{})})]}),s.jsx(He,{path:"/dashboards",element:s.jsx(DVe,{})}),s.jsx(He,{path:"/market-explorer",element:s.jsx($Ge,{})}),s.jsx(He,{path:"/academy",element:s.jsx(zGe,{})}),d&&!e.me.is_demo_showcase?s.jsx(He,{path:"/sops",element:s.jsx(Yt,{to:l,replace:!0})}):s.jsx(He,{path:"/sops",element:s.jsx(wYe,{})}),d&&!e.me.is_demo_showcase?s.jsxs(s.Fragment,{children:[s.jsx(He,{path:"/approvals
941/:slug/experiments/:batchId",element:s.jsx(Yt,{to:l,replace:!0})}),s.jsx(He,{path:"/approvals/:slug/:id",element:s.jsx(Yt,{to:l,replace:!0})})]}):s.jsxs(s.Fragment,{children:[s.jsx(He,{path:"/approvals/:slug/experiments/:batchId",element:s.jsx(iZe,{})}),s.jsx(He,{path:"/approvals/:slug/:id",element:s.jsx(nZe,{})})]}),d?s.jsxs(s.Fragment,{children:[s.jsx(He,{path:"/ads",element:s.jsx(Yt,{to:l,replace:!0})}),s.jsx(He,{path:"/ads/:slug",element:s.jsx(Yt,{to:l,replace:!0})})]}):s.jsxs(s.Fragment,{children:[s.jsx(He,{path:"/ads",element:s.jsx(ZL,{})}),s.jsx(He,{path:"/ads/:slug",element:s.jsx(ZL,{})})]}),s.jsx(He,{path:"/dashboards/new",element:d?s.jsx(Yt,{to:"/dashboards",replace:!0}):s.jsx(vL,{})}),s.jsx(He,{path:"/dashboards/:id",element:s.jsx(UVe,{})}),s.jsx(He,{path:"/dashboards/:id/edit",element:d?s.jsx(Yt,{to:"/dashboards",replace:!0}):s.jsx(vL,{})}),e.me.role==="super_admin"?s.jsxs(s.Fragment,{children:[s.jsx(He,{path:"/skills",element:s.jsx(Yt,{to:"/settings/admin/skills",replace:!0})}),s.jsx(He,{path:"/skills/:name",element:s.jsx(XUe,{})})]}):s.jsxs(s.Fragment,{children:[s.jsx(He,{path:"/skills",element:s.jsx(Yt,{to:l,replace:!0})}),s.jsx(He,{path:"/skills/:name",element:s.jsx(Yt,{to:l,replace:!0})})]}),s.jsx(He,{path:"/cron-jobs",element:s.jsx(Eq,{})}),s.jsx(He,{path:"/tasks",element:s.jsx(wKe,{})}),s.jsx(He,{path:"/crm",element:s.jsx(DKe,{})}),s.jsx(He,{path:"/crm/:id",element:s.jsx(rHe,{})}),s.jsx(He,{path:"/earn",element:s.jsx(jHe,{})}),s.jsx(He,{path:"/content",element:s.jsx(dh,{})}),s.jsx(He,{path:"/content/pillars/:id",element:s.jsx(dh,{})}),s.jsx(He,{path:"/content/review",element:s.jsx(dh,{})}),s.jsx(He,{path:"/content/repurpose",element:s.jsx(dh,{})}),s.jsx(He,{path:"/content/film-queue",element:s.jsx(dh,{})}),s.jsx(He,{path:"/content/digest/:week",element:s.jsx(dh,{})}),s.jsx(He,{path:"/calendar",element:s.jsx(IVe,{})}),s.jsx(He,{path:"/sellers/:slug/tasks",element:s.jsx(kKe,{})}),s.jsx(He,{path:"/settings/*",element:s.jsx(Ent,{})}),s.jsx(He,{path:"/admin/dashboard",element:s.jsx(Yt,{to:"/settings/admin/dashboard",replace:!0})}),s.jsx(He,{path:"/admin/users",element:s.jsx(Yt,{to:"/settings/admin/users",replace:!0})}),s.jsx(He,{path:"/admin/ai-spend",element:s.jsx(Yt,{to:"/settings/admin/ai-spend",replace:!0})}),s.jsx(He,{path:"/admin/lockout",element:s.jsx(Yt,{to:"/settings/admin/lockout",replace:!0})}),s.jsx(He,{path:"/profile",element:s.jsx(Yt,{to:"/settings/profile",replace:!0})}),s.jsx(He,{path:"/account",element:s.jsx(Yt,{to:"/settings",replace:!0})}),s.jsx(He,{path:"/overview",element:s.jsx(i$e,{})}),s.jsx(He,{path:"/overview/:slug",element:s.jsx(UH,{})}),s.jsx(He,{path:"/sellers/:slug",element:s.jsx(irt,{})}),s.jsx(He,{path:"/sellers/:slug/automations/*",element:s.jsx(J7e,{})}),s.jsx(He,{path:"/sellers/:slug/inventory",element:s.jsx(wBe,{})}),s.jsx(He,{path:"/sellers/:slug/inventory/scan",element:s.jsx(jBe,{})}),s.jsx(He,{path:"/sellers/:slug/shipments",element:s.jsx(_Be,{})}),s.jsx(He,{path:"/sellers/:slug/sales",element:s.jsx(bBe,{})}),s.jsx(He,{path:"/sellers/:slug/transactions",element:s.jsx(x9e,{})}),s.jsx(He,{path:"/sellers/:slug/returns",element:s.jsx(vBe,{})}),s.jsx(He,{path:"/sellers/:slug/chats",element:s.jsx(R$,{})}),s.jsx(He,{path:"/sellers/:slug/chats/:chatId",element:s.jsx(R$,{})}),s.jsx(He,{path:"/sellers/:slug/reports/*",element:s.jsx(D6e,{})}),s.jsx(He,{path:"/sellers/:slug/settings",element:s.jsx(ort,{})}),s.jsx(He,{path:"/exports/:id",element:s.jsx(M6e,{})}),s.jsx(He,{path:"*",element:s.jsx(Yt,{to:"/",replace:!0})})]})]})}const brt=Object.freeze(Object.defineProperty({__proto__:null,default:lrt},Symbol.toStringTag,{value:"Module"}));export{co as A,QL as B,Yr as C,On as D,Qo as E,We as F,dXe as H,Ct as I,LO as K,Fw as L,Wm as M,Oe as N,f2 as P,d2 as Q,mrt as S,Z2 as W,sT as a,o2 as b,c2 as c,JQe as d,u2 as e,iet as f,Gf as g,wt as h,wd as i,a1 as j,$O as k,brt as l};
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.