1import{n as Nt,j as e,o as w,u as O,p as bs,C as Qe,a as ys,b as js,B as C,e as vs,q as U,t as K,s as M,v as wt,w as Ns,x as ws,y as ks,z as _s,D as Ss,E as V,R as Ze,F as kt,I as Cs,J as As,X as Xe,K as be,M as ms,Y as Ke,N as Ts,O as Je,Q as Ls,V as _t,W as Ms,A as je,Z as St,_ as Te,r as y,$ as $s,a0 as Rs,a1 as Ps,a2 as Fs,a3 as Is,a4 as es,a5 as fe,a6 as ss,a7 as Ct,a8 as At,a9 as Pe,aa as Tt,ab as Fe,ac as J,ad as qs,ae as Z,af as oe,ag as ce,ah as de,ai as me,aj as z,ak as he,al as ve,am as Ie,an as Lt,ao as Mt,ap as X,f as Ds,aq as $t,ar as Es,d as We,as as Rt,at as Pt,au as Ft,av as It,aw as ts,ax as Ce,ay as qt,az as Dt,S as Le,aA as Us,aB as Bs,aC as zs,aD as Os,aE as Et,aF as Me,T as as,aG as Ut,aH as Ks,aI as Bt,aJ as zt,U as Ot,aK as Kt,aL as Wt,l as Vt,h as Ht,aM as Gt,aN as Yt,aO as Qt,aP as Zt,aQ as Xt,aR as Jt,aS as ea,aT as sa,aU as ta}from"./index-CA5JHsqG.js";import{F as aa,U as ra}from"./FeatureRequestDialog-CGhoLFLQ.js";import{P as na}from"./ProductDemoTour-CziX3eTp.js";import{A as Ws,a as Vs,b as qe,c as Hs}from"./widgetAccents-urcACvDs.js";import{A as Gs}from"./arrow-up-right-2xTnbKUV.js";import{r as Ys,w as Qs}from"./queryPersist-D137HFsL.js";import{S as us}from"./save-zITqBwRc.js";import{M as la}from"./mail-DPbGJfAb.js";import{S as ia}from"./send-9yO38K0i.js";import{u as Zs}from"./useReportCredits-CuX-5dxm.js";import{C as oa,a as ca,b as da,c as ma,d as ua,e as ha,f as xa}from"./command-BEkuTnnS.js";import{M as pa}from"./ManageTrackedAsinsDrawer-B77xk7kG.js";import{C as ga}from"./ComposedChart-Bwczg1gr.js";import{S as fa}from"./settings-2-CkO86K4r.js";import{A as ba}from"./AreaChart-DBHIS_Pf.js";import{A as ya}from"./Area-D2qpOzso.js";import{L as ja}from"./list-CSKuPiTG.js";import{u as Xs}from"./useAIUsage-DlxYbsm8.js";import{M as va}from"./message-square-DgtfTfk9.js";import{g as Na}from"./retailerRevealBalance-CEYVP7oD.js";import{L as wa}from"./lightbulb-D-wTAQas.js";import{C as ka}from"./coins-BmLcWdOu.js";import{F as _a}from"./factory-Eh6AYegd.js";import{R as Sa}from"./route-CP4hWnzl.js";import"./progress-Gf0SDZ99.js";import"./useUsageStats-DI8t7351.js";import"./chart-pie-C6xJ-eBh.js";import"./award-Douopu1M.js";import"./zap-BbNUf1f4.js";import"./building-2-Dp3Id-nh.js";import"./alert-dialog-DhhEVg46.js";import"./Scatter-CMiiTPHE.js";const Ve=Nt("Table2",[["path",{d:"M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18",key:"gugj83"}]]),re=({title:s,description:t,icon:n,accent:r="blue",href:l,ctaAction:u,ctaLabel:d="Open",className:o,loading:g,loadingComponent:m,badge:b,children:S})=>{const _=O(),{trackClick:h}=bs(),k=()=>{if(u){h(s,"navigation",{source:"dashboard-widget",action:"open-dialog"}),u();return}l&&(h(s,"navigation",{source:"dashboard-widget",href:l}),_(l))};return e.jsxs(Qe,{className:w("group relative isolate flex h-full flex-col overflow-hidden border-border/60 bg-card/80 backdrop-blur-sm","transition-all duration-300 ease-out motion-safe:hover:-translate-y-1 hover:shadow-elegant","before:pointer-events-none before:absolute before:inset-x-0 before:top-0 before:-z-10 before:h-32","before:bg-gradient-to-b before:to-transparent before:opacity-80",Vs[r],o),children:[e.jsxs(ys,{className:"space-y-1.5 p-3.5 pb-2 sm:p-5 sm:pb-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 sm:gap-3",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2 sm:gap-2.5",children:[e.jsx("span",{className:w("grid h-8 w-8 shrink-0 place-items-center rounded-xl sm:h-9 sm:w-9",Ws[r]),children:n}),e.jsxs("div",{className:"min-w-0",children:[e.jsx(js,{className:"break-words text-[15px] font-semibold leading-tight tracking-tight sm:text-lg",children:s}),b]})]}),e.jsx(C,{variant:"ghost",size:"icon","aria-label":`${d} ${s}`,title:`${d} ${s}`,className:"h-8 w-8 shrink-0 rounded-full border border-border/60 text-muted-foreground transition-colors group-hover:border-transparent group-hover:bg-foreground group-hover:text-background",onClick:k,children:e.jsx(Gs,{className:"h-4 w-4"})})]}),t&&e.jsx("p",{className:"text-xs leading-snug text-muted-foreground sm:text-sm",children:t})]}),e.jsx(vs,{className:w("flex-1 p-3.5 pt-0 sm:p-5 sm:pt-0",g&&m&&"flex flex-col"),children:g?m?e.jsx("div",{className:"flex flex-1 items-center justify-center py-6",children:m}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{className:"h-4 w-2/3"}),e.jsx(U,{className:"h-4 w-1/2"}),e.jsx(U,{className:"h-4 w-3/4"})]}):S})]})},ee=({pct:s})=>{if(s==null||!isFinite(s))return null;const t=s>=0;return e.jsxs("span",{className:w("inline-flex items-center gap-0.5 rounded-full px-1.5 py-0.5 text-[11px] font-semibold tabular-nums",t?"bg-widget-emerald/12 text-widget-emerald ring-1 ring-widget-emerald/25":"bg-destructive/10 text-destructive ring-1 ring-destructive/25"),children:[t?"â²":"â¼"," ",Math.abs(s)>=1e3?`${Math.round(Math.abs(s)/100)/10}k`:Math.abs(s).toFixed(0),"%"]})},He=({children:s})=>e.jsx("p",{className:"text-sm text-muted-foreground",children:s}),Ca=720*6e4;function Aa(s){const t=s?.computed_at?new Date(s.computed_at):null,n=s?.refresh_last_run_at?new Date(s.refresh_last_run_at):null,r=s?.refresh_error?s.refresh_error:null,l=(s?.refresh_status??"").toLowerCase()==="failed";return!s||s.pending||!t?{state:l?"failed":"pending",computedAt:null,lastRunAt:n,error:r}:l&&n&&n.getTime()>t.getTime()?{state:"failed",computedAt:t,lastRunAt:n,error:r}:Date.now()-t.getTime()>Ca?{state:"stale",computedAt:t,lastRunAt:n,error:r}:{state:"ok",computedAt:t,lastRunAt:n,error:r}}const Js="dashboard-highlights",Ta=10080*6e4;async function et(){const{data:s,error:t}=await M.rpc("get_dashboard_highlights");if(t)throw t;const n=s??null;return n&&Qs(Js,n),n}function rs(){const s=Ys(Js,Ta);return K({queryKey:["dashboard-highlights"],queryFn:et,staleTime:360*6e4,gcTime:1440*6e4,refetchOnMount:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1,retry:3,retryDelay:t=>Math.min(1500*2**t,8e3),initialData:s?.data,initialDataUpdatedAt:s?.updatedAt})}const Ge=s=>Te(s,"currency"),ae=s=>Te(s,"number"),La=s=>new Date(`${s}T00:00:00`).toLocaleDateString(void 0,{month:"short",year:"2-digit"}),Ma=[{key:"price",label:"Price",fmt:Ge},{key:"monthly_sales",label:"Monthly units",fmt:ae},{key:"bsr",label:"BSR",fmt:ae},{key:"subcategory_bsr",label:"Subcat. BSR",fmt:ae},{key:"review_rating",label:"Rating",fmt:s=>s?Number(s).toFixed(1):"â"},{key:"review_count",label:"Reviews",fmt:ae},{key:"active_sellers_count",label:"Active sellers",fmt:ae},{key:"buy_box_seller",label:"Buy box",fmt:s=>s||"â"}],$a=[{key:"monthly_sales",label:"Monthly units",fmt:ae},{key:"asin_count",label:"ASINs",fmt:ae},{key:"avg_price",label:"Avg price",fmt:s=>s?`$${Number(s).toFixed(2)}`:"â"},{key:"active_sellers",label:"Active sellers",fmt:ae}],Ra=({open:s,onOpenChange:t,entityType:n,entityKey:r,entityLabel:l,pct:u})=>{O();const{openDetail:d}=wt(),{data:o,isLoading:g}=K({queryKey:["imn-drilldown",n,r],enabled:s&&!!n&&!!r,staleTime:10*6e4,queryFn:async()=>{const{data:h,error:k}=await M.rpc("get_imn_entity_drilldown",{_entity_type:n,_entity_ke
1y:r,_months:6});if(k)throw k;return h??null}}),m=o?.latest_metrics??{},b=n==="product"?Ma:$a,S=(o?.history??[]).map(h=>({month:La(h.report_month),revenue:Number(h.revenue??0)})),_=()=>{t(!1),d(n,r,l||o?.entity_label||r)};return e.jsx(Ns,{open:s,onOpenChange:t,children:e.jsxs(ws,{side:"right",className:"w-full overflow-y-auto sm:max-w-md",children:[e.jsxs(ks,{className:"text-left",children:[e.jsx(_s,{className:"pr-6 text-base leading-snug",children:l||o?.entity_label||r}),e.jsxs(Ss,{className:"flex flex-wrap items-center gap-2",children:[e.jsx(V,{variant:"secondary",className:"capitalize",children:n}),m?.asin&&e.jsx("span",{className:"font-mono text-xs",children:m.asin}),u!=null&&e.jsx(ee,{pct:u})]})]}),g?e.jsxs("div",{className:"mt-6 space-y-3",children:[e.jsx(U,{className:"h-32 w-full"}),e.jsx(U,{className:"h-24 w-full"}),e.jsx(U,{className:"h-24 w-full"})]}):e.jsxs("div",{className:"mt-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Monthly revenue trend"}),S.length>1?e.jsx("div",{className:"h-36 w-full",children:e.jsx(Ze,{width:"100%",height:"100%",children:e.jsxs(kt,{data:S,margin:{top:4,right:8,bottom:0,left:0},children:[e.jsx(Cs,{...As}),e.jsx(Xe,{dataKey:"month",tick:ms,...be}),e.jsx(Ke,{tick:ms,...be,width:48,tickFormatter:Ts}),e.jsx(Je,{formatter:_t("currency"),...Ls}),e.jsx(Ms,{type:"monotone",dataKey:"revenue",stroke:"hsl(var(--primary))",strokeWidth:2,dot:!1})]})})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Not enough monthly history yet."})]}),e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Latest month metrics"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-2",children:[e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Monthly revenue"}),e.jsx("div",{className:"text-sm font-semibold",children:Ge(m?.monthly_revenue)})]}),b.map(h=>e.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-2",children:[e.jsx("div",{className:"text-[10px] text-muted-foreground",children:h.label}),e.jsx("div",{className:"truncate text-sm font-semibold",title:String(m?.[h.key]??""),children:h.fmt(m?.[h.key])})]},h.key))]}),(m?.category||m?.subcategory)&&e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:[m?.category,m?.subcategory].filter(Boolean).join(" ⺠")})]}),n!=="product"&&e.jsxs("div",{children:[e.jsx("div",{className:"mb-2 text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Top products"}),o?.children?.length?e.jsx("ul",{className:"space-y-2",children:o.children.map((h,k)=>e.jsxs("li",{className:"rounded-lg border border-border/60 p-2 text-xs",children:[e.jsx("div",{className:"truncate font-medium",title:h.title??"",children:h.title||h.asin}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-3 gap-y-1 text-muted-foreground",children:[e.jsx("span",{className:"font-mono",children:h.asin}),e.jsxs("span",{children:[Ge(h.monthly_revenue),"/mo"]}),e.jsxs("span",{children:[ae(h.monthly_sales)," units"]}),h.price?e.jsxs("span",{children:["$",Number(h.price).toFixed(2)]}):null]})]},`${h.asin}-${k}`))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No product breakdown available."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs(C,{size:"sm",onClick:_,children:["Open full details",e.jsx(je,{className:"ml-1 h-3.5 w-3.5"})]}),m?.listing_url&&e.jsx(C,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:m.listing_url,target:"_blank",rel:"noreferrer",children:["View on Amazon",e.jsx(St,{className:"ml-1 h-3.5 w-3.5"})]})})]})]})]})})},st=s=>Math.abs(s)>=1e3?s.toLocaleString(void 0,{maximumFractionDigits:0}):String(s),tt=({children:s,left:t,className:n})=>e.jsx("span",{role:"tooltip",className:w("pointer-events-none absolute bottom-full z-30 mb-1.5 -translate-x-1/2 whitespace-nowrap rounded-md border border-border bg-popover px-2 py-1 text-[11px] leading-tight text-popover-foreground shadow-md",n),style:t!==void 0?{left
1:`${t}%`}:void 0,children:s}),ns=({series:s,accent:t="blue",className:n,filled:r=!0,labels:l,formatValue:u=st,valueLabel:d="Value"})=>{const[o,g]=y.useState(null),m=s.filter(v=>typeof v=="number"&&isFinite(v));if(m.length<2)return null;const b=Math.min(...m),_=Math.max(...m)-b||1,h=m.map((v,j)=>{const $=j/(m.length-1)*100,A=28-(v-b)/_*22-3;return[$,A]}),k=h.map(([v,j])=>`${v},${j}`).join(" "),x=`0,28 ${k} 100,28`,T=(v,j)=>{const $=j.getBoundingClientRect();if(!$.width)return;const A=Math.min(1,Math.max(0,(v-$.left)/$.width));g(Math.round(A*(m.length-1)))},f=o!==null?h[o]:null;return e.jsxs("span",{className:w("relative inline-block h-8 w-20 shrink-0 touch-pan-y",n),onPointerDown:v=>T(v.clientX,v.currentTarget),onPointerMove:v=>{v.pointerType==="mouse"&&T(v.clientX,v.currentTarget)},onPointerLeave:()=>g(null),onClick:v=>v.stopPropagation(),children:[e.jsxs("svg",{viewBox:"0 0 100 28",preserveAspectRatio:"none",className:"h-full w-full","aria-hidden":"true",children:[r&&e.jsx("polygon",{points:x,className:w("fill-current opacity-10",qe[t])}),e.jsx("polyline",{points:k,fill:"none",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:w("stroke-current",qe[t]),vectorEffect:"non-scaling-stroke"}),f&&e.jsxs(e.Fragment,{children:[e.jsx("line",{x1:f[0],x2:f[0],y1:0,y2:28,className:"stroke-current opacity-25",strokeWidth:1,vectorEffect:"non-scaling-stroke"}),e.jsx("circle",{cx:f[0],cy:f[1],r:2.5,className:w("fill-current",qe[t]),vectorEffect:"non-scaling-stroke"})]})]}),o!==null&&e.jsxs(tt,{left:Math.min(92,Math.max(8,f?.[0]??50)),children:[l?.[o]&&e.jsx("span",{className:"mr-1 text-muted-foreground",children:l[o]}),e.jsx("span",{className:"font-semibold tabular-nums",children:u(m[o])}),!l?.[o]&&e.jsx("span",{className:"ml-1 text-muted-foreground",children:d})]})]})},Pa=({previous:s,current:t,accent:n="blue",className:r,formatValue:l=st,previousLabel:u="Prev",currentLabel:d="Now"})=>{const[o,g]=y.useState(!1);if(s==null||t==null||!isFinite(s)||!isFinite(t))return null;const m=Math.max(Math.abs(s),Math.abs(t))||1,b=h=>`${Math.max(12,Math.abs(h)/m*100)}%`,S=t<s,_=s!==0?(t-s)/s*100:null;return e.jsxs("span",{className:w("relative flex h-6 w-6 shrink-0 items-end gap-[3px]",r),onPointerEnter:()=>g(!0),onPointerLeave:()=>g(!1),onPointerDown:()=>g(h=>!h),onClick:h=>h.stopPropagation(),children:[e.jsx("span",{className:"w-[7px] rounded-sm bg-muted-foreground/35",style:{height:b(s)},"aria-hidden":"true"}),e.jsx("span",{className:w("w-[7px] rounded-sm",S?"bg-destructive/70":Hs[n]),style:{height:b(t)},"aria-hidden":"true"}),o&&e.jsxs(tt,{left:50,children:[e.jsxs("span",{className:"text-muted-foreground",children:[u," "]}),e.jsx("span",{className:"font-semibold tabular-nums",children:l(s)}),e.jsx("span",{className:"mx-1 text-muted-foreground",children:"â"}),e.jsxs("span",{className:"text-muted-foreground",children:[d," "]}),e.jsx("span",{className:"font-semibold tabular-nums",children:l(t)}),_!==null&&e.jsxs("span",{className:w("ml-1 font-semibold",S?"text-destructive":"text-widget-emerald"),children:[_>=0?"+":"",_.toFixed(1),"%"]})]})]})},at=({rows:s=3,chart:t=!1})=>e.jsxs("div",{className:"w-full space-y-3",children:[t&&e.jsx(U,{className:"h-24 w-full rounded-lg"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(U,{className:"h-14 rounded-lg"}),e.jsx(U,{className:"h-14 rounded-lg"})]}),e.jsx("div",{className:"space-y-2",children:Array.from({length:s}).map((n,r)=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(U,{className:"h-4 flex-1",style:{maxWidth:`${70-r*8}%`}}),e.jsx(U,{className:"h-4 w-12 shrink-0"})]},r))})]});function rt({open:s,onOpenChange:t,title:n,description:r,columns:l,rows:u,rowKey:d,onRowClick:o,emptyMessage:g="Nothing to break down yet.",href:m,hrefLabel:b,toolbar:S}){const _=O();return e.jsx($s,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-h-[90vh] w-[calc(100vw-1.5rem)] max-w-3xl overflow-hidden p-0 sm:w-full",children:[e.jsxs(Ps,{className:"space-y-1 border-b border-border/60 p-4 sm:p-5",children:[e.jsx(Fs,{className:"text-base sm:text-lg",children:n}),r&&e.jsx(Is,{className:"text-xs sm:text-sm",children:r})]}),S&&e.jsx("div",{className:"border-b border-border/60 px-4 py-2.5 sm:px-5",children:S}),e.jsx("div",{className:"max-h-[55vh] overflow-auto px-1 sm:px-2",children:u.length===0?e.jsx("p",{className:"p-6 text-center text-sm text-muted-foreground",children:g}):e.jsxs("table",{className:"w-full border-collapse text-[12px] sm:text-sm",children:[e.jsx("thead",{className:"sticky top-0 z-10 bg-background/95 backdrop-blur",children:e.jsx("tr",{className:"text-muted-foreground",children:l.map(h=>e.jsx("th",{scope:"col",className:w("whitespace-nowrap px-3 py-2 text-left font-medium",h.align==="right"&&"text-right",h.hideOnMobile&&"hidden sm:table-cell"),children:h.header},h.key))})}),e.jsx("tbody",{children:u.map((h,k)=>e.jsx("tr",{onClick:o?()=>o(h):void 0,className:w("border-t border-border/50",o&&"cursor-pointer transition-colors hover:bg-muted/50"),children:l.map(x=>e.jsx("td",{className:w("px-3 py-2 align-middle",x.align==="right"&&"text-right tabular-nums",x.hideOnMobile&&"hidden sm:table-cell"),children:x.cell(h)},x.key))},d(h,k)))})]})}),e.jsxs("div",{className:"flex justify-end gap-2 border-t border-border/60 p-3 sm:p-4",children:[e.jsx(C,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Close"}),e.jsxs(C,{size:"sm",onClick:()=>_(m),children:[b,e.jsx(Gs,{className:"ml-1.5 h-4 w-4"})]})]})]})})}const Fa=[{id:"absolute",label:"Values",title:"Show absolute metric values"},{id:"delta",label:"Î MoM",title:"Show month-over-month change"}],$e=({mode:s,onChange:t,className:n})=>e.jsx("div",{role:"group","aria-label":"Compare mode",className:w("inline-flex shrink-0 rounded-full border border-border/60 bg-muted/40 p-0.5",n),children:Fa.map(r=>e.jsx("button",{type:"button",title:r.title,"aria-pressed":s===r.id,onClick:l=>{l.stopPropagation(),t(r.id)}
1,className:w("rounded-full px-2.5 py-1 text-[11px] font-medium transition-colors",s===r.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:r.label},r.id))}),nt="eiq:dashboard-compare-mode",De="eiq:compare-mode";function hs(){return typeof window>"u"?"absolute":window.localStorage.getItem(nt)==="delta"?"delta":"absolute"}function lt(){const[s,t]=y.useState(hs);y.useEffect(()=>{const r=()=>t(hs());return window.addEventListener(De,r),window.addEventListener("storage",r),()=>{window.removeEventListener(De,r),window.removeEventListener("storage",r)}},[]);const n=y.useCallback(r=>{try{window.localStorage.setItem(nt,r)}catch{}window.dispatchEvent(new Event(De)),t(r)},[]);return{mode:s,setMode:n,isDelta:s==="delta"}}function Ia(s){const t=s.filter(r=>typeof r=="number"&&isFinite(r)),n=[];for(let r=1;r<t.length;r++)n.push(t[r]-t[r-1]);return n}const it=(s,t)=>`${s>=0?"+":"-"}${t(Math.abs(s))}`,ot=["dashboard-tracked-asins"],ct="tracked-asins",qa=1440*6e4;async function dt(){const{data:{user:s}}=await M.auth.getUser();if(!s)return[];const{data:t,error:n}=await M.from("tracked_asins").select("id, asin, marketplace, label, status").eq("user_id",s.id).order("created_at",{ascending:!1}).limit(50);if(n)throw n;const r=t||[];return Qs(ct,r),r}function mt(){const s=Ys(ct,qa);return K({queryKey:ot,queryFn:dt,staleTime:6e4,gcTime:30*6e4,initialData:s?.data,initialDataUpdatedAt:s?.updatedAt})}const Ye={in_app_enabled:!0,email_enabled:!1,email_address:null,frequency:"instant",digest_hour:8,min_severity_pct:0},ut={instant:"Instantly (as alerts trigger)",daily:"Daily digest",weekly:"Weekly digest",off:"Pause notifications"},Re={monthly_revenue:"Revenue",monthly_sales:"Units sold",bsr:"BSR",subcategory_bsr:"Subcategory BSR",price:"Price"},ls={any:"Up or down",up:"Increase only",down:"Decrease only"},xs=s=>s==="bsr"||s==="subcategory_bsr",ht=["imn-mover-alert-rules"],xt=["imn-mover-alert-events"],pt=["imn-alert-notification-prefs"];function gt(){return K({queryKey:ht,staleTime:6e4,queryFn:async()=>{const{data:s,error:t}=await M.from("imn_mover_alert_rules").select("id, asin, metric, direction, threshold_pct, threshold_mode, threshold_abs, label, enabled, created_at").order("created_at",{ascending:!1});if(t)throw t;return s||[]}})}function ft(s=50){return K({queryKey:[...xt,s],staleTime:3e4,queryFn:async()=>{const{data:t,error:n}=await M.from("imn_mover_alert_events").select("*").order("created_at",{ascending:!1}).limit(s);if(n)throw n;return t||[]}})}function bt(){const s=es(),t=()=>{s.invalidateQueries({queryKey:ht}),s.invalidateQueries({queryKey:xt})},n=fe({mutationFn:async d=>{const{data:{user:o}}=await M.auth.getUser();if(!o)throw new Error("You must be signed in to create alerts.");const g={user_id:o.id,asin:d.asin?d.asin.trim().toUpperCase():null,metric:d.metric,direction:d.direction??"any",threshold_pct:d.threshold_pct??20,threshold_mode:d.threshold_mode??"pct",threshold_abs:d.threshold_mode==="absolute"?d.threshold_abs??null:null,label:d.label?.trim()||null,enabled:d.enabled??!0},m=d.id?M.from("imn_mover_alert_rules").update(g).eq("id",d.id):M.from("imn_mover_alert_rules").insert(g),{error:b}=await m;if(b)throw b},onSuccess:t}),r=fe({mutationFn:async d=>{const{error:o}=await M.from("imn_mover_alert_rules").delete().eq("id",d);if(o)throw o},onSuccess:t}),l=fe({mutationFn:async()=>{const{data:d,error:o}=await M.rpc("evaluate_imn_mover_alerts");if(o)throw o;return Number(d??0)},onSuccess:t}),u=fe({mutationFn:async d=>{const{error:o}=await M.rpc("mark_imn_mover_alerts_read",{_ids:d??null});if(o)throw o},onSuccess:t});return{saveRule:n,deleteRule:r,evaluate:l,markRead:u}}function Da(){return K({queryKey:pt,staleTime:6e4,queryFn:async()=>{const{data:s,error:t}=await M.from("imn_alert_notification_prefs").select("in_app_enabled, email_enabled, email_address, frequency, digest_hour, min_severity_pct").maybeSingle();if(t)throw t;return{...Ye,...s??{}}}})}function Ea(){const s=es();return fe({mutationFn:async t=>{const{data:{user:n}}=await M.auth.getUser();if(!n)throw new Error("You must be signed in to change notification settings.");const{error:r}=await M.from("imn_alert_notification_prefs").upsert({user_id:n.id,...t},{onConflict:"user_id"});if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:pt})})}function Ua(){return fe({mutationFn:async()=>{const{data:s,error:t}=await M.functions.invoke("send-mover-alert-emails",{body:{}});if(t)throw t;return s??{sent:0}}})}function Ba(){const s=gt(),t=ft(50),{evaluate:n}=bt(),r=(s.data?.length??0)>0;y.useEffect(()=>{!r||sessionStorage.getItem("eiq:mover-alerts-scanned")||(sessionStorage.setItem("eiq:mover-alerts-scanned",String(Date.now())),n.mutate())},[r]);const l=(t.data??[]).filter(u=>!u.read_at).length;return{rules:s,events:t,unread:l}}const za=Object.keys(Re),Oa=Object.keys(ls),Ka=Object.keys(ut),Wa=s=>s?new Date(`${String(s).slice(0,10)}T00:00:00Z`).toLocaleDateString(void 0,{month:"short",year:"numeric",timeZone:"UTC"}):"â",ps=(s,t)=>
1t==null?"â":s==="monthly_revenue"?`$${Number(t).toLocaleString(void 0,{maximumFractionDigits:0})}`:s==="price"?`$${Number(t).toFixed(2)}`:Number(t).toLocaleString(void 0,{maximumFractionDigits:0}),Ae=s=>s==="monthly_revenue"||s==="price"?"$":s==="monthly_sales"?"units":"ranks",gs=s=>{const t=s.threshold_mode==="absolute"?`${Ae(s.metric)==="$"?"$":""}${Number(s.threshold_abs??0).toLocaleString()}${Ae(s.metric)==="$"?"":` ${Ae(s.metric)}`}`:`${Number(s.threshold_pct)}%`;return`${Re[s.metric]} · ${ls[s.direction].toLowerCase()} ⥠${t} MoM`},Ee={id:null,asin:"__all__",metric:"monthly_revenue",direction:"any",mode:"pct",pct:"20",abs:"",label:""},Va=({open:s,onOpenChange:t})=>{const{data:n=[],isLoading:r}=gt(),{data:l=[],isLoading:u}=ft(50),{data:d=[]}=mt(),{saveRule:o,deleteRule:g,evaluate:m,markRead:b}=bt(),{data:S,isLoading:_}=Da(),h=Ea(),k=Ua(),[x,T]=y.useState(Ee),[f,v]=y.useState(null),j=f??S??Ye,$=a=>v({...f??S??Ye,...a}),A=y.useMemo(()=>l.filter(a=>!a.read_at).length,[l]),L=x.id!==null,c=async()=>{if(S?.email_enabled&&S.frequency!=="off")try{await k.mutateAsync()}catch{}},p=async()=>{const a=Number(x.pct),F=Number(x.abs);if(x.mode==="pct"&&(!isFinite(a)||a<=0||a>1e3)){X({title:"Enter a percentage threshold between 1 and 1000",variant:"destructive"});return}if(x.mode==="absolute"&&(!isFinite(F)||F<=0)){X({title:"Enter an absolute threshold greater than 0",variant:"destructive"});return}try{await o.mutateAsync({id:x.id??void 0,asin:x.asin==="__all__"?null:x.asin,metric:x.metric,direction:x.direction,threshold_mode:x.mode,threshold_pct:x.mode==="pct"?a:20,threshold_abs:x.mode==="absolute"?F:null,label:x.label});const i=await m.mutateAsync();i>0&&await c(),X({title:L?"Alert rule updated":"Alert rule created",description:i>0?`${i} matching change${i===1?"":"s"} already triggered.`:void 0}),T(Ee)}catch(i){X({title:"Couldn't save alert",description:i?.message?.includes("duplicate")?"A rule with these settings already exists.":i?.message,variant:"destructive"})}},P=async()=>{try{const a=await m.mutateAsync();a>0&&await c(),X({title:a>0?`${a} new alert${a===1?"":"s"}`:"No new threshold crossings",description:a>0?"Check the Alerts tab.":"Everything is within your thresholds."})}catch(a){X({title:"Scan failed",description:a?.message,variant:"destructive"})}},D=async()=>{if(j.email_enabled&&j.email_address&&!/^\S+@\S+\.\S+$/.test(j.email_address)){X({title:"Enter a valid email address",variant:"destructive"});return}try{await h.mutateAsync({in_app_enabled:j.in_app_enabled,email_enabled:j.email_enabled,email_address:j.email_address?.trim()||null,frequency:j.frequency,digest_hour:j.digest_hour,min_severity_pct:Number(j.min_severity_pct)||0}),v(null),X({title:"Notification preferences saved"})}catch(a){X({title:"Couldn't save preferences",description:a?.message,variant:"destructive"})}},Q=async()=>{try{const a=await k.mutateAsync();X({title:a.sent>0?`Emailed ${a.sent} alert${a.sent===1?"":"s"}`:"Nothing to send",description:a.sent>0?void 0:a.reason==="email_disabled"?"Turn on email notifications first.":a.reason==="cadence_not_due"?"Your digest window hasn't elapsed yet.":a.reason==="email_not_configured"?"Email delivery isn't configured on this project yet.":"No unsent alerts right now."})}catch(a){X({title:"Send failed",description:a?.message,variant:"destructive"})}};return e.jsx($s,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-h-[90vh] w-[calc(100vw-1.5rem)] max-w-2xl overflow-hidden p-0 sm:w-full",children:[e.jsxs(Ps,{className:"space-y-1 border-b border-border/60 p-4 sm:p-5",children:[e.jsxs(Fs,{className:"flex items-center gap-2 text-base sm:text-lg",children:[e.jsx(ss,{className:"h-4 w-4 text-widget-amber"}),"Mover alerts"]}),e.jsx(Is,{className:"text-xs sm:text-sm",children:"Get notified when your tracked ASINs cross a month-over-month threshold â revenue jumps, BSR swings, price moves."})]}),e.jsxs(Ct,{defaultValue:A>0?"alerts":"rules",className:"flex min-h-0 flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/60 px-4 py-2.5 sm:px-5",children:[e.jsxs(At,{className:"h-8",children:[e.jsxs(Pe,{value:"alerts",className:"text-xs",children:["Alerts",A>0&&e.jsx(V,{className:"ml-1.5 h-4 px-1.5 text-[10px]",variant:"destructive",children:A})]}),e.jsxs(Pe,{value:"rules",className:"text-xs",children:["Rules (",n.length,")"]}),e.jsx(Pe,{value:"notifications",className:"text-xs",children:"Notifications"})]}),e.jsxs(C,{variant:"outline",size:"sm",className:"h-8",onClick:P,disabled:m.isPending,children:[e.jsx(Tt,{className:w("mr-1.5 h-3.5 w-3.5",m.isPending&&"animate-spin")}),"Scan now"]})]}),e.jsx(Fe,{value:"alerts",className:"m-0 max-h-[55vh] overflow-auto p-4 sm:p-5",children:u?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(J,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):l.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No alerts yet. Create a rule and we'll flag the next threshold crossing."}):e.jsxs("div",{className:"space-y-2",children:[A>0&&e.jsx("div",{className:"flex justify-end",children:e.jsx(C,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>b.mutate(void 0),children:"Mark all read"})}),l.map(a=>{const F=xs(a.metric)?(a.pct??0)>0:(a.pct??0)<0;
1return e.jsxs("div",{className:w("rounded-lg border p-3 text-sm",a.read_at?"border-border/50 bg-muted/20":"border-widget-amber/40 bg-widget-amber/5"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-medium",children:a.entity_label||a.asin}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[a.asin," · ",Re[a.metric]," · ",Wa(a.report_month)]})]}),e.jsxs("span",{className:w("shrink-0 rounded-full px-2 py-0.5 text-xs font-semibold tabular-nums",F?"bg-destructive/15 text-destructive":"bg-widget-emerald/15 text-widget-emerald"),children:[(a.pct??0)>=0?"+":"",Number(a.pct??0).toFixed(1),"%"]})]}),e.jsxs("div",{className:"mt-1.5 text-[11px] tabular-nums text-muted-foreground",children:[ps(a.metric,a.previous_value)," â ",ps(a.metric,a.current_value),a.threshold_pct!=null&&e.jsxs(e.Fragment,{children:[" · threshold ",Number(a.threshold_pct),"%"]})]}),!a.read_at&&e.jsx(C,{variant:"ghost",size:"sm",className:"mt-1 h-6 px-2 text-[11px]",onClick:()=>b.mutate([a.id]),children:"Mark read"})]},a.id)})]})}),e.jsxs(Fe,{value:"rules",className:"m-0 max-h-[55vh] space-y-4 overflow-auto p-4 sm:p-5",children:[e.jsxs("div",{className:"rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:L?"Edit rule":"New rule"}),L&&e.jsxs(C,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>T(Ee),children:[e.jsx(qs,{className:"mr-1 h-3.5 w-3.5"}),"Cancel"]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Z,{className:"text-xs",children:"ASIN"}),e.jsxs(oe,{value:x.asin,onValueChange:a=>T({...x,asin:a}),children:[e.jsx(ce,{className:"h-9 text-sm",children:e.jsx(de,{})}),e.jsxs(me,{children:[e.jsx(z,{value:"__all__",children:"All tracked ASINs"}),d.map(a=>e.jsx(z,{value:a.asin,children:a.label?`${a.label} · ${a.asin}`:a.asin},a.id))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Z,{className:"text-xs",children:"Metric"}),e.jsxs(oe,{value:x.metric,onValueChange:a=>T({...x,metric:a}),children:[e.jsx(ce,{className:"h-9 text-sm",children:e.jsx(de,{})}),e.jsx(me,{children:za.map(a=>e.jsx(z,{value:a,children:Re[a]},a))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Z,{className:"text-xs",children:"Direction"}),e.jsxs(oe,{value:x.direction,onValueChange:a=>T({...x,direction:a}),children:[e.jsx(ce,{className:"h-9 text-sm",children:e.jsx(de,{})}),e.jsx(me,{children:Oa.map(a=>e.jsx(z,{value:a,children:ls[a]},a))})]}),xs(x.metric)&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:'Lower BSR is better â "increase" means the rank got worse.'})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Z,{className:"text-xs",children:"Threshold type"}),e.jsxs(oe,{value:x.mode,onValueChange:a=>T({...x,mode:a}),children:[e.jsx(ce,{className:"h-9 text-sm",children:e.jsx(de,{})}),e.jsxs(me,{children:[e.jsx(z,{value:"pct",children:"Percent change (%)"}),e.jsx(z,{value:"absolute",children:"Absolute change"})]})]})]}),x.mode==="pct"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Z,{className:"text-xs",children:"Threshold (% MoM change)"}),e.jsx(he,{type:"number",min:1,max:1e3,value:x.pct,onChange:a=>T({...x,pct:a.target.value}),className:"h-9 text-sm"})]}):e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(Z,{className:"text-xs",children:["Threshold (",Ae(x.metric)," MoM change)"]}),e.jsx(he,{type:"number",min:0,step:"any",placeholder:x.metric==="bsr"?"e.g. 500":"e.g. 5000",value:x.abs,onChange:a=>T({...x,abs:a.target.value}),className:"h-9 text-sm"})]}),e.jsxs("div",{className:"space-y-1.5 sm:col-span-2",children:[e.jsx(Z,{className:"text-xs",children:"Nickname (optional)"}),e.jsx(he,{value:x.label,placeholder:"Big revenue swings",onChange:a=>T({...x,label:a.target.value}),className:"h-9 text-sm"})]})]}),e.jsxs(C,{size:"sm",className:"mt-3 w-full sm:w-auto",onClick:p,disabled:o.isPending,children:[L?e.jsx(us,{className:"mr-1.5 h-4 w-4"}):e.jsx(ve,{className:"mr-1.5 h-4 w-4"}),L?"Save changes":"Create alert"]}),d.length===0&&e.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:'You have no tracked ASINs yet â an "all tracked ASINs" rule will start firing once you add some.'})]}),r?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(J,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):n.length===0?e.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:"No alert rules yet."}):e.jsx("ul",{className:"space-y-2",children:n.map(a=>e.jsxs("li",{className:w("flex items-center justify-between gap-3 rounded-lg border p-3",x.id===a.id?"border-primary/50 bg-primary/5":"border-border/60"),children:[e.jsxs("div",{className:"min-w-0 text-sm",children:[e.jsx("div",{className:"truncate font-medium",children:a.label||gs(a)}),e.jsxs("div",{className:"truncate text-[11px] text-muted-foreground",children:[a.asin?a.asin:"All tracked ASINs",a.label?` · ${gs(a)}`:""]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsx(Ie,{checked:a.enabled,onCheckedChange:F=>o.mutate({...a,enabled:F}),"aria-label":"Toggle alert rule"}),e.jsx(C,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-foreground","aria-label":"Edit alert rule",onClick:()=>T({id:a.id,asin:a.asin??"__all__",metric:a.metric,direction:a.direction,mode:a.threshold_mode??"pct",pct:String(a.threshold_pct??20),abs:a.threshold_abs!=null?String(a.threshold_abs):"",label:a.label??""}),children:e.jsx(Lt,{className:"h-4 w-4"})}),e.jsx(C,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>g.mutate(a.id),"aria-label":"Delete alert rule",children:e.jsx(Mt,{className:"h-4 w-4"})})]})]},a.id))})]}),e.jsx(Fe,{value:"notifications",className:"m-0 max-h-[55vh] space-y-4 overflow-auto p-4 sm:p-5",children:_?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(J,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"In-app alerts"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Show alerts in the dashboard bell and feed."})]}),e.jsx(Ie,{checked:j.in_app_enabled,onCheckedChange:a=>
1$({in_app_enabled:a}),"aria-label":"Toggle in-app alerts"})]}),e.jsxs("div",{className:"flex items-start justify-between gap-3 border-t border-border/50 pt-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-sm font-medium",children:[e.jsx(la,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email alerts"]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Send triggered alerts to your inbox."})]}),e.jsx(Ie,{checked:j.email_enabled,onCheckedChange:a=>$({email_enabled:a}),"aria-label":"Toggle email alerts"})]}),j.email_enabled&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Z,{className:"text-xs",children:"Send to"}),e.jsx(he,{type:"email",placeholder:"Your account email",value:j.email_address??"",onChange:a=>$({email_address:a.target.value}),className:"h-9 text-sm"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Leave blank to use the email on your account."})]})]}),e.jsxs("div",{className:"grid gap-3 rounded-lg border border-border/60 p-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5 sm:col-span-2",children:[e.jsx(Z,{className:"text-xs",children:"Frequency"}),e.jsxs(oe,{value:j.frequency,onValueChange:a=>$({frequency:a}),children:[e.jsx(ce,{className:"h-9 text-sm",children:e.jsx(de,{})}),e.jsx(me,{children:Ka.map(a=>e.jsx(z,{value:a,children:ut[a]},a))})]})]}),(j.frequency==="daily"||j.frequency==="weekly")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Z,{className:"text-xs",children:"Preferred hour"}),e.jsxs(oe,{value:String(j.digest_hour),onValueChange:a=>$({digest_hour:Number(a)}),children:[e.jsx(ce,{className:"h-9 text-sm",children:e.jsx(de,{})}),e.jsx(me,{className:"max-h-60",children:Array.from({length:24},(a,F)=>e.jsxs(z,{value:String(F),children:[String(F).padStart(2,"0"),":00"]},F))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(Z,{className:"text-xs",children:"Only notify above (% change)"}),e.jsx(he,{type:"number",min:0,max:1e3,value:j.min_severity_pct,onChange:a=>$({min_severity_pct:Number(a.target.value)}),className:"h-9 text-sm"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Mutes small moves even if a rule matched. 0 sends everything."})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(C,{size:"sm",onClick:D,disabled:h.isPending,children:[e.jsx(us,{className:"mr-1.5 h-4 w-4"}),"Save preferences"]}),e.jsxs(C,{variant:"outline",size:"sm",onClick:Q,disabled:k.isPending||!S?.email_enabled,children:[e.jsx(ia,{className:w("mr-1.5 h-4 w-4",k.isPending&&"animate-pulse")}),"Send pending now"]})]})]})})]})]})})},we=[{id:"product",label:"Products"},{id:"brand",label:"Brands"},{id:"seller",label:"Sellers"}],xe=s=>s?new Date(`${s}T00:00:00`).toLocaleDateString(void 0,{month:"long",year:"numeric"}):"â",ge=s=>s==null?"â":`$${Number(s).toLocaleString(void 0,{maximumFractionDigits:0})}`,ye=s=>typeof s.current=="number"&&typeof s.previous=="number"&&isFinite(s.current)&&isFinite(s.previous)?s.current-s.previous:null,Ue=s=>s===null?"â":it(s,t=>ge(t)),Ha=()=>{const{data:s,isLoading:t,isError:n}=rs(),[r,l]=y.useState("product"),u=O(),[d,o]=y.useState(null),[g,m]=y.useState(!1),[b,S]=y.useState(!1),{mode:_,setMode:h,isDelta:k}=lt(),{unread:x}=Ba(),T=s?.movers?.[r]??[],v=(s?.movers?.product??[]).filter(c=>k?ye(c)!==null:typeof c.current=="number"&&isFinite(c.current)),j=(k?v.map(ye):v.map(c=>c.current)).filter(c=>typeof c=="number"&&isFinite(c)),$=[{key:"entity",header:we.find(c=>c.id===r)?.label??"Entity",cell:c=>e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-medium",children:c.entity_label||c.entity_key}),e.jsx("div",{className:"text-[11px] text-muted-foreground",children:c.entity_key})]})},...k?[{key:"change",header:"Î vs prev",align:"right",cell:c=>{const p=ye(c);return e.jsx("span",{className:w("font-medium",p!==null&&p<0?"text-destructive":"text-widget-emerald"),children:Ue(p)})}}]:[{key:"previous",header:"Previous",align:"right",hideOnMobile:!0,cell:c=>ge(c.previous)},{key:"current",header:"Current",align:"right",cell:c=>ge(c.current)}],{key:"delta",header:"MoM %",align:"right",cell:c=>e.jsx("span",{className:"inline-flex justify-end",children:e.jsx(ee,{pct:c.pct})})}],A=Aa(s),L=n||A.state!=="ok";return e.jsxs(re,{title:"Intelligence Pulse",description:`Biggest month-over-month movers · ${xe(s?.latest_month)}`,icon:e.jsx(We,{className:"h-5 w-5"}),accent:"blue",href:"/intelligence-pulse",ctaLabel:"Explore",loading:t,loadingComponent:e.jsx(at,{rows:3}),children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-2 sm:p-2.5",children:[e.jsx("div",{className:"truncate text-[10px] leading-tight text-muted-foreground sm:text-xs",children:"New products this month"}),e.jsxs("div",{className:"mt-0.5 flex min-w-0 items-center gap-1 text-base font-semibold tabular-nums sm:text-lg",children:[e.jsx(Ds,{className:"h-3.5 w-3.5 shrink-0 text-widget-blue"}),e.jsx("span",{className:"truncate",children:(s?.new_products??0).toLocaleStr
1ing()})]})]}),e.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-2 sm:p-2.5",children:[e.jsxs("div",{className:"truncate text-[10px] leading-tight text-muted-foreground sm:text-xs",children:["Products tracked in ",xe(s?.latest_month)]}),e.jsxs("div",{className:"mt-0.5 flex min-w-0 items-center justify-between gap-1",children:[e.jsx("span",{className:"truncate text-base font-semibold tabular-nums sm:text-lg",children:(s?.product_count??0).toLocaleString()}),j.length>1&&e.jsx(ns,{series:j,labels:v.map(c=>c.entity_label||c.entity_key),formatValue:c=>k?Ue(c):ge(c),valueLabel:k?"MoM change":"Value",accent:"blue",className:"h-6 w-10 shrink-0 sm:h-7 sm:w-14"})]})]}),e.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-2 sm:p-2.5",children:[e.jsx("div",{className:"truncate text-[10px] leading-tight text-muted-foreground sm:text-xs",children:"Fastest growing category"}),e.jsxs("div",{className:"mt-0.5 flex min-w-0 items-center justify-between gap-1",children:[e.jsx("span",{className:"truncate text-sm font-semibold sm:text-base",title:s?.fastest_growing_category?.name??void 0,children:s?.fastest_growing_category?.name??"â"}),typeof s?.fastest_growing_category?.pct=="number"&&e.jsx("span",{className:"shrink-0",children:e.jsx(ee,{pct:s.fastest_growing_category.pct})})]})]}),e.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-2 sm:p-2.5",children:[e.jsx("div",{className:"truncate text-[10px] leading-tight text-muted-foreground sm:text-xs",children:"Suppliers indexed"}),e.jsxs("div",{className:"mt-0.5 flex min-w-0 items-center gap-1 text-base font-semibold tabular-nums sm:text-lg",children:[e.jsx(Ve,{className:"h-3.5 w-3.5 shrink-0 text-widget-emerald"}),e.jsx("span",{className:"truncate",children:(s?.suppliers?.total??0).toLocaleString()})]})]}),e.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-2 sm:p-2.5",children:[e.jsx("div",{className:"truncate text-[10px] leading-tight text-muted-foreground sm:text-xs",children:"New brands this month"}),e.jsxs("div",{className:"mt-0.5 flex min-w-0 items-center gap-1 text-base font-semibold tabular-nums sm:text-lg",children:[e.jsx($t,{className:"h-3.5 w-3.5 shrink-0 text-widget-violet"}),e.jsx("span",{className:"truncate",children:(s?.new_brands??0).toLocaleString()})]})]}),e.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-2 sm:p-2.5",children:[e.jsx("div",{className:"truncate text-[10px] leading-tight text-muted-foreground sm:text-xs",children:"New sellers this month"}),e.jsxs("div",{className:"mt-0.5 flex min-w-0 items-center gap-1 text-base font-semibold tabular-nums sm:text-lg",children:[e.jsx(Es,{className:"h-3.5 w-3.5 shrink-0 text-widget-amber"}),e.jsx("span",{className:"truncate",children:(s?.new_sellers??0).toLocaleString()})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("div",{className:"-mx-1 flex min-w-0 gap-1.5 overflow-x-auto px-1 pb-0.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:we.map(c=>e.jsx("button",{onClick:()=>l(c.id),className:w("shrink-0 rounded-full px-3 py-1.5 text-xs font-medium transition-colors",r===c.id?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted/70"),children:c.label},c.id))}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsx($e,{mode:_,onChange:h}),e.jsxs(C,{variant:"ghost",size:"icon",className:"relative h-8 w-8",onClick:()=>S(!0),"aria-label":"Mover alerts",title:"Mover alerts",children:[e.jsx(ss,{className:"h-4 w-4"}),x>0&&e.jsx("span",{className:"absolute -right-0.5 -top-0.5 grid h-4 min-w-4 place-items-center rounded-full bg-destructive px-1 text-[9px] font-semibold text-destructive-foreground",children:x>9?"9+":x})]})]})]}),T.length===0?e.jsxs("div",{className:"rounded-lg border border-dashed border-border/70 bg-muted/20 p-4 text-center",children:[e.jsx("div",{className:"mx-auto grid h-9 w-9 place-items-center rounded-xl bg-widget-blue/12 text-widget-blue",children:e.jsx(We,{className:"h-4 w-4"})}),e.jsx("p",{className:"mt-2 text-sm font-medium",children:L?"Movers unavailable right now":"No month-over-month movers yet"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:L?"Movers appear again once the summary refreshes successfully.":"Movers appear once two months of snapshot data exist. Browse the current month or request ASIN data in the meantime."}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:justify-center",children:[e.jsx(C,{size:"sm",onClick:()=>u("/intelligence-pulse"),children:"Browse Intelligence Pulse"}),e.jsx(C,{variant:"outline",size:"sm",onClick:()=>u("/monthly-reports?tab=tracked-asins"),children:"Request ASIN data"})]})]}):e.jsx("ul",{className:"space-y-1.5",children:T.slice(0,5).map(c=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>
1o({type:r,key:c.entity_key,label:c.entity_label,pct:c.pct}),className:"flex w-full items-center justify-between gap-2 rounded-lg border border-transparent px-2 py-2 text-left text-[13px] transition-colors hover:border-border/60 hover:bg-muted/40 sm:gap-3 sm:text-sm",title:"View details",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx(Pa,{previous:c.previous,current:c.current,accent:"blue",formatValue:p=>ge(p),previousLabel:xe(s?.previous_month).split(" ")[0],currentLabel:xe(s?.latest_month).split(" ")[0]}),e.jsx("span",{className:"min-w-0 truncate",children:c.entity_label||c.entity_key})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 sm:gap-2",children:[e.jsx("span",{className:w("hidden text-xs tabular-nums sm:inline",k?(ye(c)??0)<0?"font-medium text-destructive":"font-medium text-widget-emerald":"text-muted-foreground"),children:k?Ue(ye(c)):ge(c.current)}),e.jsx(ee,{pct:c.pct}),e.jsx(Rt,{className:"h-3.5 w-3.5 text-muted-foreground"})]})]})},`${c.entity_type}-${c.entity_key}`))}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs(C,{variant:"outline",size:"sm",className:"w-full",disabled:T.length===0,onClick:()=>m(!0),children:[e.jsx(Ve,{className:"mr-1.5 h-4 w-4"}),"View full breakdown"]}),e.jsx(C,{variant:"outline",size:"sm",className:"w-full",onClick:()=>u("/intelligence-pulse"),children:"Browse full data"})]})]}),e.jsx(Ra,{open:!!d,onOpenChange:c=>!c&&o(null),entityType:d?.type??null,entityKey:d?.key??null,entityLabel:d?.label,pct:d?.pct}),e.jsx(rt,{open:g,onOpenChange:m,title:`${we.find(c=>c.id===r)?.label??"Movers"} breakdown`,description:`Month-over-month change · ${xe(s?.previous_month)} â ${xe(s?.latest_month)}`,columns:$,rows:T,rowKey:c=>`${c.entity_type}-${c.entity_key}`,onRowClick:c=>{m(!1),o({type:r,key:c.entity_key,label:c.entity_label,pct:c.pct})},toolbar:e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsx("div",{className:"flex gap-1.5",children:we.map(c=>e.jsx("button",{onClick:()=>
1l(c.id),className:w("rounded-full px-3 py-1 text-xs font-medium transition-colors",r===c.id?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted/70"),children:c.label},c.id))}),e.jsx($e,{mode:_,onChange:h})]}),emptyMessage:"Movers appear once two months of data are available.",href:"/intelligence-pulse?tab=movers",hrefLabel:"Open Intelligence Pulse"}),e.jsx(Va,{open:b,onOpenChange:S})]})},yt=({options:s,value:t,onChange:n,placeholder:r="Select an ASIN",className:l,disabled:u})=>{const[d,o]=y.useState(!1),g=s.find(m=>m.value===t);return e.jsxs(Pt,{open:d,onOpenChange:o,children:[e.jsx(Ft,{asChild:!0,children:e.jsxs(C,{variant:"outline",role:"combobox","aria-expanded":d,disabled:u,className:w("h-9 justify-between text-xs font-normal",l),children:[e.jsx("span",{className:"truncate",children:g?.label??r}),e.jsx(oa,{className:"ml-2 h-3.5 w-3.5 shrink-0 opacity-50"})]})}),e.jsx(It,{className:"z-50 w-[--radix-popover-trigger-width] min-w-[240px] bg-popover p-0",align:"start",children:e.jsxs(ca,{filter:(m,b)=>{const S=s.find(h=>h.value===m);return`${S?.label??""} ${S?.asin??""}`.toLowerCase().includes(b.toLowerCase())?1:0},children:[e.jsx(da,{placeholder:"Search ASIN or labelâ¦",className:"h-9"}),e.jsxs(ma,{className:"max-h-64",children:[e.jsx(ua,{children:"No ASIN found."}),e.jsx(ha,{children:s.map(m=>e.jsxs(xa,{value:m.value,onSelect:()=>{n(m.value),o(!1)},className:"text-xs",children:[e.jsx(ts,{className:w("mr-2 h-3.5 w-3.5",t===m.value?"opacity-100":"opacity-0")}),e.jsx("span",{className:"truncate",children:m.label})]},m.value))})]})]})})]})},fs=s=>new Date(`${String(s).slice(0,7)}-01T00:00:00Z`).toLocaleDateString(void 0,{month:"short",year:"2-digit",timeZone:"UTC"}),Be=(s,t=2)=>s==null?"â":`$${Number(s).toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t})}`,Ga=({open:s,onOpenChange:t,asin:n,marketplace:r,label:l,history:u})=>{const d=O(),{data:o=[],isLoading:g}=K({queryKey:["drilldown-keywords",n,r],enabled:s&&!!n,staleTime:5*6e4,queryFn:async()=>{const{data:p,error:P}=await M.from("keyword_snapshots").select("id, report_month").eq("asin",n).eq("marketplace",r).order("report_month",{ascending:!1}).limit(1);if(P)throw P;const D=p?.[0]?.id;if(!D)return[];const{data:Q,error:a}=await M.from("keyword_snapshot_rows").select("keyword_phrase, search_volume, keyword_sales, organic_rank").eq("snapshot_id",D).order("keyword_sales",{ascending:!1,nullsFirst:!1}).limit(200);if(a)throw a;return Q||[]}}),{data:m=[],isLoading:b}=K({queryKey:["drilldown-offers",n,r],enabled:s&&!!n,staleTime:5*6e4,queryFn:async()=>{const{data:p,error:P}=await M.from("inventory_snapshots").select("id, report_month").eq("asin",n).eq("marketplace",r).order("report_month",{ascending:!1}).limit(1);if(P)throw P;const D=p?.[0]?.id;if(!D)return[];const{data:Q,error:a}=await M.from("inventory_offers").select("seller_name, fulfillment, stock, stock_display, price, is_buy_box").eq("snapshot_id",D).order("price",{ascending:!0,nullsFirst:!1}).limit(100);if(a)throw a;return Q||[]}}),[S,_]=y.useState(""),[h,k]=y.useState("sales"),[x,T]=y.useState(!1),[f,v]=y.useState(""),[j,$]=y.useState("all");y.useEffect(()=>{s||(_(""),k("sales"),T(!1),v(""),$("all"))},[s]);const A=y.useMemo(()=>{const p=S.trim().toLowerCase();let P=o.filter(D=>p?String(D.keyword_phrase||"").toLowerCase().includes(p):!0);return x&&(P=P.filter(D=>D.organic_rank!=null&&Number(D.organic_rank)<=10)),[...P].sort((D,Q)=>h==="volume"?Number(Q.search_volume??0)-Number(D.search_volume??0):h==="rank"?Number(D.organic_rank??1/0)-Number(Q.organic_rank??1/0):Number(Q.keyword_sales??0)-Number(D.keyword_sales??0))},[o,S,h,x]),L=y.useMemo(()=>{const p=f.trim().toLowerCase();return m.filter(P=>p&&!String(P.seller_name||"").toLowerCase().includes(p)?!1:j==="buybox"?!!P.is_buy_box:j==="instock"?Number(P.stock??0)>0:j==="fba"?String(P.fulfillment||"").toUpperCase().includes("FBA"):!0)},[m,f,j]),c=u.map(p=>({month:fs(p.month),units:p.units??0,price:p.price??null}));return e.jsx(Ns,{open:s,onOpenChange:t,children:e.jsxs(ws,{side:"right",className:"w-full overflow-y-auto sm:max-w-xl",children:[e.jsxs(ks,{className:"text-left",children:[e.jsx(_s,{className:"truncate",children:l}),e.jsxs(Ss,{children:[n," · ",r," â what drove unit sales and price"]})]}),e.jsxs("div",{className:"mt-4 space-y-6",children:[e.jsxs("section",{children:[e.jsx("h4",{className:"mb-2 text-sm font-medium",children:"Unit sales & price by month"}),c.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No monthly snapshots yet for this ASIN."}):e.jsx("div",{className:"h-52 w-full",children:e.jsx(Ze,{width:"100%",height:"100%",children:e.jsxs(ga,{data:c,margin:{top:8,right:8,left:-12,bottom:0},children:[e.jsx(Cs,{...As}),e.jsx(Xe,{dataKey:"month",tick:Ce,...be}),e.jsx(Ke,{yAxisId:"u",tick:Ce,...be,width:44,tickFormatter:qt}),e.jsx(Ke,{yAxisId:"p",orientation:"right",tick:Ce,...be,width:44,tickFormatter:Ts}),e.jsx(Je,{...Ls,formatter:(p,P)=>P==="price"?[Te(p,"currency"),"Price"]:[Te(p,"number"),"Units"]}),e.jsx(Dt,{yAxisId:"u",dataKey:"units",fill:"hsl(var(--primary))",radius:[4,4,0,0]}),e.jsx(Ms,{yAxisId:"p",type:"monotone",dataKey:"price",stroke:"hsl(var(--chart-2, var(--muted-foreground)))",strokeWidth:2,dot:!1,connectNulls:!0})]})})})]}),e.jsxs("section",{children:[e.jsx("h4",{className:"mb-2 text-sm font-medium",children:"Monthly detail"}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-border/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-muted/40 text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-3 py-2 text-left font-medium",children:"Month"}),e.jsx("th",{className:"px-3 py-2 text-right font-medium",children:"Units"}),e.jsx("th",{className:"px-3 py-2 text-right font-medium",children:"Price"}),e.jsx("th",{className:"px-3 py-2 text-right font-medium",children:"Revenue"}),e.jsx("th",{className:"px-3 py-2 text-right font-medium",children:"BSR"})]})}),e.jsxs("tbody",{children:[[...u].reverse().map(p=>e.jsxs("tr",{className:"border-t border-border/50",children:[e.jsx("td",{className:"px-3 py-2",children:fs(p.month)}),e.jsx("td",{className:"px-3 py-2 text-right",children:p.units?.toLocaleStr
1ing()??"â"}),e.jsx("td",{className:"px-3 py-2 text-right",children:Be(p.price)}),e.jsx("td",{className:"px-3 py-2 text-right",children:Be(p.revenue,0)}),e.jsx("td",{className:"px-3 py-2 text-right",children:p.bsr?.toLocaleString()??"â"})]},p.month)),u.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:5,className:"px-3 py-4 text-center text-muted-foreground",children:"No data yet."})})]})]})})]}),e.jsxs("section",{children:[e.jsx("h4",{className:"mb-2 text-sm font-medium",children:"Top keywords driving sales"}),g?e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{className:"h-4 w-2/3"}),e.jsx(U,{className:"h-4 w-1/2"})]}):o.length===0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"No keyword data yet. Request keyword tracking for this ASIN to see which terms drive units."}),e.jsxs(C,{size:"sm",variant:"outline",className:"h-8 text-xs",onClick:()=>{t(!1),d(`/monthly-reports?tab=keywords&prefillAsin=${n??""}&marketplace=${r}`)},children:["Request keyword tracking",e.jsx(je,{className:"ml-1.5 h-3.5 w-3.5"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-2 flex flex-col gap-2 sm:flex-row",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Le,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(he,{value:S,onChange:p=>_(p.target.value),placeholder:"Search keywordsâ¦",className:"h-8 pl-8 text-xs"})]}),e.jsxs(oe,{value:h,onValueChange:p=>k(p),children:[e.jsx(ce,{className:"h-8 w-full text-xs sm:w-36",children:e.jsx(de,{})}),e.jsxs(me,{children:[e.jsx(z,{value:"sales",children:"Top sales"}),e.jsx(z,{value:"volume",children:"Top volume"}),e.jsx(z,{value:"rank",children:"Best rank"})]})]}),e.jsx(C,{type:"button",size:"sm",variant:x?"default":"outline",className:"h-8 text-xs",onClick:()=>T(p=>!p),children:"Top 10 rank"})]}),A.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No keywords match these filters."}),e.jsx("ul",{className:"max-h-64 space-y-1.5 overflow-y-auto pr-1",children:A.map((p,P)=>e.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md border border-border/60 px-3 py-2 text-xs",children:[e.jsx("span",{className:"truncate",children:p.keyword_phrase}),e.jsxs("span",{className:"flex shrink-0 items-center gap-3 text-muted-foreground",children:[p.organic_rank!=null&&e.jsxs("span",{children:["#",p.organic_rank]}),e.jsxs("span",{children:[Number(p.search_volume??0).toLocaleString()," vol"]}),e.jsxs("span",{className:"font-medium text-foreground",children:[Number(p.keyword_sales??0).toLocaleString()," sales"]})]})]},P))})]})]}),e.jsxs("section",{children:[e.jsx("h4",{className:"mb-2 text-sm font-medium",children:"Competing offers affecting price"}),b?e.jsxs("div",{className:"space-y-2",children:[e.jsx(U,{className:"h-4 w-2/3"}),e.jsx(U,{className:"h-4 w-1/2"})]}):m.length===0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"No competitor inventory data yet. Request competitor inventory for this ASIN."}),e.jsxs(C,{size:"sm",variant:"outline",className:"h-8 text-xs",onClick:()=>{t(!1),d(`/monthly-reports?tab=inventory&prefillAsin=${n??""}&marketplace=${r}`)},children:["Request competitor inventory",e.jsx(je,{className:"ml-1.5 h-3.5 w-3.5"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-2 flex flex-col gap-2 sm:flex-row",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Le,{className:"absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),e.jsx(he,{value:f,onChange:p=>v(p.target.value),placeholder:"Search sellersâ¦",className:"h-8 pl-8 text-xs"})]}),e.jsxs(oe,{value:j,onValueChange:p=>$(p),children:[e.jsx(ce,{className:"h-8 w-full text-xs sm:w-36",children:e.jsx(de,{})}),e.jsxs(me,{children:[e.jsx(z,{value:"all",children:"All offers"}),e.jsx(z,{value:"buybox",children:"Buy Box only"}),e.jsx(z,{value:"instock",children:"In stock"}),e.jsx(z,{value:"fba",children:"FBA only"})]})]})]}),L.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No offers match these filters."}),e.jsx("ul",{className:"max-h-64 space-y-1.5 overflow-y-auto pr-1",children:L.map((p,P)=>e.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md border border-border/60 px-3 py-2 text-xs",children:[e.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:"truncate",children:p.seller_name||"Unknown seller"}),p.is_buy_box&&e.jsx(V,{variant:"secondary",className:"text-[10px]",children:"Buy Box"})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-3 text-muted-foreground",children:[p.fulfillment&&e.jsx("span",{children:p.fulfillment}),e.jsx("span",{children:p.stock_display??(p.stock!=null?`${p.stock} units`:"â")}),e.jsx("span",{className:"font-medium text-foreground",children:Be(p.price)})]})]},P))})]})]}),e.jsxs(C,{className:"w-full",variant:"outline",onClick:()=>d(`/monthly-reports?tab=tracked-asins&highlightAsin=${encodeURIComponent(n||"")}`),children:["Open full report",e.jsx(je,{className:"ml-1.5 h-4 w-4"})]})]})]})})},B={asin:"B0BSHF7WHW",label:"Stainless Steel Water Bottle 32oz",marketplace:"US",trend:{revenue:184320,pct:12.4,bsr:1284,bsrPrev:1420,units:6240,unitsPct:8.1,price:29.54,pricePct:-2.3,prevRevenue:174314,prevUnits:5772,prevPrice:30.2,history:[{month:"2026-03-01",units:4820,price:30.9,revenue:148938,bsr:1890},{month:"2026-04-01",units:5310,price:30.4,revenue:161424,bsr:1642},{month:"2026-05-01",units:5772,price:30.2,revenue:174314,bsr:1420},{month:"2026-06-01",units:6240,price:29.54,revenue:184320,bsr:1284}]}},ke=s=>{const t=new URLSearchParams({tab:"tracked-asins"});return s&&(t.set("prefillAsin",s.asin),t.set("prefillMarketplace",s.marketplace),t.set("prefillLabel",s.label)),`/monthly-reports?${t.toString()}`},pe=s=>
1s==null?"â":`$${Number(s).toLocaleString(void 0,{maximumFractionDigits:0})}`,_e=s=>s==null?"â":`$${Number(s).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}`,G=s=>s==null||s===""?null:Number(s),ze=(s,t)=>s!=null&&t!=null&&t!==0?(s-t)/t*100:null,Ya=({active:s,payload:t})=>{if(!s||!t?.length)return null;const n=t[0].payload,r=(n.pct??0)>=0;return e.jsxs("div",{className:"rounded-lg border border-border bg-popover px-3 py-2 text-xs text-popover-foreground shadow-md",children:[e.jsx("div",{className:"font-medium",children:n.fullMonth}),e.jsxs("div",{className:"mt-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Units "}),e.jsx("span",{className:"font-semibold",children:n.units.toLocaleString()})]}),n.pct===null?e.jsx("div",{className:"mt-0.5 text-muted-foreground",children:"No prior month to compare"}):e.jsxs("div",{className:`mt-0.5 flex items-center gap-1 ${r?"text-emerald-500":"text-red-500"}`,children:[r?e.jsx(as,{className:"h-3 w-3"}):e.jsx(Ut,{className:"h-3 w-3"}),r?"+":"",n.pct.toFixed(1),"% MoM",e.jsxs("span",{className:"text-muted-foreground",children:["(",r?"+":"",(n.units-(n.prevUnits??0)).toLocaleString()," vs ",n.prevUnits?.toLocaleString(),")"]})]})]})},te=(s,t)=>s==null||!isFinite(s)?"â":it(s,t),Y=(s,t)=>s!=null&&t!=null&&isFinite(s)&&isFinite(t)?s-t:null,le=(s,t=!1)=>s===null?"":(t?s<=0:s>=0)?"text-widget-emerald":"text-destructive",Qa=()=>{const s=O(),{data:t}=Zs(),{mode:n,setMode:r,isDelta:l}=lt(),{data:u=[],isLoading:d}=mt(),o=u.map(i=>`${i.marketplace||"US"}:${i.asin}`),{data:g={},isLoading:m}=K({queryKey:["dashboard-tracked-asin-trends",o],enabled:o.length>0,staleTime:5*6e4,queryFn:async()=>{const i={},{data:R,error:E}=await M.from("intelligence_monthly_snapshots").select("entity_key, report_month, metrics").eq("entity_type","product").in("entity_key",o).order("report_month",{ascending:!1}).limit(120);if(E)throw E;const N=new Map;return(R||[]).forEach(I=>{const q=N.get(I.entity_key)||[];q.push(I),N.set(I.entity_key,q)}),N.forEach((I,q)=>{const W=I[0]?.metrics||{},ne=I[1]?.metrics||{},H=G(W.monthly_revenue),Ne=G(ne.monthly_revenue),is=G(W.monthly_unit_sales??W.monthly_sales),os=G(ne.monthly_unit_sales??ne.monthly_sales),cs=G(W.price),ds=G(ne.price),jt=[...I].sort((se,vt)=>String(se.report_month).localeCompare(String(vt.report_month))).slice(-6).map(se=>({month:se.report_month,units:G(se.metrics?.monthly_unit_sales??se.metrics?.monthly_sales),price:G(se.metrics?.price),revenue:G(se.metrics?.monthly_revenue),bsr:G(se.metrics?.bsr),buyBoxSeller:se.metrics?.buy_box_seller??null}));i[q]={history:jt,revenue:H,bsr:G(W.bsr),bsrPrev:G(ne.bsr),pct:ze(H,Ne),units:is,unitsPct:ze(is,os),price:cs,pricePct:ze(cs,ds),prevRevenue:Ne,prevUnits:os,prevPrice:ds}}),i}}),b=u.length>0,S=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches,[_,h]=y.useState(null),[k,x]=y.useState(null),T=d||m,f=(i,R)=>{k||(x(i),s(R))},v=y.useRef([]),j=i=>{const R=i.touches[0];if(!R)return;const E=i.currentTarget.getBoundingClientRect(),N=(R.clientX-E.left)/E.width,I=Math.min(v.current.length-1,Math.max(0,Math.round(N*(v.current.length-1))));Number.isFinite(I)&&h(I)},[$,A]=y.useState("all"),[L,c]=y.useState(null),[p,P]=y.useState(!1),D=y.useMemo(()=>u.map(i=>{const R=`${i.marketplace||"US"}:${i.asin}`;return{row:i,key:R,trend:g[R]}}),[u,g]),Q=[{key:"asin",header:"ASIN",cell:({row:i})=>e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate font-medium",children:i.label||i.asin}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[i.asin," · ",i.marketplace||"US"]})]})},{key:"revenue",header:l?"Revenue Î":"Revenue",align:"right",cell:({trend:i})=>{const R=Y(i?.revenue,i?.prevRevenue);return e.jsxs("span",{className:"inline-flex items-center justify-end gap-1.5",children:[l?e.jsx("span",{className:w("font-medium",le(R)),children:te(R,E=>pe(E))}):pe(i?.revenue??null),e.jsx(ee,{pct:i?.pct??null})]})}},{key:"units",header:l?"Units Î":"Units",align:"right",hideOnMobile:!0,cell:({trend:i})=>{const R=Y(i?.units,i?.prevUnits);return e.jsxs("span",{className:"inline-flex items-center justify-end gap-1.5",children:[l?e.jsx("span",{className:w("font-medium",le(R)),children:te(R,E=>
1E.toLocaleString())}):i?.units?.toLocaleString()??"â",e.jsx(ee,{pct:i?.unitsPct??null})]})}},{key:"price",header:l?"Price Î":"Price",align:"right",hideOnMobile:!0,cell:({trend:i})=>{const R=Y(i?.price,i?.prevPrice);return l?e.jsx("span",{className:w("font-medium",le(R)),children:te(R,E=>_e(E))}):_e(i?.price??null)}},{key:"bsr",header:l?"BSR Î":"BSR",align:"right",hideOnMobile:!0,cell:({trend:i})=>{const R=Y(i?.bsr,i?.bsrPrev);return l?e.jsx("span",{className:w("font-medium",le(R,!0)),children:te(R,E=>E.toLocaleString())}):i?.bsr?.toLocaleString()??"â"}},{key:"status",header:"Status",align:"right",cell:({row:i})=>e.jsx(V,{variant:"outline",className:"text-[10px] capitalize",children:i.status||"approved"})}],a=y.useMemo(()=>$==="all"?u.slice(0,3):u.filter(i=>`${i.marketplace||"US"}:${i.asin}`===$),[u,$]),F=y.useMemo(()=>{const i=b?a.map(N=>g[`${N.marketplace||"US"}:${N.asin}`]?.history||[]):[B.trend.history],R=new Map;i.forEach(N=>N.forEach(I=>{I.units!=null&&R.set(I.month,(R.get(I.month)||0)+I.units)}));const E=Array.from(R.entries()).sort((N,I)=>N[0].localeCompare(I[0])).slice(-6);return E.map(([N,I],q)=>{const W=q>0?E[q-1][1]:null;return{month:new Date(`${String(N).slice(0,7)}-01T00:00:00Z`).toLocaleDateString(void 0,{month:"short",timeZone:"UTC"}),fullMonth:new Date(`${String(N).slice(0,7)}-01T00:00:00Z`).toLocaleDateString(void 0,{month:"long",year:"numeric",timeZone:"UTC"}),units:I,prevUnits:W,pct:W?(I-W)/W*100:null}})},[b,a,g]);return v.current=F,e.jsxs(re,{title:"Monthly Performance Reports",description:t?`${t.remaining} of ${t.credit_limit} report credits left this month`:"Track ASIN revenue, keywords and competitor inventory",icon:e.jsx(Me,{className:"h-5 w-5"}),accent:"violet",href:"/monthly-reports",ctaLabel:"Open reports",loading:d,loadingComponent:e.jsx(at,{rows:2,chart:!0}),children:[e.jsxs("div",{className:"space-y-3",children:[b&&e.jsxs("div",{className:"reports-controls",children:[e.jsx("style",{children:` 2 .reports-controls { container-type: inline-size; } 3 @container (max-width: 400px) { 4 .reports-controls .manage-btn-text { display: none; } 5 .reports-controls .manage-btn { padding-left: 0.5rem; padding-right: 0.5rem; } 6 .reports-controls .manage-btn svg { margin-right: 0 !important; } 7 } 8 `}),e.jsxs("div",{className:"flex flex-row gap-2",children:[e.jsx(yt,{className:"min-w-0 flex-1",value:$,onChange:A,options:[{value:"all",label:`All tracked ASINs (${u.length})`,asin:""},...u.map(i=>({value:`${i.marketplace||"US"}:${i.asin}`,label:`${i.label||i.asin} · ${i.asin}`,asin:i.asin}))]}),e.jsx(Us,{children:e.jsxs(Bs,{children:[e.jsx(zs,{asChild:!0,children:e.jsx(pa,{trigger:e.jsxs(C,{variant:"outline",size:"sm",className:"manage-btn shrink-0",disabled:T,children:[T?e.jsx(J,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(fa,{className:"h-4 w-4 mr-1.5"}),e.jsx("span",{className:"manage-btn-text",children:"Manage tracked ASINs"})]})})}),e.jsx(Os,{side:"top",children:"Manage tracked ASINs"})]})})]})]}),F.length>1&&e.jsxs("div",{className:"rounded-lg border border-border/60 p-2.5 sm:p-3",children:[e.jsxs("div",{className:"mb-1 flex flex-wrap items-baseline justify-between gap-x-2 gap-y-0.5",children:[e.jsx("span",{className:"text-xs font-medium sm:text-sm",children:"Unit sales trend"}),e.jsxs("span",{className:"truncate text-[11px] text-muted-foreground sm:text-xs",children:[b?$==="all"?"All tracked ASINs":$.split(":")[1]:"Sample data"," ","· last ",F.length," months"]})]}),e.jsx("div",{className:"h-24 w-full touch-pan-y sm:h-28",onTouchStart:i=>j(i),onTouchMove:i=>j(i),children:e.jsx(Ze,{width:"100%",height:"100%",children:e.jsxs(ba,{data:F,margin:{top:4,right:4,left:4,bottom:0},onClick:i=>{i?.activeTooltipIndex!=null&&h(i.activeTooltipIndex)},onMouseLeave:()=>!S&&h(null),style:{touchAction:"pan-y"},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"unitsTrendFill",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.35}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:0})]})}),e.jsx(Xe,{dataKey:"month",tick:Ce,...be,interval:"preserveStartEnd",minTickGap:12}),e.jsx(Je,{cursor:{stroke:"hsl(var(--border))"},content:e.jsx(Ya,{}),trigger:S?"click":"hover",wrapperStyle:{zIndex:20}}),e.jsx(ya,{type:"monotone",dataKey:"units",stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#unitsTrendFill)"}),_!==null&&F[_]&&e.jsx(Et,{x:F[_].month,y:F[_].units,r:4,fill:"hsl(var(--primary))",stroke:"hsl(var(--background))",strokeWidth:2,isFront:!0})]})})}),_!==null&&F[_]?e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2 rounded-md bg-muted/50 px-2.5 py-1.5 text-[11px]",children:[e.jsxs("span",{className:"flex flex-wrap items-center gap-x-2 gap-y-0.5",children:[e.jsx("span",{className:"font-medium",children:F[_].fullMonth}),e.jsxs("span",{className:"text-muted-foreground",children:[F[_].units.toLocaleStr
8ing()," units"]}),F[_].pct!==null&&e.jsxs("span",{className:F[_].pct>=0?"text-emerald-500":"text-red-500",children:[F[_].pct>=0?"+":"",F[_].pct.toFixed(1),"% MoM"]})]}),e.jsx("button",{type:"button","aria-label":"Clear pinned month",className:"shrink-0 rounded p-0.5 text-muted-foreground hover:text-foreground",onClick:()=>h(null),children:e.jsx(qs,{className:"h-3.5 w-3.5"})})]}):e.jsx("p",{className:"mt-2 text-[10px] text-muted-foreground sm:hidden",children:"Tap a month to pin exact units and MoM change."})]}),!b&&e.jsxs("div",{className:"rounded-lg border border-dashed border-border/70 bg-muted/20 p-4 text-center",children:[e.jsx("div",{className:"mx-auto grid h-9 w-9 place-items-center rounded-xl bg-widget-violet/12 text-widget-violet",children:e.jsx(Me,{className:"h-4.5 w-4.5"})}),e.jsx("p",{className:"mt-2 text-sm font-medium",children:"No ASINs tracked yet"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Track an ASIN to get monthly revenue, units, price and BSR reports. Preview below uses sample data."}),e.jsxs("div",{className:"mt-3 flex flex-wrap justify-center gap-2",children:[e.jsxs(C,{size:"sm",className:"min-w-[150px] flex-1 sm:flex-none",disabled:k==="track-first"||T,onClick:()=>f("track-first",ke({asin:B.asin,marketplace:B.marketplace,label:B.label})),children:[k==="track-first"?e.jsx(J,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(ve,{className:"mr-1.5 h-4 w-4"}),"Track your first ASIN"]}),e.jsxs(C,{variant:"outline",size:"sm",className:"min-w-[150px] flex-1 sm:flex-none",disabled:k==="see-how"||T,onClick:()=>f("see-how","/monthly-reports"),children:[k==="see-how"&&e.jsx(J,{className:"mr-1.5 h-4 w-4 animate-spin"}),"See how reports work"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:"Tracked ASINs"}),e.jsx($e,{mode:n,onChange:r})]}),e.jsx("ul",{className:"space-y-2",children:(b?a:[null]).map((i,R)=>{const E=i?`${i.marketplace||"US"}:${i.asin}`:"sample",N=i?g[E]:B.trend,I=i?i.label||i.asin:B.label;return e.jsxs("li",{role:"button",tabIndex:0,onClick:()=>c({asin:i?i.asin:B.asin,marketplace:i?i.marketplace||"US":B.marketplace,label:I,history:N?.history||[]}),onKeyDown:q=>{(q.key==="Enter"||q.key===" ")&&(q.preventDefault(),c({asin:i?i.asin:B.asin,marketplace:i?i.marketplace||"US":B.marketplace,label:I,history:N?.history||[]}))},className:"cursor-pointer rounded-lg border border-border/60 p-2.5 transition-colors hover:border-primary/50 hover:bg-muted/40 sm:p-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 sm:gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"truncate text-[13px] font-medium sm:text-sm",children:I}),e.jsx("div",{className:"text-[11px] text-muted-foreground sm:text-xs",children:i?i.asin:B.asin})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[(()=>{const q=(N?.history??[]).filter(H=>typeof H.revenue=="number"&&isFinite(H.revenue)),W=q.map(H=>H.revenue),ne=q.map(H=>new Date(`${String(H.month).slice(0,7)}-01T00:00:00Z`).toLocaleDateString(void 0,{month:"short",year:"2-digit",timeZone:"UTC"}));return e.jsx(ns,{series:l?Ia(W):W,labels:l?ne.slice(1):ne,formatValue:H=>l?te(H,Ne=>pe(Ne)):pe(H),valueLabel:l?"revenue Î":"revenue",accent:"violet",className:"h-7 w-14 sm:w-20"})})(),i?i.status&&i.status!=="approved"?e.jsx(V,{variant:"outline",className:"shrink-0 text-[10px] capitalize",children:i.status}):null:e.jsx(V,{variant:"secondary",className:"shrink-0 text-[10px]",children:"Sample"})]})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-x-3 gap-y-1 text-[11px] text-muted-foreground sm:flex sm:flex-wrap sm:items-center sm:gap-x-4 sm:text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:["Revenue"," ",e.jsx("span",{className:w("font-medium tabular-nums",l?le(Y(N?.revenue,N?.prevRevenue)):"text-foreground"),children:l?te(Y(N?.revenue,N?.prevRevenue),q=>pe(q)):pe(N?.revenue??null)}),e.jsx(ee,{pct:N?.pct??null})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:["Units"," ",e.jsx("span",{className:w("font-medium tabular-nums",l?le(Y(N?.units,N?.prevUnits)):"text-foreground"),children:l?te(Y(N?.units,N?.prevUnits),q=>
8q.toLocaleString()):N?.units?.toLocaleString()??"â"}),e.jsx(ee,{pct:N?.unitsPct??null})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:["Price"," ",e.jsx("span",{className:w("font-medium tabular-nums",l?le(Y(N?.price,N?.prevPrice)):"text-foreground"),children:l?te(Y(N?.price,N?.prevPrice),q=>_e(q)):_e(N?.price??null)}),e.jsx(ee,{pct:N?.pricePct??null})]}),e.jsxs("span",{children:["BSR"," ",e.jsx("span",{className:w("font-medium tabular-nums",l?le(Y(N?.bsr,N?.bsrPrev),!0):"text-foreground"),children:l?te(Y(N?.bsr,N?.bsrPrev),q=>q.toLocaleString()):N?.bsr?.toLocaleString()??"â"})]})]})]},i?.id??R)})}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs(C,{variant:"outline",size:"sm",className:"w-full min-w-0 justify-center px-2 text-xs sm:text-sm",disabled:k==="track-another"||T,onClick:()=>f("track-another",b?ke():ke({asin:B.asin,marketplace:B.marketplace,label:B.label})),children:[k==="track-another"?e.jsx(J,{className:"mr-1.5 h-4 w-4 shrink-0 animate-spin"}):e.jsx(ve,{className:"mr-1.5 h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:b?"Track another ASIN":"Track your first ASIN"})]}),e.jsxs(C,{variant:"outline",size:"sm",className:"w-full min-w-0 justify-center px-2 text-xs sm:text-sm",disabled:!b||m,onClick:()=>P(!0),children:[m?e.jsx(J,{className:"mr-1.5 h-4 w-4 shrink-0 animate-spin"}):e.jsx(Ve,{className:"mr-1.5 h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:"View full breakdown"})]})]}),!b&&e.jsxs("p",{className:"text-[11px] text-muted-foreground text-center",children:["Opens the tracking form prefilled with ",B.asin," (US) â just hit Track ASIN."]})]}),e.jsx(Ga,{open:!!L,onOpenChange:i=>!i&&c(null),asin:L?.asin??null,marketplace:L?.marketplace??"US",label:L?.label??"",history:L?.history??[]}),e.jsx(rt,{open:p,onOpenChange:P,title:"Tracked ASIN breakdown",description:`${u.length} tracked ASIN${u.length===1?"":"s"} · latest monthly snapshot`,columns:Q,rows:D,rowKey:i=>i.key,onRowClick:({row:i,trend:R})=>{P(!1),c({asin:i.asin,marketplace:i.marketplace||"US",label:i.label||i.asin,history:R?.history||[]})},toolbar:e.jsx($e,{mode:n,onChange:r}),emptyMessage:"Track an ASIN to populate this table.",href:ke(),hrefLabel:"Open Monthly Reports"})]})},ie="all",ue="B0BSHF7WHW",Za=[{keyword_phrase:"stainless steel water bottle",search_volume:74200,keyword_sales:2380,organic_rank:3,asin:ue},{keyword_phrase:"insulated water bottle 32 oz",search_volume:31500,keyword_sales:1140,organic_rank:5,asin:ue},{keyword_phrase:"water bottle with straw",search_volume:58900,keyword_sales:920,organic_rank:8,asin:ue},{keyword_phrase:"metal water bottle",search_volume:27100,keyword_sales:640,organic_rank:12,asin:ue}],Xa=()=>{const s=O(),[t,n]=y.useState(ie),[r,l]=y.useState(null),{data:u,isLoading:d}=K({queryKey:["dashboard-keyword-tracking"],staleTime:6e4,queryFn:async()=>{const{data:{user:f}}=await M.auth.getUser();if(!f)return null;const{data:v}=await M.from("keyword_asin_requests").select("id, asin, label, marketplace, status, user_seen_at, created_at").order("created_at",{ascending:!1}).limit(50),j=v??[],$=j.filter(L=>L.status==="fulfilled"),A=j.filter(L=>(L.status==="fulfilled"||L.status==="rejected")&&!L.user_seen_at).length;return{total:j.length,pending:j.filter(L=>L.status==="pending").length,fulfilled:$,fulfilledCount:$.length,unseen:A}}}),o=u?.fulfilled??[];y.useEffect(()=>{t!==ie&&!o.some(f=>f.asin===t)&&n(ie)},[o,t]);const g=y.useMemo(()=>o.find(f=>f.asin===t)??null,[o,t]),m=y.useMemo(()=>t===ie?o:g?[g]:[],[t,o,g]),{data:b,isFetching:S}=K({queryKey:["dashboard-keyword-tracking-rows",m.map(f=>`${f.marketplace??"US"}:${f.asin}`).join(",")],enabled:m.length>0,staleTime:6e4,queryFn:async()=>{const f=m.slice(0,10),j=(await Promise.all(f.map(async A=>{const{data:L}=await M.from("keyword_snapshots").select("id").eq("asin",A.asin).eq("marketplace",A.marketplace??"US").order("report_month",{ascending:!1}).limit(1),c=L?.[0]?.id;if(!c)return[];const{data:p}=await M.from("keyword_snapshot_rows").select("keyword_phrase, search_volume, keyword_sales, organic_rank").eq("snapshot_id",c).order("keyword_sales",{ascending:!1,nullsFirst:!1}).limit(10);return(p??[]).map(P=>({...P,asin:A.asin}))}))).flat();if(t!==ie)return j.slice(0,4);const $=new Map;for(const A of j){const L=(A.keyword_phrase||"").toLowerCase(),c=$.get(L);
8c?(c.keyword_sales=(c.keyword_sales??0)+(A.keyword_sales??0),c.search_volume=Math.max(c.search_volume??0,A.search_volume??0),A.organic_rank!=null&&(c.organic_rank=c.organic_rank==null?A.organic_rank:Math.min(c.organic_rank,A.organic_rank)),A.asin&&c.asins.add(A.asin)):$.set(L,{...A,asins:new Set(A.asin?[A.asin]:[])})}return Array.from($.values()).sort((A,L)=>(L.keyword_sales??0)-(A.keyword_sales??0)).slice(0,4)}}),_=f=>s(`/monthly-reports?tab=keywords${f?`&prefillAsin=${f}`:""}`),h=(f,v)=>{r||(l(f),s(v))},k=f=>{const v=new URLSearchParams({tab:"keywords"});return f&&(v.set("prefillAsin",f.asin),v.set("prefillMarketplace",f.marketplace),v.set("prefillLabel",f.label)),`/monthly-reports?${v.toString()}`},x=!d&&!S&&!!u&&u.fulfilledCount===0&&!u.pending&&!b?.length,T=b?.length?b:x?Za:null;return e.jsx(re,{title:"Track ASIN Keywords",description:"See which search terms drive units for the ASINs you track",icon:e.jsx(Le,{className:"h-5 w-5"}),accent:"amber",href:"/monthly-reports?tab=keywords",ctaLabel:"Open keywords",loading:d,children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"keyword-controls",children:[e.jsx("style",{children:` 9 .keyword-controls { container-type: inline-size; } 10 @container (max-width: 400px) { 11 .keyword-controls .manage-btn-text { display: none; } 12 .keyword-controls .manage-btn { padding-left: 0.5rem; padding-right: 0.5rem; } 13 .keyword-controls .manage-btn svg { margin-right: 0 !important; } 14 } 15 `}),e.jsxs("div",{className:"flex flex-row gap-2",children:[e.jsx(yt,{className:"min-w-0 flex-1",value:t,onChange:n,disabled:!o.length,placeholder:o.length?"Select an ASIN":"No keyword data yet",options:[{value:ie,label:`All ASINs (${o.length})`,asin:""},...o.map(f=>({value:f.asin,label:f.label?`${f.label} · ${f.asin}`:f.asin,asin:f.asin}))]}),e.jsx(Us,{children:e.jsxs(Bs,{children:[e.jsx(zs,{asChild:!0,children:e.jsxs(C,{variant:"outline",size:"sm",className:"manage-btn shrink-0",onClick:()=>s("/monthly-reports?tab=keywords"),children:[e.jsx(ja,{className:"mr-1.5 h-4 w-4"}),e.jsx("span",{className:"manage-btn-text",children:"Manage keywords"})]})}),e.jsx(Os,{side:"top",children:"Manage keywords"})]})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Tracked ASINs"}),e.jsx("div",{className:"text-xl font-semibold",children:u?.total??0})]}),e.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Data ready"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xl font-semibold",children:u?.fulfilledCount??0}),!!u?.unseen&&e.jsxs(V,{className:"bg-emerald-600 hover:bg-emerald-600 text-[10px]",children:[u.unseen," new"]})]})]})]}),u?.total===0&&e.jsxs("div",{className:"rounded-lg border border-dashed border-border/70 bg-muted/20 p-4 text-center",children:[e.jsx("div",{className:"mx-auto grid h-9 w-9 place-items-center rounded-xl bg-widget-amber/12 text-widget-amber",children:e.jsx(Me,{className:"h-4.5 w-4.5"})}),e.jsx("p",{className:"mt-2 text-sm font-medium",children:"No ASINs tracked yet"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Track an ASIN to get keyword ranking, search volume and keyword sales reports. Preview below uses sample data."}),e.jsxs("div",{className:"mt-3 flex flex-wrap justify-center gap-2",children:[e.jsxs(C,{size:"sm",className:"min-w-[150px] flex-1 sm:flex-none",disabled:r==="track-first-keywords"||d,onClick:()=>h("track-first-keywords",k({asin:ue,marketplace:"US",label:"Stainless Steel Water Bottle 32oz"})),children:[r==="track-first-keywords"?e.jsx(J,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(ve,{className:"mr-1.5 h-4 w-4"}),"Track your first ASIN"]}),e.jsxs(C,{variant:"outline",size:"sm",className:"min-w-[150px] flex-1 sm:flex-none",disabled:r==="see-how-keywords"||d,onClick:()=>h("see-how-keywords","/monthly-reports?tab=keywords"),children:[r==="see-how-keywords"&&e.jsx(J,{className:"mr-1.5 h-4 w-4 animate-spin"}),"See how reports work"]})]})]}),x&&u?.total!==0&&e.jsxs("div",{className:"rounded-lg border border-dashed border-amber-500/30 bg-amber-500/5 p-3",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"No keyword tracking requests yet"}),e.jsx("p",{className:"mt-1 text-xs leading-relaxed text-muted-foreground",children:"Submit any ASIN and marketplace (e.g., B0BSHF7WHW · US). Weâll pull the top search terms, search volume, keyword sales, and organic rank. Data is usually ready within 24â48 hours, and youâll be notified as soon as it lands."})]}),x&&e.jsx("div",{className:"flex items-center justify-end",children:e.jsx(V,{variant:"secondary",className:"text-[10px]",children:"Sample preview"})}),T?.length?e.jsx("div",{className:"space-y-1.5",children:T.map((f,v)=>e.jsxs("button",{type:"button",onClick:()=>_(x?ue:t===ie?f.asin:g?.asin),className:"w-full rounded-lg border border-border/60 px-3 py-2 text-left hover:border-primary/40",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"truncate text-sm font-medium",children:f.keyword_phrase}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[x&&e.jsx(V,{variant:"secondary",className:"text-[10px]",children:"Sample"}),f.organic_rank!=null&&e.jsxs(V,{variant:"secondary",className:"text-[10px]",children:["Rank #",f.organic_rank]})]})]}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Sales"," ",e.jsx("span",{className:"font-medium text-foreground",children:Number(f.keyword_sales??0).toLocaleStr
15ing()})]}),e.jsxs("span",{children:["Volume"," ",e.jsx("span",{className:"font-medium text-foreground",children:Number(f.search_volume??0).toLocaleString()})]}),t===ie&&e.jsx("span",{className:"truncate",children:f.asins&&f.asins.size>1?`${f.asins.size} ASINs`:f.asin})]})]},v))}):S?e.jsx(He,{children:"Loading keywordsâ¦"}):u?.pending?e.jsxs(He,{children:[u.pending," keyword request",u.pending>1?"s":""," in progress â weâll notify you when the data lands (typically 24â48 hours)."]}):null,e.jsxs(C,{variant:"outline",size:"sm",className:"w-full",onClick:()=>_(x?ue:void 0),children:[e.jsx(ve,{className:"mr-1.5 h-3.5 w-3.5"}),x?"Track your first ASIN keywords":"Request keyword tracking"]}),x&&e.jsxs("p",{className:"text-center text-[11px] text-muted-foreground",children:["The rows above are a sample preview. Click the button to open the form prefilled with ",ue," (US)."]})]})})},Ja=["What are the fastest growing keywords this month?","Which brands gained the most revenue month over month?","Show me top products under $30 by monthly sales"],er=()=>{const s=O(),{data:t}=Xs(),{data:n,isLoading:r}=K({queryKey:["dashboard-recent-thread"],staleTime:6e4,queryFn:async()=>{const{data:{user:l}}=await M.auth.getUser();if(!l)return null;const{data:u,error:d}=await M.from("ai_chat_threads").select("id, title, updated_at").eq("user_id",l.id).order("updated_at",{ascending:!1}).limit(1);if(d)throw d;return u&&u[0]||null}});return e.jsx(re,{title:"AI Assistant",description:t?`${Math.max(t.query_limit-t.query_count,0)} AI queries left this month`:"Ask questions about the data in plain English",icon:e.jsx(Ks,{className:"h-5 w-5"}),accent:"rose",href:"/ai-assistant",ctaLabel:"Open chat",loading:r,children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"space-y-1.5",children:Ja.map(l=>e.jsx("button",{onClick:()=>s(`/ai-assistant?q=${encodeURIComponent(l)}`),className:"w-full rounded-lg border border-border/60 px-3 py-2 text-left text-xs hover:border-primary/50 hover:bg-muted/40 transition-colors",children:l},l))}),n&&e.jsxs("button",{onClick:()=>s(`/ai-assistant/${n.id}`),className:"flex w-full items-center gap-2 text-xs text-muted-foreground hover:text-foreground",children:[e.jsx(va,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:["Resume: ",n.title||"Untitled chat"]})]})]})})},sr=()=>{const s=O(),{data:t,isLoading:n}=rs(),r=t?.suppliers?.top_categories??[];return e.jsx(re,{title:"Supplier Directory",description:t?.suppliers?.total?`${t.suppliers.total.toLocaleString()} suppliers with verified shipment history`:"Search verified suppliers by product category",icon:e.jsx(Bt,{className:"h-5 w-5"}),accent:"amber",href:"/supplier-database",ctaLabel:"Search",loading:n,children:e.jsx("div",{className:"space-y-3",children:r.length===0?e.jsx(He,{children:"Browse suppliers by category, country and shipment volume."}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Top sourcing categories"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.map(l=>e.jsxs(V,{variant:"outline",className:"max-w-full cursor-pointer text-[11px] font-normal hover:border-primary/60",onClick:()=>s(`/supplier-database?q=${encodeURIComponent(l.name)}`),children:[e.jsx("span",{className:"truncate",children:l.name}),e.jsx("span",{className:"ml-1 shrink-0 text-muted-foreground",children:l.count.toLocaleString()})]},l.name))})]})})})},tr=()=>{const s=O(),{data:t,isLoading:n}=K({queryKey:["dashboard-retailer-balance"],staleTime:6e4,queryFn:async()=>{const l=await Na();return l?{remaining:l.plan_credits_remaining??0,allocated:l.plan_credits_allocated??0,purchased:l.purchased_credits??0}:null}}),r=(t?.remaining??0)+(t?.purchased??0);return e.jsx(re,{title:"Contact Finder",description:"Reveal buyers, merchandisers and decision-makers at retailers",icon:e.jsx(Es,{className:"h-5 w-5"}),accent:"emerald",href:"/contact-finder",ctaLabel:"Find contacts",loading:n,children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Reveal credits available"}),e.jsx("div",{className:"text-xl font-semibold",children:r.toLocaleStr
15ing()}),t&&e.jsxs("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:[t.remaining," plan · ",t.purchased," purchased"]})]}),e.jsx(C,{variant:"outline",size:"sm",className:"h-auto w-full whitespace-normal py-2 leading-tight",onClick:()=>s("/contact-finder"),children:"Search retailers by company or role"})]})})},Oe=s=>typeof s=="number"?s:typeof s=="string"&&parseFloat(s.replace(/[$,]/g,""))||0,ar=()=>K({queryKey:["dataviz-previews"],staleTime:1e3*60*30,gcTime:1e3*60*60,queryFn:async()=>{const[s,t,n]=await Promise.all([M.rpc("get_products_from_snapshots",{_limit:5,_offset:0}),M.rpc("get_products_from_snapshots",{_limit:300,_offset:0}),M.from("keywords").select('Phrase, "Search Volume"').order("Search Volume",{ascending:!1,nullsFirst:!1}).limit(5)]),r=(s.data??[]).map(o=>({label:o.brand||o.asin||"â",value:Oe(o.monthly_revenue)})),l=new Map;for(const o of t.data??[]){const g=(o.category||"Uncategorized").toString();l.set(g,(l.get(g)??0)+Oe(o.monthly_revenue))}const u=Array.from(l.entries()).map(([o,g])=>({label:o,value:g})).sort((o,g)=>g.value-o.value).slice(0,5),d=(n.data??[]).map(o=>({label:o.Phrase||"â",value:Oe(o["Search Volume"])}));return{topProducts:r,categories:u,keywords:d}}}),rr=[{id:"top-products",label:"Top Products",icon:as,params:["Filter: Brand","Value: All","Rows: 500","Sort: Monthly Revenue â¼"],preview:"topProducts",unit:"currency",previewLabel:"Top 5 by monthly revenue"},{id:"category-performance",label:"Category Performance",icon:We,params:["Data type: Products","Category: All","Sort: Revenue â¼","Page size: 50"],preview:"categories",unit:"currency",previewLabel:"Leading categories by revenue"},{id:"keyword-trends",label:"Keyword Analysis",icon:Le,params:["Category: All","Keywords: 200","Volume range: Any","Revenue range: Any"],preview:"keywords",unit:"number",previewLabel:"Highest search volume keywords"},{id:"price-revenue",label:"Comparison Report",icon:zt,params:["Compare by: Brand","Selections: up to 5","Metrics: Units, Revenue, Products"],preview:"none",unit:"currency",previewLabel:"Side-by-side brand or seller comparison",emptyNote:"Pick the brands or sellers to compare after opening."},{id:"sales-distribution",label:"Sales Distribution",icon:Ot,params:["Compare by: Brand","Breakdown: Category share","Chart: Pie"],preview:"none",unit:"currency",previewLabel:"Category share for one brand or seller",emptyNote:"Choose a brand or seller after opening to build the pie."}],nr=(s,t)=>t==="currency"?s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${(s/1e3).toFixed(0)}K`:`$${Math.round(s)}`:s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:`${Math.round(s)}`,lr=({points:s,unit:t})=>{const n=Math.max(...s.map(r=>r.value),1);return e.jsx("div",{className:"space-y-1",children:s.map((r,l)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-20 shrink-0 truncate text-[10px] text-muted-foreground",children:r.label}),e.jsx("div",{className:"h-1.5 flex-1 overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-purple-500/70",style:{width:`${Math.max(4,r.value/n*100)}%`}})}),e.jsx("span",{className:"w-12 shrink-0 text-right text-[10px] tabular-nums text-foreground",children:nr(r.value,t)})]},`${r.label}-${l}`))})},ir=()=>{const s=O(),[t,n]=y.useState("top-products"),{data:r,isLoading:l}=ar(),u=d=>!r||d==="none"?[]:r[d]??[];return e.jsx(re,{title:"Data Visualization",description:"Preview each report and its filters before you open it",icon:e.jsx(as,{className:"h-5 w-5"}),accent:"cyan",href:"/data-visualization",ctaLabel:"View all",children:e.jsx("div",{className:"space-y-1.5",children:rr.map(d=>{const o=d.icon,g=t===d.id,m=u(d.preview);
15return e.jsxs("div",{className:w("rounded-lg border border-border/60 transition-colors",g?"border-primary/40 bg-muted/30":"hover:border-primary/50 hover:bg-muted/20"),children:[e.jsxs("button",{type:"button",onClick:()=>n(g?null:d.id),"aria-expanded":g,className:"flex w-full items-center gap-2 px-3 py-2 text-left text-xs",children:[e.jsx(o,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate font-medium",children:d.label}),e.jsx(Kt,{className:w("ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform",g&&"rotate-180")})]}),g&&e.jsxs("div",{className:"space-y-2 border-t border-border/50 px-3 py-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1",children:d.params.map(b=>e.jsx(V,{variant:"secondary",className:"px-1.5 py-0 text-[10px] font-normal",children:b},b))}),e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:d.previewLabel}),d.preview==="none"?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:d.emptyNote}):l?e.jsx("div",{className:"space-y-1",children:[0,1,2].map(b=>e.jsx(U,{className:"h-3 w-full"},b))}):m.length?e.jsx(lr,{points:m,unit:d.unit}):e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"No data available yet."}),e.jsxs("button",{type:"button",onClick:()=>s(`/visualizations/${d.id}`),className:"flex items-center gap-1 text-[11px] font-medium text-primary hover:underline",children:["Open report",e.jsx(je,{className:"h-3 w-3"})]})]})]},d.id)})})})},or=["Listing and catalogue audits","Launch and pricing strategy","Competitor and category deep dives"],cr=()=>{const s=O();return e.jsx(re,{title:"Consulting Services",description:"Work directly with our Amazon strategists",icon:e.jsx(Wt,{className:"h-5 w-5"}),accent:"violet",href:"/consulting",ctaLabel:"Learn more",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("ul",{className:"space-y-1.5",children:or.map(t=>e.jsxs("li",{className:"flex items-start gap-2 text-xs text-muted-foreground",children:[e.jsx(ts,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-teal-500"}),e.jsx("span",{children:t})]},t))}),e.jsx(C,{size:"sm",className:"h-auto w-full whitespace-normal py-2 leading-tight",onClick:()=>s("/consulting"),children:"Book a consultation"})]})})},dr=["Suggest new tools and data points","Vote the roadmap with your use case","Track status from your profile"],mr=()=>{const[s,t]=y.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsx(re,{title:"Request a Feature",description:"Tell us what would make Ecominsights better",icon:e.jsx(wa,{className:"h-5 w-5"}),accent:"cyan",ctaAction:()=>t(!0),ctaLabel:"Request a feature",children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("ul",{className:"space-y-1.5",children:dr.map(n=>e.jsxs("li",{className:"flex items-start gap-2 text-xs text-muted-foreground",children:[e.jsx(ts,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-teal-500"}),e.jsx("span",{children:n})]},n))}),e.jsx(C,{size:"sm",className:"h-auto w-full whitespace-normal py-2 leading-tight",onClick:()=>t(!0),children:"Submit a feature request"})]})}),e.jsx(aa,{open:s,onOpenChange:t})]})},ur=[{id:"private-pulse",label:"Private Pulse",href:"/private-dashboard",icon:Vt},{id:"competitor-finder",label:"Competitor Finder",href:"/competitor-finder",icon:Ht},{id:"associated-keywords",label:"Associated Keywords",href:"/associated-keywords",icon:Gt},{id:"keyword-clusters",label:"Keyword Clusters",href:"/keyword-clusters",icon:Yt},{id:"launch-simulator",label:"Launch Simulator",href:"/launch-simulator",icon:Qt},{id:"watchlist",label:"Watchlist",href:"/watchlist",icon:ss},{id:"listing-optimizer",label:"Listing Optimizer",href:"/amazon-listing-optimizer",icon:Zt},{id:"competitor-alerts",label:"Competitor Alerts",href:"/competitor-alerts",icon:Xt},{id:"favorites",label:"Favorites",href:"/favorites",icon:Jt},{id:"my-requests",label:"My Requests",href:"/data-requests",icon:Me},{id:"plans-billing",label:"Plans & Billing",href:"/subscription",icon:ea},{id:"learning-hub",label:"Learning Hub",href:"/learning-hub",icon:sa,disabled:!0}],hr=()=>{const s=O(),{trackClick:t}=bs();return e.jsxs(Qe,{className:"border-border/50",children:[e.jsx(ys,{className:"p-4 sm:p-5 pb-2",children:e.jsx(js,{className:"text-base sm:text-lg",children:"All tools"})}),e.jsx(vs,{className:"p-4 sm:p-5 pt-0",children:e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2",children:ur.map(n=>{const r=n.icon;return e.jsxs("button",{disabled:n.disabled,onClick:()=>
15{t(n.label,"navigation",{source:"dashboard-tools",href:n.href}),s(n.href)},className:`flex flex-col items-start gap-2 rounded-lg border border-border/60 p-3 text-left transition-colors ${n.disabled?"cursor-not-allowed opacity-50":"hover:border-primary/50 hover:bg-muted/40"}`,children:[e.jsx(r,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs font-medium leading-tight",children:n.label}),n.disabled&&e.jsx(V,{variant:"secondary",className:"text-[10px]",children:"Coming Soon"})]},n.id)})})})]})},xr=()=>typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;function pr(s,t=900){const[n,r]=y.useState(s??0),l=y.useRef();return y.useEffect(()=>{if(s==null)return;if(xr()){r(s);return}const u=performance.now(),d=0,o=g=>{const m=Math.min(1,(g-u)/t),b=1-Math.pow(1-m,3);r(d+(s-d)*b),m<1&&(l.current=requestAnimationFrame(o))};return l.current=requestAnimationFrame(o),()=>{l.current&&cancelAnimationFrame(l.current)}},[s,t]),n}const Se=({label:s,value:t,fallback:n,prefix:r,suffix:l,sub:u,pct:d,series:o,icon:g,accent:m,href:b,loading:S,index:_=0,className:h})=>{const k=O(),x=pr(t??null);return e.jsxs(Qe,{role:"button",tabIndex:0,"aria-label":s,onClick:()=>k(b),onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),k(b))},style:{animationDelay:`${_*70}ms`},className:w("group relative isolate cursor-pointer overflow-hidden border-border/60 bg-card/80 p-3.5 backdrop-blur-sm sm:p-4","motion-safe:animate-fade-in transition-all duration-300 ease-out motion-safe:hover:-translate-y-1 hover:shadow-elegant","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background active:scale-[0.99]","before:pointer-events-none before:absolute before:inset-x-0 before:top-0 before:-z-10 before:h-24","before:bg-gradient-to-b before:to-transparent",Vs[m],h),children:[e.jsx("span",{className:w("absolute inset-x-0 top-0 h-0.5 opacity-70",Hs[m]),"aria-hidden":"true"}),e.jsxs("div",{className:"flex items-start justify-between gap-2 sm:gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:w("grid h-7 w-7 shrink-0 place-items-center rounded-lg",Ws[m]),children:g}),e.jsx("span",{className:"min-w-0 flex-1 text-[11px] font-medium leading-tight text-muted-foreground sm:truncate sm:text-xs",children:s})]}),S?e.jsx(U,{className:"mt-3 h-7 w-20 sm:h-8 sm:w-24"}):e.jsxs("div",{className:"mt-2 flex flex-wrap items-baseline gap-x-2 gap-y-1",children:[e.jsx("span",{className:"text-xl font-bold tabular-nums tracking-tight sm:text-2xl lg:text-3xl",children:t==null?n??"â":`${r??""}${Math.round(x).toLocaleString()}${l??""}`}),e.jsx(ee,{pct:d})]}),u&&e.jsx("p",{className:"mt-1 truncate text-[11px] text-muted-foreground sm:text-xs",children:u})]}),o&&o.length>1&&e.jsx("div",{className:"hidden sm:block",children:e.jsx(ns,{series:o,accent:m})})]})]})},gr=()=>{const{data:s,isLoading:t}=rs(),{data:n,isLoading:r}=Zs(),{data:l,isLoading:u}=Xs(),d=l&&typeof l.query_limit=="number"?Math.max(0,l.query_limit-(l.query_count??0)):null,o=s?.suppliers?.total??null,g=n?.remaining??null,m="min-h-[104px] w-[72%] min-w-[15rem] shrink-0 snap-start sm:w-auto sm:min-w-0";return e.jsxs("div",{role:"group","aria-label":"Key metrics",className:"-mx-3 flex snap-x snap-mandatory gap-3 overflow-x-auto px-3 pb-1 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden sm:mx-0 sm:grid sm:grid-cols-2 sm:gap-4 sm:overflow-visible sm:px-0 sm:pb-0 xl:grid-cols-4",children:[e.jsx(Se,{index:0,className:m,label:"New products this month",value:s?.new_products??null,fallback:"â",sub:"Added to Intelligence Pulse",icon:e.jsx(Ds,{className:"h-3.5 w-3.5"}),accent:"blue",href:"/intelligence-pulse",loading:t}),e.jsx(Se,{index:1,className:m,label:"AI Assistant credits left",value:d,fallback:"Ask your first question",sub:l?`${l.query_count} used of ${l.query_limit} this month`:"Included with your plan",icon:e.jsx(Ks,{className:"h-3.5 w-3.5"}),accent:"emerald",href:"/ai-assistant",loading:u}),e.jsx(Se,{index:2,className:m,label:"Report credits left",value:g,fallback:"Get credits",sub:n?`${n.used} used of ${n.credit_limit} this month`:"Track your first ASIN",icon:e.jsx(ka,{className:"h-3.5 w-3.5"}),accent:"amber",href:"/monthly-reports",loading:r}),e.jsx(Se,{index:3,className:m,label:"Suppliers in directory",value:o,fallback:"Browse",sub:s?.suppliers?.top_categories?.[0]?`Top category: ${s.suppliers.top_categories[0].name}`:"Sourcing partners you can contact",icon:e.jsx(_a,{className:"h-3.5 w-3.5"}),accent:"violet",href:"/supplier-database",loading:t})]})};function fr(){const s=es();y.useEffect(()=>{let t=!1;return(async()=>{const{data:r}=await M.auth.getSession();t||!r.session||(s.prefetchQuery({queryKey:["dashboard-highlights"],queryFn:et,staleTime:10*6e4}),s.prefetchQuery({queryKey:ot,queryFn:dt,staleTime:6e4}))})(),()=>{t=!0}},[s])}const Qr=()=>{const s=O();fr();const[t,n]=y.useState(!1),[r,l]=y.useState(""),u=new Date().toLocaleDateString(void 0,{weekday:"long",month:"long",day:"numeric"});y.useEffect(()=>{let g=!0;return M.auth.getUser().then(({data:m})=>
15{if(!g)return;const b=m.user?.user_metadata??{},S=typeof b.first_name=="string"&&b.first_name||typeof b.full_name=="string"&&b.full_name.split(" ")[0]||m.user?.email?.split("@")[0]||"";l(S)}),()=>{g=!1}},[]),y.useEffect(()=>{if(typeof window>"u"||new URLSearchParams(window.location.search).get("success")!=="true")return;let m=null;try{m=localStorage.getItem("postUpgradeRedirect")}catch{}if(m){try{localStorage.removeItem("postUpgradeRedirect")}catch{}s(m,{replace:!0})}},[s]);const d=()=>{n(!1)},o=()=>{n(!1)};return e.jsxs(ta,{children:[e.jsx(na,{isOpen:t,onClose:o,onComplete:d}),e.jsxs("div",{className:"container mx-auto space-y-4 p-3 sm:space-y-6 sm:p-5 lg:p-6",children:[e.jsxs("div",{className:"relative isolate overflow-hidden rounded-2xl border border-border/60 bg-card/60 p-4 backdrop-blur-sm sm:p-6 lg:p-7","data-tour":"dashboard-header",children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 -z-10 bg-gradient-to-br from-widget-blue/10 via-transparent to-widget-violet/10","aria-hidden":"true"}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.16em] text-muted-foreground sm:text-xs sm:tracking-[0.18em]",children:u}),e.jsxs("h1",{className:"mt-1 text-xl font-bold leading-tight tracking-tight sm:text-3xl lg:text-4xl",children:["Welcome back",r?`, ${r}`:""]}),e.jsx("p",{className:"mt-1 text-[13px] leading-snug text-muted-foreground sm:text-base lg:text-lg",children:"Here's what's moving today â jump into any tool from here."})]}),e.jsxs(C,{variant:"outline",size:"sm",onClick:()=>n(!0),className:"w-full shrink-0 sm:w-auto",children:[e.jsx(Sa,{className:"mr-2 h-4 w-4"}),"Take a tour"]})]})]}),e.jsx(gr,{}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:gap-5 md:grid-cols-2 xl:grid-cols-3 xl:gap-6",children:[e.jsx("div",{className:"md:col-span-2 xl:col-span-2","data-tour":"feature-intelligence-pulse",children:e.jsx(Ha,{})}),e.jsx("div",{children:e.jsx(Qa,{})})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:gap-5 md:grid-cols-2 xl:grid-cols-4 xl:gap-6",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsx(Xa,{})}),e.jsx("div",{"data-tour":"feature-ai-assistant",children:e.jsx(er,{})}),e.jsx(ir,{})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-5 xl:grid-cols-4 xl:gap-6",children:[e.jsx(sr,{}),e.jsx(tr,{}),e.jsx(cr,{}),e.jsx(mr,{})]}),e.jsx("div",{"data-tour":"usage-stats",children:e.jsx(ra,{})}),e.jsx("div",{"data-tour":"feature-favorites",children:e.jsx(hr,{})})]})]})};export{Qr as default};
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.