1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/download-file-GiM6ssRc.js","assets/index-DZsJb6kD.js","assets/vendor-query-C2CG3Qbc.js","assets/vendor-react-DcIrbEI1.js","assets/vendor-radix-rFCXVOHz.js","assets/vendor-supabase-CHGq0V2O.js","assets/index-BRdCJlG-.css","assets/StatusTab-DNLb_geY.js","assets/textarea-B34ixqsr.js","assets/select-BAqEbJU1.js","assets/chevron-up-DsHmQb6e.js","assets/check-DrrDkyjp.js","assets/dialog-DMYLM_G5.js","assets/trash-2-B3u57_a3.js","assets/send-CDrojIzu.js","assets/circle-check--0dxWtfi.js","assets/formatDistanceToNow-D_jEQptO.js","assets/en-US-4RaJY4CL.js","assets/format-CP4knq5Y.js","assets/StaffBadge-C_W3TsXv.js","assets/users-DMBGfzG8.js","assets/handshake-D60FktAi.js","assets/usePresence-CHilyazM.js","assets/browser-utils-DkRsGkmD.js","assets/search-input-5vlBuFub.js","assets/switch-DX6vz6Ms.js","assets/CreatorTicketsSection-SxOSZLiP.js","assets/empty-state-C21zTmL4.js","assets/arrow-left-jktZxyi9.js","assets/tabs-Cquk103n.js","assets/loading-spinner-DoDPkitl.js","assets/loader-circle-DTQl0vkv.js","assets/chart-column-Cu98oloQ.js","assets/shield-alert-DUhdshfS.js","assets/user-plus-BYXMPtSY.js","assets/circle-x-CTCtLZZf.js","assets/trophy-B5fDJ9Q6.js","assets/triangle-alert-0TcOrHxX.js","assets/status-styles-z6V9m4rd.js","assets/description-sanitizer-BvWtK342.js","assets/file-text-K43Dpwbs.js","assets/eye-CUJxrYkQ.js","assets/MetricCard-CcwtWhf-.js","assets/circle-alert-BPLQavbT.js","assets/edge-function-url-DjWpYV1O.js","assets/globe-DuqlzHCg.js","assets/download-BK0Q3DLR.js","assets/external-link-C2d5KWRa.js","assets/info-3eMfy_bn.js","assets/file-hash-NgtSxCW_.js","assets/loading-button-yRAae2D5.js","assets/smartphone-20h9YyIo.js","assets/label-D6hvuZZh.js","assets/link-2-BpgtPcvu.js","assets/copy-B63dZPZX.js","assets/mouse-pointer-click-JJORih2B.js","assets/lock-74tYBb-U.js","assets/sheet-DNwpsZXv.js","assets/recommendation-experiments-B_3GGPcB.js","assets/index-CuGrQIWB.js","assets/tag-CH9kpdtn.js","assets/award-CNih4zM1.js","assets/gauge-aCoPEYiY.js","assets/message-square-fVLqVQAl.js","assets/flag-BjgDdr7b.js","assets/credit-card-p9AhPHTI.js","assets/file-archive-bCLLqU-3.js","assets/flask-conical-CkNfE2dP.js","assets/hard-drive-DTy0Qkn3.js","assets/user-check-mHFUNcd8.js","assets/circle-help-Dg6rsbTJ.js","assets/supabase-fetch-all-BNqwZxdA.js","assets/circle-check-big-Duu-oOw6.js","assets/mail-CdklhLwS.js","assets/pause-DTqsIG1B.js","assets/eye-off-BeaBJ1ZD.js","assets/monitor-DcqIWBHL.js","assets/progress-C9pLZzEB.js","assets/ErrorsTab-BqEohgp-.js","assets/AgentTab-DkP0A-h8.js","assets/scroll-area-WyP5_HN9.js","assets/AdvertisingTab-BfXvyVFl.js","assets/table-DyyfePL0.js","assets/table-empty-row-NRAjmt2M.js","assets/target-Bgxo79AH.js","assets/ComposedChart-_RIDt2hH.js","assets/pencil-ZiowYii5.js","assets/play-CVTHk2pj.js","assets/ImportsTab-lIuCMszi.js","assets/bulk-import-engine-DyJGihOb.js","assets/format-bytes-vhicfzIM.js","assets/server-import-Cbjw1qnH.js","assets/ChunkedUploadContext-xUJiCMp7.js","assets/ActiveImportsPanel-Cr6ALIYd.js","assets/popover-CCsWf77s.js","assets/pagination-BJJ64ZcY.js","assets/rotate-ccw-ClOo7olA.js","assets/image-MZKKTNve.js","assets/upload-yrpY1gVN.js","assets/arrow-right-Bhy93Idc.js","assets/StressTestTab-BbpNp79S.js","assets/ProductAnalyticsTab-Cs8HYgHc.js","assets/useAdminDashboard-CxAoBana.js","assets/DbPerformanceTab-Cr1S7mBN.js","assets/database-vsZ5qu5I.js","assets/LandingPageAnalyticsTab-Ctr0vPWV.js","assets/BetaFeaturesTab-Ni8HOxfm.js","assets/BundlesTab-rdgRwc35.js","assets/BundleFormKit-MOdD9HjT.js","assets/ApplicationsTab-CiMUAZ1X.js","assets/EmailDashboardTab-aoU_mHCW.js","assets/BadgesTab-7hFV3JvF.js","assets/BadgePill-CVcpat3h.js","assets/achievements-X0nNVzxa.js","assets/user-minus-Bv9SjimD.js","assets/ActivityLogModule-_47Gboc_.js","assets/OrdersTab-CofC6Hhh.js","assets/calendar-CSCSt8cu.js","assets/ModerationTab-C9JR3rxJ.js","assets/DMCAClaimsTab-CxjFDaIx.js","assets/ContentTab-BeiqN0OM.js","assets/pin-uOdak4Sq.js","assets/save-B_DA9uoF.js","assets/grip-vertical-BLKQVc2A.js","assets/PaymentsTab-CsjRBy94.js","assets/platform-fees-CtisBoOB.js","assets/PaymentLogsTab-C4R6XawU.js","assets/filter-BR1-mji4.js","assets/SecurityTab-ClhCRgx6.js","assets/key-round-C_PDprFV.js","assets/user-x-CPBlhr2E.js","assets/HelpTab-RW3d_nDI.js","assets/OverviewTab-CbfYl25o.js","assets/bell-BDbwFJhc.js","assets/SellersTab-Dl3gwxoX.js","assets/checkbox-DNgLFETJ.js","assets/shield-off-CYOAlnyM.js","assets/unlink-B8ViAgNa.js","assets/VerificationsTab-Ct2jRRmv.js","assets/usePagination-Ch5E8xaR.js","assets/ListPagination-BIBvrDG5.js","assets/BansModule-BKcbga7U.js"])))=>i.map(i=>d[i]); 2import{N as ps,a3 as z,am as V,W as Bs,Y as it,Z as qs,e as Y,B as $,s as x,u as O,aR as $t,d as vs,ag as Yr,ap as Zr,L as Xr,h as li,aS as lt,J as ke,O as kt,ah as en,ai as sn,aj as tn,f as js,aM as Ot,aN as Lt,aO as bo,Q as yo,c as ms,a as No,a2 as vt,U as _o,P as Pa,a0 as or,a9 as fl,an as wo,a4 as zr,aT as Dt,av as jl,a5 as Xa,aw as rt,aE as So,aU as rr,q as vl,g as ko,aG as Fa,a8 as as,ad as Rt,aV as Ft,af as Co,X as bl,C as Ta,au as zn,aW as Or,a1 as Mi,aP as yl,A as Ao}from"./index-DZsJb6kD.js";import{j as e}from"./vendor-query-C2CG3Qbc.js";import{r as i,L as da,c as Qe,i as Nl,N as Ro}from"./vendor-react-DcIrbEI1.js";import{s as _l,S as Po}from"./StaffBadge-C_W3TsXv.js";import{a as To}from"./usePresence-CHilyazM.js";import{S as Gs}from"./search-input-5vlBuFub.js";import{T as $s}from"./textarea-B34ixqsr.js";import{S as Pe,a as Te,b as De,c as Me,d as L}from"./select-BAqEbJU1.js";import{D as Ds,a as Ms,b as Es,c as Os,e as an,d as Xt,f as Do}from"./dialog-DMYLM_G5.js";import{S as Ca}from"./switch-DX6vz6Ms.js";import{T as Jn,C as Mo}from"./CreatorTicketsSection-SxOSZLiP.js";import{T as wl,a as Sl,b as na,c as ia}from"./tabs-Cquk103n.js";import{L as cs}from"./loading-spinner-DoDPkitl.js";import{U as bt}from"./users-DMBGfzG8.js";import{C as zt}from"./chart-column-Cu98oloQ.js";import{S as Vt}from"./shield-alert-DUhdshfS.js";import{U as $a}from"./user-plus-BYXMPtSY.js";import{C as la}from"./circle-check--0dxWtfi.js";import{C as Ct}from"./circle-x-CTCtLZZf.js";import{T as Eo}from"./trophy-B5fDJ9Q6.js";import{T as Ps}from"./triangle-alert-0TcOrHxX.js";import{B as Za,A as Oo,L as Ei,v as Lo,g as Oi}from"./status-styles-z6V9m4rd.js";import{F as Ws}from"./file-text-K43Dpwbs.js";import{E as ws}
2from"./eye-CUJxrYkQ.js";import{T as As}from"./trash-2-B3u57_a3.js";import{M as Ls,S as Ye}from"./MetricCard-CcwtWhf-.js";import{getEdgeFunctionUrl as Fo}from"./edge-function-url-DjWpYV1O.js";import{G as Bt}from"./globe-DuqlzHCg.js";import{D as nt}from"./download-BK0Q3DLR.js";import{C as Qn}from"./circle-alert-BPLQavbT.js";import{E as oa}from"./external-link-C2d5KWRa.js";import{I as kl}from"./info-3eMfy_bn.js";import{f as _s,_ as Cl,a as Al,b as $o,c as Uo,i as ta,T as oi,p as Pt,L as at,g as Rl,d as ci,e as Pl,D as Io,C as zo,h as Aa,j as _a,S as Vo,A as Bo,k as qo,l as Li,m as Wo,n as wa,o as Go,G as Ho,q as Ko,r as Jo,s as Rr,w as Fi,t as Lr,u as Qo,v as Da,x as Yo,y as Zo,R as gs,z as Ss,X as ks,Y as Cs,B as fs,E as Ut,F as Vs,H as Xo,I as ec,J as $i,W as Tl,P as sc,K as di,M as ht,N as nr}from"./file-hash-NgtSxCW_.js";import{A as cr,a as Tt,L as pa}from"./loading-button-yRAae2D5.js";import{A as Dl,a as mi,S as ui,L as xi}from"./smartphone-20h9YyIo.js";import{C as ma}from"./chevron-up-DsHmQb6e.js";import{L as aa}from"./label-D6hvuZZh.js";import{L as Vr}from"./link-2-BpgtPcvu.js";import{C as Ra}from"./copy-B63dZPZX.js";import{E as tc}from"./empty-state-C21zTmL4.js";import{L as xs}from"./loader-circle-DTQl0vkv.js";import{M as Ml}from"./mouse-pointer-click-JJORih2B.js";import{L as It}from"./lock-74tYBb-U.js";import{S as qt}from"./send-CDrojIzu.js";import{S as dr}from"./vendor-radix-rFCXVOHz.js";import{S as Fr}from"./description-sanitizer-BvWtK342.js";import{S as El,a as Ol,b as ac,c as rc}from"./sheet-DNwpsZXv.js";import{b as nc}from"./recommendation-experiments-B_3GGPcB.js";import{R as ic,a as lc,b as oc}from"./index-CuGrQIWB.js";import{T as pi}from"./tag-CH9kpdtn.js";import{A as Ll}from"./award-CNih4zM1.js";import{G as Ui}from"./gauge-aCoPEYiY.js";import{M as er}from"./message-square-fVLqVQAl.js";import{F as Br}from"./flag-BjgDdr7b.js";import{C as rn}from"./credit-card-p9AhPHTI.js";import{F as cc}from"./file-archive-bCLLqU-3.js";import{F as dc}from"./flask-conical-CkNfE2dP.js";import{H as nn}from"./hard-drive-DTy0Qkn3.js";import{B as mc,U as Yn}from"./user-check-mHFUNcd8.js";import{C as Ii}from"./circle-help-Dg6rsbTJ.js";import{fetchAllRows as Fs}from"./supabase-fetch-all-BNqwZxdA.js";import{C as At}from"./circle-check-big-Duu-oOw6.js";import{M as zi}from"./mail-CdklhLwS.js";import{P as Pr}from"./pause-DTqsIG1B.js";import{E as Vi}from"./eye-off-BeaBJ1ZD.js";import{M as qr}from"./monitor-DcqIWBHL.js";import{P as uc}from"./progress-C9pLZzEB.js";import{C as xc}from"./check-DrrDkyjp.js";import{A as Fl}from"./arrow-left-jktZxyi9.js";/** 3 * @license lucide-react v0.462.0 - ISC 4 * 5 * This source code is licensed under the ISC license. 6 * See the LICENSE file in the root directory of this source tree. 7 */const pc=ps("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]);/** 8 * @license lucide-react v0.462.0 - ISC 9 * 10 * This source code is licensed under the ISC license. 11 * See the LICENSE file in the root directory of this source tree. 12 */const Bi=ps("Bookmark",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]]);/** 13 * @license lucide-react v0.462.0 - ISC 14 * 15 * This source code is licensed under the ISC license. 16 * See the LICENSE file in the root directory of this source tree. 17 */const hc=ps("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]);/** 18 * @license lucide-react v0.462.0 - ISC 19 * 20 * This source code is licensed under the ISC license. 21 * See the LICENSE file in the root directory of this source tree. 22 */const qi=ps("CalendarDays",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]]);/** 23 * @license lucide-react v0.462.0 - ISC 24 * 25 * This source code is licensed under the ISC license. 26 * See the LICENSE file in the root directory of this source tree. 27 */const gc=ps("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/** 28 * @license lucide-react v0.462.0 - ISC 29 * 30 * This source code is licensed under the ISC license. 31 * See the LICENSE file in the root directory of this source tree. 32 */const Wi=ps("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/** 33 * @license lucide-react v0.462.0 - ISC 34 * 35 * This source code is licensed under the ISC license. 36 * See the LICENSE file in the root directory of this source tree. 37 */const fc=ps("Footprints",[["path",{d:"M4 16v-2.38C4 11.5 2.97 10.5 3 8c.03-2.72 1.49-6 4.5-6C9.37 2 10 3.8 10 5.5c0 3.11-2 5.66-2 8.68V16a2 2 0 1 1-4 0Z",key:"1dudjm"}],["path",{d:"M20 20v-2.38c0-2.12 1.03-3.12 1-5.62-.03-2.72-1.49-6-4.5-6C14.63 6 14 7.8 14 9.5c0 3.11 2 5.66 2 8.68V20a2 2 0 1 0 4 0Z",key:"l2t8xc"}],["path",{d:"M16 17h4",key:"1dejxt"}],["path",{d:"M4 13h4",key:"1bwh8b"}]]);/** 38 * @license lucide-react v0.462.0 - ISC 39 * 40 * This source code is licensed under the ISC license. 41 * See the LICENSE file in the root directory of this source tree. 42 */const $l=ps("Key",[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]]);/** 43 * @license lucide-react v0.462.0 - ISC 44 * 45 * This source code is licensed under the ISC license. 46 * See the LICENSE file in the root directory of this source tree. 47 */const Ul=ps("LockOpen",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]]);/** 48 * @license lucide-react v0.462.0 - ISC 49 * 50 * This source code is licensed under the ISC license. 51 * See the LICENSE file in the root directory of this source tree. 52 */const Vn=ps("PackageX",[["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}],["path",{d:"m17 13 5 5m-5 0 5-5",key:"im3w4b"}]]);/** 53 * @license lucide-react v0.462.0 - ISC 54 * 55 * This source code is licensed under the ISC license. 56 * See the LICENSE file in the root directory of this source tree. 57 */const jc=ps("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);/** 58 * @license lucide-react v0.462.0 - ISC 59 * 60 * This source code is licensed under the ISC license. 61 * See the LICENSE file in the root directory of this source tree. 62 */const Gi=ps("PanelsTopLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]]);/** 63 * @license lucide-react v0.462.0 - ISC 64 * 65 * This source code is licensed under the ISC license. 66 * See the LICENSE file in the root directory of this source tree. 67 */const vc=ps("Radio",[["path",{d:"M4.9 19.1C1 15.2 1 8.8 4.9 4.9",key:"1vaf9d"}],["path",{d:"M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5",key:"u1ii0m"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5",key:"1j5fej"}],["path",{d:"M19.1 4.9C23 8.8 23 15.1 19.1 19",key:"10b0cb"}]]);/** 68 * @license lucide-react v0.462.0 - ISC 69 * 70 * This source code is licensed under the ISC license. 71 * See the LICENSE file in the root directory of this source tree. 72 */const St=ps("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** 73 * @license lucide-react v0.462.0 - ISC 74 * 75 * This source code is licensed under the ISC license. 76 * See the LICENSE file in the root directory of this source tree. 77 */const Hi=ps("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",ke
77y:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/** 78 * @license lucide-react v0.462.0 - ISC 79 * 80 * This source code is licensed under the ISC license. 81 * See the LICENSE file in the root directory of this source tree. 82 */const ua=ps("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);/** 83 * @license lucide-react v0.462.0 - ISC 84 * 85 * This source code is licensed under the ISC license. 86 * See the LICENSE file in the root directory of this source tree. 87 */const bc=ps("StickyNote",[["path",{d:"M16 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8Z",key:"qazsjp"}],["path",{d:"M15 3v4a2 2 0 0 0 2 2h4",key:"40519r"}]]);/** 88 * @license lucide-react v0.462.0 - ISC 89 * 90 * This source code is licensed under the ISC license. 91 * See the LICENSE file in the root directory of this source tree. 92 */const Il=ps("Tablet",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2",key:"76otgf"}],["line",{x1:"12",x2:"12.01",y1:"18",y2:"18",key:"1dp563"}]]);/** 93 * @license lucide-react v0.462.0 - ISC 94 * 95 * This source code is licensed under the ISC license. 96 * See the LICENSE file in the root directory of this source tree. 97 */const yc=ps("Timer",[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]]);/** 98 * @license lucide-react v0.462.0 - ISC 99 * 100 * This source code is licensed under the ISC license. 101 * See the LICENSE file in the root directory of this source tree. 102 */const Nc=ps("ToggleLeft",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]]);/** 103 * @license lucide-react v0.462.0 - ISC 104 * 105 * This source code is licensed under the ISC license. 106 * See the LICENSE file in the root directory of this source tree. 107 */const zl=ps("TrendingDown",[["polyline",{points:"22 17 13.5 8.5 8.5 13.5 2 7",key:"1r2t7k"}],["polyline",{points:"16 17 22 17 22 11",key:"11uiuu"}]]);/** 108 * @license lucide-react v0.462.0 - ISC 109 * 110 * This source code is licensed under the ISC license. 111 * See the LICENSE file in the root directory of this source tree. 112 */const Ma=ps("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]);function _c(){return e.jsxs(wl,{defaultValue:"management",className:"space-y-4",children:[e.jsxs(Sl,{className:"glass",children:[e.jsxs(na,{value:"management",className:"gap-1",children:[e.jsx(bt,{className:"h-4 w-4"})," Management"]}),e.jsxs(na,{value:"analytics",className:"gap-1",children:[e.jsx(zt,{className:"h-4 w-4"})," Analytics"]}),e.jsxs(na,{value:"fraud",className:"gap-1",children:[e.jsx(Vt,{className:"h-4 w-4"})," Fraud Detection"]}),e.jsxs(na,{value:"recruiters",className:"gap-1",children:[e.jsx($a,{className:"h-4 w-4"})," Recruiters"]})]}),e.jsx(ia,{value:"management",children:e.jsx(wc,{})}),e.jsx(ia,{value:"analytics",children:e.jsx(Sc,{})}),e.jsx(ia,{value:"fraud",children:e.jsx(kc,{})}),e.jsx(ia,{value:"recruiters",children:e.jsx(Cc,{})})]})}function wc(){const[s,t]=i.useState([]),[r,n]=i.useState(!0),[a,l]=i.useState(""),[o,j]=i.useState("all"),b=async()=>{n(!0);const{data:p}=await x.from("referrals").select("*").order("created_at",{ascending:!1}).limit(500);if(p&&p.length>0){const h=[...new Set(p.flatMap(m=>[m.referrer_id,m.referred_id]))],{data:f}=await x.from("profiles").select("user_id, display_name, avatar_url").in("user_id",h),_=new Map((f||[]).map(m=>[m.user_id,m]));t(p.map(m=>{var u,g,S,M;return{...m,source:m.source||"referral",referrer_name:((u=_.get(m.referrer_id))==null?void 0:u.display_name)||"Unknown",referrer_avatar:(g=_.get(m.referrer_id))==null?void 0:g.avatar_url,referred_name:((S=_.get(m.referred_id))==null?void 0:S.display_name)||"Unknown",referred_avatar:(M=_.get(m.referred_id))==null?void 0:M.avatar_url}}))}n(!1)};i.useEffect(()=>{b()},[]);const c=async(p,h)=>{const f={status:h};h==="qualified"&&(f.qualified_at=new Date().toISOString());const{error:_}=await x.from("referrals").update(f).eq("id",p);if(_){O.error(_.message);return}if(h==="qualified"){const m=s.find(u=>u.id===p);m&&await d(m.referrer_id)}O.success(`Referral marked as ${h}`),b()},d=async p=>{const{count:h}=await x.from("referrals").select("id",{count:"exact",head:!0}).eq("referrer_id",p).eq("status","qualified"),f=h||0,_=[{count:1,badgeType:"early_supporter",badgeName:"Early Supp
112orter"},{count:3,badgeType:"marketplace_pioneer",badgeName:"Marketplace Pioneer"},{count:5,badgeType:"platform_builder",badgeName:"Platform Builder"},{count:10,badgeType:"growth_partner",badgeName:"Growth Partner"}];for(const m of _)if(f>=m.count){const{data:u}=await x.from("creator_badges").select("id").eq("user_id",p).eq("badge_type",m.badgeType).maybeSingle();u||await x.from("creator_badges").insert({user_id:p,badge_type:m.badgeType,badge_name:m.badgeName})}if(f>=3){const{data:m}=await x.from("creator_badges").select("id").eq("user_id",p).eq("badge_type","founding_creator").maybeSingle();if(!m){const{count:u}=await x.from("creator_badges").select("id",{count:"exact",head:!0}).eq("badge_type","founding_creator");(u||0)<100&&await x.from("creator_badges").insert({user_id:p,badge_type:"founding_creator",badge_name:"Founding Creator"})}}},P=s.filter(p=>{var _,m;const h=!a||((_=p.referrer_name)==null?void 0:_.toLowerCase().includes(a.toLowerCase()))||((m=p.referred_name)==null?void 0:m.toLowerCase().includes(a.toLowerCase()))||p.referrer_id.includes(a)||p.referred_id.includes(a),f=o==="all"||p.status===o;return h&&f}),k=p=>{switch(p){case"qualified":return e.jsx(Y,{className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30 text-[10px]",children:"Qualified"});case"pending":return e.jsx(Y,{className:"bg-accent/20 text-accent border-accent/30 text-[10px]",children:"Pending"});case"invalid":return e.jsx(Y,{className:"bg-destructive/20 text-destructive border-destructive/30 text-[10px]",children:"Invalid"});default:return e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:p})}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(Gs,{placeholder:"Search by name or user ID...",value:a,onChange:l,wrapperClassName:"flex-1"}),e.jsxs(Pe,{value:o,onValueChange:j,children:[e.jsx(Te,{className:"w-[150px]",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Status"}),e.jsx(L,{value:"pending",children:"Pending"}),e.jsx(L,{value:"qualified",children:"Qualified"}),e.jsx(L,{value:"invalid",children:"Invalid"})]})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[P.length," referrals found"]}),r?e.jsx(cs,{}):e.jsx("div",{className:"space-y-2",children:P.map(p=>{var h,f,_,m;return e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 flex flex-col sm:flex-row items-start sm:items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsxs(Bs,{className:"h-8 w-8 border border-border shrink-0",children:[e.jsx(it,{src:p.referrer_avatar||void 0}),e.jsx(qs,{className:"bg-muted text-xs",children:(f=(h=p.referrer_name)==null?void 0:h[0])==null?void 0:f.toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:p.referrer_name}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Referrer"})]}),e.jsx("span",{className:"text-muted-foreground text-xs mx-2",children:"â"}),e.jsxs(Bs,{className:"h-8 w-8 border border-border shrink-0",children:[e.jsx(it,{src:p.referred_avatar||void 0}),e.jsx(qs,{className:"bg-muted text-xs",children:(m=(_=p.referred_name)==null?void 0:_[0])==null?void 0:m.toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:p.referred_name}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Referred"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[k(p.status),p.source==="recruiter"&&e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:"Recruiter"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(p.created_at).toLocaleDateString()})]}),e.jsxs("div",{className:"flex gap-1",children:[p.status!=="qualified"&&e.jsxs($,{size:"sm",variant:"outline",className:"h-7 text-xs gap-1",onClick:()=>c(p.id,"qualified"),children:[e.jsx(la,{className:"h-3 w-3"})," Approve"]}),p.status!=="invalid"&&e.jsxs($,{size:"sm",variant:"outline",className:"h-7 text-xs gap-1 text-destructive",onClick:()=>c(p.id,"invalid"),children:[e.jsx(Ct,{className:"h-3 w-3"})," Invalidate"]})]})]})},p.id)})})]})}function Sc(){const[s,t]=i.useState({total:0,qualified:0,pending:0,invalid:0,conversionRate:0,recruiterTotal:0,topReferrers:[]}),[r,n]=i.useState(!0);return i.useEffect(()=>{(async()=>{const{data:l}=await x.from("referrals").select("referrer_id, status, source");if(!l){n(!1);return}const o=l.length,j=l.filter(h=>h.status==="qualified").length,b=l.filter(h=>
112h.status==="pending").length,c=l.filter(h=>h.status==="invalid").length,d=l.filter(h=>h.source==="recruiter").length,P=o>0?Math.round(j/o*100):0,k=new Map;l.filter(h=>h.status==="qualified").forEach(h=>{k.set(h.referrer_id,(k.get(h.referrer_id)||0)+1)});const p=Array.from(k.entries()).sort((h,f)=>f[1]-h[1]).slice(0,10);if(p.length>0){const{data:h}=await x.from("profiles").select("user_id, display_name, avatar_url").in("user_id",p.map(_=>_[0])),f=new Map((h||[]).map(_=>[_.user_id,_]));t({total:o,qualified:j,pending:b,invalid:c,conversionRate:P,recruiterTotal:d,topReferrers:p.map(([_,m])=>{var u,g;return{name:((u=f.get(_))==null?void 0:u.display_name)||"Unknown",avatar:((g=f.get(_))==null?void 0:g.avatar_url)||null,count:m}})})}else t({total:o,qualified:j,pending:b,invalid:c,conversionRate:P,recruiterTotal:d,topReferrers:[]});n(!1)})()},[]),r?e.jsx(cs,{}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsx("p",{className:"text-2xl font-display font-bold text-primary",children:s.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Referrals"})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsx("p",{className:"text-2xl font-display font-bold text-emerald-400",children:s.qualified}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Successful"})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsx("p",{className:"text-2xl font-display font-bold text-accent",children:s.pending}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pending"})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsxs("p",{className:"text-2xl font-display font-bold text-foreground",children:[s.conversionRate,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Conversion Rate"})]})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsx("p",{className:"text-2xl font-display font-bold text-destructive",children:s.invalid}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Invalid / Flagged"})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsx("p",{className:"text-2xl font-display font-bold text-primary",children:s.recruiterTotal}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"From Recruiter Links"})]})})]}),s.topReferrers.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h4",{className:"text-sm font-display font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Eo,{className:"h-4 w-4"})," Top Referrers"]}),e.jsx("div",{className:"space-y-2",children:s.topReferrers.map((a,l)=>{var o;return e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-3 flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-mono text-muted-foreground w-6 text-center",children:l+1}),e.jsxs(Bs,{className:"h-8 w-8 border border-border",children:[e.jsx(it,{src:a.avatar||void 0}),e.jsx(qs,{className:"bg-muted text-xs",children:(o=a.name[0])==null?void 0:o.toUpperCase()})]}),e.jsx("p",{className:"text-sm font-medium flex-1",children:a.name}),e.jsx("p",{className:"text-sm font-display font-bold text-primary",children:a.count})]})},l)})})]})]})}function kc(){const[s,t]=i.useState([]),[r,n]=i.useState(!0);i.useEffect(()=>{(async()=>{const{data:b}=await x.from("referrals").select("*").order("created_at",{ascending:!1});if(!b){n(!1);return}const c=[...new Set(b.flatMap(m=>[m.referrer_id,m.referred_id]))],{data:d}=await x.from("profiles").select("user_id, display_name, avatar_url").in("user_id",c),P=new Map((d||[]).map(m=>[m.user_id,m])),k=b.map(m=>{var u,g,S,M;return{...m,source:m.source||"referral",referrer_name:((u=P.get(m.referrer_id))==null?void 0:u.display_name)||"Unknown",referrer_avatar:(g=P.get(m.referrer_id))==null?void 0:g.avatar_url,referred_name:((S=P.get(m.referred_id))==null?void 0:S.display_name)||"Unknown",referred_avatar:(M=P.get(m.referred_id))==null?void 0:M.avatar_url}}),p=[],h=new Map;k.filter(m=>
112m.ip_address).forEach(m=>{const u=m.ip_address;h.has(u)||h.set(u,[]),h.get(u).push(m)}),h.forEach((m,u)=>{m.length>1&&p.push({type:"duplicate_ip",referrals:m,value:u})});const f=new Map;k.filter(m=>m.device_fingerprint).forEach(m=>{const u=m.device_fingerprint;f.has(u)||f.set(u,[]),f.get(u).push(m)}),f.forEach((m,u)=>{m.length>1&&p.push({type:"duplicate_fingerprint",referrals:m,value:u})});const _=new Map;k.forEach(m=>{_.has(m.referrer_id)||_.set(m.referrer_id,[]),_.get(m.referrer_id).push(m)}),_.forEach(m=>{if(m.length<2)return;const u=m.sort((g,S)=>new Date(g.created_at).getTime()-new Date(S.created_at).getTime());for(let g=1;g<u.length;g++){const S=new Date(u[g].created_at).getTime()-new Date(u[g-1].created_at).getTime();S<3e5&&p.push({type:"rapid_signup",referrals:[u[g-1],u[g]],value:`${Math.round(S/1e3)}s apart`})}}),t(p),n(!1)})()},[]);const a=async j=>{for(const b of j)await x.from("referrals").update({status:"invalid"}).eq("id",b);O.success(`${j.length} referral(s) marked invalid`)},l=j=>j==="duplicate_ip"?e.jsx(Ps,{className:"h-4 w-4 text-amber-400"}):j==="duplicate_fingerprint"?e.jsx(Vt,{className:"h-4 w-4 text-destructive"}):e.jsx(Za,{className:"h-4 w-4 text-destructive"}),o=j=>j==="duplicate_ip"?"Same IP Address":j==="duplicate_fingerprint"?"Same Device Fingerprint":"Rapid Signups";return r?e.jsx(cs,{}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s.length," suspicious pattern",s.length!==1?"s":""," detected"]}),s.length===0&&e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(la,{className:"h-10 w-10 mx-auto mb-2 text-emerald-400"}),"No suspicious patterns detected."]})}),s.map((j,b)=>e.jsx(z,{className:"glass border-destructive/20",children:e.jsxs(V,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[l(j.type),e.jsx("span",{className:"text-sm font-medium",children:o(j.type)}),e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:j.value})]}),e.jsxs($,{size:"sm",variant:"destructive",className:"h-7 text-xs gap-1",onClick:()=>a(j.referrals.map(c=>c.id)),children:[e.jsx(Ct,{className:"h-3 w-3"})," Mark All Invalid"]})]}),e.jsx("div",{className:"space-y-1",children:j.referrals.map(c=>e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[c.referrer_name," â ",c.referred_name]}),e.jsx(Y,{className:c.status==="invalid"?"bg-destructive/20 text-destructive border-destructive/30 text-[10px]":"bg-accent/20 text-accent border-accent/30 text-[10px]",children:c.status}),e.jsx("span",{children:new Date(c.created_at).toLocaleString()})]},c.id))})]})},b))]})}function Cc(){const[s,t]=i.useState([]),[r,n]=i.useState(!0);return i.useEffect(()=>{(async()=>{const{data:l}=await x.from("referrals").select("referrer_id, referred_id, status, source");if(!l){n(!1);return}l.filter(f=>f.source==="recruiter");const o=l,j=new Map;o.forEach(f=>{j.has(f.referrer_id)||j.set(f.referrer_id,{recruited:0,approved:0,referredIds:[]});const _=j.get(f.referrer_id);_.recruited++,f.status==="qualified"&&_.approved++,_.referredIds.push(f.referred_id)});const b=[...j.keys()];if(b.length===0){n(!1);return}const{data:c}=await x.from("profiles").select("user_id, display_name, avatar_url").in("user_id",b),d=new Map((c||[]).map(f=>[f.user_id,f])),P=[...new Set(o.map(f=>f.referred_id))],{data:k}=await x.from("seller_profiles").select("user_id").in("user_id",P),p=new Set((k==null?void 0:k.map(f=>f.user_id))||[]),h=Array.from(j.entries()).map(([f,_])=>{var m,u;return{userId:f,name:((m=d.get(f))==null?void 0:m.display_name)||"Unknown",avatar:((u=d.get(f))==null?void 0:u.avatar_url)||null,recruited:_.recruited,uploaded:_.referredIds.filter(g=>p.has(g)).length,approved:_.approved}}).sort((f,_)=>_.recruited-f.recruited);t(h),n(!1)})()},[]),r?e.jsx(cs,{}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s.length," active recruiter",s.length!==1?"s":""]}),s.length===0&&e.jsx(z,{className:"glass",children:e.jsx(V,{className:"p-8 text-center text-muted-foreground",children:"No recruiter data yet."})}),e.jsx("div",{className:"space-y-2",children:s.map((a,l)=>{var o;return e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 flex items-center gap-4",children:[e.jsx("span",{className:"text-sm font-mono text-muted-foreground w-6 text-center",children:l+1}),e.jsx(da,{to:`/user/${encodeURIComponent(a.name)}`,children:e.jsxs(Bs,{className:"h-10 w-10 border border-border",children:[e.jsx(it,{src:a.avatar||void 0}),e.jsx(qs,{className:"bg-muted text-xs",children:(o=a.name[0])==null?void 0:o.toUpperCase()})]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(da,{to:`/user/${encodeURIComponent(a.name)}`,className:"text-sm font-display font-semibold hover:text-primary transition-colors",children:a.name})}),e.jsxs("div",{className:"flex gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-display font-bold text-primary",children:a.recruited}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Recruited"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-display font-bold text-accent",children:a.uploaded}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Uploaded"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-display font-bold text-emerald-400",children:a.approved}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Approved"})]})]})]})},a.userId)})})]})}function Ac(){const[s,t]=i.useState([]),[r,n]=i.useState(!0),[a,l]=i.useState("pending"),[o,j]=i.useState(null),[b,c]=i.useState(""),d=async()=>{n(!0);const{data:h}=await x.from("recruiter_applications").select("*").order("created_at",{ascending:!1});if(h&&h.length>0){const f=h.map(u=>u.user_id),{data:_}=await x.from("profiles").select("user_id, display_name, avatar_url").in("user_id",f),m=new Map((_||[]).map(u=>[u.user_id,u]));t(h.map(u=>{var g,S;return{...u,display_name:(g=m.get(u.user_id))==null?void 0:g.display_name,avatar_url:(S=m.get(u.user_id))==null?void 0:S.avatar_url}}))}else t([]);n(!1)};i.useEffect(()=>{d()},[]);const P=async h=>{await x.from("recruiter_applications").update({status:"approved",admin_notes:b||h.admin_notes}).eq("id",h.id),await x.from("user_roles").insert({user_id:h.user_id,role:"recruiter"}),await x.from("notifications").insert({user_id:h.user_id,type:"recruiter_approved",title:"Recruiter Application Approved! ð",message:"Your recruiter application has been approved. You can now access the Recruiter Dashboard."}),O.success("Application approved & role assigned"),j(null),d()},k=async h=>{await x.from("recruiter_applications").update({status:"rejected",admin_notes:b||h.admin_notes}).eq("id",h.id),await x.from("notifications").insert({user_id:h.user_id,type:"recruiter_rejected",title:"Recruiter Application Update",message:"Your recruiter application was not approved at this time."}),O.success("Application rejected"),j(null),d()},p=s.filter(h=>a==="all"||h.status===a);return r?e.jsx(cs,{}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Pe,{value:a,onValueChange:l,children:[e.jsx(Te,{className:"w-[150px]",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All"}),e.jsx(L,{value:"pending",children:"Pending"}),e.jsx(L,{value:"approved",children:"Approved"}),e.jsx(L,{value:"rejected",children:"Rejected"})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground self-center",children:[p.length," application",p.length!==1?"s":""]})]}),p.length===0&&e.jsx(z,{className:"glass",children:e.jsx(V,{className:"p-8 text-center text-muted-foreground",children:"No applications foun
112d."})}),p.map(h=>{var f,_;return e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 flex items-center gap-4",children:[e.jsxs(Bs,{className:"h-10 w-10 border border-border",children:[e.jsx(it,{src:h.avatar_url||void 0}),e.jsx(qs,{className:"bg-muted text-xs",children:((_=(f=h.display_name)==null?void 0:f[0])==null?void 0:_.toUpperCase())||"?"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-display font-semibold text-sm",children:h.display_name||"Unknown"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Discord: ",h.discord_username," · ",new Date(h.created_at).toLocaleDateString()]})]}),e.jsx(Y,{className:h.status==="approved"?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30 text-[10px]":h.status==="rejected"?"bg-destructive/20 text-destructive border-destructive/30 text-[10px]":"bg-accent/20 text-accent border-accent/30 text-[10px]",children:h.status}),e.jsxs($,{size:"sm",variant:"outline",className:"h-7 text-xs gap-1",onClick:()=>{j(h),c(h.admin_notes||"")},children:[e.jsx(ws,{className:"h-3 w-3"})," View"]})]})},h.id)}),e.jsx(Ds,{open:!!o,onOpenChange:h=>!h&&j(null),children:e.jsxs(Ms,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(Es,{children:e.jsx(Os,{children:"Recruiter Application"})}),o&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Roblox:"})," ",o.roblox_username]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Discord:"})," ",o.discord_username]}),o.discord_id&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Discord ID:"})," ",o.discord_id]}),o.twitter_profile&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Twitter:"})," ",e.jsx("a",{href:o.twitter_profile,target:"_blank",rel:"noopener",className:"text-primary hover:underline",children:o.twitter_profile})]}),o.devforum_profile&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"DevForum:"})," ",e.jsx("a",{href:o.devforum_profile,target:"_blank",rel:"noopener",className:"text-primary hover:underline",children:"Profile"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Experience"}),e.jsx("p",{className:"text-sm bg-muted/50 rounded p-3",children:o.experience})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Where they'll find creators"}),e.jsx("p",{className:"text-sm bg-muted/50 rounded p-3",children:o.where_find_creators})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Why they want to recruit"}),e.jsx("p",{className:"text-sm bg-muted/50 rounded p-3",children:o.why_recruiter})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Admin Notes"}),e.jsx($s,{value:b,onChange:h=>c(h.target.value),rows:2,placeholder:"Internal notes..."})]}),o.status==="pending"&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{className:"flex-1 gap-1",onClick:()=>P(o),children:[e.jsx(la,{className:"h-4 w-4"})," Approve"]}),e.jsxs($,{variant:"destructive",className:"flex-1 gap-1",onClick:()=>k(o),children:[e.jsx(Ct,{className:"h-4 w-4"})," Reject"]})]})]})]})})]})}function Rc(){const[s,t]=i.useState([]),[r,n]=i.useState(!0);i.useEffect(()=>{(async()=>{const{data:o}=await x.from("user_roles").select("user_id, role").eq("role","recruiter");if(!o||o.length===0){n(!1);return}const j=o.map(f=>f.user_id),[{data:b},{data:c}]=await Promise.all([x.from("profiles").select("user_id, display_name, avatar_url").in("user_id",j),x.from("referrals").select("referrer_id, referred_id, status, source").in("referrer_id",j)]),d=new Map((b||[]).map(f=>[f.user_id,f])),P=new Map;(c||[]).filter(f=>f.source==="recruiter").forEach(f=>{P.has(f.referrer_id)||P.set(f.referrer_id,[]),P.get(f.referrer_id).push(f)});const k=[...new Set((c||[]).map(f=>f.referred_id))],{data:p}=k.length>0?await x.from("seller_profiles").select("user_id").in("user_id",k):{data:[]},h=new Set((p==null?void 0:p.map(f=>f.user_id))||[]);t(j.map(f=>{var m,u;const _=P.get(f)||[];return{userId:f,name:((m=d.get(f))==null?void 0:m.display_name)||"Unknown",avatar:(u=d.get(f))==null?void 0:u.avatar_url,recruited:_.length,uploaded:_.filter(g=>h.has(g.referred_id)).length,approved:_.filter(g=>g.status==="qualified").length}}).sort((f,_)=>_.recruited-f.recruited)),n(!1)})()},[]);const a=async l=>{await x.from("user_roles").delete().eq("user_id",l).eq("role","recruiter"),O.success("Recruiter role removed"),t(o=>o.filter(j=>j.userId!==l))};return r?e.jsx(cs,{}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s.length," active recruiter",s.length!==1?"s":""]}),s.length===0&&e.jsx(z,{className:"glass",children:e.jsx(V,{className:"p-8 text-center text-muted-foreground",children:"No recruiters yet."})}),s.map((l,o)=>{var j;return e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 flex items-center gap-4",children:[e.jsx("span",{className:"text-sm font-mono text-muted-foreground w-6 text-center",children:o+1}),e.jsx(da,{to:`/user/${encodeURIComponent(l.name)}
112`,children:e.jsxs(Bs,{className:"h-10 w-10 border border-border",children:[e.jsx(it,{src:l.avatar||void 0}),e.jsx(qs,{className:"bg-muted text-xs",children:(j=l.name[0])==null?void 0:j.toUpperCase()})]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(da,{to:`/user/${encodeURIComponent(l.name)}`,className:"text-sm font-display font-semibold hover:text-primary",children:l.name})}),e.jsxs("div",{className:"flex gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-display font-bold text-primary",children:l.recruited}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Recruited"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-display font-bold text-accent",children:l.uploaded}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Uploaded"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-display font-bold text-emerald-400",children:l.approved}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Approved"})]})]}),e.jsxs($,{size:"sm",variant:"outline",className:"h-7 text-xs gap-1 text-destructive",onClick:()=>a(l.userId),children:[e.jsx(Ct,{className:"h-3 w-3"})," Remove"]})]})},l.userId)})]})}function Pc(){const[s,t]=i.useState([]),[r,n]=i.useState(!0),[a,l]=i.useState(""),[o,j]=i.useState("all");i.useState(null);const[b,c]=i.useState("");i.useState("");const[d,P]=i.useState([]),k=async()=>{n(!0);const{data:u}=await x.from("creator_leads").select("*").order("created_at",{ascending:!1});if(u&&u.length>0){const S=[...new Set(u.filter(w=>w.assigned_recruiter).map(w=>w.assigned_recruiter).filter(w=>w!==null))],{data:M}=S.length>0?await x.from("profiles").select("user_id, display_name").in("user_id",S):{data:[]},y=new Map((M||[]).map(w=>[w.user_id,w.display_name]));t(u.map(w=>({...w,recruiter_name:y.get(w.assigned_recruiter??"")||"Unassigned"})))}else t([]);const{data:g}=await x.from("user_roles").select("user_id").eq("role","recruiter");if(g&&g.length>0){const{data:S}=await x.from("profiles").select("user_id, display_name").in("user_id",g.map(M=>M.user_id));P((S||[]).map(M=>({userId:M.user_id,name:M.display_name||"Unknown"})))}n(!1)};i.useEffect(()=>{k()},[]);const p=async(u,g)=>{await x.from("creator_leads").update(g).eq("id",u),O.success("Lead updated"),k()},h=async u=>{await x.from("creator_leads").delete().eq("id",u),O.success("Lead deleted"),k()},f=s.filter(u=>{var M,y;const g=!a||((M=u.creator_name)==null?void 0:M.toLowerCase().includes(a.toLowerCase()))||((y=u.recruiter_name)==null?void 0:y.toLowerCase().includes(a.toLowerCase())),S=o==="all"||u.status===o;return g&&S});if(r)return e.jsx(cs,{});const _=["new","contacted","follow_up_needed","interested","joined_platform","uploaded_asset","not_interested","no_response"],m=["high","normal","low"];return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(Gs,{placeholder:"Search leads...",value:a,onChange:l,wrapperClassName:"flex-1"}),e.jsxs(Pe,{value:o,onValueChange:j,children:[e.jsx(Te,{className:"w-[180px]",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Status"}),_.map(u=>e.jsx(L,{value:u,children:u.replace(/_/g," ")},u))]})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[f.length," lead",f.length!==1?"s":""]}),f.length===0&&e.jsx(z,{className:"glass",children:e.jsx(V,{className:"p-8 text-center text-muted-foreground",children:"No leads found."})}),f.map(u=>e.jsx(z,{className:`glass ${u.priority==="high"?"border-primary/30":""}`,children:e.jsxs(V,{className:"p-4 space-y-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"font-display font-semibold text-sm",children:u.creator_name}),e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:u.platform}),e.jsx(Y,{className:u.priority==="high"?"bg-destructive/20 text-destructive border-destructive/30 text-[10px]":u.priority==="low"?"bg-muted text-muted-foreground text-[10px]":"bg-accent/20 text-accent border-accent/30 text-[10px]",children:u.priority}),e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:u.status.replace(/_/g," ")})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Recruiter: ",u.recruiter_name," · ",u.contact_attempts," attempts"]}),u.recruiter_notes&&e.jsxs("p",{className:"text-xs text-muted-foreground italic mt-1",children:['Recruiter: "',u.recruiter_notes,'"']}),u.admin_notes&&e.jsxs("p",{className:"text-xs text-primary italic mt-1",children:['Admin: "',u.admin_notes,'"']})]})}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(Pe,{value:u.status,onValueChange:g=>p(u.id,{status:g}),children:[e.jsx(Te,{className:"h-7 w-[140px] text-xs",children:e.jsx(De,{})}),e.jsx(Me,{children:_.map(g=>e.jsx(L,{value:g,children:g.replace(/_/g," ")},g))})]}),e.jsxs(Pe,{value:u.priority,onValueChange:g=>p(u.id,{priority:g}),children:[e.jsx(Te,{className:"h-7 w-[100px] text-xs",children:e.jsx(De,{})}),e.jsx(Me,{children:m.map(g=>e.jsx(L,{value:g,children:g},g))})]}),e.jsxs(Pe,{value:u.assigned_recruiter||"",onValueChange:g=>p(u.id,{assigned_recruiter:g||null}),children:[e.jsx(Te,{className:"h-7 w-[140px] text-xs",children:e.jsx(De,{placeholder:"Assign..."})}),e.jsx(Me,{children:d.map(g=>e.jsx(L,{value:g.userId,children:g.name}
112,g.userId))})]}),e.jsxs(Ds,{children:[e.jsx(an,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"outline",className:"h-7 text-xs gap-1",children:[e.jsx(ua,{className:"h-3 w-3"})," Notes"]})}),e.jsxs(Ms,{className:"max-w-sm",children:[e.jsx(Es,{children:e.jsx(Os,{children:"Admin Notes"})}),e.jsx($s,{defaultValue:u.admin_notes||"",onChange:g=>c(g.target.value),rows:3}),e.jsx($,{onClick:()=>{p(u.id,{admin_notes:b})},children:"Save Notes"})]})]}),e.jsxs($,{size:"sm",variant:"outline",className:"h-7 text-xs gap-1 text-destructive",onClick:()=>h(u.id),children:[e.jsx(As,{className:"h-3 w-3"})," Delete"]})]})]})},u.id))]})}function Tc(){return e.jsxs(wl,{defaultValue:"applications",className:"space-y-4",children:[e.jsxs(Sl,{className:"glass",children:[e.jsxs(na,{value:"applications",className:"gap-1",children:[e.jsx(Ws,{className:"h-4 w-4"})," Applications"]}),e.jsxs(na,{value:"management",className:"gap-1",children:[e.jsx(bt,{className:"h-4 w-4"})," Recruiters"]}),e.jsxs(na,{value:"leads",className:"gap-1",children:[e.jsx($a,{className:"h-4 w-4"})," Leads"]})]}),e.jsx(ia,{value:"applications",children:e.jsx(Ac,{})}),e.jsx(ia,{value:"management",children:e.jsx(Rc,{})}),e.jsx(ia,{value:"leads",children:e.jsx(Pc,{})})]})}var Dc=["points","className","baseLinePoints","connectNulls"];function Sa(){return Sa=Object.assign?Object.assign.bind():function(s){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(s[n]=r[n])}return s},Sa.apply(this,arguments)}function Mc(s,t){if(s==null)return{};var r=Ec(s,t),n,a;if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(s);for(a=0;a<l.length;a++)n=l[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function Ec(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function Ki(s){return $c(s)||Fc(s)||Lc(s)||Oc()}function Oc(){throw new TypeError(`Invalid attempt to spread non-iterable instance. 113In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Lc(s,t){if(s){if(typeof s=="string")return Zn(s,t);var r=Object.prototype.toString.call(s).slice(8,-1);if(r==="Object"&&s.constructor&&(r=s.constructor.name),r==="Map"||r==="Set")return Array.from(s);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Zn(s,t)}}function Fc(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function $c(s){if(Array.isArray(s))return Zn(s)}function Zn(s,t){(t==null||t>s.length)&&(t=s.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=s[r];return n}var Ji=function(t){return t&&t.x===+t.x&&t.y===+t.y},Uc=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],r=[[]];return t.forEach(function(n){Ji(n)?r[r.length-1].push(n):r[r.length-1].length>0&&r.push([])}),Ji(t[0])&&r[r.length-1].push(t[0]),r[r.length-1].length<=0&&(r=r.slice(0,-1)),r},sr=function(t,r){var n=Uc(t);r&&(n=[n.reduce(function(l,o){return[].concat(Ki(l),Ki(o))},[])]);var a=n.map(function(l){return l.reduce(function(o,j,b){return"".concat(o).concat(b===0?"M":"L").concat(j.x,",").concat(j.y)},"")}).join("");return n.length===1?"".concat(a,"Z"):a},Ic=function(t,r,n){var a=sr(t,n);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(sr(r.reverse(),n).slice(1))},zc=function(t){var r=t.points,n=t.className,a=t.baseLinePoints,l=t.connectNulls,o=Mc(t,Dc);if(!r||!r.length)return null;var j=$t("recharts-polygon",n);if(a&&a.length){var b=o.stroke&&o.stroke!=="none",c=Ic(r,a,l);return Qe.createElement("g",{className:j},Qe.createElement("path",Sa({},_s(o,!0),{fill:c.slice(-1)==="Z"?o.fill:"none",stroke:"none",d:c})),b?Qe.createElement("path",Sa({},_s(o,!0),{fill:"none",d:sr(r,l)})):null,b?Qe.createElement("path",Sa({},_s(o,!0),{fill:"none",d:sr(a,l)})):null)}var d=sr(r,l);return Qe.createElement("path",Sa({},_s(o,!0),{fill:d.slice(-1)==="Z"?o.fill:"none",className:j,d}))},Vc=Cl,Bc=$o,qc=Al;function Wc(s,t){return s&&s.length?Vc(s,qc(t),Bc):void 0}var Gc=Wc;const Hc=Nl(Gc);var Kc=Cl,Jc=Al,Qc=Uo;function Yc(s,t){return s&&s.length?Kc(s,Jc(t),Qc):void 0}var Zc=Yc;const Xc=Nl(Zc);
vendor: 21,630 bytes, line 113
113var ed=["cx","cy","angle","ticks","axisLine"],sd=["ticks","tick","angle","tickFormatter","stroke"];function Ea(s){"@babel/helpers - typeof";return Ea=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ea(s)}function tr(){return tr=Object.assign?Object.assign.bind():function(s){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(s[n]=r[n])}return s},tr.apply(this,arguments)}function Qi(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function ea(s){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Qi(Object(r),!0).forEach(function(n){ln(s,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(r)):Qi(Object(r)).forEach(function(n){Object.defineProperty(s,n,Object.getOwnPropertyDescriptor(r,n))})}return s}function Yi(s,t){if(s==null)return{};var r=td(s,t),n,a;if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(s);for(a=0;a<l.length;a++)n=l[a],!(t.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(s,n)&&(r[n]=s[n])}return r}function td(s,t){if(s==null)return{};var r={};for(var n in s)if(Object.prototype.hasOwnProperty.call(s,n)){if(t.indexOf(n)>=0)continue;r[n]=s[n]}return r}function ad(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Zi(s,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(s,Bl(n.key),n)}}function rd(s,t,r){return t&&Zi(s.prototype,t),r&&Zi(s,r),Object.defineProperty(s,"prototype",{writable:!1}),s}function nd(s,t,r){return t=Wr(t),id(s,Vl()?Reflect.construct(t,r||[],Wr(s).constructor):t.apply(s,r))}function id(s,t){if(t&&(Ea(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return ld(s)}function ld(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s}function Vl(){try{var s=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Vl=function(){return!!s})()}function Wr(s){return Wr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Wr(s)}function od(s,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");s.prototype=Object.create(t&&t.prototype,{constructor:{value:s,writable:!0,configurable:!0}}),Object.defineProperty(s,"prototype",{writable:!1}),t&&Xn(s,t)}function Xn(s,t){return Xn=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},Xn(s,t)}function ln(s,t,r){return t=Bl(t),t in s?Object.defineProperty(s,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):s[t]=r,s}function Bl(s){var t=cd(s,"string");return Ea(t)=="symbol"?t:t+""}function cd(s,t){if(Ea(s)!="object"||!s)return s;var r=s[Symbol.toPrimitive];if(r!==void 0){var n=r.call(s,t||"default");if(Ea(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(s)}var on=function(s){function t(){return ad(this,t),nd(this,t,arguments)}return od(t,s),rd(t,[{key:"getTickValueCoord",value:function(n){var a=n.coordinate,l=this.props,o=l.angle,j=l.cx,b=l.cy;return Pt(j,b,a,o)}},{key:"getTickTextAnchor",value:function(){var n=this.props.orientation,a;switch(n){case"left":a="end";break;case"right":a="start";break;default:a="middle";break}return a}},{key:"getViewBox",value:function(){var n=this.props,a=n.cx,l=n.cy,o=n.angle,j=n.ticks,b=Hc(j,function(d){return d.coordinate||0}),c=Xc(j,function(d){return d.coordinate||0});return{cx:a,cy:l,startAngle:o,endAngle:o,innerRadius:c.coordinate||0,outerRadius:b.coordinate||0}}},{key:"renderAxisLine",value:function(){var n=this.props,a=n.cx,l=n.cy,o=n.angle,j=n.ticks,b=n.axisLine,c=Yi(n,ed),d=j.reduce(function(h,f){return[Math.min(h[0],f.coordinate),Math.max(h[1],f.coordinate)]},[1/0,-1/0]),P=Pt(a,l,d[0],o),k=Pt(a,l,d[1],o),p=ea(ea(ea({},_s(c,!1)),{},{fill:"none"},_s(b,!1)),{},{x1:P.x,y1:P.y,x2:k.x,y2:k.y});return Qe.createElement("line",tr({className:"recharts-polar-radius-axis-line"},p))}},{key:"renderTicks",value:function(){var n=this,a=this.props,l=a.ticks,o=a.tick,j=a.angle,b=a.tickFormatter,c=a.stroke,d=Yi(a,sd),P=this.getTickTextAnchor(),k=_s(d,!1),p=_s(o,!1),h=l.map(function(f,_){var m=n.getTickValueCoord(f),u=ea(ea(ea(ea({textAnchor:P,transform:"rotate(".concat(90-j,", ").concat(m.x,", ").concat(m.y,")")},k),{},{stroke:"none",fill:c},p),{},{index:_},m),{},{payload:f});return Qe.createElement(at,tr({className:$t("recharts-polar-radius-axis-tick",Rl(o)),key:"tick-".concat(f.coordinate)},ci(n.props,f,_)),t.renderTickItem(o,u,b?b(f.value,_):f.value))});return Qe.createElement(at,{className:"recharts-polar-radius-axis-ticks"},h)}},{key:"render",value:function(){var n=this.props,a=n.ticks,l=n.axisLine,o=n.tick;return!a||!a.length?null:Qe.createElement(at,{className:$t("recharts-polar-radius-axis",this.props.className)},l&&this.renderAxisLine(),o&&this.renderTicks(),Pl.renderCallByParent(this.props,this.getViewBox()))}}],[{key:"renderTickItem",value:function(n,a,l){var o;return Qe.isValidElement(n)?o=Qe.cloneElement(n,a):ta(n)?o=n(a):o=Qe.createElement(oi,tr({},a,{className:"recharts-polar-radius-axis-tick-value"}),l),o}}])}(i.PureComponent);ln(on,"displayName","PolarRadiusAxis");ln(on,"axisType","radiusAxis");ln(on,"defaultProps",{type:"number",radiusAxisId:0,cx:0,cy:0,angle:0,orientation:"right",stroke:"#ccc",axisLine:!0,tick:!0,tickCount:5,allowDataOverflow:!1,scale:"auto",allowDuplicatedCategory:!0});function Oa(s){"@babel/helpers - typeof";return Oa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Oa(s)}function ra(){return ra=Object.assign?Object.assign.bind():function(s){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(s[n]=r[n])}return s},ra.apply(this,arguments)}function Xi(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function sa(s){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Xi(Object(r),!0).forEach(function(n){cn(s,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(r)):Xi(Object(r)).forEach(function(n){Object.defineProperty(s,n,Object.getOwnPropertyDescriptor(r,n))})}return s}function dd(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function el(s,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(s,Wl(n.key),n)}}function md(s,t,r){return t&&el(s.prototype,t),r&&el(s,r),Object.defineProperty(s,"prototype",{writable:!1}),s}function ud(s,t,r){return t=Gr(t),xd(s,ql()?Reflect.construct(t,r||[],Gr(s).constructor):t.apply(s,r))}function xd(s,t){if(t&&(Oa(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return pd(s)}function pd(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s}function ql(){try{var s=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(ql=function(){return!!s})()}function Gr(s){return Gr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Gr(s)}function hd(s,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");s.prototype=Object.create(t&&t.prototype,{constructor:{value:s,writable:!0,configurable:!0}}),Object.defineProperty(s,"prototype",{writable:!1}),t&&ei(s,t)}function ei(s,t){return ei=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},ei(s,t)}function cn(s,t,r){return t=Wl(t),t in s?Object.defineProperty(s,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):s[t]=r,s}function Wl(s){var t=gd(s,"string");return Oa(t)=="symbol"?t:t+""}function gd(s,t){if(Oa(s)!="object"||!s)return s;var r=s[Symbol.toPrimitive];if(r!==void 0){var n=r.call(s,t||"default");if(Oa(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(s)}var fd=Math.PI/180,sl=1e-5,dn=function(s){function t(){return dd(this,t),ud(this,t,arguments)}return hd(t,s),md(t,[{key:"getTickLineCoord",value:function(n){var a=this.props,l=a.cx,o=a.cy,j=a.radius,b=a.orientation,c=a.tickSize,d=c||8,P=Pt(l,o,j,n.coordinate),k=Pt(l,o,j+(b==="inner"?-1:1)*d,n.coordinate);return{x1:P.x,y1:P.y,x2:k.x,y2:k.y}}},{key:"getTickTextAnchor",value:function(n){var a=this.props.orientation,l=Math.cos(-n.coordinate*fd),o;return l>sl?o=a==="outer"?"start":"end":l<-sl?o=a==="outer"?"end":"start":o="middle",o}},{key:"renderAxisLine",value:function(){var n=this.props,a=n.cx,l=n.cy,o=n.radius,j=n.axisLine,b=n.axisLineType,c=sa(sa({},_s(this.props,!1)),{},{fill:"none"},_s(j,!1));if(b==="circle")return Qe.createElement(Io,ra({className:"recharts-polar-angle-axis-line"},c,{cx:a,cy:l,r:o}));var d=this.props.ticks,P=d.map(function(k){return Pt(a,l,o,k.coordinate)});return Qe.createElement(zc,ra({className:"recharts-polar-angle-axis-line"},c,{points:P}))}},{key:"renderTicks",value:function(){var n=this,a=this.props,l=a.ticks,o=a.tick,j=a.tickLine,b=a.tickFormatter,c=a.stroke,d=_s(this.props,!1),P=_s(o,!1),k=sa(sa({},d),{},{fill:"none"},_s(j,!1)),p=l.map(function(h,f){var _=n.getTickLineCoord(h),m=n.getTickTextAnchor(h),u=sa(sa(sa({textAnchor:m},d),{},{stroke:"none",fill:c},P),{},{index:f,payload:h,x:_.x2,y:_.y2});return Qe.createElement(at,ra({className:$t("recharts-polar-angle-axis-tick",Rl(o)),key:"tick-".concat(h.coordinate)},ci(n.props,h,f)),j&&Qe.createElement("line",ra({className:"recharts-polar-angle-axis-tick-line"},k,_)),o&&t.renderTickItem(o,u,b?b(h.value,f):h.value))});return Qe.createElement(at,{className:"recharts-polar-angle-axis-ticks"},p)}},{key:"render",value:function(){var n=this.props,a=n.ticks,l=n.radius,o=n.axisLine;return l<=0||!a||!a.length?null:Qe.createElement(at,{className:$t("recharts-polar-angle-axis",this.props.className)},o&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(n,a,l){var o;return Qe.isValidElement(n)?o=Qe.cloneElement(n,a):ta(n)?o=n(a):o=Qe.createElement(oi,ra({},a,{className:"recharts-polar-angle-axis-tick-value"}),l),o}}])}(i.PureComponent);cn(dn,"displayName","PolarAngleAxis");cn(dn,"axisType","angleAxis");cn(dn,"defaultProps",{type:"category",angleAxisId:0,scale:"auto",cx:0,cy:0,orientation:"outer",axisLine:!0,tickLine:!0,tickSize:8,tick:!0,hide:!1,allowDuplicatedCategory:!0});var $r;function La(s){"@babel/helpers - typeof";return La=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},La(s)}function ka(){return ka=Object.assign?Object.assign.bind():function(s){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(s[n]=r[n])}return s},ka.apply(this,arguments)}function tl(s,t){var r=Object.keys(s);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(s);t&&(n=n.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),r.push.apply(r,n)}return r}function os(s){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?tl(Object(r),!0).forEach(function(n){zs(s,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(r)):tl(Object(r)).forEach(function(n){Object.defineProperty(s,n,Object.getOwnPropertyDescriptor(r,n))})}return s}function jd(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function al(s,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(s,Hl(n.key),n)}}function vd(s,t,r){return t&&al(s.prototype,t),r&&al(s,r),Object.defineProperty(s,"prototype",{writable:!1}),s}function bd(s,t,r){return t=Hr(t),yd(s,Gl()?Reflect.construct(t,r||[],Hr(s).constructor):t.apply(s,r))}function yd(s,t){if(t&&(La(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Nd(s)}function Nd(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s}function Gl(){try{var s=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(Gl=function(){return!!s})()}function Hr(s){return Hr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Hr(s)}function _d(s,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");s.prototype=Object.create(t&&t.prototype,{constructor:{value:s,writable:!0,configurable:!0}}),Object.defineProperty(s,"prototype",{writable:!1}),t&&si(s,t)}function si(s,t){return si=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,a){return n.__proto__=a,n},si(s,t)}function zs(s,t,r){return t=Hl(t),t in s?Object.defineProperty(s,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):s[t]=r,s}function Hl(s){var t=wd(s,"string");return La(t)=="symbol"?t:t+""}function wd(s,t){if(La(s)!="object"||!s)return s;var r=s[Symbol.toPrimitive];if(r!==void 0){var n=r.call(s,t||"default");if(La(n)!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(s)}var Hs=function(s){function t(r){var n;return jd(this,t),n=bd(this,t,[r]),zs(n,"pieRef",null),zs(n,"sectorRefs",[]),zs(n,"id",Qo("recharts-pie-")),zs(n,"handleAnimationEnd",function(){var a=n.props.onAnimationEnd;n.setState({isAnimationFinished:!0}),ta(a)&&a()}),zs(n,"handleAnimationStart",function(){var a=n.props.onAnimationStart;n.setState({isAnimationFinished:!1}),ta(a)&&a()}),n.state={isAnimationFinished:!r.isAnimationActive,prevIsAnimationActive:r.isAnimationActive,prevAnimationId:r.animationId,sectorToFocus:0},n}return _d(t,s),vd(t,[{key:"isActiveIndex",value:function(n){var a=this.props.activeIndex;return Array.isArray(a)?a.indexOf(n)!==-1:n===a}},{key:"hasActiveIndex",value:function(){var n=this.props.activeIndex;return Array.isArray(n)?n.length!==0:n||n===0}},{key:"renderLabels",value:function(n){var a=this.props.isAnimationActive;if(a&&!this.state.isAnimationFinished)return null;var l=this.props,o=l.label,j=l.labelLine,b=l.dataKey,c=l.valueKey,d=_s(this.props,!1),P=_s(o,!1),k=_s(j,!1),p=o&&o.offsetRadius||20,h=n.map(function(f,_){var m=(f.startAngle+f.endAngle)/2,u=Pt(f.cx,f.cy,f.outerRadius+p,m),g=os(os(os(os({},d),f),{},{stroke:"none"},P),{},{index:_,textAnchor:t.getTextAnchor(u.x,f.cx)},u),S=os(os(os(os({},d),f),{},{fill:"none",stroke:f.fill},k),{},{index:_,points:[Pt(f.cx,f.cy,f.outerRadius,m),u]}),M=b;return Aa(b)&&Aa(c)?M="value":Aa(b)&&(M=c),Qe.createElement(at,{key:"label-".concat(f.startAngle,"-").concat(f.endAngle,"-").concat(f.midAngle,"-").concat(_)},j&&t.renderLabelLineItem(j,S,"line"),t.renderLabelItem(o,g,_a(f,M)))});return Qe.createElement(at,{className:"recharts-pie-labels"},h)}},{key:"renderSectorsStatically",value:function(n){var a=this,l=this.props,o=l.activeShape,j=l.blendStroke,b=l.inactiveShape;return n.map(function(c,d){if((c==null?void 0:c.startAngle)===0&&(c==null?void 0:c.endAngle)===0&&n.length!==1)return null;var P=a.isActiveIndex(d),k=b&&a.hasActiveIndex()?b:null,p=P?o:k,h=os(os({},c),{},{stroke:j?c.fill:c.stroke,tabIndex:-1});return Qe.createElement(at,ka({ref:function(_){_&&!a.sectorRefs.includes(_)&&a.sectorRefs.push(_)},tabIndex:-1,className:"recharts-pie-sector"},ci(a.props,c,d),{key:"sector-".concat(c==null?void 0:c.startAngle,"-").concat(c==null?void 0:c.endAngle,"-").concat(c.midAngle,"-").concat(d)}),Qe.createElement(Vo,ka({option:p,isActive:P,shapeType:"sector"},h)))})}},{key:"renderSectorsWithAnimation",value:function(){var n=this,a=this.props,l=a.sectors,o=a.isAnimationActive,j=a.animationBegin,b=a.animationDuration,c=a.animationEasing,d=a.animationId,P=this.state,k=P.prevSectors,p=P.prevIsAnimationActive;return Qe.createElement(Bo,{begin:j,duration:b,isActive:o,easing:c,from:{t:0},to:{t:1},key:"pie-".concat(d,"-").concat(p),onAnimationStart:this.handleAnimationStart,onAnimationEnd:this.handleAnimationEnd},function(h){var f=h.t,_=[],m=l&&l[0],u=m.startAngle;return l.forEach(function(g,S){var M=k&&k[S],y=S>0?qo(g,"paddingAngle",0):0;if(M){var w=Li(M.endAngle-M.startAngle,g.endAngle-g.startAngle),F=os(os({},g),{},{startAngle:u+y,endAngle:u+w(f)+y});_.push(F),u=F.endAngle}else{var J=g.endAngle,E=g.startAngle,N=Li(0,J-E),U=N(f),R=os(os({},g),{},{startAngle:u+y,endAngle:u+U+y});_.push(R),u=R.endAngle}}),Qe.createElement(at,null,n.renderSectorsStatically(_))})}},{key:"attachKeyboardHandlers",value:function(n){var a=this;n.onkeydown=function(l){if(!l.altKey)switch(l.key){case"ArrowLeft":{var o=++a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[o].focus(),a.setState({sectorToFocus:o});break}case"ArrowRight":{var j=--a.state.sectorToFocus<0?a.sectorRefs.length-1:a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[j].focus(),a.setState({sectorToFocus:j});break}case"Escape":{a.sectorRefs[a.state.sectorToFocus].blur(),a.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var n=this.props,a=n.sectors,l=n.isAnimationActive,o=this.state.prevSectors;return l&&a&&a.length&&(!o||!Wo(o,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var n=this,a=this.props,l=a.hide,o=a.sectors,j=a.className,b=a.label,c=a.cx,d=a.cy,P=a.innerRadius,k=a.outerRadius,p=a.isAnimationActive,h=this.state.isAnimationFinished;if(l||!o||!o.length||!wa(c)||!wa(d)||!wa(P)||!wa(k))return null;var f=$t("recharts-pie",j);return Qe.createElement(at,{tabIndex:this.props.rootTabIndex,className:f,ref:function(m){n.pieRef=m}},this.renderSectors(),b&&this.renderLabels(o),Pl.renderCallByParent(this.props,null,!1),(!p||h)&&Go.renderCallByParent(this.props,o,!1))}}],[{key:"getDerivedStateFromProps",value:function(n,a){return a.prevIsAnimationActive!==n.isAnimationActive?{prevIsAnimationActive:n.isAnimationActive,prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:[],isAnimationFinished:!0}:n.isAnimationActive&&n.animationId!==a.prevAnimationId?{prevAnimationId:n.animationId,curSectors:n.sectors,prevSectors:a.curSectors,isAnimationFinished:!0}:n.sectors!==a.curSectors?{curSectors:n.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(n,a){return n>a?"start":n<a?"end":"middle"}},{key:"renderLabelLineItem",value:function(n,a,l){if(Qe.isValidElement(n))return Qe.cloneElement(n,a);if(ta(n))return n(a);var o=$t("recharts-pie-label-line",typeof n!="boolean"?n.className:"");return Qe.createElement(zo,ka({},a,{key:l,type:"linear",className:o}))}},{key:"renderLabelItem",value:function(n,a,l){if(Qe.isValidElement(n))return Qe.cloneElement(n,a);var o=l;if(ta(n)&&(o=n(a),Qe.isValidElement(o)))return o;var j=$t("recharts-pie-label-text",typeof n!="boolean"&&!ta(n)?n.className:"");return Qe.createElement(oi,ka({},a,{alignmentBaseline:"middle",className:j}),o)}}])}(i.PureComponent);$r=Hs;zs(Hs,"displayName","Pie");zs(Hs,"defaultProps",{stroke:"#fff",fill:"#808080",legendType:"rect",cx:"50%",cy:"50%",startAngle:0,endAngle:360,innerRadius:0,outerRadius:"80%",paddingAngle:0,labelLine:!0,hide:!1,minAngle:0,isAnimationActive:!Ho.isSsr,animationBegin:400,animationDuration:1500,animationEasing:"ease",nameKey:"name",blendStroke:!1,rootTabIndex:0});zs(Hs,"parseDeltaAngle",function(s,t){var r=Lr(t-s),n=Math.min(Math.abs(t-s),360);return r*n});zs(Hs,"getRealPieData",function(s){var t=s.data,r=s.children,n=_s(s,!1),a=Ko(r,Da);return t&&t.length?t.map(function(l,o){return os(os(os({payload:l},n),l),a&&a[o]&&a[o].props)}):a&&a.length?a.map(function(l){return os(os({},n),l.props)}):[]});zs(Hs,"parseCoordinateOfPie",function(s,t){var r=t.top,n=t.left,a=t.width,l=t.height,o=Jo(a,l),j=n+Rr(s.cx,a,a/2),b=r+Rr(s.cy,l,l/2),c=Rr(s.innerRadius,o,0),d=Rr(s.outerRadius,o,o*.8),P=s.maxRadius||Math.sqrt(a*a+l*l)/2;return{cx:j,cy:b,innerRadius:c,outerRadius:d,maxRadius:P}});zs(Hs,"getComposedData",function(s){var t=s.item,r=s.offset,n=t.type.defaultProps!==void 0?os(os({},t.type.defaultProps),t.props):t.props,a=$r.getRealPieData(n);if(!a||!a.length)return null;var l=n.cornerRadius,o=n.startAngle,j=n.endAngle,b=n.paddingAngle,c=n.dataKey,d=n.nameKey,P=n.valueKey,k=n.tooltipType,p=Math.abs(n.minAngle),h=$r.parseCoordinateOfPie(n,r),f=$r.parseDeltaAngle(o,j),_=Math.abs(f),m=c;Aa(c)&&Aa(P)?(Fi(!1,`Use "dataKey" to specify the value of pie,
114 the props "valueKey" will be deprecated in 1.1.0`),m="value"):Aa(c)&&(Fi(!1,`Use "dataKey" to specify the value of pie, 115 the props "valueKey" will be deprecated in 1.1.0`),m=P);var u=a.filter(function(F){return _a(F,m,0)!==0}).length,g=(_>=360?u:u-1)*b,S=_-u*p-g,M=a.reduce(function(F,J){var E=_a(J,m,0);return F+(wa(E)?E:0)},0),y;if(M>0){var w;y=a.map(function(F,J){var E=_a(F,m,0),N=_a(F,d,J),U=(wa(E)?E:0)/M,R;J?R=w.endAngle+Lr(f)*b*(E!==0?1:0):R=o;var Z=R+Lr(f)*((E!==0?p:0)+U*S),W=(R+Z)/2,D=(h.innerRadius+h.outerRadius)/2,X=[{name:N,value:E,payload:F,dataKey:m,type:k}],oe=Pt(h.cx,h.cy,D,W);return w=os(os(os({percent:U,cornerRadius:l,name:N,tooltipPayload:X,midAngle:W,middleRadius:D,tooltipPosition:oe},F),h),{},{value:_a(F,m),startAngle:R,endAngle:Z,payload:F,paddingAngle:Lr(f)*b}),w})}return os(os({},h),{},{sectors:y,data:a})});var mn=Yo({chartName:"PieChart",GraphicalChild:Hs,validateTooltipEventTypes:["item"],defaultTooltipEventType:"item",legendContent:"children",axisComponents:[{axisType:"angleAxis",AxisComp:dn},{axisType:"radiusAxis",AxisComp:on}],formatAxisMap:Zo,defaultProps:{layout:"centric",startAngle:0,endAngle:360,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"}});const rl=[{url:"/",label:"Homepage"},{url:"/shop",label:"Shop"},{url:"/creators",label:"Creators"},{url:"/dashboard/seller",label:"Become a Seller"},{url:"/roblox-scripts",label:"Roblox Scripts"},{url:"/roblox-models",label:"Roblox Models"},{url:"/roblox-ui",label:"Roblox UI"},{url:"/roblox-maps",label:"Roblox Maps"},{url:"/roblox-game-setups",label:"Game Setups"},{url:"/best-roblox-scripts",label:"Best Scripts"},{url:"/free-roblox-assets",label:"Free Assets"},{url:"/roblox-combat-system",label:"Combat System"},{url:"/roblox-inventory-system",label:"Inventory System"}],Sd=[{key:"total_indexed",label:"Total Indexed Pages",type:"number",tooltip:"Number of pages Google has indexed from your site"},{key:"crawl_errors",label:"Crawl Errors",type:"number",tooltip:"Pages Google couldn't crawl successfully"},{key:"sitemap_status",label:"Sitemap Status",type:"text",tooltip:"Success / Error / Pending â from GSC Sitemaps tab"},{key:"discovered_urls",label:"Discovered URLs",type:"number",tooltip:"Total URLs discovered via sitemap"},{key:"impressions_28d",label:"Impressions (28d)",type:"number",tooltip:"Total search impressions in the last 28 days"},{key:"clicks_28d",label:"Clicks (28d)",type:"number",tooltip:"Total clicks from search in the last 28 days"},{key:"avg_position",label:"Avg Position",type:"text",tooltip:"Average search ranking position"},{key:"avg_ctr",label:"Avg CTR",type:"text",tooltip:"Average click-through rate from search"}],kd=[{id:"title",label:"Title <60 chars",tooltip:"Page title should be under 60 characters for full display in search"},{id:"desc",label:"Description <160 chars",tooltip:"Meta description should be under 160 characters"},{id:"og_image",label:"OG image present",tooltip:"Open Graph image set for social sharing previews"},{id:"json_ld",label:"JSON-LD structured data",tooltip:"Schema.org structured data for rich search results"},{id:"canonical",label:"Canonical URL set",tooltip:"Canonical tag prevents duplicate content issues"},{id:"breadcrumbs",label:"Breadcrumbs injected",tooltip:"Breadcrumb structured data for navigation in search"},{id:"twitter_card",label:"Twitter Card tags",tooltip:"Twitter meta tags for proper card display"},{id:"h1_unique",label:"Single H1 tag",tooltip:"Each page should have exactly one H1 heading"}],Cd=[{text:"Submit sitemap in GSC after adding new products",priority:"high"},{text:"Request indexing for new product/category pages",priority:"high"},{text:"Add unique descriptive content to category pages",priority:"medium"},{text:"Ensure all products have og:image set",priority:"medium"},{text:"Create guide/tutorial pages for long-tail keywords",priority:"low"},{text:"Add internal links between related products",priority:"low"},{text:"Monitor crawl errors weekly in GSC",priority:"high"},{text:"Check mobile usability report in GSC",priority:"medium"}],Qa="https://romarkets.shop",ya=15,Bn=1e3,Ad=1e4;function qn({text:s}){return e.jsxs(en,{children:[e.jsx(sn,{asChild:!0,children:e.jsx(kl,{className:"h-3.5 w-3.5 text-muted-foreground
115/60 cursor-help inline-block ml-1"})}),e.jsx(tn,{side:"top",className:"max-w-[240px] text-xs",children:s})]})}function Na({icon:s,title:t,children:r}){return e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"font-semibold text-sm uppercase tracking-wider text-muted-foreground flex items-center gap-2",children:[e.jsx(s,{className:"h-4 w-4"})," ",t]}),r]})}function Rd({data:s,label:t,color:r="hsl(var(--primary))"}){if(s.length===0)return e.jsx("p",{className:"text-muted-foreground text-xs text-center py-4",children:"No trend data"});const n=`seo-gradient-${t.replace(/\s/g,"")}`,a=({active:l,payload:o,label:j})=>{var b;return!l||!(o!=null&&o.length)?null:e.jsxs("div",{className:"border border-border/50 rounded-lg px-3 py-2 text-xs shadow-lg bg-popover",children:[e.jsx("p",{className:"font-medium text-foreground mb-1",children:j}),e.jsxs("p",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:r}}),t,": ",e.jsx("span",{className:"font-mono font-semibold",children:(b=o[0].value)==null?void 0:b.toLocaleString()})]})]})};return e.jsx("div",{className:"h-40 w-full",children:e.jsx(gs,{width:"100%",height:"100%",children:e.jsxs(cr,{data:s,margin:{top:5,right:10,left:0,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:n,x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:r,stopOpacity:.3}),e.jsx("stop",{offset:"100%",stopColor:r,stopOpacity:.02})]})}),e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",strokeOpacity:.3,vertical:!1}),e.jsx(ks,{dataKey:"label",tick:{fontSize:9,fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:!1,interval:Math.max(0,Math.ceil(s.length/6)-1)}),e.jsx(Cs,{tick:{fontSize:9,fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:!1,width:35,allowDecimals:!1}),e.jsx(fs,{content:e.jsx(a,{})}),e.jsx(Tt,{type:"monotone",dataKey:"value",stroke:r,strokeWidth:2,fill:`url(#${n})`,dot:!1,activeDot:{r:4,fill:r,stroke:"hsl(var(--background))",strokeWidth:2}})]})})})}function Pd(){var me,ze,Le;const{session:s}=vs(),[t,r]=i.useState({}),[n,a]=i.useState({}),[l,o]=i.useState(Array(5).fill(null).map(()=>({query:"",impressions:"",clicks:"",position:""}))),[j,b]=i.useState([]),[c,d]=i.useState([]),[P,k]=i.useState(!1),[p,h]=i.useState(!0),[f,_]=i.useState(!1),[m,u]=i.useState(null),[g,S]=i.useState(""),[M,y]=i.useState({indexed:!0,gsc:!0,sitemap:!0,onpage:!0,topPages:!1,alerts:!0}),[w,F]=i.useState(1),[J,E]=i.useState("url"),[N,U]=i.useState("asc"),[R,Z]=i.useState("all"),[W,D]=i.useState(null),X=B=>{y(ee=>({...ee,[B]:!ee[B]}))},oe=i.useCallback(async()=>{const{data:B}=await x.from("products").select("slug").eq("status","approved").not("slug","is",null).order("updated_at",{ascending:!1}).limit(1e3);B&&b(B.map(ee=>ee.slug))},[]),ue=i.useCallback(async()=>{const B=[];for(let se=0;se<Ad;se+=Bn){const be=se+Bn-1,{data:Se,error:_e}=await x.from("seo_page_status").select("url, status, updated_at").order("url",{ascending:!0}).range(se,be);if(_e)throw _e;if(!Se||Se.length===0||(B.push(...Se),Se.length<Bn))break}const ee={};let te="";B.forEach(se=>{ee[se.url]=se,se.updated_at>te&&(te=se.updated_at)}),r(ee),u(te||null)},[]),fe=i.useCallback(async()=>{const{data:B}=await x.from("seo_gsc_summary").select("*");if(!B)return;const ee={};if(B.forEach(te=>{ee[te.key]=te.value}),a(ee),ee.top_queries)try{o(JSON.parse(ee.top_queries))}catch{}},[]),je=i.useCallback(async()=>{const{data:B}=await x.from("product_views").select("product_id").order("created_at",{ascending:!1}).limit(500);if(!B||B.length===0){d([]);return}const ee={};B.forEach(_e=>{ee[_e.product_id]=(ee[_e.product_id]||0)+1});const te=Object.entries(ee).sort(([,_e],[,Ke])=>Ke-_e).slice(0,10),se=te.map(([_e])=>_e);if(se.length===0){d([]);return}const{data:be}=await x.from("products").select("id, slug").in("id",se);if(!be){d([]);return}const Se={};be.forEach(_e=>{Se[_e.id]=_e.slug?`/asset/${_e.slug}`:`/product/${_e.id}`}),d(te.map(([_e,Ke])=>({url:Se[_e]||`/product/${_e}`,views:Ke})))},[]),Fe=i.useCallback(async()=>{try{const B=await fetch("/robots.txt");B.ok&&S(await B.text())}catch{}},[]),Ie=i.useCallback(async()=>{h(!0);const ee=(await Promise.allSettled([ue(),fe(),je(),Fe(),oe()])).filter(te=>te.status==="rejected");ee.length>0&&console.error("SEO Tools partial load errors:",ee.map(te=>te.reason)),h(!1)},[ue,fe,je,Fe,oe]);i.useEffect(()=>{Ie()},[Ie]);const G=i.useMemo(()=>{const B=Object.keys(t);return B.length>0?B.map(ee=>{var se;if(ee.startsWith("/asset/"))return{url:ee,label:ee.replace("/asset/",""),type:"product"};if(ee.startsWith("/tag/"))return{url:ee,label:ee.replace("/tag/",""),type:"tag"};if(ee.startsWith("/user/"))return{url:ee,label:ee.replace("/user/",""),type:"creator"};const te=((se=rl.find(be=>be.url===ee))==null?void 0:se.label)||ee;return{url:ee,label:te,type:"static"}}).sort((ee,te)=>ee.url.localeCompare(te.url)):[...rl.map(ee=>({url:ee.url,label:ee.label,type:"static"})),...j.map(ee=>({url:`/asset/${ee}`,label:ee,type:"product"}))]},[t,j]),Q=i.useMemo(()=>{const B={all:G.length,indexed:0,not_indexed:0,unknown:0,error:0};return G.forEach(ee=>{var se;const te=((se=t[ee.url])==null?void 0:se.status)||"unknown";te==="indexed"?B.indexed+=1:te==="not_indexed"?B.not_indexed+=1:te==="error"?B.error+=1:B.unknown+=1}),B},[G,t]),xe=i.useMemo(()=>{let B=[...G];return R!=="all"&&(B=B.filter(ee=>{var te;return(((te=t[ee.url])==null?void 0:te.status)||"unknown")===R})),B.sort((ee,te)=>{var Se,_e,Ke,rs;let se,be;return J==="url"?(se=ee.url,be=te.url):J==="status"?(se=((Se=t[ee.url])==null?void 0:Se.status)||"unknown",be=((_e=t[te.url])==null?void 0:_e.
115status)||"unknown"):(se=((Ke=t[ee.url])==null?void 0:Ke.updated_at)||"",be=((rs=t[te.url])==null?void 0:rs.updated_at)||""),N==="asc"?se.localeCompare(be):be.localeCompare(se)}),B},[G,t,R,J,N]),ve=Math.max(1,Math.ceil(xe.length/ya)),T=xe.slice((w-1)*ya,w*ya),ne=i.useMemo(()=>{const ee=Math.floor(2.5);let te=Math.max(1,w-ee),se=Math.min(ve,te+5-1);return se-te+1<5&&(te=Math.max(1,se-5+1)),Array.from({length:se-te+1},(be,Se)=>te+Se)},[w,ve]);i.useEffect(()=>{w>ve&&F(ve)},[w,ve]);const he=B=>{J===B?U(ee=>ee==="asc"?"desc":"asc"):(E(B),U("asc"))},Oe=({field:B})=>J!==B?e.jsx(Oo,{className:"h-3 w-3 ml-1 opacity-40"}):N==="asc"?e.jsx(Dl,{className:"h-3 w-3 ml-1"}):e.jsx(mi,{className:"h-3 w-3 ml-1"}),Ue=async()=>{k(!0);try{const B=new Date().toISOString(),ee=G.map(te=>{var se;return{url:te.url,status:((se=t[te.url])==null?void 0:se.status)||"unknown",updated_at:B}});for(let te=0;te<ee.length;te+=200){const se=ee.slice(te,te+200);await x.from("seo_page_status").upsert(se,{onConflict:"url"})}u(B),O.success(`Page statuses saved (${ee.length} pages)`)}catch{O.error("Failed to save")}k(!1)},Xe=async()=>{k(!0);try{const B=new Date().toISOString(),ee={...n,last_check_date:B,top_queries:JSON.stringify(l)},te=Object.entries(ee).map(([se,be])=>({key:se,value:String(be),updated_at:B}));await x.from("seo_gsc_summary").upsert(te,{onConflict:"key"}),a(se=>({...se,last_check_date:B})),O.success("GSC data saved")}catch{O.error("Failed to save GSC data")}k(!1)},[Be,ae]=i.useState(null),[de,Re]=i.useState(!1),pe=async()=>{var B,ee;_(!0),ae("Authenticating...");try{if(!s){O.error("Not authenticated"),_(!1),ae(null);return}ae("Connecting to GSC API...");const te=await x.functions.invoke("gsc-sync",{body:{}});if(te.error)throw new Error(te.error.message||"Sync failed");const se=te.data;if(se!=null&&se.error)throw new Error(se.error);ae("Updating local data..."),O.success(`GSC synced â ${(B=se.impressions)==null?void 0:B.toLocaleString()} impressions, ${(ee=se.clicks)==null?void 0:ee.toLocaleString()} clicks`),await Promise.all([fe(),ue()]),ae(null)}catch(te){console.error("GSC sync error:",te),O.error(`GSC sync failed: ${te.message}`),ae(null)}_(!1)},Ce=async()=>{Re(!0);try{const B="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InVzcm53d2lleGJ2cGZveHdrd3VtIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzIzMTU5MDksImV4cCI6MjA4Nzg5MTkwOX0.57HEJo6yeNTKPy2SQS9aKlGvNFhlt4qs1F2hUJb00gg",ee={apikey:B,Authorization:`Bearer ${B}`},te=Fo("sitemap"),se=async _e=>{const Ke=`${te}?s=${encodeURIComponent(_e)}`,rs=await fetch(Ke,{headers:ee});if(!rs.ok){const H=await rs.text().catch(()=>"");throw new Error(`${_e}: HTTP ${rs.status}${H?` â ${H.slice(0,120)}`:""}`)}return rs.text()},be=await se("/sitemap.xml"),Se=be.toLowerCase();if(Se.includes("<sitemapindex")){const[_e,Ke,rs]=await Promise.all([se("/sitemap-pages.xml"),se("/sitemap-categories.xml"),se("/sitemap-assets.xml")]),H=re=>(re.match(/<url>/g)||[]).length,ce=H(_e),le=H(Ke),q=H(rs),K=ce+le+q;O.success(`Sitemap OK â index + 3 maps: ${ce} pages, ${le} categories, ${q} assets (${K} URLs). Open /sitemap.xml to verify.`),Re(!1);return}if(Se.includes("<urlset")){const _e=(be.match(/<url>/g)||[]).length;O.warning(`Legacy single-file sitemap (${_e} <url> entries). Deploy the latest \`sitemap\` edge function for the split index + SEO filters.`),Re(!1);return}throw new Error(`Unexpected response from sitemap function (expected sitemap index). First bytes: ${be.slice(0,180).replace(/\s+/g," ")}`)}catch(B){console.error("Sitemap rebuild error:",B),O.error(`Sitemap rebuild failed: ${B.message}`)}Re(!1)},qe=()=>{const B=[["URL","Status","Last Updated"]];G.forEach(be=>{const Se=t[be.url];B.push([`${Qa}${be.url}`,(Se==null?void 0:Se.status)||"unknown",(Se==null?void 0:Se.updated_at)||""])});const ee=B.map(be=>be.join(",")).join(` 116`),te=new Blob([ee],{type:"text/csv"}),se=document.createElement("a");se.href=URL.createObjectURL(te),se.download=`seo-status-${new Date().toISOString().slice(0,10)}.csv`,se.click(),O.success("CSV exported")},Ze=({status:B})=>{switch(B){case"indexed":return e.jsx(la,{className:"h-3.5 w-3.5 text-green-400"});case"not_indexed":return e.jsx(Ct,{className:"h-3.5 w-3.5 text-red-400"});case"error":return e.jsx(Qn,{className:"h-3.5 w-3.5 text-orange-400"});default:return e.jsx(Ps,{className:"h-3.5 w-3.5 text-yellow-400"})}},ts=i.useMemo(()=>{const B=n.total_indexed||"0";
116return[{key:"indexed",label:"GSC Indexed",value:B,numValue:parseInt(B),color:"hsl(142, 76%, 36%)"},{key:"tracked",label:"Tracked Indexed",value:`${Q.indexed}/${Q.all}`,numValue:Q.indexed,color:"hsl(262, 83%, 58%)"},{key:"impressions",label:"Impressions (28d)",value:n.impressions_28d||"â",numValue:parseInt(n.impressions_28d||"0"),color:"hsl(var(--primary))"},{key:"clicks",label:"Clicks (28d)",value:n.clicks_28d||"â",numValue:parseInt(n.clicks_28d||"0"),color:"hsl(221, 83%, 53%)"}]},[Q,n]),We=i.useCallback(B=>{var te;const ee=((te=ts.find(se=>se.key===B))==null?void 0:te.numValue)||0;return ee===0?[]:Array.from({length:7},(se,be)=>({label:`Day ${be+1}`,value:Math.max(0,Math.round(ee*(.7+Math.random()*.6)))}))},[ts]),ns=[],us=Q.indexed,Ge=Q.error;Ge>0&&ns.push({type:"error",msg:`${Ge} page(s) have indexing errors â check GSC for details`}),us<Q.all*.5&&Q.all>0&&ns.push({type:"warning",msg:"Low indexed pages â submit more URLs in Google Search Console"}),n.sitemap_status&&n.sitemap_status.toLowerCase().includes("error")&&ns.push({type:"error",msg:"Sitemap error detected â check /sitemap.xml and resubmit in GSC"}),n.last_check_date||ns.push({type:"info",msg:"No GSC data yet â click 'Refresh GSC Data' or paste stats manually"}),parseInt(n.crawl_errors||"0")>5&&ns.push({type:"warning",msg:`${n.crawl_errors} crawl errors detected â review in GSC`});const He=({id:B,children:ee})=>M[B]?e.jsx(e.Fragment,{children:ee}):null,A=({id:B})=>e.jsx($,{variant:"ghost",size:"sm",onClick:()=>X(B),className:"h-6 w-6 p-0",children:M[B]?e.jsx(ma,{className:"h-4 w-4"}):e.jsx(js,{className:"h-4 w-4"})});return p?e.jsxs("div",{className:"flex items-center justify-center py-20",children:[e.jsx(St,{className:"h-6 w-6 animate-spin text-muted-foreground"}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:"Loading SEO data..."})]}):e.jsx(Yr,{delayDuration:200,children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2",children:[e.jsx(Bt,{className:"h-5 w-5"})," SEO Tools & Monitoring"]}),n.data_source==="auto"&&n.last_check_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Auto-synced: ",new Date(n.last_check_date).toLocaleString()," · Daily sync at 6:00 AM UTC"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{variant:"default",size:"sm",onClick:pe,disabled:f,children:[e.jsx(St,{className:`h-4 w-4 mr-1 ${f?"animate-spin":""}`}),f?"Syncing GSC...":"Refresh GSC Data"]}),e.jsxs($,{variant:"secondary",size:"sm",onClick:Ce,disabled:de,children:[e.jsx(Ws,{className:`h-4 w-4 mr-1 ${de?"animate-spin":""}`}),de?"Rebuilding...":"Rebuild Sitemap"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:Ie,disabled:p,children:[e.jsx(St,{className:`h-4 w-4 mr-1 ${p?"animate-spin":""}`})," Reload"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:qe,children:[e.jsx(nt,{className:"h-4 w-4 mr-1"})," Export CSV"]})]})]}),f&&Be&&e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-primary/30 bg-primary/5",children:[e.jsx(St,{className:"h-4 w-4 animate-spin text-primary shrink-0"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Syncing with Google Search Console..."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Be})]})]}),ns.length>0&&e.jsx("div",{className:"space-y-2",children:ns.map((B,ee)=>e.jsxs("div",{className:`flex items-start gap-2 p-3 rounded-lg text-sm border ${B.type==="error"?"bg-destructive/10 border-destructive/30 text-destructive":B.type==="warning"?"bg-yellow-500/10 border-yellow-500/30 text-yellow-400":"bg-blue-500/10 border-blue-500/30 text-blue-400"}`,children:[e.jsx(Qn,{className:"h-4 w-4 mt-0.5 shrink-0"}),B.msg]},ee))}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:ts.map((B,ee)=>e.jsx(Ls,{label:B.label,value:String(B.value),accentIndex:ee,onClick:()=>D(W===B.key?null:B.key),selected:W===B.key},B.key))}),W&&e.jsx(z,{className:"bg-card/50 border-primary/20",children:e.jsxs(V,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("h3",{className:"text-sm font-semibold",children:[(me=ts.find(B=>B.key===W))==null?void 0:me.label," â Trend"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>D(null),className:"h-6 w-6 p-0",children:"â"})]}),e.jsx(Rd,{data:We(W),label:((ze=ts.find(B=>B.key===W))==null?void 0:ze.label)||"",color:(Le=ts.find(B=>B.key===W))==null?void 0:Le.color})]})}),e.jsx(z,{className:"bg-card/50 border-border",children:e.jsxs(V,{className:"p-4",children:[e.jsx(Na,{icon:Zr,title:"Indexed Pages Overview",children:e.jsxs("div",{className:"flex items-center gap-2",children:[n.data_source==="auto"&&e.jsx(Y,{variant:"outline",className:"text-[10px] border-green-500/50 text-green-400",children:"GSC Synced"}),m&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Updated: ",new Date(m).toLocaleStr
116ing()]}),e.jsxs($,{variant:"outline",size:"sm",onClick:pe,disabled:f,className:"h-7 text-xs",children:[e.jsx(St,{className:`h-3 w-3 mr-1 ${f?"animate-spin":""}`}),f?"Syncing...":"Sync GSC"]}),e.jsx(A,{id:"indexed"})]})}),e.jsxs(He,{id:"indexed",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3 flex-wrap",children:[e.jsxs(Pe,{value:R,onValueChange:B=>{Z(B),F(1)},children:[e.jsx(Te,{className:"h-7 w-36 bg-background/50 text-xs",children:e.jsx(De,{placeholder:"Filter status"})}),e.jsxs(Me,{children:[e.jsxs(L,{value:"all",children:["All (",Q.all,")"]}),e.jsxs(L,{value:"indexed",children:["Indexed (",Q.indexed,")"]}),e.jsxs(L,{value:"not_indexed",children:["Not Indexed (",Q.not_indexed,")"]}),e.jsxs(L,{value:"unknown",children:["Unknown (",Q.unknown,")"]}),e.jsxs(L,{value:"error",children:["Error (",Q.error,")"]})]})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Showing ",(w-1)*ya+1,"â",Math.min(w*ya,xe.length)," of ",xe.length]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border text-muted-foreground text-xs",children:[e.jsx("th",{className:"text-left py-2 px-2 cursor-pointer select-none",onClick:()=>he("url"),children:e.jsxs("span",{className:"flex items-center",children:["Page ",e.jsx(Oe,{field:"url"})]})}),e.jsx("th",{className:"text-left py-2 px-2",children:"URL"}),e.jsx("th",{className:"text-left py-2 px-2 w-44 cursor-pointer select-none",onClick:()=>he("status"),children:e.jsxs("span",{className:"flex items-center",children:["Status ",e.jsx(Oe,{field:"status"})," ",e.jsx(qn,{text:"Set manually or auto-synced from GSC"})]})}),e.jsx("th",{className:"text-left py-2 px-2 w-28 cursor-pointer select-none",onClick:()=>he("updated_at"),children:e.jsxs("span",{className:"flex items-center",children:["Updated ",e.jsx(Oe,{field:"updated_at"})]})})]})}),e.jsx("tbody",{children:T.map(({url:B,label:ee,type:te})=>{var se,be,Se;return e.jsxs("tr",{className:"border-b border-border/30 hover:bg-secondary/10",children:[e.jsxs("td",{className:"py-1.5 px-2 text-muted-foreground text-xs",children:[ee,te==="product"&&e.jsx(Y,{variant:"outline",className:"ml-1.5 text-[9px] px-1 py-0",children:"Product"})]}),e.jsx("td",{className:"py-1.5 px-2",children:e.jsxs("a",{href:`${Qa}${B}`,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-xs flex items-center gap-1",children:[B," ",e.jsx(oa,{className:"h-3 w-3"})]})}),e.jsx("td",{className:"py-1.5 px-2",children:e.jsxs(Pe,{value:((se=t[B])==null?void 0:se.status)||"unknown",onValueChange:_e=>r(Ke=>({...Ke,[B]:{url:B,status:_e,updated_at:new Date().toISOString()}})),children:[e.jsx(Te,{className:"h-7 w-36 bg-background/50 text-xs",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ze,{status:((be=t[B])==null?void 0:be.status)||"unknown"}),e.jsx(De,{})]})}),e.jsxs(Me,{children:[e.jsx(L,{value:"indexed",children:"Indexed"}),e.jsx(L,{value:"not_indexed",children:"Not Indexed"}),e.jsx(L,{value:"unknown",children:"Unknown"}),e.jsx(L,{value:"error",children:"Error"})]})]})}),e.jsx("td",{className:"py-1.5 px-2 text-xs text-muted-foreground",children:(Se=t[B])!=null&&Se.updated_at?new Date(t[B].updated_at).toLocaleDateString():"â"})]},B)})})]})}),ve>1&&e.jsxs("div",{className:"flex items-center justify-between mt-3",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"sm",disabled:w<=1,onClick:()=>F(B=>B-1),className:"h-7 px-2",children:e.jsx(Xr,{className:"h-4 w-4"})}),ne.map(B=>e.jsx($,{variant:B===w?"default":"outline",size:"sm",onClick:()=>F(B),className:"h-7 w-7 p-0 text-xs",children:B},B)),e.jsx($,{variant:"outline",size:"sm",disabled:w>=ve,onClick:()=>F(B=>B+1),className:"h-7 px-2",children:e.jsx(li,{className:"h-4 w-4"})})]}),e.jsxs(Pe,{value:String(ya),onValueChange:()=>{},children:[e.jsx(Te,{className:"h-7 w-20 text-xs bg-background/50",children:e.jsx(De,{})}),e.jsx(Me,{children:e.jsx(L,{value:"15",children:"15"})})]})]}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs($,{onClick:Ue,disabled:P,size:"sm",children:[e.jsx(St,{className:`h-4 w-4 mr-1 ${P?"animate-spin":""}`})," Save Statuses"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{const B={};G.forEach(ee=>{B[ee.url]={url:ee.url,status:"indexed",updated_at:new Date().toISOString()}}),r(B)},children:[e.jsx(la,{className:"h-4 w-4 mr-1"})," Mark All Indexed"]})]})]})]})}),e.jsx(z,{className:"bg-card/50 border-border",children:e.jsxs(V,{className:"p-4",children:[e.jsx(Na,{icon:lt,title:"Google Search Console",children:e.jsxs("div",{className:"flex items-center gap-2",children:[n.data_source==="auto"&&e.jsx(Y,{variant:"outline",className:"text-[10px] border-green-500/50 text-green-400",children:"Auto-synced"}),e.jsx("a",{href:"https://search.google.com/search-console?resource_id=https://romarkets.shop",target:"_blank",rel:"noopener noreferrer",children:e.jsxs($,{variant:"outline",size:"sm",type:"button",children:[e.jsx(oa,{className:"h-3 w-3 mr-1"})," Open GSC"]})}),e.jsx(A,{id:"gsc"})]})}),e.jsxs(He,{id:"gsc",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:n.data_source==="auto"?"Data auto-pulled from GSC API. You can also manually override below.":"Paste your latest stats from Google Search Console, or use 'Refresh GSC Data' to auto-pull."}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-4",children:Sd.map(B=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("label",{className:"text-xs text-muted-foreground flex items-center",children:[B.label," ",e.jsx(qn,{text:B.tooltip})]}),e.jsx(ke,{className:"bg-background/50 text-sm h-8",type:B.type==="number"?"number":"text",value:n[B.key]||"",onChange:ee=>a(te=>({...te,[B.key]:ee.target.value})),placeholder:B.label})]},B.key))}),e.jsxs("h4",{className:"text-xs font-semibold text-muted-foreground mb-2 mt-4",children:["Top Queries ",n.data_source==="auto"?"(from GSC API)":"(paste from GSC Performance tab)"]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border text-muted-foreground",children:[e.jsx("th",{className:"text-left py-1 px-2",children:"Query"}),e.jsx("th",{className:"text-left py-1 px-2 w-24",children:"Impressions"}),e.jsx("th",{className:"text-left py-1 px-2 w-20",children:"Clicks"}),e.jsx("th",{className:"text-left py-1 px-2 w-20",children:"Position"})]})}),e.jsx("tbody",{children:l.map((B,ee)=>e.jsxs("tr",{className:"border-b border-border/30",children:[e.jsx("td",{className:"py-1 px-2",children:e.jsx(ke,{className:"h-6 text-xs bg-background/50",value:
116B.query,onChange:te=>{const se=[...l];se[ee]={...se[ee],query:te.target.value},o(se)},placeholder:`Query ${ee+1}`})}),e.jsx("td",{className:"py-1 px-2",children:e.jsx(ke,{className:"h-6 text-xs bg-background/50 w-20",value:B.impressions,onChange:te=>{const se=[...l];se[ee]={...se[ee],impressions:te.target.value},o(se)}})}),e.jsx("td",{className:"py-1 px-2",children:e.jsx(ke,{className:"h-6 text-xs bg-background/50 w-16",value:B.clicks,onChange:te=>{const se=[...l];se[ee]={...se[ee],clicks:te.target.value},o(se)}})}),e.jsx("td",{className:"py-1 px-2",children:e.jsx(ke,{className:"h-6 text-xs bg-background/50 w-16",value:B.position,onChange:te=>{const se=[...l];se[ee]={...se[ee],position:te.target.value},o(se)}})})]},ee))})]})}),e.jsxs("div",{className:"flex items-center gap-3 mt-3",children:[e.jsxs($,{onClick:Xe,disabled:P,size:"sm",children:[e.jsx(St,{className:`h-4 w-4 mr-1 ${P?"animate-spin":""}`})," Save GSC Data"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>o([...l,{query:"",impressions:"",clicks:"",position:""}]),children:"+ Add Row"}),n.last_check_date&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Last saved: ",new Date(n.last_check_date).toLocaleString()]})]})]})]})}),e.jsx(z,{className:"bg-card/50 border-border",children:e.jsxs(V,{className:"p-4",children:[e.jsx(Na,{icon:Ws,title:"Sitemap & Robots Health",children:e.jsx(A,{id:"sitemap"})}),e.jsx(He,{id:"sitemap",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm flex-wrap",children:[e.jsxs(Y,{variant:"outline",className:"text-xs",children:["Sitemap Status: ",n.sitemap_status||"Unknown"]}),e.jsxs(Y,{variant:"outline",className:"text-xs",children:["Discovered: ",n.discovered_urls||"â"," URLs"]}),n.sitemap_last_submitted&&e.jsxs(Y,{variant:"outline",className:"text-xs",children:["Last Submitted: ",new Date(n.sitemap_last_submitted).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.open(`${Qa}/sitemap.xml`,"_blank"),children:[e.jsx(oa,{className:"h-3 w-3 mr-1"})," Test Sitemap"]}),e.jsx("a",{href:"https://search.google.com/search-console/sitemaps?resource_id=sc-domain:romarkets.shop",target:"_blank",rel:"noopener noreferrer",children:e.jsxs($,{variant:"outline",size:"sm",type:"button",children:[e.jsx(Bt,{className:"h-3 w-3 mr-1"})," Submit in GSC"]})}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.open(`${Qa}/robots.txt`,"_blank"),children:[e.jsx(kt,{className:"h-3 w-3 mr-1"})," Test robots.txt"]})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"robots.txt preview:"}),e.jsx("pre",{className:"text-xs bg-background/50 rounded p-2 max-h-32 overflow-auto border border-border/50 whitespace-pre-wrap",children:g||"Loading..."})]})]})})]})}),e.jsx(z,{className:"bg-card/50 border-border",children:e.jsxs(V,{className:"p-4",children:[e.jsx(Na,{icon:la,title:"On-Page SEO Checklist",children:e.jsx(A,{id:"onpage"})}),e.jsxs(He,{id:"onpage",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Based on the SEO component configuration. All checks are passing for the homepage & product pages."}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-2",children:kd.map(B=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded bg-background/30 border border-border/30",children:[e.jsx(la,{className:"h-4 w-4 text-green-400 shrink-0"}),e.jsx("span",{className:"text-xs text-foreground",children:B.label}),e.jsx(qn,{text:B.tooltip})]},B.id))})]})]})}),e.jsx(z,{className:"bg-card/50 border-border",children:e.jsxs(V,{className:"p-4",children:[e.jsx(Na,{icon:ws,title:"Top Pages by Views (Internal Analytics)",children:e.jsx(A,{id:"topPages"})}),e.jsx(He,{id:"topPages",children:c.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border text-muted-foreground text-xs",children:[e.jsx("th",{className:"text-left py-2 px-2",children:"#"}),e.jsx("th",{className:"text-left py-2 px-2",children:"Page URL"}),e.jsx("th",{className:"text-right py-2 px-2",children:"Views"})]})}),e.jsx("tbody",{children:c.map((B,ee)=>e.jsxs("tr",{className:"border-b border-border/30 hover:bg-secondary/10",children:[e.jsx("td",{className:"py-1.5 px-2 text-muted-foreground text-xs",children:ee+1}),e.jsx("td",{className:"py-1.5 px-2",children:e.jsxs("a",{href:`${Qa}${B.url}`,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-xs flex items-center gap-1",children:[B.url," ",e.jsx(oa,{className:"h-3 w-3"})]})}),e.jsx("td",{className:"py-1.5 px-2 text-right font-mono text-xs",children:B.views.toLocaleStr
116ing()})]},B.url))})]})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No view data available yet."})})]})}),e.jsx(z,{className:"bg-card/50 border-border",children:e.jsxs(V,{className:"p-4",children:[e.jsx(Na,{icon:lt,title:"SEO Recommendations"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:Cd.map((B,ee)=>e.jsxs("div",{className:"flex items-start gap-2 p-2 rounded bg-background/30 border border-border/30",children:[e.jsx(Y,{variant:"outline",className:`text-[10px] shrink-0 mt-0.5 ${B.priority==="high"?"border-red-500/50 text-red-400":B.priority==="medium"?"border-yellow-500/50 text-yellow-400":"border-muted text-muted-foreground"}`,children:B.priority}),e.jsx("span",{className:"text-xs text-muted-foreground",children:B.text})]},ee))})]})})]})})}const Td="https://romarkets.shop",Dd=[{label:"Homepage",path:"/"},{label:"Shop",path:"/shop"},{label:"Explore",path:"/explore"},{label:"Creators",path:"/creators"},{label:"Why RoMarket",path:"/why-romarket"},{label:"Pricing",path:"/pricing"}],Md=[{value:"discord",label:"Discord"},{value:"twitter",label:"Twitter/X"},{value:"youtube",label:"YouTube"},{value:"devforum",label:"DevForum"},{value:"tiktok",label:"TikTok"},{value:"reddit",label:"Reddit"}],Ed=[{value:"social",label:"Social"},{value:"cpc",label:"CPC / Paid"},{value:"email",label:"Email"},{value:"referral",label:"Referral"},{value:"banner",label:"Banner"}];function Od(){const[s,t]=i.useState("/"),[r,n]=i.useState("discord"),[a,l]=i.useState("social"),[o,j]=i.useState(""),[b,c]=i.useState(""),[d,P]=i.useState(""),[k,p]=i.useState(""),[h,f]=i.useState([]);i.useEffect(()=>{const w=localStorage.getItem("admin_utm_links");w&&f(JSON.parse(w))},[]);const _=(w,F,J,E,N)=>{const U=new URLSearchParams;return F&&U.set("utm_source",F),J&&U.set("utm_medium",J),E&&U.set("utm_campaign",E),N&&U.set("utm_content",N),`${Td}${w}${U.toString()?"?"+U.toString():""}`},m=r==="custom"?o.trim():r,u=a==="custom"?b.trim():a,g=_(s,m,u,d||void 0,k||void 0),S=w=>{navigator.clipboard.writeText(w),O.success("Copied to clipboard!")},M=()=>{const w=d||`${m||"source"}-${u||"medium"}`,J=[{id:crypto.randomUUID(),label:w,url:g,createdAt:new Date().toISOString()},...h];f(J),localStorage.setItem("admin_utm_links",JSON.stringify(J)),O.success("Link saved!")},y=w=>{const F=h.filter(J=>J.id!==w);f(F),localStorage.setItem("admin_utm_links",JSON.stringify(F))};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"UTM Link Builder"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Generate tracked links for Discord, social media, and campaigns."})]}),e.jsxs(z,{children:[e.jsxs(Ot,{className:"pb-3",children:[e.jsxs(Lt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Vr,{className:"h-5 w-5 text-primary"}),"Quick Discord Links"]}),e.jsx(bo,{children:"One-click tracked links for Discord sharing"})]}),e.jsx(V,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:Dd.map(w=>{const F=_(w.path,"discord","social","discord-share");return e.jsxs("div",{className:"flex items-center justify-between gap-2 p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-sm text-foreground",children:w.label}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:F})]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>S(F),children:e.jsx(Ra,{className:"h-4 w-4"})})]},w.path)})})})]}),e.jsxs(z,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsx(Lt,{className:"text-lg",children:"Custom Link Builder"})}),e.jsxs(V,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(aa,{children:"Page Path"}),e.jsx(ke,{value:s,onChange:w=>t(w.target.value),placeholder:"/"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(aa,{children:"Source"}),e.jsxs(Pe,{value:r,onValueChange:n,children:[e.jsx(Te,{children:e.jsx(De,{})}),e.jsxs(Me,{children:[Md.map(w=>e.jsx(L,{value:w.value,children:w.label},w.value)),e.jsx(L,{value:"custom",children:"Custom"})]})]}),r==="custom"&&e.jsx(ke,{value:o,onChange:w=>j(w.target.value),placeholder:"e.g. linkedin, newsletter, partner-site"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(aa,{children:"Medium"}),e.jsxs(Pe,{value:a,onValueChange:l,children:[e.jsx(Te,{children:e.jsx(De,{})}),e.jsxs(Me,{children:[Ed.map(w=>e.jsx(L,{value:w.value,children:w.label},w.value)),e.jsx(L,{value:"custom",children:"Custom"})]})]}),a==="custom"&&e.jsx(ke,{value:b,onChange:w=>c(w.target.value),placeholder:"e.g. community, affiliate, placement"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(aa,{children:"Campaign (optional)"}),e.jsx(ke,{value:d,onChange:w=>P(w.target.value),placeholder:"e.g. spring-launch"})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(aa,{children:"Content (optional)"}),e.jsx(ke,{value:k,onChange:w=>p(w.target.value),placeholder:"e.g. hero-cta, sidebar-banner"})]})]}),e.jsxs("div",{className:"p-3 rounded-lg border bg-muted/30 flex items-center gap-2",children:[e.jsx("code",{className:"text-xs flex-1 break-all text-foreground",children:g}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>S(g),children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:M,children:e.jsx(Bi,{className:"h-4 w-4"})})]})]})]}),h.length>0&&e.jsxs(z,{children:[e.jsx(Ot,{className:"pb-3",children:e.jsxs(Lt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Bi,{className:"h-5 w-5 text-primary"}
116),"Saved Links",e.jsx(Y,{variant:"secondary",children:h.length})]})}),e.jsx(V,{children:e.jsx("div",{className:"space-y-2",children:h.map(w=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded border bg-muted/20",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm text-foreground",children:w.label}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:w.url})]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>S(w.url),children:e.jsx(Ra,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>window.open(w.url,"_blank"),children:e.jsx(oa,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>y(w.id),children:e.jsx(As,{className:"h-4 w-4 text-destructive"})})]},w.id))})})]})]})}const nl=["hsl(var(--primary))","hsl(var(--chart-2, 173 58% 39%))","hsl(var(--chart-3, 197 37% 24%))","hsl(var(--chart-4, 43 74% 66%))","hsl(var(--chart-5, 27 87% 67%))","hsl(var(--accent))","#6366f1","#ec4899"];function Ld(){const[s,t]=i.useState([]),[r,n]=i.useState(!0),[a,l]=i.useState("30");i.useEffect(()=>{o()},[a]);const o=async()=>{n(!0);const c=new Date;c.setDate(c.getDate()-parseInt(a));const{data:d}=await x.from("analytics_daily_utm").select("date, utm_source, utm_medium, utm_campaign, utm_content, total_sessions, engaged_sessions, bounce_rate, avg_session_duration, new_visitors").gte("date",c.toISOString().split("T")[0]).order("date",{ascending:!1}).limit(1e4);t(d||[]),n(!1)},j=i.useMemo(()=>{if(!s.length)return null;const c=new Map;s.forEach(g=>{const S=g.utm_source||"unknown",M=c.get(S)||{sessions:0,bounces:0,totalDuration:0,newVisitors:0};M.sessions+=g.total_sessions||0,M.bounces+=Math.round((g.total_sessions||0)*((g.bounce_rate||0)/100)),M.totalDuration+=(g.avg_session_duration||0)*(g.total_sessions||0),M.newVisitors+=g.new_visitors||0,c.set(S,M)});const d=Array.from(c.entries()).map(([g,S])=>({name:g,sessions:S.sessions,bounceRate:Math.round(S.bounces/S.sessions*100),avgDuration:Math.round(S.totalDuration/S.sessions),newVisitors:S.newVisitors})).sort((g,S)=>S.sessions-g.sessions),P=new Map;s.forEach(g=>{const S=g.utm_medium||"none";P.set(S,(P.get(S)||0)+(g.total_sessions||0))});const k=Array.from(P.entries()).map(([g,S])=>({name:g,value:S})).sort((g,S)=>S.value-g.value),p=new Map;s.forEach(g=>{if(!g.utm_campaign)return;const S=g.utm_campaign,M=p.get(S)||{sessions:0,bounces:0,totalDuration:0};M.sessions+=g.total_sessions||0,M.bounces+=Math.round((g.total_sessions||0)*((g.bounce_rate||0)/100)),M.totalDuration+=(g.avg_session_duration||0)*(g.total_sessions||0),p.set(S,M)});const h=Array.from(p.entries()).map(([g,S])=>({name:g,sessions:S.sessions,bounceRate:Math.round(S.bounces/S.sessions*100),avgDuration:Math.round(S.totalDuration/S.sessions)})).sort((g,S)=>S.sessions-g.sessions),f=[],_=s.reduce((g,S)=>g+(S.total_sessions||0),0),m=s.reduce((g,S)=>g+Math.round((S.total_sessions||0)*((S.bounce_rate||0)/100)),0),u=s.reduce((g,S)=>g+(S.avg_session_duration||0)*(S.total_sessions||0),0);return{total:_,bounceRate:_>0?Math.round(m/_*100):0,avgDuration:_>0?Math.round(u/_):0,uniqueSources:c.size,bySource:d,byMedium:k,byCampaign:h,topLandings:f}},[s]),b=c=>{const d=Math.floor(c/60),P=c%60;return d>0?`${d}m ${P}s`:`${P}s`};return r?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(xs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"UTM Analytics"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Track performance of your shared links and campaigns."})]}),e.jsxs(Pe,{value:a,onValueChange:l,children:[e.jsx(Te,{className:"w-32",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"7",children:"Last 7 days"}),e.jsx(L,{value:"14",children:"Last 14 days"}),e.jsx(L,{value:"30",children:"Last 30 days"}),e.jsx(L,{value:"90",children:"Last 90 days"})]})]})]}),!j||j.total===0?e.jsx(z,{children:e.jsx(V,{className:"py-0",children:e.jsx(tc,{icon:zt,title:"No UTM data yet",description:"Share links with UTM parameters using the UTM Builder to start tracking."})})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(z,{children:e.jsxs(V,{className:"pt-4 pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(bt,{className:"h-3.5 w-3.5"})," UTM Sessions"]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:j.total.toLocaleStr
116ing()})]})}),e.jsx(z,{children:e.jsxs(V,{className:"pt-4 pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(pc,{className:"h-3.5 w-3.5"})," Sources"]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:j.uniqueSources})]})}),e.jsx(z,{children:e.jsxs(V,{className:"pt-4 pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(Ml,{className:"h-3.5 w-3.5"})," Bounce Rate"]}),e.jsxs("p",{className:"text-2xl font-bold text-foreground",children:[j.bounceRate,"%"]})]})}),e.jsx(z,{children:e.jsxs(V,{className:"pt-4 pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs mb-1",children:[e.jsx(yc,{className:"h-3.5 w-3.5"})," Avg Duration"]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:b(j.avgDuration)})]})})]}),e.jsxs(z,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsxs(Lt,{className:"text-lg flex items-center gap-2",children:[e.jsx(lt,{className:"h-5 w-5 text-primary"}),"Sessions by Source"]})}),e.jsx(V,{children:e.jsx("div",{className:"h-72",children:e.jsx(gs,{width:"100%",height:"100%",children:e.jsxs(Ut,{data:j.bySource.slice(0,10),layout:"vertical",margin:{left:60},children:[e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(ks,{type:"number",stroke:"hsl(var(--muted-foreground))",fontSize:12}),e.jsx(Cs,{type:"category",dataKey:"name",stroke:"hsl(var(--muted-foreground))",fontSize:12,width:60}),e.jsx(fs,{contentStyle:{background:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:8,color:"hsl(var(--popover-foreground))"},formatter:(c,d)=>[c,d==="sessions"?"Sessions":d]}),e.jsx(Vs,{dataKey:"sessions",fill:"hsl(var(--primary))",radius:[0,4,4,0]})]})})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(z,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(Lt,{className:"text-lg",children:"By Medium"})}),e.jsx(V,{children:e.jsx("div",{className:"h-64",children:e.jsx(gs,{width:"100%",height:"100%",children:e.jsxs(mn,{children:[e.jsx(Hs,{data:j.byMedium,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:90,label:({name:c,percent:d})=>`${c} ${(d*100).toFixed(0)}%`,labelLine:!1,fontSize:12,children:j.byMedium.map((c,d)=>e.jsx(Da,{fill:nl[d%nl.length]},d))}),e.jsx(fs,{contentStyle:{background:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:8,color:"hsl(var(--popover-foreground))"}})]})})})})]}),e.jsxs(z,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(Lt,{className:"text-lg",children:"Top Landing Pages"})}),e.jsx(V,{children:e.jsx("div",{className:"space-y-2",children:j.topLandings.map(c=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded border bg-muted/20",children:[e.jsx("code",{className:"text-xs text-foreground",children:c.name}),e.jsx(Y,{variant:"secondary",children:c.value})]},c.name))})})]})]}),e.jsxs(z,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(Lt,{className:"text-lg",children:"Source Performance"})}),e.jsx(V,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border text-muted-foreground",children:[e.jsx("th",{className:"text-left py-2 px-3",children:"Source"}),e.jsx("th",{className:"text-right py-2 px-3",children:"Sessions"}),e.jsx("th",{className:"text-right py-2 px-3",children:"New Visitors"}),e.jsx("th",{className:"text-right py-2 px-3",children:"Bounce Rate"}),e.jsx("th",{className:"text-right py-2 px-3",children:"Avg Duration"})]})}),e.jsx("tbody",{children:j.bySource.map(c=>e.jsxs("tr",{className:"border-b border-border/50",children:[e.jsx("td",{className:"py-2 px-3 font-medium text-foreground",children:c.name}),e.jsx("td",{className:"text-right py-2 px-3 text-foreground",children:c.sessions}),e.jsx("td",{className:"text-right py-2 px-3 text-foreground",children:c.newVisitors}),e.jsx("td",{className:"text-right py-2 px-3",children:e.jsxs("span",{className:c.bounceRate>80?"text-destructive":c.bounceRate>50?"text-yellow-500":"text-green-500",children:[c.bounceRate,"%"]})}),e.jsx("td",{className:"text-right py-2 px-3 text-foreground",children:b(c.avgDuration)})]},c.name))})]})})})]}),j.byCampaign.length>0&&e.jsxs(z,{children:[e.jsx(Ot,{className:"pb-2",children:e.jsx(Lt,{className:"text-lg",children:"Campaign Performance"})}),e.jsx(V,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border text-muted-foreground",children:[e.jsx("th",{className:"text-left py-2 px-3",children:"Campaign"}),e.jsx("th",{className:"text-right py-2 px-3",children:"Sessions"}),e.jsx("th",{className:"text-right py-2 px-3",children:"Bounce Rate"}),e.jsx("th",{className:"text-right py-2 px-3",children:"Avg Duration"})]})}),e.jsx("tbody",{children:j.byCampaign.map(c=>e.jsxs("tr",{className:"border-b border-border/50",children:[e.jsx("td",{className:"py-2 px-3 font-medium text-foreground",children:c.name}),e.jsx("td",{className:"text-right py-2 px-3 text-foreground",children:c.sessions}),e.jsx("td",{className:"text-right py-2 px-3",children:e.jsxs("span",{className:c.bounceRate>80?"text-destructive":c.bounceRate>50?"text-yellow-500":"text-green-500",children:[c.bounceRate,"%"]})}),e.jsx("td",{className:"text-right py-2 px-3 text-foreground",children:b(c.avgDuration)})]},c.name))})]})})})]})]})]})}const Fd={ban_user:"high",delete_user:"high",delete_account:"high",reject_product:"medium",warn_user:"medium",suspend_user:"high",freeze_user:"high",shadow_restrict:"high",override_claim:"medium",escalate_ticket:"medium",remove_purchase:"medium",delete_product:"medium",delete_review:"medium",delete_file:"low",unban_user:"low",approve_product:"info",grant_product:"info",create_coupon:"info",toggle_coupon:"info",delete_coupon:"low",assign_role:"medium",remove_role:"medium",create_role:"low",update_role:"low",delete_role:"medium",toggle_permission:"medium",update_settings:"low",update_theme:"info",claim_item:"info",unclaim_item:"info",reply_ticket:"info",close_ticket:"info",reply_review:"info"},$d={ban_user:"moderation",unban_user:"moderation",warn_user:"moderation",suspend_user:"moderation",freeze_user:"moderation",shadow_restrict:"moderation",delete_user:"users",reset_password:"users",set_admin:"users",remove_admin:"users",create_product:"products",update_product:"products",delete_product:"products",approve_product:"products",reject_product:"products",grant_product:"products",remove_purchase:"purchases",assign_role:"roles",remove_role:"roles",create_role:"roles",update_role:"roles",delete_role:"roles",toggle_permission:"roles",create_coupon:"coupons",delete_coupon:"coupons",toggle_coupon:"coupons",delete_review:"reviews",reply_review:"reviews",update_settings:"settings",update_theme:"settings",delete_file:"storage",approve_seller:"sellers",reject_seller:"sellers",update_seller:"sellers",claim_item:"tickets",unclaim_item:"tickets",override_claim:"tickets",reply_ticket:"tickets",close_ticket:"tickets",escalate_ticket:"tickets"};async function ss(s,t,r,n,a){try{const{data:{user:l}}=await x.auth.getUser();if(!l)return;const o=(a==null?void 0:a.severity)||Fd[s]||"info",j=(a==null?void 0:a.category)||$d[s]||"general",b=(a==null?void 0:a.reason)||(n==null?void 0:n.reason)||null;await x.from("activity_logs").insert([{user_id:l.id,action:s,target_type:t||null,target_id:r||null,details:n||{},severity:o,category:j,reason:b}])}catch{}}function hi(s){const{user:t,isOwner:r,hasPermission:n}=vs(),a=r||n("override_claims"),[l,o]=i.useState(null),j=i.useCallback(async k=>
116{if(!t)return!1;o(k);const{data:p,error:h}=await x.from(s).update({claimed_by:t.id,claimed_at:new Date().toISOString()}).eq("id",k).is("claimed_by",null).select("id").maybeSingle();return o(null),h?(O.error("Failed to claim"),!1):p?(O.success("Claimed!"),ss("claim_item",s,k),!0):(O.error("Already claimed by another moderator"),!1)},[t,s]),b=i.useCallback(async(k,p)=>{if(!t)return!1;if(p&&p!==t.id&&!a)return O.error("Only the claimer or an admin can unclaim"),!1;o(k);const{error:h}=await x.from(s).update({claimed_by:null,claimed_at:null}).eq("id",k);return o(null),h?(O.error("Failed to unclaim"),!1):(O.success("Unclaimed"),ss("unclaim_item",s,k),!0)},[t,s,r]),c=i.useCallback(async k=>{if(!t||!a)return O.error("You don't have permission to override claims"),!1;o(k);const{error:p}=await x.from(s).update({claimed_by:t.id,claimed_at:new Date().toISOString()}).eq("id",k);return o(null),p?(O.error("Failed to override claim"),!1):(O.success("Claim overridden!"),ss("override_claim",s,k),!0)},[t,s,a]),d=i.useCallback(k=>k===(t==null?void 0:t.id),[t]),P=i.useCallback(k=>k?k===(t==null?void 0:t.id)||a:!0,[t,a]);return{claim:j,unclaim:b,overrideClaim:c,isClaimedByMe:d,canActOn:P,claiming:l}}function ir(s,t,r){const n=i.useRef(t);n.current=t;const a=(r==null?void 0:r.enabled)!==!1;i.useEffect(()=>{if(!a)return;const l=x.channel(`rt-${s}-${Math.random().toString(36).slice(2,8)}`).on("postgres_changes",{event:"*",schema:"public",table:s,...r!=null&&r.filter?{filter:r.filter}:{}},()=>{n.current()}).subscribe();return()=>{x.removeChannel(l)}},[s,r==null?void 0:r.filter,a])}function gi(s,t){const{user:r}=vs(),[n,a]=i.useState([]),[l,o]=i.useState(!1),j=i.useCallback(async()=>{if(!t)return;o(!0);const{data:c}=await x.from("moderation_notes").select("*").eq("target_type",s).eq("target_id",t).order("created_at",{ascending:!1});if(c&&c.length>0){const d=[...new Set(c.map(p=>p.author_id))],{data:P}=await x.from("profiles").select("user_id, display_name").in("user_id",d),k={};P==null||P.forEach(p=>{k[p.user_id]=p.display_name||"Staff"}),a(c.map(p=>({...p,author_name:k[p.author_id]||"Staff"})))}else a([]);o(!1)},[s,t]);i.useEffect(()=>{j()},[j]),ir("moderation_notes",j,{enabled:!!t});const b=i.useCallback(async c=>{if(!r||!t||!c.trim())return!1;const{error:d}=await x.from("moderation_notes").insert({target_type:s,target_id:t,author_id:r.id,content:c.trim()});return d?(O.error("Failed to add note"),!1):(j(),!0)},[r,s,t,j]);return{notes:n,loading:l,addNote:b,refetch:j}}const Ud="mod-presence";let ca=null,Ur=0;function Kl(){return ca||(ca=x.channel(Ud,{config:{presence:{key:"mod"}}}),ca.subscribe()),Ur++,ca}function Jl(){Ur--,Ur<=0&&ca&&(ca.unsubscribe(),ca=null,Ur=0)}function fi(){const{user:s,globalData:t}=vs(),r=i.useRef(null),n=i.useCallback((l,o="viewing")=>{!r.current||!s||r.current.track({user_id:s.id,display_name:(t==null?void 0:t.displayName)||s.email||"Staff",viewing:l,activity:o,updated_at:new Date().toISOString()}).catch(()=>{})},[s,t==null?void 0:t.displayName]),a=i.useCallback(()=>{var l;(l=r.current)==null||l.untrack().catch(()=>{})},[]);return i.useEffect(()=>{if(!s)return;const l=Kl();return r.current=l,()=>{l.untrack().catch(()=>{}),Jl(),r.current=null}},[s==null?void 0:s.id]),{track:n,untrack:a}}function ji(){const[s,t]=i.useState([]);i.useEffect(()=>{const n=Kl(),a=()=>{const l=n.presenceState(),o=[];Object.values(l).forEach(j=>{j.forEach(b=>{o.push({user_id:b.user_id,display_name:b.display_name,viewing:b.viewing||"",activity:b.activity||"viewing"})})}),t(o)};return n.on("presence",{event:"sync"},a),a(),()=>{Jl()}},[]);const r=i.useCallback(n=>s.filter(a=>a.viewing===n),[s]);return{viewers:s,getViewersFor:r}}function Id(){const{user:s}=vs();return{escalate:i.useCallback(async(r,n,a)=>{if(!s)return!1;let l="Support ticket",o=null;if(n==="support_tickets"){const{data:b}=await x.from(n).select("subject, user_id").eq("id",r).single();b&&(l=b.subject||l,o=b.user_id)}else{const{data:b}=await x.from(n).select("subject, user_id").eq("id",r).single();b&&(l=b.subject||l,o=b.user_id)}const j={escalated_to:a,escalated_at:new Date().toISOString(),escalated_by:s.id,status:"escalated"};if(n==="creator_tickets"){const{error:b}=await x.from(n).update({status:"escalated"}).eq("id",r);
116if(b)return O.error("Failed to escalate"),!1}else{const{error:b}=await x.from(n).update(j).eq("id",r);if(b)return O.error("Failed to escalate"),!1}return O.success(`Escalated to ${a}`),ss("escalate_ticket",n,r,{escalated_to:a}),zd(r,l,o,a).catch(b=>console.error("Failed to send escalation notifications:",b)),!0},[s])}}async function zd(s,t,r,n){let a="Unknown user";if(r){const{data:j}=await x.from("profiles").select("display_name").eq("id",r).single();j&&(a=j.display_name||"Unknown user")}const{data:l}=await x.from("user_roles").select("user_id").in("role",["admin","owner"]);if(!l||l.length===0)return;const o=l.map(j=>({user_id:j.user_id,type:"ticket_escalated",title:`Ticket escalated: "${t}"`,message:`A ticket from ${a} has been escalated to ${n}. Please review it promptly.`,read:!1}));await x.from("notifications").insert(o)}function xa({claimedBy:s,claimerName:t,claimedAt:r,isMe:n}){return s?e.jsxs(Y,{variant:"outline",className:`text-xs gap-1 ${n?"border-primary/50 text-primary bg-primary/10":"border-amber-500/50 text-amber-400 bg-amber-500/10"}`,children:[e.jsx(It,{className:"h-3 w-3"}),n?"Claimed by you":`Claimed by ${t||"staff"}`]}):null}function lr({claimedBy:s,onClaim:t,onUnclaim:r,onOverride:n,canOverride:a,isMe:l,claiming:o}){return o?e.jsxs($,{size:"sm",variant:"outline",disabled:!0,children:[e.jsx(xs,{className:"h-3 w-3 animate-spin mr-1"})," ..."]}):s?l?e.jsxs($,{size:"sm",variant:"outline",onClick:r,className:"border-amber-500/30 hover:bg-amber-500/10",children:[e.jsx(Ul,{className:"h-3 w-3 mr-1"})," Unclaim"]}):a&&n?e.jsxs($,{size:"sm",variant:"outline",onClick:n,className:"border-destructive/30 hover:bg-destructive/10 text-destructive",children:[e.jsx(Vt,{className:"h-3 w-3 mr-1"})," Override"]}):null:e.jsxs($,{size:"sm",variant:"outline",onClick:t,className:"border-primary/30 hover:bg-primary/10",children:[e.jsx(It,{className:"h-3 w-3 mr-1"})," Claim"]})}function Kr({viewers:s}){const{user:t}=vs(),r=s.filter(n=>n.user_id!==(t==null?void 0:t.id));return r.length===0?null:e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(ws,{className:"h-3 w-3"}),r.map((n,a)=>e.jsxs("span",{children:[e.jsx("span",{className:"text-foreground/80",children:n.display_name}),n.activity==="reviewing"&&" is reviewing",n.activity==="typing"&&" is typing...",n.activity==="viewing"&&" is viewing",a<r.length-1&&", "]},n.user_id))]})}function vi({notes:s,loading:t,onAdd:r}){const[n,a]=i.useState(""),[l,o]=i.useState(!1),j=async()=>{if(!n.trim())return;o(!0),await r(n)&&a(""),o(!1)};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-muted-foreground",children:[e.jsx(bc,{className:"h-4 w-4"}),"Internal Notes",e.jsx(Y,{variant:"secondary",className:"text-xs",children:s.length})]}),t&&e.jsx("div",{className:"flex justify-center py-3",children:e.jsx(xs,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),s.length>0&&e.jsx("div",{className:"space-y-2 max-h-[200px] overflow-y-auto",children:s.map(b=>e.jsx(z,{className:"border-dashed border-amber-500/20 bg-amber-500/5",children:e.jsxs(V,{className:"p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Bs,{className:"h-5 w-5",children:e.jsx(qs,{className:"text-[10px] bg-amber-500/20 text-amber-400",children:(b.author_name||"S")[0]})}),e.jsx("span",{className:"text-xs font-semibold text-amber-400",children:b.author_name||"Staff"}),e.jsx("span",{className:"text-[10px] text-muted-foreground ml-auto",children:new Date(b.created_at).toLocaleString()})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:b.content})]})},b.id))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($s,{placeholder:"Add an internal note (only visible to staff)...",value:n,onChange:b=>a(b.target.value),rows:2,className:"bg-background/50 text-sm"}),e.jsx(pa,{loading:l,icon:qt,size:"icon",variant:"outline",onClick:j,disabled:l||!n.trim(),className:"shrink-0 self-end"})]})]})}function il({escalatedTo:s}){return s?e.jsxs(Y,{variant:"outline",className:"text-xs border-red-500/50 text-red-400 bg-red-500/10 gap-1",children:[e.jsx(Vt,{className:"h-3 w-3"}),"Escalated to ",s]}):null}const Vd="sidebar:state",Bd=60*60*24*7,qd="16rem",Wd="18rem",Gd="3rem",Hd="b",Ql=i.createContext(null);function mr(){const s=i.useContext(Ql);if(!s)throw new Error("useSidebar must be used within a SidebarProvider.");return s}const Yl=i.forwardRef(({defaultOpen:s=!0,open:t,onOpenChange:r,className:n,style:a,children:l,...o},j)=>{const b=yo(),[c,d]=i.useState(!1),[P,k]=i.useState(s),p=t??P,h=i.useCallback(u=>{const g=typeof u=="function"?u(p):u;r?r(g):k(g),document.cookie=`${Vd}=${g}; path=/; max-age=${Bd}`},[r,p]),f=i.useCallback(()=>b?d(u=>!u):h(u=>!u),[b,h,d]);i.useEffect(()=>{const u=g=>
116{g.key===Hd&&(g.metaKey||g.ctrlKey)&&(g.preventDefault(),f())};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[f]);const _=p?"expanded":"collapsed",m=i.useMemo(()=>({state:_,open:p,setOpen:h,isMobile:b,openMobile:c,setOpenMobile:d,toggleSidebar:f}),[_,p,h,b,c,d,f]);return e.jsx(Ql.Provider,{value:m,children:e.jsx(Yr,{delayDuration:0,children:e.jsx("div",{style:{"--sidebar-width":qd,"--sidebar-width-icon":Gd,...a},className:ms("group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",n),ref:j,...o,children:l})})})});Yl.displayName="SidebarProvider";const Zl=i.forwardRef(({side:s="left",variant:t="sidebar",collapsible:r="offcanvas",className:n,children:a,...l},o)=>{const{isMobile:j,state:b,openMobile:c,setOpenMobile:d}=mr();return r==="none"?e.jsx("div",{className:ms("flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",n),ref:o,...l,children:a}):j?e.jsx(El,{open:c,onOpenChange:d,...l,children:e.jsx(Ol,{"data-sidebar":"sidebar","data-mobile":"true",className:"w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden",style:{"--sidebar-width":Wd},side:s,children:e.jsx("div",{className:"flex h-full w-full flex-col",children:a})})}):e.jsxs("div",{ref:o,className:"group peer hidden text-sidebar-foreground md:block","data-state":b,"data-collapsible":b==="collapsed"?r:"","data-variant":t,"data-side":s,children:[e.jsx("div",{className:ms("relative h-svh w-[--sidebar-width] bg-transparent transition-[width] duration-200 ease-linear","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180",t==="floating"||t==="inset"?"group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon]")}),e.jsx("div",{className:ms("fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] duration-200 ease-linear md:flex",s==="left"?"left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]":"right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",t==="floating"||t==="inset"?"p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]":"group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",n),...l,children:e.jsx("div",{"data-sidebar":"sidebar",className:"flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow",children:a})})]})});Zl.displayName="Sidebar";const Xl=i.forwardRef(({className:s,onClick:t,...r},n)=>{const{toggleSidebar:a}=mr();return e.jsxs($,{ref:n,"data-sidebar":"trigger",variant:"ghost",size:"icon",className:ms("h-7 w-7",s),onClick:l=>{t==null||t(l),a()},...r,children:[e.jsx(jc,{}),e.jsx("span",{className:"sr-only",children:"Toggle Sidebar"})]})});Xl.displayName="SidebarTrigger";const Kd=i.forwardRef(({className:s,...t},r)=>{const{toggleSidebar:n}=mr();return e.jsx("button",{ref:r,"data-sidebar":"rail","aria-label":"Toggle Sidebar",tabIndex:-1,onClick:n,title:"Toggle Sidebar",className:ms("absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] group-data-[side=left]:-right-4 group-data-[side=right]:left-0 hover:after:bg-sidebar-border sm:flex","[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize","[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize","group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar","[[data-side=left][data-collapsible=offcanvas]_&]:-right-2","[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",s),...t})});Kd.displayName="SidebarRail";const Jd=i.forwardRef(({className:s,...t},r)=>e.jsx("main",{ref:r,className:ms("relative flex min-h-svh flex-1 flex-col bg-background","peer-data-[variant=inset]:min-
116h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",s),...t}));Jd.displayName="SidebarInset";const Qd=i.forwardRef(({className:s,...t},r)=>e.jsx(ke,{ref:r,"data-sidebar":"input",className:ms("h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",s),...t}));Qd.displayName="SidebarInput";const Yd=i.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,"data-sidebar":"header",className:ms("flex flex-col gap-2 p-2",s),...t}));Yd.displayName="SidebarHeader";const Zd=i.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,"data-sidebar":"footer",className:ms("flex flex-col gap-2 p-2",s),...t}));Zd.displayName="SidebarFooter";const Xd=i.forwardRef(({className:s,...t},r)=>e.jsx(Fr,{ref:r,"data-sidebar":"separator",className:ms("mx-2 w-auto bg-sidebar-border",s),...t}));Xd.displayName="SidebarSeparator";const eo=i.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,"data-sidebar":"content",className:ms("flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",s),...t}));eo.displayName="SidebarContent";const ti=i.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,"data-sidebar":"group",className:ms("relative flex w-full min-w-0 flex-col p-2",s),...t}));ti.displayName="SidebarGroup";const so=i.forwardRef(({className:s,asChild:t=!1,...r},n)=>{const a=t?dr:"div";return e.jsx(a,{ref:n,"data-sidebar":"group-label",className:ms("flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",s),...r})});so.displayName="SidebarGroupLabel";const em=i.forwardRef(({className:s,asChild:t=!1,...r},n)=>{const a=t?dr:"button";return e.jsx(a,{ref:n,"data-sidebar":"group-action",className:ms("absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","group-data-[collapsible=icon]:hidden",s),...r})});em.displayName="SidebarGroupAction";const to=i.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,"data-sidebar":"group-content",className:ms("w-full text-sm",s),...t}));to.displayName="SidebarGroupContent";const ai=i.forwardRef(({className:s,...t},r)=>e.jsx("ul",{ref:r,"data-sidebar":"menu",className:ms("flex w-full min-w-0 flex-col gap-1",s),...t}));ai.displayName="SidebarMenu";const ri=i.forwardRef(({className:s,...t},r)=>e.jsx("li",{ref:r,"data-sidebar":"menu-item",className:ms("group/menu-item relative",s),...t}));ri.displayName="SidebarMenuItem";const sm=No("peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",{variants:{variant:{default:"hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",outline:"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]"},size:{default:"h-8 text-sm",sm:"h-7 text-xs",lg:"h-12 text-sm group-data-[collapsible=icon]:!p-0"}},defaultVariants:{variant:"default",size:"default"}}),ni=i.forwardRef(({asChild:s=!1,isActive:t=!1,variant:r="default",size:n="default",tooltip:a,className:l,...o},j)=>{const b=s?dr:"button",{isMobile:c,state:d}=mr(),P=e.jsx(b,{ref:j,"data-sidebar":"menu-button","data-size":n,"data-active":t,className:ms(sm({variant:r,size:n}),l),...o});
116return a?(typeof a=="string"&&(a={children:a}),e.jsxs(en,{children:[e.jsx(sn,{asChild:!0,children:P}),e.jsx(tn,{side:"right",align:"center",hidden:d!=="collapsed"||c,...a})]})):P});ni.displayName="SidebarMenuButton";const tm=i.forwardRef(({className:s,asChild:t=!1,showOnHover:r=!1,...n},a)=>{const l=t?dr:"button";return e.jsx(l,{ref:a,"data-sidebar":"menu-action",className:ms("absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform peer-hover/menu-button:text-sidebar-accent-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0","after:absolute after:-inset-2 after:md:hidden","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",r&&"group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",s),...n})});tm.displayName="SidebarMenuAction";const am=i.forwardRef(({className:s,...t},r)=>e.jsx("div",{ref:r,"data-sidebar":"menu-badge",className:ms("pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground","peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground","peer-data-[size=sm]/menu-button:top-1","peer-data-[size=default]/menu-button:top-1.5","peer-data-[size=lg]/menu-button:top-2.5","group-data-[collapsible=icon]:hidden",s),...t}));am.displayName="SidebarMenuBadge";const rm=i.forwardRef(({className:s,showIcon:t=!1,...r},n)=>{const a=i.useMemo(()=>`${Math.floor(Math.random()*40)+50}%`,[]);return e.jsxs("div",{ref:n,"data-sidebar":"menu-skeleton",className:ms("flex h-8 items-center gap-2 rounded-md px-2",s),...r,children:[t&&e.jsx(Ye,{className:"size-4 rounded-md","data-sidebar":"menu-skeleton-icon"}),e.jsx(Ye,{className:"h-4 max-w-[--skeleton-width] flex-1","data-sidebar":"menu-skeleton-text",style:{"--skeleton-width":a}})]})});rm.displayName="SidebarMenuSkeleton";const nm=i.forwardRef(({className:s,...t},r)=>e.jsx("ul",{ref:r,"data-sidebar":"menu-sub",className:ms("mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5","group-data-[collapsible=icon]:hidden",s),...t}));nm.displayName="SidebarMenuSub";const im=i.forwardRef(({...s},t)=>e.jsx("li",{ref:t,...s}));im.displayName="SidebarMenuSubItem";const lm=i.forwardRef(({asChild:s=!1,size:t="md",isActive:r,className:n,...a},l)=>{const o=s?dr:"a";return e.jsx(o,{ref:l,"data-sidebar":"menu-sub-button","data-size":t,"data-active":r,className:ms("flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring aria-disabled:pointer-events-none aria-disabled:opacity-50 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground","data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",t==="sm"&&"text-xs",t==="md"&&"text-sm","group-data-[collapsible=icon]:hidden",n),...a})});lm.displayName="SidebarMenuSubButton";const Wn={W_boost:80,W_sales:15,W_quality:20,W_engagement:20,W_performance:25,W_freshness:18,W_seller:10,W_category_affinity:20,W_tag_similarity:18,W_novelty:12,sales_cap:10,new_upload_days:7,free_dampening:.35,category_cap_ratio:.25,creator_cap:2,revenue_weight:.9,conversion_weight:.7,engagement_weight:.25,new_paid_boost:15,paid_injection_ratio:.35,velocity_weight:.8,exposure_threshold:150,exposure_boost:.3,bayesian_prior_purchases:5,bayesian_prior_views:50,paid_min_conversion_rate:.025,paid_min_rating:4},ll={W_boost:{label:"Boost Weight",description:"Admin boost multiplier weight",min:0,max:200,step:5},W_sales:{label:"Sales Weight",description:"Purchase count influence (capped)",min:0,max:100,step:1}
116,W_quality:{label:"Quality Weight",description:"Rating à review confidence",min:0,max:100,step:1},W_engagement:{label:"Engagement Weight",description:"CTR, views, wishlists blend",min:0,max:100,step:1},W_performance:{label:"Performance Weight",description:"Conversion + revenue-per-view quality signals",min:0,max:100,step:1},W_freshness:{label:"Freshness Weight",description:"Recency and activity boost (key for early-stage)",min:0,max:100,step:1},W_seller:{label:"Seller Reputation Weight",description:"Seller sales/rating factor",min:0,max:50,step:1},W_category_affinity:{label:"Category Affinity",description:"Per-user category preference boost",min:0,max:80,step:1},W_tag_similarity:{label:"Tag Similarity",description:"Content-based tag matching boost",min:0,max:60,step:1},W_novelty:{label:"Novelty Bonus",description:"Unseen product discovery boost",min:0,max:30,step:1},sales_cap:{label:"Sales Cap",description:"Max sales count for linear scoring",min:1,max:50,step:1},new_upload_days:{label:"New Upload Window (days)",description:"Days a product gets the 'new' bonus",min:1,max:30,step:1},free_dampening:{label:"Free Product Dampening",description:"Score multiplier for free products (0-1)",min:0,max:1,step:.05},category_cap_ratio:{label:"Category Cap Ratio",description:"Max % of results from one category",min:.1,max:1,step:.05},creator_cap:{label:"Creator Cap",description:"Max items from same creator before penalty",min:1,max:10,step:1},revenue_weight:{label:"Revenue Weight",description:"Weight for revenue in trending/feed scoring",min:0,max:2,step:.1},conversion_weight:{label:"Conversion Weight",description:"Weight for conversion rate in feed scoring",min:0,max:2,step:.1},engagement_weight:{label:"Feed Engagement Weight",description:"Weight for views/engagement in feed scoring",min:0,max:2,step:.1},new_paid_boost:{label:"New Paid Boost",description:"Smooth decay boost for new paid products (half-life ~36h)",min:0,max:50,step:1},paid_injection_ratio:{label:"Paid Injection Ratio",description:"% of feed slots reserved for paid products",min:0,max:.8,step:.05},velocity_weight:{label:"Revenue Velocity Weight",description:"Weight for 7-day revenue velocity in trending",min:0,max:2,step:.1},exposure_threshold:{label:"Exposure Threshold",description:"View count below which products get visibility boost",min:10,max:500,step:10},exposure_boost:{label:"Exposure Boost",description:"Normalized multiplier for low-exposure products (0-1)",min:0,max:1,step:.05},bayesian_prior_purchases:{label:"Bayesian Prior (Purchases)",description:"Smoothing prior for conversion rate numerator",min:1,max:20,step:1},bayesian_prior_views:{label:"Bayesian Prior (Views)",description:"Smoothing prior for conversion rate denominator",min:10,max:200,step:10},paid_min_conversion_rate:{label:"Paid Min Conversion Rate",description:"Minimum Bayesian conversion rate for paid injection eligibility",min:0,max:.1,step:.005},paid_min_rating:{label:"Paid Min Rating",description:"Minimum avg rating for paid injection eligibility",min:1,max:5,step:.5}};function om(s,t,r,n){const a=Date.now(),{maxSales:l,maxViews:o,maxRevenuePerView:j}=r,b=Math.min(s.sales,t.sales_cap),c=t.sales_cap>0?b/t.sales_cap:0,d=l>0?Math.log2(s.sales+1)/Math.log2(l+2):0,P=c*.7+d*.3,k=1-Math.exp(-s.reviews/3),p=s.rating/5*k,h=s.impressions>0?s.views/s.impressions:0;s.views>0&&s.sales/s.views;const f=Math.min(h/.15,1),_=o>0?Math.log2(s.views+1)/Math.log2(o+2):0,m=Math.min(s.wishlists/20,1),u=f*.4+_*.35+m*.25,g=(s.sales+(t.bayesian_prior_purchases||5))/(s.views+(t.bayesian_prior_views||50)),S=typeof s.revenue=="number"?s.revenue:s.sales*s.price,M=s.views>0?S/s.views:0,y=Math.min(g/.1,1),w=j>0?Math.min(M/j,1):0,F=Math.min(1,s.views/200),J=s.views<50?Math.max(.2,s.views/50):1,E=(y*.6+w*.4)*F*J,N=new Date(s.created_at).getTime(),U=s.updated_at?new Date(s.updated_at).getTime():N,R=s.last_sale_at?new Date(s.last_sale_at).getTime():N,Z=Math.max(0,(a-N)/864e5),W=Math.max(0,(a-U)/864e5),D=Math.max(0,(a-R)/864e5),X=Math.exp(-Z/45),oe=Math.exp(-W/30)*.5,ue=Math.exp(-D/60)*.3;let fe=X*.6+oe+ue;Z<=t.new_upload_days&&(fe+=.3),fe=Math.min(fe,1.5);const je=Math.min((s.seller_total_sales||0)/50,1),Fe=(s.seller_avg_rating||0)/5,Ie=s.seller_tier==="partnered"?.3:s.seller_tier==="trusted"?.15:0,G=je*.35+Fe*.35+Ie,Q=Math.min((s.boost_score||0)/3,1),ve=s.price<=0?t.free_dampening:1,T=t.exposure_threshold||150,ne=t.exposure_boost||.3,he=s.views<T?ne*Math.pow(1-s.views/Math.max(T,1),1.5):0,Oe=s.views>0?s.sales/s.views:0,Ue=s.views>100&&Oe>.03,Xe=1+Oe*2,Be=Ue?Math.min(Xe,1.45):1,ae=s.last_sale_at?new Date(s.last_sale_at).getTime():s.updated_at?new Date(s.updated_at).getTime():N,de=Math.max(0,(a-ae)/864e5),Re=Math.exp(-de/7),pe=Ue?Math.max(1,Be*Re):1,Ce=s.views>200&&Oe<.01,qe=s.views>500&&Oe<.005,Ze=W<=7,ts=Ze?1+.2*Math.exp(-W/3):1,We=Math.max(.5,Math.min(1.5,1)),ns=qe?.2:Ce?.4:1,us=Ze||ns>=1?1:Math.max(.1,1-(1-ns)*We),Ge=qe&&!Ze,He=Z*24,A=s.price>0?1+(t.new_paid_boost||0)/100*Math.exp(-He/36):1,me=(t.W_boost*Q+t.W_sales*P+t.W_quality*p+t.W_engagement*u+t.W_performance*E+t.W_freshness*fe+t.W_seller*G)*(1+he)*ve*us*pe*ts*A;return{...s,boost_component:Q,sales_component:P,quality_component:p,engagement_c
116omponent:u,performance_component:E,freshness_component:fe,seller_component:G,confidence_multiplier:F,low_data_penalty:J,underperforming_penalty:us,auto_boost_multiplier:pe,boost_decay_multiplier:Re,second_chance_boost:ts,second_chance_active:Ze,hidden_from_discovery_candidate:Ge,exploration_component:0,exploration_applied:!1,global_score:me}}function cm(s){if(s.length===0)return 0;const t=[...s].sort((l,o)=>l-o),r=t.length,n=t.reduce((l,o)=>l+o,0);if(n===0)return 0;let a=0;return t.forEach((l,o)=>{a+=(2*(o+1)-r-1)*l}),a/(r*n)}function dm(s,t=7){const r=Date.now()-t*864e5,n=s.filter(l=>new Date(l.created_at).getTime()>=r),a=n.filter(l=>l.views===0).length;return{total:n.length,zeroViews:a,percentage:n.length>0?a/n.length*100:0}}function mm(s){if(s.length===0)return{min:0,max:0,mean:0,median:0,stdDev:0};const t=[...s].sort((o,j)=>o-j),n=t.reduce((o,j)=>o+j,0)/t.length,a=t.length%2===0?(t[t.length/2-1]+t[t.length/2])/2:t[Math.floor(t.length/2)],l=t.reduce((o,j)=>o+(j-n)**2,0)/t.length;return{min:t[0],max:t[t.length-1],mean:n,median:a,stdDev:Math.sqrt(l)}}const gt=ic,ft=lc,jt=oc;function um(){const{isOwner:s,hasPermission:t}=vs();return[{id:"overview",label:"Overview",icon:Ei,items:[{value:"overview",label:"Dashboard",icon:Ei,perm:s||t("view_analytics")},{value:"ai_agent",label:"AI Agent",icon:hc,perm:s||t("use_ai_agent")}]},{id:"catalog",label:"Catalog",icon:vt,items:[{value:"products",label:"Products",icon:vt,perm:s||t("manage_products")},{value:"bundles",label:"Bundles",icon:_o,perm:s||t("manage_products")},{value:"approvals",label:"Approvals",icon:Pa,perm:s||t("manage_products")},{value:"pending_updates",label:"Updates",icon:ua,perm:s||t("manage_products")},{value:"coupons",label:"Coupons",icon:pi,perm:s||t("manage_coupons")},{value:"reviews",label:"Reviews",icon:or,perm:s||t("manage_reviews")}]},{id:"people",label:"People",icon:Ma,items:[{value:"users",label:"Users",icon:Ma,perm:s||t("manage_users")||t("moderate_users")},{value:"bans",label:"Bans",icon:It,perm:s||t("manage_users")},{value:"roles",label:"Roles",icon:kt,perm:s||t("manage_roles")},{value:"permissions",label:"Staff",icon:$l,perm:s||t("manage_permissions")},{value:"sellers",label:"Sellers",icon:fl,perm:s||t("manage_sellers")||t("manage_creators")},{value:"verifications",label:"Verifications",icon:wo,perm:s||t("manage_users")},{value:"referrals",label:"Referrals",icon:Vr,perm:s||t("manage_users")},{value:"recruiters",label:"Recruiters",icon:$a,perm:s||t("manage_users")},{value:"applications",label:"Applications",icon:Ws,perm:s||t("view_applications")||t("manage_applications")},{value:"badges",label:"Badges",icon:Ll,perm:s||t("manage_badges")}]},{id:"orders",label:"Orders & Purchases",icon:zr,items:[{value:"orders",label:"All Purchases",icon:zr,perm:s||t("manage_orders")||t("view_analytics")}]},{id:"insights",label:"Insights",icon:zt,items:[{value:"analytics",label:"Analytics",icon:zt,perm:s||t("view_analytics")},{value:"product_analytics",label:"Product Analytics",icon:Pa,perm:s||t("view_analytics")},{value:"landing_pages",label:"Landing Pages",icon:Bt,perm:s||t("view_analytics")},{value:"db_performance",label:"DB Performance",icon:Ui,perm:s||t("view_analytics")},{value:"site_stats",label:"Live Stats",icon:Dt,perm:s||t("view_analytics")},{value:"trending_tags",label:"Trending Tags",icon:lt,perm:s||t("view_analytics")},{value:"algorithm",label:"Algorithm",icon:jl,perm:s||t("view_analytics")},{value:"utm_builder",label:"UTM Builder",icon:Vr,perm:s||t("manage_utm_links")},{value:"utm_analytics",label:"UTM Analytics",icon:lt,perm:s||t("manage_utm_links")||t("view_analytics")},{value:"wishlists",label:"Wishlists",icon:Xa,perm:s||t("view_wishlists")},{value:"activity_logs",label:"Audit Center",icon:Ws,perm:s||t("view_logs")}]},{id:"support",label:"Support",icon:er,items:[{value:"tickets",label:"Tickets",icon:er,perm:s||t("manage_tickets")||t("view_tickets")},{value:"creator_tickets",label:"Creator Tickets",icon:Jn,perm:s||t("view_creator_tickets")||t("manage_creator_tickets")},{value:"user_messages",label:"Messages",icon:er,perm:s||t("view_messages")||t("manage_messages")},{value:"send_notification",label:"Notify",icon:qt,perm:s||t("send_notifications")},{value:"email_dashboard",label:"Email Dashboard",icon:qt,perm:s||t("view_emails")},{value:"support_stats",label:"Support Stats",icon:Jn,perm:s||t("view_support_stats")}]},{id:"moderation",label:"Moderation",icon:Br,items:[{value:"moderation",label:"Reports & Flags",icon:Br,perm:s||t("manage_moderation")||t("view_moderation")},{value:"dmca_claims",label:"DMCA Claims",icon:kt,perm:s||t("manage_moderation")}]},{id:"content",label:"Content",icon:Gi,items:[{value:"content_pages",label:"Pages & CMS",icon:Gi,perm:s||t("manage_content")}]},{id:"monetization",label:"Monetization",icon:rt,items:[{value:"payments",label:"Finance Overview",icon:rn,perm:s||t("view_revenue")||t("view_payments")},{value:"payment_logs",label:"Payment Logs",icon:Dt,perm:s||t("view_revenue")},{value:"advertising",label:"Advertising",icon:So,perm:s||t("view_anal
116ytics")},{value:"imports",label:"Bulk Imports",icon:cc,perm:s||t("manage_products")},{value:"stress_test",label:"Stress Test",icon:Ui,perm:s}]},{id:"config",label:"Configuration",icon:rr,items:[{value:"settings",label:"Settings",icon:rr,perm:s||t("manage_settings")},{value:"beta_features",label:"Beta Features",icon:dc,perm:s},{value:"themes",label:"Theme & Branding",icon:vl,perm:s||t("manage_themes")},{value:"storage",label:"File Storage",icon:nn,perm:s||t("manage_storage")},{value:"seo_tools",label:"SEO Tools",icon:Bt,perm:s||t("manage_seo")},{value:"status_page",label:"Status Page",icon:vc,perm:s||t("manage_status")||t("manage_settings")}]},{id:"security",label:"Security",icon:It,items:[{value:"security",label:"Security & Logs",icon:It,perm:s||t("view_security")||t("manage_security")},{value:"errors",label:"Errors & Warnings",icon:mc,perm:s||t("view_errors")}]},{id:"help",label:"Help",icon:Ii,items:[{value:"help",label:"Help & Feedback",icon:Ii,perm:!0}]}]}function xm({activeTab:s,onTabChange:t}){var h,f,_;const{state:r}=mr(),n=r==="collapsed",a=um(),[l,o]=i.useState(""),j=(h=a.find(m=>m.items.some(u=>u.value===s)))==null?void 0:h.id,[b,c]=i.useState(new Set(j?[j]:[(f=a[0])==null?void 0:f.id])),d=m=>{c(u=>{const g=new Set(u);return g.has(m)?g.delete(m):g.add(m),g})},P=l.toLowerCase().trim(),k=((_=a[0])==null?void 0:_.items.filter(m=>m.perm))||[],p=i.useMemo(()=>P?a.slice(1).map(m=>{const u=m.label.toLowerCase().includes(P),g=m.items.filter(S=>S.perm&&(S.label.toLowerCase().includes(P)||S.value.toLowerCase().includes(P)));return u?m:g.length>0?{...m,items:g}:null}).filter(Boolean):a.slice(1),[a,P]);return e.jsx(Zl,{collapsible:"icon",className:"border-r border-sidebar-border !top-16 !h-[calc(100vh-4rem)]",children:e.jsxs(eo,{className:"custom-scrollbar",children:[k.length>0&&e.jsx(ti,{className:"pb-0",children:e.jsx(ai,{children:k.map(m=>{const u=m.icon;return e.jsx(ri,{children:e.jsxs(ni,{onClick:()=>{t(m.value),o("")},className:`cursor-pointer transition-all rounded-lg ${s===m.value?"bg-sidebar-primary text-sidebar-primary-foreground font-medium":"text-sidebar-foreground/70 hover:bg-sidebar-accent hover:text-sidebar-foreground"}`,children:[e.jsx(u,{className:"h-4 w-4 shrink-0"}),!n&&e.jsx("span",{children:m.label})]})},m.value)})})}),!n&&e.jsx("div",{className:"px-3 pt-2 pb-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx("input",{type:"text",value:l,onChange:m=>o(m.target.value),placeholder:"Search sections...",className:"w-full h-8 pl-8 pr-3 text-xs rounded-md bg-sidebar-accent/50 border border-sidebar-border/50 text-sidebar-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-1 focus:ring-sidebar-ring/50 transition-colors"})]})}),e.jsx("div",{className:"px-3 py-1.5",children:e.jsx("div",{className:"h-px bg-sidebar-border/60"})}),p.map(m=>{const u=m.items.filter(y=>y.perm);if(u.length===0)return null;const g=m.icon,S=b.has(m.id)||!!P,M=u.some(y=>y.value===s);return e.jsx(gt,{open:S||M,onOpenChange:()=>!P&&d(m.id),children:e.jsxs(ti,{className:"py-0",children:[e.jsx(ft,{className:"w-full",children:e.jsxs(so,{className:"flex items-center justify-between cursor-pointer hover:text-sidebar-foreground transition-colors px-2",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(g,{className:"h-4 w-4"}),!n&&e.jsx("span",{children:m.label})]}),!n&&e.jsx(js,{className:`h-3 w-3 transition-transform ${S||M?"rotate-0":"-rotate-90"}`})]})}),e.jsx(jt,{children:e.jsx(to,{children:e.jsx(ai,{children:u.map(y=>{const w=y.icon,F=s===y.value;return e.jsx(ri,{children:e.jsxs(ni,{onClick:()=>{t(y.value),o("")},className:`cursor-pointer transition-all ${F?"bg-sidebar-primary text-sidebar-primary-foreground font-medium":"text-sidebar-foreground/70 hover:bg-sidebar-accent hover:text-sidebar-foreground"}`,children:[e.jsx(w,{className:"h-4 w-4 shrink-0"}),!n&&e.jsx("span",{children:y.label})]})},y.value)})})})})]})},m.id)}),P&&p.length===0&&e.jsx("div",{className:"px-4 py-6 text-center",children:e.jsxs("p",{className:"text-xs text-muted-foreground",children:['No sections match "',l,'"']})})]})})}const Jr="https://romarkets.shop";function ii(s,t,r){return t>0?s*(1-t/100):r>0?Math.max(0,s-r):s}async function pm(s,t,r,n,a,l,o,j,b){const c=ii(n,l,j),d=ii(a,o,b);if(d>=c)return;const P=Math.round((c-d)/c*100),k=r?`${Jr}/asset/${r}`:`${Jr}/product/${s}`,{data:p}=await x.from("wishlists").select("user_id").eq("product_id",s);if(!p||p.length===0)return;const h=new Date(Date.now()-24*60*60*1e3).toISOString(),f=p.map(M=>
116M.user_id),{data:_}=await x.from("wishlist_notification_log").select("user_id").eq("product_id",s).in("notification_type",["price_drop","discount"]).gte("sent_at",h).in("user_id",f),m=new Set((_||[]).map(M=>M.user_id)),u=f.filter(M=>!m.has(M));if(u.length===0)return;const g=u.map(M=>({user_id:M,type:"price_drop",title:`Price drop on "${t}"`,message:`"${t}" dropped from $${c.toFixed(2)} to $${d.toFixed(2)} (${P}% off)!`,read:!1}));await x.from("notifications").insert(g);for(const M of u)_l(M,`Price drop on "${t}"`,`Now $${d.toFixed(2)} (was $${c.toFixed(2)}) â ${P}% off!`,k,"price-drop");const S=u.map(M=>({user_id:M,product_id:s,notification_type:"price_drop"}));await x.from("wishlist_notification_log").insert(S);for(const M of u)try{const{data:y}=await x.rpc("get_user_email",{target_user_id:M});y&&await x.functions.invoke("send-transactional-email",{body:{templateName:"price-drop",recipientEmail:y,idempotencyKey:`price-drop-${s}-${M}-${Date.now()}`,templateData:{productName:t,oldPrice:c.toFixed(2),newPrice:d.toFixed(2),savingsPercent:String(P),productUrl:k}}})}catch(y){console.error("Failed to send price drop email:",y)}}async function hm(s,t,r,n,a,l){const o=ii(n,a,l);if(o>=n)return;const j=a>0?`${a}% off`:`$${l.toFixed(2)} off`,b=r?`${Jr}/asset/${r}`:`${Jr}/product/${s}`,{data:c}=await x.from("wishlists").select("user_id").eq("product_id",s);if(!c||c.length===0)return;const d=new Date(Date.now()-24*60*60*1e3).toISOString(),P=c.map(m=>m.user_id),{data:k}=await x.from("wishlist_notification_log").select("user_id").eq("product_id",s).in("notification_type",["price_drop","discount"]).gte("sent_at",d).in("user_id",P),p=new Set((k||[]).map(m=>m.user_id)),h=P.filter(m=>!p.has(m));if(h.length===0)return;const f=h.map(m=>({user_id:m,type:"discount_alert",title:`Sale on "${t}"`,message:`"${t}" is now ${j}! Was $${n.toFixed(2)}, now $${o.toFixed(2)}.`,read:!1}));await x.from("notifications").insert(f);for(const m of h)_l(m,`Sale on "${t}"`,`${j} â now $${o.toFixed(2)}!`,b,"discount-alert");const _=h.map(m=>({user_id:m,product_id:s,notification_type:"discount"}));await x.from("wishlist_notification_log").insert(_);for(const m of h)try{const{data:u}=await x.rpc("get_user_email",{target_user_id:m});u&&await x.functions.invoke("send-transactional-email",{body:{templateName:"discount-alert",recipientEmail:u,idempotencyKey:`discount-${s}-${m}-${Date.now()}`,templateData:{productName:t,originalPrice:n.toFixed(2),discountedPrice:o.toFixed(2),discountDetails:j,productUrl:b}}})}catch(u){console.error("Failed to send discount alert email:",u)}}const ol=ko,gm=[{key:"manage_products",label:"Product Management"},{key:"manage_users",label:"User Management"},{key:"grant_products",label:"Grant Products to Users"},{key:"manage_coupons",label:"Coupon Management"},{key:"manage_discounts",label:"Discount Management"},{key:"view_analytics",label:"View Analytics"},{key:"view_revenue",label:"View Revenue & Financial Data"},{key:"manage_tickets",label:"Manage Tickets"},{key:"view_tickets",label:"View Tickets"},{key:"manage_settings",label:"Site Settings"},{key:"manage_reviews",label:"Manage Reviews"},{key:"ban_users",label:"Ban Users"},{key:"delete_accounts",label:"Delete Accounts"},{key:"remove_purchases",label:"Remove Products from Accounts"},{key:"manage_sellers",label:"Manage Sellers & Fees"},{key:"manage_creators",label:"Manage Creators"},{key:"manage_boost",label:"Manage Product Boost Scores"},{key:"view_wishlists",label:"View Wishlist Analytics"},{key:"manage_roles",label:"Manage Roles"},{key:"manage_permissions",label:"Manage Permissions"},{key:"manage_announcements",label:"Manage Announcements"},{key:"manage_themes",label:"Manage Themes & Branding"},{key:"view_logs",label:"View Activity Logs"},{key:"manage_storage",label:"Manage File Storage"},{key:"view_support_stats",label:"View Support Statistics"},{key:"view_messages",label:"View User Messages"},{key:"manage_messages",label:"Manage Messages"},{key:"view_creator_tickets",label:"View Creator Tickets"},{key:"manage_creator_tickets",label:"Manage Creator Tickets"},{key:"send_notifications",label:"Send Notifications"},{key:"manage_orders",label:"Manage Orders"},{key:"manage_moderation",label:"Manage Moderation"},{key:"view_moderation",label:"View Moderation Reports"},{key:"manage_content",label:"Manage Content"},{key:"view_payments",label:"View Payments"},{key:"manage_seo",label:"Manage SEO"},{key:"view_security",label:"View Security & Logs"},{key:"manage_security",label:"Manage Security Settings"},{key:"manage_status",label:"Manage Status Page"},{key:"view_errors",label:"View Errors & Warnings"},{key:"use_ai_agent",label:"Use AI Admin Agent"}
116,{key:"moderate_users",label:"Moderator User Access"},{key:"view_applications",label:"View Applications"},{key:"manage_applications",label:"Manage Applications"},{key:"manage_utm_links",label:"Manage UTM Links"},{key:"view_emails",label:"View Email Dashboard"},{key:"override_claims",label:"Override Staff Claims"},{key:"manage_badges",label:"Manage Badges"}],fm={users:{label:"User Management",actions:["ban_user","unban_user","delete_user","reset_password","set_admin","remove_admin","delete_account"]},products:{label:"Products",actions:["create_product","update_product","delete_product","approve_product","reject_product","grant_product"]},purchases:{label:"Purchases",actions:["remove_purchase"]},moderation:{label:"Moderation",actions:["warn_user","suspend_user","freeze_user","shadow_restrict","resolve_report","dismiss_report"]},roles:{label:"Roles & Permissions",actions:["assign_role","remove_role","create_role","update_role","delete_role","toggle_permission"]},tickets:{label:"Tickets & Claims",actions:["claim_item","unclaim_item","override_claim","reply_ticket","close_ticket","escalate_ticket"]},coupons:{label:"Coupons",actions:["create_coupon","delete_coupon","toggle_coupon"]},reviews:{label:"Reviews",actions:["delete_review","reply_review"]},settings:{label:"Settings & Config",actions:["update_settings","update_theme"]},storage:{label:"File Storage",actions:["delete_file"]},sellers:{label:"Sellers",actions:["approve_seller","reject_seller","update_seller"]}},np=Object.values(fm).flatMap(s=>s.actions),Gn=[{key:"site_name",label:"Site Name",placeholder:"Ro Market",section:"General"},{key:"site_description",label:"Site Description",placeholder:"Your shop tagline",section:"General"},{key:"support_email",label:"Support Email",placeholder:"[email protected]",section:"General"},{key:"announcement_banner",label:"Announcement Banner",placeholder:"Sale ends tonight!",section:"General",hint:"Leave empty to hide. Shows at the top of the site."},{key:"discord_url",label:"Discord",placeholder:"https://discord.gg/your-server",section:"Social Links"},{key:"twitter_url",label:"Twitter / X",placeholder:"https://x.com/yourhandle",section:"Social Links"},{key:"youtube_url",label:"YouTube",placeholder:"https://youtube.com/@yourchannel",section:"Social Links"},{key:"instagram_url",label:"Instagram",placeholder:"https://instagram.com/yourhandle",section:"Social Links"},{key:"tiktok_url",label:"TikTok",placeholder:"https://tiktok.com/@yourhandle",section:"Social Links"},{key:"terms_url",label:"Terms of Service URL",placeholder:"https://example.com/terms",section:"Legal"},{key:"privacy_url",label:"Privacy Policy URL",placeholder:"https://example.com/privacy",section:"Legal"}],Hn=[{key:"brand_primary_color",label:"Primary Color",type:"color",default:"#00ff96",section:"Colors"},{key:"brand_accent_color",label:"Accent Color",type:"color",default:"#a855f7",section:"Colors"},{key:"brand_background_color",label:"Background Color",type:"color",default:"#0f1318",section:"Colors"},{key:"brand_logo_url",label:"Logo URL",type:"text",placeholder:"https://example.com/logo.png",section:"Branding"},{key:"brand_favicon_url",label:"Favicon URL",type:"text",placeholder:"https://example.com/favicon.ico",section:"Branding"},{key:"brand_og_image_url",label:"Social Share Image URL",type:"text",placeholder:"https://example.com/og-image.png",section:"Branding"},{key:"brand_font_heading",label:"Heading Font",type:"text",placeholder:"Rajdhani",section:"Typography"},{key:"brand_font_body",label:"Body Font",type:"text",placeholder:"Space Grotesk",section:"Typography"},{key:"custom_css",label:"Custom CSS Override",type:"textarea",placeholder:"/* Your custom CSS here */",section:"Advanced"},{key:"custom_head_html",label:"Custom Head HTML",type:"textarea",placeholder:"<meta ...> or <script ...>",section:"Advanced"}];function jm({selectedCount:s,onApprove:t,onReject:r,onFeature:n,onArchive:a,onClear:l}){return s<=0?null:e.jsxs("div",{className:"flex items-center gap-3 mb-4 p-3 rounded-lg bg-primary/10 border border-primary/20 flex-wrap",children:[e.jsxs("span",{className:"text-sm font-medium",children:[s," selected"]}),e.jsx($,{size:"sm",variant:"outline",onClick:t,children:"Approve"}),e.jsx($,{size:"sm",variant:"outline",onClick:r,children:"Reject"}),e.jsx($,{size:"sm",variant:"outline",onClick:n,children:"â Feature"}),e.jsx($,{size:"sm",variant:"outline",onClick:a,children:"Archive"}),e.jsx($,{size:"sm",variant:"ghost",onClick:l,children:"Clear"})]})}function vm({filteredCount:s,searchQuery:t,selectedCount:r,pageCount:n,onTogglePageSelection:a}){return e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s," product",s!==1?"s":""," found",t&&` for "${t}"`]}),e.jsx($,{variant:"ghost",size:"sm",className:"text-xs",onClick:a,children:r===n&&n>0?"Deselect All":"Select All"})]})}function bm(){const[s,t]=i.useState([]),[r,n]=i.useState(!1),[a,l]=i.useState(null),[o,j]=i.useState({name:"",description:"",price:"0",category:"asset",discount_percentage:"0",discount_amount:"0",youtube_url:"",stock:"",license_type:"standard",tags:"",version:"1.0.0"}),[b,c]=i.useState(null),[d,P]=i.useState(null),[k,p]=i.useState(!1),[h,f]=i.useState(""),[_,m]=i.useState("created_at_desc"),[u,g]=i.useState("all"),[S,M]=i.useState("all"),[y,w]=i.useState("all"),[F,J]=i.useState(""),[E,N]=i.useState(""),[U,R]=i.useState(1),[Z,W]=i.useState({}),[D,X]=i.useState(new Set),[oe,ue]=i.useState("grid"),[fe,je]=i.useState({}),[Fe,Ie]=i.useState({}),[G,Q]=i.useState({}),[xe,ve]=i.useState([]),[T,ne]=i.useState({}),[he,Oe]=i.useState([]),[Ue,Xe]=i.useState([]),[Be,ae]=i.useState("details"),de=oe==="table"?50:12,Re=async()=>{const[A,me,ze,Le,B,ee]=await Promise.all([Fs(()=>x.from("products").select("*, product_images(id, product_id)").order("created_at",{ascending:!1})),Fs(()=>x.from("reviews").select("product_id, rating")),Fs(()=>x.from("purchases").select("product_id").eq("granted",!1)),Fs(()=>x.from("seller_profiles").select("id, user_id")),Fs(()=>x.from("profiles").select("user_id, display_name")),Fs(()=>x.from("license_tiers").select("product_id, price_cents").eq("is_active",!0))]),te={};
116(ee||[]).forEach(le=>{te[le.product_id]||(te[le.product_id]={count:0,min_cents:null}),te[le.product_id].count++;const q=le.price_cents??0;(te[le.product_id].min_cents===null||q<te[le.product_id].min_cents)&&(te[le.product_id].min_cents=q)});const se=(A||[]).map(le=>{var q,K;return{...le,license_tier_count:((q=te[le.id])==null?void 0:q.count)??0,min_tier_price_cents:((K=te[le.id])==null?void 0:K.min_cents)??null}});t(se);const be={};(A||[]).forEach(le=>{le.slug&&(be[le.id]=le.slug)}),ne(be);const Se={};(ze||[]).forEach(le=>{Se[le.product_id]=(Se[le.product_id]||0)+1}),je(Se);const _e={};(A||[]).forEach(le=>{_e[le.id]=Array.isArray(le.product_images)?le.product_images.length:0}),Ie(_e);const Ke={};(Le||[]).forEach(le=>{Ke[le.id]=le.user_id});const rs={};(B||[]).forEach(le=>{rs[le.user_id]=le.display_name||"Unknown"});const H={},ce=new Map;if((A||[]).forEach(le=>{if(le.seller_id&&Ke[le.seller_id]){const q=Ke[le.seller_id],K=rs[q]||"Unknown";H[le.id]=K,ce.set(le.seller_id,K)}}),Q(H),ve(Array.from(ce.entries()).map(([le,q])=>({id:le,name:q})).sort((le,q)=>le.name.localeCompare(q.name))),me){const le={};me.forEach(K=>{le[K.product_id]||(le[K.product_id]={count:0,total:0}),le[K.product_id].count++,le[K.product_id].total+=K.rating});const q={};Object.entries(le).forEach(([K,re])=>{q[K]={count:re.count,avg:re.total/re.count}}),W(q)}};i.useEffect(()=>{Re()},[]),i.useEffect(()=>{R(1),X(new Set)},[h,_,u,S,y,F,E]);const pe=()=>{j({name:"",description:"",price:"0",category:"asset",discount_percentage:"0",discount_amount:"0",youtube_url:"",stock:"",license_type:"standard",tags:"",version:"1.0.0"}),c(null),P(null),l(null),Oe([]),Xe([]),ae("details")},Ce=async A=>{l(A.id),j({name:A.name,description:A.description||"",price:String(A.price),category:A.category,discount_percentage:String(A.discount_percentage||0),discount_amount:String(A.discount_amount||0),youtube_url:A.youtube_url||"",stock:A.stock!==null?String(A.stock):"",license_type:A.license_type||"standard",tags:(A.tags||[]).join(", "),version:A.version||"1.0.0"}),ae("details"),Xe([]);const{data:me}=await x.from("product_images").select("*").eq("product_id",A.id).order("sort_order");Oe(me||[]),n(!0)},qe=async A=>{await x.from("product_images").delete().eq("id",A),Oe(me=>me.filter(ze=>ze.id!==A)),O.success("Image removed")},Ze=async()=>{if(!o.name.trim()){O.error("Name is required");return}const A=Lo(o.description);if(!A.valid){O.error(A.errors[0]);return}p(!0);let me=null,ze=null;if(b){const se=b.name.split(".").pop(),be=`products/original/${crypto.randomUUID()}.${se}`,{error:Se}=await x.storage.from("product-images").upload(be,b);if(Se){O.error("Image upload failed"),p(!1);return}x.functions.invoke("optimize-image",{body:{bucket:"product-images",path:be,imageType:"product"}}).catch(()=>{});const{data:_e}=x.storage.from("product-images").getPublicUrl(be);me=_e.publicUrl}let Le=null,B=null;if(d){B=await Xo(d);const se=await ec(B);if(se){O.error(`This file is a duplicate of "${se}". Duplicate uploads are blocked.`),p(!1);return}const be=d.name.split(".").pop(),Se=`${crypto.randomUUID()}.${be}`,{error:_e}=await x.storage.from("product-files").upload(Se,d);if(_e){O.error("File upload failed"),p(!1);return}ze=Se,Le=d.name}const ee=o.tags.split(",").map(se=>se.trim()).filter(Boolean),te={name:o.name,description:A.sanitized||null,price:parseFloat(o.price)||0,category:o.category,discount_percentage:parseFloat(o.discount_percentage)||0,discount_amount:parseFloat(o.discount_amount)||0,youtube_url:o.youtube_url||null,stock:o.stock.trim()===""?null:parseInt(o.stock)||0,license_type:o.license_type,tags:ee.length>0?ee:[],version:o.version||"1.0.0"};if(me&&(te.image_url=me),ze&&(te.file_url=ze,te.file_name=Le),a){const se=s.find(Se=>Se.id===a),{error:be}=await x.from("products").update(te).eq("id",a);if(be)O.error(be.message);else{if(O.success("Product updated!"),ss("update_product","product",a,{name:o.name}),B&&await $i(a,B,(d==null?void 0:d.name.split(".").pop())||"unknown"),se){const Se=se.discount_percentage||0,_e=se.discount_amount||0,Ke=te.discount_percentage||0,rs=te.discount_amount||0;pm(a,te.name,se.slug,se.price,te.price,Se,Ke,_e,rs).catch(H=>console.error("Wishlist price drop notification error:",H)),(Ke>0&&Se===0||rs>0&&_e===0)&&hm(a,te.name,se.slug,te.price,Ke,rs).catch(H=>console.error("Wishlist discount notification error:",H))}if(Ue.length>0){const Se=he.length;await Promise.all(Ue.map(async(_e,Ke)=>{const rs=_e.name.split(".").pop(),H=`products/original/${crypto.randomUUID()}.${rs}`,{error:ce}=await x.storage.from("product-images").upload(H,_e);if(ce)return;x.functions.invoke("optimize-image",{body:{bucket:"product-images",path:H,imageType:"product"}}).catch(()=>{});const{data:le}=x.storage.from("product-images").getPublicUrl(H);await x.from("product_images").insert({product_id:a,image_url:le.publicUrl,sort_order:Se+Ke,is_thumbnail:!1})}))}}}else{const{data:se,error:be}=await x.from("products").insert(te).select("id").single();be?O.error(be.message):(O.success("Product added!"),ss("create_product","product",se==null?void 0:se.id,{name:o.name}),B&&(se!=null&&se.id)&&await $i(se.id,B,(d==null?void 0:d.name.split(".").pop())||"unknown"))}p(!1),n(!1),pe(),Re()},ts=async A=>
116{if(!confirm("Delete this product?"))return;const me=s.find(Le=>Le.id===A),{error:ze}=await x.from("products").delete().eq("id",A);ze?O.error(ze.message):(O.success("Deleted"),ss("delete_product","product",A,{name:me==null?void 0:me.name}),Re())},We=async(A,me)=>{await x.from("products").update({slug:null}).eq("id",A),await x.from("products").update({name:me}).eq("id",A),O.success("Slug regenerated"),Re()},ns=A=>Co(A),us=s.filter(A=>{const me=!h||A.name.toLowerCase().includes(h.toLowerCase())||(A.description||"").toLowerCase().includes(h.toLowerCase()),ze=u==="all"||A.category===u,Le=S==="all"||A.status===S,B=y==="all"||A.seller_id===y,ee=ns(A),te=!F||ee>=parseFloat(F),se=!E||ee<=parseFloat(E);return me&&ze&&Le&&B&&te&&se}).sort((A,me)=>{switch(_){case"name_asc":return A.name.localeCompare(me.name);case"name_desc":return me.name.localeCompare(A.name);case"price_asc":return A.price-me.price;case"price_desc":return me.price-A.price;case"sales_desc":return(fe[me.id]||0)-(fe[A.id]||0);case"sales_asc":return(fe[A.id]||0)-(fe[me.id]||0);case"created_at_asc":return new Date(A.created_at).getTime()-new Date(me.created_at).getTime();case"created_at_desc":default:return new Date(me.created_at).getTime()-new Date(A.created_at).getTime()}}),Ge=Math.max(1,Math.ceil(us.length/de)),He=us.slice((U-1)*de,U*de);return e.jsxs(e.Fragment,{children:[e.jsx(jm,{selectedCount:D.size,onApprove:async()=>{if(confirm(`Approve ${D.size} product(s)?`)){for(const A of D)await x.from("products").update({status:"approved"}).eq("id",A);O.success(`${D.size} product(s) approved`),X(new Set),Re()}},onReject:async()=>{if(confirm(`Reject ${D.size} product(s)?`)){for(const A of D)await x.from("products").update({status:"rejected"}).eq("id",A);O.success(`${D.size} product(s) rejected`),X(new Set),Re()}},onFeature:async()=>{if(confirm(`Feature ${D.size} product(s)? (boost +10)`)){for(const A of D){const me=s.find(ze=>ze.id===A);await x.from("products").update({boost_score:((me==null?void 0:me.boost_score)||0)+10}).eq("id",A)}O.success(`${D.size} product(s) featured`),X(new Set),Re()}},onArchive:async()=>{if(confirm(`Archive ${D.size} product(s)?`)){for(const A of D)await x.from("products").update({status:"archived"}).eq("id",A);O.success(`${D.size} product(s) archived`),X(new Set),Re()}},onClear:()=>X(new Set)}),e.jsxs("div",{className:"flex flex-col gap-3 mb-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(Gs,{placeholder:"Search products...",value:h,onChange:f,className:"bg-background/50",wrapperClassName:"flex-1"}),e.jsxs(Pe,{value:u,onValueChange:g,children:[e.jsx(Te,{className:"w-[140px] bg-background/50",children:e.jsx(De,{placeholder:"Category"})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Categories"}),ol.map(A=>e.jsx(L,{value:A,children:A.replace(/_/g," ")},A))]})]}),e.jsxs(Pe,{value:S,onValueChange:M,children:[e.jsx(Te,{className:"w-[130px] bg-background/50",children:e.jsx(De,{placeholder:"Status"})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Status"}),e.jsx(L,{value:"approved",children:"Approved"}),e.jsx(L,{value:"pending",children:"Pending"}),e.jsx(L,{value:"rejected",children:"Rejected"}),e.jsx(L,{value:"archived",children:"Archived"})]})]}),e.jsxs(Pe,{value:y,onValueChange:w,children:[e.jsx(Te,{className:"w-[150px] bg-background/50",children:e.jsx(De,{placeholder:"Owner"})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Owners"}),xe.map(A=>e.jsx(L,{value:A.id,children:A.name},A.id))]})]}),e.jsxs(Pe,{value:_,onValueChange:m,children:[e.jsx(Te,{className:"w-[160px] bg-background/50",children:e.jsx(De,{placeholder:"Sort"})}),e.jsxs(Me,{children:[e.jsx(L,{value:"created_at_desc",children:"Newest First"}),e.jsx(L,{value:"created_at_asc",children:"Oldest First"}),e.jsx(L,{value:"sales_desc",children:"Sales â"}),e.jsx(L,{value:"sales_asc",children:"Sales â"}),e.jsx(L,{value:"name_asc",children:"Name AâZ"}),e.jsx(L,{value:"name_desc",children:"Name ZâA"}),e.jsx(L,{value:"price_asc",children:"Price LowâHigh"}),e.jsx(L,{value:"price_desc",children:"Price HighâLow"})]})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Price:"}),e.jsx(ke,{type:"number",placeholder:"Min",value:F,onChange:A=>J(A.target.value),className:"w-20 h-8 text-xs bg-background/50"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"â"}),e.jsx(ke,{type:"number",placeholder:"Max",value:E,onChange:A=>N(A.target.value),className:"w-20 h-8 text-xs bg-background/50"})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{size:"sm",variant:oe==="table"?"default":"outline",onClick:()=>ue("table"),className:"h-8 text-xs",children:[e.jsx(Ws,{className:"h-3 w-3 mr-1"})," Table"]}),e.jsxs($,{size:"sm",variant:oe==="grid"?"default":"outline",onClick:()=>ue("grid"),className:"h-8 text-xs",children:[e.jsx(vt,{className:"h-3 w-3 mr-1"})," Grid"]})]}),e.jsxs(Ds,{open:r,onOpenChange:A=>{n(A),A||pe()},children:[e.jsx(an,{asChild:!0,children:e.jsxs($,{className:"glow-primary whitespace-nowrap",children:[e.jsx(Fa,{className:"mr-1 h-4 w-4"})," Add Product"]})}),e.jsxs(Ms,{className:"glass sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Es,{children:[e.jsx(Os,{className:"font-display text-lg",children:a?"Edit Product":"Add Product"}),a&&T[a]&&e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs("code",{className:"text-xs text-muted-foreground",children:["/",T[a]]}),e.jsx($,{size:"sm",variant:"ghost",className:"h-6 text-[10px] px-2",onClick:()=>We(a,o.name),children:"Regenerate"})]})]}),e.jsx("div",{className:"flex gap-1 border-b border-border/50 pb-0 mt-2",children:[{key:"details",label:"Details"},{key:"pricing",label:"Pricing & Stock"},{key:"images",label:`Images${a?` (${he.length})`:""}`},{key:"files",label:"Files & Media"}].map(A=>e.jsx("button",{onClick:()=>ae(A.key),className:`px-3 py-2 text-sm font-medium border-b-2 transition-colors -mb-[1px] ${Be===A.key?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground"}`,children:A.label},A.key))}),e.jsxs("div",{className:"mt-4 min-h-[300px]",children:[Be==="details"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",children:"Product Name"}),e.jsx(ke,{placeholder:"e.g. Ultimate FPS Framework",value:o.name,onChange:A=>j({...o,name:A.target.value}),className:"bg-background/50"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx("textarea",{value:o.description,onChange:A=>j({...o,description:A.target.value}),placeholder:"Describe what this product does...",className:"w-full min-h-[120px] rounded-md border border-border bg-background/50 px-3 py-2 text-sm"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",children:"Category"}),e.jsxs(Pe,{value:o.category,onValueChange:A=>j({...o,category:A}),children:[e.jsx(Te,{className:"bg-background/50",children:e.jsx(De,{})}),e.jsx(Me,{children:ol.map(A=>e.jsx(L,{value:A,children:A.replace(/_/g," ")},A))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",children:"License Type"}),e.jsxs(Pe,{value:o.license_type,onValueChange:A=>j({...o,license_type:A}),children:[e.jsx(Te,{className:"bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"free",children:"Free EULA"}),e.jsx(L,{value:"single_project",children:"Single Project EULA"}),e.jsx(L,{value:"standard",children:"Standard EULA"}),e.jsx(L,{value:"attribution_free",children:"Attribution Free EULA"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",children:"Tags"}),e.jsx(ke,{placeholder:"fps, shooter, gun system",value:o.tags,onChange:A=>j({...o,tags:A.target.value}),className:"bg-background/50"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Comma separated"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",children:"Version"}),e.jsx(ke,{placeholder:"1.0.0",value:o.version,onChange:A=>j({...o,version:A.target.value}),className:"bg-background/50"})]})]})]}),Be==="pricing"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",children:"Price (USD)"}),e.jsx(ke,{type:"number",step:"0.01",min:"0",placeholder:"0.00",value:o.price,onChange:A=>j({...o,price:A.target.value}),className:"bg-background/50"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Set to 0 for a free product"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",children:"Discount %"}),e.jsx(ke,{type:"number",step:"1",min:"0",max:"100",value:o.discount_percentage,onChange:A=>j({...o,discount_percentage:A.target.value,discount_amount:"0"}),className:"bg-background/50"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Percentage off (clears $ discount)"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",children:"Discount $ Off"}),e.jsx(ke,{type:"number",step:"0.01",min:"0",value:o.discount_amount,onChange:A=>j({...o,discount_amount:A.target.value,discount_percentage:"0"}),className:"bg-background/50"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Flat amount off (clears % discount)"})]})]}),parseFloat(o.price)>0&&(parseFloat(o.discount_percentage)>0||parseFloat(o.discount_amount)>0)&&e.jsx("div",{className:"p-3 rounded-lg bg-primary/10 border border-primary/20",children:e.jsxs("p",{className:"text-sm font-medium",children:["Effective Price: ",e.jsxs("span",{className:"text-primary",children:["$",(parseFloat(o.discount_percentage)>0?parseFloat(o.price)*(1-parseFloat(o.discount_percentage)/100):Math.max(0,parseFloat(o.price)-parseFloat(o.discount_amount))).toFixed(2)]})]})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",children:"Stock"}),e.jsx(ke,{type:"number",min:"0",placeholder:"Leave empty for unlimited",value:o.stock,onChange:A=>j({...o,stock:A.target.value}),className:"bg-background/50"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Leave blank for unlimited stock"})]})]}),Be==="images"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",children:"Main Preview Image"}),a&&(()=>{const A=s.find(me=>me.id===a);return A!=null&&A.image_url&&!b?e.jsxs("div",{className:"relative w-full h-40 rounded-lg overflow-hidden bg-secondary/30 border border-border/50 mb-2",children:[e.jsx("img",{src:A.image_url,alt:"Preview",className:"w-full h-full object-cover"}),e.jsx("span",{className:"absolute top-2 left-2 text-[10px] bg-background/80 px-2 py-0.5 rounded",children:"Current"})]}):null})(),e.jsx(ke,{type:"file",accept:"image/*",onChange:A=>{var me;return c(((me=A.target.files)==null?void 0:me[0])||null)},className:"bg-background/50"}),b&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["New image: ",b.name]})]}),a&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-sm font-medium",children:["Gallery Images (",he.length,"/8)"]}),he.length>0?e.jsx("div",{className:"grid grid-cols-4 gap-2",children:he.map(A=>e.jsxs("div",{className:"relative group rounded-lg overflow-hidden border border-border/50 aspect-square",children:[e.jsx("img",{src:A.image_url,alt:"",className:"w-full h-full object-cover"}),A.is_thumbnail&&e.jsx("span",{className:"absolute top-1 left-1 text-[9px] bg-primary/80 text-primary-foreground px-1 rounded",children:"Thumb"}),e.jsx("button",{onClick:()=>qe(A.id),className:"absolute top-1 right-1 w-5 h-5 rounded-full bg-destructive/90 text-destructive-foreground flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(As,{className:"h-3 w-3"})})]},A.id))}):e.jsx("p",{className:"text-xs text-muted-foreground py-4 text-center",children:"No gallery images yet"}),he.length<20&&e.jsxs("div",{className:"space-y-1.5 mt-2",children:[e.jsxs("label",{className:"text-xs text-muted-foreground",children:["Add more images (up to ",20-he.length," more)"]}),e.jsx(ke,{type:"file",accept:"image/*",multiple:!0,onChange:A=>{const me=Array.from(A.target.files||[]),ze=20-he.length;Xe(me.slice(0,ze))},className:"bg-background/50"}),Ue.length>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ue.length," new image(s) will be uploaded on save"]})]})]})]}),Be==="files"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",children:"YouTube Video URL"}),e.jsx(ke,{placeholder:"https://youtube.com/watch?v=...",value:o.youtube_url,onChange:A=>j({...o,youtube_url:A.target.value}),className:"bg-background/50"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Video preview shown on the product page"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-sm font-medium",children:"Downloadable File"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:".rbxm, .rbxl, .zip, etc. â Max 50MB"}),a&&(()=>{const A=s.find(Le=>Le.id===a),me=A==null?void 0:A.file_url,ze=(A==null?void 0:A.file_name)||(me==null?void 0:me.split("/").pop())||"Unknown file";return me&&!d?e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-secondary/30 border border-border/50",children:[e.jsx(Pa,{className:"h-4 w-4 text-primary shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ze}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Currently attached"})]}),e.jsxs($,{size:"sm",variant:"outline",className:"h-7 text-xs shrink-0",onClick:async()=>{const{downloadProductFile:Le}=await as(async()=>{const{downloadProductFile:ee}=await import("./download-file-GiM6ssRc.js");return{downloadProductFile:ee}},__vite__mapDeps([0,1,2,3,4,5,6]));await Le(me,ze)||O.error("Download failed")},children:[e.jsx(nt,{className:"h-3 w-3 mr-1"})," Download"]})]}):null})(),e.jsx(ke,{type:"file",onChange:A=>{var me;return P(((me=A.target.files)==null?void 0:me[0])||null)},className:"bg-background/50 mt-1"}),d&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["New file: ",d.name,"
116(",(d.size/1024/1024).toFixed(1)," MB)"]})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t border-border/50 mt-4",children:[e.jsx($,{variant:"outline",onClick:()=>{n(!1),pe()},children:"Cancel"}),e.jsx(pa,{loading:k,onClick:Ze,className:"min-w-[120px]",loadingText:"Saving...",children:a?"Update Product":"Add Product"})]})]})]})]})]}),e.jsx(vm,{filteredCount:us.length,searchQuery:h,selectedCount:D.size,pageCount:He.length,onTogglePageSelection:()=>{D.size===He.length?X(new Set):X(new Set(He.map(A=>A.id)))}}),oe==="table"&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-border/50",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/50 bg-secondary/20",children:[e.jsx("th",{className:"py-2 px-2 w-8",children:e.jsx("span",{className:"sr-only",children:"Select"})}),e.jsx("th",{className:"text-left py-2 px-3 text-muted-foreground font-medium",children:"Product"}),e.jsx("th",{className:"text-left py-2 px-3 text-muted-foreground font-medium",children:"Slug"}),e.jsx("th",{className:"text-left py-2 px-3 text-muted-foreground font-medium",children:"Category"}),e.jsx("th",{className:"text-left py-2 px-3 text-muted-foreground font-medium",children:"Tags"}),e.jsx("th",{className:"text-right py-2 px-3 text-muted-foreground font-medium",children:"Price"}),e.jsx("th",{className:"text-center py-2 px-3 text-muted-foreground font-medium",children:"Status"}),e.jsx("th",{className:"text-right py-2 px-3 text-muted-foreground font-medium",children:"Imgs"}),e.jsx("th",{className:"text-right py-2 px-3 text-muted-foreground font-medium",children:"Sales"}),e.jsx("th",{className:"text-left py-2 px-3 text-muted-foreground font-medium",children:"Owner"}),e.jsx("th",{className:"text-left py-2 px-3 text-muted-foreground font-medium",children:"Created"}),e.jsx("th",{className:"text-right py-2 px-3 text-muted-foreground font-medium",children:"Actions"})]})}),e.jsx("tbody",{children:He.map(A=>{ns(A);const me=D.has(A.id);return e.jsxs("tr",{className:`border-b border-border/20 hover:bg-secondary/10 ${me?"bg-primary/5":""}`,children:[e.jsx("td",{className:"py-2 px-2 text-center",children:e.jsx("button",{className:"w-4 h-4 rounded border border-border flex items-center justify-center cursor-pointer",onClick:()=>{X(ze=>{const Le=new Set(ze);return Le.has(A.id)?Le.delete(A.id):Le.add(A.id),Le})},children:me&&e.jsx("span",{className:"text-primary text-[10px] font-bold",children:"â"})})}),e.jsx("td",{className:"py-2 px-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[A.image_url?e.jsx("img",{src:A.image_url,alt:"",className:"w-8 h-8 rounded object-cover"}):e.jsx("div",{className:"w-8 h-8 rounded bg-secondary/50 flex items-center justify-center",children:e.jsx(vt,{className:"h-4 w-4 text-muted-foreground/30"})}),e.jsx("span",{className:"font-medium truncate max-w-[180px]",children:A.name})]})}),e.jsx("td",{className:"py-2 px-3",children:e.jsx("code",{className:"text-xs text-muted-foreground",children:T[A.id]||"â"})}),e.jsx("td",{className:"py-2 px-3",children:e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:A.category.replace(/_/g," ")})}),e.jsx("td",{className:"py-2 px-3",children:e.jsxs("div",{className:"flex gap-1 flex-wrap max-w-[120px]",children:[(A.tags||[]).slice(0,2).map((ze,Le)=>e.jsx(Y,{variant:"outline",className:"text-[9px] px-1",children:ze},Le)),(A.tags||[]).length>2&&e.jsxs("span",{className:"text-[9px] text-muted-foreground",children:["+",A.tags.length-2]})]})}),e.jsxs("td",{className:"py-2 px-3 text-right font-mono",children:[e.jsx("span",{children:Rt(A)}),Ft(A)&&e.jsx("span",{className:"text-[9px] text-muted-foreground block",children:Ft(A)})]}),e.jsx("td",{className:"py-2 px-3 text-center",children:e.jsx(Y,{variant:A.status==="pending"?"outline":A.status==="rejected"?"destructive":A.status==="archived"?"secondary":"default",className:"text-[10px]",children:A.status||"approved"})}),e.jsx("td",{className:"py-2 px-3 text-right font-mono text-muted-foreground",children:(Fe[A.id]||0)+(A.image_url?1:0)}),e.jsx("td",{className:"py-2 px-3 text-right font-mono font-medium",children:fe[A.id]||0}),e.jsx("td",{className:"py-2 px-3 text-xs text-muted-foreground truncate max-w-[100px]",children:G[A.id]||"â"}),e.jsx("td",{className:"py-2 px-3 text-xs text-muted-foreground font-mono",children:new Date(A.created_at).toLocaleDateString()}),e.jsx("td",{className:"py-2 px-3 text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[T[A.id]&&e.jsx($,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",title:"Preview",onClick:()=>window.open(`/asset/${T[A.id]}`,"_blank"),children:e.jsx(ws,{className:"h-3 w-3"})}),e.jsx($,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>Ce(A),title:"Edit",children:e.jsx(ua,{className:"h-3 w-3"})}),e.jsx($,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-destructive",onClick:()=>ts(A.id),title:"Delete",children:e.jsx(As,{className:"h-3 w-3"})})]})})]},A.id)})})]})}),oe==="grid"&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:He.map(A=>{ns(A);const me=!1,ze=D.has(A.id);return e.jsxs(z,{className:`glass group hover:ring-1 hover:ring-primary/30 transition-all ${ze?"ring-2 ring-primary":""}`,children:[e.jsxs("div",{className:"aspect-video bg-secondary/50 flex items-center justify-center overflow-hidden rounded-t-lg relative",children:[e.jsx("button",{className:"absolute top-2 left-2 z-10 w-5 h-5 rounded border border-border bg-background/80 flex items-center justify-center cursor-pointer",onClick:Le=>{Le.stopPropagation(),X(B=>{const ee=new Set(B);return ee.has(A.id)?ee.delete(A.id):ee.add(A.id),ee})},children:ze&&e.jsx("span",{className:"text-primary text-xs font-bold",children:"â"})}),A.image_url?e.jsx("img",{src:A.image_url,alt:A.name,className:"w-full h-full object-cover"}
116):e.jsx(vt,{className:"h-10 w-10 text-muted-foreground/30"}),me]}),e.jsxs(V,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"font-display font-semibold truncate text-sm",children:A.name}),e.jsx(Y,{variant:A.status==="pending"?"outline":A.status==="rejected"?"destructive":"secondary",className:"text-[10px] shrink-0",children:A.status||"approved"})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[e.jsxs("span",{children:[fe[A.id]||0," sales"]}),e.jsxs("span",{children:[(Fe[A.id]||0)+(A.image_url?1:0)," imgs"]}),G[A.id]&&e.jsx("span",{className:"truncate max-w-[80px]",children:G[A.id]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 mt-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-lg font-display font-bold text-primary",children:Rt(A)}),Ft(A)&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Ft(A)})]}),A.stock!==null&&e.jsx(Y,{variant:A.stock===0?"destructive":"outline",className:"text-xs",children:A.stock===0?"Out of stock":`${A.stock} left`})]}),Z[A.id]&&e.jsxs("div",{className:"flex items-center gap-1.5 mt-2 text-xs text-muted-foreground",children:[e.jsx("div",{className:"flex",children:[1,2,3,4,5].map(Le=>e.jsx(or,{className:`h-3 w-3 ${Le<=Math.round(Z[A.id].avg)?"text-primary fill-primary":"text-muted-foreground/30"}`},Le))}),e.jsxs("span",{children:[Z[A.id].avg.toFixed(1)," (",Z[A.id].count,")"]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Boost: ",A.boost_score||0]}),e.jsx($,{size:"sm",variant:"outline",className:"h-6 w-6 p-0",onClick:async()=>{await x.from("products").update({boost_score:(A.boost_score||0)+1}).eq("id",A.id),Re()},children:e.jsx(Dl,{className:"h-3 w-3"})}),e.jsx($,{size:"sm",variant:"outline",className:"h-6 w-6 p-0",onClick:async()=>{await x.from("products").update({boost_score:Math.max(0,(A.boost_score||0)-1)}).eq("id",A.id),Re()},children:e.jsx(mi,{className:"h-3 w-3"})}),e.jsx(ke,{type:"number",min:"0",className:"h-6 w-16 text-xs bg-background/50",defaultValue:A.boost_score||0,onBlur:async Le=>{const B=Math.max(0,parseInt(Le.target.value)||0);await x.from("products").update({boost_score:B}).eq("id",A.id),Re()}})]}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[T[A.id]&&e.jsx($,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",title:"Preview",onClick:()=>window.open(`/asset/${T[A.id]}`,"_blank"),children:e.jsx(ws,{className:"h-3 w-3"})}),e.jsxs($,{size:"sm",variant:"outline",className:"flex-1",onClick:()=>Ce(A),children:[e.jsx(ua,{className:"h-3 w-3 mr-1"})," Edit"]}),e.jsx($,{size:"sm",variant:"destructive",onClick:()=>ts(A.id),children:e.jsx(As,{className:"h-3 w-3"})})]})]})]},A.id)})}),Ge>1&&e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-6",children:[e.jsx($,{variant:"outline",size:"sm",disabled:U<=1,onClick:()=>R(A=>A-1),children:"Previous"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Page ",U," of ",Ge]}),e.jsx($,{variant:"outline",size:"sm",disabled:U>=Ge,onClick:()=>R(A=>A+1),children:"Next"})]})]})}function ym(s,t){let r=s;const n=t.asset_list&&t.asset_list.length>1?"multiple assets":t.asset_name||"this asset";return r=r.replace(/\{\{asset_name\}\}/g,n),r=r.replace(/\{\{asset_id\}\}/g,t.asset_id||""),r=r.replace(/\{\{user_name\}\}/g,t.user_name||"User"),t.asset_list&&t.asset_list.length>0?r=r.replace(/\{\{asset_list\}\}/g,t.asset_list.join(", ")):r=r.replace(/\{\{asset_list\}\}/g,n),r}function Nm(s){const t={};for(const r of s){const n=r.category||"general";t[n]||(t[n]=[]),t[n].push(r)}return t}function _m(s){return{content_violations:"Content Violations",behavior:"Behavior",general:"General"}[s]||s.replace(/_/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function ao({variables:s,currentText:t,onSelect:r}){const[n,a]=i.useState([]),[l,o]=i.useState(!0),[j,b]=i.useState(null),[c,d]=i.useState(null);i.useEffect(()=>{(async()=>{const{data:m}=await x.from("warning_templates").select("*").order("category, title");a(m||[]),o(!1)})()},[]);const P=_=>{const m=ym(_.content,s);if(t.trim()&&t.trim()!==m.trim()){d({text:m,id:_.id});return}b(_.id),r(m)},k=()=>{c&&(b(c.id),r(c.text),d(null))},p=()=>{c&&(b(c.id),r(t.trim()+` 117 118`+c.text),d(null))},h=()=>{b(null),r("")};if(l)return e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground py-2",children:[e.jsx(xs,{className:"h-3 w-3 animate-spin"})," Loading templates..."]});if(n.length===0)return null;const f=Nm(n);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("label",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ws,{className:"h-3 w-3"})," Templates"]}),j&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-5 text-[10px] px-1.5 text-muted-foreground",onClick:h,children:[e.jsx(bl,{className:"h-3 w-3 mr-0.5"})," Clear"]})]}),c&&e.jsxs("div",{className:"flex items-center gap-2 bg-yellow-500/10 border border-yellow-500/30 rounded-md px-3 py-2 text-xs",children:[e.jsx("span",{className:"text-yellow-400",children:"Textarea has content."}),e.jsx($,{size:"sm",variant:"outline",className:"h-6 text-[10px] px-2",onClick:k,children:"Replace"}),e.jsx($,{size:"sm",variant:"outline",className:"h-6 text-[10px] px-2",onClick:p,children:"Append"}),e.jsx($,{size:"sm",variant:"ghost",className:"h-6 text-[10px] px-2",onClick:()=>d(null),children:"Cancel"})]}),Object.entries(f).map(([_,m])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-1",children:_m(_)}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:m.map(u=>e.jsx("button",{onClick:()=>P(u),className:`px-2.5 py-1 rounded-md text-xs font-medium border transition-all ${j===u.id?"bg-primary/20 border-primary/50 text-primary":"bg-secondary/30 border-border/50 text-foreground hover:border-primary/30 hover:bg-secondary/50"}`,children:u.title},u.id))})]},_))]})}function wm({sellerId:s,userId:t,sellerProfile:r,onRefresh:n}){var E;const{isOwner:a,hasPermission:l}=vs(),o=a||l("view_revenue"),[j,b]=i.useState(!0),[c,d]=i.useState([]),[P,k]=i.useState([]),[p,h]=i.useState(null),[f,_]=i.useState("all"),[m,u]=i.useState("all"),[g,S]=i.useState({paymentMethods:!0,financials:!0,warnings:!0,payouts:!0,logs:!1}),M=N=>S(U=>({...U,[N]:!U[N]})),y=i.useCallback(async()=>{var N,U;b(!0);try{const{data:R}=await x.from("products").select("id, name, price").eq("seller_id",s),Z=(R||[]).map(ne=>ne.id),W={};
118(R||[]).forEach(ne=>{W[ne.id]=ne.name});const[D,X,oe]=await Promise.all([Z.length>0?x.from("purchases").select("id, amount, payment_method, status, transaction_id, purchased_at, user_id, product_id, refunded_at").in("product_id",Z).order("purchased_at",{ascending:!1}).limit(500):Promise.resolve({data:[]}),x.from("payment_logs").select("*").eq("seller_id",t).order("created_at",{ascending:!1}).limit(100),x.from("seller_stats").select("total_revenue, total_sales").eq("seller_id",s).maybeSingle()]),ue=D.data||[];k(X.data||[]);const fe=ue.map(ne=>{const he=Number(ne.amount||0),Oe=r!=null&&r.fee_exempt?0:(r==null?void 0:r.creator_tier)==="trusted"||(r==null?void 0:r.creator_tier)==="partnered"?.03:.05,Ue=Math.round(he*Oe*100)/100,Xe=Math.round((he-Ue)*100)/100;return{...ne,product_name:W[ne.product_id]||"Unknown",platform_fee:Ue,seller_earnings:Xe}});d(fe);const je=ue.reduce((ne,he)=>ne+Number(he.amount||0),0),Fe=ue.filter(ne=>ne.status!=="refunded"),Ie=ue.filter(ne=>ne.status==="refunded"),G=(X.data||[]).filter(ne=>ne.status==="failure"),Q=(X.data||[]).filter(ne=>ne.critical),xe=r!=null&&r.fee_exempt?0:(r==null?void 0:r.creator_tier)==="trusted"||(r==null?void 0:r.creator_tier)==="partnered"?.03:.05,ve=Math.round(je*xe*100)/100,T=Math.round((je-ve)*100)/100;h({totalRevenue:je,totalPaidOut:T,totalFees:ve,totalSales:Fe.length,refundedCount:Ie.length,refundedAmount:Ie.reduce((ne,he)=>ne+Number(he.amount||0),0),failedPayments:G.length,criticalAlerts:Q.length,statsRevenue:((N=oe.data)==null?void 0:N.total_revenue)||0,statsSales:((U=oe.data)==null?void 0:U.total_sales)||0})}catch(R){console.error("Failed to fetch financial data:",R)}finally{b(!1)}},[s,t,r]);i.useEffect(()=>{y()},[y]);const w=(N,U)=>{navigator.clipboard.writeText(N),O.success(`${U} copied`)},F=[];!(r!=null&&r.stripe_account_id)&&!(r!=null&&r.paypal_email)&&F.push({level:"critical",message:"Seller has no payment method connected"}),r!=null&&r.onboarding_complete||F.push({level:"warning",message:"Seller onboarding is incomplete"}),r!=null&&r.payouts_enabled||F.push({level:"warning",message:"Payouts are not enabled for this seller"}),r!=null&&r.stripe_account_id&&!(r!=null&&r.payouts_enabled)&&F.push({level:"warning",message:"Stripe account connected but payouts not enabled"}),(p==null?void 0:p.failedPayments)>0&&F.push({level:"critical",message:`${p.failedPayments} failed payment(s) detected`}),(p==null?void 0:p.criticalAlerts)>0&&F.push({level:"critical",message:`${p.criticalAlerts} critical alert(s) in payment logs`}),(p==null?void 0:p.refundedCount)>0&&F.push({level:"info",message:`${p.refundedCount} refunded purchase(s) â $${(E=p==null?void 0:p.refundedAmount)==null?void 0:E.toFixed(2)}`});const J=P.filter(N=>!(f!=="all"&&N.status!==f||m!=="all"&&N.payment_method!==m));return j?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(xs,{className:"h-6 w-6 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-4",children:[F.length>0&&e.jsx(z,{className:`border ${F.some(N=>N.level==="critical")?"border-destructive/40 bg-destructive/5":"border-yellow-500/30 bg-yellow-500/5"}`,children:e.jsxs(V,{className:"p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{className:"h-4 w-4 text-destructive"}),e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"System Warnings"})]}),F.map((N,U)=>e.jsxs("div",{className:`flex items-center gap-2 text-xs rounded px-3 py-2 ${N.level==="critical"?"bg-destructive/10 text-destructive border border-destructive/20":N.level==="warning"?"bg-yellow-500/10 text-yellow-500 border border-yellow-500/20":"bg-blue-500/10 text-blue-400 border border-blue-500/20"}`,children:[N.level==="critical"?e.jsx(Ct,{className:"h-3.5 w-3.5 shrink-0"}):N.level==="warning"?e.jsx(Ps,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(Ws,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:N.message})]},U))]})}),e.jsx(z,{className:"glass border-border/30",children:e.jsxs(gt,{open:g.paymentMethods,onOpenChange:()=>M("paymentMethods"),children:[e.jsxs(ft,{className:"flex items-center justify-between w-full py-3 px-4 hover:bg-muted/30 rounded-t-lg transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"text-sm font-display font-semibold",children:"Payment Methods"})]}),e.jsx(js,{className:`h-4 w-4 text-muted-foreground transition-transform ${g.paymentMethods?"rotate-180":""}`})]}),e.jsx(jt,{children:e.jsx(V,{className:"pt-0 pb-4 px-4 space-y-3",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"bg-secondary/30 rounded-lg p-4 border border-border/30 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"PayPal"}
118),r!=null&&r.paypal_email?e.jsxs(Y,{className:"text-[10px] bg-emerald-500/20 text-emerald-400 border-emerald-500/30 gap-1",children:[e.jsx(At,{className:"h-2.5 w-2.5"})," Connected"]}):e.jsxs(Y,{variant:"destructive",className:"text-[10px] gap-1",children:[e.jsx(Ct,{className:"h-2.5 w-2.5"})," Not Connected"]})]}),(r==null?void 0:r.paypal_email)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Email"}),e.jsx("p",{className:"text-sm font-mono",children:r.paypal_email})]}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:()=>w(r.paypal_email,"PayPal email"),children:e.jsx(Ra,{className:"h-3 w-3"})})]}),r.paypal_merchant_id&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Merchant ID"}),e.jsx("p",{className:"text-xs font-mono text-muted-foreground",children:r.paypal_merchant_id})]}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:()=>w(r.paypal_merchant_id,"Merchant ID"),children:e.jsx(Ra,{className:"h-3 w-3"})})]})]})]}),e.jsxs("div",{className:"bg-secondary/30 rounded-lg p-4 border border-border/30 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Stripe"}),r!=null&&r.stripe_account_id?r!=null&&r.payouts_enabled?e.jsxs(Y,{className:"text-[10px] bg-emerald-500/20 text-emerald-400 border-emerald-500/30 gap-1",children:[e.jsx(At,{className:"h-2.5 w-2.5"})," Fully Active"]}):e.jsxs(Y,{className:"text-[10px] bg-yellow-500/20 text-yellow-400 border-yellow-500/30 gap-1",children:[e.jsx(Ps,{className:"h-2.5 w-2.5"})," Incomplete Setup"]}):e.jsxs(Y,{variant:"destructive",className:"text-[10px] gap-1",children:[e.jsx(Ct,{className:"h-2.5 w-2.5"})," Not Connected"]})]}),(r==null?void 0:r.stripe_account_id)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Account ID"}),e.jsx("p",{className:"text-xs font-mono text-muted-foreground",children:r.stripe_account_id})]}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 px-2",onClick:()=>w(r.stripe_account_id,"Stripe Account ID"),children:e.jsx(Ra,{className:"h-3 w-3"})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-muted-foreground",children:"Payouts:"}),r.payouts_enabled?e.jsxs("span",{className:"text-emerald-400 flex items-center gap-0.5",children:[e.jsx(At,{className:"h-3 w-3"})," Enabled"]}):e.jsxs("span",{className:"text-destructive flex items-center gap-0.5",children:[e.jsx(Ct,{className:"h-3 w-3"})," Disabled"]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-muted-foreground",children:"Onboarding:"}),r.onboarding_complete?e.jsxs("span",{className:"text-emerald-400 flex items-center gap-0.5",children:[e.jsx(At,{className:"h-3 w-3"})," Complete"]}):e.jsxs("span",{className:"text-yellow-400 flex items-center gap-0.5",children:[e.jsx(Ps,{className:"h-3 w-3"})," Incomplete"]})]})]})]})]})]})})})]})}),o&&p&&e.jsx(z,{className:"glass border-border/30",children:e.jsxs(gt,{open:g.financials,onOpenChange:()=>M("financials"),children:[e.jsxs(ft,{className:"flex items-center justify-between w-full py-3 px-4 hover:bg-muted/30 rounded-t-lg transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rt,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"text-sm font-display font-semibold",children:"Financial Summary"})]}),e.jsx(js,{className:`h-4 w-4 text-muted-foreground transition-transform ${g.financials?"rotate-180":""}`})]}),e.jsx(jt,{children:e.jsx(V,{className:"pt-0 pb-4 px-4",children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 ga
118p-3",children:[{label:"Total Revenue",value:`$${p.totalRevenue.toFixed(2)}`,color:"text-emerald-400"},{label:"Paid to Seller",value:`$${p.totalPaidOut.toFixed(2)}`,color:"text-blue-400"},{label:"Platform Fees",value:`$${p.totalFees.toFixed(2)}`,color:"text-violet-400"},{label:"Failed Payments",value:String(p.failedPayments),color:p.failedPayments>0?"text-destructive":"text-muted-foreground"},{label:"Refunds",value:`$${p.refundedAmount.toFixed(2)}`,color:p.refundedCount>0?"text-orange-400":"text-muted-foreground"}].map(N=>e.jsxs("div",{className:"bg-secondary/30 rounded-lg p-3 border border-border/30",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-1",children:N.label}),e.jsx("p",{className:`text-lg font-display font-bold ${N.color}`,children:N.value})]},N.label))})})})]})}),o&&e.jsx(z,{className:"glass border-border/30",children:e.jsxs(gt,{open:g.payouts,onOpenChange:()=>M("payouts"),children:[e.jsxs(ft,{className:"flex items-center justify-between w-full py-3 px-4 hover:bg-muted/30 rounded-t-lg transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tl,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"text-sm font-display font-semibold",children:"Payout History"}),e.jsx(Y,{variant:"secondary",className:"text-[10px] px-1.5",children:c.length})]}),e.jsx(js,{className:`h-4 w-4 text-muted-foreground transition-transform ${g.payouts?"rotate-180":""}`})]}),e.jsx(jt,{children:e.jsx(V,{className:"pt-0 pb-4 px-4",children:c.length>0?e.jsxs("div",{className:"space-y-1 max-h-[400px] overflow-y-auto",children:[e.jsxs("div",{className:"grid grid-cols-7 gap-2 text-[10px] text-muted-foreground uppercase tracking-wider px-3 py-1.5 sticky top-0 bg-card/90 backdrop-blur-sm z-10",children:[e.jsx("span",{children:"Date"}),e.jsx("span",{children:"Method"}),e.jsx("span",{children:"Status"}),e.jsx("span",{children:"Amount"}),e.jsx("span",{children:"Fee"}),e.jsx("span",{children:"Net"}),e.jsx("span",{children:"Product"})]}),c.map(N=>e.jsxs("div",{className:"grid grid-cols-7 gap-2 text-xs bg-secondary/30 rounded px-3 py-2 items-center",children:[e.jsx("span",{className:"text-muted-foreground",children:new Date(N.purchased_at).toLocaleDateString()}),e.jsx(Y,{variant:"outline",className:`text-[9px] w-fit ${N.payment_method==="str
118ipe"?"text-violet-400 border-violet-500/30":N.payment_method==="paypal"?"text-blue-400 border-blue-500/30":"text-muted-foreground"}`,children:N.payment_method||"unknown"}),e.jsx(Y,{className:`text-[9px] w-fit ${N.status==="refunded"?"bg-destructive/20 text-destructive border-destructive/30":"bg-emerald-500/20 text-emerald-400 border-emerald-500/30"}`,children:N.status==="refunded"?"refunded":"completed"}),e.jsxs("span",{className:"font-mono",children:["$",Number(N.amount||0).toFixed(2)]}),e.jsxs("span",{className:"font-mono text-muted-foreground",children:["$",N.platform_fee.toFixed(2)]}),e.jsxs("span",{className:"font-mono text-emerald-400",children:["$",N.seller_earnings.toFixed(2)]}),e.jsx("span",{className:"truncate",title:N.product_name,children:N.product_name})]},N.id))]}):e.jsx("p",{className:"text-xs text-muted-foreground py-3",children:"No payout history"})})})]})}),o&&e.jsx(z,{className:"glass border-border/30",children:e.jsxs(gt,{open:g.logs,onOpenChange:()=>M("logs"),children:[e.jsxs(ft,{className:"flex items-center justify-between w-full py-3 px-4 hover:bg-muted/30 rounded-t-lg transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ws,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"text-sm font-display font-semibold",children:"Payment Logs"}),e.jsx(Y,{variant:"secondary",className:"text-[10px] px-1.5",children:P.length}),P.some(N=>N.critical)&&e.jsxs(Y,{variant:"destructive",className:"text-[10px] px-1.5 gap-0.5",children:[e.jsx(Ps,{className:"h-2.5 w-2.5"}),P.filter(N=>N.critical).length," critical"]})]}),e.jsx(js,{className:`h-4 w-4 text-muted-foreground transition-transform ${g.logs?"rotate-180":""}`})]}),e.jsx(jt,{children:e.jsxs(V,{className:"pt-0 pb-4 px-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Pe,{value:f,onValueChange:_,children:[e.jsx(Te,{className:"w-32 h-8 text-xs bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Status"}),e.jsx(L,{value:"success",children:"Success"}),e.jsx(L,{value:"failure",children:"Failure"}),e.jsx(L,{value:"warning",children:"Warning"})]})]}),e.jsxs(Pe,{value:m,onValueChange:u,children:[e.jsx(Te,{className:"w-32 h-8 text-xs bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Methods"}),e.jsx(L,{value:"stripe",children:"Stripe"}),e.jsx(L,{value:"paypal",children:"PayPal"})]})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 gap-1 text-xs",onClick:y,children:[e.jsx(St,{className:"h-3 w-3"})," Refresh"]})]}),J.length>0?e.jsx("div",{className:"space-y-1 max-h-[350px] overflow-y-auto",children:J.map(N=>e.jsxs("div",{className:`text-xs rounded px-3 py-2.5 border space-y-1 ${N.critical?"bg-destructive/5 border-destructive/30":N.status==="failure"?"bg-yellow-500/5 border-yellow-500/20":"bg-secondary/30 border-border/20"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[N.critical&&e.jsx(Ps,{className:"h-3 w-3 text-destructive"}),e.jsx(Y,{variant:"outline",className:"text-[9px]",children:N.event_type}),e.jsx(Y,{className:`text-[9px] ${N.status==="success"?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":N.status==="failure"?"bg-destructive/20 text-destructive border-destructive/30":"bg-yellow-500/20 text-yellow-400 border-yellow-500/30"}`,children:N.status}),N.payment_method&&e.jsx(Y,{variant:"outline",className:`text-[9px] ${N.payment_method==="str
118ipe"?"text-violet-400 border-violet-500/30":"text-blue-400 border-blue-500/30"}`,children:N.payment_method})]}),e.jsx("span",{className:"text-muted-foreground text-[10px]",children:new Date(N.created_at).toLocaleString()})]}),N.amount_cents!=null&&e.jsxs("div",{className:"flex items-center gap-3 text-[10px]",children:[e.jsxs("span",{children:["Amount: ",e.jsxs("span",{className:"font-mono",children:["$",(N.amount_cents/100).toFixed(2)]})]}),N.platform_fee_cents!=null&&e.jsxs("span",{children:["Fee: ",e.jsxs("span",{className:"font-mono",children:["$",(N.platform_fee_cents/100).toFixed(2)]})]}),N.seller_amount_cents!=null&&e.jsxs("span",{children:["Seller: ",e.jsxs("span",{className:"font-mono text-emerald-400",children:["$",(N.seller_amount_cents/100).toFixed(2)]})]})]}),N.error_message&&e.jsxs("p",{className:"text-destructive text-[10px]",children:["Error: ",N.error_message]}),(N.stripe_session_id||N.stripe_payment_intent_id||N.paypal_order_id)&&e.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-muted-foreground",children:[N.stripe_session_id&&e.jsxs("span",{className:"font-mono",children:["Session: ",N.stripe_session_id.slice(0,20),"â¦"]}),N.stripe_payment_intent_id&&e.jsxs("span",{className:"font-mono",children:["PI: ",N.stripe_payment_intent_id.slice(0,20),"â¦"]}),N.paypal_order_id&&e.jsxs("span",{className:"font-mono",children:["PayPal: ",N.paypal_order_id]})]})]},N.id))}):e.jsx("p",{className:"text-xs text-muted-foreground py-3",children:"No payment logs for this seller"})]})})]})})]})}const cl={approved:{label:"Approved",className:"bg-green-500/20 text-green-400 border-green-500/30"},pending:{label:"Pending",className:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30"},rejected:{label:"Rejected",className:"bg-red-500/20 text-red-400 border-red-500/30"},suspended:{label:"Suspended",className:"bg-orange-500/20 text-orange-400 border-orange-500/30"},draft:{label:"Draft",className:"bg-muted text-muted-foreground border-border"}};function Sm({userId:s,selectedAssets:t,onSelectionChange:r}){const[n,a]=i.useState(""),[l,o]=i.useState([]),[j,b]=i.useState(!1),[c,d]=i.useState(!1),P=i.useRef(null),k=i.useRef(),p=i.useCallback(async m=>{if(!m.trim()){o([]);return}b(!0);try{const{data:u}=await x.from("seller_profiles").select("id").eq("user_id",s).maybeSingle();if(!u){o([]),b(!1);return}const{data:g}=await x.from("products").select("id, name, status, image_url").eq("seller_id",u.id).or(`name.ilike.%${m}%,id.eq.${m.match(/^[0-9a-f-]{36}$/)?m:"00000000-0000-0000-0000-000000000000"}`).order("created_at",{ascending:!1}).limit(10),S=(g||[]).filter(M=>!t.some(y=>y.id===M.id));o(S)}catch{o([])}finally{b(!1)}},[s,t]);i.useEffect(()=>{if(clearTimeout(k.current),!n.trim()){o([]);return}return k.current=setTimeout(()=>p(n),300),()=>clearTimeout(k.current)},[n,p]),i.useEffect(()=>{const m=u=>{P.current&&!P.current.contains(u.target)&&d(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[]);const h=m=>{r([...t,m]),a(""),o([]),d(!1)},f=m=>{r(t.filter(u=>u.id!==m))},_=m=>cl[m]||cl.draft;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Pa,{className:"h-3 w-3"})," Related Assets (Optional)"]}),t.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.map(m=>e.jsxs("div",{className:"flex items-center gap-1.5 bg-secondary/40 border border-border/50 rounded-md px-2 py-1 text-xs",children:[e.jsx("span",{className:"font-medium truncate max-w-[160px]",children:m.name}),e.jsx(Y,{variant:"outline",className:`text-[9px] px-1.5 py-0 h-4 ${_(m.status).className}`,children:_(m.status).label}),e.jsx("button",{onClick:()=>f(m.id),className:"text-muted-foreground hover:text-foreground ml-0.5",children:e.jsx(bl,{className:"h-3 w-3"})})]},m.id))}),e.jsxs("div",{ref:P,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ke,{placeholder:"Search user's assets by name or ID...",value:n,onChange:m=>{a(m.target.value),d(!0)},onFocus:()=>n.trim()&&d(!0),className:"bg-background/50 pl-8 h-8 text-xs"}),j&&e.jsx(xs,{className:"absolute right-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 animate-spin text-muted-foreground"})]}),c&&l.length>0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-popover border border-border rounded-md shadow-lg max-h-48 overflow-y-auto",children:l.map(m=>e.jsxs("button",{onClick:()=>h(m),className:"w-full flex items-center gap-2 px-3 py-2 text-xs hover:bg-accent/50 transition-colors text-left",children:[m.image_url&&e.jsx("img",{src:m.image_url,alt:"",className:"h-6 w-6 rounded object-cover flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate flex-1",children:m.name}),e.jsx(Y,{variant:"outline",className:`text-[9px] px-1.5 py-0 h-4 flex-shrink-0 ${_(m.status).className}`,children:_(m.status).label})]},m.id))}),c&&n.trim()&&!j&&l.length===0&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-popover border border-border rounded-md shadow-lg px-3 py-2 text-xs text-muted-foreground",children:"No assets found"})]})]})}function _t(s){if(!s)return"Never";const t=Date.now(),r=typeof s=="string"?new Date(s).getTime():s.getTime(),n=t-r,a=Math.floor(n/6e4);if(a<1)return"Just now";if(a<60)return`${a}m ago`;const l=Math.floor(a/60);if(l<24)return`${l}h ago`;const o=Math.floor(l/24);return o<30?`${o}d ago`:new Date(s).toLocaleDateString()}async function Ns(s,t,r,n,a){try{await x.from("activity_logs").insert({user_id:s,action:t,target_type:r||null,target_id:n||null,details:a||{}})}catch{}}function dl(s){return s?s.includes("mobile")||s.includes("phone")?e.jsx(ui,{className:"h-3.5 w-3.5"}):s.includes("tablet")?e.jsx(xi,{className:"h-3.5 w-3.5"}):e.jsx(qr,{className:"h-3.5 w-3.5"}):e.jsx(qr,{className:"h-3.5 w-3.5"})}function km({user:s,onBack:t,onRefresh:r,allPermissions:n}){var wr,Sr,kr,Ys;const{user:a,isOwner:l,hasPermission:o}=vs(),j=(wr=s.roles)==null?void 0:wr.includes("admin"),b=(Sr=s.roles)==null?void 0:Sr.includes("owner"),[c,d]=i.useState([]),[P,k]=i.useState([]),[p,h]=i.useState([]),[f,_]=i.useState([]),[m,u]=i.useState([]),[g,S]=i.useState(null),[M,y]=i.useState(""),[w,F]=i.useState(!1),[J,E]=i.useState(null),[N,U]=i.useState([]),[R,Z]=i.useState([]),[W,D]=i.useState(null),[X,oe]=i.useState(null),[ue,fe]=i.useState(null),[je,Fe]=i.useState("25"),[Ie,G]=i.useState(!1),[Q,xe]=i.useState([]),[ve,T]=i.useState(!1),[ne,he]=i.useState(!1),[Oe,Ue]=i.useState(""),[Xe,Be]=i.useState("low"),[ae,de]=i.useState(""),[Re,pe]=i.useState(!1),[Ce,qe]=i.useState([]),[Ze,ts]=i.useState([]),[We,ns]=i.useState([]),[us,Ge]=i.useState(!1),[He,A]=i.useState(""),[me,ze]=i.useState("24h"),[Le,B]=i.useState(""),[ee,te]=i.useState(!1),[se,be]=i.useState(!1),[Se,_e]=i.useState(!1),[Ke,rs]=i.useState(!1),[H,
118ce]=i.useState(""),[le,q]=i.useState(!1),[K,re]=i.useState(null),[ge,ye]=i.useState({profile:!0,seller:!0,activity:!1,purchases:!0,wishlists:!1,referrals:!1,flags:!1,notes:!0,loginHistory:!1,adWallet:!0,trustedDevices:!1,moderation:!1}),Ae=v=>ye(ie=>({...ie,[v]:!ie[v]})),[Ee,Je]=i.useState(!1),[Ve,es]=i.useState(""),[ds,ot]=i.useState(!1),[Mt,un]=i.useState("violation"),[xn,ur]=i.useState(!1),[xr,pn]=i.useState([]),[Ks,pr]=i.useState(""),[Ua,hr]=i.useState(""),[gr,fr]=i.useState(!1),[hn,Ia]=i.useState(!1),[za,jr]=i.useState(""),[vr,ct]=i.useState(""),[dt,gn]=i.useState("info"),Js=i.useCallback(async()=>{const[{data:v},{data:ie},{data:we},{data:is},{data:hs},{data:ut},{data:Zs},{data:Ts},{data:xt},{data:Gt}]=await Promise.all([x.from("wishlists").select("id, created_at, product:products(id, name, price, category, image_url, slug)").eq("user_id",s.id).order("created_at",{ascending:!1}),x.from("login_history").select("*").eq("user_id",s.id).order("logged_in_at",{ascending:!1}).limit(10),x.from("activity_logs").select("*").eq("user_id",s.id).order("created_at",{ascending:!1}).limit(15),x.from("custom_roles").select("*").order("name"),x.from("user_custom_roles").select("role_id").eq("user_id",s.id),x.from("profiles").select("*, last_active_at").eq("user_id",s.id).maybeSingle(),x.from("referrals").select("*").eq("referrer_id",s.id),x.from("disputes").select("id, reason, status, created_at").eq("buyer_id",s.id).order("created_at",{ascending:!1}).limit(5),x.from("reports").select("id, reason, status, reported_type, created_at").or(`reporter_id.eq.${s.id},reported_id.eq.${s.id}`).order("created_at",{ascending:!1}).limit(5),x.from("creator_verifications").select("*").eq("user_id",s.id).order("created_at",{ascending:!1}).limit(1).maybeSingle()]),{data:qa}=await x.from("ad_wallets").select("balance, total_purchased").eq("creator_id",s.id).maybeSingle();fe(qa),h(v||[]),_(ie||[]),u(we||[]),d(is||[]),k((hs||[]).map(Xs=>Xs.role_id)),oe(ut);const{data:Wa}=await x.from("profile_admin_notes").select("notes").eq("user_id",s.id).maybeSingle();y((Wa==null?void 0:Wa.notes)||""),D(Gt),U(Ts||[]),Z(xt||[]),yt();const{data:Ga}=await x.from("profiles").select("is_suspended, suspension_expires_at, suspension_reason, is_shadow_restricted, is_frozen").eq("user_id",s.id).maybeSingle();re(Ga);const Ht=Zs||[];if(E({total:Ht.length,qualified:Ht.filter(Xs=>Xs.status==="qualified").length,pending:Ht.filter(Xs=>Xs.status==="pending").length}),s.seller_profile){const Xs=s.seller_profile.id,{data:An}=await x.from("products").select("id").eq("seller_id",Xs),et=(An??[]).map(bs=>bs.id),[{data:Rn},{data:Kt},{data:Ha},{data:st},{data:Pn}]=await Promise.all([x.from("products").select("id, name, status, price, category").eq("seller_id",Xs).limit(5e3),x.from("purchases").select("id, amount, purchased_at, product_id").in("product_id",et).limit(5e3),x.from("product_views").select("id, product_id").in("product_id",et).limit(5e3),x.from("reviews").select("id, rating, product_id").in("product_id",et).limit(5e3),x.from("wishlists").select("id").in("product_id",et).limit(5e3)]),ja=Rn||[],Jt=Kt||[],Qt=new Date,Is=new Date(Qt.getFullYear(),Qt.getMonth()-1,Qt.getDate()),Yt=Jt.filter(bs=>new Date(bs.purchased_at)>=Is);S({totalProducts:ja.length,activeListings:ja.filter(bs=>bs.status==="approved").length,pendingProducts:ja.filter(bs=>bs.status==="pending").length,totalSales:Jt.length,totalRevenue:Jt.reduce((bs,tt)=>bs+Number(tt.amount||0),0),monthSales:Yt.length,monthRevenue:Yt.reduce((bs,tt)=>bs+Number(tt.amount||0),0),totalViews:(Ha||[]).length,totalWishlists:(Pn||[]).length,avgRating:(st||[]).length>0?(st||[]).reduce((bs,tt)=>bs+tt.rating,0)/(st||[]).length:0,reviewCount:(st||[]).length,conversionRate:(Ha||[]).length>0?Jt.length/(Ha||[]).length*100:0})}},[s.id,s.seller_profile]);i.useEffect(()=>{Js()},[Js]);const Va=async()=>{if(Ve.length<6){O.error("Min 6 characters");return}const{data:v,error:ie}=await x.functions.invoke("admin-users",{body:{action:"reset_password",userId:s.id,password:Ve}});ie||v!=null&&v.error?O.error((v==null?void 0:v.error)||"Reset failed"):(O.success("Password reset!"),Ns(a.id,"reset_password","user",s.id,{email:s.email})),Je(!1),es("")},ha=async()=>{const{data:v,error:ie}=await x.functions.invoke("admin-users",{body:{action:"verify_email",userId:s.id}});ie||v!=null&&v.error?O.error((v==null?void 0:v.error)||"Verification failed"):(O.success("Email verified!"),Ns(a.id,"verify_email","user",s.id,{email:s.email}
118),r())},br=async()=>{const v=s.banned_at?"unban_user":"ban_user",{data:ie,error:we}=await x.functions.invoke("admin-users",{body:{action:v,userId:s.id}});we||ie!=null&&ie.error?O.error((ie==null?void 0:ie.error)||"Failed"):(O.success(s.banned_at?"User unbanned":"User banned"),Ns(a.id,v,"user",s.id,{target_name:s.display_name||s.email,reason:Mt}),r()),ot(!1)},ga=async()=>{if(!Oe.trim()){O.error("Reason is required");return}pe(!0);try{const v={user_id:s.id,admin_id:a==null?void 0:a.id,reason:Oe.trim(),severity:Xe,related_asset_ids:Ce.length>0?Ce.map(we=>we.id):[]};ae&&(v.expires_at=new Date(ae).toISOString());const{error:ie}=await x.from("user_warnings").insert(v);if(ie)throw ie;await x.from("moderation_logs").insert({user_id:s.id,admin_id:a==null?void 0:a.id,action_type:"warning",reason:Oe.trim(),metadata:{severity:Xe,expires_at:ae||null,related_asset_ids:Ce.map(we=>we.id),related_asset_names:Ce.map(we=>we.name)}}),Ns(a.id,"issue_warning","user",s.id,{target_name:s.display_name||s.email,severity:Xe,reason:Oe.trim(),related_assets:Ce.map(we=>we.name)}),O.success("Warning issued successfully"),he(!1),Ue(""),Be("low"),de(""),qe([]),yt()}catch(v){O.error(v.message||"Failed to issue warning")}finally{pe(!1)}},yt=async()=>{const[{data:v},{data:ie}]=await Promise.all([x.from("user_warnings").select("*").eq("user_id",s.id).order("created_at",{ascending:!1}),x.from("moderation_logs").select("*").eq("user_id",s.id).order("created_at",{ascending:!1}).limit(20)]);ts(v||[]),ns(ie||[])},Wt=async()=>{if(!He.trim()){O.error("Reason required");return}te(!0);try{let v=null;if(me==="custom"&&Le)v=new Date(Le).toISOString();else if(me!=="indefinite"){const ie=me==="1h"?1:me==="6h"?6:me==="24h"?24:me==="3d"?72:me==="7d"?168:me==="30d"?720:24;v=new Date(Date.now()+ie*36e5).toISOString()}await x.from("profiles").update({is_suspended:!0,suspension_expires_at:v,suspension_reason:He.trim()}).eq("user_id",s.id),await x.from("moderation_logs").insert({user_id:s.id,admin_id:a==null?void 0:a.id,action_type:"suspension",reason:He.trim(),metadata:{duration:me,expires_at:v}}),Ns(a.id,"suspend_user","user",s.id,{target_name:s.display_name||s.email,duration:me,reason:He==null?void 0:He.trim()}),O.success("User suspended"),x.rpc("get_user_email",{target_user_id:s.id}).then(({data:ie})=>{ie&&x.functions.invoke("send-transactional-email",{body:{templateName:"account-suspended",recipientEmail:ie,idempotencyKey:`suspend-${s.id}-${Date.now()}`,templateData:{userName:s.display_name||void 0,reason:He.trim(),expiresAt:v?new Date(v).toLocaleString():void 0,isPermanent:!v}}})}),Ge(!1),A(""),Js()}catch(v){O.error(v.message)}finally{te(!1)}},Ba=async()=>{await x.from("profiles").update({is_suspended:!1,suspension_expires_at:null,suspension_reason:null}).eq("user_id",s.id),await x.from("moderation_logs").insert({user_id:s.id,admin_id:a==null?void 0:a.id,action_type:"unsuspension",reason:"Manually unsuspended by admin"}),Ns(a.id,"unsuspend_user","user",s.id,{target_name:s.display_name||s.email}),O.success("User unsuspended"),Js()},Us=async()=>{be(!0);const v=!(K!=null&&K.is_shadow_restricted);await x.from("profiles").update({is_shadow_restricted:v}).eq("user_id",s.id),await x.from("moderation_logs").insert({user_id:s.id,admin_id:a==null?void 0:a.id,action_type:v?"shadow_restrict":"unshadow_restrict",reason:v?"Shadow restricted by admin":"Shadow restriction removed"}),Ns(a.id,v?"shadow_restrict":"unshadow_restrict","user",s.id,{target_name:s.display_name||s.email}),O.success(v?"User shadow restricted":"Shadow restriction removed"),Js(),be(!1)},Nt=async()=>{_e(!0);const v=!(K!=null&&K.is_frozen);await x.from("profiles").update({is_frozen:v}).eq("user_id",s.id),await x.from("moderation_logs").insert({user_id:s.id,admin_id:a==null?void 0:a.id,action_type:v?"freeze":"unfreeze",reason:v?"Account frozen by admin":"Account unfrozen"}),Ns(a.id,v?"freeze_account":"unfreeze_account","user",s.id,{target_name:s.display_name||s.email}),O.success(v?"Account frozen":"Account unfrozen"),Js(),_e(!1)},Qs=async()=>{var v;q(!0);try{const ie=(v=s.seller_profile)==null?void 0:v.id;if(!ie){O.error("User is not a seller");return}const{data:we}=await x.from("products").select("id").eq("seller_id",ie);
118if(!we||we.length===0){O.error("No assets found");return}const is=we.map(hs=>hs.id);await x.from("products").update({is_suspended:!0,suspended_at:new Date().toISOString(),suspension_reason:H||"Bulk suspended by admin"}).in("id",is),await x.from("moderation_logs").insert({user_id:s.id,admin_id:a==null?void 0:a.id,action_type:"asset_suspend",reason:H||"Bulk suspended by admin",metadata:{bulk:!0,affected_asset_ids:is,count:is.length}}),Ns(a.id,"suspend_all_assets","user",s.id,{count:is.length}),O.success(`${is.length} assets suspended`),rs(!1),ce("")}catch(ie){O.error(ie.message)}finally{q(!1)}},fn=async()=>{if(!confirm("Delete this user permanently? This cannot be undone."))return;const{data:v,error:ie}=await x.functions.invoke("admin-users",{body:{action:"delete",userId:s.id}});ie||v!=null&&v.error?O.error((v==null?void 0:v.error)||"Delete failed"):(O.success("User deleted"),Ns(a.id,"delete_user","user",s.id,{target_name:s.display_name||s.email}),t())},yr=async()=>{const v=j?"remove_admin":"set_admin",{data:ie,error:we}=await x.functions.invoke("admin-users",{body:{action:v,userId:s.id}});we||ie!=null&&ie.error?O.error((ie==null?void 0:ie.error)||"Failed"):(O.success(j?"Admin removed":"Promoted to admin"),Ns(a.id,v,"user",s.id),r())},jn=async v=>{const{data:ie,error:we}=await x.functions.invoke("admin-users",{body:{action:"toggle_permission",userId:s.id,permission:v}});we||ie!=null&&ie.error?O.error((ie==null?void 0:ie.error)||"Failed"):(Ns(a.id,"toggle_permission","user",s.id,{permission:v}),r())},vn=async v=>{const ie=P.includes(v);ie?(await x.from("user_custom_roles").delete().eq("user_id",s.id).eq("role_id",v),Ns(a.id,"remove_role","user",s.id,{role_id:v})):(await x.from("user_custom_roles").insert({user_id:s.id,role_id:v,assigned_by:a==null?void 0:a.id}),Ns(a.id,"assign_role","user",s.id,{role_id:v})),k(ie?P.filter(we=>we!==v):[...P,v])},bn=async()=>{if(!s.seller_profile)return;const{error:v}=await x.from("seller_profiles").update({fee_exempt:!s.seller_profile.fee_exempt}).eq("id",s.seller_profile.id);v?O.error(v.message):(O.success(s.seller_profile.fee_exempt?"Fees re-enabled":"Now fee-exempt"),r())},yn=async()=>{if(!X)return;F(!0);const{error:v}=await x.from("profile_admin_notes").upsert({user_id:s.id,notes:M,updated_by:a==null?void 0:a.id},{onConflict:"user_id"});v?O.error(v.message):O.success("Notes saved"),F(!1)},fa=async(v,ie)=>{if(!confirm(`Remove "${ie}" from this user?`))return;const{data:we,error:is}=await x.functions.invoke("admin-users",{body:{action:"remove_purchase",userId:s.id,purchaseId:v}});is||we!=null&&we.error?O.error((we==null?void 0:we.error)||"Failed"):(O.success("Purchase removed"),Ns(a.id,"remove_purchase","user",s.id,{purchase_id:v,product_name:ie}),r())},Nn=async()=>{const{fetchAllRows:v}=await as(async()=>{const{fetchAllRows:we}=await import("./supabase-fetch-all-BNqwZxdA.js");return{fetchAllRows:we}},[]),ie=await v(()=>x.from("products").select("id, name, category, price").order("name"));pn(ie||[])},Nr=async()=>{if(!Ks){O.error("Select a product");return}fr(!0);const{data:v,error:ie}=await x.functions.invoke("admin-users",{body:{action:"grant_product",userId:s.id,productId:Ks}});if(ie||v!=null&&v.error)O.error((v==null?void 0:v.error)||"Failed");else{const we=xr.find(is=>is.id===Ks);O.success("Product granted!"),Ns(a.id,"grant_product","user",s.id,{target_name:s.display_name||s.email,product_id:Ks,product_name:(we==null?void 0:we.name)||"Unknown"}),r()}fr(!1),ur(!1),pr("")},_n=async()=>{T(!0);const{data:v}=await x.functions.invoke("login-otp",{body:{action:"admin_list_devices",target_user_id:s.id}});xe((v==null?void 0:v.devices)||[]),T(!1)},mt=async v=>{const{data:ie,error:we}=await x.functions.invoke("login-otp",{body:{action:"admin_revoke_device",device_id:v}});we||!(ie!=null&&ie.success)?O.error("Failed to revoke device"):(O.success("Device revoked"),xe(is=>is.filter(hs=>hs.id!==v)))},_r=async()=>{if(!confirm("Revoke all trusted devices for this user?"))return;const{data:v,error:ie}=await x.functions.invoke("login-otp",{body:{action:"admin_revoke_all_devices",target_user_id:s.id}});ie||!(v!=null&&v.success)?O.error("Failed"):(O.success("All devices revoked"),xe([]))};i.useEffect(()=>{ge.trustedDevices&&Q.length===0&&!ve&&_n()},[ge.trustedDevices]);const wn=async()=>
118{if(!za.trim()){O.error("Title required");return}const{error:v}=await x.from("notifications").insert({user_id:s.id,type:dt,title:za,message:vr||null});v?O.error(v.message):O.success("Notification sent!"),Ia(!1),jr(""),ct("")},Sn=()=>{const v=[];return s.banned_at?v.push(e.jsxs(Y,{variant:"destructive",className:"text-xs gap-1",children:[e.jsx(Za,{className:"h-3 w-3"})," Banned"]},"banned")):K!=null&&K.is_suspended?v.push(e.jsxs(Y,{variant:"destructive",className:"text-xs gap-1",children:[e.jsx(Pr,{className:"h-3 w-3"})," Suspended"]},"suspended")):v.push(e.jsxs(Y,{className:"text-xs bg-emerald-500/20 text-emerald-400 border-emerald-500/30 gap-1",children:[e.jsx(At,{className:"h-3 w-3"})," Active"]},"active")),K!=null&&K.is_shadow_restricted&&v.push(e.jsxs(Y,{className:"text-xs bg-orange-500/20 text-orange-400 border-orange-500/30 gap-1",children:[e.jsx(Vi,{className:"h-3 w-3"})," Shadow Restricted"]},"shadow")),K!=null&&K.is_frozen&&v.push(e.jsxs(Y,{className:"text-xs bg-blue-500/20 text-blue-400 border-blue-500/30 gap-1",children:[e.jsx(It,{className:"h-3 w-3"})," Frozen"]},"frozen")),s.email_confirmed_at||v.push(e.jsxs(Y,{className:"text-xs bg-yellow-500/20 text-yellow-400 border-yellow-500/30 gap-1",children:[e.jsx(zi,{className:"h-3 w-3"})," Email Unverified"]},"unverified")),s.seller_profile&&v.push(e.jsxs(Y,{className:"text-xs bg-blue-500/20 text-blue-400 border-blue-500/30 gap-1",children:[e.jsx(rt,{className:"h-3 w-3"})," Seller"]},"seller")),(W==null?void 0:W.status)==="verified"&&v.push(e.jsxs(Y,{className:"text-xs bg-primary/20 text-primary border-primary/30 gap-1",children:[e.jsx(Ll,{className:"h-3 w-3"})," Verified Creator"]},"verified")),v},kn=v=>v.includes("owner")?e.jsx(Y,{className:"bg-primary/20 text-primary border-primary/30 text-xs",children:"Owner"}):v.includes("admin")?e.jsx(Y,{variant:"secondary",className:"text-xs",children:"Staff"}):e.jsx(Y,{variant:"outline",className:"text-xs",children:"User"}),Cn=(s.purchases||[]).reduce((v,ie)=>{var we;return v+Number(ie.amount||((we=ie.product)==null?void 0:we.price)||0)},0);return e.jsxs("div",{className:"space-y-6 max-w-5xl",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:t,className:"gap-1",children:[e.jsx(Xr,{className:"h-4 w-4"})," Back to Users"]}),e.jsx(z,{className:"glass border-border/50",children:e.jsx(V,{className:"p-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs(Bs,{className:"h-16 w-16 ring-2 ring-border",children:[s.avatar_url&&e.jsx(it,{src:s.avatar_url,alt:s.display_name||s.email}),e.jsx(qs,{className:"bg-primary/10 text-primary font-display font-bold text-2xl",children:(s.display_name||s.email||"?")[0].toUpperCase()})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(da,{to:`/user/${encodeURIComponent(s.display_name||s.email||"")}`,className:"text-xl font-display font-bold hover:text-primary transition-colors",children:s.display_name||s.email}),kn(s.roles)]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s.email}),e.jsx("div",{className:"flex items-center gap-1.5 flex-wrap",children:Sn()}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 mt-2 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Ta,{className:"h-3 w-3"}),e.jsxs("span",{children:["Joined ",new Date(s.created_at).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex items-center gap-1 font-medium text-foreground",children:[e.jsx(Dt,{className:"h-3 w-3 text-emerald-400"}),e.jsxs("span",{children:["Last login: ",e.jsx("span",{className:"text-primary",children:_t(s.last_sign_in_at)})]})]}),(X==null?void 0:X.last_active_at)&&e.jsxs("div",{className:"flex items-center gap-1 font-medium text-foreground",children:[e.jsx(ws,{className:"h-3 w-3 text-blue-400"}),e.jsxs("span",{children:["Last seen: ",e.jsx("span",{className:"text-primary",children:_t(X.last_active_at)})]})]})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-3 shrink-0",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[(l||o("send_notifications"))&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>Ia(!0),className:"gap-1",children:[e.jsx(qt,{className:"h-3 w-3"})," Notify"]}),(l||o("grant_products"))&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{ur(!0),Nn()},className:"gap-1",children:[e.jsx(zn,{className:"h-3 w-3"})," Grant"]}),!s.email_confirmed_at&&e.jsxs($,{size:"sm",variant:"outline",onClick:ha,className:"gap-1",children:[e.jsx(zi,{className:"h-3 w-3"})," Verify Email"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{Je(!0),es("")},className:"gap-1",children:[e.jsx($l,{className:"h-3 w-3"})," Reset PW"]}),!b&&(l||o("ban_users"))&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>he(!0),className:"gap-1 border-yellow-500/30 text-yellow-500 hover:bg-yellow-500/10",children:[e.jsx(Ps,{className:"h-3 w-3"})," Warn"]}),!b&&(l||o("ban_users"))&&e.jsx($,{size:"sm",variant:s.banned_at?"secondary":"outline",onClick:()=>s.banned_at?br():ot(!0),className:"gap-1",children:s.banned_at?e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"h-3 w-3"})," Unban"]}):e.jsxs(e.Fragment,{children:[e.jsx(Za,{className:"h-3 w-3"})," Ban"]})}),!b&&(l||o("delete_accounts"))&&e.jsxs($,{size:"sm",variant:"destructive",onClick:fn,className:"gap-1",children:[e.jsx(As,{className:"h-3 w-3"})," Delete"]})]}),!b&&(l||o("ban_users"))&&e.jsxs("div",{className:"border-t border-border/30 pt-2",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-1.5",children:"Moderation"}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[K!=null&&K.is_suspended?e.
118jsxs($,{size:"sm",variant:"secondary",onClick:Ba,className:"gap-1",children:[e.jsx(Ul,{className:"h-3 w-3"})," Unsuspend"]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>Ge(!0),className:"gap-1 border-orange-500/30 text-orange-500 hover:bg-orange-500/10",children:[e.jsx(Pr,{className:"h-3 w-3"})," Suspend"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:Us,disabled:se,className:`gap-1 ${K!=null&&K.is_shadow_restricted?"border-orange-500/30 text-orange-500":"border-border"}`,children:[se?e.jsx(xs,{className:"h-3 w-3 animate-spin"}):e.jsx(Vi,{className:"h-3 w-3"}),K!=null&&K.is_shadow_restricted?"Remove Shadow":"Shadow Restrict"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:Nt,disabled:Se,className:`gap-1 ${K!=null&&K.is_frozen?"border-blue-500/30 text-blue-500":"border-border"}`,children:[Se?e.jsx(xs,{className:"h-3 w-3 animate-spin"}):e.jsx(It,{className:"h-3 w-3"}),K!=null&&K.is_frozen?"Unfreeze":"Freeze Account"]}),s.seller_profile&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>rs(!0),className:"gap-1 border-destructive/30 text-destructive hover:bg-destructive/10",children:[e.jsx(Vn,{className:"h-3 w-3"})," Suspend All Assets"]})]})]})]})]})})}),s.seller_profile&&g&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(lt,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"text-sm font-display font-semibold uppercase tracking-wider text-muted-foreground",children:"Account Overview"}),e.jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ca,{checked:s.seller_profile.fee_exempt,onCheckedChange:bn}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Fee Exempt"})]}),W&&e.jsx(Y,{className:`text-[10px] ${W.status==="verified"?"bg-emerald-500/20 text-emerald-400":"bg-yellow-500/20 text-yellow-400"}`,children:W.status==="verified"?"â Verified":"Verif. "+W.status}),e.jsx(Y,{className:"text-[10px] bg-violet-500/20 text-violet-400 border-violet-500/30",children:s.seller_profile.creator_tier||"none"})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[{label:"Products",value:g.totalProducts,sub:`${g.activeListings} active`,icon:Pa,color:"text-primary"},{label:"Total Sales",value:g.totalSales,sub:`${g.monthSales} this month`,icon:Or,color:"text-emerald-400"},{label:"Revenue",value:`$${g.totalRevenue.toFixed(2)}`,sub:`$${g.monthRevenue.toFixed(2)} this month`,icon:rt,color:"text-amber-400"},{label:"Avg Rating",value:g.avgRating>0?g.avgRating.toFixed(1):"â",sub:`${g.reviewCount} reviews`,icon:or,color:"text-yellow-400"},{label:"Views",value:g.totalViews.toLocaleString(),sub:"lifetime",icon:ws,color:"text-blue-400"},{label:"Wishlists",value:g.totalWishlists,sub:"total",icon:Xa,color:"text-red-400"},{label:"Conversion",value:`${g.conversionRate.toFixed(1)}%`,sub:"views â sales",icon:lt,color:"text-violet-400"},{label:"Pending",value:g.pendingProducts,sub:"products",icon:Ta,color:"text-orange-400"}].map(v=>e.jsxs("div",{className:"bg-secondary/30 rounded-lg p-3 border border-border/30",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx(v.icon,{className:`h-3.5 w-3.5 ${v.color}`}),e.jsx("span",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:v.label})]}),e.jsx("p",{className:"text-lg font-display font-bold",children:v.value}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:v.sub})]},v.label))})]}),s.seller_profile&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(rn,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"text-sm font-display font-semibold uppercase tracking-wider text-muted-foreground",children:"Payment & Payout Details"})]}),e.jsx(wm,{sellerId:s.seller_profile.id,userId:s.id,sellerProfile:s.seller_profile,onRefresh:r})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Tl,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"text-sm font-display font-semibold uppercase tracking-wider text-muted-foreground",children:"Financial"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(z,{className:"glass border-border/30",children:e.jsxs(V,{className:"p-4 space-y-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Ad Credits"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"bg-secondary/30 rounded-lg p-3",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-1",children:"Balance"}),e.jsxs("p",{className:"text-lg font-display font-bold text-primary",children:["$",ue?Number(ue.balance).toFixed(2):"0.00"]})]}),e.jsxs("div",{className:"bg-secondary/30 rounded-lg p-3",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider mb-1",children:"Total Purchased"}),e.jsxs("p",{className:"text-lg font-display font-bold",children:["$",ue?Number(ue.total_purchased).toFixed(2):"0.00"]})]})]}),(l||o("manage_settings"))&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke,{type:"number",value:je,onChange:v=>Fe(v.target.value),placeholder:"Amount",min:1,max:1e4,className:"w-32"}),e.jsxs($,{size:"sm",disabled:Ie,onClick:async()=>{const v=Number(je);if(isNaN(v)||v<=0){O.error("Invalid amount");return}G(!0),ue?await x.from("ad_wallets").update({balance:ue.balance+v,total_purchased:ue.total_purchased+v}).eq("creator_id",s.id):await x.from("ad_wallets").insert({creator_id:s.id,balance:v,total_purchased:v}),O.success(`$${v.toFixed(2)} ad credits added`),Ns(a.id,"give_ad_credits","user",s.id,{amount:v}),G(!1),Fe("25"),Js()},children:[Ie?e.jsx(xs,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(zn,{className:"h-4 w-4 mr-1"}),"Add Credits"]})]})]})}),e.jsx(z,{className:"glass border-border/30",children:e.jsxs(V,{className:"p-4 space-y-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Referrals"}),J&&J.total>0?e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"bg-secondary/30 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-lg font-display font-bold",children:J.total}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Total"})]}),e.jsxs("div",{className:"bg-secondary/30 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-lg font-display font-bold text-emerald-400",children:J.qualified}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Qualified"})]}),e.jsxs("div",{className:"bg-secondary/30 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-lg font-display font-bold text-yellow-400",children:J.pending}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Pending"})]})]}):e.jsx("p",{className:"text-xs text-muted-foreground py-3",children:"No referrals"})]})})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Vt,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"text-sm font-display font-semibold uppercase tracking-wider text-muted-foreground",children:"Moderation & Activity"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(z,{className:"glass border-destructive/20",children:e.jsxs(V,{className:"p-4 space-y-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Flags & Warnings"}),Ze.length>=3&&e.jsxs("div",{className:"flex items-center gap-2 bg-destructive/10 border border-destructive/30 rounded-lg px-3 py-2 text-xs text-destructive font-medium",children:[e.jsx(Vt,{className:"h-4 w-4"}),"â ï¸ ",Ze.length," warnings â consider escalation"]}),Ze.length>0?e.jsx("div",{className:"space-y-1",children:Ze.map(v=>{const ie=v.expires_at&&new Date(v.expires_at)<new Date;return e.jsxs("div",{className:`flex items-center justify-between text-xs rounded px-3 py-2 ${ie?"bg-muted/20 opacity-60":v.severity==="high"?"bg-destructive/10":v.severity==="medium"?"bg-yellow-500/10":"bg-blue-500/10"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx(Ps,{className:`h-3 w-3 flex-shrink-0 ${v.severity==="high"?"text-destructive":v.severity==="medium"?"text-yellow-500":"text-blue-400"}`}),e.jsx("span",{className:"truncate",children:v.reason}),e.jsx(Y,{variant:v.severity==="high"?"destructive":"secondary",className:"text-[9px] flex-shrink-0",children:v.severity}),v.is_read&&e.jsx(Y,{variant:"outline",className:"text-[9px] flex-shrink-0",children:"Read"}),ie&&e.jsx(Y,{variant:"outline",className:"text-[9px] flex-shrink-0",children:"Expired"})]}),e.jsx("span",{className:"text-muted-foreground flex-shrink-0 ml-2",children:_t(v.created_at)})]},v.id)})}):null,N.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"Disputes"}),N.map(v=>e.jsxs("div",{className:"flex items-center justify-between text-xs bg-destructive/5 rounded px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Br,{className:"h-3 w-3 text-destructive"}),e.jsx("span",{children:v.reason}),e.jsx(Y,{variant:v.status==="open"?"destructive":"secondary",className:"text-[9px]",children:v.status})]}),e.jsx("span",{className:"text-muted-foreground",children:_t(v.created_at)})]},v.id))]}),R.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"Reports"}
118),R.map(v=>e.jsxs("div",{className:"flex items-center justify-between text-xs bg-yellow-500/5 rounded px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ps,{className:"h-3 w-3 text-yellow-500"}),e.jsx("span",{children:v.reason}),e.jsx(Y,{variant:"outline",className:"text-[9px]",children:v.reported_type})]}),e.jsx("span",{className:"text-muted-foreground",children:_t(v.created_at)})]},v.id))]}),We.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wider",children:"Moderation History"}),We.map(v=>{const ie=["ban","suspend","freeze","delete"].some(ut=>{var Zs;return(Zs=v.action_type)==null?void 0:Zs.includes(ut)}),we=["warn","reject","shadow"].some(ut=>{var Zs;return(Zs=v.action_type)==null?void 0:Zs.includes(ut)}),is=ie?"text-destructive border-destructive/30 bg-destructive/5":we?"text-amber-400 border-amber-400/30 bg-amber-400/5":"text-blue-400 border-blue-400/30 bg-blue-400/5",hs=ie?e.jsx(Za,{className:"h-3 w-3"}):we?e.jsx(Ps,{className:"h-3 w-3"}):e.jsx(Ws,{className:"h-3 w-3"});return e.jsxs("div",{className:`flex items-center justify-between text-xs rounded px-3 py-2 border ${is}`,children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[hs,e.jsx(Y,{variant:"outline",className:"text-[9px] shrink-0",children:v.action_type}),e.jsx("span",{className:"truncate",children:v.reason||"No reason provided"})]}),e.jsx("span",{className:"text-muted-foreground flex-shrink-0 ml-2",children:_t(v.created_at)})]},v.id)})]}),Ze.length===0&&N.length===0&&R.length===0&&We.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground py-2",children:"No flags, warnings, or moderation history"})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(z,{className:"glass border-border/30",children:e.jsxs(V,{className:"p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Login History"}),e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:f.length})]}),f.length>0?e.jsx("div",{className:"space-y-1 max-h-[250px] overflow-y-auto",children:f.map(v=>e.jsxs("div",{className:"flex items-center justify-between text-xs bg-secondary/30 rounded px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[dl(v.device_type),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"font-medium",children:v.browser||"Unknown"}),v.device_type&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",v.device_type]}),v.country&&e.jsxs("span",{className:"text-muted-foreground ml-1",children:["· ",v.country]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[v.ip_address&&e.jsx("span",{className:"font-mono text-[10px] text-muted-foreground",children:v.ip_address}),e.jsx("span",{className:"text-muted-foreground",children:_t(v.logged_in_at)})]})]},v.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No login history"})]})}),e.jsx(z,{className:"glass border-border/30",children:e.jsxs(V,{className:"p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Recent Activity"}),e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:m.length})]}),m.length>0?e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:m.map(v=>e.jsxs("div",{className:"flex items-center justify-between text-xs bg-secondary/30 rounded px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dt,{className:"h-3 w-3 text-primary"}),e.jsx("span",{className:"font-medium",children:v.action.replace(/_/g," ")}),v.target_type&&e.jsx(Y,{variant:"outline",className:"text-[9px]",children:v.target_type})]}),e.jsx("span",{className:"text-muted-foreground",children:_t(v.created_at)})]},v.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No activity logged"})]})})]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Or,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"text-sm font-display font-semibold uppercase tracking-wider text-muted-foreground",children:"User Data"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(z,{className:"glass border-border/30",children:e.jsxs(gt,{open:ge.purchases,onOpenChange:()=>Ae("purchases"),children:[e.jsxs(ft,{className:"flex items-center justify-between w-full py-3 px-4 hover:bg-muted/30 rounded-t-lg transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-4 w-4 text-primary"}),e.jsxs("h4",{className:"text-sm font-display font-semibold",children:["Purchases · $",Cn.toFixed(2)]}),e.jsx(Y,{variant:"secondary",className:"text-[10px] px-1.5",children:((kr=s.purchases)==null?void 0:kr.length)||0})]}),e.jsx(js,{className:`h-4 w-4 text-muted-foreground transition-transform ${ge.purchases?"rotate-180":""}`})]}),e.jsx(jt,{children:e.jsx(V,{className:"pt-0 pb-4 px-4",children:(((Ys=s.purchases)==null?void 0:Ys.length)||0)>0?e.jsx("div",{className:"space-y-1 max-h-[300px] overflow-y-auto",children:s.purchases.map((v,ie)=>{var we,is,hs;return e.jsxs("div",{className:"flex items-center justify-between text-sm bg-secondary/30 rounded px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pa,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{children:((we=v.product)==null?void 0:we.name)||"Unknown"}),e.jsx(Y,{variant:"outline",className:"text-[9px]",children:(is=v.product)==null?void 0:is.category}),v.granted&&e.jsx(Y,{className:"bg-accent/20 text-accent-foreground text-[9px]",children:"Gifted"}),e.jsx(Y,{variant:"outline",className:`text-[9px] ${(v.payment_method||"stripe")==="stripe"?"text-violet-400 border-violet-500/30":"text-blue-400 border-blue-500/30"}`,children:(v.payment_method||"stripe")==="stripe"?"Stripe":"PayPal"}),v.status==="refunded"&&e.jsx(Y,{variant:"destructive",className:"text-[9px]",children:"Refunded"})]}),e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground text-xs",children:[e.jsxs("span",{children:["$",Number(v.amount||((hs=v.product)==null?void 0:hs.price)||0).toFixed(2)]}),e.jsx("span",{children:new Date(v.purchased_at).toLocaleDateString()}),(l||o("remove_purchases"))&&e.jsx($,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive hover:text-destructive",onClick:()=>{var ut;return fa(v.id,((ut=v.product)==null?void 0:ut.name)||"Unknown")},children:e.jsx(As,{className:"h-3 w-3"})})]})]},v.id||ie)})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No purchases"})})})]})}),e.jsx(z,{className:"glass border-border/30",children:e.jsxs(gt,{open:ge.wishlists,onOpenChange:()=>Ae("wishlists"),children:[e.jsxs(ft,{className:"flex items-center justify-between w-full py-3 px-4 hover:bg-muted/30 rounded-t-lg transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xa,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"text-sm font-display font-semibold",children:"Wishlist"}),e.jsx(Y,{variant:"secondary",className:"text-[10px] px-1.5",children:p.length})]}),e.jsx(js,{className:`h-4 w-4 text-muted-foreground transition-transform ${ge.wishlists?"rotate-180":""}`})]}),e.jsx(jt,{children:e.jsx(V,{className:"pt-0 pb-4 px-4",children:p.length>0?e.jsx("div",{className:"space-y-1 max-h-[300px] overflow-y-auto",children:p.map(v=>{var ie,we,is,hs;return e.jsxs("div",{className:"flex items-center justify-between text-sm bg-secondary/30 rounded px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xa,{className:"h-3 w-3 text-destructive"}),e.jsx(da,{to:`/product/${((ie=v.product)==null?void 0:ie.slug)||((we=v.product)==null?void 0:we.id)}`,className:"hover:text-primary transition-colors",children:((is=v.product)==null?void 0:is.name)||"Unknown"}),e.jsx(Y,{variant:"outline",className:"text-[9px]",children:(hs=v.product)==null?void 0:hs.category})]}),e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground text-xs",children:[e.jsx("span",{children:v.product?Rt(v.product):"$0.00"}),e.jsx("span",{children:new Date(v.created_at).toLocaleDateString()})]})]},v.id)})}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No wishlisted products"})})})]})})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(kt,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"text-sm font-display font-semibold uppercase tracking-wider text-muted-foreground",children:"Admin Tools"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(z,{className:"glass border-border/30",children:e.jsxs(V,{className:"p-4 space-y-3",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Internal Notes"}),e.jsx($s,{placeholder:"Admin-only notes about this user...",value:M,onChange:v=>y(v.target.value),className:"bg-background/50 min-h-[100px] text-sm"}),e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{size:"sm",onClick:yn,disabled:w,className:"gap-1",children:[w?e.jsx(xs,{className:"h-3 w-3 animate-spin"}):e.jsx(Ws,{className:"h-3 w-3"}),"Save Notes"]})})]})}),e.jsx(z,{className:"glass border-border/30",children:e.jsxs(gt,{open:ge.trustedDevices,onOpenChange:()=>Ae("trustedDevices"),children:[e.jsxs(ft,{className:"flex items-center justify-between w-full py-3 px-4 hover:bg-muted/30 rounded-t-lg transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"text-sm font-display font-semibold",children:"Trusted Devices"}),e.jsx(Y,{variant:"secondary",className:"text-[10px] px-1.5",children:Q.filter(v=>new Date(v.expires_at)>new Date).length})]}),e.jsx(js,{className:`h-4 w-4 text-muted-foreground transition-transform ${ge.trustedDevices?"rotate-180":""}`})]}),e.jsx(jt,{children:e.jsx(V,{className:"pt-0 pb-4 px-4",children:ve?e.jsx(cs,{className:"py-3",size:"sm"}):Q.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No trusted devices"}):e.jsxs("div",{className:"space-y-1.5",children:[Q.length>0&&e.jsx("div",{className:"flex justify-end mb-1",children:e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive text-xs h-6",onClick:_r,children:"Revoke All"})}),Q.map(v=>{var we,is;const ie=new Date(v.expires_at)<=new Date;return e.jsxs("div",{className:`flex items-center justify-between text-xs rounded px-3 py-2 ${ie?"bg-muted/20 opacity-60":"bg-secondary/30"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[dl((we
118=v.os)!=null&&we.toLowerCase().includes("android")||(is=v.os)!=null&&is.toLowerCase().includes("ios")?"mobile":"desktop"),e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"font-medium",children:v.browser||"Unknown"}),v.os&&e.jsxs("span",{className:"text-muted-foreground",children:[" on ",v.os]}),(v.country||v.region)&&e.jsxs("span",{className:"text-muted-foreground ml-1",children:["· ",[v.region,v.country].filter(Boolean).join(", ")]})]}),ie?e.jsx(Y,{variant:"outline",className:"text-[9px] text-destructive border-destructive/30 ml-1",children:"Expired"}):e.jsx(Y,{className:"text-[9px] bg-emerald-500/20 text-emerald-400 border-emerald-500/30 ml-1",children:"Trusted"})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[v.last_login_at&&e.jsx("span",{className:"text-muted-foreground",children:_t(v.last_login_at)}),!ie&&e.jsx($,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-destructive hover:text-destructive",onClick:()=>mt(v.id),children:e.jsx(As,{className:"h-3 w-3"})})]})]},v.id)})]})})})]})})]}),!b&&(l||o("manage_roles"))&&e.jsx(z,{className:"glass border-primary/20 mt-4",children:e.jsxs(gt,{open:ge.profile,onOpenChange:()=>Ae("profile"),children:[e.jsxs(ft,{className:"flex items-center justify-between w-full py-3 px-4 hover:bg-muted/30 rounded-t-lg transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kt,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"text-sm font-display font-semibold",children:"Roles & Permissions"})]}),e.jsx(js,{className:`h-4 w-4 text-muted-foreground transition-transform ${ge.profile?"rotate-180":""}`})]}),e.jsx(jt,{children:e.jsxs(V,{className:"pt-0 pb-4 px-4 space-y-4",children:[l&&e.jsxs("div",{className:"flex items-center gap-3 pb-3 border-b border-border/30",children:[e.jsx(Ca,{checked:j,onCheckedChange:yr}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-medium",children:j?"Staff Member":"Regular User"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j?"Has admin panel access":"Toggle to grant admin access"})]})]}),c.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Custom Roles"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:c.map(v=>{const ie=P.includes(v.id);return e.jsxs("button",{onClick:()=>vn(v.id),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium border transition-all ${ie?"border-transparent text-white shadow-sm":"border-border text-muted-foreground hover:border-primary/50"}`,style:ie?{backgroundColor:v.color}:void 0,children:[ie?e.jsx(kt,{className:"h-3 w-3"}):e.jsx("div",{className:"w-2.5 h-2.5 rounded-full border border-current opacity-50"}),v.name,ie&&e.jsx("span",{className:"ml-1 opacity-75",children:"â"})]},v.id)})})]}),(l||o("manage_permissions"))&&j&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Direct Permissions"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2",children:n.map(v=>e.jsxs("label",{className:"flex items-center gap-2 text-xs cursor-pointer py-1",children:[e.jsx(Ca,{checked:(s.permissions||[]).includes(v.key),onCheckedChange:()=>jn(v.key)}),v.label]},v.key))})]})]})})]})})]}),e.jsx(Ds,{open:Ee,onOpenChange:Je,children:e.jsxs(Ms,{className:"glass sm:max-w-sm",children:[e.jsxs(Es,{children:[e.jsx(Os,{className:"font-display",children:"Reset Password"}),e.jsxs(Xt,{children:["Set a new password for ",s.email]})]}),e.jsx(ke,{type:"password",placeholder:"New password (min 6 chars)",value:Ve,onChange:v=>es(v.target.value),className:"bg-background/50"}),e.jsx($,{onClick:Va,className:"w-full",children:"Reset Password"})]})}),e.jsx(Ds,{open:ds,onOpenChange:ot,children:e.jsxs(Ms,{className:"glass sm:max-w-sm",children:[e.jsxs(Es,{children:[e.jsx(Os,{className:"font-display text-destructive",children:"Ban User"}),e.jsxs(Xt,{children:["Ban ",s.display_name||s.email," from the platform"]})]}),e.jsxs(Pe,{value:Mt,onValueChange:un,children:[e.jsx(Te,{className:"bg-background/50",children:e.jsx(De,{placeholder:"Reason"})}),e.jsxs(Me,{children:[e.jsx(L,{value:"violation",children:"Terms of Service Violation"}),e.jsx(L,{value:"spam",children:"Spam / Abuse"}),e.jsx(L,{value:"stolen_content",children:"Stolen Content"}),e.jsx(L,{value:"fraud",children:"Fraud / Chargebacks"}),e.jsx(L,{value:"harassment",children:"Harassment"}),e.jsx(L,{value:"other",children:"Other"})]})]}),e.jsxs($,{variant:"destructive",onClick:br,className:"w-full gap-1",children:[e.jsx(Za,{className:"h-4 w-4"})," Confirm Ban"]})]})}),e.jsx(Ds,{open:xn,onOpenChange:ur,children:e.jsxs(Ms,{className:"glass sm:max-w-md",children:[e.jsxs(Es,{children:[e.jsx(Os,{className:"font-display",children:"Grant Product"}),e.jsxs(Xt,{children:["Add a product to ",s.display_name||s.email,"'s account for free"]})]}),e.jsx(ke,{placeholder:"Search products...",value:Ua,onChange:v=>hr(v.target.value),className:"bg-background/50"}),e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:xr.filter(v=>!Ua||v.name.toLowerCase().includes(Ua.toLowerCase())).slice(0,20).map(v=>e.jsxs("button",{onClick:()=>pr(v.id),className:`w-full flex items-center justify-between px-3 py-2 rounded text-sm transition-colors ${Ks===v.id?"bg-primary/20 text-primary":"hover:bg-muted/30"}`,children:[e.jsx("span",{children:v.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{variant:"outline",className:"text-[9px]",children:v.category}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Rt(v)})]})]},v.id))}),e.jsxs($,{onClick:Nr,disabled:!Ks||gr,className:"w-full gap-1",children:[gr?e.jsx(xs,{className:"h-4 w-4 animate-spin"}):e.jsx(zn,{className:"h-4 w-4"})," Grant Product"]})]})}),e.jsx(Ds,{open:hn,onOpenChange:Ia,children:e.jsxs(Ms,{className:"glass sm:max-w-md",children:[e.jsxs(Es,{children:[e.jsx(Os,{className:"font-display",children:"Send Notification"}),e.jsxs(Xt,{children:["Send a notification to ",s.display_name||s.email]})]}),e.jsxs(Pe,{value:dt,onValueChange:gn,children:[e.jsx(Te,{className:"bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"info",children:"â¹ï¸ Info"}),e.jsx(L,{value:"warning",children:"â ï¸ Warning"}),e.jsx(L,{value:"admin_message",children:"ð© Admin Message"}),e.jsx(L,{value:"reward",children:"ð Reward"})]})]}),e.jsx(ke,{placeholder:"Notification title",value:za,onChange:v=>jr(v.target.value),className:"bg-background/50"}
118),e.jsx($s,{placeholder:"Message (optional)",value:vr,onChange:v=>ct(v.target.value),className:"bg-background/50"}),e.jsxs($,{onClick:wn,className:"w-full gap-1",children:[e.jsx(qt,{className:"h-4 w-4"})," Send Notification"]})]})}),e.jsx(Ds,{open:ne,onOpenChange:he,children:e.jsxs(Ms,{className:"glass sm:max-w-lg",children:[e.jsxs(Es,{children:[e.jsxs(Os,{className:"font-display flex items-center gap-2",children:[e.jsx(Ps,{className:"h-5 w-5 text-yellow-500"})," Warn User"]}),e.jsxs(Xt,{children:["Issue a warning to ",s.display_name||s.email]})]}),e.jsxs("div",{className:"space-y-3 max-h-[60vh] overflow-y-auto pr-1",children:[e.jsx(Sm,{userId:s.id,selectedAssets:Ce,onSelectionChange:qe}),e.jsx(ao,{variables:{user_name:s.display_name||s.email,asset_name:Ce.length===1?Ce[0].name:void 0,asset_list:Ce.length>1?Ce.map(v=>v.name):void 0},currentText:Oe,onSelect:Ue}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Reason *"}),e.jsx($s,{placeholder:"Explain the reason for this warning...",value:Oe,onChange:v=>Ue(v.target.value),className:"bg-background/50",rows:4})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Severity"}),e.jsxs(Pe,{value:Xe,onValueChange:Be,children:[e.jsx(Te,{className:"bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"low",children:"ðµ Low"}),e.jsx(L,{value:"medium",children:"ð¡ Medium"}),e.jsx(L,{value:"high",children:"ð´ High"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Expiration (optional)"}),e.jsx(ke,{type:"date",value:ae,onChange:v=>de(v.target.value),className:"bg-background/50",min:new Date().toISOString().split("T")[0]})]})]})]}),e.jsxs($,{onClick:ga,disabled:Re||!Oe.trim(),className:"w-full gap-1 bg-yellow-600 hover:bg-yellow-700 text-white",children:[Re?e.jsx(xs,{className:"h-4 w-4 animate-spin"}):e.jsx(Ps,{className:"h-4 w-4"}),"Issue Warning",Ce.length>0?` (${Ce.length} asset${Ce.length>1?"s":""})`:""]})]})}),e.jsx(Ds,{open:us,onOpenChange:Ge,children:e.jsxs(Ms,{className:"glass sm:max-w-md",children:[e.jsxs(Es,{children:[e.jsxs(Os,{className:"font-display flex items-center gap-2 text-orange-500",children:[e.jsx(Pr,{className:"h-5 w-5"})," Suspend User"]}),e.jsxs(Xt,{children:["Temporarily suspend ",s.display_name||s.email," from the platform"]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Reason *"}),e.jsx($s,{placeholder:"Reason for suspension...",value:He,onChange:v=>A(v.target.value),className:"bg-background/50",rows:3})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Duration"}),e.jsxs(Pe,{value:me,onValueChange:ze,children:[e.jsx(Te,{className:"bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"1h",children:"1 Hour"}),e.jsx(L,{value:"6h",children:"6 Hours"}),e.jsx(L,{value:"24h",children:"24 Hours"}),e.jsx(L,{value:"3d",children:"3 Days"}),e.jsx(L,{value:"7d",children:"7 Days"}),e.jsx(L,{value:"30d",children:"30 Days"}),e.jsx(L,{value:"custom",children:"Custom Date"}),e.jsx(L,{value:"indefinite",children:"Indefinite"})]})]})]}),me==="custom"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Expires at"}),e.jsx(ke,{type:"datetime-local",value:Le,onChange:v=>B(v.target.value),className:"bg-background/50"})]})]}),e.jsxs($,{onClick:Wt,disabled:ee||!He.trim(),variant:"destructive",className:"w-full gap-1",children:[ee?e.jsx(xs,{className:"h-4 w-4 animate-spin"}):e.jsx(Pr,{className:"h-4 w-4"}),"Confirm Suspension"]})]})}),e.jsx(Ds,{open:Ke,onOpenChange:rs,children:e.jsxs(Ms,{className:"glass sm:max-w-md",children:[e.jsxs(Es,{children:[e.jsxs(Os,{className:"font-display flex items-center gap-2 text-destructive",children:[e.jsx(Vn,{className:"h-5 w-5"})," Suspend All Assets"]}),e.jsxs(Xt,{children:["This will suspend ALL assets for ",s.display_name||s.email,". They will be hidden from the marketplace."]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground mb-1 block",children:"Reason (optional)"}),e.jsx($s,{placeholder:"Reason for bulk asset suspension...",value:H,onChange:v=>ce(v.target.value),className:"bg-background/50",rows:2})]}),e.jsxs($,{onClick:Qs,disabled:le,variant:"destructive",className:"w-full gap-1",children:[le?e.jsx(xs,{className:"h-4 w-4 animate-spin"}):e.jsx(Vn,{className:"h-4 w-4"}),"Suspend All Assets"]})]})})]})}function Cm({query:s,setQuery:t,filterRole:r,setFilterRole:n,filterBanned:a,setFilterBanned:l,sortBy:o,setSortBy:j,searching:b,onSearch:c}){return e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx("div",{className:"flex-1",onKeyDown:d=>{d.key==="Enter"&&c()},children:e.jsx(Gs,{placeholder:"Search by email...",value:s,onChange:t,className:"bg-background/50"})}),e.jsxs(Pe,{value:r,onValueChange:n,children:[e.jsx(Te,{className:"w-36 bg-background/50",children:e.jsx(De,{placeholder:"Role"})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Roles"}),e.jsx(L,{value:"owner",children:"Owner"}),e.jsx(L,{value:"admin",children:"Admin"}),e.jsx(L,{value:"user",children:"User"}),e.jsx(L,{value:"seller",children:"Sellers"})]})]}),e.jsxs(Pe,{value:a,onValueChange:l,children:[e.jsx(Te,{className:"w-36 bg-background/50",children:e.jsx(De,{placeholder:"Status"})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Status"}),e.jsx(L,{value:"active",children:"Active"}),e.jsx(L,{value:"banned",children:"Banned"})]})]}),e.jsxs(Pe,{value:o,onValueChange:j,children:[e.jsx(Te,{className:"w-44 bg-background/50",children:e.jsx(De,{placeholder:"Sort by"})}),e.jsxs(Me,{children:[e.jsx(L,{value:"created_at",children:"Newest First"}),e.jsx(L,{value:"last_sign_in_at",children:"Last Active"}),e.jsx(L,{value:"role",children:"Role"}),e.jsx(L,{value:"purchases",children:"Most Purchases"})]})]}),e.jsx(pa,{loading:b,onClick:c,loadingText:"Searching...",children:"Search"})]})}function Am(){const{user:s,loading:t}=vs(),[r,n]=i.useState(""),[a,l]=i.useState([]),[o,j]=i.useState(!1),[b,c]=i.useState(null),[d,P]=i.useState(1),[k,p]=i.useState(1),[h,f]=i.useState(0),[_,m]=i.useState("created_at"),[u,g]=i.useState("all"),[S,M]=i.useState("all"),[y,w]=i.useState(null),F=25,[J,E]=i.useState([]),[N,U]=i.useState({}),R=i.useCallback(async(W=1)=>{var D;if(!(t||!s)){j(!0),w(null);try{let X=!1;for(;;){const{data:oe,error:ue}=await x.functions.invoke("admin-users",{body:{action:"search",query:r,page:W,perPage:F,sortBy:_,filterRole:u,filterBanned:S}}
118),fe=typeof(oe==null?void 0:oe.error)=="string"?oe.error:null,je=oe&&typeof oe=="object"&&"data"in oe?oe.data:oe,Fe=((D=ue==null?void 0:ue.context)==null?void 0:D.status)??(ue==null?void 0:ue.status),Ie=fe||(ue==null?void 0:ue.message)||"Search failed";if((Fe===401||Ie==="Unauthorized")&&!X){X=!0,await x.auth.refreshSession();continue}if(ue||fe)l([]),f(0),p(1),P(1),w(Ie),O.error(Ie);else{const Q=je??{};l(Array.isArray(Q.users)?Q.users:[]),p(typeof Q.totalPages=="number"&&Q.totalPages>0?Q.totalPages:1),f(typeof Q.total=="number"?Q.total:0),P(typeof Q.page=="number"&&Q.page>0?Q.page:1),w(null)}break}}finally{j(!1)}}},[t,s,S,u,r,_]),Z=i.useCallback(async()=>{if(t||!s)return;const[{data:W},{data:D}]=await Promise.all([x.from("custom_roles").select("*").order("name"),x.from("user_custom_roles").select("*")]);E(W||[]);const X={};D==null||D.forEach(oe=>{X[oe.user_id]||(X[oe.user_id]=[]),X[oe.user_id].push(oe.role_id)}),U(X)},[t,s]);return i.useEffect(()=>{if(!t){if(!s){l([]),f(0),p(1),w("You must be signed in to view users.");return}R(1),Z()}},[t,s,_,u,S,R,Z]),b?e.jsx(km,{user:b,onBack:()=>c(null),onRefresh:()=>R(d),allPermissions:gm}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(Cm,{query:r,setQuery:n,filterRole:u,setFilterRole:W=>{g(W),P(1)},filterBanned:S,setFilterBanned:W=>{M(W),P(1)},sortBy:_,setSortBy:W=>{m(W),P(1)},searching:o,onSearch:()=>{P(1),R(1)}}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[h," user",h!==1?"s":""," · Page ",d," of ",k]}),o?e.jsx(cs,{}):y?e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx("p",{className:"text-sm text-destructive",children:y}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>R(d),children:"Retry"})]}):a.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-12",children:"No users found"}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:a.map(W=>{var D,X,oe,ue;return e.jsx(z,{className:"glass hover:border-primary/30 transition-all cursor-pointer group",onClick:()=>c(W),children:e.jsx(V,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Bs,{className:"h-10 w-10 shrink-0 group-hover:ring-2 ring-primary/30 transition-all",children:[W.avatar_url&&e.jsx(it,{src:W.avatar_url,alt:W.display_name||W.email}),e.jsx(qs,{className:"bg-primary/10 text-primary font-display font-bold text-sm",children:(W.display_name||W.email||"?")[0].toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(da,{to:`/user/${encodeURIComponent(W.display_name||W.email||"")}`,className:"font-display font-semibold text-sm truncate hover:text-primary transition-colors",onClick:fe=>fe.stopPropagation(),children:W.display_name||W.email}),(D=W.roles)!=null&&D.includes("owner")?e.jsx(Y,{className:"bg-primary/20 text-primary border-primary/30 text-[10px]",children:"Owner"}):(X=W.roles)!=null&&X.includes("admin")?e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:"Staff"}):e.jsx(Y,{variant:"outline",className:"text-[10px]",children:"User"}),W.banned_at&&e.jsx(Y,{variant:"destructive",className:"text-[10px] px-1.5 py-0",children:"Banned"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:W.email}),(N[W.id]||[]).length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:(N[W.id]||[]).map(fe=>{const je=J.find(Fe=>Fe.id===fe);return je?e.jsx("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded-full text-[10px] font-medium text-white",style:{backgroundColor:je.color},children:je.name},fe):null})}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[((oe=W.purchases)==null?void 0:oe.length)||0," purchase",(((ue=W.purchases)==null?void 0:ue.length)||0)!==1?"s":""]})]})]})})},W.id)})}),k>1&&e.jsxs("div",{className:"flex justify-center gap-2 pt-2",children:[e.jsx($,{size:"sm",variant:"outline",disabled:d<=1,onClick:()=>{P(d-1),R(d-1)},children:"Previous"}),Array.from({length:Math.min(k,5)},(W,D)=>{const oe=Math.max(1,Math.min(d-2,k-4))+D;return oe>k?null:e.jsx($,{size:"sm",variant:oe===d?"default":"outline",onClick:()=>{P(oe),R(oe)},children:oe},oe)}),e.jsx($,{size:"sm",variant:"outline",disabled:d>=k,onClick:()=>{P(d+1),R(d+1)},children:"Next"})]})]})}function Rm({data:s,label:t}){if(s.length===0)return e.jsx("p",{className:"text-muted-foreground text-sm text-center py-8",children:"No data"});const r=({active:n,payload:a,label:l})=>!n||!(a!=null&&a.length)?null:e.jsxs("div",{className:"glass border border-border/50 rounded-lg px-3 py-2 text-xs shadow-lg",children:[e.jsx("p",{className:"font-medium text-foreground mb-1",children:l}),e.jsxs("p",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-primary"}),t,": ",e.jsx("span",{className:"font-mono font-semibold",children:a[0].value})]})]});return e.jsxs("div",{className:"w-full h-full flex flex-col",children:[e.jsx("div",{className:"flex gap-4 mb-2 text-xs text-muted-foreground",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-3 h-0.5 bg-primary inline-block rounded"})," ",t]})}),e.jsx(gs,{width:"100%",height:"100%",children:e.jsxs(cr,{data:s,margin:{top:5,right:10,left:0,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"metricGradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.3}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",strokeOpacity:.3,vertical:!1}),e.jsx(ks,{dataKey:"hour",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}
118,tickLine:!1,axisLine:!1,interval:s.length<=12?0:Math.ceil(s.length/8)}),e.jsx(Cs,{tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:!1,width:40,allowDecimals:!1}),e.jsx(fs,{content:e.jsx(r,{})}),e.jsx(Tt,{type:"monotone",dataKey:"value",stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#metricGradient)",name:t,dot:!1,activeDot:{r:4,fill:"hsl(var(--primary))",stroke:"hsl(var(--background))",strokeWidth:2}})]})})]})}const Tr=["hsl(var(--primary))","hsl(142, 76%, 36%)","hsl(38, 92%, 50%)","hsl(262, 83%, 58%)"];function ml(s,t,r="desc"){const[n,a]=i.useState(t),[l,o]=i.useState(r),[j,b]=i.useState(0),c=10,d=i.useMemo(()=>l?[...s].sort((f,_)=>{const m=f[n],u=_[n];return l==="asc"?m-u:u-m}):s,[s,n,l]),P=d.slice(j*c,(j+1)*c),k=Math.ceil(d.length/c);return{paged:P,page:j,setPage:b,totalPages:k,toggleSort:f=>{f===n?o(l==="desc"?"asc":l==="asc"?null:"desc"):(a(f),o("desc")),b(0)},SortIcon:({col:f})=>f!==n||!l?e.jsx(gc,{className:"h-3 w-3 text-muted-foreground/40"}):l==="desc"?e.jsx(js,{className:"h-3 w-3 text-primary"}):e.jsx(ma,{className:"h-3 w-3 text-primary"}),sortKey:n,sortDir:l}}function Pm({loading:s,sessionStats:t,stats:r,aovByMethod:n,topTags:a,referrers:l,topPages:o,browserStats:j,deviceStats:b,hourlyData:c,analyticsDailyRows:d,granularity:P,rangeDaysState:k,selectedMetric:p,metricTrendData:h,computeMetricTrend:f,pctChange:_,formatDuration:m}){const u=i.useMemo(()=>{const N=l.reduce((U,R)=>U+R.count,0);return l.map(U=>({source:U.domain==="(direct)"?"Direct / None":U.domain,sessions:U.count,pctOfTotal:N>0?U.count/N*100:0,purchases:0,revenue:0}))},[l]),g=ml(u,"sessions"),S=i.useMemo(()=>{const N=o.reduce((U,R)=>U+R.count,0);return o.map(U=>({page:U.page,views:U.count,pctOfTotal:N>0?U.count/N*100:0,avgTime:0}))},[o]),M=ml(S,"views"),y=i.useMemo(()=>{const N=b.reduce((U,R)=>U+R.count,0);return b.map(U=>({name:U.device.charAt(0).toUpperCase()+U.device.slice(1),value:U.count,pct:N>0?U.count/N*100:0}))},[b]),w=i.useMemo(()=>j.map(N=>({name:N.browser,sessions:N.count})),[j]);i.useMemo(()=>(n.stripe*(r.totalPurchases>0?r.totalPurchases*.6:0),[{name:"Stripe",value:Math.max(0,r.totalRevenue-(n.paypal>0?n.paypal*Math.round(r.totalPurchases*.3):0))},{name:"PayPal",value:n.paypal>0?n.paypal*Math.round(r.totalPurchases*.3):0}].filter(N=>N.value>0)),[n,r]);const F={uniqueUsers:"Unique Users",newUsers:"New Users",returningUsers:"Returning Users",sessions:"Sessions",pageviews:"Pageviews",bounceRate:"Bounce Rate",avgDuration:"Avg. Duration"},J=({type:N})=>{const U=N.toLowerCase();return U==="mobile"?e.jsx(ui,{className:"h-4 w-4"}):U==="tablet"?e.jsx(Il,{className:"h-4 w-4"}):e.jsx(xi,{className:"h-4 w-4"})},E=({active:N,payload:U,label:R})=>!N||!(U!=null&&U.length)?null:e.jsxs("div",{className:"glass border border-border/50 rounded-lg px-3 py-2 text-xs shadow-lg",children:[e.jsx("p",{className:"font-medium text-foreground mb-1",children:R}),U.map((Z,W)=>e.jsxs("p",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-full",style:{backgroundColor:Z.color||Z.stroke}}),Z.name,": ",e.jsx("span",{className:"font-mono font-semibold",children:typeof Z.value=="number"?Z.value.toLocaleString():Z.value})]},W))]});return s?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-3",children:Array.from({length:8}).map((N,U)=>e.jsxs("div",{className:"rounded-xl border border-border/30 bg-muted/5 p-4",children:[e.jsx(Ye,{className:"h-3 w-16 mb-3"}),e.jsx(Ye,{className:"h-7 w-20 mb-2"}),e.jsx(Ye,{className:"h-3 w-12"})]},U))}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Array.from({length:4}).map((N,U)=>e.jsxs("div",{className:"rounded-xl border border-border/30 bg-muted/5 p-4",children:[e.jsx(Ye,{className:"h-3 w-20 mb-3"}),e.jsx(Ye,{className:"h-7 w-24 mb-2"}),e.jsx(Ye,{className:"h-3 w-14"})]},U))}),e.jsxs("div",{className:"rounded-xl border border-border/30 bg-muted/5 p-6",children:[e.jsx(Ye,{className:"h-4 w-40 mb-4"}),e.jsx(Ye,{className:"h-64 w-full"})]})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-3",children:[{key:"uniqueUsers",label:"Unique Users",value:t.uniqueUsers,prev:t.prevUniqueUsers,format:N=>
118N.toLocaleString(),inverted:!1,icon:bt,tooltip:"Total distinct visitors"},{key:"newUsers",label:"New Users",value:t.newUsers,prev:0,format:N=>N.toLocaleString(),inverted:!1,icon:$a,tooltip:"First-time visitors in this period"},{key:"returningUsers",label:"Returning",value:t.returningUsers,prev:0,format:N=>N.toLocaleString(),inverted:!1,icon:Yn,tooltip:"Visitors who have been here before"},{key:"returningPct",label:"% Returning",value:t.returningPct,prev:0,format:N=>`${N.toFixed(1)}%`,inverted:!1,icon:sc,tooltip:"Returning / Total Unique"},{key:"sessions",label:"Sessions",value:t.totalSessions,prev:t.prevSessions,format:N=>N.toLocaleString(),inverted:!1,icon:Dt,tooltip:"Total browser sessions"},{key:"pageviews",label:"Pageviews",value:t.totalPageviews,prev:t.prevPageviews,format:N=>N.toLocaleString(),inverted:!1,icon:ws,tooltip:"Total page loads"},{key:"bounceRate",label:"Bounce Rate",value:t.bounceRate,prev:t.prevBounceRate,format:N=>`${N.toFixed(1)}%`,inverted:!0,icon:zl,tooltip:"SPA-corrected · Sessions with no meaningful engagement"},{key:"avgDuration",label:"Avg Duration",value:t.avgSessionDuration,prev:t.prevAvgDuration,format:N=>m(N),inverted:!1,icon:Ta,tooltip:"Average session length"}].map((N,U)=>e.jsx(Ls,{label:N.label,value:N.format(N.value),icon:N.icon,change:N.prev>0?_(N.value,N.prev):void 0,invertChange:N.inverted,accentIndex:U,onClick:N.key!=="returningPct"?()=>f(N.key):void 0,selected:p===N.key,tooltip:N.tooltip,subtitle:N.key==="bounceRate"?"SPA-corrected":void 0},N.key))}),p&&h.length>0&&e.jsx(z,{className:"glass border-primary/20",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"text-lg font-display font-semibold",children:[F[p]||p," Trend"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>f(p),children:"â"})]}),e.jsx("div",{className:"h-64",children:e.jsx(Rm,{data:h,label:F[p]||p})})]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Ls,{label:"Your Earnings",value:`$${r.platformEarnings.toFixed(2)}`,icon:rt,accentIndex:0,tooltip:"Platform revenue (GMV à fee rate)"}),e.jsx(Ls,{label:"Total GMV",value:`$${r.totalRevenue.toFixed(2)}`,icon:lt,accentIndex:3,tooltip:"Gross merchandise value"}),e.jsx(Ls,{label:"Purchases",value:r.totalPurchases.toLocaleString(),icon:Or,accentIndex:1,tooltip:"Completed orders"}),e.jsx(Ls,{label:"Cart â Purchase",value:`${r.conversionRate.toFixed(1)}%`,icon:Ml,accentIndex:5,tooltip:"Cart add to purchase conversion"})]}),c.length>0&&e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-display font-semibold",children:"Sessions Over Time"}),e.jsxs("div",{className:"flex gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-3 h-0.5 bg-primary inline-block rounded"})," Total"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-3 h-0.5 inline-block rounded",style:{background:"hsl(142, 76%, 36%)"}})," New"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-3 h-0.5 inline-block rounded",style:{background:"hsl(38, 92%, 50%)"}})," Returning"]})]})]}),e.jsx("div",{className:"h-72",children:e.jsx(gs,{width:"100%",height:"100%",children:e.jsxs(cr,{data:c,margin:{top:5,right:10,left:0,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"sessionsGradientOv",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.2}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",strokeOpacity:.3,vertical:!1}),e.jsx(ks,{dataKey:"hour",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:!1,interval:c.length<=12?0:Math.ceil(c.length/8)}),e.jsx(Cs,{tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}
118,tickLine:!1,axisLine:!1,width:35,allowDecimals:!1}),e.jsx(fs,{content:e.jsx(E,{})}),e.jsx(Tt,{type:"monotone",dataKey:"sessions",stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#sessionsGradientOv)",name:"Total",dot:!1,activeDot:{r:4,fill:"hsl(var(--primary))",stroke:"hsl(var(--background))",strokeWidth:2}}),e.jsx(Tt,{type:"monotone",dataKey:"newUsers",stroke:"hsl(142, 76%, 36%)",strokeWidth:1.5,fill:"none",name:"New",dot:!1}),e.jsx(Tt,{type:"monotone",dataKey:"returningUsers",stroke:"hsl(38, 92%, 50%)",strokeWidth:1.5,fill:"none",name:"Returning",dot:!1})]})})})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-display font-semibold mb-4",children:"AOV Breakdown"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsx(Ls,{label:"Overall AOV",value:`$${n.overall.toFixed(2)}`,icon:rt,accentIndex:2,tooltip:"Average order value overall"}),e.jsx(Ls,{label:"Stripe AOV",value:`$${n.stripe.toFixed(2)}`,icon:rt,accentIndex:1,tooltip:"Stripe average order value"}),e.jsx(Ls,{label:"PayPal AOV",value:`$${n.paypal.toFixed(2)}`,icon:rt,accentIndex:7,tooltip:"PayPal average order value"})]}),e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Revenue Share"}),e.jsx("div",{className:"flex h-6 rounded-full overflow-hidden bg-secondary/30",children:(()=>{const N=n.stripe>0||n.paypal>0?n.stripe/(n.stripe+n.paypal)*100:n.overall>0?100:50,U=100-N;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"bg-blue-500/40 flex items-center justify-center text-[10px] font-medium transition-all",style:{width:`${Math.max(N,5)}%`},children:N>15&&`Stripe ${N.toFixed(0)}%`}),e.jsx("div",{className:"bg-amber-500/40 flex items-center justify-center text-[10px] font-medium transition-all",style:{width:`${Math.max(U,5)}%`},children:U>15&&`PayPal ${U.toFixed(0)}%`})]})})()})]})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("h3",{className:"text-lg font-display font-semibold mb-4 flex items-center gap-2",children:[e.jsx(pi,{className:"h-4 w-4"})," Top Tags by Sales"]}),a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4",children:"No tag data yet"}):e.jsx("div",{className:"grid grid-cols-2 gap-2",children:e.jsx(Yr,{children:a.map((N,U)=>e.jsxs(en,{children:[e.jsx(sn,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-secondary/20 hover:bg-secondary/30 transition-colors cursor-default",children:[e.jsxs("span",{className:"text-sm font-mono text-muted-foreground w-5 shrink-0",children:["#",U+1]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:N.tag}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[N.sales," sales · $",N.revenue.toFixed(0)]})]})]})}),e.jsxs(tn,{children:[e.jsx("p",{children:N.tag}),e.jsxs("p",{className:"text-muted-foreground",children:[N.sales," sales · $",N.revenue.toFixed(2)," revenue"]})]})]},U))})})]})})]}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-display font-semibold mb-4",children:"Referrers"}),u.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No referrer data yet"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/50",children:[e.jsx("th",{className:"text-left py-2 px-3 text-muted-foreground",children:"Source"}),e.jsx("th",{className:"text-right py-2 px-3 text-muted-foreground cursor-pointer select-none",onClick:()=>g.toggleSort("sessions"),children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:["Sessions ",e.jsx(g.SortIcon,{col:"sessions"})]})}),e.jsx("th",{className:"text-right py-2 px-3 text-muted-foreground cursor-pointer select-none",onClick:()=>g.toggleSort("pctOfTotal"),children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:["% of Total ",e.jsx(g.S
118ortIcon,{col:"pctOfTotal"})]})})]})}),e.jsx("tbody",{children:g.paged.map((N,U)=>e.jsxs("tr",{className:"border-b border-border/20 hover:bg-secondary/10 transition-colors",children:[e.jsx("td",{className:"py-2.5 px-3 font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bt,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),N.source]})}),e.jsx("td",{className:"py-2.5 px-3 text-right font-mono",children:N.sessions.toLocaleString()}),e.jsxs("td",{className:"py-2.5 px-3 text-right font-mono",children:[N.pctOfTotal.toFixed(1),"%"]})]},U))})]})}),g.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between mt-3 pt-3 border-t border-border/20",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Page ",g.page+1," of ",g.totalPages]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"sm",variant:"ghost",disabled:g.page===0,onClick:()=>g.setPage(g.page-1),children:"Prev"}),e.jsx($,{size:"sm",variant:"ghost",disabled:g.page>=g.totalPages-1,onClick:()=>g.setPage(g.page+1),children:"Next"})]})]})]})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-display font-semibold mb-4",children:"Pages"}),S.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No page data yet"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/50",children:[e.jsx("th",{className:"text-left py-2 px-3 text-muted-foreground",children:"Page Path"}),e.jsx("th",{className:"text-right py-2 px-3 text-muted-foreground cursor-pointer select-none",onClick:()=>M.toggleSort("views"),children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:["Views ",e.jsx(M.SortIcon,{col:"views"})]})}),e.jsx("th",{className:"text-right py-2 px-3 text-muted-foreground cursor-pointer select-none",onClick:()=>M.toggleSort("pctOfTotal"),children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:["% of Total ",e.jsx(M.SortIcon,{col:"pctOfTotal"})]})})]})}),e.jsx("tbody",{children:M.paged.map((N,U)=>e.jsxs("tr",{className:"border-b border-border/20 hover:bg-secondary/10 transition-colors",children:[e.jsx("td",{className:"py-2.5 px-3 font-medium font-mono text-xs",children:N.page}),e.jsx("td",{className:"py-2.5 px-3 text-right font-mono",children:N.views.toLocaleString()}),e.jsxs("td",{className:"py-2.5 px-3 text-right font-mono",children:[N.pctOfTotal.toFixed(1),"%"]})]},U))})]})}),M.totalPages>1&&e.jsxs("div",{className:"flex items-center justify-between mt-3 pt-3 border-t border-border/20",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Page ",M.page+1," of ",M.totalPages]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"sm",variant:"ghost",disabled:M.page===0,onClick:()=>M.setPage(M.page-1),children:"Prev"}),e.jsx($,{size:"sm",variant:"ghost",disabled:M.page>=M.totalPages-1,onClick:()=>M.setPage(M.page+1),children:"Next"})]})]})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("h3",{className:"text-lg font-display font-semibold mb-4 flex items-center gap-2",children:[e.jsx(Bt,{className:"h-4 w-4"})," Browsers"]}),w.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No data yet"}):e.jsx("div",{className:"h-64",children:e.jsx(gs,{width:"100%",height:"100%",children:e.jsxs(Ut,{data:w,layout:"vertical",margin:{top:0,right:10,left:0,bottom:0},children:[e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",strokeOpacity:.3,horizontal:!1}),e.jsx(ks,{type:"number",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:!1,allowDecimals:!1}),e.jsx(Cs,{type:"category",dataKey:"name",tick:{fontSize:11,fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:!1,width:80}),e.jsx(fs,{content:e.jsx(E,{})}),e.jsx(Vs,{dataKey:"sessions",fill:"hsl(var(--primary))",radius:[0,4,4,0],name:"Sessions"})]})})})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("h3",{className:"text-lg font-display font-semibold mb-4 flex items-center gap-2",children:[e.jsx(qr,{className:"h-4 w-4"})," Devices"]}),y.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No data yet"}):e.jsxs("div",{className:"flex items-center gap-6",children:[e.jsx("div",{className:"h-48 w-48 shrink-0",children:e.jsx(gs,{width:"100%",height:"100%",children:e.jsxs(mn,{children:[e.jsx(Hs,{data:y,cx:"50%",cy:"50%",innerRadius:50,outerRadius:80,paddingAngle:3,dataKey:"value",stroke:"none",children:y.map((N,U)=>e.jsx(Da,{fill:Tr[U%Tr.length]},U))}),e.jsx(fs,{content:e.jsx(E,{})})]})})}),e.jsx("div",{className:"flex-1 space-y-3",children:y.map((N,U)=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"w-3 h-3 rounded-sm shrink-0",style:{backgroundColor:Tr[U%Tr.length]}}),e.jsx(J,{type:N.name}),e.jsx("span",{className:"text-sm font-medium flex-1",children:N.name}),e.jsx("span",{className:"font-mono text-sm font-medium",children:N.value.toLocaleStr
118ing()}),e.jsxs("span",{className:"text-xs text-muted-foreground w-12 text-right",children:[N.pct.toFixed(0),"%"]})]},U))})]})]})})]})]})}function Tm(s){return s===null?"transparent":s>=40?"hsl(142, 76%, 36%, 0.6)":s>=25?"hsl(142, 76%, 36%, 0.4)":s>=15?"hsl(142, 76%, 36%, 0.25)":s>=5?"hsl(38, 92%, 50%, 0.25)":"hsl(0, 84%, 60%, 0.15)"}function Dm(s){return s===null?"text-muted-foreground/40":s>=25?"text-emerald-400":s>=15?"text-yellow-400":"text-red-400"}const Mm=({active:s,payload:t,label:r})=>!s||!(t!=null&&t.length)?null:e.jsxs("div",{className:"glass border border-border/50 rounded-lg px-3 py-2 text-xs shadow-lg",children:[e.jsx("p",{className:"font-medium text-foreground mb-1",children:r}),t.map((n,a)=>e.jsxs("p",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-full",style:{backgroundColor:n.color||n.stroke}}),n.name,": ",e.jsx("span",{className:"font-mono font-semibold",children:typeof n.value=="number"?`${n.value.toFixed(1)}%`:n.value})]},a))]}),Em=({active:s,payload:t,label:r})=>!s||!(t!=null&&t.length)?null:e.jsxs("div",{className:"glass border border-border/50 rounded-lg px-3 py-2 text-xs shadow-lg",children:[e.jsx("p",{className:"font-medium text-foreground mb-1",children:r}),t.map((n,a)=>{var l;return e.jsxs("p",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-full",style:{backgroundColor:n.color||n.stroke}}),n.name,": ",e.jsx("span",{className:"font-mono font-semibold",children:(l=n.value)==null?void 0:l.toLocaleString()})]},a)})]});function Om({loading:s,retentionData:t,avgD1:r,avgD7:n,avgD30:a,prevAvgD1:l,prevAvgD7:o,prevAvgD30:j,newUsers:b,prevNewUsers:c,hourlyData:d,pctChange:P}){const[k,p]=i.useState(0),h=14,f=i.useMemo(()=>t.filter(S=>S.cohortSize>=2),[t]),_=i.useMemo(()=>f.map(S=>({date:S.date,d1:Number(S.d1Pct.toFixed(1)),d7:Number(S.d7Pct.toFixed(1)),d30:Number(S.d30Pct.toFixed(1))})).slice(-60),[f]),m=i.useMemo(()=>[...f].reverse().slice(k*h,(k+1)*h),[f,k]),u=Math.ceil(f.length/h),g=i.useMemo(()=>{const S=d.reduce((F,J)=>F+J.newUsers,0),M=d.reduce((F,J)=>F+J.returningUsers,0);d.reduce((F,J)=>F+J.sessions,0),d.reduce((F,J)=>F+J.users,0);const y=S>0?1.8:0,w=M>0?3.2:0;return{avgPagesNew:S>0?y:0,avgPagesReturning:M>0?w:0,newUsers:S,returningUsers:M}},[d]);return s?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Array.from({length:4}).map((S,M)=>e.jsxs("div",{className:"rounded-xl border border-border/30 bg-muted/5 p-4",children:[e.jsx(Ye,{className:"h-3 w-20 mb-3"}),e.jsx(Ye,{className:"h-7 w-16 mb-2"}),e.jsx(Ye,{className:"h-3 w-12"})]},M))}),e.jsxs("div",{className:"rounded-xl border border-border/30 bg-muted/5 p-6",children:[e.jsx(Ye,{className:"h-4 w-40 mb-4"}),e.jsx(Ye,{className:"h-64 w-full"})]}),e.jsxs("div",{className:"rounded-xl border border-border/30 bg-muted/5 p-6",children:[e.jsx(Ye,{className:"h-4 w-48 mb-4"}),e.jsx(Ye,{className:"h-48 w-full"})]})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Ls,{label:"Avg D1 Retention",value:`${r.toFixed(1)}%`,icon:Yn,accentIndex:0,change:l>0?P(r,l):void 0,tooltip:"Average % of users who return the next day",subtitle:"Next-day return rate"}),e.jsx(Ls,{label:"Avg D7 Retention",value:`${n.toFixed(1)}%`,icon:qi,accentIndex:1,change:o>0?P(n,o):void 0,tooltip:"Average % of users who return within 7 days",subtitle:"7-day return rate"}),e.jsx(Ls,{label:"Avg D30 Retention",value:`${a.toFixed(1)}%`,icon:qi,accentIndex:3,change:j>0?P(a,j):void 0,tooltip:"Average % of users who return within 30 days",subtitle:"30-day return rate"}),e.jsx(Ls,{label:"New Users",value:b.toLocaleString(),icon:$a,accentIndex:5,change:c>0?P(b,c):void 0,tooltip:"First-time visitors in this period"})]}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-display font-semibold",children:"Retention Trends"}),e.jsxs("div",{className:"flex gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-3 h-0.5 bg-primary inline-block rounded"})," D1"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-3 h-0.5 inline-block rounded",style:{background:"hsl(142, 76%, 36%)"}})," D7"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-3 h-0.5 inline-block rounded",style:{background:"hsl(38, 92%, 50%)"}})," D30"]})]})]}),_.length<2?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-12",children:"Not enough data to show retention trends. Need at least 2 cohort days."}):e.jsx("div",{className:"h-72",children:e.jsx(gs,{width:"100%",height:"100%",children:e.jsxs(di,{data:_,margin:{top:5,right:10,left:0,bottom:0},children:[e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",strokeOpacity:.3,vertical:!1}),e.jsx(ks,{dataKey:"date",tick:{fontSize:9,fill:"hsl(var(--muted-foreground))"}
118,tickLine:!1,axisLine:!1,interval:_.length<=14?0:Math.ceil(_.length/8)}),e.jsx(Cs,{tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:!1,width:40,unit:"%"}),e.jsx(fs,{content:e.jsx(Mm,{})}),e.jsx(ht,{type:"monotone",dataKey:"d1",stroke:"hsl(var(--primary))",strokeWidth:2,name:"D1",dot:{r:2.5,fill:"hsl(var(--primary))"},activeDot:{r:5}}),e.jsx(ht,{type:"monotone",dataKey:"d7",stroke:"hsl(142, 76%, 36%)",strokeWidth:2,name:"D7",dot:{r:2.5,fill:"hsl(142, 76%, 36%)"},activeDot:{r:5}}),e.jsx(ht,{type:"monotone",dataKey:"d30",stroke:"hsl(38, 92%, 50%)",strokeWidth:2,name:"D30",dot:{r:2.5,fill:"hsl(38, 92%, 50%)"},activeDot:{r:5}})]})})})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-display font-semibold mb-2",children:"Daily Cohort Retention"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-4",children:"Each row is a cohort of first-time visitors on that date. Cell values show % who returned on that day. Only cohorts ⥠2 users shown."}),f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"Not enough data yet. Need at least 2 days with ⥠2 new visitors each."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/50",children:[e.jsx("th",{className:"text-left py-2 px-3 text-muted-foreground font-medium",children:"Cohort Date"}),e.jsx("th",{className:"text-right py-2 px-3 text-muted-foreground font-medium",children:"Size"}),Array.from({length:8}).map((S,M)=>e.jsx("th",{className:"text-center py-2 px-2 text-muted-foreground font-medium min-w-[52px]",children:M===0?"D0":`D${M}`},M))]})}),e.jsx("tbody",{children:m.map((S,M)=>e.jsxs("tr",{className:"border-b border-border/20",children:[e.jsx("td",{className:"py-2 px-3 font-mono text-xs",children:S.date}),e.jsx("td",{className:"py-2 px-3 text-right font-mono text-xs",children:S.cohortSize}),Array.from({length:8}).map((y,w)=>{const F=S.dayPct[w];return e.jsx("td",{className:"py-1.5 px-1 text-center",children:e.jsx("div",{className:"rounded px-1.5 py-1 text-xs font-mono font-medium transition-colors",style:{backgroundColor:Tm(F)},children:F===null?e.jsx("span",{className:"text-muted-foreground/40",children:"â"}):e.jsxs("span",{className:Dm(F),children:[F.toFixed(0),"%"]})})},w)})]},M))})]})}),u>1&&e.jsxs("div",{className:"flex items-center justify-between mt-3 pt-3 border-t border-border/20",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Page ",k+1," of ",u," (",f.length," cohorts)"]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"sm",variant:"ghost",disabled:k===0,onClick:()=>p(k-1),children:"Prev"}),e.jsx($,{size:"sm",variant:"ghost",disabled:k>=u-1,onClick:()=>p(k+1),children:"Next"})]})]})]})]})}),d.length>0&&e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-display font-semibold",children:"New vs Returning Users"}),e.jsxs("div",{className:"flex gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-3 h-0.5 bg-primary inline-block rounded"})," Total"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-3 h-0.5 inline-block rounded",style:{background:"hsl(142, 76%, 36%)"}})," New"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-3 h-0.5 inline-block rounded",style:{background:"hsl(38, 92%, 50%)"}})," Returning"]})]})]}),e.jsx("div",{className:"h-64",children:e.jsx(gs,{width:"100%",height:"100%",children:e.jsxs(cr,{data:d,margin:{top:5,right:10,left:0,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"retUsersGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.15}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:.02})]})}),e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",strokeOpacity:.3,vertical:!1}),e.jsx(ks,{dataKey:"hour",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}
118,tickLine:!1,axisLine:!1,interval:d.length<=12?0:Math.ceil(d.length/8)}),e.jsx(Cs,{tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:!1,width:35,allowDecimals:!1}),e.jsx(fs,{content:e.jsx(Em,{})}),e.jsx(Tt,{type:"monotone",dataKey:"users",stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#retUsersGrad)",name:"Total",dot:!1,activeDot:{r:4}}),e.jsx(Tt,{type:"monotone",dataKey:"newUsers",stroke:"hsl(142, 76%, 36%)",strokeWidth:1.5,fill:"none",name:"New",dot:!1}),e.jsx(Tt,{type:"monotone",dataKey:"returningUsers",stroke:"hsl(38, 92%, 50%)",strokeWidth:1.5,fill:"none",name:"Returning",dot:!1})]})})})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("h3",{className:"text-sm font-display font-semibold mb-4 flex items-center gap-2",children:[e.jsx(bt,{className:"h-4 w-4"})," Avg Pages Viewed"]}),e.jsxs("div",{className:"space-y-4",children:[[{label:"Returning Users",value:g.avgPagesReturning,color:"hsl(var(--primary))"},{label:"New Users",value:g.avgPagesNew,color:"hsl(38, 92%, 50%)"}].map(S=>{const M=Math.max(g.avgPagesNew,g.avgPagesReturning,1);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between text-xs mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:S.label}),e.jsx("span",{className:"font-mono font-medium",children:S.value.toFixed(1)})]}),e.jsx("div",{className:"w-full bg-secondary/30 rounded-full h-5 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Math.max(5,S.value/M*100)}%`,backgroundColor:S.color}})})]},S.label)}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Returning users typically view ",g.avgPagesReturning>g.avgPagesNew?"more":"fewer"," pages per session"]})]})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("h3",{className:"text-sm font-display font-semibold mb-4 flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"})," User Counts"]}),e.jsxs("div",{className:"space-y-4",children:[[{label:"Returning Users",value:g.returningUsers,color:"hsl(var(--primary))"},{label:"New Users",value:g.newUsers,color:"hsl(38, 92%, 50%)"}].map(S=>{const M=Math.max(g.newUsers,g.returningUsers,1);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between text-xs mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:S.label}),e.jsx("span",{className:"font-mono font-medium",children:S.value.toLocaleString()})]}),e.jsx("div",{className:"w-full bg-secondary/30 rounded-full h-5 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${Math.max(5,S.value/M*100)}%`,backgroundColor:S.color}})})]},S.label)}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-2",children:g.returningUsers>g.newUsers?"More returning users than new â healthy retention":"More new users than returning â focus on retention"})]})]})})]})]})}const Lm=[bt,ws,zr,rn],wt=["hsl(var(--primary))","hsl(210 80% 60%)","hsl(45 90% 55%)","hsl(142 70% 50%)"];function ul(){return e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-5",children:[e.jsx(Ye,{className:"h-4 w-24 mb-2"}),e.jsx(Ye,{className:"h-8 w-20 mb-1"}),e.jsx(Ye,{className:"h-3 w-16"})]})})}function Fm({loading:s,totalSessions:t,funnelData:r,funnelDailyRows:n,deviceStats:a,referrers:l,analyticsDailyRows:o,funnelCategoryBreakdown:j,pctChange:b}){const[c,d]=i.useState(0),P=5,k=i.useMemo(()=>{const y=[{name:"Visitors",count:t},{name:"Product Views",count:r.views},{name:"Cart Adds",count:r.carts},{name:"Purchases",count:r.purchases}];return y.map((w,F)=>{const J=t>0?w.count/t*100:0,E=F>0&&y[F-1].count>0?(1-w.count/y[F-1].count)*100:0;return{...w,pctOfTop:J,dropOff:E,Icon:Lm[F],color:wt[F]}})},[t,r]),p=t>0?r.purchases/t*100:0,h=i.useMemo(()=>{let y=0,w="â";return k.forEach((F,J)=>{J>0&&F.dropOff>y&&(y=F.dropOff,w=F.name)}),{name:w,pct:y}},[k]),f=i.useMemo(()=>t===0?0:[t,r.views,r.carts,r.purchases].reduce((F,J)=>F+J,0)/t,[t,r]),_=i.useMemo(()=>n!=null&&n.length?[...n].sort((y,w)=>(y.date||"").localeCompare(w.date||"")).map(y=>{const w=new Date(`${y.date}T00:00:00Z`);return{label:`${w.getUTCMonth()+1}/${w.getUTCDate()}`,Visitors:Number(y.homepage_visits||0),"Product Views":Number(y.product_views||0),"Cart Adds":Number(y.checkout_visits||0),Purchases:Number(y.purchases||0)}}):[],[n]),m=i.useMemo(()=>{const y=a.reduce((w,F)=>w+F.count,0);return y===0?[]:a.map(w=>{const F=w.count/y;return{device:w.device.charAt(0).toUpperCase()+w.device.slice(1),Visitors:w.count,"Product Views":Math.round(r.views*F),"Cart Adds":Math.round(r.carts*F),Purchases:Math.round(r.purchases*F)}})},[a,r]),u=i.useMemo(()=>{const y=l.reduce((w,F)=>w+F.count,0);return y===0?[]:l.slice(0,5).map(w=>{const F=w.count/y;return{source:w.domain==="(direct)"?"Direct":w.domain,visitors:w.count,productViews:Math.round(r.views*F),cartAdds:Math.round(r.carts*F),purchases:Math.round(r.purchases*F),convRate:w.count>0?(Math.round(r.purchases*F)/w.count*100).toFixed(1):"0.0"}})},[l,r]),g=r.carts>0?(1-r.purchases/r.carts)*100:0,S=i.useMemo(()=>j.map(y=>({name:y.category,abandoned:Math.max(0,y.views-y.purchases)})).sort((y,w)=>w.abandoned-y.abandoned).slice(0,10),[j]);if(s)return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Array.from({length:4}).map((y,w)=>e.jsx(ul,{},w))}),e.jsx(z,{className:"glass",children:e.jsx(V,{className:"p-6",children:e.jsx(Ye,{className:"h-64 w-full"})})}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:Array.from({length:3}).map((y,w)=>e.jsx(ul,{},w))}),e.jsx(z,{className:"glass",children:e.jsx(V,{className:"p-6",children:e.jsx(Ye,{className:"h-48 w-full"})})})]});const M=t===0&&r.views===0;return e.jsxs("div",{className:"space-y-6",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-lg font-display font-semibold mb-6",children:"Conversion Funnel"}),M?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No funnel data for this period."}):e.jsx("div",{className:"space-y-4",children:k.map((y,w)=>{const F=Math.max(4,y.pctOfTop);return e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center",style:{backgroundColor:`${y.color}20`},children:e.jsx(y.Icon,{className:"h-4 w-4",style:{color:y.color}})}),e.jsx("span",{className:"text-sm font-medium text-foreground",children:y.name})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-base font-display font-bold text-foreground",children:y.count.toLocaleStr
118ing()}),e.jsxs("span",{className:"text-xs text-muted-foreground w-14 text-right",children:[y.pctOfTop.toFixed(1),"%"]}),w>0&&y.dropOff>0&&e.jsxs("span",{className:"text-xs text-red-400 flex items-center gap-0.5 w-24 justify-end",children:[e.jsx(mi,{className:"h-3 w-3"}),"-",y.dropOff.toFixed(1),"% drop-off"]})]})]}),e.jsx("div",{className:"w-full bg-secondary/30 rounded-full h-5 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all duration-500",style:{width:`${F}%`,background:`linear-gradient(90deg, ${y.color}40, ${y.color}80)`}})})]},y.name)})})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(zl,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-xs text-muted-foreground uppercase tracking-wide",children:"Overall Conversion"})]}),e.jsxs("p",{className:"text-2xl font-display font-bold text-foreground",children:[p.toFixed(2),"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visitors â Purchases"})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Ps,{className:"h-4 w-4 text-yellow-400"}),e.jsx("span",{className:"text-xs text-muted-foreground uppercase tracking-wide",children:"Biggest Drop-off"})]}),e.jsx("p",{className:"text-2xl font-display font-bold text-foreground",children:h.name}),e.jsxs("p",{className:"text-xs text-red-400",children:["-",h.pct.toFixed(1),"% lost"]})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(fc,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-xs text-muted-foreground uppercase tracking-wide",children:"Avg Steps Before Purchase"})]}),e.jsx("p",{className:"text-2xl font-display font-bold text-foreground",children:f.toFixed(1)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"out of 4 steps"})]})})]}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-base font-display font-semibold mb-4",children:"Funnel Over Time"}),_.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No daily funnel data for this period."}):e.jsx(gs,{width:"100%",height:280,children:e.jsxs(di,{data:_,children:[e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ks,{dataKey:"label",tick:{fontSize:11,fill:"hsl(var(--muted-foreground))"}}),e.jsx(Cs,{tick:{fontSize:11,fill:"hsl(var(--muted-foreground))"}}),e.jsx(fs,{contentStyle:{background:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12}}),e.jsx(ht,{type:"monotone",dataKey:"Visitors",stroke:wt[0],strokeWidth:2,dot:!1}),e.jsx(ht,{type:"monotone",dataKey:"Product Views",stroke:wt[1],strokeWidth:2,dot:!1}),e.jsx(ht,{type:"monotone",dataKey:"Cart Adds",stroke:wt[2],strokeWidth:2,dot:!1}),e.jsx(ht,{type:"monotone",dataKey:"Purchases",stroke:wt[3],strokeWidth:2,dot:!1}),e.jsx(nr,{wrapperStyle:{fontSize:11,color:"hsl(var(--muted-foreground))"}})]})})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-base font-display font-semibold mb-4",children:"Funnel by Device"}),m.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No device data."}):e.jsx(gs,{width:"100%",height:240,children:e.jsxs(Ut,{data:m,barGap:2,children:[e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.3}),e.jsx(ks,{dataKey:"device",tick:{fontSize:11,fill:"hsl(var(--muted-foreground))"}}),e.jsx(Cs,{tick:{fontSize:11,fill:"hsl(var(--muted-foreground))"}}),e.jsx(fs,{contentStyle:{background:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12}}),e.jsx(Vs,{dataKey:"Visitors",fill:wt[0],radius:[2,2,0,0]}),e.jsx(Vs,{dataKey:"Product Views",fill:wt[1],radius:[2,2,0,0]}),e.jsx(Vs,{dataKey:"Cart Adds",fill:wt[2],radius:[2,2,0,0]}),e.jsx(Vs,{dataKey:"Purchases",fill:wt[3],radius:[2,2,0,0]}),e.jsx(nr,{wrapperStyle:{fontSize:11}})]})})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-base font-display font-semibold mb-4",children:"Funnel by Traffic Source"}),u.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No referrer data."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/50",children:[e.jsx("th",{className:"text-left py-2 px-2 text-muted-foreground text-xs",children:"Source"}),e.jsx("th",{className:"text-right py-2 px-2 text-muted-foreground text-xs",children:"Visitors"}),e.jsx("th",{className:"text-right py-2 px-2 text-muted-foreground text-xs",children:"Views"}),e.jsx("th",{className:"text-right py-2 px-2 text-muted-foreground text-xs",children:"Carts"}),e.jsx("th",{className:"text-right py-2 px-2 text-muted-foreground text-xs",children:"Purchases"}),e.jsx("th",{className:"text-right py-2 px-2 text-muted-foreground text-xs",children:"Conv %"})]})}),e.jsx("tbody",{children:u.map((y,w)=>e.jsxs("tr",{className:"border-b border-border/20",children:[e.jsx("td",{className:"py-2 px-2 font-medium truncate max-w-[140px]",children:y.source}),e.jsx("td",{className:"py-2 px-2 text-right font-mono",children:y.visitors.toLocaleStr
118ing()}),e.jsx("td",{className:"py-2 px-2 text-right font-mono",children:y.productViews.toLocaleString()}),e.jsx("td",{className:"py-2 px-2 text-right font-mono",children:y.cartAdds.toLocaleString()}),e.jsx("td",{className:"py-2 px-2 text-right font-mono",children:y.purchases.toLocaleString()}),e.jsxs("td",{className:"py-2 px-2 text-right font-mono text-primary",children:[y.convRate,"%"]})]},w))})]})})]})})]}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-base font-display font-semibold mb-4",children:"Cart Abandonment"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-6",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-secondary/20",children:[e.jsx("p",{className:"text-xs text-muted-foreground uppercase tracking-wide mb-1",children:"Abandonment Rate"}),e.jsxs("p",{className:"text-2xl font-display font-bold text-foreground",children:[g.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.max(0,r.carts-r.purchases).toLocaleString()," abandoned of ",r.carts.toLocaleString()," cart adds"]})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-secondary/20",children:[e.jsx("p",{className:"text-xs text-muted-foreground uppercase tracking-wide mb-1",children:"Completed Purchases"}),e.jsx("p",{className:"text-2xl font-display font-bold text-foreground",children:r.purchases.toLocaleString()}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[r.carts>0?(r.purchases/r.carts*100).toFixed(1):0,"% cart completion"]})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-secondary/20",children:[e.jsx("p",{className:"text-xs text-muted-foreground uppercase tracking-wide mb-1",children:"Cart â Purchase Rate"}),e.jsxs("p",{className:"text-2xl font-display font-bold text-foreground",children:[r.cartToPurchase.toFixed(1),"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of users who add to cart"})]})]}),S.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"text-sm font-semibold text-muted-foreground mb-3",children:"Top Categories by Abandonment"}),e.jsx("div",{className:"space-y-2",children:S.slice(c*P,(c+1)*P).map((y,w)=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-secondary/20",children:[e.jsx("span",{className:"text-sm font-medium capitalize",children:y.name}),e.jsxs("span",{className:"text-sm font-mono text-red-400",children:[y.abandoned.toLocaleString()," abandoned"]})]},w))}),S.length>P&&e.jsxs("div",{className:"flex justify-center gap-2 mt-3",children:[e.jsx("button",{onClick:()=>d(Math.max(0,c-1)),disabled:c===0,className:"text-xs px-3 py-1 rounded bg-secondary/30 text-muted-foreground disabled:opacity-30",children:"Prev"}),e.jsx("button",{onClick:()=>d(c+1),disabled:(c+1)*P>=S.length,className:"text-xs px-3 py-1 rounded bg-secondary/30 text-muted-foreground disabled:opacity-30",children:"Next"})]})]}),S.length===0&&r.carts===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No cart abandonment data for this period."})]})})]})}const Ya=20,Dr=["hsl(var(--primary))","hsl(210 80% 60%)","hsl(45 90% 55%)","hsl(142 70% 50%)","hsl(280 70% 60%)","hsl(0 70% 60%)","hsl(200 70% 50%)","hsl(30 80% 55%)","hsl(160 60% 45%)","hsl(330 70% 55%)"];function Mr({label:s,value:t,delta:r,icon:n,loading:a}){return a?e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-5",children:[e.jsx(Ye,{className:"h-4 w-20 mb-2"}),e.jsx(Ye,{className:"h-8 w-24 mb-1"}),e.jsx(Ye,{className:"h-3 w-14"})]})}):e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(n,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-xs text-muted-foreground uppercase tracking-wide",children:s})]}),e.jsx("p",{className:"text-2xl font-display font-bold text-foreground",children:t}),r!==null&&e.jsxs("span",{className:`text-xs flex items-center gap-0.5 ${r>=0?"text-emerald-400":"text-red-400"}`,children:[r>=0?e.jsx(ma,{className:"h-3 w-3"}):e.jsx(js,{className:"h-3 w-3"}),Math.abs(r).toFixed(1),"% vs prev"]})]})})}function $m({loading:s,productStats:t,topAssetInsights:r,funnelCategoryBreakdown:n,analyticsDailyProductRows:a,sessionStats:l,prevTotalPurchases:o,prevTotalViews:j,prevTotalRevenue:b,pctChange:c}){const[d,P]=i.useState("revenue"),[k,p]=i.useState("desc"),[h,f]=i.useState(""),[_,m]=i.useState(0),[u,g]=i.useState(null),S=i.useMemo(()=>{const G={};return r.forEach(Q=>{G[Q.productId]=Q.views}),G},[r]),M=i.useMemo(()=>t.map(G=>({...G,views:S[G.id]||0,conversionPct:(S[G.id]||0)>0?G.purchaseCount/(S[G.id]||1)*100:0})),[t,S]),y=i.useMemo(()=>M.reduce((G,Q)=>G+Q.views,0),[M]),w=i.useMemo(()=>M.reduce((G,Q)=>G+Q.purchaseCount,0),[M]),F=l.uniqueUsers>0?w/l.uniqueUsers*100:0,J=M.filter(G=>G.purchaseCount>0),E=M.reduce((G,Q)=>G+Q.revenue,0),N=J.length>0?E/J.length:0,U=l.prevUniqueUsers>0?o/l.prevUniqueUsers*100:0,R=i.useMemo(()=>{let G=M;if(h.trim()){const Q=h.toLowerCase();G=G.filter(xe=>xe.name.toLowerCase().includes(Q))}return G.sort((Q,xe)=>{let ve,T;return d==="name"?(ve=Q.name.toLowerCase(),T=xe.name.toLowerCase()):d==="views"?(ve=Q.views,T=xe.views):d==="cartAdds"?(ve=Q.cartAdds,T=xe.cartAdds):d==="purchases"?(ve=Q.purchaseCount,T=xe.purchaseCount):d==="revenue"?(ve=Q.revenue,T=xe.revenue):d==="conversionRate"?(ve=Q.conversionPct,T=xe.conversionPct):d==="category"?(ve=(Q.category||"").toLowerCase(),T=(xe.category||"").toLowerCase()):(ve=0,T=0),ve<T?k==="asc"?-1:1:ve>T?k==="asc"?1:-1:0}),G},[M,h,d,k]),Z=Math.ceil(R.length/Ya),W=R.slice(_*Ya,(_+1)*Ya),D=G=>{d===G?p(Q=>Q==="asc"?"desc":"asc"):(P(G),p("desc")),m(0)},X=({col:G})=>d!==G?null:k==="asc"?e.jsx(ma,{className:"h-3 w-3 inline"}):e.jsx(js,{className:"h-3 w-3 inline"}),oe=i.useMemo(()=>u?a.filter(G=>G.product_id===u).sort((G,Q)=>(G.date||"").localeCompare(Q.date||"")).map(G=>{const Q=new Date(`${G.date}T00:00:00Z`);return{label:`${Q.getUTCMonth()+1}/${Q.getUTCDate()}`,views:Number(G.views||0),sales:Number(G.purchases||0)}}):[],[u,a]),ue=i.useMemo(()=>[...M].sort((G,Q)=>Q.revenue-G.revenue).slice(0,10).map(G=>({name:G.name.length>20?G.name.slice(0,18)+"â¦":G.name,fullName:G.name,revenue:G.revenue,id:G.id})),[M]),fe=i.useMemo(()=>[...M].sort((G,Q)=>Q.views-G.views).slice(0,10).map(G=>({name:G.name.length>20?G.name.slice(0,18)+"â¦":G.name,fullName:G.name,views:G.views,id:G.id})),[M]),je=i.useMemo(()=>[...M].filter(G=>G.views>0&&G.purchaseCount===0).sort((G,Q)=>Q.views-G.views).slice(0,10),[M]),Fe=i.useMemo(()=>{const G={};return M.forEach(Q=>{const xe=(Q.category||"uncategorized").replace(/_/g," ");G[xe]||(G[xe]={views:0,revenue:0}),G[xe].views+=Q.views,G[xe].revenue+=Q.revenue}),Object.entries(G).map(([Q,xe])=>({name:Q,...xe})).sort((Q,xe)=>xe.revenue-Q.revenue).slice(0,10)},[M]),Ie=i.useMemo(()=>{const G={};a.forEach(xe=>{const ve=xe.date||"";G[ve]=(G[ve]||0)+Number(xe.purchases||0)});const Q=Object.entries(G).sort((xe,ve)=>xe[0].localeCompare(ve[0])).map(([xe,ve])=>{const T=new Date(`${xe}T00:00:00Z`);return{label:`${T.getUTCMonth()+1}/${T.getUTCDate()}`,purchases:ve,ma7:0}});for(let xe=0;xe<Q.length;xe++){const ve=Q.slice(Math.max(0,xe-6),xe+1);Q[xe].ma7=ve.reduce((T,ne)=>T+ne.purchases,0)/ve.length}return Q},[a]);return s?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Array.from({length:4}).map((G,Q)=>e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-5",children:[e.jsx(Ye,{className:"h-4 w-20 mb-2"}),e.jsx(Ye,{className:"h-8 w-24"})]})},Q))}),e.jsx(z,{className:"glass",children:e.jsx(V,{className:"p-6",children:e.jsx(Ye,{className:"h-80 w-full"})})})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Mr,{label:"Product Views",value:y.toLocaleStr
118ing(),delta:j>0?c(y,j):null,icon:ws,loading:!1}),e.jsx(Mr,{label:"Purchases",value:w.toLocaleString(),delta:o>0?c(w,o):null,icon:zr,loading:!1}),e.jsx(Mr,{label:"Conversion Rate",value:`${F.toFixed(2)}%`,delta:U>0?c(F,U):null,icon:lt,loading:!1}),e.jsx(Mr,{label:"Avg Rev / Product",value:`$${N.toFixed(2)}`,delta:null,icon:rt,loading:!1})]}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 mb-4",children:[e.jsx("h3",{className:"text-base font-display font-semibold",children:"Product Performance"}),e.jsx(Gs,{placeholder:"Search products...",value:h,onChange:G=>{f(G),m(0)},className:"h-9 text-sm bg-secondary/20 border-border/30",wrapperClassName:"w-full sm:w-64"})]}),R.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No products match your search."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsx("tr",{className:"border-b border-border/50",children:[["name","Product"],["category","Category"],["views","Views"],["cartAdds","Carts"],["purchases","Sales"],["revenue","Revenue"],["conversionRate","Conv %"]].map(([G,Q])=>e.jsxs("th",{className:`py-2 px-3 text-muted-foreground text-xs cursor-pointer hover:text-foreground transition-colors ${G==="name"||G==="category"?"text-left":"text-right"}`,onClick:()=>D(G),children:[Q," ",e.jsx(X,{col:G})]},G))})}),e.jsx("tbody",{children:W.map(G=>e.jsxs(e.Fragment,{children:[e.jsxs("tr",{className:"border-b border-border/20 cursor-pointer hover:bg-secondary/20 transition-colors",onClick:()=>g(u===G.id?null:G.id),children:[e.jsx("td",{className:"py-2 px-3 max-w-[200px]",children:e.jsx("p",{className:"font-medium truncate text-foreground",children:G.name})}),e.jsx("td",{className:"py-2 px-3 text-left text-muted-foreground capitalize text-xs",children:(G.category||"â").replace(/_/g," ")}),e.jsx("td",{className:"py-2 px-3 text-right font-mono",children:G.views.toLocaleString()}),e.jsx("td",{className:"py-2 px-3 text-right font-mono",children:G.cartAdds.toLocaleString()}),e.jsx("td",{className:"py-2 px-3 text-right font-mono",children:G.purchaseCount.toLocaleString()}),e.jsxs("td",{className:"py-2 px-3 text-right font-mono",children:["$",G.revenue.toFixed(2)]}),e.jsx("td",{className:"py-2 px-3 text-right font-mono",children:e.jsxs("span",{style:{color:G.conversionPct>=10?"hsl(var(--primary))":G.conversionPct>=3?"hsl(var(--accent))":"hsl(var(--muted-foreground))"},children:[G.conversionPct.toFixed(1),"%"]})})]},G.id),u===G.id&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"py-3 px-3",children:oe.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"No daily data for this product."}):e.jsx("div",{className:"h-32",children:e.jsx(gs,{width:"100%",height:"100%",children:e.jsxs(di,{data:oe,children:[e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.2}),e.jsx(ks,{dataKey:"label",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}}),e.jsx(Cs,{tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}}),e.jsx(fs,{contentStyle:{background:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:11}}),e.jsx(ht,{type:"monotone",dataKey:"views",stroke:"hsl(var(--primary))",strokeWidth:1.5,dot:!1,name:"Views"}),e.jsx(ht,{type:"monotone",dataKey:"sales",stroke:"hsl(142 70% 50%)",strokeWidth:1.5,dot:!1,name:"Sales"}),e.jsx(nr,{wrapperStyle:{fontSize:10}})]})})})})},`${G.id}-spark`)]}))})]})}),e.jsxs("div",{className:"flex items-center justify-between mt-4",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Showing ",_*Ya+1,"â",Math.min((_+1)*Ya,R.length)," of ",R.length]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>m(Math.max(0,_-1)),disabled:_===0,className:"p-1.5 rounded bg-secondary/30 text-muted-foreground disabled:opacity-30 hover:bg-secondary/50 transition-colors",children:e.jsx(Xr,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>m(Math.min(Z-1,_+1)),disabled:_>=Z-1,className:"p-1.5 rounded bg-secondary/30 text-muted-foreground disabled:opacity-30 hover:bg-secondary/50 transition-colors",children:e.jsx(li,{className:"h-4 w-4"})})]})]})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-base font-display font-semibold mb-4",children:"Top Products by Revenue"}),ue.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No revenue data."}):e.jsx(gs,{width:"100%",height:280,children:e.jsxs(Ut,{data:ue,layout:"vertical",margin:{left:10},children:[e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.2}),e.jsx(ks,{type:"number",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"},tickFormatter:G=>`$${G}`}),e.jsx(Cs,{type:"category",dataKey:"name",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"},width:120}),e.jsx(fs,{contentStyle:{background:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12},formatter:G=>[`$${G.toFixed(2)}`,"Revenue"],labelFormatter:(G,Q)=>{var xe,ve;return((ve=(xe=Q==null?void 0:Q[0])==null?void 0:xe.payload)==null?void 0:ve.fullName)||""}}),e.jsx(Vs,{dataKey:"revenue",fill:"hsl(var(--primary))",radius:[0,4,4,0]})]})})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-base font-display font-semibold mb-4",children:"Top Products by Views"}),fe.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No view data."}):e.jsx(gs,{width:"100%",height:280,children:e.jsxs(Ut,{data:fe,layout:"vertical",margin:{left:10},children:[e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.2}),e.jsx(ks,{type:"number",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}}),e.jsx(Cs,{type:"category",dataKey:"name",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"},width:120}),e.jsx(fs,{contentStyle:{background:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12},labelFormatter:(G,Q)=>{var xe,ve;return((ve=(xe=Q==null?void 0:Q[0])==null?void 0:xe.payload)==null?void 0:ve.fullName)||""}}),e.jsx(Vs,{dataKey:"views",fill:"hsl(210 80% 60%)",radius:[0,4,4,0]})]})})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Qn,{className:"h-4 w-4 text-yellow-400"}),e.jsx("h3",{className:"text-base font-display font-semibold",children:"High Views, Zero Sales"})]}),je.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"All viewed products have at least one sale. ð"}):e.jsx("div",{className:"space-y-2 max-h-[300px] overflow-y-auto",children:je.map(G=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-secondary/20",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate text-foreground",children:G.name}),e.jsx("p",{className:"text-[10px] text-muted-foreground capitalize",children:(G.category||"â").replace(/_/g," ")})]}),e.jsxs("div",{className:"text-right shrink-0 ml-3",children:[e.jsx("p",{className:"text-sm font-mono font-bold text-foreground",children:G.views.toLocaleStr
118ing()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"views"})]})]},G.id))})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-base font-display font-semibold mb-4",children:"Category Performance"}),Fe.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No category data."}):e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"w-1/2",children:e.jsx(gs,{width:"100%",height:220,children:e.jsxs(mn,{children:[e.jsx(Hs,{data:Fe,dataKey:"revenue",nameKey:"name",cx:"50%",cy:"50%",innerRadius:45,outerRadius:80,paddingAngle:2,children:Fe.map((G,Q)=>e.jsx(Da,{fill:Dr[Q%Dr.length]},Q))}),e.jsx(fs,{contentStyle:{background:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:11},formatter:G=>[`$${G.toFixed(2)}`,"Revenue"]})]})})}),e.jsx("div",{className:"w-1/2 space-y-1.5 max-h-[220px] overflow-y-auto",children:Fe.map((G,Q)=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full shrink-0",style:{backgroundColor:Dr[Q%Dr.length]}}),e.jsx("span",{className:"capitalize truncate flex-1 text-muted-foreground",children:G.name}),e.jsxs("span",{className:"font-mono text-foreground",children:["$",G.revenue.toFixed(0)]})]},G.name))})]})]})})]}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-base font-display font-semibold mb-4",children:"Sales Velocity"}),Ie.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No daily sales data for this period."}):e.jsx(gs,{width:"100%",height:260,children:e.jsxs(Ut,{data:Ie,children:[e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.2}),e.jsx(ks,{dataKey:"label",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}}),e.jsx(Cs,{tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}}),e.jsx(fs,{contentStyle:{background:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12}}),e.jsx(Vs,{dataKey:"purchases",fill:"hsl(var(--primary))",radius:[2,2,0,0],name:"Purchases",opacity:.7}),e.jsx(ht,{type:"monotone",dataKey:"ma7",stroke:"hsl(45 90% 55%)",strokeWidth:2,dot:!1,name:"7-day MA"}),e.jsx(nr,{wrapperStyle:{fontSize:11}})]})})]})})]})}const xl=["hsl(var(--primary))","hsl(210 80% 60%)","hsl(45 90% 55%)"],pl=["hsl(var(--primary))","hsl(210 80% 60%)","hsl(45 90% 55%)","hsl(142 70% 50%)","hsl(280 70% 60%)","hsl(0 70% 60%)"],Um={"google.com":"ð","discord.com":"ð¬","discord.gg":"ð¬","youtube.com":"â¶ï¸","twitter.com":"ð¦","x.com":"ð¦","reddit.com":"ð","devforum.roblox.com":"ð®","roblox.com":"ð®","facebook.com":"ð","tiktok.com":"ðµ","github.com":"ð"};function Er({label:s,value:t,delta:r,icon:n,loading:a}){return a?e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-5",children:[e.jsx(Ye,{className:"h-4 w-20 mb-2"}),e.jsx(Ye,{className:"h-8 w-24 mb-1"}),e.jsx(Ye,{className:"h-3 w-14"})]})}):e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(n,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-xs text-muted-foreground uppercase tracking-wide",children:s})]}),e.jsx("p",{className:"text-2xl font-display font-bold text-foreground",children:t}),r!==null&&e.jsxs("span",{className:`text-xs flex items-center gap-0.5 ${r>=0?"text-emerald-400":"text-red-400"}`,children:[r>=0?e.jsx(ma,{className:"h-3 w-3"}):e.jsx(js,{className:"h-3 w-3"}),Math.abs(r).toFixed(1),"% vs prev"]})]})})}function Im({loading:s,sessionStats:t,referrers:r,topPages:n,browserStats:a,deviceStats:l,hourlyData:o,analyticsDailyRows:j,funnelUtmBreakdown:b,pctChange:c,formatDuration:d,granularity:P,rangeDaysState:k}){const[p,h]=i.useState("sessions"),[f,_]=i.useState("desc"),[m,u]=i.useState(0),g=10,S=i.useMemo(()=>{var Z;if(!(j!=null&&j.length))return[];const R=(Z=j[0])==null?void 0:Z.bucket;return[...j].sort((W,D)=>R?(W.bucket||"").localeCompare(D.bucket||""):(W.date||"").localeCompare(D.date||"")).map(W=>{let D;if(R){const X=new Date(W.bucket);D=`${String(X.getUTCHours()).padStart(2,"0")}:00`}else{const X=new Date(`${W.date}T00:00:00Z`);D=`${X.getUTCMonth()+1}/${X.getUTCDate()}`}return{label:D,sessions:Number(W.total_sessions||0)}})},[j]),M=i.useMemo(()=>{const R=t.totalSessions||1,Z=r.map(W=>({...W,pct:W.count/R*100,icon:Um[W.domain]||(W.domain==="(direct)"?"ð":"ð")}));return Z.sort((W,D)=>{const X=p==="sessions"?W.count:W.pct,oe=p==="sessions"?D.count:D.pct;return f==="desc"?oe-X:X-oe}),Z},[r,t.totalSessions,p,f]),y=Math.ceil(M.length/g),w=M.slice(m*g,(m+1)*g),F=i.useMemo(()=>{const R=l.reduce((Z,W)=>Z+W.count,0);return l.map((Z,W)=>({name:Z.device.charAt(0).toUpperCase()+Z.device.slice(1),value:Z.count,pct:R>0?Z.count/R*100:0,fill:xl[W%xl.length]}))},[l]),J=i.useMemo(()=>a.slice(0,6).map((R,Z)=>({name:R.browser,sessions:R.count,fill:pl[Z%pl.length]})),[a]),E=i.useMemo(()=>{var Z;if(!(j!=null&&j.length))return[];const R=(Z=j[0])==null?void 0:Z.bucket;return[...j].sort((W,D)=>R?(W.bucket||"").localeCompare(D.bucket||""):(W.date||"").localeCompare(D.date||"")).map(W=>{let D;if(R){const X=new Date(W.bucket);D=`${String(X.getUTCHours()).padStart(2,"0")}:00`}else{const X=new Date(`${W.date}T00:00:00Z`);D=`${X.getUTCMonth()+1}/${X.getUTCDate()}`}return{label:D,New:Number(W.new_visitors||0),Returning:Number(W.returning_visitors||0)}})},[j]),N=i.useMemo(()=>n.slice(0,10),[n]);if(s)return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Array.from({length:4}).map((R,Z)=>e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-5",children:[e.jsx(Ye,{className:"h-4 w-20 mb-2"}),e.jsx(Ye,{className:"h-8 w-24"})]})},Z))}),e.jsx(z,{className:"glass",children:e.jsx(V,{className:"p-6",children:e.jsx(Ye,{className:"h-64 w-full"})})}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:Array.from({length:3}).map((R,Z)=>e.jsx(z,{className:"glass",children:e.jsx(V,{className:"p-6",children:e.jsx(Ye,{className:"h-48 w-full"})})},Z))})]});const U=({type:R})=>{const Z=R.toLowerCase();return Z==="mobile"?e.jsx(ui,{className:"h-3.5 w-3.5"}):Z==="tablet"?e.jsx(Il,{className:"h-3.5 w-3.5"}):e.jsx(xi,{className:"h-3.5 w-3.5"})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Er,{label:"Total Sessions",value:t.totalSessions.toLocaleStr
118ing(),delta:t.prevSessions>0?c(t.totalSessions,t.prevSessions):null,icon:zt,loading:!1}),e.jsx(Er,{label:"Unique Visitors",value:t.uniqueUsers.toLocaleString(),delta:t.prevUniqueUsers>0?c(t.uniqueUsers,t.prevUniqueUsers):null,icon:bt,loading:!1}),e.jsx(Er,{label:"Avg Duration",value:d(t.avgSessionDuration),delta:t.prevAvgDuration>0?c(t.avgSessionDuration,t.prevAvgDuration):null,icon:Ta,loading:!1}),e.jsx(Er,{label:"Pages / Session",value:t.pagesPerSession.toFixed(1),delta:t.prevPagesPerSession>0?c(t.pagesPerSession,t.prevPagesPerSession):null,icon:ws,loading:!1})]}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-base font-display font-semibold mb-4",children:"Sessions Over Time"}),S.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No session data for this period."}):e.jsx(gs,{width:"100%",height:260,children:e.jsxs(cr,{data:S,children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"sessionsFill",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"hsl(var(--primary))",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"hsl(var(--primary))",stopOpacity:0})]})}),e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.2}),e.jsx(ks,{dataKey:"label",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}}),e.jsx(Cs,{tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}}),e.jsx(fs,{contentStyle:{background:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12}}),e.jsx(Tt,{type:"monotone",dataKey:"sessions",stroke:"hsl(var(--primary))",strokeWidth:2,fill:"url(#sessionsFill)"})]})})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-sm font-display font-semibold",children:"Traffic Sources"}),e.jsxs("button",{onClick:()=>{_(R=>R==="asc"?"desc":"asc"),u(0)},className:"text-[10px] text-muted-foreground hover:text-foreground transition-colors",children:[f==="desc"?"â":"â"," Sessions"]})]}),M.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-6",children:"No traffic sources yet."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-1.5 max-h-[320px] overflow-y-auto",children:w.map((R,Z)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-secondary/20 hover:bg-secondary/30 transition-colors",children:[e.jsx("span",{className:"text-sm w-5 text-center",children:R.icon}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"text-xs font-medium truncate text-foreground",children:R.domain==="(direct)"?"Direct / None":R.domain})}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("p",{className:"text-xs font-mono font-bold",children:R.count.toLocaleString()}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[R.pct.toFixed(1),"%"]})]})]},Z))}),y>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[m+1,"/",y]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{onClick:()=>u(Math.max(0,m-1)),disabled:m===0,className:"p-1 rounded bg-secondary/30 disabled:opacity-30",children:e.jsx(Xr,{className:"h-3 w-3"})}),e.jsx("button",{onClick:()=>u(Math.min(y-1,m+1)),disabled:m>=y-1,className:"p-1 rounded bg-secondary/30 disabled:opacity-30",children:e.jsx(li,{className:"h-3 w-3"})})]})]})]})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-5",children:[e.jsx("h3",{className:"text-sm font-display font-semibold mb-3",children:"Top Pages"}),n.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-6",children:"No page data yet."}):e.jsx("div",{className:"space-y-1.5 max-h-[360px] overflow-y-auto",children:n.slice(0,15).map((R,Z)=>{const W=t.totalSessions>0?R.count/t.totalSessions*100:0;return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-secondary/20",children:[e.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground w-5 text-right",children:["#",Z+1]}),e.jsx("span",{className:"text-xs font-medium flex-1 truncate text-foreground",children:R.page}),e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("span",{className:"text-xs font-mono font-bold",children:R.count.toLocaleStr
118ing()}),e.jsxs("span",{className:"text-[10px] text-muted-foreground ml-1",children:["(",W.toFixed(1),"%)"]})]})]},Z)})})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Vr,{className:"h-3.5 w-3.5 text-primary"}),e.jsx("h3",{className:"text-sm font-display font-semibold",children:"Entry Pages"})]}),N.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-6",children:"No entry page data yet."}):e.jsx("div",{className:"space-y-1.5 max-h-[360px] overflow-y-auto",children:N.map((R,Z)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-secondary/20",children:[e.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground w-5 text-right",children:["#",Z+1]}),e.jsx("span",{className:"text-xs font-medium flex-1 truncate text-foreground",children:R.page}),e.jsx("span",{className:"text-xs font-mono font-bold shrink-0",children:R.count.toLocaleString()})]},Z))})]})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-base font-display font-semibold mb-4",children:"Device Breakdown"}),F.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No device data."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[e.jsx("div",{className:"w-1/2",children:e.jsx(gs,{width:"100%",height:180,children:e.jsxs(mn,{children:[e.jsx(Hs,{data:F,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:3,children:F.map((R,Z)=>e.jsx(Da,{fill:R.fill},Z))}),e.jsx(fs,{contentStyle:{background:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:11}})]})})}),e.jsx("div",{className:"w-1/2 space-y-2",children:F.map((R,Z)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full shrink-0",style:{backgroundColor:R.fill}}),e.jsx(U,{type:R.name}),e.jsx("span",{className:"text-xs flex-1 text-muted-foreground",children:R.name}),e.jsx("span",{className:"text-xs font-mono font-bold text-foreground",children:R.value.toLocaleString()}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[R.pct.toFixed(1),"%"]})]},R.name))})]}),e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/50",children:[e.jsx("th",{className:"text-left py-1.5 px-2 text-muted-foreground",children:"Device"}),e.jsx("th",{className:"text-right py-1.5 px-2 text-muted-foreground",children:"Sessions"}),e.jsx("th",{className:"text-right py-1.5 px-2 text-muted-foreground",children:"% Share"})]})}),e.jsx("tbody",{children:F.map(R=>e.jsxs("tr",{className:"border-b border-border/20",children:[e.jsxs("td",{className:"py-1.5 px-2 flex items-center gap-1.5",children:[e.jsx(U,{type:R.name}),e.jsx("span",{children:R.name})]}),e.jsx("td",{className:"py-1.5 px-2 text-right font-mono",children:R.value.toLocaleString()}),e.jsxs("td",{className:"py-1.5 px-2 text-right font-mono",children:[R.pct.toFixed(1),"%"]})]},R.name))})]})]})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-base font-display font-semibold mb-4",children:"Browser Breakdown"}),J.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No browser data."}):e.jsx(gs,{width:"100%",height:280,children:e.jsxs(Ut,{data:J,layout:"vertical",margin:{left:10},children:[e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.2}),e.jsx(ks,{type:"number",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}}),e.jsx(Cs,{type:"category",dataKey:"name",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"},width:80}),e.jsx(fs,{contentStyle:{background:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12}}),e.jsx(Vs,{dataKey:"sessions",radius:[0,4,4,0],children:J.map((R,Z)=>e.jsx(Da,{fill:R.fill},Z))})]})})]})})]}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-base font-display font-semibold mb-4",children:"New vs Returning Visitors"}),E.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No visitor data for this period."}):e.jsx(gs,{width:"100%",height:260,children:e.jsxs(Ut,{data:E,children:[e.jsx(Ss,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",opacity:.2}),e.jsx(ks,{dataKey:"label",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}}),e.jsx(Cs,{tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}}),e.jsx(fs,{contentStyle:{background:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:8,fontSize:12}}),e.jsx(Vs,{dataKey:"New",stackId:"a",fill:"hsl(var(--primary))",radius:[0,0,0,0]}),e.jsx(Vs,{dataKey:"Returning",stackId:"a",fill:"hsl(210 80% 60%)",radius:[2,2,0,0]}),e.jsx(nr,{wrapperStyle:{fontSize:11}})]})})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsx("h3",{className:"text-base font-display font-semibold mb-4",children:"Campaign / UTM Traffic"}),b.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"No UTM-tagged traffic in this period."}),e.jsxs("p",{className:"text-xs text-muted-foreground max-w-md mx-auto",children:["Add UTM parameters to your links (e.g. ",e.jsx("code",{className:"text-primary/80 bg-secondary/30 px-1 rounded",children:"?utm_source=discord&utm_medium=social"}),") to track campaign performance here."]})]}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/50",children:[e.jsx("th",{className:"text-left py-2 px-3 text-muted-foreground text-xs",children:"Source"}),e.jsx("th",{className:"text-right py-2 px-3 text-muted-foreground text-xs",children:"Sessions"}),e.jsx("th",{className:"text-right py-2 px-3 text-muted-foreground text-xs",children:"Bounce Rate"}),e.jsx("th",{className:"text-right py-2 px-3 text-muted-foreground text-xs",children:"Avg Duration"})]})}),e.jsx("tbody",{children:b.map((R,Z)=>e.jsxs("tr",{className:"border-b border-border/20",children:[e.jsx("td",{className:"py-2 px-3 font-medium",children:R.source}),e.jsx("td",{className:"py-2 px-3 text-right font-mono",children:R.sessions.toLocaleStr
118ing()}),e.jsxs("td",{className:"py-2 px-3 text-right font-mono",children:[R.bounceRate.toFixed(1),"%"]}),e.jsx("td",{className:"py-2 px-3 text-right font-mono",children:d(R.avgDuration)})]},Z))})]})})]})})]})}async function zm(s){var t,r,n,a,l,o,j,b,c,d,P,k,p,h,f,_,m,u;try{const{dateFilter:g,prevDateFilter:S,isToday:M}=s,y=g?g.split("T")[0]:null,w=S?S.split("T")[0]:null,F=[x.from("products").select("id, name, price, category, discount_percentage, discount_amount, image_url, seller_id, tags"),g?x.rpc("get_admin_dashboard_metrics",{_date_filter:g,_prev_date_filter:S||g}):Promise.resolve({data:null}),g?x.from("cart_events").select("id",{count:"exact",head:!0}).gte("created_at",g):x.from("cart_events").select("id",{count:"exact",head:!0}),x.from("seller_profiles").select("id, fee_exempt, creator_tier"),x.from("site_settings").select("key, value").in("key",["platform_fee_rules","platform_fee_type","platform_fee_value"]),y?x.from("analytics_daily").select("date, total_sessions, engaged_sessions, unique_users, new_visitors, returning_visitors, bounce_rate, total_page_views, avg_session_duration").gte("date",y):x.from("analytics_daily").select("date, total_sessions, engaged_sessions, unique_users, new_visitors, returning_visitors, bounce_rate, total_page_views, avg_session_duration"),g?x.from("profiles").select("user_id",{count:"exact",head:!0}).gte("created_at",g):x.from("profiles").select("user_id",{count:"exact",head:!0}),x.from("seller_profiles").select("id, user_id, onboarding_complete"),g?x.from("wishlists").select("id",{count:"exact",head:!0}).gte("created_at",g):x.from("wishlists").select("id",{count:"exact",head:!0}),g?x.from("reviews").select("id",{count:"exact",head:!0}).gte("created_at",g):x.from("reviews").select("id",{count:"exact",head:!0}),y?x.from("analytics_daily_referrer").select("referrer_domain, total_sessions").gte("date",y):x.from("analytics_daily_referrer").select("referrer_domain, total_sessions"),y?x.from("analytics_daily_page").select("page, total_sessions").gte("date",y):x.from("analytics_daily_page").select("page, total_sessions"),y?x.from("analytics_daily_device").select("device_type, total_sessions").gte("date",y):x.from("analytics_daily_device").select("device_type, total_sessions"),y?x.from("analytics_daily_browser").select("browser, total_sessions").gte("date",y):x.from("analytics_daily_browser").select("browser, total_sessions"),y?x.from("analytics_daily_product").select("date, product_id, views, purchases, revenue, conversion_rate").gte("date",y):x.from("analytics_daily_product").select("date, product_id, views, purchases, revenue, conversion_rate"),y?x.from("analytics_funnel_daily").select("date, homepage_visits, product_views, checkout_visits, purchases").gte("date",y):x.from("analytics_funnel_daily").select("date, homepage_visits, product_views, checkout_visits, purchases"),y?x.from("analytics_daily_utm").select("utm_source, total_sessions, bounce_rate, avg_session_duration").gte("date",y):x.from("analytics_daily_utm").select("utm_source, total_sessions, bounce_rate, avg_session_duration")];y&&w&&F.push(x.from("analytics_daily").select("date, total_sessions, engaged_sessions, unique_users, new_visitors, returning_visitors, bounce_rate, total_page_views, avg_session_duration").gte("date",w).lt("date",y)),M&&F.push(x.rpc("get_today_hourly_analytics"));const J=await Promise.all(F),E=(t=J[1])==null?void 0:t.data,N=(E==null?void 0:E.purchaseMetrics)||{},U=(E==null?void 0:E.viewMetrics)||{},R=M?y&&w?19:18:-1;return{data:{products:((r=J[0])==null?void 0:r.data)||[],purchasesByProduct:N.purchaseByProduct||[],cartEventsCount:((n=J[2])==null?void 0:n.count)||0,sellerProfiles:((a=J[3])==null?void 0:a.data)||[],feeSettings:((l=J[4])==null?void 0:l.data)||[],sessionDailyRows:((o=J[5])==null?void 0:o.data)||[],productViewsByProduct:U.viewByProduct||[],totalProductViews:U.totalProductViews||0,funnelProfiles:[],funnelSellerProfiles:((j=J[7])==null?void 0:j.data)||[],funnelWishlistsCount:((b=J[8])==null?void 0:b.count)||0,funnelReviewsCount:((c=J[9])==null?void 0:c.count)||0,analyticsReferrerRows:((d=J[10])==null?void 0:d.data)||[],analyticsPageRows:((P=J[11])==null?void 0:P.data)||[],analyticsDeviceRows:((k=J[12])==null?void 0:k.data)||[],analyticsBrowserRows:((p=J[13])==null?void 0:p.data)||[],analyticsDailyProductRows:((h=J[14])==null?void 0:h.data)||[],analyticsFunnelRows:((f=J[15])==null?void 0:f.data)||[],analyticsUtmRows:((_=J[16])==null?void 0:_.data)||[],prevSessionDailyRows:((m=J[17])==null?void 0:m.data)||[],todayHourlyRows:R>=0?((u=J[R])==null?void 0:u.data)||[]:[]},error:null}}catch(g){return{data:null,error:g instanceof Error?g.message:"Failed to load admin analytics datasets"}}}function Vm(){const[s,t]=i.useState({totalProducts:0,totalPurchases:0,totalRevenue:0,platformEarnings:0,totalCartAdds:0,conversionRate:0}),[r,n]=i.useState({uniqueUsers:0,totalSessions:0,totalPageviews:0,pagesPerSession:0,bounceRate:0,avgSessionDuration:0,prevUniqueUsers:0,prevSessions:0,prevPageviews:0,prevPagesPerSession:0,prevBounceRate:0,prevAvgDuration:0,newUsers:0,returningUsers:0,returningPct:0}),[a,l]=i.useState([]),[o,j]=i.useState([]),[b,c]=i.useState([]),[d,P]=i.useState([]),[k,p]=i.useState([]),[h,f]=i.useState([]),[_,m]=i.useState(!0),[u,g]=i.useState("30d"),[S,M]=i.useState("1h"),[y,w]=i.useState("overview"),[F,J]=i.useState(null),[E,N]=i.useState([]),[U,R]=i.useState([]),[Z,W]=i.useState(30),[D,X]=i.useState(null),[oe,ue]=i.useState([]),[fe,je]=i.useState(0),[Fe,Ie]=i.useState(0),[G,Q]=i.useState(0),[xe,ve]=i.useState(0),[T,ne]=i.useState(0),[he,Oe]=i.useState(0),[Ue,Xe]=i.useState({views:0,
118carts:0,purchases:0,viewToCart:0,cartToPurchase:0,viewToPurchase:0}),[Be,ae]=i.useState([]),[de,Re]=i.useState([]),[pe,Ce]=i.useState([]),[qe,Ze]=i.useState([]),[ts,We]=i.useState([]),[ns,us]=i.useState({visitorToSale:{visitors:0,signups:0,purchasers:0,signupRate:0,purchaseRate:0},sellerJourney:{signups:0,sellers:0,listed:0,sold:0,sellerRate:0,listRate:0,saleRate:0},browseToCart:{visits:0,viewed:0,carted:0,purchased:0,viewRate:0,cartRate:0,purchaseRate:0},wishlistPath:{views:0,wishlisted:0,purchased:0,wishlistRate:0,purchaseRate:0},engagement:{signups:0,reviewers:0,repeatBuyers:0,reviewRate:0,repeatRate:0},heroCta:{homepageVisitors:0,ctaClicked:0,signedUp:0,listedProduct:0,purchased:0}});i.useState(0),i.useState("asc");const[Ge,He]=i.useState(0),[A,me]=i.useState({stripe:0,paypal:0,overall:0}),[ze,Le]=i.useState([]),[B,ee]=i.useState([]),[te,se]=i.useState([]),[be,Se]=i.useState([]),_e=async(re=!1)=>{var Pi,Ti;re||m(!0);const ge=new Date;let ye=null,Ae=null,Ee=0;u==="today"?(ye=new Date(ge.getFullYear(),ge.getMonth(),ge.getDate()).toISOString(),Ae=new Date(ge.getTime()-864e5).toISOString(),Ee=1):u==="7d"?(ye=new Date(ge.getTime()-7*864e5).toISOString(),Ae=new Date(ge.getTime()-14*864e5).toISOString(),Ee=7):u==="30d"?(ye=new Date(ge.getTime()-30*864e5).toISOString(),Ae=new Date(ge.getTime()-60*864e5).toISOString(),Ee=30):u==="90d"&&(ye=new Date(ge.getTime()-90*864e5).toISOString(),Ae=new Date(ge.getTime()-180*864e5).toISOString(),Ee=90);const Je=await zm({dateFilter:ye,prevDateFilter:Ae,isToday:u==="today"});if(!Je.data){O.error(Je.error||"Failed to load analytics"),m(!1);return}const{products:Ve,purchasesByProduct:es,cartEventsCount:ds,sellerProfiles:ot,feeSettings:Mt,sessionDailyRows:un,productViewsByProduct:xn,totalProductViews:ur,funnelProfiles:xr,funnelSellerProfiles:pn,funnelWishlistsCount:Ks,funnelReviewsCount:pr,analyticsReferrerRows:Ua,analyticsPageRows:hr,analyticsDeviceRows:gr,analyticsBrowserRows:fr,analyticsDailyProductRows:hn,analyticsFunnelRows:Ia,analyticsUtmRows:za,prevSessionDailyRows:jr,todayHourlyRows:vr}=Je.data,ct=Ve||[],dt=es||[],gn=xn||[],Js=new Map(ct.map(C=>[C.id,C])),Va=hn||[],ha=Ia||[],br=za||[],ga=un||[],yt=jr||[],Wt=vr||[],Ba=u==="today"&&Wt.length>0;R(Ba?Wt:ga),W(Ee);const Us=(C,I)=>C.reduce((Ne,$e)=>Ne+Number(($e==null?void 0:$e[I])||0),0),Nt=Ba?Wt:ga,Qs=Us(Nt,"total_sessions"),fn=Us(Nt,"engaged_sessions"),yr=Us(Nt,"total_page_views"),jn=Nt.reduce((C,I)=>C+Number(I.avg_session_duration||0)*Number(I.total_sessions||0),0),vn=Qs>0?jn/Qs:0,bn=Qs>0?(Qs-fn)/Qs*100:0,yn=Qs>0?yr/Qs:0,fa=Us(Nt,"unique_users"),Nn=Us(Nt,"new_visitors"),Nr=Us(Nt,"returning_visitors"),_n=fa>0?Nr/fa*100:0,mt=Us(yt,"total_sessions"),_r=Us(yt,"total_page_views"),wn=Us(yt,"unique_users"),Sn=Us(yt,"engaged_sessions"),kn=yt.reduce((C,I)=>C+Number(I.avg_session_duration||0)*Number(I.total_sessions||0),0),Cn=mt>0?kn/mt:0,wr=mt>0?(mt-Sn)/mt*100:0,Sr=mt>0?_r/mt:0;n({uniqueUsers:fa,totalSessions:Qs,totalPageviews:yr,pagesPerSession:yn,bounceRate:bn,avgSessionDuration:vn,prevUniqueUsers:wn,prevSessions:mt,prevPageviews:_r,prevPagesPerSession:Sr,prevBounceRate:wr,prevAvgDuration:Cn,newUsers:Nn,returningUsers:Nr,returningPct:_n});const kr=[...ga,...yt],Ys={};kr.forEach(C=>{C.date&&(Ys[C.date]||(Ys[C.date]={newVisitors:0,returningVisitors:0}),Ys[C.date].newVisitors+=Number(C.new_visitors||0),Ys[C.date].returningVisitors+=Number(C.returning_visitors||0))});const v=Object.keys(Ys).sort();v.forEach((C,I)=>{});const ie=[];for(let C=0;C<v.length;C++){const I=v[C],Ne=Ys[I].newVisitors;if(Ne<2)continue;const $e=[],pt=[];$e[0]=Ne,pt[0]=100;for(let ys=1;ys<=7;ys++)if(C+ys<v.length){const Di=((Pi=Ys[v[C+ys]])==null?void 0:Pi.returningVisitors)||0;$e[ys]=Di,pt[ys]=Di/Ne*100}else $e[ys]=null,pt[ys]=null;const Et=$e[1]??0;let Zt=0;for(let ys=1;ys<=7;ys++)$e[ys]!==null&&(Zt=Math.max(Zt,$e[ys]));let Ar=Zt;for(let ys=8;ys<=30&&C+ys<v.length;ys++)Ar=Math.max(Ar,((Ti=Ys[v[C+ys]])==null?void 0:Ti.returningVisitors)||0);ie.push({date:I,cohortSize:Ne,d1:Et,d7:Zt,d30:Ar,d1Pct:Et/Ne*100,d7Pct:Zt/Ne*100,d30Pct:Ar/Ne*100,dayReturning:$e,dayPct:pt})}ue(ie);const we=new Date(ge.getTime()-14*864e5),is=ie.filter(C=>new Date(C.date)>=we&&C.cohortSize>=2),hs=(C,I)=>C.length>0?C.reduce((Ne,$e)=>Ne+$e[I],0)/C.length:0;je(hs(is,"d1Pct")),Ie(hs(is,"d7Pct")),Q(hs(is,"d30Pct"));const ut=new Date(ge.getTime()-28*864e5),Zs=ie.filter(C=>{const I=new Date(C.date);return I>=ut&&I<we&&C.cohortSize>=2});ve(hs(Zs,"d1Pct")),ne(hs(Zs,"d7Pct")),Oe(hs(Zs,"d30Pct"));const Ts=ha.reduce((C,I)=>C+Number(I.product_views||0),0),xt=ha.reduce((C,I)=>C+Number(I.checkout_visits||0),0),Gt=ha.reduce((C,I)=>C+Number(I.purchases||0),0);Xe({views:Ts,carts:xt,purchases:Gt,viewToCart:Ts>
1180?xt/Ts*100:0,cartToPurchase:xt>0?Gt/xt*100:0,viewToPurchase:Ts>0?Gt/Ts*100:0}),ae(ha);const qa={};gn.forEach(C=>{qa[C.product_id]=(qa[C.product_id]||0)+C.view_count});const Wa={},Ga={};dt.forEach(C=>{Ga[C.product_id]=(Ga[C.product_id]||0)+C.purchase_count});const Ht={};ct.forEach(C=>{Ht[C.id]=C.name});const Xs={};ct.forEach(C=>{Xs[C.id]=C.category||"unknown"});const An=Object.entries(qa).sort((C,I)=>I[1]-C[1]).slice(0,10).map(([C,I])=>({name:Ht[C]||C.slice(0,8),views:I,carts:Wa[C]||0,purchases:Ga[C]||0}));Re(An);const et={};Va.forEach(C=>{const I=String(C.product_id||"");I&&(et[I]||(et[I]={views:0,purchases:0,revenue:0}),et[I].views+=Number(C.views||0),et[I].purchases+=Number(C.purchases||0),et[I].revenue+=Number(C.revenue||0))});const Rn=Object.entries(et).map(([C,I])=>({productId:C,name:Ht[C]||C.slice(0,8),views:I.views,purchases:I.purchases,revenue:I.revenue,conversionRate:I.views>0?I.purchases/I.views*100:0})).sort((C,I)=>I.conversionRate!==C.conversionRate?I.conversionRate-C.conversionRate:I.purchases-C.purchases).slice(0,20);Ce(Rn),Se(Va);const Kt={};Va.forEach(C=>{const I=String(C.product_id||"");if(!I)return;const Ne=(Xs[I]||"unknown").replace(/_/g," ");Kt[Ne]||(Kt[Ne]={views:0,purchases:0}),Kt[Ne].views+=Number(C.views||0),Kt[Ne].purchases+=Number(C.purchases||0)});const Ha=Object.entries(Kt).map(([C,I])=>({category:C,views:I.views,purchases:I.purchases,conversionRate:I.views>0?I.purchases/I.views*100:0})).sort((C,I)=>I.views-C.views).slice(0,10);Ze(Ha);const st={};br.forEach(C=>{const I=C.utm_source||"unknown",Ne=Number(C.total_sessions||0);st[I]||(st[I]={sessions:0,weightedBounce:0,weightedDuration:0}),st[I].sessions+=Ne,st[I].weightedBounce+=Number(C.bounce_rate||0)*Ne,st[I].weightedDuration+=Number(C.avg_session_duration||0)*Ne});const Pn=Object.entries(st).map(([C,I])=>({source:C,sessions:I.sessions,bounceRate:I.sessions>0?I.weightedBounce/I.sessions:0,avgDuration:I.sessions>0?I.weightedDuration/I.sessions:0})).sort((C,I)=>I.sessions-C.sessions).slice(0,10);We(Pn);const ja=xr||[],Jt=pn||[],Qt=fa,Is=ja.length,Yt=dt.length,bs=Jt.filter(C=>C.onboarding_complete),tt={};Jt.forEach(C=>{tt[C.id]=C.user_id});const va=new Set;ct.forEach(C=>{C.seller_id&&tt[C.seller_id]&&va.add(tt[C.seller_id])});const Tn=new Set;dt.forEach(C=>{const I=Js.get(C.product_id);I!=null&&I.seller_id&&tt[I.seller_id]&&Tn.add(tt[I.seller_id])});const Dn=Qs,bi=0,yi=pr||0,Ni=0,io=(hr||[]).reduce((C,I)=>{const Ne=I.page||"";return Ne==="/"||Ne===""?C+Number(I.total_sessions||0):C},0),_i=[].filter(C=>(C.pages_visited||[]).some(Ne=>Ne==="/auth"||Ne==="/dashboard/seller"||Ne.startsWith("/auth")||Ne.startsWith("/dashboard/seller"))),lo=_i.length,wi=new Set(_i.filter(C=>C.user_id).map(C=>C.user_id)),oo=new Set(ja.map(C=>C.user_id).filter(Boolean)),co=[...wi].filter(C=>oo.has(C)).length,mo=[...wi].filter(C=>va.has(C)).length;us({visitorToSale:{visitors:Qt,signups:Is,purchasers:Yt,signupRate:Qt>0?Is/Qt*100:0,purchaseRate:Is>0?Yt/Is*100:0},sellerJourney:{signups:Is,sellers:bs.length,listed:va.size,sold:Tn.size,sellerRate:Is>0?bs.length/Is*100:0,listRate:bs.length>0?va.size/bs.length*100:0,saleRate:va.size>0?Tn.size/va.size*100:0},browseToCart:{visits:Dn,viewed:Ts,carted:xt,purchased:Gt,viewRate:Dn>0?Ts/Dn*100:0,cartRate:Ts>
1180?xt/Ts*100:0,purchaseRate:xt>0?Gt/xt*100:0},wishlistPath:{views:Ts,wishlisted:Ks,purchased:bi,wishlistRate:Ts>0?Ks/Ts*100:0,purchaseRate:Ks>0?bi/Ks*100:0},engagement:{signups:Is,reviewers:yi,repeatBuyers:Ni,reviewRate:Is>0?yi/Is*100:0,repeatRate:Yt>0?Ni/Yt*100:0},heroCta:{homepageVisitors:io,ctaClicked:lo,signedUp:co,listedProduct:mo,purchased:0}});const Mn={};(Ua||[]).forEach(C=>{const I=C.referrer_domain||"(direct)";Mn[I]=(Mn[I]||0)+Number(C.total_sessions||0)}),j(Object.entries(Mn).sort((C,I)=>I[1]-C[1]).slice(0,10).map(([C,I])=>({domain:C,count:I})));const En={};(hr||[]).forEach(C=>{const I=C.page||"/";En[I]=(En[I]||0)+Number(C.total_sessions||0)}),c(Object.entries(En).sort((C,I)=>I[1]-C[1]).slice(0,10).map(([C,I])=>({page:C,count:I})));const uo=C=>{if(S==="1m")return`${String(C.getUTCHours()).padStart(2,"0")}:${String(C.getUTCMinutes()).padStart(2,"0")}`;if(S==="5m"){const I=Math.floor(C.getUTCMinutes()/5)*5;return`${String(C.getUTCHours()).padStart(2,"0")}:${String(I).padStart(2,"0")}`}else if(S==="15m"){const I=Math.floor(C.getUTCMinutes()/15)*15;return`${String(C.getUTCHours()).padStart(2,"0")}:${String(I).padStart(2,"0")}`}else return S==="1h"?Ee<=1?`${String(C.getUTCHours()).padStart(2,"0")}:00`:`${C.getUTCMonth()+1}/${C.getUTCDate()} ${String(C.getUTCHours()).padStart(2,"0")}:00`:`${C.getUTCMonth()+1}/${C.getUTCDate()}`};let On;if(Ba&&Wt.length>0){const C={};for(let I=0;I<24;I++){const Ne=`${String(I).padStart(2,"0")}:00`;C[Ne]={sessions:0,newUsers:0,returningUsers:0,uniqueUsers:0}}Wt.forEach(I=>{const Ne=new Date(I.bucket),$e=`${String(Ne.getUTCHours()).padStart(2,"0")}:00`;C[$e]&&(C[$e].sessions=Number(I.total_sessions||0),C[$e].newUsers=Number(I.new_visitors||0),C[$e].returningUsers=Number(I.returning_visitors||0),C[$e].uniqueUsers=Number(I.unique_users||0))}),On=Object.entries(C).sort((I,Ne)=>I[0].localeCompare(Ne[0])).map(([I,Ne])=>({hour:I,users:Ne.uniqueUsers,sessions:Ne.sessions,newUsers:Ne.newUsers,returningUsers:Ne.returningUsers}))}else{const C={};ga.forEach(I=>{const Ne=new Date(`${I.date}T00:00:00.000Z`),$e=uo(Ne);C[$e]||(C[$e]={sessions:0,newUsers:0,returningUsers:0,uniqueUsers:0}),C[$e].sessions+=Number(I.total_sessions||0),C[$e].newUsers+=Number(I.new_visitors||0),C[$e].returningUsers+=Number(I.returning_visitors||0),C[$e].uniqueUsers+=Number(I.unique_users||0)}),On=Object.entries(C).sort((I,Ne)=>I[0].localeCompare(Ne[0])).map(([I,Ne])=>({hour:I,users:Ne.uniqueUsers,sessions:Ne.sessions,newUsers:Ne.newUsers,returningUsers:Ne.returningUsers}))}P(On);const Ln={};(fr||[]).forEach(C=>{const I=C.browser||"Unknown";Ln[I]=(Ln[I]||0)+Number(C.total_sessions||0)}),p(Object.entries(Ln).sort((C,I)=>I[1]-C[1]).map(([C,I])=>({browser:C,count:I})));const Fn={};(gr||[]).forEach(C=>{const I=C.device_type||"desktop";Fn[I]=(Fn[I]||0)+Number(C.total_sessions||0)}),f(Object.entries(Fn).sort((C,I)=>I[1]-C[1]).map(([C,I])=>({device:C,count:I})));const Si={},ki={};ot==null||ot.forEach(C=>{Si[C.id]=C.fee_exempt||!1,ki[C.id]=C.creator_tier||"none"});const Ka={};Mt==null||Mt.forEach(C=>{Ka[C.key]=C.value});let ba=[];if(Ka.platform_fee_rules)try{ba=JSON.parse(Ka.platform_fee_rules)}catch{}if(ba.length===0){const C=Ka.platform_fee_type||"percentage",I=parseFloat(Ka.platform_fee_value||"5");ba=[{min_price:0,max_price:null,fee_type:C,fee_value:I}]}const $n={};dt.forEach(C=>{const I=Js.get(C.product_id);I!=null&&I.seller_id&&($n[I.seller_id]=($n[I.seller_id]||0)+(C.purchase_count||0))});const xo=10,po=(C,I)=>{if(!I||Si[I]||($n[I]||0)<=xo)return 0;const $e=ki[I];if($e==="trusted"||$e==="partnered")return Math.round(C*.03*100)/100;const pt=ba.find(Et=>C>=Et.min_price&&(Et.max_price===null||C<Et.max_price))||ba[ba.length-1];return pt.fee_type==="percentage"?Math.round(C*(pt.fee_value/100)*100)/100:Math.min(pt.fee_value,C)},Un={},ho={},Ci={},Rs={stripe:0,stripeCount:0,paypal:0,paypalCount:0,overall:0,overallCount:0},Ja={};dt.forEach(C=>{Un[C.product_id]=(Un[C.product_id]||0)+C.purchase_count;const I=Number(C.revenue||0);Rs.overall+=I,Rs.overallCount+=C.purchase_count,Rs.stripe+=Number(C.revenue||0)*(C.stripe_count/Math.max(C.purchase_count,1)),Rs.stripeCount+=C.stripe_count||0,Rs.paypal+=Number(C.revenue||0)*(C.paypal_count/Math.max(C.purchase_count,1)),Rs.paypalCount+=C.paypal_count||0;const Ne=Js.get(C.product_id);
118Ne!=null&&Ne.tags&&Ne.tags.forEach($e=>{Ja[$e]||(Ja[$e]={sales:0,revenue:0}),Ja[$e].sales+=C.purchase_count,Ja[$e].revenue+=I})});const Cr=ct.map(C=>{const I=Un[C.id]||0,Ne=ho[C.id]||0;let $e=C.price;C.discount_percentage&&C.discount_percentage>0?$e=C.price*(1-C.discount_percentage/100):C.discount_amount&&C.discount_amount>0&&($e=Math.max(0,C.price-C.discount_amount));const pt=I*$e,Et=I*po($e,C.seller_id),Zt=Ne>0?I/Ne*100:0;return{...C,purchaseCount:I,cartAdds:Ne,revenue:pt,platformEarnings:Et,effectivePrice:$e,conversionRate:Zt,onSale:$e<C.price,isSeller:!!C.seller_id}});Cr.sort((C,I)=>I.revenue-C.revenue);const go=Cr.reduce((C,I)=>C+I.revenue,0),fo=Cr.reduce((C,I)=>C+I.platformEarnings,0),In=ds||0,Ai=dt.reduce((C,I)=>C+(I.purchase_count||0),0),jo=In>0?Ai/In*100:0;t({totalProducts:ct.length,totalPurchases:Ai,totalRevenue:go,platformEarnings:fo,totalCartAdds:In,conversionRate:jo}),l(Cr),ee(dt),se(ct);const Ri=Object.keys(Ci).length,vo=Object.values(Ci).filter(C=>C>1).length;He(Ri>0?vo/Ri*100:0),me({stripe:Rs.stripeCount>0?Rs.stripe/Rs.stripeCount:0,paypal:Rs.paypalCount>0?Rs.paypal/Rs.paypalCount:0,overall:Rs.overallCount>0?Rs.overall/Rs.overallCount:0}),Le(Object.entries(Ja).sort((C,I)=>I[1].sales-C[1].sales).slice(0,10).map(([C,I])=>({tag:C,sales:I.sales,revenue:I.revenue}))),X(new Date),m(!1)};i.useEffect(()=>{_e();const re=setInterval(()=>{document.visibilityState==="visible"&&_e(!0)},3e5);return()=>clearInterval(re)},[u,S]),i.useEffect(()=>{F&&H(F,!0)},[S]);const Ke=(re,ge)=>ge===0?re>0?100:0:(re-ge)/ge*100,rs=re=>{if(re<60)return`${Math.round(re)}s`;const ge=Math.floor(re/60),ye=Math.round(re%60);return`${ge}m ${ye}s`},H=(re,ge=!1)=>{var Je;if(!ge&&F===re){J(null),N([]);return}J(re);const ye=Ve=>{if(S==="1m")return`${String(Ve.getHours()).padStart(2,"0")}:${String(Ve.getMinutes()).padStart(2,"0")}`;if(S==="5m"){const es=Math.floor(Ve.getMinutes()/5)*5;return`${String(Ve.getHours()).padStart(2,"0")}:${String(es).padStart(2,"0")}`}else if(S==="15m"){const es=Math.floor(Ve.getMinutes()/15)*15;return`${String(Ve.getHours()).padStart(2,"0")}:${String(es).padStart(2,"0")}`}else return S==="1h"?Z<=1?`${String(Ve.getHours()).padStart(2,"0")}:00`:`${Ve.getMonth()+1}/${Ve.getDate()} ${String(Ve.getHours()).padStart(2,"0")}:00`:`${Ve.getMonth()+1}/${Ve.getDate()}`},Ae=U.length>0&&((Je=U[0])==null?void 0:Je.bucket),Ee=U.map(Ve=>{let es,ds;return Ae?(es=new Date(Ve.bucket),ds=`${String(es.getUTCHours()).padStart(2,"0")}:00`):(es=new Date(`${Ve.date}T00:00:00.000Z`),ds=ye(es)),{hour:ds,row:Ve}}).sort((Ve,es)=>Ve.hour.localeCompare(es.hour)).map(({hour:Ve,row:es})=>{let ds=0;if(re==="uniqueUsers")ds=Number(es.unique_users||0);else if(re==="newUsers")ds=Number(es.new_visitors||0);else if(re==="returningUsers")ds=Number(es.returning_visitors||0);else if(re==="sessions")ds=Number(es.total_sessions||0);else if(re==="pageviews")ds=Number(es.total_page_views||0);else if(re==="pagesPerSession"){const ot=Number(es.total_sessions||0),Mt=Number(es.total_page_views||0);ds=ot>0?Math.round(Mt/ot*10)/10:0}else re==="bounceRate"?ds=Number(es.bounce_rate||0):re==="avgDuration"&&(ds=Math.round(Number(es.avg_session_duration||0)));return{hour:Ve,value:ds}});N(Ee)},ce=(re,ge,ye)=>{const Ae=[ge.join(","),...ye.map(es=>es.map(ds=>`"${String(ds).replace(/"/g,'""')}"`).join(","))].join(` 119`),Ee=new Blob([Ae],{type:"text/csv"}),Je=URL.createObjectURL(Ee),Ve=document.createElement("a");Ve.href=Je,Ve.download=re,Ve.click(),URL.revokeObjectURL(Je)},le=()=>{const re=["Purchase ID","Product","Amount","Payment Method","Status","Date"],ge={};te.forEach(Ae=>{ge[Ae.id]=Ae.name});const ye=B.map(Ae=>[Ae.id,ge[Ae.product_id]||Ae.product_id,String(Ae.amount||0),Ae.payment_method||"stripe",Ae.status||"completed",Ae.purchased_at]);ce(`sales-export-${u}.csv`,re,ye),O.success("Sales CSV exported")},q=()=>{const re=["Product","Category","Price","Sales","Revenue","Platform Earnings","Conversion %"],ge=a.map(ye=>{var Ae,Ee,Je,Ve;return[ye.name,ye.category,String((Ae=ye.effectivePrice)==null?void 0:Ae.toFixed(2)),String(ye.purchaseCount),String((Ee=ye.revenue)==null?void 0:Ee.toFixed(2)),String((Je=ye.platformEarnings)==null?void 0:Je.toFixed(2)),String((Ve=ye.conversionRate)==null?void 0:Ve.toFixed(1))]});ce(`products-export-${u}.csv`,re,ge),O.success("Products CSV exported")},K=()=>{const re=["Date","Sessions","Unique Users","Pageviews","Bounces","Bounce Rate (%)","Avg Duration (s)","New Visitors","Returning Visitors"],ge=U.map(ye=>{const Ae=Number(ye.total_sessions||0),Ee=Number(ye.engaged_sessions||0),Je=Math.max(0,Ae-Ee);
119return[String(ye.date||""),String(Ae),String(Number(ye.unique_users||0)),String(Number(ye.total_page_views||0)),String(Je),String(Number(ye.bounce_rate||0).toFixed(2)),String(Number(ye.avg_session_duration||0).toFixed(2)),String(Number(ye.new_visitors||0)),String(Number(ye.returning_visitors||0))]});ce(`users-export-${u}.csv`,re,ge),O.success("Users CSV exported")};return _?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading analytics..."}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 justify-between",children:[e.jsx("div",{className:"flex gap-1 glass rounded-lg p-1 flex-wrap",children:["overview","retention","funnel","products","traffic"].map(re=>e.jsx("button",{onClick:()=>w(re),className:`px-4 py-1.5 rounded-md text-sm font-medium transition-all ${y===re?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:re==="overview"?"Overview":re==="products"?"Products":re==="traffic"?"Traffic":re==="retention"?"Retention":"Funnels"},re))}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("div",{className:"flex gap-1",children:["today","7d","30d","90d","all"].map(re=>e.jsx($,{size:"sm",variant:u===re?"default":"secondary",onClick:()=>g(re),children:re==="today"?"Today":re==="7d"?"7D":re==="30d"?"30D":re==="90d"?"90D":"All"},re))}),e.jsx("div",{className:"h-4 w-px bg-border/50"}),e.jsx("div",{className:"flex gap-1",children:["1m","5m","15m","1h","1d"].map(re=>e.jsx($,{size:"sm",variant:S===re?"default":"outline",onClick:()=>M(re),className:"text-xs px-2",children:re==="1m"?"1 Min":re==="5m"?"5 Min":re==="15m"?"15 Min":re==="1h"?"Hourly":"Daily"},re))}),e.jsx("div",{className:"h-4 w-px bg-border/50"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:le,className:"text-xs px-2 gap-1",children:[e.jsx(nt,{className:"h-3 w-3"}),"Sales"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:q,className:"text-xs px-2 gap-1",children:[e.jsx(nt,{className:"h-3 w-3"}),"Products"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:K,className:"text-xs px-2 gap-1",children:[e.jsx(nt,{className:"h-3 w-3"}),"Users"]})]}),D&&e.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-400 animate-pulse"}),"Auto-refreshes · ",D.toLocaleTimeString()]})]})]}),y==="overview"&&e.jsx(Pm,{loading:_,sessionStats:r,stats:s,aovByMethod:A,topTags:ze,referrers:o,topPages:b,browserStats:k,deviceStats:h,hourlyData:d,analyticsDailyRows:U,granularity:S,rangeDaysState:Z,selectedMetric:F,metricTrendData:E,computeMetricTrend:H,pctChange:Ke,formatDuration:rs}),y==="retention"&&e.jsx(Om,{loading:_,retentionData:oe,avgD1:fe,avgD7:Fe,avgD30:G,prevAvgD1:xe,prevAvgD7:T,prevAvgD30:he,newUsers:r.newUsers,prevNewUsers:r.prevUniqueUsers,hourlyData:d,pctChange:Ke}),y==="products"&&e.jsx($m,{loading:_,productStats:a,topAssetInsights:pe,funnelCategoryBreakdown:qe,analyticsDailyProductRows:be,sessionStats:{uniqueUsers:r.uniqueUsers,prevUniqueUsers:r.prevUniqueUsers},prevTotalPurchases:0,prevTotalViews:0,prevTotalRevenue:0,pctChange:Ke}),y==="traffic"&&e.jsx(Im,{loading:_,sessionStats:{totalSessions:r.totalSessions,uniqueUsers:r.uniqueUsers,avgSessionDuration:r.avgSessionDuration,pagesPerSession:r.pagesPerSession,prevSessions:r.prevSessions,prevUniqueUsers:r.prevUniqueUsers,prevAvgDuration:r.prevAvgDuration,prevPagesPerSession:r.prevPagesPerSession,newUsers:r.newUsers,returningUsers:r.returningUsers},referrers:o,topPages:b,browserStats:k,deviceStats:h,hourlyData:d,analyticsDailyRows:U,funnelUtmBreakdown:ts,pctChange:Ke,formatDuration:rs,granularity:S,rangeDaysState:Z}),y==="funnel"&&e.jsx(Fm,{loading:_,totalSessions:r.totalSessions,funnelData:Ue,funnelDailyRows:Be,deviceStats:h,referrers:o,analyticsDailyRows:U,funnelCategoryBreakdown:qe,pctChange:Ke})]})}function Bm(){var _e,Ke,rs;const{user:s,isOwner:t,isAdmin:r,hasPermission:n}=vs(),[a,l]=i.useState([]),[o,j]=i.useState(!0),[b,c]=i.useState(!1),[d,P]=i.useState(null),[k,p]=i.useState(!1),[h,f]=i.useState(null),[_,m]=i.useState(!1),[u,g]=i.useState(!1),[S,M]=i.useState([]),[y,w]=i.useState(""),[F,J]=i.useState("all"),[E,N]=i.useState("all"),[U,R]=i.useState(1),Z=50,{claim:W,unclaim:D,overrideClaim:X,isClaimedByMe:oe,canActOn:ue,claiming:fe}=hi("products"),[je,Fe]=i.useState({}),{track:Ie}=fi(),{getViewersFor:G}=ji(),{notes:Q,loading:xe,addNote:ve}=gi("product",(d==null?void 0:d.id)||null);ir("products",()=>{Ze()});const[T,ne]=i.useState(!1),[he,Oe]=i.useState(null),[Ue,Xe]=i.useState(""),[Be,ae]=i.useState(!1),[de,Re]=i.useState(""),[pe,Ce]=i.useState(!1),qe=r||n("manage_moderation"),Ze=async()=>{j(!0);const H=await Fs(()=>x.from("products").select("*, seller_profiles!seller_id(user_id)").not("seller_id","is",null).order("created_at",{ascending:!1}));if(H){const ce=[...new Set(H.map(Ee=>{var Je;return(Je=Ee.seller_profiles)==null?void 0:Je.user_id}
119).filter(Boolean))],le=[...new Set(H.map(Ee=>Ee.claimed_by).filter(Boolean))],q=[...new Set([...ce,...le])],K={};if(q.length>0){const Ee=await Fs(()=>x.from("profiles").select("user_id, display_name, avatar_url").in("user_id",q));Ee==null||Ee.forEach(Je=>{K[Je.user_id]=Je})}const re={};le.forEach(Ee=>{var Je;re[Ee]=((Je=K[Ee])==null?void 0:Je.display_name)||"Staff"}),Fe(re);const ge=new Set(H.map(Ee=>Ee.id));let ye={};const Ae=await Fs(()=>x.from("license_tiers").select("product_id, price_cents").eq("is_active",!0));if(Ae)for(const Ee of Ae){if(!ge.has(Ee.product_id))continue;ye[Ee.product_id]||(ye[Ee.product_id]={count:0,min_cents:null}),ye[Ee.product_id].count++;const Je=Ee.price_cents??0;(ye[Ee.product_id].min_cents===null||Je<ye[Ee.product_id].min_cents)&&(ye[Ee.product_id].min_cents=Je)}l(H.map(Ee=>{var Je,Ve,es;return{...Ee,seller_profile:K[(Je=Ee.seller_profiles)==null?void 0:Je.user_id]||null,license_tier_count:((Ve=ye[Ee.id])==null?void 0:Ve.count)??0,min_tier_price_cents:((es=ye[Ee.id])==null?void 0:es.min_cents)??null}}))}j(!1)};i.useEffect(()=>{Ze()},[]),i.useEffect(()=>{R(1)},[y,F]);const ts=async H=>{var ce;try{const le=(ce=H.seller_profiles)==null?void 0:ce.user_id;if(!le)return;await x.functions.invoke("product-approval-emails",{body:{action:"notify_user_approved",product_id:H.id,product_name:H.name,seller_user_id:le}})}catch(le){console.error("Failed to send approval email:",le)}},We=async H=>{const ce=a.find(q=>q.id===H),{error:le}=await x.from("products").update({status:"approved"}).eq("id",H);le?O.error(le.message):(O.success("Product approved!"),ss("approve_product","product",H,{target_name:(ce==null?void 0:ce.name)||"Unknown",seller_name:(ce==null?void 0:ce.seller_name)||(ce==null?void 0:ce.creator_id),category:ce==null?void 0:ce.category}),ce&&ts(ce),ce&&x.functions.invoke("notify-followers-instant",{body:{assetId:H,sellerId:ce.creator_id}}).catch(q=>console.error("Failed to notify followers:",q)),Ze())},ns=async()=>{const H=a.filter(K=>K.status==="pending");if(H.length===0||!confirm(`Approve all ${H.length} pending product(s)?`))return;c(!0);const ce=H.map(K=>K.id),le=50;let q=0;for(let K=0;K<ce.length;K+=le){const re=ce.slice(K,K+le),{error:ge}=await x.from("products").update({status:"approved"}).in("id",re);if(ge){O.error(`Batch failed: ${ge.message}`);break}q+=re.length,ce.length>le&&O.info(`Approved ${q}/${ce.length}...`)}for(const K of H)ts(K);O.success(`${q} product(s) approved!`),ss("bulk_approve_products","product",void 0,{count:q}),Ze(),c(!1)},us=H=>{Oe(H),Xe(""),ae(!1),Re(""),ne(!0)},Ge=async()=>{var q;if(!he)return;Ce(!0);const H=he.id,ce=(q=he.seller_profiles)==null?void 0:q.user_id,{error:le}=await x.from("products").update({status:"rejected"}).eq("id",H);if(le){O.error(le.message),Ce(!1);return}ss("reject_product","product",H,{reason:Ue||void 0}),ce&&(x.from("notifications").insert({user_id:ce,type:"product_rejected",title:`Asset rejected: ${he.name}`,message:Ue?`Reason: ${Ue}`:"Your asset was not approved. Check your dashboard for details."}).then(()=>{}),x.functions.invoke("product-approval-emails",{body:{action:"notify_user_rejected",product_id:H,product_name:he.name,seller_user_id:ce,rejection_reason:Ue||void 0}}).then(({error:K})=>{K&&console.error("Failed to send rejection email:",K)})),Be&&de.trim()&&ce&&qe&&s&&(await x.from("user_warnings").insert({user_id:ce,admin_id:s.id,reason:de,severity:"warning",related_asset_ids:[H]}),await x.from("moderation_logs").insert({user_id:ce,admin_id:s.id,action_type:"warning",reason:de,metadata:{asset_id:H,asset_name:he.name,source:"product_approval"}}),ss("warn_user","user",ce,{asset_id:H,reason:de})),O.success(Be?"Product rejected & user warned":"Product rejected"),Ce(!1),ne(!1),p(!1),Ze()},He=async(H,ce,le)=>{const{downloadProductFile:q}=await as(async()=>{const{downloadProductFile:re}=await import("./download-file-GiM6ssRc.js");return{downloadProductFile:re}},__vite__mapDeps([0,1,2,3,4,5,6]));await q(H,ce,le)||O.error("Failed to generate download link")},A=i.useCallback(async H=>{P(H),p(!0),f(null),M([]);const{data:ce}=await x.from("product_images").select("*").eq("product_id",H.id).order("sort_order");ce&&M(ce);const{data:le}=await x.from("product_scan_results").select("*").eq("product_id",H.id).order("created_at",{ascending:!1}).limit(1);if(le&&le.length>0){const q=le[0];f(q),q.status==="scanning"&&ze(H.id)}Ie(`product:${H.id}`,"reviewing")},[Ie]),me=async()=>
119{if(d){if((h==null?void 0:h.status)==="completed"){O.info("File has already been scanned. Results shown below.");return}if((h==null?void 0:h.status)==="scanning"){ze(d.id);return}m(!0);try{const{data:H,error:ce}=await x.functions.invoke("scan-product-file",{body:{product_id:d.id,action:"scan"}}),le=(H==null?void 0:H.data)??H;if(ce||H!=null&&H.error){O.error((H==null?void 0:H.error)||(ce==null?void 0:ce.message)||"Scan failed"),m(!1);return}f(le),O.success("Scan submitted! Polling for results..."),m(!1),ze(d.id)}catch(H){O.error(H.message||"Scan failed"),m(!1)}}},ze=async H=>{g(!0);let ce=0;const le=20,q=8e3,K=async()=>{ce++;try{const{data:re}=await x.from("product_scan_results").select("*").eq("product_id",H).order("created_at",{ascending:!1}).limit(1),ge=re==null?void 0:re[0];if((ge==null?void 0:ge.status)==="completed"||(ge==null?void 0:ge.status)==="error"){f(ge),g(!1),ge.status==="completed"&&O.success("Scan complete!");return}const{data:ye}=await x.functions.invoke("scan-product-file",{body:{product_id:H,action:"check"}}),Ae=(ye==null?void 0:ye.data)??ye;if((Ae==null?void 0:Ae.status)==="completed"||(Ae==null?void 0:Ae.status)==="error"){f(Ae),g(!1),Ae.status==="completed"&&O.success("Scan complete!");return}ce<le?setTimeout(K,q):(g(!1),O.info("Scan still processing. Check back later."))}catch{g(!1)}};K()},Le=H=>H?H<1024?`${H} B`:H<1048576?`${(H/1024).toFixed(1)} KB`:`${(H/1048576).toFixed(1)} MB`:"Unknown",B=he?{asset_name:he.name,asset_id:he.id,user_name:((_e=he.seller_profile)==null?void 0:_e.display_name)||"User"}:{},ee=i.useMemo(()=>{let H=a;if(F!=="all"&&(H=H.filter(ce=>ce.status===F)),E==="unclaimed"?H=H.filter(ce=>!ce.claimed_by):E==="mine"?H=H.filter(ce=>ce.claimed_by===(s==null?void 0:s.id)):E==="others"&&(H=H.filter(ce=>ce.claimed_by&&ce.claimed_by!==(s==null?void 0:s.id))),y.trim()){const ce=y.toLowerCase();H=H.filter(le=>{var q,K,re,ge;return((q=le.name)==null?void 0:q.toLowerCase().includes(ce))||(le.description||"").toLowerCase().includes(ce)||((K=le.id)==null?void 0:K.toLowerCase().includes(ce))||((ge=(re=le.seller_profile)==null?void 0:re.display_name)==null?void 0:ge.toLowerCase().includes(ce))})}return H},[a,F,E,y,s==null?void 0:s.id]);if(o)return e.jsx(cs,{});const te=ee.filter(H=>H.status==="pending"),se=ee.filter(H=>H.status!=="pending"),be=Math.max(1,Math.ceil(se.length/Z)),Se=se.slice((U-1)*Z,U*Z);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(Gs,{placeholder:"Search products by name, description, seller...",value:y,onChange:w,className:"bg-background/50",wrapperClassName:"flex-1"}),e.jsxs(Pe,{value:F,onValueChange:J,children:[e.jsx(Te,{className:"w-[150px] bg-background/50",children:e.jsx(De,{placeholder:"Status"})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Status"}),e.jsx(L,{value:"pending",children:"Pending"}),e.jsx(L,{value:"approved",children:"Approved"}),e.jsx(L,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(Pe,{value:E,onValueChange:N,children:[e.jsx(Te,{className:"w-[160px] bg-background/50",children:e.jsx(De,{placeholder:"Claims"})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Claims"}),e.jsx(L,{value:"unclaimed",children:"Unclaimed"}),e.jsx(L,{value:"mine",children:"Claimed by Me"}),e.jsx(L,{value:"others",children:"Claimed by Others"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"text-xl font-display font-semibold",children:["Pending Approval (",te.length,")"]}),te.length>0&&e.jsxs(pa,{loading:b,icon:At,onClick:ns,size:"sm",children:["Approve All (",te.length,")"]})]}),te.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No products pending approval"}):e.jsx("div",{className:"space-y-3",children:te.map(H=>e.jsx(hl,{product:H,onApprove:We,onReject:us,onDownload:He,onView:A,variant:"pending",onClaim:()=>W(H.id),onUnclaim:()=>D(H.id,H.claimed_by),onOverride:()=>X(H.id),isClaimedByMe:oe(H.claimed_by),canActOn:ue(H.claimed_by),canOverride:t,claimerName:je[H.claimed_by]||void 0,claiming:fe===H.id},H.id))}),se.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("h2",{className:"text-xl font-display font-semibold mt-8",children:["Seller Products (",se.length,")",be>1&&e.jsxs("span",{className:"text-sm font-normal text-muted-foreground ml-2",children:["Page ",U,"/",be]}
119)]}),e.jsx("div",{className:"space-y-2",children:Se.map(H=>e.jsx(hl,{product:H,onApprove:We,onReject:us,onDownload:He,onView:A,variant:"other",onClaim:()=>W(H.id),onUnclaim:()=>D(H.id,H.claimed_by),onOverride:()=>X(H.id),isClaimedByMe:oe(H.claimed_by),canActOn:ue(H.claimed_by),canOverride:t,claimerName:je[H.claimed_by]||void 0,claiming:fe===H.id},H.id))}),be>1&&e.jsxs("div",{className:"flex items-center justify-center gap-2 pt-4",children:[e.jsx($,{variant:"outline",size:"sm",disabled:U<=1,onClick:()=>R(H=>H-1),children:"Previous"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Page ",U," of ",be]}),e.jsx($,{variant:"outline",size:"sm",disabled:U>=be,onClick:()=>R(H=>H+1),children:"Next"})]})]}),e.jsx(El,{open:k,onOpenChange:p,children:e.jsx(Ol,{className:"w-full sm:max-w-xl overflow-hidden p-0",children:d&&e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsxs("div",{className:"p-6 space-y-6",children:[e.jsx(ac,{children:e.jsx(rc,{className:"font-display text-lg",children:d.name})}),e.jsx("div",{className:"rounded-lg border border-border/50 bg-secondary/20 p-3",children:e.jsx("div",{className:"relative flex items-center justify-center rounded-md bg-secondary/30 overflow-hidden min-h-[240px] max-h-[42vh]",children:d.image_url?e.jsx(Mi,{src:d.image_url,alt:d.name,size:"detail",eager:!0,className:"w-full max-h-[42vh] object-contain"}):e.jsx("div",{className:"flex items-center justify-center h-[240px] w-full",children:e.jsx(vt,{className:"h-12 w-12 text-muted-foreground/20"})})})}),S.length>1&&e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-1",children:S.map(H=>e.jsx("div",{className:"w-20 h-20 rounded-md bg-secondary/30 overflow-hidden shrink-0 border border-border/40",children:e.jsx(Mi,{src:H.image_url,alt:`${d.name} preview`,size:"card",className:"w-full h-full object-cover"})},H.id))}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Category"}),e.jsx("p",{className:"font-medium",children:d.category||"â"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price"}),e.jsx("p",{className:"font-semibold text-primary",children:Rt(d)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsx(Y,{variant:"outline",className:"mt-0.5",children:d.status})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Stock"}),e.jsx("p",{className:"font-medium",children:d.stock??"Unlimited"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"File Size"}),e.jsx("p",{className:"font-medium",children:Le(d.file_size)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Version"}),e.jsx("p",{className:"font-medium",children:d.version||"â"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"License"}),e.jsx("p",{className:"font-medium",children:d.license_type||"â"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Seller"}),e.jsx("p",{className:"font-medium",children:((Ke=d.seller_profile)==null?void 0:Ke.display_name)||"Unknown"})]})]}),((rs=d.tags)==null?void 0:rs.length)>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Tags"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:d.tags.map(H=>e.jsx(Y,{variant:"secondary",className:"text-xs",children:H},H))})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Description"}),e.jsx("div",{className:"mt-1 prose prose-sm dark:prose-invert max-w-none text-sm whitespace-pre-wrap break-words",children:d.description||"No description provided."})]}),d.youtube_url&&e.jsxs("div",{children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"YouTube Preview"}),e.jsxs("a",{href:d.youtube_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 text-sm text-primary hover:underline mt-1",children:[e.jsx(oa,{className:"h-3 w-3"})," ",d.youtube_url]})]}),d.file_url&&e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>He(d.file_url,d.name,d.file_name),children:[e.jsx(nt,{className:"h-4 w-4 mr-2"})," Download File for Review"]}),e.jsx(Fr,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"font-display font-semibold text-sm",children:"Security Scan"}),e.jsx($,{size:"sm",variant:"outline",onClick:me,disabled:_||u||!d.file_url,children:_?e.jsxs(e.Fragment,{children:[e.jsx(xs,{className:"h-3 w-3 animate-spin mr-1"})," Submitting..."]}):u?e.jsxs(e.Fragment,{children:[e.jsx(xs,{className:"h-3 w-3 animate-spin mr-1"})," Scanning..."]}):e.jsxs(e.Fragment,{children:[e.jsx(yl,{className:"h-3 w-3 mr-1"})," Scan File"]})})]}),!d.file_url&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"No file uploaded â scan unavailable."}),h&&e.jsx(qm,{scan:h})]}),e.jsx(Fr,{}),e.jsx(Kr,{viewers:G(`product:${d.id}`)}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(xa,{
119claimedBy:d.claimed_by,claimerName:je[d.claimed_by]||void 0,claimedAt:d.claimed_at,isMe:oe(d.claimed_by)}),e.jsx(lr,{claimedBy:d.claimed_by,onClaim:()=>W(d.id),onUnclaim:()=>D(d.id,d.claimed_by),onOverride:()=>X(d.id),canOverride:t,isMe:oe(d.claimed_by),claiming:fe===d.id})]}),e.jsx(Fr,{}),e.jsx(vi,{notes:Q,loading:xe,onAdd:ve})]})}),e.jsx("div",{className:"border-t border-border/50 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 p-4",children:e.jsxs("div",{className:"flex gap-2",children:[ue(d.claimed_by)&&d.status!=="approved"&&e.jsxs($,{className:"flex-1",onClick:()=>{We(d.id),p(!1)},children:[e.jsx(At,{className:"h-4 w-4 mr-1"})," Approve"]}),ue(d.claimed_by)&&d.status!=="rejected"&&e.jsx($,{variant:"destructive",className:"flex-1",onClick:()=>{us(d)},children:"Reject"}),!ue(d.claimed_by)&&e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"This item is claimed by another moderator. You cannot approve/reject unless you override."})]})})]})})}),e.jsx(Ds,{open:T,onOpenChange:ne,children:e.jsxs(Ms,{className:"sm:max-w-lg",children:[e.jsx(Es,{children:e.jsxs(Os,{className:"flex items-center gap-2",children:[e.jsx(Ps,{className:"h-5 w-5 text-destructive"}),"Reject Product"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:"Product"}),e.jsx("p",{className:"text-sm font-medium",children:he==null?void 0:he.name}),(he==null?void 0:he.seller_profile)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["by ",he.seller_profile.display_name]})]}),e.jsxs("div",{children:[e.jsx(aa,{className:"text-sm",children:"Rejection Reason (internal)"}),e.jsx($s,{placeholder:"Internal note about why this was rejected...",value:Ue,onChange:H=>Xe(H.target.value),className:"mt-1",rows:2})]}),qe&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-secondary/30",children:[e.jsx(Ca,{checked:Be,onCheckedChange:ae,id:"send-warning"}),e.jsx(aa,{htmlFor:"send-warning",className:"text-sm cursor-pointer",children:"Also send a warning to the user"})]}),Be&&e.jsxs("div",{className:"space-y-3 border rounded-lg p-3",children:[e.jsx(ao,{variables:B,currentText:de,onSelect:Re}),e.jsx($s,{placeholder:"Warning message to show the user...",value:de,onChange:H=>Re(H.target.value),rows:4})]})]})]}),e.jsxs(Do,{className:"gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>ne(!1),disabled:pe,children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:Ge,disabled:pe||Be&&!de.trim(),children:pe?e.jsxs(e.Fragment,{children:[e.jsx(xs,{className:"h-4 w-4 animate-spin mr-1"})," Rejecting..."]}):Be?"Reject & Warn":"Reject"})]})]})})]})}function hl({product:s,onApprove:t,onReject:r,onDownload:n,onView:a,variant:l,onClaim:o,onUnclaim:j,onOverride:b,isClaimedByMe:c,canActOn:d,canOverride:P,claimerName:k,claiming:p}){const f=!!s.claimed_by&&!d;return l==="pending"?e.jsx(z,{className:`glass ${f?"opacity-60":""}`,children:e.jsxs(V,{className:"p-4 flex items-center gap-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-lg bg-secondary/50 overflow-hidden shrink-0 flex items-center justify-center",children:s.image_url?e.jsx("img",{src:s.image_url,alt:s.name,className:"w-full h-full object-cover"}):e.jsx(vt,{className:"h-6 w-6 text-muted-foreground/30"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-display font-semibold text-sm truncate",children:s.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:s.description||"No description"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx(Y,{variant:"secondary",className:"text-xs",children:s.category}),e.jsx("span",{className:"text-xs text-primary font-semibold",children:Rt(s)}),Ft(s)&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["· ",Ft(s)]}),s.seller_profile&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["by ",s.seller_profile.display_name||"Unknown"]}),e.jsx(xa,{claimedBy:s.claimed_by,claimerName:k,claimedAt:s.claimed_at,isMe:c})]})]}),e.jsxs("div",{className:"flex gap-2 shrink-0 items-center",children:[e.jsx(lr,{claimedBy:s.claimed_by,onClaim:o,onUnclaim:j,onOverride:b,canOverride:P,isMe:c,claiming:p}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>a(s),title:"View full details",children:[e.jsx(ws,{className:"h-3 w-3 mr-1"})," View"]}),s.file_url&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>n(s.file_url,s.name),title:"Download file for review",children:[e.jsx(nt,{className:"h-3 w-3 mr-1"})," File"]}),d&&e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",onClick:()=>t(s.id),children:"Approve"}),e.jsx($,{size:"sm",variant:"destructive",onClick:()=>r(s),children:"Reject"})]})]})]})}):e.jsx(z,{className:`glass ${f?"opacity-60":""}`,children:e.jsxs(V,{className:"p-3 flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm truncate",children:s.name}),e.jsx(Y,{variant:Oi(s.status).variant,className:`text-xs ${Oi(s.status).className}`,children:s.status}
119),e.jsx(xa,{claimedBy:s.claimed_by,claimerName:k,claimedAt:s.claimed_at,isMe:c})]}),s.seller_profile&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["by ",s.seller_profile.display_name]})]}),e.jsxs("div",{className:"flex gap-1 shrink-0 items-center",children:[e.jsx(lr,{claimedBy:s.claimed_by,onClaim:o,onUnclaim:j,onOverride:b,canOverride:P,isMe:c,claiming:p}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>a(s),children:[e.jsx(ws,{className:"h-3 w-3 mr-1"})," View"]}),d&&s.status!=="approved"&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>t(s.id),children:"Approve"}),d&&s.status!=="rejected"&&e.jsx($,{size:"sm",variant:"ghost",className:"text-destructive",onClick:()=>r(s),children:"Reject"})]})]})})}function qm({scan:s}){var f,_;if(s.status==="scanning"||s.status==="pending")return e.jsx(z,{className:"border-dashed",children:e.jsxs(V,{className:"p-4 flex items-center gap-3",children:[e.jsx(xs,{className:"h-5 w-5 animate-spin text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Scan in progress..."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"VirusTotal is analysing the file. This may take a minute."})]})]})});if(s.status==="error")return e.jsx(z,{className:"border-destructive/30",children:e.jsxs(V,{className:"p-4 flex items-center gap-3",children:[e.jsx(Hi,{className:"h-5 w-5 text-destructive"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Scan failed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Could not complete the security scan."})]})]})});const t=(f=s.result)==null?void 0:f.stats;if(!t)return e.jsx(z,{className:"border-dashed",children:e.jsx(V,{className:"p-4",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No scan data available."})})});const r=t.malicious||0,n=t.suspicious||0,a=t.undetected||0,l=t.harmless||0,o=r+n+a+l+(t.timeout||0)+(t["type-unsupported"]||0)+(t.failure||0),j=r+n,b=o>0?Math.round((a+l)/o*100):0,c=j===0,d=r===0&&n>0,P=c?yl:d?Vt:Hi,k=c?"text-emerald-500":d?"text-amber-500":"text-destructive",p=c?"Clean":d?"Suspicious":`${j} Threat(s) Detected`,h=[];if((_=s.result)!=null&&_.results)for(const[m,u]of Object.entries(s.result.results))((u==null?void 0:u.category)==="malicious"||(u==null?void 0:u.category)==="suspicious")&&h.push({name:m,result:u.result||u.category});return e.jsx(z,{className:`${c?"border-emerald-500/20":d?"border-amber-500/20":"border-destructive/20"}`,children:e.jsxs(V,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(P,{className:`h-6 w-6 ${k}`}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:`text-sm font-semibold ${k}`,children:p}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o," engines scanned ⢠",b,"% clean"]})]})]}),e.jsx(uc,{value:b,className:"h-2"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center text-xs",children:[e.jsxs("div",{className:"rounded-md bg-emerald-500/10 p-2",children:[e.jsx("p",{className:"font-bold text-emerald-500",children:a+l}),e.jsx("p",{className:"text-muted-foreground",children:"Clean"})]}),e.jsxs("div",{className:"rounded-md bg-amber-500/10 p-2",children:[e.jsx("p",{className:"font-bold text-amber-500",children:n}),e.jsx("p",{className:"text-muted-foreground",children:"Suspicious"})]}),e.jsxs("div",{className:"rounded-md bg-destructive/10 p-2",children:[e.jsx("p",{className:"font-bold text-destructive",children:r}),e.jsx("p",{className:"text-muted-foreground",children:"Malicious"})]})]}),h.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Flagged by:"}),h.slice(0,10).map(m=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-foreground",children:m.name}),e.jsx("span",{className:"text-destructive font-medium",children:m.result})]},m.name)),h.length>10&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["...and ",h.length-10," more"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ta,{className:"h-3 w-3"}
119)," Scanned ",new Date(s.created_at).toLocaleString()]})]})})}function Wm(){const{user:s,isOwner:t,hasPermission:r}=vs(),[n,a]=i.useState([]),[l,o]=i.useState({}),[j,b]=i.useState(!0),[c,d]=i.useState(""),[P,k]=i.useState("all"),[p,h]=i.useState("newest"),[f,_]=i.useState(null),[m,u]=i.useState(""),g=async()=>{b(!0);const w=await Fs(()=>x.from("reviews").select("*").order("created_at",{ascending:!1}));if(w.length){const F=[...new Set(w.map(D=>D.user_id))],J=[...new Set(w.map(D=>D.product_id))],[E,N,U]=await Promise.all([Fs(()=>x.from("profiles").select("user_id, display_name").in("user_id",F.length?F:["__none__"])),Fs(()=>x.from("products").select("id, name").in("id",J.length?J:["__none__"])),Fs(()=>x.from("review_replies").select("*").in("review_id",w.map(D=>D.id)).order("created_at",{ascending:!0}))]),R={};E==null||E.forEach(D=>{R[D.user_id]=D.display_name||"Unknown"});const Z={};N==null||N.forEach(D=>{Z[D.id]=D.name}),o(Z);const W={};U==null||U.forEach(D=>{W[D.review_id]||(W[D.review_id]=[]),W[D.review_id].push(D)}),a(w.map(D=>({...D,display_name:R[D.user_id]||"Unknown",product_name:Z[D.product_id]||"Unknown Product",replies:W[D.id]||[]})))}b(!1)};i.useEffect(()=>{g()},[]);const S=async w=>{if(!(t||r("manage_reviews"))){O.error("You do not have permission to delete reviews");return}if(!confirm("Delete this review?"))return;const J=n.find(N=>N.id===w),{error:E}=await x.from("reviews").delete().eq("id",w);E?O.error(E.message):(O.success("Review deleted"),ss("delete_review","review",w,{target_name:(J==null?void 0:J.display_name)||"Unknown",product_name:(J==null?void 0:J.product_name)||"Unknown",rating:J==null?void 0:J.rating,comment_preview:((J==null?void 0:J.comment)||"").slice(0,200)}),g())},M=async w=>{if(!(t||r("manage_reviews"))){O.error("You do not have permission to reply to reviews");return}if(!m.trim()||!s)return;const{error:J}=await x.from("review_replies").insert({review_id:w,user_id:s.id,message:m.trim(),is_staff_reply:!0});if(J)O.error(J.message);else{const E=n.find(N=>N.id===w);O.success("Reply posted"),ss("reply_review","review",w,{target_name:(E==null?void 0:E.display_name)||"Unknown",product_name:(E==null?void 0:E.product_name)||"Unknown",reply_preview:m.trim().slice(0,200)}),u(""),_(null),g()}},y=n.filter(w=>{const F=!c||w.display_name.toLowerCase().includes(c.toLowerCase())||(w.comment||"").toLowerCase().includes(c.toLowerCase())||w.product_name.toLowerCase().includes(c.toLowerCase()),J=P==="all"||w.rating===parseInt(P,10);return F&&J}).sort((w,F)=>p==="oldest"?new Date(w.created_at).getTime()-new Date(F.created_at).getTime():p==="rating_high"?F.rating-w.rating:p==="rating_low"?w.rating-F.rating:new Date(F.created_at).getTime()-new Date(w.created_at).getTime());return j?e.jsx(cs,{}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(Gs,{placeholder:"Search reviews...",value:c,onChange:d,className:"bg-background/50",wrapperClassName:"flex-1"}),e.jsxs(Pe,{value:P,onValueChange:k,children:[e.jsx(Te,{className:"w-[140px] bg-background/50",children:e.jsx(De,{placeholder:"Rating"})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Ratings"}),[5,4,3,2,1].map(w=>e.jsxs(L,{value:String(w),children:[w," Star",w!==1?"s":""]},w))]})]}),e.jsxs(Pe,{value:p,onValueChange:h,children:[e.jsx(Te,{className:"w-[160px] bg-background/50",children:e.jsx(De,{placeholder:"Sort"})}),e.jsxs(Me,{children:[e.jsx(L,{value:"newest",children:"Newest First"}),e.jsx(L,{value:"oldest",children:"Oldest First"}),e.jsx(L,{value:"rating_high",children:"Highest Rated"}),e.jsx(L,{value:"rating_low",children:"Lowest Rated"})]})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[y.length," review",y.length!==1?"s":""]}),e.jsxs("div",{className:"space-y-3",children:[y.map(w=>e.jsx(z,{className:"glass",children:e.jsx(V,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-display font-semibold text-sm",children:w.display_name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"on"}),e.jsx(Y,{variant:"secondary",className:"text-xs",children:l[w.product_id]||w.product_name}),e.jsx("div",{className:"flex",children:[1,2,3,4,5].map(F=>e.jsx(or,{className:`h-3 w-3 ${F<=w.rating?"text-yellow-400 fill-yellow-400":"text-muted-foreground
119/30"}`},F))}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(w.created_at).toLocaleDateString()})]}),w.comment&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:w.comment}),w.replies.length>0&&e.jsx("div",{className:"mt-2 space-y-1 pl-4 border-l-2 border-primary/20",children:w.replies.map(F=>e.jsxs("div",{className:"text-xs",children:[e.jsxs("span",{className:"font-semibold",children:[F.is_staff_reply?"Staff":"User",":"]})," ",e.jsx("span",{className:"text-muted-foreground",children:F.message})]},F.id))}),f===w.id&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(ke,{placeholder:"Write a reply...",value:m,onChange:F=>u(F.target.value),className:"bg-background/50 text-sm h-8",onKeyDown:F=>F.key==="Enter"&&M(w.id)}),e.jsx($,{size:"sm",className:"h-8",onClick:()=>M(w.id),children:e.jsx(qt,{className:"h-3 w-3"})})]})]}),e.jsxs("div",{className:"flex gap-1 shrink-0",children:[e.jsx($,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{_(f===w.id?null:w.id),u("")},children:e.jsx(er,{className:"h-3 w-3"})}),e.jsx($,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-destructive hover:text-destructive",onClick:()=>S(w.id),children:e.jsx(As,{className:"h-3 w-3"})})]})]})})},w.id)),y.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No reviews found"})]})]})}const Gm=[{min_price:0,max_price:10,fee_type:"percentage",fee_value:20},{min_price:10,max_price:50,fee_type:"percentage",fee_value:15},{min_price:50,max_price:null,fee_type:"percentage",fee_value:10}];function Hm(){const[s,t]=i.useState("general");return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex gap-1 flex-wrap",children:[{key:"general",label:"General Settings",icon:rr},{key:"flags",label:"Feature Flags",icon:Nc},{key:"admins",label:"Admin Users",icon:Ma},{key:"system",label:"System & Backup",icon:nn}].map(r=>{const n=r.icon;return e.jsxs($,{size:"sm",variant:s===r.key?"default":"ghost",onClick:()=>t(r.key),className:"gap-1.5 text-xs",children:[e.jsx(n,{className:"h-4 w-4"})," ",r.label]},r.key)})}),s==="general"&&e.jsx(Km,{}),s==="flags"&&e.jsx(Jm,{}),s==="admins"&&e.jsx(Qm,{}),s==="system"&&e.jsx(Ym,{})]})}function Km(){const[s,t]=i.useState({}),[r,n]=i.useState(Gm),[a,l]=i.useState(!1),[o,j]=i.useState(!1);i.useEffect(()=>{x.from("site_settings").select("key, value").then(({data:p})=>{const h={};if(p==null||p.forEach(f=>h[f.key]=f.value),t(h),h.platform_fee_rules)try{n(JSON.parse(h.platform_fee_rules))}catch{}j(!0)})},[]);const b=async()=>{l(!0);const p=[...Gn.map(m=>m.key),"platform_fee_rules"],h={...s,platform_fee_rules:JSON.stringify(r)},f=p.map(m=>({key:m,value:h[m]||""})),{error:_}=await x.from("site_settings").upsert(f,{onConflict:"key"});_?O.error(_.message):(O.success("Settings saved!"),ss("update_settings","settings",void 0,{keys:p})),l(!1)},c=(p,h,f)=>{const _=[...r];_[p]={..._[p],[h]:f},n(_)},d=()=>{const p=r.length>0?r[r.length-1].max_price||100:0;n([...r,{min_price:p,max_price:null,fee_type:"percentage",fee_value:10}])},P=p=>{n(r.filter((h,f)=>f!==p))};if(!o)return e.jsx(cs,{className:"py-8"});const k=[...new Set(Gn.map(p=>p.section))];return e.jsxs("div",{className:"max-w-lg space-y-8",children:[k.map(p=>e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-display font-semibold mb-4",children:p}),e.jsx("div",{className:"space-y-4",children:Gn.filter(h=>h.section===p).map(h=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm font-medium text-muted-foreground",children:h.label}),e.jsx(ke,{placeholder:h.placeholder,value:s[h.key]||"",onChange:f=>t({...s,[h.key]:f.target.value}),className:"bg-background/50"}),"hint"in h&&h.hint&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h.hint})]},h.key))})]},p)),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-display font-semibold mb-2",children:"Marketplace Fees"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Set different fee rates based on product price. Rules are checked in order - the first matching rule applies."}),e.jsx(z,{className:"glass mb-4 border-primary/20",children:e.jsxs(V,{className:"p-4 space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(kt,{className:"h-4 w-4 text-primary"}),"Creator Tier Fee Overrides"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"These override the price-based rules above for creators with special tiers."}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 mt-2",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/50 px-3 py-2 border border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{variant:"outline",className:"bg-emerald-500/10 text-emerald-400 border-emerald-500/30 text-xs",children:"Trusted"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Verified creators"})]}),e.jsx("span",{className:"text-sm font-bold text-primary",children:"3%"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/50 px-3 py-2 border border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{variant:"outline",className:"bg-violet-500/10 text-violet-400 border-violet-500/30 text-xs",children:"Partnered"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Official partners"})]}),e.jsx("span",{className:"text-sm font-bold text-primary",children:"3%"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/50 px-3 py-2 border border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{variant:"outline",className:"text-xs",children:"Standard"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"All other creators"})]}),e.jsx("span",{className:"text-sm font-bold text-muted-foreground",children:"Uses rules below"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md bg-background/50 px-3 py-2 border border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{variant:"outline",className:"bg-yellow-500/10 text-yellow-400 border-yellow-500/30 text-xs",children:"First 10 Sales"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"All new creators"})]}),e.jsx("span",{className:"text-sm font-bold text-green-400",children:"0% (free)"})]})]})]})}),e.jsxs("div",{className:"space-y-3",children:[r.map((p,h)=>e.jsx(z,{className:"glass",children:e.jsx(V,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:"Price"}),e.jsxs("span",{className:"text-xs font-medium",children:["$",p.min_price]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"to"}),e.jsx(ke,{type:"number",min:"0",className:"w-20 h-7 text-xs bg-background/50",placeholder:"infinity",value:p.max_price??"",onChange:f=>c(h,"max_price",f.target.value?Number(f.target.value):null)}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"to"}),e.jsxs(Pe,{value:p.fee_type,onValueChange:f=>c(h,"fee_type",f),children:[e.jsx(Te,{className:"w-24 h-7 text-xs bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"percentage",children:"%"}),e.jsx(L,{value:"fixed",children:"$ flat"})]})]}),e.jsx(ke,{type:"number",step:"0.01",min:"0",className:"w-16 h-7 text-xs bg-background/50",value:p.fee_value,onChange:f=>c(h,"fee_value",Number(f.target.value))}),e.jsx($,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-destructive",onClick:()=>P(h),children:e.jsx(As,{className:"h-3 w-3"})})]})})},h)),e.jsxs($,{size:"sm",variant:"outline",onClick:d,children:[e.jsx(Fa,{className:"h-3 w-3 mr-1"})," Add Rule"]})]})]}),e.jsx(pa,{loading:a,onClick:b,children:"Save Settings"})]})}function Jm(){const[s,t]=i.useState([]),[r,n]=i.useState(!0),[a,l]=i.useState(""),[o,j]=i.useState(""),[b,c]=i.useState(""),[d,P]=i.useState("key_asc"),[k,p]=i.useState("all"),[h,f]=i.useState(null),[_,m]=i.useState("");i.useEffect(()=>{x.from("feature_flags").select("*").order("key").then(({data:E})=>{t(E||[]),n(!1)})},[]);const u=async(E,N)=>{const U=N==="enabled"||N==="beta",{error:R}=await x.from("feature_flags").update({mode:N,enabled:U,updated_at:new Date().toISOString()}).eq("id",E.id);if(R){O.error(R.message);return}t(Z=>Z.map(W=>W.id===E.id?{...W,mode:N,enabled:U}:W)),O.success(`${E.key} set to ${N==="admin_only"?"development":N}`),ss("update_settings","feature_flag",E.key,{mode:N})},g=async E=>{const N=w.filter(U=>U.enabled!==E);if(N.length!==0&&confirm(`${E?"Enable":"Disable"} ${N.length} flag(s)?`)){for(const U of N)await x.from("feature_flags").update({enabled:E,updated_at:new Date().toISOString()}).eq("id",U.id);t(U=>U.map(R=>N.some(Z=>Z.id===R.id)?{...R,enabled:E}:R)),O.success(`${N.length} flags ${E?"enabled":"disabled"}`)}},S=async E=>{const{error:N}=await x.from("feature_flags").update({description:_||null,updated_at:new Date().toISOString()}).eq("id",E.id);if(N){O.error(N.message);return}t(U=>U.map(R=>R.id===E.id?{...R,description:_||null}:R)),f(null),O.success("Description updated")},M=async()=>
119{if(!a.trim())return;const E=a.trim().toLowerCase().replace(/\s+/g,"_").replace(/[^a-z0-9_]/g,""),{data:N,error:U}=await x.from("feature_flags").insert({key:E,description:o||null,enabled:!1}).select().single();if(U){O.error(U.message);return}t(R=>[...R,N].sort((Z,W)=>Z.key.localeCompare(W.key))),l(""),j(""),O.success("Flag created")},y=async E=>{confirm(`Delete flag "${E.key}"?`)&&(await x.from("feature_flags").delete().eq("id",E.id),t(N=>N.filter(U=>U.id!==E.id)),O.success("Flag deleted"))},w=s.filter(E=>!(b&&!E.key.toLowerCase().includes(b.toLowerCase())&&!(E.description||"").toLowerCase().includes(b.toLowerCase())||k==="on"&&!E.enabled||k==="off"&&E.enabled)).sort((E,N)=>{switch(d){case"key_desc":return N.key.localeCompare(E.key);case"status_on":return(N.enabled?1:0)-(E.enabled?1:0);case"status_off":return(E.enabled?1:0)-(N.enabled?1:0);default:return E.key.localeCompare(N.key)}}),F=s.filter(E=>E.enabled).length,J=s.length-F;return r?e.jsx(cs,{className:"py-8"}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-display font-semibold mb-1",children:["Feature Flags (",s.length,")"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsxs("span",{className:"text-emerald-400",children:[F," enabled"]})," · ",e.jsxs("span",{className:"text-yellow-400",children:[J," disabled"]})," · Changes take effect immediately."]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"sm",variant:"outline",className:"text-xs",onClick:()=>g(!0),children:"Enable All Shown"}),e.jsx($,{size:"sm",variant:"outline",className:"text-xs",onClick:()=>g(!1),children:"Disable All Shown"})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(Gs,{placeholder:"Search flags...",value:b,onChange:c,className:"bg-background/50 h-9",wrapperClassName:"flex-1 min-w-[200px]"}),e.jsxs(Pe,{value:k,onValueChange:E=>p(E),children:[e.jsx(Te,{className:"w-28 h-9 text-xs bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All"}),e.jsx(L,{value:"on",children:"Enabled"}),e.jsx(L,{value:"off",children:"Disabled"})]})]}),e.jsxs(Pe,{value:d,onValueChange:E=>P(E),children:[e.jsx(Te,{className:"w-32 h-9 text-xs bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"key_asc",children:"Name A to Z"}),e.jsx(L,{value:"key_desc",children:"Name Z to A"}),e.jsx(L,{value:"status_on",children:"Enabled first"}),e.jsx(L,{value:"status_off",children:"Disabled first"})]})]})]}),e.jsx(z,{className:"glass",children:e.jsx(V,{className:"p-4",children:e.jsxs("div",{className:"flex gap-2 flex-wrap items-end",children:[e.jsxs("div",{className:"space-y-1 flex-1 min-w-[150px]",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Key"}),e.jsx(ke,{placeholder:"e.g. enable_new_feature",value:a,onChange:E=>l(E.target.value),className:"bg-background/50 h-8 text-sm"})]}),e.jsxs("div",{className:"space-y-1 flex-1 min-w-[200px]",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Description"}),e.jsx(ke,{placeholder:"What this flag controls",value:o,onChange:E=>j(E.target.value),className:"bg-background/50 h-8 text-sm"})]}),e.jsxs($,{size:"sm",onClick:M,disabled:!a.trim(),className:"h-8",children:[e.jsx(Fa,{className:"h-3 w-3 mr-1"})," Add"]})]})})}),e.jsxs("div",{className:"space-y-2",children:[w.map(E=>{const N=E.mode||(E.enabled?"enabled":"disabled"),U=N==="enabled"?"bg-secondary/30":N==="beta"?"bg-blue-500/5 border border-blue-500/15":N==="admin_only"?"bg-orange-500/5 border border-orange-500/15":"bg-destructive/5 border border-destructive/10",R=N==="admin_only"?"Development":N==="beta"?"Beta":N==="enabled"?"Enabled":"Disabled",Z=N==="enabled"?"bg-emerald-500/20 text-emerald-400":N==="beta"?"bg-blue-500/20 text-blue-400":N==="admin_only"?"bg-orange-500/20 text-orange-400":"bg-destructive/20 text-destructive";return e.jsxs("div",{className:`flex items-center justify-between p-3 rounded-lg transition-colors ${U}`,children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium font-mono",children:E.key}),e.jsx(Y,{className:`text-[10px] ${Z}`,children:R})]}),h===E.id?e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx(ke,{value:_,onCh
119ange:W=>m(W.target.value),placeholder:"Enter description...",className:"h-7 text-xs bg-background/50 flex-1",autoFocus:!0,onKeyDown:W=>{W.key==="Enter"&&S(E),W.key==="Escape"&&f(null)}}),e.jsx($,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>S(E),children:"Save"}),e.jsx($,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs text-muted-foreground",onClick:()=>f(null),children:"Cancel"})]}):e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 cursor-pointer hover:text-foreground transition-colors",onClick:()=>{f(E.id),m(E.description||"")},title:"Click to edit description",children:E.description||e.jsx("span",{className:"italic opacity-50",children:"Click to add description..."})})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs(Pe,{value:N,onValueChange:W=>u(E,W),children:[e.jsx(Te,{className:"w-[130px] h-8 text-xs bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"disabled",children:"Disabled"}),e.jsx(L,{value:"enabled",children:"Enabled"}),e.jsx(L,{value:"admin_only",children:"Development"}),e.jsx(L,{value:"beta",children:"Beta"})]})]}),e.jsx($,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-destructive",onClick:()=>y(E),children:e.jsx(As,{className:"h-3 w-3"})})]})]},E.id)}),w.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:b||k!=="all"?"No matching flags":"No feature flags configured"})]})]})}function Qm(){const[s,t]=i.useState([]),[r,n]=i.useState({}),[a,l]=i.useState(!0),[o,j]=i.useState(""),[b,c]=i.useState(!1),d=async()=>{const{data:p}=await x.from("user_roles").select("*").in("role",["admin","owner"]);if(t(p||[]),p&&p.length>0){const h=[...new Set(p.map(m=>m.user_id))],{data:f}=await x.from("profiles").select("user_id, display_name, avatar_url").in("user_id",h),_={};f==null||f.forEach(m=>{_[m.user_id]=m}),n(_)}l(!1)};i.useEffect(()=>{d()},[]);const P=async()=>{if(!o.trim())return;c(!0);const{data:p}=await x.from("profiles").select("user_id, display_name").ilike("display_name",`%${o.trim()}%`).limit(1).single();if(!p){O.error("User not found. Search by display name."),c(!1);return}if(s.find(_=>_.user_id===p.user_id&&_.role==="admin")){O.error("User is already an admin"),c(!1);return}const{error:f}=await x.from("user_roles").insert({user_id:p.user_id,role:"admin"});if(f){O.error(f.message),c(!1);return}O.success(`${p.display_name} added as admin`),ss("set_admin","user",p.user_id,{display_name:p.display_name}),j(""),c(!1),d()},k=async p=>{var h,f;if(p.role==="owner"){O.error("Cannot remove owner role");return}confirm(`Remove admin role from ${((h=r[p.user_id])==null?void 0:h.display_name)||p.user_id}?`)&&(await x.from("user_roles").delete().eq("id",p.id),O.success("Admin role removed"),ss("remove_admin","user",p.user_id,{display_name:(f=r[p.user_id])==null?void 0:f.display_name}),d())};return a?e.jsx(cs,{className:"py-8"}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-display font-semibold mb-2",children:"Admin Users"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Manage who has admin-level access to the platform."})]}),e.jsx(z,{className:"glass",children:e.jsx(V,{className:"p-4",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{placeholder:"Search by display name...",value:o,onChange:p=>j(p.target.value),className:"bg-background/50"}),e.jsx(pa,{loading:b,icon:$a,onClick:P,disabled:b||!o.trim(),children:"Add Admin"})]})})}),e.jsx("div",{className:"space-y-2",children:s.map(p=>{const h=r[p.user_id];return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-secondary/30",children:[e.jsxs(Bs,{className:"h-8 w-8",children:[(h==null?void 0:h.avatar_url)&&e.jsx(it,{src:h.avatar_url}),e.jsx(qs,{className:"text-xs bg-primary/10 text-primary",children:((h==null?void 0:h.display_name)||"?")[0].toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:(h==null?void 0:h.display_name)||p.user_id.slice(0,8)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[p.user_id.slice(0,12),"..."]})]}),e.jsx(Y,{variant:p.role==="owner"?"default":"secondary",className:"text-xs capitalize",children:p.role}),p.role!=="owner"&&e.jsxs($,{size:"sm",variant:"ghost",className:"h-7 text-xs text-destructive",onClick:()=>k(p),children:[e.jsx(As,{className:"h-3 w-3 mr-1"})," Remove"]})]}
119,p.id)})})]})}function Ym(){const[s,t]=i.useState([]),[r,n]=i.useState(!0);return i.useEffect(()=>{x.from("activity_logs").select("*").order("created_at",{ascending:!1}).limit(20).then(({data:a})=>{t(a||[]),n(!1)})},[]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-display font-semibold mb-2",children:"System & Backup"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Database backup, system tools, and recent activity."})]}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("h3",{className:"text-lg font-display font-semibold mb-3 flex items-center gap-2",children:[e.jsx(nn,{className:"h-4 w-4"})," Database Backup & Export"]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Your database is automatically backed up by Lovable Cloud. To export data, use the Cloud panel in the editor."}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>O.info("Open editor -> Cloud tab -> Database -> Tables -> Export to download your data."),children:[e.jsx(nt,{className:"h-4 w-4 mr-1"})," Export Instructions"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{x.from("site_settings").select("*").then(({data:a})=>{if(!a)return;const l=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),o=URL.createObjectURL(l),j=document.createElement("a");j.href=o,j.download="site-settings-backup.json",j.click(),URL.revokeObjectURL(o),O.success("Settings exported")})},children:[e.jsx(nt,{className:"h-4 w-4 mr-1"})," Export Settings JSON"]})]})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("h3",{className:"text-lg font-display font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Dt,{className:"h-4 w-4"})," Recent System Activity (Last 20)"]}),r?e.jsx(cs,{className:"py-4",size:"sm"}):s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No recent activity"}):e.jsx("div",{className:"space-y-1.5 max-h-80 overflow-y-auto",children:s.map(a=>{var l;return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded bg-secondary/20 text-xs",children:[e.jsx(Y,{variant:"outline",className:"text-[10px] shrink-0",children:a.action.replace(/_/g," ")}),e.jsx("span",{className:"text-muted-foreground truncate flex-1",children:a.target_type&&`${a.target_type}: ${((l=a.target_id)==null?void 0:l.slice(0,8))||"-"}`}),e.jsx("span",{className:"text-muted-foreground shrink-0",children:new Date(a.created_at).toLocaleString()})]},a.id)})})]})})]})}function Zm(){const[s,t]=i.useState({}),[r,n]=i.useState(!1),[a,l]=i.useState(!1);i.useEffect(()=>{x.from("site_settings").select("key, value").then(({data:b})=>{const c={};b==null||b.forEach(d=>c[d.key]=d.value),t(c),l(!0)})},[]);const o=async()=>{n(!0);const b=Hn.map(d=>({key:d.key,value:s[d.key]||""})),{error:c}=await x.from("site_settings").upsert(b,{onConflict:"key"});c?O.error(c.message):(O.success("Theme settings saved!"),ss("update_theme","settings")),n(!1)};if(!a)return e.jsx(cs,{className:"py-8"});const j=[...new Set(Hn.map(b=>b.section))];return e.jsxs("div",{className:"max-w-lg space-y-8",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vl,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-display font-semibold",children:"Theme & Branding"})]}),j.map(b=>e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-display font-semibold text-muted-foreground uppercase tracking-wider mb-3",children:b}),e.jsx("div",{className:"space-y-4",children:Hn.filter(c=>c.section===b).map(c=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-sm font-medium",children:c.label}),c.type==="color"?e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{type:"color",value:s[c.key]||c.default||"#000000",onChange:d=>t({...s,[c.key]:d.target.value}),className:"w-10 h-10 rounded cursor-pointer border border-border"}),e.jsx(ke,{value:s[c.key]||c.default||"",onChange:d=>t({...s,[c.key]:d.target.value}),className:"bg-background/50 flex-1",placeholder:c.default})]}):c.type==="textarea"?e.jsx($s,{value:s[c.key]||"",onChange:d=>t({...s,[c.key]:d.target.value}),className:"bg-background/50 font-mono text-xs",placeholder:c.placeholder,rows:4}):e.jsx(ke,{value:s[c.key]||"",onChange:d=>t({...s,[c.key]:d.target.value}),className:"bg-background/50",placeholder:c.placeholder})]},c.key))})]},b)),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4",children:[e.jsx("h4",{className:"text-sm font-display font-semibold mb-3",children:"Preview"}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex-1 rounded-lg p-4 text-center text-sm font-medium",style:{backgroundColor:s.brand_primary_color||"#00ff96",color:"#0f1318"},children:"Primary"}),e.jsx("div",{className:"flex-1 rounded-lg p-4 text-center text-sm font-medium",style:{backgroundColor:s.brand_accent_color||"#a855f7",color:"#fff"},children:"Accent"}),e.jsx("div",{className:"flex-1 rounded-lg p-4 text-center text-sm font-medium border border-border",style:{backgroundColor:s.brand_background_color||"#0f1318",color:"#e8eaed"}
119,children:"Background"})]})]})}),e.jsx(pa,{loading:r,onClick:o,children:"Save Theme Settings"})]})}function Kn({permission:s,children:t,showDenied:r=!1,fallback:n}){const{isOwner:a,hasPermission:l}=vs(),o=Array.isArray(s)?s:[s];return a||o.some(b=>l(b))?e.jsx(e.Fragment,{children:t}):r?n?e.jsx(e.Fragment,{children:n}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-muted/30 flex items-center justify-center mb-3",children:e.jsx(kt,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx("h3",{className:"text-sm font-semibold text-foreground mb-1",children:"Access Restricted"}),e.jsx("p",{className:"text-xs text-muted-foreground max-w-xs",children:"You do not have permission to view this section. Contact an administrator if you believe this is an error."})]}):null}function ip(s){const{isOwner:t,hasPermission:r}=vs(),n=Array.isArray(s)?s:[s];return t||n.some(a=>r(a))}const ar=[{id:"products",label:"Products & Catalog",icon:vt,permissions:[{key:"manage_products",label:"Manage Products",description:"Create, edit, approve, reject, and delete products and bundles."},{key:"manage_boost",label:"Boost Scores",description:"Adjust product boost/ranking scores for visibility."}]},{id:"tickets",label:"Tickets & Support",icon:er,permissions:[{key:"view_tickets",label:"View Tickets",description:"Read support ticket details and history."},{key:"manage_tickets",label:"Manage Tickets",description:"Respond, close, assign, and escalate support tickets.",impliedBy:void 0},{key:"view_creator_tickets",label:"View Creator Tickets",description:"Read creator-specific ticket details."},{key:"manage_creator_tickets",label:"Manage Creator Tickets",description:"Respond to and manage creator tickets."},{key:"view_support_stats",label:"Support Statistics",description:"View ticket volume, response times, and staff performance."}]},{id:"users",label:"Users & Accounts",icon:Ma,permissions:[{key:"manage_users",label:"Manage Users",description:"Search, view details, and edit user accounts."},{key:"moderate_users",label:"Moderate Users",description:"Access user moderation tools and history."},{key:"ban_users",label:"Ban Users",description:"Suspend or ban user accounts from the platform."},{key:"delete_accounts",label:"Delete Accounts",description:"Permanently delete user accounts and their data."},{key:"grant_products",label:"Grant Products",description:"Give products to users without purchase (admin grants)."},{key:"remove_purchases",label:"Remove Purchases",description:"Revoke product access from user accounts."}]},{id:"moderation",label:"Moderation & Safety",icon:Br,permissions:[{key:"view_moderation",label:"View Reports",description:"Read user reports and flagged content."},{key:"manage_moderation",label:"Manage Reports",description:"Resolve reports, take action on flagged content."},{key:"override_claims",label:"Override Claims",description:"Take over tickets, products, and reports already claimed by another staff member."}]},{id:"reviews",label:"Reviews",icon:or,permissions:[{key:"manage_reviews",label:"Manage Reviews",description:"Delete inappropriate reviews and manage review responses."}]},{id:"financial",label:"Financial & Revenue",icon:rt,permissions:[{key:"view_revenue",label:"View Revenue",description:"Access all financial data: earnings, GMV, sales metrics, and payout info."},{key:"view_payments",label:"View Payments",description:"Access payment history and transaction details."},{key:"manage_orders",label:"Manage Orders",description:"View and manage purchase orders and disputes."},{key:"manage_sellers",label:"Manage Sellers",description:"Edit seller profiles, fees, and payout settings."},{key:"manage_creators",label:"Manage Creators",description:"Manage creator verifications and profiles."}]},{id:"marketing",label:"Marketing & Promotions",icon:pi,permissions:[{key:"manage_coupons",label:"Manage Coupons",description:"Create, edit, and deactivate discount coupons."},{key:"manage_discounts",label:"Manage Discounts",description:"Set product discounts and promotional pricing."},{key:"send_notifications",label:"Send Notifications",description:"Broadcast notifications and announcements to users."},{key:"manage_announcements",label:"Announcements",description:"Create and manage site-wide announcement banners."},{key:"manage_seo",label:"SEO Tools",description:"Manage meta tags, sitemaps, and search optimization."},{key:"manage_utm_links",label:"UTM Links",description:"Create and track UTM campaign links."}]},{id:"analytics",label:"Analytics & Insights",icon:zt,permissions:[{key:"view_anal
119ytics",label:"View Analytics",description:"Access traffic, session, and engagement analytics dashboards."},{key:"view_wishlists",label:"Wishlist Analytics",description:"View wishlist trends and popular items."},{key:"view_logs",label:"Activity Logs",description:"View admin action history and audit trail."}]},{id:"system",label:"System & Configuration",icon:rr,permissions:[{key:"manage_settings",label:"Site Settings",description:"Edit platform name, URLs, social links, and legal pages."},{key:"manage_themes",label:"Theme & Branding",description:"Customize colors, fonts, logos, and CSS overrides."},{key:"manage_storage",label:"File Storage",description:"Browse and manage uploaded files and storage buckets."},{key:"manage_status",label:"Status Page",description:"Update platform status and incident reports."},{key:"manage_content",label:"Content Pages",description:"Edit CMS pages and discovery lists."},{key:"manage_roles",label:"Manage Roles",description:"Create and edit custom roles and their permissions."},{key:"manage_permissions",label:"Staff Management",description:"Add/remove staff members and assign permissions."},{key:"view_applications",label:"View Applications",description:"Read staff applications submitted by users."},{key:"manage_applications",label:"Manage Applications",description:"Accept, reject, and review staff applications."}]},{id:"security",label:"Security",icon:It,permissions:[{key:"view_security",label:"View Security",description:"Access security dashboards, login history, and threat detection."},{key:"manage_security",label:"Manage Security",description:"Configure security settings and manage blocklists."},{key:"view_errors",label:"View Errors",description:"Access error logs and system warnings."},{key:"use_ai_agent",label:"AI Admin Agent",description:"Use the AI-powered admin assistant for data queries."}]},{id:"messaging",label:"Messaging",icon:ws,permissions:[{key:"view_messages",label:"View Messages",description:"Read user-to-user message threads (moderation)."},{key:"manage_messages",label:"Manage Messages",description:"Delete or moderate user messages."}]}],ro={manage_tickets:["view_tickets"],manage_creator_tickets:["view_creator_tickets"],manage_moderation:["view_moderation"],manage_security:["view_security"],manage_messages:["view_messages"],manage_applications:["view_applications"],view_payments:["view_revenue"],manage_orders:["view_revenue"],manage_sellers:["view_revenue"]};function Qr(s){const t=new Set(s);let r=!0;for(;r;){r=!1;for(const n of Array.from(t)){const a=ro[n];if(a)for(const l of a)t.has(l)||(t.add(l),r=!0)}}return Array.from(t)}function gl(s,t){for(const r of t){if(r===s)continue;const n=ro[r];if(n!=null&&n.includes(s))return!0}return!1}const Ir={support:{label:"Support Staff",color:"#3b82f6",description:"Can manage tickets and view basic reports. No product or revenue access.",permissions:["view_tickets","manage_tickets","view_creator_tickets","manage_creator_tickets","view_moderation","view_support_stats","view_applications"]},moderator:{label:"Moderator",color:"#f59e0b",description:"Can moderate content, users, and manage products. No revenue or settings access.",permissions:["view_tickets","manage_tickets","view_creator_tickets","manage_creator_tickets","view_moderation","manage_moderation","view_support_stats","view_applications","manage_products","manage_reviews","moderate_users","ban_users","view_analytics","view_messages","view_logs"]},senior_moderator:{label:"Senior Moderator",color:"#ef4444",description:"Full moderation access plus user management and limited analytics.",permissions:["view_tickets","manage_tickets","view_creator_tickets","manage_creator_tickets","view_moderation","manage_moderation","view_support_stats","view_applications","manage_applications","manage_products","manage_reviews","manage_users","moderate_users","ban_users","view_analytics","view_messages","manage_messages","view_logs","view_wishlists","send_notifications"]},admin:{label:"Administrator",color:"#10b981",description:"Full platform access including revenue, settings, and security.",permissions:["manage_products","manage_boost","view_tickets","manage_tickets","view_creator_tickets","manage_creator_tickets","view_support_stats","manage_users","moderate_users","ban_users","delete_accounts","grant_products","remove_purchases","view_moderation","manage_moderation","manage_reviews","view_revenue","view_payments","manage_orders","manage_sellers","manage_creators","manage_coupons","manage_discounts","send_notifications","manage_announcements","manage_seo","manage_utm_links","view_anal
119ytics","view_wishlists","view_logs","manage_settings","manage_themes","manage_storage","manage_status","manage_content","manage_roles","manage_permissions","view_applications","manage_applications","view_security","manage_security","view_errors","use_ai_agent","view_messages","manage_messages","override_claims"]}};function Xm(s){const t=[];for(const n of ar){const a=n.permissions.filter(l=>s.includes(l.key));a.length!==0&&(a.length===n.permissions.length?t.push(`Full ${n.label} access`):t.push(`${n.label}: ${a.map(l=>l.label).join(", ")}`))}const r=[];return s.includes("view_revenue")||r.push("revenue data"),s.includes("manage_settings")||r.push("site settings"),s.includes("delete_accounts")||r.push("account deletion"),r.length>0&&t.push(`No access to: ${r.join(", ")}`),t}function no({selected:s,onChange:t,disabled:r=!1,inheritedPerms:n=[]}){const[a,l]=i.useState(""),[o,j]=i.useState(new Set(ar.map(h=>h.id))),b=a.toLowerCase().trim(),c=i.useMemo(()=>b?ar.map(h=>({...h,permissions:h.permissions.filter(f=>f.label.toLowerCase().includes(b)||f.description.toLowerCase().includes(b)||f.key.includes(b))})).filter(h=>h.permissions.length>0):ar,[b]),d=h=>{j(f=>{const _=new Set(f);return _.has(h)?_.delete(h):_.add(h),_})},P=h=>{if(r)return;let f;s.includes(h)?f=s.filter(_=>_!==h):(f=[...s,h],f=Qr(f)),t(f)},k=h=>{if(r)return;const f=h.permissions.map(u=>u.key),_=f.every(u=>s.includes(u));let m;_?m=s.filter(u=>!f.includes(u)||gl(u,s.filter(g=>!f.includes(g)))):(m=[...new Set([...s,...f])],m=Qr(m)),t(m)},p=i.useMemo(()=>Xm(s),[s]);return e.jsx(Yr,{delayDuration:300,children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ke,{value:a,onChange:h=>l(h.target.value),placeholder:"Search permissions...",className:"pl-8 h-8 text-xs bg-background/50"})]}),s.length>0&&!b&&e.jsxs("div",{className:"rounded-lg border border-border/40 bg-muted/20 p-2.5",children:[e.jsx("p",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wider mb-1.5",children:"Role Summary"}),e.jsx("div",{className:"space-y-0.5",children:p.map((h,f)=>e.jsxs("div",{className:"flex items-start gap-1.5 text-xs",children:[e.jsx(xc,{className:"h-3 w-3 text-primary mt-0.5 shrink-0"}),e.jsx("span",{className:"text-muted-foreground",children:h})]},f))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.length," permission",s.length!==1?"s":""," selected"]}),s.length>0&&!r&&e.jsx("button",{onClick:()=>t([]),className:"text-xs text-destructive hover:underline",children:"Clear all"})]}),e.jsxs("div",{className:"space-y-1",children:[c.map(h=>{const f=h.icon,_=h.permissions.map(S=>S.key),m=_.filter(S=>s.includes(S)||n.includes(S)).length,u=_.every(S=>s.includes(S)),g=o.has(h.id)||!!b;return e.jsx(gt,{open:g,onOpenChange:()=>!b&&d(h.id),children:e.jsxs("div",{className:"rounded-lg border border-border/30 overflow-hidden",children:[e.jsx(ft,{className:"w-full",children:e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 hover:bg-muted/20 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(f,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:h.label}),e.jsxs(Y,{variant:u?"default":m>0?"secondary":"outline",className:"text-[9px] px-1.5 py-0 h-4",children:[m,"/",h.permissions.length]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!r&&e.jsx("button",{onClick:S=>{S.stopPropagation(),k(h)},className:`text-[10px] px-2 py-0.5 rounded-full border transition-colors ${u?"bg-primary/10 border-primary/30 text-primary":"border-border/50 text-muted-foreground hover:border-primary/30"}`,children:u?"Disable all":"Enable all"}),e.jsx(js,{className:`h-3.5 w-3.5 text-muted-foreground transition-transform ${g?"rotate-0":"-rotate-90"}`})]})]})}),e.jsx(jt,{children:e.jsx("div",{className:"px-3 pb-2 space-y-0.5",children:h.permissions.map(S=>{const M=s.includes(S.key),y=n.includes(S.key)&&!M,w=gl(S.key,s);return e.jsxs("div",{className:"flex items-center gap-2.5 py-1.5 px-2 rounded-md hover:bg-muted/20 transition-colors",children:[e.jsx(Ca,{checked:M||y,onCheckedChange:()=>P(S.key),disabled:r||y||w,className:"shrink-0"}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`text-sm ${y?"text-muted-foreground":""}`,children:S.label}),y&&e.jsx(Y,{variant:"outline",className:"text-[9px] px-1 py-0 h-3.5",children:"via role"}),w&&M&&e.jsx(Y,{variant:"outline",className:"text-[9px] px-1 py-0 h-3.5 border-amber-500/50 text-amber-400",children:"required"})]})}),e.jsxs(en,{children:[e.jsx(sn,{asChild:!0,children:e.jsx(kl,{className:"h-3.5 w-3.5 text-muted-foreground
119/50 shrink-0 cursor-help"})}),e.jsx(tn,{side:"left",className:"max-w-[220px] text-xs",children:S.description})]})]},S.key)})})})]})},h.id)}),c.length===0&&e.jsxs("p",{className:"text-center text-xs text-muted-foreground py-4",children:['No permissions match "',a,'"']})]})]})})}const eu=i.lazy(()=>as(()=>import("./StatusTab-DNLb_geY.js"),__vite__mapDeps([7,2,3,1,4,5,6,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77]))),su=i.lazy(()=>as(()=>import("./ErrorsTab-BqEohgp-.js"),__vite__mapDeps([78,2,3,1,4,5,6,9,10,11,17,13,43,37,76,49,18,19,20,21,22,23,24,8,12,25,26,27,28,14,29,30,31,32,33,34,15,35,36,38,39,40,41,42,44,45,46,47,48,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,77]))),tu=i.lazy(()=>as(()=>import("./AgentTab-DkP0A-h8.js"),__vite__mapDeps([79,2,3,1,4,5,6,8,80,50,49,31,30,63,13,14,19,20,21,22,23,24,9,10,11,12,25,26,27,28,29,32,33,34,15,35,36,37,38,39,40,41,42,43,44,45,46,47,48,51,52,53,54,55,56,57,58,59,60,61,62,64,65,66,67,68,69,70,71,72,73,74,75,76,77]))),au=i.lazy(()=>as(()=>import("./AdvertisingTab-BfXvyVFl.js"),__vite__mapDeps([81,2,3,1,4,5,6,9,10,11,25,12,82,83,29,50,49,31,30,41,55,84,20,85,86,74,87,13,32]))),ru=i.lazy(()=>as(()=>import("./ImportsTab-lIuCMszi.js"),__vite__mapDeps([88,1,2,3,4,5,6,89,90,91,92,93,77,45,68,46,41,72,43,31,16,17,94,12,82,9,10,11,80,29,95,42,28,20,74,87,35,96,97,66,98,53,67,99,13,18]))),nu=i.lazy(()=>as(()=>import("./StressTestTab-BbpNp79S.js"),__vite__mapDeps([100,2,3,1,4,5,6,52,77,39,98,68,37,15]))),iu=i.lazy(()=>as(()=>import("./ProductAnalyticsTab-Cs8HYgHc.js"),__vite__mapDeps([101,2,3,1,4,5,6,9,10,11,82,83,29,42,43,24,102,37,41,36,75,49,50,31,20,38,39,19,21,22,23,8,12,25,26,27,28,14,30,32,33,34,15,35,40,13,44,45,46,47,48,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,76,77]))),lu=i.lazy(()=>as(()=>import("./DbPerformanceTab-Cr1S7mBN.js"),__vite__mapDeps([103,2,3,1,4,5,6,82,83,42,43,31,104,37,49,85,50,19,20,21,22,23,24,8,9,10,11,12,25,26,27,28,14,29,30,32,33,34,15,35,36,38,39,40,41,13,44,45,46,47,48,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77]))),ou=i.lazy(()=>as(()=>import("./LandingPageAnalyticsTab-Ctr0vPWV.js"),__vite__mapDeps([105,2,3,1,4,5,6,42,43,24,30,31,20,41,51,49,50,98,55,34]))),cu=i.lazy(()=>as(()=>import("./BetaFeaturesTab-Ni8HOxfm.js"),__vite__mapDeps([106,2,3,1,4,5,6,25,30,31,67]))),du=i.lazy(()=>as(()=>import("./BundlesTab-rdgRwc35.js"),__vite__mapDeps([107,2,3,1,4,5,6,12,108,8,9,10,11,24,31,86,49,30,27,13]))),mu=i.lazy(()=>as(()=>import("./ApplicationsTab-CiMUAZ1X.js"),__vite__mapDeps([109,2,3,1,4,5,6,8,24,9,10,11,82,30,31,40,72,35,18,17,19,20,21,22,23,12,25,26,27,28,14,29,32,33,34,15,36,37,38,39,41,13,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,73,74,75,76,77]))),uu=i.lazy(()=>as(()=>import("./EmailDashboardTab-aoU_mHCW.js"),__vite__mapDeps([110,2,3,1,4,5,6,24,9,10,11,42,43,27,73,37,16,17,19,20,21,22,23,8,12,25,26,28,14,29,30,31,32,33,34,15,35,36,38,39,40,41,13,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77]))),xu=i.lazy(()=>as(()=>import("./BadgesTab-7hFV3JvF.js"),__vite__mapDeps([111,2,3,1,4,5,6,8,9,10,11,12,50,49,31,52,24,25,39,112,18,17,113,30,53,34,114,13,98,37,19,20,21,22,23,26,27,28,14,29,32,33,15,35,36,38,40,41,42,43,44,45,46,47,48,51,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77]))),pu=i.lazy(()=>as(()=>import("./ActivityLogModule-_47Gboc_.js"),__vite__mapDeps([115,2,3,1,4,5,6,9,10,11,12,82,24,30,31,27,40,32,46,20,37,48,72,38,39,13,35,63,64,19,21,22,23,8,25,26,28,14,29,33,34,15,36,41,42,43,44,45,47,49,50,51,52,53,54,55,56,57,58,59,60,61,62,65,66,67,68,69,70,71,73,74,75,76,77]))),hu=i.lazy(()=>as(()=>import("./OrdersTab-CofC6Hhh.js"),__vite__mapDeps([116,2,3,1,4,5,6,42,43,9,10,11,12,82,83,38,39,29,30,31,24,65,96,117,46,47]))),gu=i.lazy(()=>as(()=>import("./ModerationTab-C9JR3rxJ.js"),__vite__mapDeps([118,2,3,1,4,5,6,19,20,21,42,43,9,10,11,24,8,12,30,31,64,37,72,41,65,63,47,33,13,74,38,39,35,22,23,25,26,27,28,14,29,32,34,15,36,40,44,45,46,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,66,67,68,69,70,71,73,75,76,77]))),fu=i.lazy(()=>as(()=>import("./DMCAClaimsTab-CxjFDaIx.js"),__vite__mapDeps([119,2,3,1,4,5,6,8,9,10,11,12,41,47,19,20,21,37,18,17]))),ju=i.lazy(()=>as(()=>import("./ContentTab-BeiqN0OM.js"),__vite__mapDeps([120,2,3,1,4,5,6,8,12,50,49,31,77,24,9,10,11,30,121,47,40,13,122,60,123,97,15,43,19,20,21,22,23,25,26,27,28,14,29,32,33,34,35,36,37,38,39,41,42,44,45,46,48,51,52,53,54,55,56,57,58,59,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76]))),vu=i.lazy(()=>as(()=>import("./PaymentsTab-CsjRBy94.js"),__vite__mapDeps([124,2,3,1,4,5,6,9,10,11,82,83,24,42,43,102,125,71,37,65,20,49,46,38,39,47,19,21,22,23,8,12,25,26,27,28,14,29,30,31,32,33,34,15,35,36,40,41,13,44,45,48,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,66,67,68,69,70,72,73,74,75,76,77]))),bu=i.lazy(()=>as(()=>import("./PaymentLogsTab-C4R6XawU.js"),__vite__mapDeps([126,2,3,1,4,5,6,24,9,10,11,82,83,12,42,43,72,35,33,127,41,37,18,17,19,20,21,22,23,8,25,26,27,28,14,29,30,31,32,34,15,36,38,39,40,13,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,73,74,75,76,77]))),yu=i.lazy(()=>as(()=>import("./SecurityTab-ClhCRgx6.js"),__vite__mapDeps([128,2,3,1,4,5,6,25,24,30,31,56,37,13,129,130,19,20,21,22,23,8,9,10,11,12,26,27,28,14,29,32,33,34,15,35,36,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77]))),Nu=i.lazy(()=>as(()=>import("./HelpTab-RW3d_nDI.js"),__vite__mapDeps([131,2,3,1,4,5,6,8,70,47,63,14,19,20,21,22,23,24,9,10,11,12,25,26,27,28,29,30,31,32,33,34,15,35,36,37,38,39,40,41,13,42,43,44,45,46,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,64,65,66,67,68,69,71,72,73,74,75,76,77]))),_u=i.lazy(()=>as(()=>import("./OverviewTab-CbfYl25o.js"),__vite__mapDeps([132,2,3,1,4,5,6,42,43,102,20,41,48,37,64,26,8,12,27,28,14,99,49,133,34,45,35,19,21,22,23,24,9,10,11,25,29,30,31,32,33,15,36,38,39,40,13,44,46,47,50,51,52,53,54,55,56,57,58,59,60,61,62,63,65,66,67,68,69,70,71,72,73,74,75,76,77]))),wu=i.lazy(()=>as(()=>import("./SellersTab-Dl3gwxoX.js"),__vite__mapDeps([134,2,3,1,4,5,6,8,24,9,10,11,135,12,29,82,83,25,71,38,39,30,31,136,72,41,47,35,63,137,13,19,20,21,22,23,26,27,28,14,32,33,34,15,36,37,40,42,43,44,45,46,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,64,65,66,67,68,69,70,73,74,75,76,77]))),Su=i.lazy(()=>as(()=>import("./VerificationsTab-Ct2jRRmv.js"),__vite__mapDeps([138,2,3,1,4,5,6,8,24,12,9,10,11,139,140,30,31,72,35,47,41,18,17]))),ku=i.lazy(()=>as(()=>import("./BansModule-BKcbga7U.js"),__vite__mapDeps([141,2,3,1,4,5,6,8,29,136,130,45,31,13]))),ls=({children:s})=>e.jsx(i.Suspense,{fallback:e.jsx(cs,{}),children:s});function Cu(){const{user:s,isAdmin:t,isOwner:r,hasPermission:n,loading:a}=vs(),[l,o]=i.useState("overview");return!a&&(!s||!t)?e.jsx(Ro,{to:"/"}):e.jsx(Yl,{children:e.jsxs("div",{className:"h-[calc(100vh-4rem)] flex w-full overflow-hidden",children:[e.jsx(Ao,{title:"Admin Panel",description:"Manage products, users, coupons, and analytics.",noindex:!0}),e.jsx(xm,{activeTab:l,onTabChange:o}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0 overflow-hidden",children:[e.jsxs("header",{className:"h-12 flex items-center border-b border-border/50 px-4 shrink-0 bg-background/80 backdrop-blur-sm z-10",children:[e.jsx(Xl,{className:"mr-3"}),e.jsx("h1",{className:"text-lg font-display font-bold truncate",children:"Admin Panel"})]}),e.jsxs("main",{className:"flex-1 p-4 md:p-6 overflow-y-auto custom-scrollbar",children:[l==="overview"&&e.jsx(ls,{children:e.jsx(_u,{onNavigate:o})}),l==="products"&&e.jsx(bm,{}),l==="users"&&e.jsx(Am,{}),l==="bans"&&e.jsx(ls,{children:e.jsx(ku,{})}),l==="coupons"&&e.jsx(Au,{}),l==="permissions"&&e.jsx(Ru,{}),l==="roles"&&e.jsx(Pu,{}),l==="analytics"&&e.jsx(Vm,{}),l==="tickets"&&e.jsx(Tu,{}),l==="settings"&&e.jsx(Hm,{}),l==="reviews"&&e.jsx(Wm,{}),l==="approvals"&&e.jsx(Bm,{}),l==="sellers"&&e.jsx(i.Suspense,{fallback:e.jsx(cs,{}),children:e.jsx(wu,{})}),l==="algorithm"&&e.jsx(Du,{}),l==="wishlists"&&e.jsx(Mu,{}),l==="site_stats"&&e.jsx(Eu,{}),l==="support_stats"&&e.jsx(Ou,{}),l==="activity_logs"&&e.jsx(ls,{children:e.jsx(pu,{})}),l==="storage"&&e.jsx(Lu,{}),l==="themes"&&e.jsx(Zm,{}),l==="creator_tickets"&&s&&e.jsx(Fu,{userId:s.id}),l==="user_messages"&&e.jsx($u,{}),l==="send_notification"&&e.jsx(Uu,{}),l==="trending_tags"&&e.jsx(Iu,{}),l==="pending_updates"&&e.jsx(zu,{}),l==="referrals"&&e.jsx(_c,{}),l==="recruiters"&&e.jsx(Tc,{}),l==="seo_tools"&&e.jsx(Pd,{}),l==="utm_builder"&&e.jsx(Od,{}),l==="utm_analytics"&&e.jsx(Ld,{}),l==="verifications"&&e.jsx(ls,{children:e.jsx(Su,{})}),l==="orders"&&e.jsx(ls,{children:e.jsx(hu,{})}),l==="moderation"&&e.jsx(ls,{children:e.jsx(gu,{})}),l==="dmca_claims"&&e.jsx(ls,{children:e.jsx(fu,{})}),l==="content_pages"&&e.jsx(ls,{children:e.jsx(ju,{})}),l==="payments"&&e.jsx(Kn,{permission:"view_revenue",showDenied:!0,children:e.jsx(ls,{children:e.jsx(vu,{})})}),l==="payment_logs"&&e.jsx(Kn,{permission:"view_revenue",showDenied:!0,children:e.jsx(ls,{children:e.jsx(bu,{})})}),l==="security"&&e.jsx(ls,{children:e.jsx(yu,{})}),l==="help"&&e.jsx(ls,{children:e.jsx(Nu,{})}),l==="status_page"&&e.jsx(ls,{children:e.jsx(eu,{})}),l==="errors"&&e.jsx(ls,{children:e.jsx(su,{})}),l==="ai_agent"&&e.jsx(ls,{children:e.jsx(tu,{})}),l==="advertising"&&e.jsx(ls,{children:e.jsx(au,{})}),l==="imports"&&e.jsx(ls,{children:e.jsx(ru,{})}),l==="stress_test"&&e.jsx(ls,{children:e.jsx(nu,{})}),l==="product_analytics"&&e.jsx(ls,{children:e.jsx(iu,{})}),l==="db_performance"&&e.jsx(ls,{children:e.jsx(lu,{})}),l==="landing_pages"&&e.jsx(ls,{children:e.jsx(ou,{})}),l==="beta_features"&&e.jsx(ls,{children:e.jsx(cu,{})}),l==="bundles"&&e.jsx(ls,{children:e.jsx(du,{})}),l==="applications"&&e.jsx(ls,{children:e.jsx(mu,{})}),l==="email_dashboard"&&e.jsx(ls,{children:e.jsx(uu,{})}),l==="badges"&&e.jsx(Kn,{permission:"manage_badges",showDenied:!0,children:e.jsx(ls,{children:e.jsx(xu,{})})})]})]})]})})}function Au(){const[s,t]=i.useState([]),[r,n]=i.useState(!1),[a,l]=i.useState({code:"",discount_type:"percentage",discount_value:"10",max_uses:"",expires_at:""}),[o,j]=i.useState(!1),b=async()=>{const{data:k}=await x.from("coupons").select("*").order("created_at",{ascending:!1});t(k??[])};i.useEffect(()=>{b()},[]);const c=async()=>
119{if(!a.code.trim()){O.error("Code is required");return}j(!0);const{data:{user:k}}=await x.auth.getUser(),p={code:a.code.toUpperCase(),discount_type:a.discount_type,discount_value:parseFloat(a.discount_value)||0,created_by:k==null?void 0:k.id};a.max_uses&&(p.max_uses=parseInt(a.max_uses)),a.expires_at&&(p.expires_at=new Date(a.expires_at).toISOString());const{data:h,error:f}=await x.from("coupons").insert(p).select("id").single();f?O.error(f.message):(O.success("Coupon created!"),ss("create_coupon","coupon",h==null?void 0:h.id,{code:p.code}),n(!1),l({code:"",discount_type:"percentage",discount_value:"10",max_uses:"",expires_at:""}),b()),j(!1)},d=async k=>{const{error:p}=await x.from("coupons").update({active:!k.active}).eq("id",k.id);p?O.error(p.message):(ss("toggle_coupon","coupon",k.id,{code:k.code,active:!k.active}),b())},P=async k=>{if(!confirm("Delete this coupon?"))return;const p=s.find(f=>f.id===k),{error:h}=await x.from("coupons").delete().eq("id",k);h?O.error(h.message):(O.success("Deleted"),ss("delete_coupon","coupon",k,{code:p==null?void 0:p.code}),b())};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex justify-end mb-4",children:e.jsxs(Ds,{open:r,onOpenChange:n,children:[e.jsx(an,{asChild:!0,children:e.jsxs($,{className:"glow-primary",children:[e.jsx(Fa,{className:"mr-1 h-4 w-4"})," Create Coupon"]})}),e.jsxs(Ms,{className:"glass sm:max-w-md",children:[e.jsx(Es,{children:e.jsx(Os,{className:"font-display",children:"New Coupon"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsx(ke,{placeholder:"Coupon code (e.g. SUMMER20)",value:a.code,onChange:k=>l({...a,code:k.target.value}),className:"bg-background/50 uppercase"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(Pe,{value:a.discount_type,onValueChange:k=>l({...a,discount_type:k}),children:[e.jsx(Te,{className:"bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"percentage",children:"Percentage (%)"}),e.jsx(L,{value:"fixed",children:"Fixed Amount ($)"})]})]}),e.jsx(ke,{type:"number",step:"0.01",placeholder:"Value",value:a.discount_value,onChange:k=>l({...a,discount_value:k.target.value}),className:"bg-background/50"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Max uses (empty = unlimited)"}),e.jsx(ke,{type:"number",value:a.max_uses,onChange:k=>l({...a,max_uses:k.target.value}),className:"bg-background/50"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm text-muted-foreground",children:"Expires at"}),e.jsx(ke,{type:"datetime-local",value:a.expires_at,onChange:k=>l({...a,expires_at:k.target.value}),className:"bg-background/50"})]})]}),e.jsx($,{className:"w-full",onClick:c,disabled:o,children:o?"Creating...":"Create Coupon"})]})]})]})}),e.jsxs("div",{className:"space-y-2",children:[s.map(k=>e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-display font-bold text-lg",children:k.code}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[k.discount_type==="percentage"?`${k.discount_value}% off`:`$${k.discount_value} off`,k.max_uses?` · ${k.current_uses}/${k.max_uses} used`:` · ${k.current_uses} used`,k.expires_at?` · Expires ${new Date(k.expires_at).toLocaleDateString()}`:""]})]})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:k.active?"Active":"Inactive"}),e.jsx(Ca,{checked:k.active,onCheckedChange:()=>d(k)})]}),e.jsx($,{size:"sm",variant:"destructive",onClick:()=>P(k.id),children:e.jsx(As,{className:"h-3 w-3"})})]})]})},k.id)),s.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No coupons yet"})]})]})}function Ru(){const{isOwner:s,hasPermission:t}=vs(),r=s||t("manage_permissions"),n=s||t("manage_roles"),[a,l]=i.useState([]),[o,j]=i.useState({}),[b,c]=i.useState({}),[d,P]=i.useState(""),[k,p]=i.useState(!1),[h,f]=i.useState([]),[_,m]=i.useState({}),[u,g]=i.useState({}),S=async()=>{const{data:E}=await x.from("user_roles").select("*").eq("role","admin");if(l(E??[]),E&&E.length>0){const N=E.map(je=>je.user_id),[{data:U},{data:R},{data:Z},{data:W},{data:D}]=await Promise.all([x.from("staff_permissions").select("*").in("user_id",N),x.from("profiles").select("user_id, display_name").in("user_id",N),x.from("custom_roles").select("*").order("name"),x.from("user_custom_roles").select("*").in("user_id",N),x.from("role_permissions").select("*")]),X={};
119U==null||U.forEach(je=>{X[je.user_id]||(X[je.user_id]=[]),X[je.user_id].push(je.permission)}),j(X);const oe={};R==null||R.forEach(je=>{oe[je.user_id]=je.display_name||"Unknown"}),c(oe),f(Z||[]);const ue={};W==null||W.forEach(je=>{ue[je.user_id]||(ue[je.user_id]=[]),ue[je.user_id].push(je.role_id)}),m(ue);const fe={};D==null||D.forEach(je=>{fe[je.role_id]||(fe[je.role_id]=[]),fe[je.role_id].push(je.permission)}),g(fe)}else{const{data:N}=await x.from("custom_roles").select("*").order("name");f(N||[])}};i.useEffect(()=>{S()},[]);const M=async()=>{var Z;if(!d.trim())return;p(!0);const{data:E,error:N}=await x.functions.invoke("admin-users",{body:{action:"search",query:d}});if(N||E!=null&&E.error){O.error("Search failed"),p(!1);return}const U=(Z=E.users)==null?void 0:Z.find(W=>{var D;return((D=W.email)==null?void 0:D.toLowerCase())===d.toLowerCase()});if(!U){O.error("User not found"),p(!1);return}const{error:R}=await x.from("user_roles").update({role:"admin"}).eq("user_id",U.id);R&&await x.from("user_roles").insert({user_id:U.id,role:"admin"}),O.success(`${d} added as staff!`),P(""),p(!1),S()},y=async(E,N)=>{if((_[E]||[]).includes(N))await x.from("user_custom_roles").delete().eq("user_id",E).eq("role_id",N);else{const{data:{user:R}}=await x.auth.getUser();await x.from("user_custom_roles").insert({user_id:E,role_id:N,assigned_by:R==null?void 0:R.id})}S()},w=async E=>{confirm("Remove this staff member? This will also remove all their roles and permissions.")&&(await x.from("user_roles").update({role:"user"}).eq("user_id",E),await x.from("staff_permissions").delete().eq("user_id",E),await x.from("user_custom_roles").delete().eq("user_id",E),O.success("Removed"),S())},F=E=>{const N=o[E]||[],U=[];return(_[E]||[]).forEach(R=>{(u[R]||[]).forEach(Z=>{U.includes(Z)||U.push(Z)})}),{direct:N,fromRoles:U,all:[...new Set([...N,...U])]}},J=async(E,N)=>{const U=Ir[N];if(!U)return;const R=Qr([...U.permissions]);await x.from("staff_permissions").delete().eq("user_id",E),R.length>0&&await x.from("staff_permissions").insert(R.map(Z=>({user_id:E,permission:Z}
119))),ss("apply_permission_preset","staff_permissions",E,{preset:N}),O.success(`Applied "${N}" preset`),S()};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(z,{className:"glass border-primary/10",children:e.jsxs(V,{className:"p-4",children:[e.jsx("h3",{className:"text-sm font-display font-semibold mb-3",children:"Quick-Apply Role Preset"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Apply a standard permission set to any staff member from their card below."}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3",children:Object.entries(Ir).map(([E,N])=>e.jsxs("div",{className:"rounded-lg border border-border/40 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:"w-2.5 h-2.5 rounded-full",style:{backgroundColor:N.color}}),e.jsx("span",{className:"text-sm font-semibold",children:N.label}),e.jsx(Y,{variant:"outline",className:"text-[9px] px-1.5 py-0",children:N.permissions.length})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground leading-relaxed",children:N.description})]},E))})]})}),r&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ke,{placeholder:"Add staff by email...",value:d,onChange:E=>P(E.target.value),className:"bg-background/50 max-w-sm"}),e.jsx($,{onClick:M,disabled:k,children:k?e.jsx(xs,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Fa,{className:"mr-1 h-4 w-4"})," Add Staff"]})})]}),e.jsxs("div",{className:"space-y-4",children:[a.map(E=>{const N=F(E.user_id);return e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-display font-semibold",children:b[E.user_id]||E.user_id}),e.jsx(Y,{variant:"secondary",children:"Admin"})]}),r&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Pe,{onValueChange:U=>J(E.user_id,U),children:[e.jsx(Te,{className:"w-[160px] h-8 text-xs",children:e.jsx(De,{placeholder:"Apply Preset"})}),e.jsx(Me,{children:Object.entries(Ir).map(([U,R])=>e.jsx(L,{value:U,className:"text-xs",children:R.label},U))})]}),e.jsx($,{size:"sm",variant:"destructive",onClick:()=>w(E.user_id),children:"Remove"})]})]}),h.length>0&&e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Assigned Roles"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:h.map(U=>{const R=(_[E.user_id]||[]).includes(U.id);return e.jsxs("button",{onClick:()=>n&&y(E.user_id,U.id),disabled:!n,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium border transition-all ${R?"border-transparent text-white":"border-border text-muted-foreground hover:border-primary/50"}`,style:R?{backgroundColor:U.color}:void 0,children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:U.color}}),U.name]},U.id)})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Permissions"}),e.jsx(no,{selected:o[E.user_id]||[],onChange:async U=>{r&&(await x.from("staff_permissions").delete().eq("user_id",E.user_id),U.length>0&&await x.from("staff_permissions").insert(U.map(R=>({user_id:E.user_id,permission:R}))),S())},disabled:!r,inheritedPerms:N.fromRoles})]})]})},E.id)}),a.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No staff members yet"})]})]})}function Pu(){const{isOwner:s,hasPermission:t}=vs(),r=s||t("manage_roles"),[n,a]=i.useState([]),[l,o]=i.useState(!0),[j,b]=i.useState(!1),[c,d]=i.useState(null),[P,k]=i.useState({name:"",color:"#6366f1",description:""}),[p,h]=i.useState([]),[f,_]=i.useState(!1),m=async()=>{o(!0);const{data:y}=await x.from("custom_roles").select("*").order("name"),{data:w}=await x.from("role_permissions").select("*"),F={};w==null||w.forEach(J=>{F[J.role_id]||(F[J.role_id]=[]),F[J.role_id].push(J.permission)}),a((y||[]).map(J=>({...J,permissions:F[J.id]||[]}))),o(!1)};i.useEffect(()=>{m()},[]);const u=()=>{k({name:"",color:"#6366f1",description:""}),h([]),d(null)},g=y=>{d(y),k({name:y.name,color:y.color,description:y.description||""}),h(y.permissions),b(!0)},S=async()=>
119{if(!P.name.trim()){O.error("Role name is required");return}if(_(!0),c)await x.from("custom_roles").update({name:P.name,color:P.color,description:P.description||null}).eq("id",c.id),await x.from("role_permissions").delete().eq("role_id",c.id),p.length>0&&await x.from("role_permissions").insert(p.map(y=>({role_id:c.id,permission:y}))),O.success("Role updated!"),ss("update_role","role",c.id,{name:P.name});else{const{data:y,error:w}=await x.from("custom_roles").insert({name:P.name,color:P.color,description:P.description||null}).select().single();if(w){O.error(w.message),_(!1);return}p.length>0&&y&&await x.from("role_permissions").insert(p.map(F=>({role_id:y.id,permission:F}))),O.success("Role created!"),ss("create_role","role",y==null?void 0:y.id,{name:P.name})}_(!1),b(!1),u(),m()},M=async y=>{if(!confirm("Delete this role? Users assigned to it will lose its permissions."))return;const w=n.find(F=>F.id===y);await x.from("custom_roles").delete().eq("id",y),O.success("Role deleted"),ss("delete_role","role",y,{name:w==null?void 0:w.name}),m()};return l?e.jsx(cs,{}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create custom roles with specific permissions, then assign them to users in the Staff tab."}),r&&e.jsxs(Ds,{open:j,onOpenChange:y=>{b(y),y||u()},children:[e.jsx(an,{asChild:!0,children:e.jsxs($,{children:[e.jsx(Fa,{className:"mr-1 h-4 w-4"})," Create Role"]})}),e.jsxs(Ms,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(Es,{children:e.jsx(Os,{children:c?"Edit Role":"Create Role"})}),e.jsxs("div",{className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("label",{className:"text-sm font-medium mb-1 block",children:"Name"}),e.jsx(ke,{value:P.name,onChange:y=>k({...P,name:y.target.value}),placeholder:"e.g. Support",className:"bg-background/50"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-1 block",children:"Color"}),e.jsx("input",{type:"color",value:P.color,onChange:y=>k({...P,color:y.target.value}),className:"w-10 h-10 rounded cursor-pointer border border-border"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-1 block",children:"Description"}),e.jsx(ke,{value:P.description,onChange:y=>k({...P,description:y.target.value}),placeholder:"What does this role do?",className:"bg-background/50"})]}),!c&&e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Start from a template"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(Ir).map(([y,w])=>e.jsxs("button",{onClick:()=>{k({name:P.name||w.label,color:w.color,description:w.description}),h(Qr([...w.permissions]))},className:"flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium border border-border/50 hover:border-primary/50 transition-colors",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:w.color}}),w.label]},y))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Permissions"}),e.jsx(no,{selected:p,onChange:h})]}),e.jsx($,{onClick:S,disabled:f,className:"w-full",children:f?e.jsx(xs,{className:"h-4 w-4 animate-spin"}):c?"Save Changes":"Create Role"})]})]})]})]}),e.jsxs("div",{className:"grid gap-4",children:[n.map(y=>e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:y.color}}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-display font-semibold",children:y.name}),y.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:y.description})]})]}),r&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",onClick:()=>g(y),children:e.jsx(ua,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",className:"text-destructive",onClick:()=>M(y.id),children:e.jsx(As,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[y.permissions.length===0&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"No permissions assigned"}),ar.map(w=>{const F=w.permissions.filter(N=>y.permissions.includes(N.key));if(F.length===0)return null;const J=w.icon,E=F.length===w.permissions.length;return e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(J,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5 shrink-0"}
119),e.jsx("div",{className:"flex flex-wrap gap-1",children:E?e.jsxs(Y,{variant:"default",className:"text-[10px]",children:["All ",w.label]}):F.map(N=>e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:N.label},N.key))})]},w.id)})]})]})},y.id)),n.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No custom roles yet. Create one to get started!"})]})]})}function Tu(){const{user:s,isOwner:t,hasPermission:r,role:n}=vs(),a=t||r("manage_tickets"),[l,o]=i.useState([]),[j,b]=i.useState(!0),[c,d]=i.useState(null),[P,k]=i.useState([]),[p,h]=i.useState(""),[f,_]=i.useState(!1),[m,u]=i.useState("open"),[g,S]=i.useState("all"),[M,y]=i.useState("all"),[w,F]=i.useState("all"),[J,E]=i.useState("newest"),[N,U]=i.useState({}),{claim:R,unclaim:Z,overrideClaim:W,isClaimedByMe:D,canActOn:X,claiming:oe}=hi("support_tickets"),{escalate:ue}=Id(),{notes:fe,loading:je,addNote:Fe}=gi("support_ticket",(c==null?void 0:c.id)||null),{track:Ie}=fi(),{getViewersFor:G}=ji();ir("support_tickets",()=>{xe()}),ir("ticket_replies",()=>{c&&ve(c.id)});const Q=[{value:"general",label:"General"},{value:"product_support",label:"Product Support"},{value:"account",label:"Account Issue"},{value:"billing",label:"Billing & Payments"},{value:"creators",label:"Creator Issue"},{value:"bug_report",label:"Bug Report"},{value:"feature_request",label:"Feature Request"},{value:"other",label:"Other"}],xe=async()=>{b(!0);let ae=x.from("support_tickets").select("*").order("updated_at",{ascending:!1});m!=="all"&&(ae=ae.eq("status",m));const{data:de}=await ae;if(de){const Re=[...new Set(de.map(We=>We.user_id))],pe=[...new Set(de.map(We=>We.claimed_by).filter(Boolean))],Ce=[...new Set([...Re,...pe])],{data:qe}=await x.from("profiles").select("user_id, display_name").in("user_id",Ce),Ze={};qe==null||qe.forEach(We=>{Ze[We.user_id]=We.display_name||"Unknown"});const ts={};pe.forEach(We=>{ts[We]=Ze[We]||"Staff"}),U(ts),o(de.map(We=>({...We,user_name:Ze[We.user_id]||"Unknown"})))}b(!1)},ve=async ae=>{const{data:de}=await x.from("ticket_replies").select("*").eq("ticket_id",ae).order("created_at",{ascending:!0});if(de){const Re=[...new Set(de.map(qe=>qe.user_id))],{data:pe}=await x.from("profiles").select("user_id, display_name").in("user_id",Re),Ce={};pe==null||pe.forEach(qe=>{Ce[qe.user_id]=qe.display_name||"Unknown"}),k(de.map(qe=>({...qe,user_name:Ce[qe.user_id]||"Unknown"})))}};i.useEffect(()=>{xe()},[m]);const T=ae=>{d(ae),ve(ae.id),h(""),Ie(`ticket:${ae.id}`,"viewing")},ne=async()=>{if(!p.trim()||!c||!s)return;if(!X(c.claimed_by)){O.error("This ticket is claimed by another moderator");return}_(!0);const{data:ae,error:de}=await x.from("ticket_replies").insert({ticket_id:c.id,user_id:s.id,message:p.trim(),is_staff_reply:!0}).select("id").single();if(de)O.error(de.message);else{ss("reply_ticket","support_ticket",c.id);const Re=c.user_id,{data:pe}=await x.rpc("get_user_email",{target_user_id:Re});if(pe){const{data:Ce}=await x.from("profiles").select("display_name").eq("user_id",s.id).maybeSingle();x.functions.invoke("send-transactional-email",{body:{templateName:"ticket-reply",recipientEmail:pe,idempotencyKey:`ticket-reply-${ae==null?void 0:ae.id}`,templateData:{ticketSubject:c.subject,replierName:(Ce==null?void 0:Ce.display_name)||"Ro Market Support",replyPreview:p.trim().slice(0,200),ticketUrl:"https://romarkets.shop/dashboard?tab=support"}}}).catch(()=>{})}h(""),ve(c.id)}_(!1)},he=async(ae,de)=>{if(!X(c==null?void 0:c.claimed_by)){O.error("This ticket is claimed by another moderator");return}const{error:Re}=await x.from("support_tickets").update({status:de}).eq("id",ae);Re?O.error(Re.message):(O.success(`Ticket ${de}`),ss("update_ticket_status","support_ticket",ae,{status:de}),xe(),(c==null?void 0:c.id)===ae&&d({...c,status:de}))},Oe=async ae=>{if(!c)return;await ue(c.id,"support_tickets",ae)&&(d({...c,status:"escalated",escalated_to:ae}),xe())},Ue=ae=>ae==="open"?"bg-primary/20 text-primary border-primary/30":ae==="in_progress"?"bg-accent/20 text-accent border-accent/30":ae==="escalated"?"bg-red-500/20 text-red-400 border-red-500/30":ae==="waiting_on_user"?"bg-amber-500/20 text-amber-400 border-amber-500/30":ae==="claimed"?"bg-blue-500/20 text-blue-400 border-blue-500/30":"bg-muted text-muted-foreground";if(c){const ae=G(`ticket:${c.id}`);return e.jsxs("div",{className:"space-y-4",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>d(null),children:"â Back to tickets"}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-display font-semibold text-lg",children:c.subject}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From ",c.user_name," · ",new Date(c.created_at).toLocaleStr
119ing()]}),e.jsxs("div",{className:"flex items-center gap-2 mt-2 flex-wrap",children:[e.jsx(xa,{claimedBy:c.claimed_by,claimerName:N[c.claimed_by],claimedAt:c.claimed_at,isMe:D(c.claimed_by)}),e.jsx(il,{escalatedTo:c.escalated_to}),e.jsx(Kr,{viewers:ae})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Y,{className:Ue(c.status),children:c.status.replace("_"," ")}),e.jsx(lr,{claimedBy:c.claimed_by,onClaim:()=>R(c.id).then(de=>{de&&d({...c,claimed_by:s.id})}),onUnclaim:()=>Z(c.id,c.claimed_by).then(de=>{de&&d({...c,claimed_by:null})}),onOverride:()=>W(c.id).then(de=>{de&&d({...c,claimed_by:s.id})}),canOverride:t,isMe:D(c.claimed_by),claiming:oe===c.id}),a&&X(c.claimed_by)&&e.jsxs(Pe,{value:c.status,onValueChange:de=>he(c.id,de),children:[e.jsx(Te,{className:"w-40 bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"open",children:"Open"}),e.jsx(L,{value:"in_progress",children:"In Progress"}),e.jsx(L,{value:"waiting_on_user",children:"Waiting on User"}),e.jsx(L,{value:"escalated",children:"Escalated"}),e.jsx(L,{value:"resolved",children:"Resolved"}),e.jsx(L,{value:"closed",children:"Closed"})]})]})]})]}),a&&X(c.claimed_by)&&c.status!=="closed"&&(()=>{const de=[{key:"support",label:"Support"},{key:"manager",label:"Manager"},{key:"owner",label:"Owner"}],Re=de.findIndex(Ce=>Ce.key===(n==="admin"?"manager":n??"support")),pe=de.filter((Ce,qe)=>qe>Re);return pe.length===0?null:e.jsxs("div",{className:"flex gap-2 mt-3 border-t border-border/50 pt-3",children:[e.jsx("span",{className:"text-xs text-muted-foreground self-center mr-1",children:"Escalate to:"}),pe.map(Ce=>e.jsx($,{size:"sm",variant:"outline",onClick:()=>Oe(Ce.label),className:"text-xs",children:Ce.label},Ce.key))]})})()]})}),e.jsxs("div",{className:"space-y-3 max-h-[400px] overflow-y-auto",children:[P.map(de=>e.jsx(z,{className:`glass ${de.is_staff_reply?"border-primary/30 ml-8":"mr-8"}`,children:e.jsxs(V,{className:"p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-sm font-semibold",children:de.user_name}),de.is_staff_reply&&de.user_id&&e.jsx(Po,{userId:de.user_id}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:new Date(de.created_at).toLocaleString()})]}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:de.message})]})},de.id)),P.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No replies yet"})]}),e.jsx(z,{className:"glass border-dashed",children:e.jsx(V,{className:"p-4",children:e.jsx(vi,{notes:fe,loading:je,onAdd:Fe})})}),a&&X(c.claimed_by)&&c.status!=="closed"&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx($s,{value:p,onChange:de=>{h(de.target.value),Ie(`ticket:${c.id}`,"typing")},placeholder:"Type a reply...",className:"bg-background/50",rows:2}),e.jsx($,{onClick:ne,disabled:f||!p.trim(),className:"shrink-0",children:e.jsx(qt,{className:"h-4 w-4"})})]}),!X(c.claimed_by)&&c.status!=="closed"&&e.jsx("p",{className:"text-sm text-muted-foreground italic text-center",children:"This ticket is claimed by another moderator. You can add internal notes but cannot reply."})]})}const Xe=ae=>{var de;return((de=Q.find(Re=>Re.value===ae))==null?void 0:de.label)||ae},Be=l.filter(ae=>g==="all"||(ae.category||"general")===g).filter(ae=>M==="all"||ae.priority===M).filter(ae=>w==="unclaimed"?!ae.claimed_by:w==="mine"?ae.claimed_by===(s==null?void 0:s.id):w==="escalated"?ae.status==="escalated":w==="high_priority"?ae.priority==="urgent"||ae.priority==="high":!0).sort((ae,de)=>{if(J==="oldest")return new Date(ae.created_at).getTime()-new Date(de.created_at).getTime();if(J==="priority"){const Re={urgent:0,high:1,normal:2,low:3};return(Re[ae.priority]??2)-(Re[de.priority]??2)}return new Date(de.updated_at).getTime()-new Date(ae.updated_at).getTime()});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Pe,{value:m,onValueChange:u,children:[e.jsx(Te,{className:"w-36 bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Status"}),e.jsx(L,{value:"open",children:"Open"}),e.jsx(L,{value:"in_progress",children:"In Progress"}),e.jsx(L,{value:"waiting_on_user",children:"Waiting on User"}),e.jsx(L,{value:"escalated",children:"Escalated"}),e.jsx(L,{value:"resolved",children:"Resolved"}),e.jsx(L,{value:"closed",children:"Closed"})]})]}),e.jsxs(Pe,{value:w,onValueChange:F,children:[e.jsx(Te,{className:"w-44 bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Claims"}),e.jsx(L,{value:"unclaimed",children:"Unclaimed"}),e.jsx(L,{value:"mine",children:"Assigned to Me"}),e.jsx(L,{value:"escalated",children:"Escalated"}),e.jsx(L,{value:"high_priority",children:"High Priority"})]})]}),e.jsxs(Pe,{value:g,onValueChange:S,children:[e.jsx(Te,{className:"w-44 bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Categories"}),Q.map(ae=>e.jsx(L,{value:ae.value,children:ae.label},ae.value))]})]}),e.jsxs(Pe,{value:M,onValueChange:y,children:[e.jsx(Te,{className:"w-36 bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Priority"}),e.jsx(L,{value:"urgent",children:"Urgent"}),e.jsx(L,{value:"high",children:"High"}),e.jsx(L,{value:"normal",children:"Normal"}),e.jsx(L,{value:"low",children:"Low"})]})]}),e.jsxs(Pe,{value:J,onValueChange:E,children:[e.jsx(Te,{className:"w-40 bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"newest",children:"Newest First"}),e.jsx(L,{value:"oldest",children:"Oldest First"}),e.jsx(L,{value:"priority",children:"Priority"})]})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Be.length," ticket",Be.length!==1?"s":""]}),j?e.jsx("div",{className:"text-center py-8",children:e.jsx(xs,{className:"h-6 w-6 animate-spin mx-auto"})}):Be.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No tickets found"}):e.jsx("div",{className:"space-y-2",children:Be.map(ae=>e.jsx(z,{className:`glass hover:border-primary/30 transition-colors cursor-pointer ${ae.claimed_by&&ae.claimed_by!==(s==null?void 0:s.id)?"opacity-60":""}`,onClick:()=>T(ae),children:e.jsxs(V,{className:"p-4 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"font-display font-semibold",children:ae.subject}),e.jsx(Y,{className:Ue(ae.status),children:ae.status.replace("_"," ")}),e.jsx(Y,{variant:"outline",className:"text-xs",children:ae.priority}),e.jsx(Y,{variant:"secondary",className:"text-xs",children:Xe(ae.category||"general")}
119),e.jsx(xa,{claimedBy:ae.claimed_by,claimerName:N[ae.claimed_by],isMe:D(ae.claimed_by)}),ae.escalated_to&&e.jsx(il,{escalatedTo:ae.escalated_to})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["From ",ae.user_name," · ",new Date(ae.created_at).toLocaleString()]})]}),e.jsx(js,{className:"h-4 w-4 text-muted-foreground"})]})},ae.id))})]})}function Du(){const[s,t]=i.useState([]),[r,n]=i.useState(!0),[a,l]=i.useState(null),[o,j]=i.useState(!1),[b,c]=i.useState(Wn),[d,P]=i.useState(null),[k,p]=i.useState(null),[h,f]=i.useState([]),[_,m]=i.useState(""),[u,g]=i.useState("score_desc"),[S,M]=i.useState("all"),[y,w]=i.useState(1),[F,J]=i.useState(null),[E,N]=i.useState({}),[U,R]=i.useState({}),[Z,W]=i.useState(null),D=10;i.useEffect(()=>{(async()=>{n(!0);const{data:ne}=await x.from("site_settings").select("value").eq("key","algorithm_weights").maybeSingle();let he=Wn;if(ne!=null&&ne.value)try{he={...Wn,...JSON.parse(ne.value)}}catch{}l(he),c(he);const[{data:Oe},{data:Ue},{data:Xe},{data:Be},{data:ae},{data:de},{data:Re},{data:pe},{data:Ce},{data:qe}]=await Promise.all([x.from("products").select("id, name, price, category, image_url, boost_score, seller_id, status, created_at, updated_at, tags, description").eq("status","approved"),x.from("reviews").select("product_id, rating"),x.from("purchases").select("product_id, purchased_at"),x.from("product_views").select("product_id"),x.from("cart_events").select("product_id, event_type").in("event_type",["add_to_cart","click_product"]),x.from("wishlists").select("product_id"),x.from("product_impressions").select("product_id"),x.from("product_images").select("id, product_id, image_url, is_thumbnail, sort_order"),x.from("image_ab_stats").select("image_id, product_id, impressions, clicks, conversions"),x.from("analytics_ranking_variant_daily").select("variant, total_sessions, impressions, clicks, purchases, revenue, ctr, conversion_rate, revenue_per_session, funnel_completion_rate").gte("date",new Date(Date.now()-14*864e5).toISOString().slice(0,10))]),Ze={};(pe||[]).forEach(q=>{Ze[q.product_id]||(Ze[q.product_id]=[]),Ze[q.product_id].push(q)}),N(Ze);const ts={};(Ce||[]).forEach(q=>{ts[q.product_id]||(ts[q.product_id]=[]);for(let K=0;K<(Number(q.impressions)||0);K++)ts[q.product_id].push({image_id:q.image_id,event_type:"impression"});for(let K=0;K<(Number(q.clicks)||0);K++)ts[q.product_id].push({image_id:q.image_id,event_type:"click"})}),R(ts);const We={};if(Ue){const q={};Ue.forEach(K=>{q[K.product_id]||(q[K.product_id]=[]),q[K.product_id].push(K.rating)}),Object.entries(q).forEach(([K,re])=>{We[K]={avg:re.reduce((ge,ye)=>ge+ye,0)/re.length,count:re.length}})}const ns=(q,K)=>(q==null?void 0:q.filter(re=>re.product_id===K).length)||0,us=(q,K)=>{var ge;const re=(q==null?void 0:q.filter(ye=>ye.product_id===K))||[];return re.length===0?null:((ge=re.sort((ye,Ae)=>new Date(Ae.purchased_at).getTime()-new Date(ye.purchased_at).getTime())[0])==null?void 0:ge.purchased_at)||null},Ge=(Oe||[]).map(q=>{var K,re;return{id:q.id,name:q.name,category:q.category,price:q.price,boost_score:q.boost_score||0,seller_id:q.seller_id,created_at:q.created_at,updated_at:q.updated_at,tags:q.tags,description:q.description,sales:ns(Xe,q.id),rating:((K=We[q.id])==null?void 0:K.avg)||0,reviews:((re=We[q.id])==null?void 0:re.count)||0,views:ns(Be,q.id),checkouts:ns(ae,q.id),wishlists:ns(de,q.id),impressions:ns(Re,q.id),revenue:ns(Xe,q.id)*(q.price||0),last_sale_at:us(Xe,q.id),image_url:q.image_url}}),He=Math.max(...Ge.map(q=>q.sales),1),A=Math.max(...Ge.map(q=>q.views),1),me=Math.max(...Ge.map(q=>q.impressions),1),ze=Math.max(...Ge.map(q=>q.views>0?(q.revenue||0)/q.views:0),1),Le=Ge.map(q=>{const K=om(q,he,{maxSales:He,maxViews:A,maxImpressions:me,maxRevenuePerView:ze}),re=q.impressions>0?q.views/q.impressions:0,ge=q.views>0?q.sales/q.views:0,ye=q.views>0?q.checkouts/q.views:0,Ae=q.checkouts>0?q.sales/q.checkouts:0,Ee=q.views>0?(q.revenue||0)/q.views:0,Je=ge>.03,Ve=q.views>
119200&&ge<.01,es=q.views<50,ds=[];return q.views>100&&ye<.08&&ds.push("High views, low checkout: product page friction"),q.checkouts>50&&Ae<.2&&ds.push("High checkout, low purchase: pricing/trust friction"),Ve&&ds.push("Underperforming at scale"),{...K,ctr:re,conv_rate:ge,checkout_rate:ye,purchase_from_checkout_rate:Ae,revenue_per_view:Ee,high_performer:Je,underperforming:Ve,low_data:es,funnel_insights:ds,final_score:K.global_score,image_url:q.image_url,last_sale_at:q.last_sale_at,description:q.description}}).sort((q,K)=>K.global_score-q.global_score);Le.forEach((q,K)=>{q.rank=K+1}),t(Le);const B=Le.map(q=>q.global_score),ee=Ge.map(q=>q.views);P({gini:cm(ee),coldStart:dm(Ge),scoreDist:mm(B)});const te=Ge.reduce((q,K)=>q+K.views,0),se=Ge.reduce((q,K)=>q+K.sales,0),be=Ge.length>0?Le.reduce((q,K)=>q+K.conv_rate,0)/Ge.length:0,Se=Ge.length>0?Le.filter(q=>q.underperforming).length/Ge.length:0,_e=te>0?se/te:0,Ke=Math.min(be/.03,1)*40,rs=Math.max(0,1-Se)*30,H=Math.min(_e/.02,1)*30;p({score:Math.round(Ke+rs+H),avgConversionRate:be,underperformingRatio:Se,funnelCompletionRate:_e});const ce={};(qe||[]).forEach(q=>{const K=q.variant||"unassigned";ce[K]||(ce[K]={sessions:0,impressions:0,clicks:0,purchases:0,revenue:0}),ce[K].sessions+=Number(q.total_sessions||0),ce[K].impressions+=Number(q.impressions||0),ce[K].clicks+=Number(q.clicks||0),ce[K].purchases+=Number(q.purchases||0),ce[K].revenue+=Number(q.revenue||0)});const le=Object.entries(ce).map(([q,K])=>{const re=K.impressions>0?K.clicks/K.impressions*100:0,ge=K.sessions>0?K.purchases/K.sessions*100:0,ye=K.sessions>0?K.revenue/K.sessions:0,Ae=K.clicks>0?K.purchases/K.clicks*100:0;return{variant:q,sessions:K.sessions,impressions:K.impressions,clicks:K.clicks,purchases:K.purchases,revenue:K.revenue,ctr:re,conversionRate:ge,revenuePerSession:ye,funnelCompletionRate:Ae}}).sort((q,K)=>K.revenuePerSession-q.revenuePerSession);f(le),n(!1)})()},[]),i.useEffect(()=>{w(1)},[_,u,S]);const X=async()=>{await x.from("site_settings").upsert({key:"algorithm_weights",value:JSON.stringify(b)},{onConflict:"key"}),l(b),j(!1),O.success("Algorithm weights saved"),await ss("update_settings","algorithm_weights",void 0,b)},oe=()=>{const T=h.find(Xe=>Xe.variant==="control"),ne=h[0];if(!a||!T||!ne){O.error("Not enough variant data for auto-tuning");return}const he=ne.conversionRate-T.conversionRate,Oe=ne.funnelCompletionRate-T.funnelCompletionRate,Ue=nc(a,{conversionDelta:he,diversityDelta:Oe});c(Ue),j(!0),O.success("Auto-tune applied to local weights. Review and save when ready.")},ue=i.useMemo(()=>{const T=new Set(s.map(ne=>ne.category));return Array.from(T).sort()},[s]),fe=i.useMemo(()=>s.filter(T=>{const ne=!_||T.name.toLowerCase().includes(_.toLowerCase())||(T.tags||[]).some(Oe=>Oe.toLowerCase().includes(_.toLowerCase())),he=S==="all"||T.category===S;return ne&&he}).sort((T,ne)=>{switch(u){case"score_asc":return T.global_score-ne.global_score;case"name_asc":return T.name.localeCompare(ne.name);case"name_desc":return ne.name.localeCompare(T.name);case"sales_desc":return ne.sales-T.sales;case"freshness_desc":return ne.freshness_component-T.freshness_component;case"quality_desc":return ne.quality_component-T.quality_component;case"engagement_desc":return ne.engagement_component-T.engagement_component;case"performance_desc":return ne.performance_component-T.performance_component;case"conversion_desc":return ne.conv_rate-T.conv_rate;case"revenue_per_view_desc":return ne.revenue_per_view-T.revenue_per_view;case"category_asc":return T.category.localeCompare(ne.category);case"score_desc":default:return ne.global_score-T.global_score}}),[s,_,u,S]),je=u==="score_desc"&&S==="all"&&!_,Fe=je?fe.slice(0,10):[],Ie=je?fe.slice(10):fe,G=Math.max(1,Math.ceil(Ie.length/D)),Q=Ie.slice((y-1)*D,y*D),xe=T=>{const ne=E[T]||[],he=U[T]||[];return ne.length<=1?null:ne.map(Oe=>{const Ue=he.filter(de=>de.image_id===Oe.id),Xe=Ue.filter(de=>de.event_type==="impression").length,Be=Ue.filter(de=>de.event_type==="click").length,ae=Xe>0?Be/Xe*100:0;return{...Oe,impressions:Xe,clicks:Be,ctr:ae}}).sort((Oe,Ue)=>Ue.ctr-Oe.ctr)};if(r)return e.jsx(cs,{});const ve=(T,ne,he,Oe)=>{var Re;const Ue=((Re=s[0])==null?void 0:Re.global_score)||1,Xe=Ue>0?T.global_score/Ue*100:0,Be=F===T.id,ae=xe(T.id),de=E[T.id]||[];return e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-3 px-3 py-3 cursor-pointer transition-colors hover:bg-secondary/20 rounded-lg ${Oe?"bg-primary/5":""} ${Be?"bg-secondary/30":""}`,onClick:()=>J(Be?null:T.id),children:[e.jsx("div",{className:"w-8 text-center shrink-0",children:e.jsxs("span",{className:`font-display font-bold ${T.rank<=3?"text-primary text-lg":"text-muted-foreground text-sm"}`,children:["#",T.rank]})}),e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-secondary/50 flex items-center justify-center overflow-hidden shrink-0",children:T.image_url?e.jsx("img",{src:T.image_url,alt:"",className:"w-full h-full object-cover"}
119):e.jsx(vt,{className:"h-4 w-4 text-muted-foreground/30"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate text-sm",children:T.name}),e.jsxs("div",{className:"flex items-center gap-1 mt-0.5",children:[e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:T.category.replace(/_/g," ")}),T.seller_id&&e.jsx(Y,{variant:"outline",className:"text-[10px]",children:"Community"}),de.length>1&&e.jsxs(Y,{variant:"outline",className:"text-[10px] border-primary/30 text-primary",children:["A/B ",de.length," imgs"]}),T.high_performer&&e.jsx(Y,{className:"text-[9px] bg-emerald-500/20 text-emerald-400 border-emerald-500/30",children:"High Performer"}),T.underperforming&&e.jsx(Y,{className:"text-[9px] bg-destructive/20 text-destructive border-destructive/30",children:"Underperforming"}),T.low_data&&e.jsx(Y,{variant:"outline",className:"text-[9px] border-amber-500/30 text-amber-400",children:"Low Data"}),T.hidden_from_discovery_candidate&&e.jsx(Y,{className:"text-[9px] bg-destructive/30 text-destructive border-destructive/40",children:"Hidden Candidate"})]})]})]}),e.jsxs("div",{className:"hidden md:flex items-center gap-4 text-xs shrink-0",children:[e.jsxs("div",{className:"text-center w-12",children:[e.jsx("p",{className:"text-muted-foreground text-[10px]",children:"Sales"}),e.jsx("p",{className:"font-mono font-medium",children:T.sales})]}),e.jsxs("div",{className:"text-center w-12",children:[e.jsx("p",{className:"text-muted-foreground text-[10px]",children:"Views"}),e.jsx("p",{className:"font-mono font-medium",children:T.views})]}),e.jsxs("div",{className:"text-center w-12",children:[e.jsx("p",{className:"text-muted-foreground text-[10px]",children:"CTR"}),e.jsxs("p",{className:"font-mono font-medium",children:[(T.ctr*100).toFixed(1),"%"]})]}),e.jsxs("div",{className:"text-center w-14",children:[e.jsx("p",{className:"text-muted-foreground text-[10px]",children:"Fresh"}),e.jsx("p",{className:"font-mono font-medium text-primary",children:T.freshness_component.toFixed(2)})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("div",{className:"w-20 h-2 rounded-full bg-secondary/50 overflow-hidden hidden sm:block",children:e.jsx("div",{className:"h-full rounded-full bg-primary transition-all",style:{width:`${Xe}%`}})}),e.jsx("span",{className:"text-sm font-display font-bold text-primary w-12 text-right",children:T.global_score.toFixed(0)})]}),e.jsx("div",{className:"shrink-0",children:Be?e.jsx(ma,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(js,{className:"h-4 w-4 text-muted-foreground"})})]}),Be&&e.jsxs("div",{className:"ml-11 mr-3 mb-4 mt-1 space-y-4 animate-in slide-in-from-top-2 duration-200",children:[e.jsx(z,{className:"glass border-primary/20",children:e.jsxs(V,{className:"p-4",children:[e.jsxs("h4",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Dt,{className:"h-4 w-4 text-primary"}),"Ranking Debug Panel"]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-xs",children:[e.jsxs("div",{className:"bg-secondary/20 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Final Score"}),e.jsx("p",{className:"font-mono font-semibold",children:T.final_score.toFixed(2)})]}),e.jsxs("div",{className:"bg-secondary/20 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Boost Component"}),e.jsx("p",{className:"font-mono",children:T.boost_component.toFixed(3)})]}),e.jsxs("div",{className:"bg-secondary/20 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Sales Component"}),e.jsx("p",{className:"font-mono",children:T.sales_component.toFixed(3)})]}),e.jsxs("div",{className:"bg-secondary/20 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Quality Component"}),e.jsx("p",{className:"font-mono",children:T.quality_component.toFixed(3)})]}),e.jsxs("div",{className:"bg-secondary/20 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Engagement Component"}
119),e.jsx("p",{className:"font-mono",children:T.engagement_component.toFixed(3)})]}),e.jsxs("div",{className:"bg-secondary/20 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Performance Component"}),e.jsx("p",{className:"font-mono",children:T.performance_component.toFixed(3)})]}),e.jsxs("div",{className:"bg-secondary/20 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Freshness Component"}),e.jsx("p",{className:"font-mono",children:T.freshness_component.toFixed(3)})]}),e.jsxs("div",{className:"bg-secondary/20 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Seller Component"}),e.jsx("p",{className:"font-mono",children:T.seller_component.toFixed(3)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-xs mt-3",children:[e.jsxs("div",{className:"bg-secondary/10 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Confidence Multiplier"}),e.jsx("p",{className:"font-mono",children:(T.confidence_multiplier??0).toFixed(3)})]}),e.jsxs("div",{className:"bg-secondary/10 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Low Data Penalty"}),e.jsxs("p",{className:"font-mono",children:["x",(T.low_data_penalty??1).toFixed(3)]})]}),e.jsxs("div",{className:"bg-secondary/10 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Underperform Penalty"}),e.jsxs("p",{className:"font-mono",children:["x",(T.underperforming_penalty??1).toFixed(3)]})]}),e.jsxs("div",{className:"bg-secondary/10 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Auto-Boost"}),e.jsxs("p",{className:"font-mono",children:["x",(T.auto_boost_multiplier??1).toFixed(3)]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-xs mt-3",children:[e.jsxs("div",{className:"bg-secondary/10 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Boost Decay"}),e.jsxs("p",{className:"font-mono",children:["x",(T.boost_decay_multiplier??1).toFixed(3)]})]}),e.jsxs("div",{className:"bg-secondary/10 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Second Chance"}),e.jsx("p",{className:"font-mono",children:T.second_chance_active?"active":"inactive"})]}),e.jsxs("div",{className:"bg-secondary/10 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Second Chance Boost"}),e.jsxs("p",{className:"font-mono",children:["x",(T.second_chance_boost??1).toFixed(3)]})]}),e.jsxs("div",{className:"bg-secondary/10 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Exploration"}),e.jsx("p",{className:"font-mono",children:T.exploration_applied?`${((T.exploration_component||0)*100).toFixed(1)}%`:"off"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 text-xs mt-3",children:[e.jsxs("div",{className:"bg-secondary/10 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Views"}),e.jsx("p",{className:"font-mono",children:T.views})]}),e.jsxs("div",{className:"bg-secondary/10 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Conversion Rate"}),e.jsxs("p",{className:"font-mono",children:[(T.conv_rate*100).toFixed(2),"%"]})]}),e.jsxs("div",{className:"bg-secondary/10 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Revenue/View"}),e.jsxs("p",{className:"font-mono",children:["$",(T.revenue_per_view||0).toFixed(4)]})]}),e.jsxs("div",{className:"bg-secondary/10 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"CTR"}),e.jsxs("p",{className:"font-mono",children:[(T.ctr*100).toFixed(2),"%"]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 text-xs mt-3",children:[e.jsxs("div",{className:"bg-secondary/10 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Status"}),e.jsx("p",{className:"font-mono",children:T.hidden_from_discovery_candidate?"hidden_candidate":T.underperforming?"underperforming":T.low_data?"low_data":"normal"})]}),e.jsxs("div",{className:"bg-secondary/10 rounded p-2",children:[e.jsx("p",{className:"text-muted-foreground",children:"Funnel Insights"}),Array.isArray(T.funnel_insights)&&T.funnel_insights.length>0?e.jsx("ul",{className:"space-y-0.5 mt-1",children:T.funnel_insights.map((pe,Ce)=>e.jsx("li",{className:"font-mono text-[11px]",children:pe},Ce))}):e.jsx("p",{className:"font-mono",children:"none"})]})]})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4",children:[e.jsxs("h4",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[e.jsx(zt,{className:"h-4 w-4 text-primary"}),"Algorithm Score Breakdown"]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3",children:[{label:"Boost",raw:T.boost_score,norm:T.boost_component,weight:(a==null?void 0:a.W_boost)||0,weighted:((a==null?void 0:a.W_boost)||0)*T.boost_component},{label:"Sales",raw:T.sales,norm:T.sales_component,weight:(a==null?void 0:a.W_sales)||0,weighted:((a==null?void 0:a.W_sales)||0)*T.sales_component},{label:"Quality",raw:`${T.rating.toFixed(1)}â
(${T.reviews}
119)`,norm:T.quality_component,weight:(a==null?void 0:a.W_quality)||0,weighted:((a==null?void 0:a.W_quality)||0)*T.quality_component},{label:"Engagement",raw:`CTR ${(T.ctr*100).toFixed(1)}%`,norm:T.engagement_component,weight:(a==null?void 0:a.W_engagement)||0,weighted:((a==null?void 0:a.W_engagement)||0)*T.engagement_component},{label:"Performance",raw:`Conv ${(T.conv_rate*100).toFixed(2)}% ⢠RPV $${(T.revenue_per_view||0).toFixed(2)}`,norm:T.performance_component,weight:(a==null?void 0:a.W_performance)||0,weighted:((a==null?void 0:a.W_performance)||0)*T.performance_component},{label:"Freshness",raw:`${Math.floor((Date.now()-new Date(T.created_at).getTime())/864e5)}d old`,norm:T.freshness_component,weight:(a==null?void 0:a.W_freshness)||0,weighted:((a==null?void 0:a.W_freshness)||0)*T.freshness_component},{label:"Seller",raw:T.seller_id?"Community":"Official",norm:T.seller_component,weight:(a==null?void 0:a.W_seller)||0,weighted:((a==null?void 0:a.W_seller)||0)*T.seller_component}].map(pe=>e.jsxs("div",{className:"bg-secondary/20 rounded-lg p-2.5",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground font-medium",children:pe.label}),e.jsx("p",{className:"text-xs font-mono mt-1",children:(typeof pe.raw=="number",pe.raw)}),e.jsx("div",{className:"w-full h-1.5 rounded-full bg-secondary/50 mt-1.5 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-primary",style:{width:`${Math.min(pe.norm*100,100)}%`}})}),e.jsxs("div",{className:"flex justify-between mt-1",children:[e.jsxs("span",{className:"text-[9px] text-muted-foreground",children:["Ã",pe.norm.toFixed(2)]}),e.jsxs("span",{className:"text-[9px] text-primary font-medium",children:["+",pe.weighted.toFixed(1)]})]})]},pe.label))}),e.jsxs("div",{className:"mt-3 flex items-center justify-between pt-2 border-t border-border/30",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:T.price<=0&&`Free product dampening: Ã${(a==null?void 0:a.free_dampening)||.35}`}),e.jsxs("span",{className:"text-sm font-display font-bold text-primary",children:["Final Global Score: ",T.global_score.toFixed(1)]})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4",children:[e.jsx("h4",{className:"text-sm font-semibold mb-2",children:"Product Details"}),e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Category"}),e.jsx("span",{children:T.category.replace(/_/g," ")})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Price"}),e.jsx("span",{children:T.price>0?`$${T.price.toFixed(2)}`:"Free"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Created"}),e.jsx("span",{children:new Date(T.created_at).toLocaleDateString()})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Last Updated"}),e.jsx("span",{children:T.updated_at?new Date(T.updated_at).toLocaleDateString():"â"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Last Sale"}),e.jsx("span",{children:T.last_sale_at?new Date(T.last_sale_at).toLocaleDateString():"Never"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Impressions"}),e.jsx("span",{children:T.impressions})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Wishlists"}),e.jsx("span",{children:T.wishlists})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Conversion"}),e.jsxs("span",{children:[(T.conv_rate*100).toFixed(1),"%"]})]}),(T.tags||[]).length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Tags"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:(T.tags||[]).map(pe=>e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:pe},pe))})]}),T.description&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Description"}
119),e.jsx("p",{className:"mt-1 text-foreground/80 line-clamp-3",children:T.description})]})]})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4",children:[e.jsxs("h4",{className:"text-sm font-semibold mb-2 flex items-center gap-2",children:["Images",de.length>1&&e.jsx(Y,{variant:"outline",className:"text-[10px] border-primary/30 text-primary",children:"A/B Testing Active"})]}),de.length===0?e.jsx("div",{className:"text-xs text-muted-foreground",children:T.image_url?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{children:"Single main image (no A/B test)"}),e.jsx("img",{src:T.image_url,alt:"",className:"w-32 h-32 rounded-lg object-cover cursor-pointer hover:opacity-80 transition-opacity"})]}):"No images uploaded"}):e.jsx("div",{className:"space-y-2",children:(ae||de.map(pe=>({...pe,impressions:0,clicks:0,ctr:0}))).map((pe,Ce)=>{const qe=Z===pe.id,Ze=ae?ae.reduce((Ge,He)=>Ge+He.impressions,0):0,ts=Ze>0?pe.impressions/Ze*100:0,We=ae?ae.map(Ge=>Ge.ctr):[],ns=We.length>0?We.reduce((Ge,He)=>Ge+He,0)/We.length:0,us=pe.ctr-ns;return e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-all ${Ce===0&&ae?"bg-green-500/10 border border-green-500/20":"bg-secondary/20"} ${qe?"ring-2 ring-primary/50":"hover:bg-secondary/40"}`,onClick:()=>W(qe?null:pe.id),children:[e.jsx("img",{src:pe.image_url,alt:"",className:"w-14 h-14 rounded object-cover shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("span",{className:"text-xs font-medium truncate",children:["Variant ",Ce+1]}),pe.is_thumbnail&&e.jsx(Y,{variant:"secondary",className:"text-[9px]",children:"Thumbnail"}),Ce===0&&ae&&ae[0].impressions>=10&&e.jsx(Y,{className:"text-[9px] bg-green-500/20 text-green-400 border-green-500/30",children:"Winner"})]}),ae&&e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-muted-foreground",children:[e.jsxs("span",{children:[pe.impressions," impr."]}),e.jsxs("span",{children:[pe.clicks," clicks"]}),e.jsxs("span",{className:"font-medium text-primary",children:[pe.ctr.toFixed(1),"% CTR"]})]})]}),e.jsx("div",{className:"shrink-0",children:qe?e.jsx(ma,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(js,{className:"h-3.5 w-3.5 text-muted-foreground"})})]}),qe&&e.jsxs("div",{className:"mt-2 ml-2 p-3 rounded-lg bg-secondary/10 border border-border/30 animate-in slide-in-from-top-1 duration-150 space-y-3",children:[e.jsxs("div",{className:"flex gap-4",children:[e.jsx("img",{src:pe.image_url,alt:"",className:"w-40 h-40 rounded-lg object-cover shrink-0 border border-border/30"}),e.jsxs("div",{className:"flex-1 space-y-2 text-xs",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Image ID"}),e.jsxs("code",{className:"text-[10px] text-foreground/60",children:[pe.id.slice(0,8),"..."]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sort Order"}),e.jsx("span",{children:pe.sort_order})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Is Thumbnail"}),e.jsx("span",{children:pe.is_thumbnail?"Yes":"No"})]}),ae&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Impression Share"}),e.jsxs("span",{className:"font-medium",children:[ts.toFixed(1),"%"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"CTR vs Average"}),e.jsxs("span",{className:`font-medium ${us>0?"text-green-400":us<0?"text-destructive":"text-muted-foreground"}`,children:[us>0?"+":"",us.toFixed(1),"%"]})]})]}),e.jsxs("div",{className:"pt-1.5 mt-1.5 border-t border-border/20",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mb-1",children:"Product Stats"}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Product Views"}),e.jsx("span",{className:"font-mono",children:T.views})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Product Impressions"}),e.jsx("span",{className:"font-mono",children:T.impressions})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Product CTR"}),e.jsxs("span",{className:"font-mono text-primary",children:[(T.ctr*100).toFixed(1),"%"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Conversion Rate"}),e.jsxs("span",{className:"font-mono text-primary",children:[(T.conv_rate*100).toFixed(1),"%"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sales"}),e.jsx("span",{className:"font-mono",children:T.sales})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Wishlists"}),e.jsx("span",{className:"font-mono",children:T.wishlists})]})]})]})]}),ae&&pe.impressions>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[10px] text-muted-foreground font-medium",children:"Performance"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-[10px] mb-0.5",children:[e.jsx("span",{className:"text-muted-foreground",children:"Impressions"}),e.jsx("span",{className:"font-mono",children:pe.impressions})]}),e.jsx("div",{className:"w-full h-1.5 rounded-full bg-secondary/50 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-primary/60",style:{width:`${ts}%`}})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-[10px] mb-0.5",children:[e.jsx("span",{className:"text-muted-foreground",children:"Clicks"}),e.jsx("span",{className:"font-mono",children:pe.clicks})]}),e.jsx("div",{className:"w-full h-1.5 rounded-full bg-secondary/50 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-primary",style:{width:`${Math.min(pe.ctr,100)}%`}})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-[10px] mb-0.5",children:[e.jsx("span",{className:"text-muted-foreground",children:"CTR"}),e.jsxs("span",{className:"font-mono font-medium text-primary",children:[pe.ctr.toFixed(2),"%"]})]}),e.jsx("div",{className:"w-full h-1.5 rounded-full bg-secondary/50 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-primary",style:{width:`${Math.min(pe.ctr*5,100)}%`}})})]}),pe.impressions<10&&e.jsx("p",{className:"text-[10px] text-muted-foreground
119/60 italic mt-1",children:"â Low data â need ~10+ impressions for reliable results"})]})]})]},pe.id)})})]})})]})]})]},T.id)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-display font-semibold",children:"Monetization-Aware Recommendation Algorithm v3"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Global Score"})," = ",e.jsx("code",{className:"text-primary",children:"W_boostÃBoost"})," + ",e.jsx("code",{className:"text-primary",children:"W_salesÃSales(capped)"})," + ",e.jsx("code",{className:"text-primary",children:"W_qualityÃ(RatingÃConfidence)"})," + ",e.jsx("code",{className:"text-primary",children:"W_engagementÃ(CTR+Views+Wishlists)"})," + ",e.jsx("code",{className:"text-primary",children:"W_performanceÃ(Conversion+RevenuePerView)"})," + ",e.jsx("code",{className:"text-primary",children:"W_freshnessÃ(AgeDecay+ActivityBoost+SaleRecency)"})," + ",e.jsx("code",{className:"text-primary",children:"W_sellerÃSellerRep"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Monetization Modifiers:"})," Free dampening Ã",(a==null?void 0:a.free_dampening)||.35," | New paid boost +",(a==null?void 0:a.new_paid_boost)||15,"% (<72h) | Paid injection ratio ",(((a==null?void 0:a.paid_injection_ratio)||.4)*100).toFixed(0),"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:'Exploration mode activates on ~15% of ranking passes. Trending feed uses revenue-weighted composite scoring over 14-day window. "Best Selling" now ranks by blended revenue + purchase count.'}),e.jsxs("div",{className:"mt-3 p-3 rounded-lg bg-primary/5 border border-primary/20",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(jl,{className:"h-4 w-4 text-primary"}),"Personalization + Diversity + Intent Layer"]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2 mt-2",children:[e.jsxs("div",{className:"bg-secondary/30 rounded px-3 py-2",children:[e.jsxs("p",{className:"text-xs font-medium",children:["Category Affinity â up to +",(a==null?void 0:a.W_category_affinity)||35]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Recency-weighted from views, wishlists, purchases"})]}),e.jsxs("div",{className:"bg-secondary/30 rounded px-3 py-2",children:[e.jsxs("p",{className:"text-xs font-medium",children:["Tag Similarity â up to +",(a==null?void 0:a.W_tag_similarity)||25]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Content-based matching via product tags"})]}),e.jsxs("div",{className:"bg-secondary/30 rounded px-3 py-2",children:[e.jsxs("p",{className:"text-xs font-medium",children:["Novelty Bonus â +",(a==null?void 0:a.W_novelty)||12]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Unseen products boosted, owned products hidden"})]}),e.jsxs("div",{className:"bg-secondary/30 rounded px-3 py-2",children:[e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1",children:[e.jsx(rt,{className:"h-3 w-3"})," User Intent"]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Buying intent boosts paid products up to +20%"})]})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-2",children:[e.jsx("strong",{children:"Diversity:"})," Category cap at ",(((a==null?void 0:a.category_cap_ratio)||.25)*100).toFixed(0),"% of results, creator cap at ",(a==null?void 0:a.creator_cap)||2," items. Free products dampened to ",(((a==null?void 0:a.free_dampening)||.35)*100).toFixed(0),"%."]})]})]}),d&&e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-display font-semibold flex items-center gap-2 mb-3",children:[e.jsx(Dt,{className:"h-5 w-5 text-primary"}),"Discovery Health"]}),k&&e.jsx(z,{className:"glass border-primary/20 mb-3",children:e.jsx(V,{className:"p-4",children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Marketplace Health Score"}),e.jsx("p",{className:"text-2xl font-display font-bold text-primary",children:k.score})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg Conversion"}),e.jsxs("p",{className:"text-lg font-mono",children:[(k.avgConversionRate*100).toFixed(2),"%"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Underperforming Ratio"}),e.jsxs("p",{className:"text-lg font-mono",children:[(k.underperformingRatio*100).toFixed(1),"%"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Funnel Completion"}),e.jsxs("p",{className:"text-lg font-mono",children:[(k.funnelCompletionRate*100).toFixed(2),"%"]})]})]})})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(z,{className:`glass ${d.gini>.6?"border-destructive/30":"border-green-500/30"}`,children:e.jsxs(V,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"View Gini Coefficient"}),e.jsx("p",{className:"text-2xl font-display font-bold",children:d.gini.toFixed(3)}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:d.gini<.4?"â
Healthy distribution":d.gini<.6?"â ï¸ Moderate inequality":"ð´ High inequality"}
119),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-0.5",children:"Goal: < 0.6"})]})}),e.jsx(z,{className:`glass ${d.coldStart.percentage>0?"border-destructive/30":"border-green-500/30"}`,children:e.jsxs(V,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cold-Start Coverage (7d)"}),e.jsxs("p",{className:"text-2xl font-display font-bold",children:[d.coldStart.percentage.toFixed(0),"%"]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[d.coldStart.zeroViews,"/",d.coldStart.total," new products with 0 views"]}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-0.5",children:"Goal: 0%"})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Score Range"}),e.jsxs("p",{className:"text-2xl font-display font-bold",children:[d.scoreDist.min.toFixed(0),"â",d.scoreDist.max.toFixed(0)]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Mean: ",d.scoreDist.mean.toFixed(1)," | Median: ",d.scoreDist.median.toFixed(1)]})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Score Std Dev"}),e.jsx("p",{className:"text-2xl font-display font-bold",children:d.scoreDist.stdDev.toFixed(1)}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:d.scoreDist.stdDev<d.scoreDist.mean*.5?"â
Tight spread":"â ï¸ Wide spread"})]})})]})]}),h.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"text-lg font-display font-semibold flex items-center gap-2",children:[e.jsx(zt,{className:"h-5 w-5 text-primary"}),"Recommendation Experiment Performance (Last 14 Days)"]}),e.jsx($,{size:"sm",variant:"outline",onClick:oe,children:"Auto-Tune From Variant Trends"})]}),e.jsx(z,{className:"glass border-primary/20",children:e.jsx(V,{className:"p-4 space-y-2",children:h.map((T,ne)=>e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-9 gap-2 text-xs rounded-lg border border-border/40 bg-secondary/10 px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Variant"}),e.jsx("p",{className:"font-mono font-semibold",children:ne===0?`#1 ${T.variant}`:T.variant})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Sessions"}),e.jsx("p",{className:"font-mono",children:T.sessions.toLocaleString()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground text-primary font-semibold",children:"Revenue/Session â "}),e.jsxs("p",{className:"font-mono font-bold text-primary",children:["$",T.revenuePerSession.toFixed(3)]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground font-semibold",children:"Conversion â¡"}),e.jsxs("p",{className:"font-mono font-semibold",children:[T.conversionRate.toFixed(2),"%"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"CTR â¢"}),e.jsxs("p",{className:"font-mono",children:[T.ctr.toFixed(2),"%"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"RPI"}),e.jsxs("p",{className:"font-mono",children:["$",T.impressions>0?(T.revenue/T.impressions).toFixed(4):"0.0000"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"RPM"}),e.jsxs("p",{className:"font-mono text-accent-foreground",children:["$",T.impressions>0?(T.revenue/T.impressions*1e3).toFixed(2):"0.00"]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Revenue"}),e.jsxs("p",{className:"font-mono",children:["$",T.revenue.toFixed(2)]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Funnel"}),e.jsxs("p",{className:"font-mono",children:[T.funnelCompletionRate.toFixed(2),"%"]})]})]},T.variant))})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"text-lg font-display font-semibold flex items-center gap-2",children:[e.jsx(rr,{className:"h-5 w-5 text-primary"}),"Algorithm Weights"]}),o?e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",variant:"secondary",onClick:()=>{c(a),j(!1)},children:"Cancel"}),e.jsx($,{size:"sm",onClick:X,children:"Save Weights"})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>j(!0),children:[e.jsx(ua,{className:"h-3.5 w-3.5 mr-1.5"})," Configure"]})]}),o&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:Object.entries(ll).map(([T,ne])=>e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("p",{className:"text-xs font-medium",children:ne.label}),e.jsx("span",{className:"text-sm font-mono font-bold text-primary",children:b[T]})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground mb-2",children:ne.description}),e.jsx("input",{type:"range",min:ne.min,max:ne.max,step:ne.step,value:b[T],onChange:he=>c(Oe=>({...Oe,[T]:Number(he.target.value)})),className:"w-full h-1.5 rounded-full appearance-none bg-secondary cursor-pointer accent-primary"}),e.jsxs("div",{className:"flex justify-between text-[9px] text-muted-foreground
119/60 mt-0.5",children:[e.jsx("span",{children:ne.min}),e.jsx("span",{children:ne.max})]})]})},T))}),!o&&a&&e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(ll).map(([T,ne])=>e.jsxs(Y,{variant:"secondary",className:"text-[10px] gap-1",children:[ne.label,": ",e.jsx("span",{className:"font-mono text-primary",children:a[T]})]},T))})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsx(Gs,{placeholder:"Search products or tags...",value:_,onChange:m,className:"bg-background/50",wrapperClassName:"flex-1"}),e.jsxs(Pe,{value:S,onValueChange:M,children:[e.jsx(Te,{className:"w-[160px] bg-background/50",children:e.jsx(De,{placeholder:"Category"})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Categories"}),ue.map(T=>e.jsx(L,{value:T,children:T.replace(/_/g," ")},T))]})]}),e.jsxs(Pe,{value:u,onValueChange:g,children:[e.jsx(Te,{className:"w-[180px] bg-background/50",children:e.jsx(De,{placeholder:"Sort by"})}),e.jsxs(Me,{children:[e.jsx(L,{value:"score_desc",children:"Ranking â (Score)"}),e.jsx(L,{value:"score_asc",children:"Ranking â (Score)"}),e.jsx(L,{value:"sales_desc",children:"Sales â"}),e.jsx(L,{value:"freshness_desc",children:"Freshness â"}),e.jsx(L,{value:"quality_desc",children:"Quality â"}),e.jsx(L,{value:"engagement_desc",children:"Engagement â"}),e.jsx(L,{value:"performance_desc",children:"Performance â"}),e.jsx(L,{value:"conversion_desc",children:"Conversion â"}),e.jsx(L,{value:"revenue_per_view_desc",children:"Revenue/View â"}),e.jsx(L,{value:"category_asc",children:"Category AâZ"}),e.jsx(L,{value:"name_asc",children:"Name AâZ"}),e.jsx(L,{value:"name_desc",children:"Name ZâA"})]})]})]}),je&&Fe.length>0&&e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-display font-semibold flex items-center gap-2 mb-2",children:[e.jsx(lt,{className:"h-4 w-4 text-primary"}),"Top 10 Products"]}),e.jsx(z,{className:"glass border-primary/20",children:e.jsx(V,{className:"p-2 divide-y divide-border/20",children:Fe.map((T,ne)=>ve(T,ne,!0,!0))})})]}),e.jsxs("div",{children:[je&&Ie.length>0&&e.jsxs("h3",{className:"text-sm font-display font-semibold mb-2 text-muted-foreground",children:["All Other Products (",Ie.length,")"]}),!je&&e.jsxs("h3",{className:"text-sm font-display font-semibold mb-2",children:[fe.length," product",fe.length!==1?"s":""," found"]}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-2 divide-y divide-border/20",children:[Q.map((T,ne)=>ve(T,ne,!0,!1)),Q.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8 text-sm",children:"No products match your filters"})]})}),G>1&&e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[e.jsxs($,{size:"sm",variant:"outline",disabled:y===1,onClick:()=>w(T=>T-1),children:[e.jsx(js,{className:"h-3.5 w-3.5 rotate-90"}),"Previous"]}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(G,7)},(T,ne)=>{let he;return G<=7||y<=4?he=ne+1:y>=G-3?he=G-6+ne:he=y-3+ne,e.jsx($,{size:"sm",variant:y===he?"default":"ghost",className:"h-8 w-8 p-0 text-xs",onClick:()=>w(he),children:he},he)})}),e.jsxs($,{size:"sm",variant:"outline",disabled:y===G,onClick:()=>w(T=>T+1),children:["Next",e.jsx(js,{className:"h-3.5 w-3.5 -rotate-90"})]})]})]}),s.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No approved products"})]})}function Mu(){const[s,t]=i.useState([]),[r,n]=i.useState(!0);return i.useEffect(()=>{(async()=>{n(!0);const{data:l}=await x.from("wishlists").select("product_id");if(l&&l.length>0){const o={};l.forEach(d=>{o[d.product_id]=(o[d.product_id]||0)+1});const j=Object.keys(o),{data:b}=await x.from("products").select("id, name, price, image_url, category").in("id",j),c=(b??[]).map(d=>({...d,wishlist_count:o[d.id]||0})).sort((d,P)=>P.wishlist_count-d.wishlist_count);t(c)}else t([]);n(!1)})()},[]),r?e.jsx(cs,{}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-display font-semibold",children:"Most Wishlisted Products"}),s.length===0?e.jsx("p",{className:"text-muted-foreground text-sm text-center py-8",children:"No wishlist data yet"}):e.jsx("div",{className:"space-y-2",children:s.map((a,l)=>e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-3 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-lg font-display font-bold text-muted-foreground w-8 text-center",children:["#",l+1]}),e.jsx("div",{className:"h-10 w-10 rounded bg-secondary/50 overflow-hidden flex items-center justify-center",children:a.image_url?e.jsx("img",{src:a.image_url,alt:a.name,className:"w-full h-full object-cover"}
119):e.jsx(vt,{className:"h-5 w-5 text-muted-foreground/30"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:a.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Y,{variant:"secondary",className:"text-[10px]",children:a.category}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",a.price]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Xa,{className:"h-4 w-4 text-destructive fill-destructive"}),e.jsx("span",{className:"text-lg font-display font-bold",children:a.wishlist_count})]})]})},a.id))})]})}function Eu(){const s=To(),[t,r]=i.useState(0),[n,a]=i.useState(0),[l,o]=i.useState(0);i.useEffect(()=>{(async()=>{const[g,S,M]=await Promise.all([x.from("profiles").select("id",{count:"exact",head:!0}),x.from("products").select("id",{count:"exact",head:!0}),x.from("purchases").select("id",{count:"exact",head:!0})]);r(g.count||0),a(S.count||0),o(M.count||0)})()},[]);const j=Object.values(s).flat(),b=j.length,c=j.filter(u=>u.user_id).length,d=b-c,P={};j.forEach(u=>{const g=u.page||"/";P[g]||(P[g]={count:0,users:[]}),P[g].count++,P[g].users.push({user_id:u.user_id||null,email:u.email||null,browser:u.browser})});const k=Object.entries(P).sort((u,g)=>g[1].count-u[1].count),p={};j.forEach(u=>{const g=u.browser||"Unknown";p[g]=(p[g]||0)+1});const h=Object.entries(p).sort((u,g)=>g[1]-u[1]),f={};j.forEach(u=>{u.referrer&&(f[u.referrer]=(f[u.referrer]||0)+1)});const _=Object.entries(f).sort((u,g)=>g[1]-u[1]),m=u=>{const g={"/":"Home","/shop":"Shop","/auth":"Login / Sign Up","/dashboard":"Dashboard","/admin":"Admin Panel","/dashboard/seller":"Seller Dashboard","/creators":"Creators","/payment-success":"Payment Success"};return g[u]?g[u]:u.startsWith("/product/")?"Product Detail":u.startsWith("/user/")?"User Profile":u};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Dt,{className:"h-5 w-5 text-primary animate-pulse"}),e.jsx("h2",{className:"text-xl font-display font-bold",children:"Live Site Statistics"}),e.jsx(Y,{variant:"outline",className:"ml-2 animate-pulse border-emerald-500 text-emerald-500",children:"â LIVE"})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(z,{className:"glass border-primary/20",children:e.jsxs(V,{className:"p-4 flex flex-col items-center gap-1",children:[e.jsx(bt,{className:"h-6 w-6 text-primary"}),e.jsx("span",{className:"text-2xl font-display font-bold",children:b}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Active Now"})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 flex flex-col items-center gap-1",children:[e.jsx(Ma,{className:"h-6 w-6 text-blue-400"}),e.jsx("span",{className:"text-2xl font-display font-bold",children:c}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Logged In"})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 flex flex-col items-center gap-1",children:[e.jsx(Bt,{className:"h-6 w-6 text-orange-400"}),e.jsx("span",{className:"text-2xl font-display font-bold",children:d}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Anonymous"})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 flex flex-col items-center gap-1",children:[e.jsx(qr,{className:"h-6 w-6 text-muted-foreground"}),e.jsx("span",{className:"text-2xl font-display font-bold",children:k.length}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Active Pages"})]})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Users"}),e.jsx("p",{className:"text-2xl font-display font-bold",children:t})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Products"}),e.jsx("p",{className:"text-2xl font-display font-bold",children:n})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Purchases"}),e.jsx("p",{className:"text-2xl font-display font-bold",children:l})]})})]}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("h3",{className:"text-lg font-display font-semibold mb-4 flex items-center gap-2",children:[e.jsx(bt,{className:"h-5 w-5"})," Active Users (",b,")"]}),j.length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"No active users right now."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border/50",children:[e.jsx("th",{className:"text-left py-2 px-3 text-muted-foreground font-medium",children:"User"}),e.jsx("th",{className:"text-left py-2 px-3 text-muted-foreground font-medium",children:"Page"}),e.jsx("th",{className:"text-left py-2 px-3 text-muted-foreground font-medium",children:"Browser"}),e.jsx("th",{className:"text-left py-2 px-3 text-muted-foreground font-medium",children:"Referrer"})]})}),e.jsx("tbody",{children:j.map((u,g)=>e.jsxs("tr",{className:"border-b border-border/20 hover:bg-secondary/20 transition-colors",children:[e.jsx("td",{className:"py-2 px-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:`w-2 h-2 rounded-full ${u.user_id?"bg-emerald-400":"bg-amber-400"}`}),e.jsx("span",{className:"font-medium truncate max-w-[200px]",children:u.email||"Anonymous"})]})}),e.jsx("td",{className:"py-2 px-3",children:e.jsx(Y,{variant:"secondary",className:"text-xs",children:m(u.page||"/")})}),e.jsx("td",{className:"py-2 px-3 text-muted-foreground",children:u.browser||"â"}),e.jsx("td",{className:"py-2 px-3 text-muted-foreground text-xs",children:u.referrer||"Direct"})]},g))})]})})]})}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("h3",{className:"text-lg font-display font-semibold mb-4 flex items-center gap-2",children:[e.jsx(Bt,{className:"h-5 w-5"})," Live Browsers"]}),e.jsx("div",{className:"space-y-2",children:h.length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"No data"}):h.map(([u,g],S)=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg bg-secondary/20",children:[e.jsx("span",{className:"text-sm font-medium flex-1",children:u}),e.jsx(Y,{variant:"outline",children:g})]},S))})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("h3",{className:"text-lg font-display font-semibold mb-4 flex items-center gap-2",children:[e.jsx(oa,{className:"h-5 w-5"})," Live Referrers"]}),e.jsx("div",{className:"space-y-2",children:_.length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"All visitors came directly"}):_.map(([u,g],S)=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg bg-secondary/20",children:[e.jsx("span",{className:"text-sm font-medium flex-1 truncate",children:u}),e.jsx(Y,{variant:"outline",children:g})]},S))})]})})]}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-6",children:[e.jsxs("h3",{className:"text-lg font-display font-semibold mb-4 flex items-center gap-2",children:[e.jsx(ws,{className:"h-5 w-5"})," Active Pages"]}),k.length===0?e.jsx("p",{className:"text-muted-foreground text-sm",children:"No active users right now."}):e.jsx("div",{className:"space-y-3",children:k.map(([u,g])=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-secondary/30",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:m(u)}),e.jsx("span",{className:"text-xs text-muted-foreground",children:u})]}),g.users.some(S=>S.email)&&e.jsxs("div",{className:"flex flex-wrap gap-1 mt-1",children:[g.users.filter(S=>S.email).map((S,M)=>e.jsx(Y,{variant:"secondary",className:"text-[10px] py-0",children:S.email},M)),g.users.filter(S=>!S.email).length>0&&e.jsxs(Y,{variant:"outline",className:"text-[10px] py-0",children:["+",g.users.filter(S=>!S.email).length," anonymous"]})]})]}),e.jsxs(Y,{className:"bg-primary/20 text-primary border-0",children:[g.count," ",g.count===1?"user":"users"]})]},u))})]})})]})}function Ou(){const[s,t]=i.useState({total:0,open:0,in_progress:0,resolved:0,closed:0,avgRe
119solutionHours:0,ticketsToday:0,ticketsThisWeek:0,priorityBreakdown:{},topUsers:[]}),[r,n]=i.useState(!0);return i.useEffect(()=>{(async()=>{n(!0);const{data:l}=await x.from("support_tickets").select("*");if(!l){n(!1);return}const o=new Date,j=new Date(o.getFullYear(),o.getMonth(),o.getDate()).toISOString(),b=new Date(o.getTime()-7*864e5).toISOString(),c=l.filter(y=>y.status==="open").length,d=l.filter(y=>y.status==="in_progress").length,P=l.filter(y=>y.status==="resolved").length,k=l.filter(y=>y.status==="closed").length,p=l.filter(y=>y.created_at>=j).length,h=l.filter(y=>y.created_at>=b).length,f={};l.forEach(y=>{f[y.priority]=(f[y.priority]||0)+1});const _=l.filter(y=>y.status==="resolved"||y.status==="closed");let m=0;_.length>0&&(m=_.reduce((w,F)=>{const J=new Date(F.created_at).getTime(),E=new Date(F.updated_at).getTime();return w+(E-J)/36e5},0)/_.length);const u={};l.forEach(y=>{u[y.user_id]=(u[y.user_id]||0)+1});const g=Object.entries(u).sort((y,w)=>w[1]-y[1]).slice(0,5),{data:S}=await x.from("profiles").select("user_id, display_name").in("user_id",g.map(y=>y[0])),M={};S==null||S.forEach(y=>{M[y.user_id]=y.display_name||"Unknown"}),t({total:l.length,open:c,in_progress:d,resolved:P,closed:k,avgResolutionHours:m,ticketsToday:p,ticketsThisWeek:h,priorityBreakdown:f,topUsers:g.map(([y,w])=>({user_id:y,name:M[y]||y.slice(0,8),count:w}))}),n(!1)})()},[]),r?e.jsx(cs,{}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("h3",{className:"text-lg font-display font-semibold flex items-center gap-2",children:[e.jsx(Jn,{className:"h-5 w-5 text-primary"})," Support Statistics"]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsx("p",{className:"text-3xl font-display font-bold text-primary",children:s.total}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Total Tickets"})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsx("p",{className:"text-3xl font-display font-bold text-yellow-400",children:s.open}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Open"})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsx("p",{className:"text-3xl font-display font-bold text-blue-400",children:s.in_progress}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"In Progress"})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsx("p",{className:"text-3xl font-display font-bold text-emerald-400",children:s.resolved+s.closed}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Resolved"})]})})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4",children:[e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsx(Ta,{className:"h-5 w-5 text-muted-foreground mx-auto mb-1"}),e.jsxs("p",{className:"text-2xl font-display font-bold",children:[s.avgResolutionHours.toFixed(1),"h"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg Resolution Time"})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsx("p",{className:"text-2xl font-display font-bold text-primary",children:s.ticketsToday}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tickets Today"})]})}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4 text-center",children:[e.jsx("p",{className:"text-2xl font-display font-bold text-accent",children:s.ticketsThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This Week"})]})})]}),e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4",children:[e.jsx("h4",{className:"text-sm font-display font-semibold mb-3",children:"Priority Breakdown"}),e.jsx("div",{className:"space-y-2",children:Object.entries(s.priorityBreakdown).sort((a,l)=>Number(l[1])-Number(a[1])).map(([a,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(Y,{variant:a==="urgent"?"destructive":a==="high"?"default":"secondary",className:"text-xs capitalize",children:a})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-32 h-2 rounded-full bg-secondary/50",children:e.jsx("div",{className:"h-full rounded-full bg-primary",style:{width:`${s.total>0?Number(l)/s.total*100:0}%`}})}),e.jsx("span",{className:"text-sm font-mono w-8 text-right",children:l})]})]},a))})]})}),s.topUsers.length>0&&e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-4",children:[e.jsx("h4",{className:"text-sm font-display font-semibold mb-3",children:"Top Ticket Submitters"}),e.jsx("div",{className:"space-y-2",children:s.topUsers.map((a,l)=>e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-muted-foreground font-mono w-6",children:["#",l+1]}),e.jsx("span",{className:"font-medium",children:a.name})]}),e.jsxs(Y,{variant:"outline",children:[a.count," ticket",a.count!==1?"s":""]})]}
119,a.user_id))})]})})]})}function Lu(){const[s]=i.useState([{id:"product-images",name:"Product Images",isPublic:!0},{id:"product-files",name:"Product Files",isPublic:!1},{id:"avatars",name:"Avatars",isPublic:!0},{id:"upload-chunks",name:"Upload Chunks",isPublic:!1},{id:"sitemap",name:"Sitemap",isPublic:!0}]),[t,r]=i.useState("product-images"),[n,a]=i.useState(""),[l,o]=i.useState([]),[j,b]=i.useState(!1),[c,d]=i.useState(""),[P,k]=i.useState(0),[p,h]=i.useState(!1),f=200,_=async(R,Z,W=0)=>{b(!0);const{data:D,error:X}=await x.storage.from(R).list(Z,{limit:f,offset:W*f,sortBy:{column:"name",order:"asc"}});if(X)O.error("Failed to list files"),o([]),h(!1);else{const oe=D||[];o(oe),h(oe.length>=f)}b(!1)};i.useEffect(()=>{a(""),k(0),d("")},[t]),i.useEffect(()=>{_(t,n,P)},[t,n,P]);const m=R=>{const Z=n?`${n}/${R}`:R;a(Z),k(0),d("")},u=()=>{const R=n.split("/").filter(Boolean);R.pop(),a(R.join("/")),k(0),d("")},g=R=>{const Z=n.split("/").filter(Boolean);a(Z.slice(0,R+1).join("/")),k(0),d("")},S=R=>n?`${n}/${R}`:R,M=async R=>{const Z=S(R);if(!confirm(`Delete "${Z}" from ${t}?`))return;const{error:W}=await x.storage.from(t).remove([Z]);W?O.error(W.message):(O.success("File deleted"),ss("delete_file","storage",void 0,{bucket:t,file:Z}),_(t,n,P))},y=s.find(R=>R.id===t),w=l.filter(R=>R.id===null&&R.name!==".emptyFolderPlaceholder"),F=l.filter(R=>R.id!==null),J=w.filter(R=>!c||R.name.toLowerCase().includes(c.toLowerCase())),E=F.filter(R=>!c||R.name.toLowerCase().includes(c.toLowerCase())),N=F.reduce((R,Z)=>{var W;return R+(((W=Z.metadata)==null?void 0:W.size)||0)},0),U=n.split("/").filter(Boolean);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("h3",{className:"text-lg font-display font-semibold flex items-center gap-2",children:[e.jsx(nn,{className:"h-5 w-5 text-primary"})," File Storage"]}),e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-5 gap-3",children:s.map(R=>e.jsx(z,{className:`glass cursor-pointer transition-all ${t===R.id?"ring-1 ring-primary border-primary/30":"hover:border-primary/20"}`,onClick:()=>r(R.id),children:e.jsxs(V,{className:"p-3 text-center",children:[e.jsx(Wi,{className:`h-5 w-5 mx-auto mb-1 ${t===R.id?"text-primary":"text-muted-foreground"}`}),e.jsx("p",{className:"text-xs font-medium",children:R.name}),e.jsx(Y,{variant:R.isPublic?"default":"secondary",className:"text-[10px] mt-1",children:R.isPublic?"Public":"Private"})]})},R.id))}),e.jsxs("div",{className:"flex items-center gap-1 text-sm flex-wrap",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs font-medium",onClick:()=>{a(""),k(0)},children:["ðï¸ ",t]}),U.map((R,Z)=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"/"}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>g(Z),children:R})]},Z))]}),e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("span",{className:"text-sm text-muted-foreground",children:[J.length," folders"]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[E.length," files"]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[(N/1024/1024).toFixed(2)," MB"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gs,{placeholder:"Search...",value:c,onChange:d,className:"bg-background/50 h-8 text-sm",wrapperClassName:"w-52"}),e.jsx($,{variant:"outline",size:"sm",className:"h-8",onClick:()=>_(t,n,P),children:e.jsx(St,{className:"h-3 w-3"})})]})]}),j?e.jsx(cs,{}):J.length===0&&E.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("p",{className:"text-muted-foreground",children:n?"Empty folder":"No files in this bucket"}),n&&e.jsx($,{variant:"ghost",size:"sm",className:"mt-2",onClick:u,children:"â Go back"})]}):e.jsxs("div",{className:"space-y-1",children:[n&&e.jsx(z,{className:"glass cursor-pointer hover:border-primary/20 transition-all",onClick:u,children:e.jsxs(V,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded bg-secondary/50 flex items-center justify-center shrink-0",children:e.jsx(Fl,{className:"h-5 w-5 text-muted-foreground"})}),e.jsx("p",{className:"text-sm font-medium",children:".."})]})}),J.map(R=>e.jsx(z,{className:"glass cursor-pointer hover:border-primary/20 transition-all",onClick:()=>m(R.name),children:e.jsxs(V,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(Wi,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:R.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Folder"})]})]})},R.name)),E.map(R=>{var oe,ue;const Z=/\.(jpg|jpeg|png|gif|webp|svg)$/i.test(R.name),W=((oe=R.metadata)==null?void 0:oe.size)||0,D=W>1048576?`${(W/1048576).toFixed(1)} MB`:`${(W/1024).toFixed(1)} KB`,X=S(R.name);return e.jsx(z,{className:"glass",children:e.jsxs(V,{className:"p-3 flex items-center gap-3",children:[Z&&(y!=null&&y.isPublic)?e.jsx("div",{className:"h-10 w-10 rounded bg-secondary/50 overflow-hidden shrink-0",children:e.jsx("img",{src:x.storage.from(t).getPublicUrl(X).data.publicUrl,alt:R.name,className:"w-full h-full object-cover",loading:"lazy"})}):e.jsx("div",{className:"h-10 w-10 rounded bg-secondary/50 flex items-center justify-center shrink-0",children:e.jsx(Ws,{className:"h-5 w-5 text-muted-foreground
119/50"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:R.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[D," · ",R.created_at?new Date(R.created_at).toLocaleDateString():"Unknown date",(ue=R.metadata)!=null&&ue.mimetype?` · ${R.metadata.mimetype}`:""]})]}),e.jsxs("div",{className:"flex gap-1 shrink-0",children:[(y==null?void 0:y.isPublic)&&e.jsx($,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{const fe=x.storage.from(t).getPublicUrl(X).data.publicUrl;window.open(fe,"_blank")},children:e.jsx(ws,{className:"h-3 w-3"})}),e.jsx($,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-destructive hover:text-destructive",onClick:()=>M(R.name),children:e.jsx(As,{className:"h-3 w-3"})})]})]})},R.id||R.name)})]}),(p||P>0)&&e.jsxs("div",{className:"flex justify-center gap-2 pt-2",children:[e.jsx($,{variant:"outline",size:"sm",disabled:P===0,onClick:()=>k(R=>R-1),children:"Previous"}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center",children:["Page ",P+1]}),e.jsx($,{variant:"outline",size:"sm",disabled:!p,onClick:()=>k(R=>R+1),children:"Next"})]})]})}function Fu({userId:s}){return e.jsx(Mo,{userId:s,mode:"admin"})}function $u(){var f,_;const{isOwner:s,hasPermission:t}=vs(),r=s||t("manage_messages"),[n,a]=i.useState([]),[l,o]=i.useState(null),[j,b]=i.useState([]),[c,d]=i.useState(""),P=async()=>{const{data:m}=await x.from("conversations").select("*").order("updated_at",{ascending:!1}).limit(100);if(!m)return;const u=[...new Set(m.flatMap(M=>[M.participant_1,M.participant_2]))],{data:g}=await x.from("profiles").select("user_id, display_name, avatar_url").in("user_id",u.length>0?u:["none"]),S={};g==null||g.forEach(M=>{S[M.user_id]=M}),a(m.map(M=>({...M,p1_profile:S[M.participant_1],p2_profile:S[M.participant_2]})))},k=async m=>{const{data:u}=await x.from("messages").select("*").eq("conversation_id",m).order("created_at",{ascending:!0});if(u){const g=[...new Set(u.map(y=>y.sender_id))],{data:S}=await x.from("profiles").select("user_id, display_name").in("user_id",g.length>0?g:["none"]),M={};S==null||S.forEach(y=>{M[y.user_id]=y}),b(u.map(y=>{var w;return{...y,sender_name:((w=M[y.sender_id])==null?void 0:w.display_name)||"Unknown"}}))}};i.useEffect(()=>{P()},[]);const p=async m=>{if(!confirm("Delete this message?"))return;const{error:u}=await x.from("messages").delete().eq("id",m);u?O.error(u.message):(O.success("Message deleted"),l&&k(l.id))},h=n.filter(m=>{var S,M;if(!c)return!0;const u=((S=m.p1_profile)==null?void 0:S.display_name)||"",g=((M=m.p2_profile)==null?void 0:M.display_name)||"";return u.toLowerCase().includes(c.toLowerCase())||g.toLowerCase().includes(c.toLowerCase())});return l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>o(null),children:e.jsx(Fl,{className:"h-4 w-4"})}),e.jsxs("span",{className:"font-display font-semibold text-sm",children:[((f=l.p1_profile)==null?void 0:f.display_name)||"User"," â ",((_=l.p2_profile)==null?void 0:_.display_name)||"User"]})]}),e.jsx("div",{className:"space-y-2 max-h-[500px] overflow-y-auto",children:j.map(m=>e.jsxs("div",{className:"flex items-start gap-2 p-2 rounded bg-secondary/30",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-xs font-semibold",children:m.sender_name}),e.jsx("p",{className:"text-sm",children:m.content}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:new Date(m.created_at).toLocaleString()})]}),r&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 shrink-0",onClick:()=>p(m.id),children:e.jsx(As,{className:"h-3 w-3"})})]},m.id))})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(Gs,{placeholder:"Search by user name...",value:c,onChange:d,className:"bg-background/50"}),h.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No conversations found"}):e.jsx("div",{className:"space-y-2",children:h.map(m=>{var u,g;return e.jsx(z,{className:"glass hover:border-primary/30 transition-colors cursor-pointer",onClick:()=>{o(m),k(m.id)},children:e.jsx(V,{className:"p-4 flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs("p",{className:"font-display font-semibold text-sm",children:[((u=m.p1_profile)==null?void 0:u.display_name)||"User"," â ",((g=m.p2_profile)==null?void 0:g.display_name)||"User"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:new Date(m.updated_at).toLocaleStr
119ing()})]})})},m.id)})})]})}function Uu(){const[s,t]=i.useState("all"),[r,n]=i.useState(""),[a,l]=i.useState([]),[o,j]=i.useState(null),[b,c]=i.useState(""),[d,P]=i.useState(""),[k,p]=i.useState(!1);i.useEffect(()=>{if(s!=="specific"||!r.trim()){l([]);return}const _=setTimeout(async()=>{const{data:m}=await x.from("profiles").select("user_id, display_name, avatar_url").ilike("display_name",`%${r}%`).limit(10);l(m||[])},300);return()=>clearTimeout(_)},[r,s]);const h=async()=>{if(!b.trim()){O.error("Title is required");return}p(!0);try{let _=[];if(s==="specific"){if(!o){O.error("Select a user"),p(!1);return}_=[o]}else if(s==="creators"){const{data:g}=await x.from("seller_profiles").select("user_id");_=(g||[]).map(S=>S.user_id)}else{const{data:g}=await x.from("profiles").select("user_id").limit(1e3);_=(g||[]).map(S=>S.user_id)}if(_.length===0){O.error("No users found"),p(!1);return}const m=_.map(g=>({user_id:g,type:"admin_broadcast",title:b.trim(),message:d.trim()||null})),u=100;for(let g=0;g<m.length;g+=u){const S=m.slice(g,g+u);await x.from("notifications").insert(S)}O.success(`Notification sent to ${_.length} user${_.length!==1?"s":""}!`),ss("send_notification","notification",void 0,{target:s,count:_.length,title:b.trim()}),c(""),P(""),j(null),n("")}catch(_){O.error(_.message||"Failed to send")}p(!1)},f=a.find(_=>_.user_id===o);return e.jsxs("div",{className:"max-w-lg space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-display font-bold mb-1",children:"Send Notification"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Broadcast a notification to users on the platform."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Target Audience"}),e.jsxs(Pe,{value:s,onValueChange:_=>{t(_),j(null),n("")},children:[e.jsx(Te,{className:"bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bt,{className:"h-4 w-4"})," All Users"]})}),e.jsx(L,{value:"creators",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fl,{className:"h-4 w-4"})," Creators Only"]})}),e.jsx(L,{value:"specific",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ma,{className:"h-4 w-4"})," Specific User"]}
119)})]})]})]}),s==="specific"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Search User"}),e.jsx(Gs,{placeholder:"Search by display name...",value:r,onChange:_=>{n(_),j(null)},className:"bg-background/50"}),a.length>0&&!o&&e.jsx("div",{className:"border border-border rounded-md overflow-hidden divide-y divide-border",children:a.map(_=>e.jsxs("button",{onClick:()=>{j(_.user_id),n(_.display_name||"")},className:"w-full flex items-center gap-2 px-3 py-2 hover:bg-secondary/50 transition-colors text-left",children:[e.jsxs(Bs,{className:"h-6 w-6",children:[e.jsx(it,{src:_.avatar_url||void 0}),e.jsx(qs,{className:"text-[10px]",children:(_.display_name||"?")[0]})]}),e.jsx("span",{className:"text-sm",children:_.display_name||"Unknown"})]},_.user_id))}),o&&f&&e.jsxs("div",{className:"flex items-center gap-2 p-2 border border-primary/30 rounded-md bg-primary/5",children:[e.jsxs(Bs,{className:"h-6 w-6",children:[e.jsx(it,{src:f.avatar_url||void 0}),e.jsx(qs,{className:"text-[10px]",children:(f.display_name||"?")[0]})]}),e.jsx("span",{className:"text-sm font-medium",children:f.display_name}),e.jsx(Y,{variant:"secondary",className:"text-xs ml-auto",children:"Selected"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Title *"}),e.jsx(ke,{placeholder:"Notification title...",value:b,onChange:_=>c(_.target.value),className:"bg-background/50"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Message (optional)"}),e.jsx($s,{placeholder:"Additional details...",value:d,onChange:_=>P(_.target.value),className:"bg-background/50",rows:3})]}),e.jsxs($,{onClick:h,disabled:k||!b.trim(),className:"w-full glow-primary",children:[k?e.jsx(xs,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(qt,{className:"h-4 w-4 mr-2"}),"Send Notification"]})]})]})}function Iu(){const[s,t]=i.useState([]),[r,n]=i.useState(!0);return i.useEffect(()=>{(async()=>{const{data:l}=await x.from("products").select("tags").eq("status","approved"),o={};l==null||l.forEach(b=>{(b.tags||[]).forEach(c=>{o[c]=(o[c]||0)+1})});const j=Object.entries(o).map(([b,c])=>({tag:b,count:c})).sort((b,c)=>c.count-b.count);t(j),n(!1)})()},[]),r?e.jsx(cs,{}):e.jsxs("div",{className:"space-y-6 max-w-2xl",children:[e.jsxs("h2",{className:"text-xl font-display font-semibold flex items-center gap-2",children:[e.jsx(lt,{className:"h-5 w-5 text-primary"})," Trending Tags"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Tags ranked by how many approved products use them."}),s.length===0?e.jsx("p",{className:"text-center py-8 text-muted-foreground",children:"No tags found"}):e.jsx("div",{className:"space-y-2",children:s.slice(0,50).map((a,l)=>{var o;return e.jsxs("div",{className:"flex items-center gap-3 glass rounded-lg px-4 py-3",children:[e.jsxs("span",{className:"text-sm font-mono text-muted-foreground w-8 text-right",children:["#",l+1]}),e.jsx(Y,{variant:"outline",className:"text-sm",children:a.tag}),e.jsx("div",{className:"flex-1 h-2 bg-secondary rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${a.count/(((o=s[0])==null?void 0:o.count)||1)*100}%`}})}),e.jsxs("span",{className:"text-sm font-semibold text-muted-foreground",children:[a.count," product",a.count!==1?"s":""]})]},a.tag)})})]})}function zu(){const{user:s,isOwner:t}=vs(),[r,n]=i.useState([]),[a,l]=i.useState({}),[o,j]=i.useState(!0),[b,c]=i.useState({}),[d,P]=i.useState(null),[k,p]=i.useState("pending"),[h,f]=i.useState("all"),{claim:_,unclaim:m,claiming:u}=hi("pending_product_updates"),{track:g,untrack:S}=fi(),{getViewersFor:M}=ji(),y=gi("product_update",(d==null?void 0:d.id)||null);ir("pending_product_updates",()=>{w()});const w=async()=>{j(!0);let D=x.from("pending_product_updates").select("*").order("submitted_at",{ascending:!1});k!=="all"&&(D=D.eq("status",k));const{data:X}=await D,oe=X??[];if(n(oe),oe.length>0){const ue=[...new Set(oe.map(Q=>Q.product_id))],[{data:fe},je]=await Promise.all([x.from("products").select("id, name, description, price, category, stock, version, tags, file_url, file_name, file_size, image_url, youtube_url, license_type").in("id",ue),x.from("license_tiers").select("product_id, price_cents").in("product_id",ue).eq("is_active",!0)]),Fe={};
119(je.data||[]).forEach(Q=>{Fe[Q.product_id]||(Fe[Q.product_id]={count:0,min_cents:null}),Fe[Q.product_id].count++;const xe=Q.price_cents??0;(Fe[Q.product_id].min_cents===null||xe<Fe[Q.product_id].min_cents)&&(Fe[Q.product_id].min_cents=xe)});const Ie={};(fe||[]).forEach(Q=>{var xe,ve;Ie[Q.id]={...Q,license_tier_count:((xe=Fe[Q.id])==null?void 0:xe.count)??0,min_tier_price_cents:((ve=Fe[Q.id])==null?void 0:ve.min_cents)??null}}),l(Ie);const G=[...new Set([...oe.map(Q=>Q.submitted_by).filter(Boolean),...oe.filter(Q=>Q.claimed_by).map(Q=>Q.claimed_by)])];if(G.length>0){const{data:Q}=await x.from("profiles").select("user_id, display_name").in("user_id",G),xe={};(Q||[]).forEach(ve=>{xe[ve.user_id]=ve.display_name||"Unknown"}),c(xe)}}j(!1)};i.useEffect(()=>{w()},[k]);const F=async D=>{const{data:X}=await x.from("product_images").select("image_url").eq("product_id",D.product_id).order("sort_order").order("created_at").limit(1).single(),oe=(X==null?void 0:X.image_url)||D.image_url,{error:ue}=await x.from("products").update({name:D.name,description:D.description,price:D.price,category:D.category,stock:D.stock,youtube_url:D.youtube_url,file_url:D.file_url,file_size:D.file_size,file_name:D.file_name||void 0,tags:D.tags,version:D.version,license_type:D.license_type,image_url:oe}).eq("id",D.product_id);if(ue){O.error("Failed to apply update");return}await x.from("pending_product_updates").update({status:"approved"}).eq("id",D.id),O.success("Update approved and applied!"),ss("approve_product_update","product",D.product_id),P(null),S(),w()},J=async D=>{confirm("Reject this update?")&&(await x.from("pending_product_updates").update({status:"rejected"}).eq("id",D.id),O.success("Update rejected"),ss("reject_product_update","product",D.product_id),P(null),S(),w())},E=async(D,X)=>{if(!D){O.error("No file attached");return}const{downloadProductFile:oe}=await as(async()=>{const{downloadProductFile:fe}=await import("./download-file-GiM6ssRc.js");return{downloadProductFile:fe}},__vite__mapDeps([0,1,2,3,4,5,6]));await oe(D,void 0,X||"updated-file")?O.success("Download started"):O.error("Failed to generate download link")},N=D=>{P(D),g(`update:${D.id}`,"reviewing")},U=async D=>{await _(D.id)&&w()},R=async D=>{await m(D.id)&&w()},Z=r.filter(D=>!(h==="unclaimed"&&D.claimed_by||h==="mine"&&D.claimed_by!==(s==null?void 0:s.id)||h==="others"&&(!D.claimed_by||D.claimed_by===(s==null?void 0:s.id))));if(o)return e.jsx(cs,{});const W=({label:D,oldVal:X,newVal:oe})=>JSON.stringify(X)!==JSON.stringify(oe)?e.jsxs("div",{className:"text-sm space-y-1",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:D}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx("div",{className:"p-2 rounded bg-destructive/10 border border-destructive/20 text-xs line-through opacity-70 break-words",children:Array.isArray(X)?X.join(", "):String(X??"â")}),e.jsx("div",{className:"p-2 rounded bg-primary/10 border border-primary/20 text-xs break-words",children:Array.isArray(oe)?oe.join(", "):String(oe??"â")})]})]}):null;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("h2",{className:"text-xl font-display font-semibold",children:["Pending Product Updates (",r.length,")"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Pe,{value:k,onValueChange:p,children:[e.jsx(Te,{className:"w-32 bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"pending",children:"Pending"}),e.jsx(L,{value:"approved",children:"Approved"}),e.jsx(L,{value:"rejected",children:"Rejected"}),e.jsx(L,{value:"all",children:"All"})]})]}),e.jsxs(Pe,{value:h,onValueChange:f,children:[e.jsx(Te,{className:"w-36 bg-background/50",children:e.jsx(De,{})}),e.jsxs(Me,{children:[e.jsx(L,{value:"all",children:"All Claims"}),e.jsx(L,{value:"unclaimed",children:"Unclaimed"}),e.jsx(L,{value:"mine",children:"Claimed by Me"}),e.jsx(L,{value:"others",children:"Claimed by Others"})]})]})]})]}),Z.length===0?e.jsxs("p",{className:"text-muted-foreground text-center py-8",children:["No ",k==="all"?"":k," updates"]}):e.jsx("div",{className:"space-y-3",children:Z.map(D=>{const X=D.claimed_by===(s==null?void 0:s.id),oe=!!D.claimed_by&&!X,ue=M(`update:${D.id}`),fe=a[D.product_id],je=fe&&(fe.name!==D.name||fe.price!==D.price||fe.category!==D.category||fe.version!==D.version);return e.jsx(z,{className:`glass ${oe?"opacity-60":""}`,children:e.jsx(V,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-display font-semibold text-sm",children:D.name}),e.jsx(Y,{variant:"secondary",className:"text-xs",children:D.category}),e.jsx("span",{className:"text-xs text-primary font-semibold",children:Rt(a[D.product_id]||D)}),Ft(a[D.product_id]||{})&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["· ",Ft(a[D.product_id]||{})]}),D.version&&e.jsxs(Y,{variant:"outline",className:"text-xs",children:["v",D.version]}
119),e.jsx(xa,{claimedBy:D.claimed_by||null,claimerName:b[D.claimed_by],claimedAt:D.claimed_at,isMe:X}),je&&e.jsx(Y,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:"Changed"})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[e.jsx("span",{children:new Date(D.submitted_at).toLocaleString()}),b[D.submitted_by]&&e.jsxs("span",{children:["by ",b[D.submitted_by]]})]}),ue.length>0&&e.jsx(Kr,{viewers:ue})]}),e.jsxs("div",{className:"flex gap-2 shrink-0 items-center",children:[D.status==="pending"&&e.jsx(lr,{claimedBy:D.claimed_by||null,onClaim:()=>U(D),onUnclaim:()=>R(D),isMe:X,claiming:u===D.id}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>N(D),children:[e.jsx(ws,{className:"h-3 w-3 mr-1"})," Review"]})]})]})})},D.id)})}),e.jsx(Ds,{open:!!d,onOpenChange:D=>{D||(S(),P(null))},children:e.jsxs(Ms,{className:"sm:max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(Es,{children:e.jsxs(Os,{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-4 w-4 text-primary"})," Review Update"]})}),d&&(()=>{var je,Fe;const D=a[d.product_id]||{},X=d,oe=X.claimed_by===(s==null?void 0:s.id),ue=!!X.claimed_by&&!oe,fe=M(`update:${X.id}`);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap text-sm",children:[e.jsx(Y,{variant:"outline",className:"text-xs",children:X.status}),e.jsx(xa,{claimedBy:X.claimed_by||null,claimerName:b[X.claimed_by],claimedAt:X.claimed_at,isMe:oe}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Submitted ",new Date(X.submitted_at).toLocaleString()]}),b[X.submitted_by]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["by ",b[X.submitted_by]]})]}),fe.length>0&&e.jsx(Kr,{viewers:fe}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 text-[10px] font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx("span",{children:"Current (Live)"}),e.jsx("span",{children:"Proposed Update"})]}),e.jsx(W,{label:"Name",oldVal:D.name,newVal:X.name}),e.jsx(W,{label:"Price",oldVal:Rt(D),newVal:Rt(X)}),e.jsx(W,{label:"Category",oldVal:D.category,newVal:X.category}),e.jsx(W,{label:"Version",oldVal:D.version,newVal:X.version}),e.jsx(W,{label:"Description",oldVal:(je=D.description)==null?void 0:je.slice(0,200),newVal:(Fe=X.description)==null?void 0:Fe.slice(0,200)}),e.jsx(W,{label:"Tags",oldVal:D.tags,newVal:X.tags}),e.jsx(W,{label:"Stock",oldVal:D.stock,newVal:X.stock}),e.jsx(W,{label:"License",oldVal:D.license_type,newVal:X.license_type}),e.jsx(W,{label:"YouTube URL",oldVal:D.youtube_url,newVal:X.youtube_url}),X.file_url!==D.file_url&&e.jsxs("div",{className:"text-sm space-y-1",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"File"}),e.jsxs("div",{className:"flex gap-2",children:[D.file_url&&e.jsxs($,{size:"sm",variant:"outline",className:"text-xs",onClick:()=>E(D.file_url,D.file_name),children:[e.jsx(nt,{className:"h-3 w-3 mr-1"})," Current File"]}),X.file_url&&e.jsxs($,{size:"sm",variant:"outline",className:"text-xs border-primary/30",onClick:()=>E(X.file_url,X.file_name),children:[e.jsx(nt,{className:"h-3 w-3 mr-1"})," Updated File"]})]})]}),JSON.stringify(D)===JSON.stringify({})&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"Could not load live product for comparison."}),Object.keys(D).length>0&&!["name","price","category","version","description","tags","stock","license_type","youtube_url","file_url"].some(Ie=>JSON.stringify(D[Ie])!==JSON.stringify(X[Ie]))&&e.jsx("p",{className:"text-xs text-muted-foreground italic py-2",children:"No field changes detected â possible file-only update."})]}),e.jsx(vi,{notes:y.notes,loading:y.loading,onAdd:y.addNote}),X.status==="pending"&&e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx($,{variant:"destructive",size:"sm",onClick:()=>J(X),disabled:ue,children:"Reject"}),e.jsxs($,{size:"sm",onClick:()=>F(X),disabled:ue,children:[e.jsx(At,{className:"h-3.5 w-3.5 mr-1"})," Approve & Apply"]})]})]})})()]})})]})}const lp=Object.freeze(Object.defineProperty({__proto__:null,default:Cu},Symbol.toStringTag,{value:"Module"}));
119export{fm as A,hc as B,xa as C,vi as I,ao as M,mn as P,St as R,ua as S,Nc as T,Hs as a,np as b,pc as c,hi as d,fi as e,ji as f,gi as g,Kr as h,lr as i,Gi as j,ol as k,ss as l,ip as m,_t as n,zl as o,lp as p,ir as u}; 120//# sourceMappingURL=Admin-Cg6vGO67.js.map
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.