PageSourceSearch

https://aiclubstudio.com/assets/Admin-BDLlvDQC.js

js aiclubstudio.com collected 2026-09-24 14:37:43 UTC 736,875 bytes, 731 lines download raw bytes

1import{bt as ys,cw as Va,c9 as r,cp as F,cv as o,bT as e,x as y,am as he,aL as Qe,z as Cr,aJ as li,P as ds,R as cs,U as ms,V as us,f as va,i as ba,l as Na,m as ya,j as _a,k as wa,h as ka,g as Ca,bb as ca,y as Ea,cP as kt,Y as na,cH as fr,cD as bn,a8 as di,ba as Ga,$ as ia,bH as gt,bf as Za,bl as Ue,b as Ts,d as Se,e as Ae,aa as Ma,c as Ee,a0 as fa,b6 as sa,C as ci,aB as mi,N as sr,b9 as er,aV as Xs,v as ui,L as Ra,a4 as Sr,ai as jt,n as Nn,T as Bs,s as Lr,an as Fa,B as yn,aD as Mt,D as nr,cu as Ft,S as ra,aS as _n,aW as ar,a6 as xi,A as hi,a as pi,u as gi,M as wn,bq as ji,a2 as fi,cI as kn,a1 as Cn,cM as vi,al as Sn,aR as bi,ao as Ni,b8 as yi,W as _i}from"./index-CI6avYI6.js";import{I as je}from"./input-c2KtIZde.js";import{L as oe}from"./label-BQlKK_f_.js";import{T as Te,d as Le,e as b,c as f,a as De,b as a,D as Ua}from"./table-DKDKTEvA.js";import{S as as,f as rs,g as ts,a as ns,c as pe}from"./select-i2WPjJAf.js";import{S as Vs}from"./switch-D6zflKri.js";import{T as Ss}from"./textarea-IX93-vF_.js";import{b as wi,a as ki,C as Ci}from"./collapsible-DInXZP2-.js";import{k as Si,l as Ut}from"./creditMath-ySl2BM2y.js";import{S as Ai}from"./settings-QR8NFPa2.js";import{S as Zs}from"./save-BkC7D8kW.js";import{S as $a,i as Oa,G as Ei,g as Ri,t as Pi,A as $t,C as Ii,L as Ti}from"./LoraLibraryList-10kqsTq2.js";import{C as ta}from"./coins-H2WIqHPe.js";import{P as Us}
1from"./plus-BBFzmmnQ.js";import{C as Sa,G as Dr}from"./globe-DkHoVhqA.js";import{T as qs}from"./triangle-alert-BWa2d4ok.js";import{B as Re}from"./badge-s7zqJApu.js";import{S as aa}from"./search-Bhk1X3Qs.js";import{C as An}from"./copy-Drq--ImP.js";import{E as oa}from"./external-link-Bbps5s9z.js";import{L as En,u as Li,f as Di,s as zt,S as Oi,a as Mi}from"./SupportTicketView-B-laB5hA.js";import{B as Bt,G as Rn}from"./graduation-cap-DnTgXwF6.js";import{C as Or}from"./circle-alert-hlsKdNHB.js";import{A as Fi}from"./audio-lines-Dq3Y7hRA.js";import{C as Ct}from"./chevron-left-JMBTzHrp.js";import{F as St}from"./flame-ejCjciHA.js";import{P as Ui,p as $i,r as zi}from"./communityFlowsStore-DowbukZb.js";import{D as At}from"./useUserLoras-FamGh9ax.js";import{S as rr,L as Pn,B as Bi}from"./shield-DwxFSf8w.js";import{G as qi}from"./gauge-DvJZIXTw.js";import{L as Vi}from"./lock-DUISuNvr.js";import{L as Gi}from"./leaf-CugAOBYJ.js";import{A as In,a as Et,F as Tn}from"./folder-plus-BEu-GL-d.js";import{E as Ln}from"./eye-off-C3zH4o_Z.js";import{P as $r}from"./pencil-BWcptimW.js";import{T as _s}from"./trash-2-D5KzDcyR.js";import{I as Wi}from"./info-DXcYVG5D.js";import{B as Dn}from"./book-open-ht34hyQh.js";import{T as za,b as Ba,c as Fs,a as Qs}from"./tabs-BGQ9QXuD.js";import{a as Ki,S as Hi,d as Yi,b as Ji}from"./swapTemplates-BDz9nWhr.js";import{R as ir}from"./rotate-ccw-DaRVmOC9.js";import{v as Xi,s as Qi}from"./fishaudioClient-DmOFxiIl.js";import{M as On}from"./mic-Byu7jJ-C.js";import{S as qt}from"./square-CvJMjA1Q.js";import{C as Zi,c as eo,e as so,a as ao,b as ro,d as to,A as no,F as Mn,T as Fn,S as Rt,p as Mr}from"./AdminCreateManualPostDialog-ByAYxFoS.js";import{P as io,b as oo,a as lo}from"./popover-DB1-wPER.js";import{U as jr}from"./index-BcJPsVME.js";import{F as Un}from"./frame-CZ3Jjrzo.js";import{C as co}from"./clock-D3F-Mnix.js";import{C as Da}from"./circle-x-Bi-tq8zD.js";import{U as or}from"./upload-Dk6Qf-Wu.js";import{L as mo}from"./lightbulb-DWq3TERE.js";import{B as tr}from"./ban-CFCXiXwL.js";import{G as uo}from"./gpt-image-models-B9mJr-5C.js";import{A as qa,S as xo}from"./settings-2-BMGIEJ1z.js";import{C as la,c as xa,b as ha,d as pa,a as ga}from"./card-i29gSW3Q.js";import{C as $n}from"./credit-card-BqY6ud1w.js";import{W as zn}from"./wallet-zjUNLzfN.js";import{g as ho,p as Bn,v as po,C as go,j as Aa,b as jo}from"./subDays-1ejqalbl.js";import{W as Ar,b as fo}from"./loraWeight-GadODXkb.js";import{v as vo}from"./checkpointVersion-DWUmled3.js";import{p as qr,i as Vr,u as bo}from"./loraUpload-BaP7OO3S.js";import{M as No,m as yo,p as Gr,a as _o}from"./active-workflow-CIbIXW9d.js";import{W as wo}from"./workflow-2urjC8gC.js";import{H as ko}from"./hard-drive-Ddhl-BzV.js";import{S as Co}from"./slider-7gOe2CXO.js";import{m as So,C as qn,P as Ao,D as Vt}from"./presets-4JwVuIOF.js";import{C as Vn}from"./SavePromptTemplateDialog-C9Gh4u37.js";import{D as Gn,d as Wn,a as Kn,b as gr,c as ft}from"./dropdown-menu-Bjjy4zf9.js";import{S as Wr,a as Kr,c as Hr,d as Yr,b as Jr}from"./sheet-DX3EzlTs.js";import{M as Pt}from"./mail-Dw9PaqV7.js";import{F as Eo}from"./file-text-CFZKRJ-8.js";import{S as It}from"./send-BrwBoPfv.js";import{S as Tt}from"./shield-alert-C5-HcLXp.js";import{E as Ro}from"./ellipsis-CieBqUzR.js";import{P as Fr}from"./paperclip-BPFg0BL9.js";import{C as Po}from"./check-check-BmbafQTy.js";import{U as Hn}from"./undo-2-CMZdwaPr.js";import{I as Io}from"./image-off-C5HKoMag.js";import{G as To}from"./grip-vertical-JCAMTWvw.js";import{U as Lo}from"./user-x-BVIoKKoR.js";import"./index-BdQq_4o_.js";import"./index-B_KX8jQJ.js";import"./chevron-up-wPm2ohBk.js";import"./tag-C1AxP3a0.js";import"./link-D_gGr4ry.js";import"./minimize-2-DUWeSIlq.js";import"./maximize-2-CP5SPdBE.js";import"./ModelIcon-DZ7sxSJt.js";import"./GrokBrandIcon-BwdE94Pb.js";import"./googleCreditMode-bNxNPhoz.js";import"./Gpt25ModeSelector-BbkY0pg4.js";import"./validateFileSize-C7ikwWBe.js";import"./useSpeechToText-D1o2qGV5.js";import"./use-mobile-BN24EY3X.js";import"./civitaiResolver-DL-GunhL.js";import"./PresetSelector-DNZwdfrT.js";import"./package-D4myghke.js";import"./PromptTemplatesButton-DND6xasD.js";import"./usePromptTemplates-96pHPzTm.js";import"./usePromptLibrary-C5CEaCAA.js";import"./useQuery-D5L_x_gu.js";import"./bookmark-8KyNiB-W.js";import"./EnhancePromptButton-DdVNcnp-.js";import"./GoogleAuthPicker-DNYaDylq.js";import"./useUserGoogleKeys-DYA_LwoN.js";import"./seedreamPricing-_VPL6COl.js";import"./qwen3Pricing-Cz2SNhkX.js";import"./sliders-horizontal-Co0fz36n.js";import"./minus-DFCv2y7o.js";import"./edgeRouter-BVYNcvQs.js";import"./modelLabels-BO7vGs15.js";import"./edgeFunctionError-tJ6Y4zvS.js";/**
2 * @license lucide-react v0.462.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const Yn=ys("Activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l
6-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]);/**
7 * @license lucide-react v0.462.0 - ISC
8 *
9 * This source code is licensed under the ISC license.
10 * See the LICENSE file in the root directory of this source tree.
11 */const Do=ys("ArrowDownRight",[["path",{d:"m7 7 10 10",key:"1fmybs"}],["path",{d:"M17 7v10H7",key:"6fjiku"}]]);/**
12 * @license lucide-react v0.462.0 - ISC
13 *
14 * This source code is licensed under the ISC license.
15 * See the LICENSE file in the root directory of this source tree.
16 */const Jn=ys("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);/**
17 * @license lucide-react v0.462.0 - ISC
18 *
19 * This source code is licensed under the ISC license.
20 * See the LICENSE file in the root directory of this source tree.
21 */const Xn=ys("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/**
22 * @license lucide-react v0.462.0 - ISC
23 *
24 * This source code is licensed under the ISC license.
25 * See the LICENSE file in the root directory of this source tree.
26 */const Oo=ys("CalendarClock",[["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M17.5 17.5 16 16.3V14",key:"akvzfd"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]]);/**
27 * @license lucide-react v0.462.0 - ISC
28 *
29 * This source code is licensed under the ISC license.
30 * See the LICENSE file in the root directory of this source tree.
31 */const Mo=ys("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/**
32 * @license lucide-react v0.462.0 - ISC
33 *
34 * This source code is licensed under the ISC license.
35 * See the LICENSE file in the root directory of this source tree.
36 */const Fo=ys("CircleArrowUp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}]]);/**
37 * @license lucide-react v0.462.0 - ISC
38 *
39 * This source code is licensed under the ISC license.
40 * See the LICENSE file in the root directory of this source tree.
41 */const vt=ys("CircleDot",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);/**
42 * @license lucide-react v0.462.0 - ISC
43 *
44 * This source code is licensed under the ISC license.
45 * See the LICENSE file in the root directory of this source tree.
46 */const bt=ys("FolderTree",[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]]);/**
47 * @license lucide-react v0.462.0 - ISC
48 *
49 * This source code is licensed under the ISC license.
50 * See the LICENSE file in the root directory of this source tree.
51 */const Uo=ys("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/**
52 * @license lucide-react v0.462.0 - ISC
53 *
54 * This source code is licensed under the ISC license.
55 * See the LICENSE file in the root directory of this source tree.
56 */const $o=ys("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
57 * @license lucide-react v0.462.0 - ISC
58 *
59 * This source code is licensed under the ISC license.
60 * See the LICENSE file in the root directory of this source tree.
61 */const Qn=ys("Inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]);/**
62 * @license lucide-react v0.462.0 - ISC
63 *
64 * This source code is licensed under the ISC license.
65 * See the LICENSE file in the root directory of this source tree.
66 */const zo=ys("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/**
67 * @license lucide-react v0.462.0 - ISC
68 *
69 * This source code is licensed under the ISC license.
70 * See the LICENSE file in the root directory of this source tree.
71 */const Zn=ys("MailOpen",[["path",{d:"M21.2 8.4c.5.38.8.97.8 1.6v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V10a2 2 0 0 1 .8-1.6l8-6a2 2 0 0 1 2.4 0l8 6Z",key:"1jhwl8"}],["path",{d:"m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10",key:"1qfld7"}]]);/**
72 * @license lucide-react v0.462.0 - ISC
73 *
74 * This source code is licensed under the ISC license.
75 * See the LICENSE file in the root directory of this source tree.
76 */const ei=ys("MailPlus",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M19 16v6",key:"tddt3s"}],["path",{d:"M16 19h6",key:"xwg31i"}]]);/**
77 * @license lucide-react v0.462.0 - ISC
78 *
79 * This source code is licensed under the ISC license.
80 * See the LICENSE file in the root directory of this source tree.
81 */const Lt=ys("MessageSquareText",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M13 8H7",key:"14i4kc"}],["path",{d:"M17 12H7",key:"16if0g"}]]);/**
82 * @license lucide-react v0.462.0 - ISC
83 *
84 * This source code is licensed under the ISC license.
85 * See the LICENSE file in the root directory of this source tree.
86 */const Bo=ys("OctagonAlert",[["path",{d:"M12 16h.01",key:"1drbdi"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M15.312 2a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586l-4.688-4.688A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2z",key:"1fd625"}]]);/**
87 * @license lucide-react v0.462.0 - ISC
88 *
89 * This source code is licensed under the ISC license.
90 * See the LICENSE file in the root directory of this source tree.
91 */const si=ys("PowerOff",[["path",{d:"M18.36 6.64A9 9 0 0 1 20.77 15",key:"dxknvb"}],["path",{d:"M6.16 6.16a9 9 0 1 0 12.68 12.68",key:"1x7qb5"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/**
92 * @license lucide-react v0.462.0 - ISC
93 *
94 * This source code is licensed under the ISC license.
95 * See the LICENSE file in the root directory of this source tree.
96 */const ai=ys("Power",[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]]);/**
97 * @license lucide-react v0.462.0 - ISC
98 *
99 * This source code is licensed under the ISC license.
100 * See the LICENSE file in the root directory of this source tree.
101 */const qo=ys("Printer",[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]]);/**
102 * @license lucide-react v0.462.0 - ISC
103 *
104 * This source code is licensed under the ISC license.
105 * See the LICENSE file in the root directory of this source tree.
106 */const Vo=ys("Repeat",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]]);/**
107 * @license lucide-react v0.462.0 - ISC
108 *
109 * This source code is licensed under the ISC license.
110 * See the LICENSE file in the root directory of this source tree.
111 */const Er=ys("Reply",[["polyline",{points:"9 17 4 12 9 7",key:"hvgpf2"}],["path",{d:"M20 18v-2a4 4 0 0 0-4-4H4",key:"5vmcpk"}]]);/**
112 * @license lucide-react v0.462.0 - ISC
113 *
114 * This source code is licensed under the ISC license.
115 * See the LICENSE file in the root directory of this source tree.
116 */const Gt=ys("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"}]]);/**
117 * @license lucide-react v0.462.0 - ISC
118 *
119 * This source code is licensed under the ISC license.
120 * See the LICENSE file in the root directory of this source tree.
121 */const Go=ys("Ticket",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"M13 5v2",key:"dyzc3o"}],["path",{d:"M13 17v2",key:"1ont0d"}],["path",{d:"M13 11v2",key:"1wjjxi"}]]);/**
122 * @license lucide-react v0.462.0 - ISC
123 *
124 * This source code is licensed under the ISC license.
125 * See the LICENSE file in the root directory of this source tree.
126 */const Wt=ys("UserRound",[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}
126],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]]);function ri(s){return ho(s,Date.now())}function Wo(s){return Bn(s,ri(s))}function Ko(s){return Bn(s,po(ri(s),1))}const hr="Provedor A",pr="Provedor B",Rr="Provedor C",Ho="Provedor D",Pr="API Própria",Xr=s=>s.join(""),Yo={[hr]:Xr(["Ki","e.","AI"]),[pr]:Xr(["Wave","Speed"]),[Rr]:"OpenRouter",[Ho]:Xr(["Fish"," ","Audio"]),[Pr]:"Google AI (API do usuário)",Outro:"Outro"};function Dt(){const{isAdmin:s}=Va();return r.useMemo(()=>n=>s?Yo[n]??n:n,[s])}function Jo(){const s=Dt(),[n,c]=r.useState([]),[u,m]=r.useState(!0),[_,k]=r.useState(null),[g,l]=r.useState(new Set),[h,x]=r.useState(new Set),[w,v]=r.useState(new Set),[R,$]=r.useState({credit_value_usd:"0.01",credit_markup_multiplier:"2.00",brl_usd_rate:"5.50",standalone_markup_percent:"25"}),[V,C]=r.useState(!1),[ee,Z]=r.useState(!1),[p,z]=r.useState(null),[Q,ae]=r.useState({action_key:"",label:"",wavespeed_cost_usd:"0",credits_charged:"1",api_endpoint:"",description:""}),Y=r.useCallback(async()=>{m(!0);try{const[i,A,O]=await Promise.all([F.from("credit_costs").select("*").order("label"),F.from("admin_settings").select("key, value").in("key",["credit_value_usd","credit_markup_multiplier","brl_usd_rate","standalone_markup_percent","seedance25_provider"]),F.from("credit_cost_internals").select("action_key, api_endpoint")]);if(i.data){const te=new Map((O.data||[]).map(T=>[T.action_key,T.api_endpoint]));c(i.data.map(T=>({...T,api_endpoint:te.get(T.action_key)??""})))}if(A.data){const te={};A.data.forEach(T=>{te[T.key]=T.value}),$(T=>({...T,...te}))}}catch(i){o.error(i.message)}finally{m(!1)}},[]);r.useEffect(()=>{Y()},[Y]);const B=parseFloat(R.credit_markup_multiplier)||2,G=parseFloat(R.credit_value_usd)||.01,q=i=>i<=0||G<=0?1:Math.ceil(i*B/G),E=new Set(["wavespeed_cost_usd","credits_charged","is_active"]),P=(i,A,O,te,T)=>{if(E.has(A)){const re=n.find(ke=>ke.id===i);z({id:i,field:A,value:O,label:(re==null?void 0:re.label)||te||A,oldValue:T??(re?re[A]:"?")})}else K(i,A,O)},K=async(i,A,O)=>{k(i);try{if(A==="api_endpoint"){const T=n.find(ke=>ke.id===i);if(!T)throw new Error("Linha não encontrada.");const{error:re}=await F.from("credit_cost_internals").upsert({action_key:T.action_key,api_endpoint:O,updated_at:new Date().toISOString()},{onConflict:"action_key"});if(re)throw re;c(ke=>ke.map(fe=>fe.id===i?{...fe,api_endpoint:O}:fe)),o.success("Atualizado!");return}const{error:te}=await F.from("credit_costs").update({[A]:O}).eq("id",i);if(te)throw te;c(T=>T.map(re=>re.id===i?{...re,[A]:O}:re)),o.success("Atualizado!")}catch(te){o.error(te.message)}finally{k(null),z(null)}},J=async()=>{C(!0);try{for(const[i,A]of Object.entries(R)){const{error:O}=await F.from("admin_settings").upsert({key:i,value:A,updated_at:new Date().toISOString()},{onConflict:"key"});if(O)throw O}Si(),await Y(),o.success("Configurações salvas — preços recalculados.")}catch(i){o.error(i.message)}finally{C(!1)}},W=async()=>{if(!Q.action_key||!Q.label){o.error("Preencha todos os campos obrigatórios");return}try{const{error:i}=await F.from("credit_costs").insert({action_key:Q.action_key,label:Q.label,wavespeed_cost_usd:parseFloat(Q.wavespeed_cost_usd)||0,credits_charged:parseInt(Q.credits_charged)||1,description:Q.description});if(i)throw i;if(Q.api_endpoint.trim()){const{error:A}=await F.from("credit_cost_internals").upsert({action_key:Q.action_key,api_endpoint:Q.api_endpoint.trim()},{onConflict:"action_key"});A&&o.error(`Modelo criado, mas o endpoint não salvou: ${A.message}`)}o.success("Modelo adicionado!"),Z(!1),ae({action_key:"",label:"",wavespeed_cost_usd:"0",credits_charged:"1",api_endpoint:"",description:""}),Y()}catch(i){o.error(i.message)}},N=i=>{l(A=>{const O=new Set(A);return O.has(i)?O.delete(i):O.add(i),O})},ce=i=>{const A=parseFloat(i)||0,O=q(A);ae(te=>({...te,wavespeed_cost_usd:i,credits_charged:O.toString()}))},D=i=>[{rowKey:i.id,actionKey:i.action_key,label:i.label,wavespeed_cost_usd:i.wavespeed_cost_usd,credits_charged:i.credits_charged,editable:!0}];return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"glass rounded-xl p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Ai,{className:"w-5 h-5 text-primary"}),e.jsx("h2",{className:"font-display font-semibold",children:"Configurações Globais de Créditos"})]}),e.jsxs("div",{className:"mb-4 rounded-lg border border-primary/30 bg-primary/5 p-3",children:[e.jsx("p",{className:"text-xs font-semibold text-primary mb-1",children:"📐 Fórmula oficial de cálculo"}),e.jsxs("code",{className:"text-sm font-mono",children:["créditos = (custo_USD × ",Math.round(1/G),") × ",B]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:["Equivale a: ",e.jsxs("code",{children:["USD × ",Math.round(1/G*B)]})," créditos por dólar de custo do provedor. Ex.: $0.51/s × 4s = $2.04 → ",Math.ceil(2.04*(1/G)*B)," créditos."]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Valor de 1 crédito (USD)"}),e.jsx(je,{value:R.credit_value_usd,onChange:i=>$(A=>({...A,credit_value_usd:i.target.value})),className:"h-9 text-sm"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Multiplicador de margem"}
126),e.jsx(je,{value:R.credit_markup_multiplier,onChange:i=>$(A=>({...A,credit_markup_multiplier:i.target.value})),className:"h-9 text-sm"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Câmbio BRL/USD"}),e.jsx(je,{value:R.brl_usd_rate,onChange:i=>$(A=>({...A,brl_usd_rate:i.target.value})),className:"h-9 text-sm",placeholder:"5.50"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Markup avulso (%)"}),e.jsx(je,{value:R.standalone_markup_percent,onChange:i=>$(A=>({...A,standalone_markup_percent:i.target.value})),className:"h-9 text-sm",placeholder:"25"})]})]}),e.jsx("div",{className:"mt-3 rounded-lg border border-border/50 bg-secondary/30 p-3",children:e.jsxs("p",{className:"text-[11px] text-muted-foreground space-y-0.5",children:[e.jsx("strong",{className:"text-foreground",children:"Fórmula dedução:"})," Custo USD × ",R.credit_markup_multiplier," × 100 = créditos cobrados",e.jsx("br",{}),e.jsx("strong",{className:"text-foreground",children:"Avulso:"})," $1 = ",Math.round(100/(1+(parseFloat(R.standalone_markup_percent)||25)/100))," créditos (",R.standalone_markup_percent,"% mais caro que plano)",e.jsx("br",{}),e.jsx("span",{className:"text-amber-500",children:"⚠️ Markup avulso é apenas informativo — os pacotes de crédito têm preço/quantidade fixos. Mudar este campo não altera a venda."}),e.jsx("br",{}),e.jsxs("span",{className:"text-primary",children:["ℹ️ ",e.jsx("strong",{children:"Salvar e recalcular"})," aplica os novos valores e recalcula todos os modelos automaticamente. Créditos mensais por plano são gerenciados em ",e.jsx("strong",{children:"Planos & Assinaturas"}),"."]})]})}),e.jsx("div",{className:"flex justify-end mt-4 gap-2",children:e.jsxs(y,{onClick:J,disabled:V,size:"sm",className:"gap-2",children:[V?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(Zs,{className:"w-4 h-4"}),"Salvar e recalcular"]})})]}),e.jsxs("div",{className:"glass rounded-xl p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx($a,{className:"w-5 h-5 text-primary"}),e.jsx("h2",{className:"font-display font-semibold",children:"Servidor do Seedance 2.5"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[[{v:"runninghub",label:"RunningHub",nota:"480p → 4K · até 30s"},{v:"kie",label:"Kie",nota:"480p e 720p (só isso no 2.5)"}].map(i=>{const A=R.seedance25_provider===i.v;return e.jsxs("button",{type:"button",onClick:()=>$(O=>({...O,seedance25_provider:i.v})),className:`flex flex-col items-start gap-0.5 px-4 py-2.5 rounded-lg border text-left transition-colors ${A?"border-primary bg-primary/10 text-primary":"border-border/60 bg-card/40 text-muted-foreground hover:text-foreground"}`,children:[e.jsxs("span",{className:"text-sm font-medium",children:[i.label,A&&" ✓"]}),e.jsx("span",{className:"text-[12px] opacity-70",children:i.nota})]},i.v)}),e.jsxs(y,{onClick:J,disabled:V,size:"sm",variant:"outline",className:"gap-2 ml-auto",children:[V?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(Zs,{className:"w-4 h-4"}),"Salvar servidor"]})]}),e.jsxs("p",{className:"text-[12px] text-muted-foreground mt-3",children:["Trocar pra Kie ",e.jsx("strong",{children:"remove 1080p, 2K e 4K"})," do playground — ela só oferece 480p e 720p neste modelo. Os preços de cada servidor estão na tabela abaixo, agrupados por “Seedance 2.5 · <servidor>”."]})]}),e.jsxs("div",{className:"glass rounded-xl p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ta,{className:"w-5 h-5 text-primary"}),e.jsx("h2",{className:"font-display font-semibold",children:"Custos por Modelo/Ação"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(y,{variant:"outline",size:"sm",onClick:Y,className:"gap-2",children:[e.jsx(Qe,{className:"w-4 h-4"})," Atualizar"]}),e.jsxs(y,{size:"sm",onClick:()=>Z(!0),className:"gap-2",children:[e.jsx(Us,{className:"w-4 h-4"})," Novo Modelo"]})]})]}),u?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-x-auto",children:(()=>{const i=fe=>{var _e,$e;const X=((_e=fe.api_endpoint)==null?void 0:_e.toLowerCase())||"",me=(($e=fe.action_key)==null?void 0:$e.toLowerCase())||"";return X.includes("openrouter")?!1:X.includes("generativelanguage.goo")||X.includes("google")||me.startsWith("google_")||me==="social_post"||me==="skin_enhancer_pro"},A=fe=>{var _e,$e;const X=((_e=fe.api_endpoint)==null?void 0:_e.toLowerCase())||"",me=(($e=fe.action_key)==null?void 0:$e.toLowerCase())||"";return me.startsWith("seedance")||me.startsWith("kling_motion")||me.startsWith("kling_video")||me.startsWith("gemini_omni")||me.startsWith("wan_27")||me.startsWith("nano_banana")||me.startsWith("gpt_image")||X.includes("kie")?hr:X.includes("openrouter")||me.includes("caption_generation")||me.includes("aura_describe")?Rr:i(fe)?Pr:(me==="lora_training"||X.includes("wave"),pr)},O=[pr,hr,Rr,Pr,"Outro"],te={[pr]:"text-blue-400 border-blue-500/30 bg-blue-500/10",[hr]:"text-amber-400 border-amber-500/30 bg-amber-500/10",[Rr]:"text-violet-400 border-violet-500/30 bg-violet-500/10",[Pr]:"text-emerald-400 border-emerald-500/30 bg-emerald-500/10",Outro:"text-muted-foreground border-border bg-secondary/30"},T=n.reduce((fe,X)=>{const me=A(X);return(fe[me]||(fe[me]=[])).push(X),fe},{}),re=O.filter(fe=>{var X;return(X=T[fe])==null?void 0:X.length});Object.keys(T).forEach(fe=>{re.includes(fe)||re.push(fe)});const ke=fe=>{x(X=>{const me=new Set(X);return me.has(fe)?me.delete(fe):me.add(fe),me})};return re.map(fe=>{const X=h.has(fe);return e.jsxs("div",{className:"mb-3 last:mb-0",children:[e.jsxs("button",{type:"button",onClick:()=>
126ke(fe),className:`w-full flex items-center gap-2 px-3 py-2 rounded-lg border transition-colors cursor-pointer ${te[fe]||te.Outro}`,children:[X?e.jsx(Cr,{className:"w-3.5 h-3.5"}):e.jsx(Sa,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-xs font-bold uppercase tracking-wider",children:s(fe)}),e.jsxs("span",{className:"text-[10px] opacity-60",children:["(",T[fe].length," ",T[fe].length===1?"modelo":"modelos",")"]})]}),X&&e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{className:"w-8"}),e.jsx(f,{children:"Ação"}),e.jsx(f,{children:"Label"}),e.jsx(f,{children:"Endpoint"}),e.jsx(f,{className:"text-right",children:"Custo Real (USD)"}),e.jsxs(f,{className:"text-right",children:["Custo × ",B,"x"]}),e.jsx(f,{className:"text-right",children:"Créditos"}),e.jsx(f,{className:"text-center",children:"Ativo"})]})}),e.jsx(De,{children:(()=>{const me=T[fe],_e=be=>{const ue=be.action_key;return ue.startsWith("seedance25_rh")?"Seedance 2.5 · RunningHub":ue.startsWith("seedance25_kie")?"Seedance 2.5 · Kie":ue.startsWith("seedance_mini")?"Seedance 2 Mini":ue.startsWith("seedance_fast")?"Seedance 2 Fast":ue.startsWith("seedance_pro")?"Seedance 2 Pro":ue.startsWith("kling_motion_3")?"Kling 3.0 Motion Control":ue.startsWith("kling_motion")?"Kling 2.6 Motion Control":ue.startsWith("nano_banana_pro")?"Nano Banana Pro":ue.startsWith("nano_banana_2_lite")?"Nano Banana 2 Lite":ue.startsWith("nano_banana_2")?"Nano Banana 2":ue.startsWith("gpt_image_2_5_flare")?"GPT Image 2.5 Flare":ue.startsWith("gpt_image_2_5_sunburst")?"GPT Image 2.5 Sunburst":ue.startsWith("gpt_image_2")?"GPT Image 2":ue.startsWith("veo_3_1_")?"Veo 3.1":ue.startsWith("gemini_omni")?"Gemini Omni 1.1 Flash":ue.startsWith("wan_27_video")?"WAN 2.7 Video":ue.startsWith("wan_27_image_pro")?"WAN 2.7 Image Pro":ue.startsWith("wan_27_image")?"WAN 2.7 Image":ue.startsWith("wan_extend")?"WAN Extend":ue.startsWith("wan_hot_lora")?"WAN 2.2 Hot LoRA":ue.startsWith("wan_hot")?"WAN 2.2 Hot":ue.startsWith("qwen_image_21")?"Qwen Image 2.1":ue.startsWith("qwen_image_2_pro")?"Qwen Image 2 Pro":ue.startsWith("qwen_image_2")?"Qwen Image 2":ue.startsWith("qwen_image_3_pro")?"Qwen Image 3 Pro":ue.startsWith("qwen_image_3")?"Qwen Image 3":ue.startsWith("flux_klein")?"Flux 2 Klein":ue.startsWith("z_image_turbo")?"Z-Image Turbo":ue.startsWith("z_image_base")?"Z-Image Base":ue.startsWith("skin_enhancer")?"Skin Enhancer":ue.startsWith("rh_upscale")?"Upscaler 4K":ue.startsWith("rh_video_upscale")?"Video Upscaler":ue.startsWith("upscaler")?"Upscaler":ue.startsWith("image_background_remover")?"Background Remover":ue.startsWith("ltx23_lora")?"LTX 2.3 Hot LoRA":ue.startsWith("ltx23")?"LTX 2.3 Hot":ue.startsWith("seedream")?"Seedream":ue.startsWith("recraft")?"Recraft V4.1":ue.startsWith("grok_imagine_pro")?"Grok Imagine legado":ue.startsWith("grok_imagine")?"Grok Imagine 2.0":ue.startsWith("aura")?"Aura":ue.startsWith("lora_trainer_")?"LoRA Trainer (Labs)":ue.startsWith("lora_training")?"Treinamento LoRA":ue.startsWith("caption")?"Captions":ue.startsWith("suno_")?"Áudio · Música (Suno)":ue.startsWith("fishaudio_")?"Áudio · Voz (TTS)":be.label.trim()},$e={};me.forEach(be=>{const ue=_e(be);($e[ue]||($e[ue]=[])).push(be)});const Ve=["Seedance 2.5 · RunningHub","Seedance 2.5 · Kie","Seedance 2 Mini","Seedance 2 Fast","Seedance 2 Pro","Seedance 2 Mini Ref","Seedance 2 Fast Ref","Seedance 2 Pro Ref"],Je=Object.keys($e).sort((be,ue)=>{const Pe=Ve.indexOf(be),ze=Ve.indexOf(ue);return Pe!==-1||ze!==-1?Pe===-1?1:ze===-1?-1:Pe-ze:be.localeCompare(ue)}),we=be=>{const ue=ze=>ze.includes("_480p")?0:ze.includes("_720p")?1:ze.includes("_1080p")?2:99,Pe=ze=>ze.includes("_t2v_ref_")?2:ze.includes("_t2v_")?0:ze.includes("_i2v_")?1:99;return[...be].sort((ze,Ie)=>{const xs=Pe(ze.action_key)-Pe(Ie.action_key);if(xs!==0)return xs;const Ps=ue(ze.action_key)-ue(Ie.action_key);return Ps!==0?Ps:ze.action_key.localeCompare(Ie.action_key)})},We=be=>{v(ue=>{const Pe=new Set(ue);return Pe.has(be)?Pe.delete(be):Pe.add(be),Pe})},Ge=be=>{var ue,Pe,ze;return((ue=be.action_key)==null?void 0:ue.startsWith("kling_motion"))||((Pe=be.action_key)==null?void 0:Pe.startsWith("seedance"))||((ze=be.action_key)==null?void 0:ze.startsWith("wan_27_video"))},ps=be=>D(be).map(Pe=>
126{const ze=Pe.editable&&g.has(Pe.rowKey),Ie=i(be),xs=Ge(be),Ps=Ie?0:q(be.wavespeed_cost_usd);Pe.editable&&!Ie&&!xs&&be.credits_charged;const Ze=e.jsxs(e.Fragment,{children:[e.jsxs(b,{className:"group",children:[e.jsx(a,{className:"w-8 p-1",children:Pe.editable?e.jsx(wi,{asChild:!0,children:e.jsx("button",{className:"p-1 rounded hover:bg-secondary/60 transition-colors",children:ze?e.jsx(Cr,{className:"w-3.5 h-3.5 text-muted-foreground"}):e.jsx(Sa,{className:"w-3.5 h-3.5 text-muted-foreground"})})}):e.jsx("span",{className:"block w-5"})}),e.jsx(a,{className:"text-xs font-mono text-muted-foreground",children:Pe.actionKey}),e.jsx(a,{children:Pe.editable?e.jsx(je,{defaultValue:be.label,className:"h-8 text-xs w-48",onBlur:es=>{es.target.value!==be.label&&P(be.id,"label",es.target.value)}}):e.jsx("span",{className:"text-xs text-muted-foreground",children:Pe.label})}),e.jsx(a,{className:"text-xs font-mono text-muted-foreground max-w-[200px] truncate",title:be.api_endpoint,children:be.api_endpoint?e.jsx("span",{className:"flex items-center gap-1",children:e.jsx("span",{className:"truncate",children:be.api_endpoint})}):e.jsx("span",{className:"opacity-50",children:"—"})}),e.jsx(a,{className:"text-right",children:Ie?e.jsx("span",{className:"text-xs text-muted-foreground opacity-50",children:"—"}):Pe.editable?e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[e.jsx(je,{defaultValue:be.wavespeed_cost_usd.toString(),className:"h-8 text-xs w-24 text-right",onBlur:es=>{const ws=parseFloat(es.target.value);!isNaN(ws)&&ws!==be.wavespeed_cost_usd&&P(be.id,"wavespeed_cost_usd",ws,be.label,be.wavespeed_cost_usd)}}),xs&&e.jsx("span",{className:"text-[10px] text-amber-400 font-medium",children:"/s"})]}):e.jsxs("span",{className:"text-xs font-mono",children:["$",Pe.wavespeed_cost_usd.toFixed(4)]})}),e.jsx(a,{className:"text-right text-xs text-muted-foreground",children:Ie?"—":xs?e.jsxs("span",{className:"text-amber-400",children:["$",(Pe.wavespeed_cost_usd*B).toFixed(4),"/s"]}):`$${(Pe.wavespeed_cost_usd*B).toFixed(4)}`}),e.jsx(a,{className:"text-right",children:Ie?e.jsx("span",{className:"text-xs text-emerald-400 font-medium",children:"Grátis (API do usuário)"}):xs?e.jsx("span",{className:"text-xs text-amber-400 font-medium",children:"Dinâmico (por segundo)"}):e.jsxs("div",{className:"flex flex-col items-end gap-0.5",children:[e.jsx("span",{className:"text-sm font-mono font-semibold text-primary",children:Pe.credits_charged}),e.jsxs("span",{className:"text-[9px] text-muted-foreground",title:"Calculado automaticamente pelo trigger",children:["auto: $",Pe.wavespeed_cost_usd.toFixed(4)," × ",Math.round(B/G)]})]})}),e.jsx(a,{className:"text-center",children:e.jsx(Vs,{checked:be.is_active,onCheckedChange:es=>Pe.editable&&P(be.id,"is_active",es,be.label,be.is_active),disabled:!Pe.editable||_===be.id})})]}),Pe.editable&&e.jsx(ki,{asChild:!0,children:e.jsx(b,{className:"bg-secondary/20 hover:bg-secondary/30",children:e.jsx(a,{colSpan:8,className:"py-3 px-6",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Endpoint da API"}
126),e.jsx(je,{defaultValue:be.api_endpoint,className:"h-8 text-xs font-mono",placeholder:"ex: caminho-do-modelo/variante",onBlur:es=>{es.target.value!==be.api_endpoint&&P(be.id,"api_endpoint",es.target.value)}})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"Descrição (quando/como/por que é usado)"}),e.jsx(Ss,{defaultValue:be.description,className:"text-xs min-h-[60px] resize-none",placeholder:"Descreva quando este modelo é acionado, em qual contexto e por quê...",onBlur:es=>{es.target.value!==be.description&&P(be.id,"description",es.target.value)}})]})]})})})})]});return Pe.editable?e.jsx(Ci,{asChild:!0,open:ze,onOpenChange:()=>N(Pe.rowKey),children:e.jsx(e.Fragment,{children:Ze})},Pe.rowKey):e.jsx(r.Fragment,{children:Ze},Pe.rowKey)});return Je.map(be=>{const ue=we($e[be]);if(ue.length===1)return ps(ue[0]);const Pe=`${fe}::${be}`,ze=w.has(Pe);return e.jsxs(li.Fragment,{children:[e.jsxs(b,{className:"cursor-pointer hover:bg-secondary/40 transition-colors",onClick:()=>We(Pe),children:[e.jsx(a,{className:"w-8 p-1",children:e.jsx("button",{className:"p-1 rounded",children:ze?e.jsx(Cr,{className:"w-3.5 h-3.5 text-muted-foreground"}):e.jsx(Sa,{className:"w-3.5 h-3.5 text-muted-foreground"})})}),e.jsxs(a,{colSpan:5,className:"text-xs font-semibold text-foreground",children:[be,e.jsxs("span",{className:"ml-2 text-[10px] text-muted-foreground font-normal",children:["(",ue.reduce((Ie,xs)=>Ie+D(xs).length,0)," variantes)"]})]}),e.jsxs(a,{className:"text-right text-[10px] text-muted-foreground",children:[Math.min(...ue.map(Ie=>Ie.credits_charged)),"–",Math.max(...ue.map(Ie=>Ie.credits_charged))]}),e.jsx(a,{className:"text-center text-[10px]",children:e.jsxs("span",{className:ue.every(Ie=>Ie.is_active)?"text-emerald-400":ue.some(Ie=>Ie.is_active)?"text-amber-400":"text-muted-foreground",children:[ue.filter(Ie=>Ie.is_active).length,"/",ue.length]})})]}),ze&&ue.flatMap(Ie=>ps(Ie))]},Pe)})})()})]})]},fe)})})()}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-3",children:["Fórmula: Créditos = ceil(Custo USD × ",B," / $",G,") · 1 crédito = $",G," USD"]})]}),e.jsx(ds,{open:ee,onOpenChange:Z,children:e.jsxs(cs,{className:"sm:max-w-lg",children:[e.jsx(ms,{children:e.jsx(us,{children:"Adicionar Novo Modelo"})}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Action Key (único)"}),e.jsx(je,{value:Q.action_key,onChange:i=>ae(A=>({...A,action_key:i.target.value})),placeholder:"ex: new_model_t2i",className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Label (nome exibido)"}),e.jsx(je,{value:Q.label,onChange:i=>ae(A=>({...A,label:i.target.value})),placeholder:"ex: Novo Modelo - T2I",className:"h-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Endpoint da API"}),e.jsx(je,{value:Q.api_endpoint,onChange:i=>ae(A=>({...A,api_endpoint:i.target.value})),placeholder:"ex: provider/model-name",className:"h-9 font-mono text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Descrição"}),e.jsx(Ss,{value:Q.description,onChange:i=>ae(A=>({...A,description:i.target.value})),placeholder:"Quando e por que este modelo é usado...",className:"text-xs min-h-[60px] resize-none"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Custo Real (USD)"}),e.jsx(je,{value:Q.wavespeed_cost_usd,onChange:i=>ce(i.target.value),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(oe,{className:"text-xs flex items-center gap-1",children:["Créditos Cobrados",e.jsx(Xn,{className:"w-3 h-3 text-primary/60"}),e.jsx("span",{className:"text-[10px] text-primary/60 font-normal",children:"(auto)"})]}),e.jsx(je,{value:Q.credits_charged,onChange:i=>ae(A=>({...A,credits_charged:i.target.value})),type:"number",className:"h-9"})]})]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Cálculo automático: ceil($",Q.wavespeed_cost_usd||"0"," × ",B," / $",G,") = ",e.jsxs("strong",{children:[q(parseFloat(Q.wavespeed_cost_usd)||0)," créditos"]})]}),e.jsxs(y,{onClick:W,className:"w-full gap-2",children:[e.jsx(Us,{className:"w-4 h-4"})," Adicionar"]})]})]})}),e.jsx(va,{open:!!p,onOpenChange:i=>!i&&z(null),children:e.jsxs(ba,{children:[e.jsxs(Na,{children:[e.jsxs(ya,{className:"flex items-center gap-2",children:[e.jsx(qs,{className:"w-5 h-5 text-yellow-500"}),"Confirmar alteração"]}),e.jsx(_a,{asChild:!0,children:e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("p",{children:["Você está alterando ",e.jsx("strong",{children:(p==null?void 0:p.field)==="wavespeed_cost_usd"?"o custo real (USD)":(p==null?void 0:p.field)==="credits_charged"?"os créditos cobrados":"o status"})," de ",e.jsx("strong",{children:p==null?void 0:p.label}),"."]}),e.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-3 text-xs space-y-1",children:[e.jsxs("p",{children:["⚠️ ",e.jsx("strong",{children:"Essa mudança impacta todo o sistema:"})]}),e.jsxs("ul",{className:"list-disc list-inside space-y-0.5 text-muted-foreground",children:[e.jsx("li",{children:"Afeta o custo de todas as gerações futuras para todos os usuários"}),e.jsx("li",{children:"Pode alterar a margem de lucro por operação"}),e.jsx("li",{children:"Impacta as estimativas de imagens nos pacotes de créditos"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Valor anterior: ",e.jsx("strong",{children:String(p==null?void 0:p.oldValue)})," → Novo valor: ",e.jsx("strong",{children:String(p==null?void 0:p.value)})]})]})})]}),e.jsxs(wa,{children:[e.jsx(ka,{children:"Cancelar"}),e.jsx(Ca,{onClick:()=>{p&&K(p.id,p.field,p.value)},className:"bg-destructive hover:bg-destructive/90",children:"Confirmar Alteração"})]})]})})]})}const Kt={seedance:{label:"Seedance 2",color:"border-amber-500/30 bg-amber-500/10 text-amber-400"},kling:{label:"Kling Motion",color:"border-violet-500/30 bg-violet-500/10 text-violet-400"},klingvideo:{label:"Kling (Vídeo)",color:"border-sky-500/30 bg-sky-500/10 text-sky-400"},wan27_video:{label:"WAN 2.7 Vídeo",color:"border-cyan-500/30 bg-cyan-500/10 text-cyan-400"},wan30_video:{label:"WAN 3.0 Vídeo",color:"border-fuchsia-500/30 bg-fuchsia-500/10 text-fuchsia-400"},happyhorse:{label:"HappyHorse 1.0 (Vídeo)",color:"border-fuchsia-500/30 bg-fuchsia-500/10 text-fuchsia-400"},wan22_hot:{label:"WAN 2.2 Hot",color:"border-pink-500/30 bg-pink-500/10 text-pink-400"},ltx23:{label:"LTX 2.3 Hot",color:"border-emerald-500/30 bg-emerald-500/10 text-emerald-400"},ltx23n:{label:"LTX 2.3 (Normal)",color:"border-teal-500/30 bg-teal-500/10 text-teal-400"},grokvideo:{label:"Grok Imagine 1.5 (Vídeo)",color:"border-indigo-500/30 bg-indigo-500/10 text-indigo-400"}};function Xo(){const[s,n]=r.useState([]),[c,u]=r.useState(!0),[m,_]=r.useState(null),[k,g]=r.useState(200),[l,h]=r.useState([]),[x,w]=r.useState({}),[v,R]=r.useState(null),$=r.useCallback(async()=>{u(!0);const[p,z,Q,ae]=await Promise.all([F.from("model_pricing_tiers").select("*").order("engine").order("sort_order"),F.from("admin_settings").select("key, value").in("key",["credit_markup_multiplier","credit_value_usd"]),F.from("model_provider_options").select("engine,provider,label,pricing,notes,is_enabled,sort_order").eq("is_enabled",!0).order("engine").order("sort_order"),F.from("model_provider_routes").select("engine,active_provider")]);if(n(p.data??[]),z.data){const Y={};z.data.forEach(q=>{Y[q.key]=q.value});const B=parseFloat(Y.credit_markup_multiplier)||2,G=parseFloat(Y.credit_value_usd)||.01;G>0&&g(Math.round(B/G))}Q.error||ae.error?o.error("Não foi possível carregar o roteamento de provedores."):(h(Q.data??[]),w(Object.fromEntries((ae.data??[]).map(Y=>[Y.engine,Y.active_provider])))),u(!1)},[]);r.useEffect(()=>{$()},[$]);const V=async(p,z,Q)=>{_(p);const{error:ae}=await F.from("model_pricing_tiers").update({[z]:Q}).eq("id",p);if(_(null),ae){o.error(ae.message);return}Ut(),n(Y=>Y.map(B=>B.id===p?{...B,[z]:Q}:B)),o.success("Atualizado!")},C=async()=>{const{data:p,error:z}=await F.rpc("recalculate_all_credit_costs");if(z){o.error(z.message);return}o.success(`${(p==null?void 0:p.updated)??0} modelos recalculados.`)},ee=async(p,z)=>{R(`${p}:${z}`);const{error:Q}=await F.rpc("set_active_model_provider",{p_engine:p,p_provider:z});if(R(null),Q){o.error(Q.message);return}Ut(),await $(),o.success("Provedor ativo e tabela de preços atualizados.")},Z=s.reduce((p,z)=>{var Q;return(p[Q=z.engine]||(p[Q]=[])).push(z),p},{});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"glass rounded-xl p-6 border border-primary/30 bg-primary/5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(ca,{className:"w-5 h-5 text-primary"}),e.jsx("h2",{className:"font-display font-semibold",children:"Preç
126os Dinâmicos por Segundo/Imagem"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Aqui você gerencia os ",e.jsx("strong",{children:"custos USD por unidade"})," de TODOS os modelos com cobrança variável. Edite somente o ",e.jsx("code",{children:"USD/unidade"})," — os créditos finais são calculados em tempo real pela fórmula",e.jsxs("code",{className:"ml-1",children:["USD × ",k]})," (markup × valor do crédito).",e.jsx("br",{}),e.jsx("span",{className:"text-primary",children:'✓ Frontend (preview), edge functions (cobrança real) e a aba "Créditos" lêem desta tabela.'}),e.jsx("br",{}),e.jsx("span",{className:"text-muted-foreground",children:'⚡ WAN 2.2 Hot: ao salvar aqui, os registros em "Créditos" sincronizam automaticamente via trigger.'})]}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(y,{variant:"outline",size:"sm",onClick:$,className:"gap-2",children:[e.jsx(Qe,{className:"w-4 h-4"})," Recarregar"]}),e.jsxs(y,{size:"sm",onClick:C,className:"gap-2",children:[e.jsx(Xn,{className:"w-4 h-4"})," Recalcular custos fixos"]})]})]}),l.length>0&&e.jsxs("div",{className:"glass rounded-xl p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx($a,{className:"w-5 h-5 text-primary"}),e.jsx("h2",{className:"font-display font-semibold",children:"Roteamento de provedores por modelo"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mb-4",children:"A troca vale somente para novas gerações. Cada job em andamento continua consultando o provedor que o aceitou. A tabela pública de preço é sincronizada na mesma operação, sem precisar de deploy."}),e.jsx("div",{className:"space-y-4",children:Object.entries(l.reduce((p,z)=>{var Q;return(p[Q=z.engine]||(p[Q]=[])).push(z),p},{})).map(([p,z])=>{var Q;return e.jsxs("div",{className:"rounded-lg border border-border/60 bg-card/30 p-4",children:[e.jsx("div",{className:"text-sm font-semibold mb-3",children:((Q=Kt[p])==null?void 0:Q.label)??p}),e.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:z.map(ae=>{const Y=x[p]===ae.provider,B=Object.values(ae.pricing).map(Number).filter(Number.isFinite),G=B.length?Math.min(...B):0,q=B.length?Math.max(...B):0,E=v===`${p}:${ae.provider}`;return e.jsxs("button",{type:"button",disabled:v!==null,onClick:()=>ee(p,ae.provider),className:`rounded-lg border p-3 text-left transition-colors ${Y?"border-primary bg-primary/10":"border-border/60 bg-background/30 hover:border-primary/40"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:ae.label}),E?e.jsx(he,{className:"h-4 w-4 animate-spin"}):Y?e.jsx(Ea,{className:"h-4 w-4 text-primary"}):null]}),e.jsxs("div",{className:"mt-1 text-[11px] text-muted-foreground",children:["$",G.toFixed(4),"–$",q.toFixed(4),"/s · ",ae.notes]})]},ae.provider)})})]},p)})})]}),c?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):Object.entries(Z).map(([p,z])=>{const Q=Kt[p]??{label:p,color:"border-border bg-secondary/30 text-muted-foreground"};return e.jsxs("div",{className:"glass rounded-xl p-4",children:[e.jsxs("div",{className:`inline-flex items-center gap-2 px-3 py-1.5 rounded-lg border text-xs font-bold uppercase tracking-wider mb-3 ${Q.color}`,children:[Q.label,e.jsxs("span",{className:"text-[10px] opacity-60",children:["(",z.length,")"]})]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Tier"}),e.jsx(f,{children:"Label"}),e.jsx(f,{className:"text-right",children:"USD/unidade"}),e.jsx(f,{className:"text-center",children:"Unidade"}),e.jsx(f,{className:"text-right",children:"Preview (4 un.)"}),e.jsx(f,{className:"text-center",children:"Ativo"})]})}),e.jsx(De,{children:z.map(ae=>e.jsxs(b,{children:[e.jsx(a,{className:"text-xs font-mono text-muted-foreground",children:ae.tier_key}),e.jsx(a,{className:"text-xs",children:ae.label}),e.jsx(a,{className:"text-right",children:e.jsx(je,{type:"number",step:"0.0001",defaultValue:ae.usd_per_unit,className:"h-8 text-xs w-24 text-right ml-auto",onBlur:Y=>{const B=parseFloat(Y.target.value);!isNaN(B)&&B!==Number(ae.usd_per_unit)&&V(ae.id,"usd_per_unit",B)},disabled:m===ae.id})}),e.jsx(a,{className:"text-center text-xs text-muted-foreground",children:ae.unit}),e.jsxs(a,{className:"text-right text-xs",children:[e.jsxs("span",{className:"font-mono text-primary",children:[Math.max(1,Math.ceil(Number(ae.usd_per_unit)*4*k))," créditos"]}),e.jsxs("div",{className:"text-[9px] text-muted-foreground",children:["$",(Number(ae.usd_per_unit)*4).toFixed(4)," × ",k]})]}),e.jsx(a,{className:"text-center",children:e.jsx(Vs,{checked:ae.is_active,onCheckedChange:Y=>V(ae.id,"is_active",Y),disabled:m===ae.id})})]},ae.id))})]})]},p)})]})}function Es(s){if(!s)return null;const n=Date.parse(s);return Number.isFinite(n)?n:null}function Ht(s,n){const c=Es(s),u=Es(n);return c===null?n??null:u===null?s??null:c<=u?s:n}function He(s){return String(s??"").replace(/[&<>"]/g,n=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[n])}function da(s){if(!s)return"—";const n=Date.parse(s);
126return Number.isFinite(n)?`${new Date(n).toLocaleString("pt-BR",{timeZone:"UTC"})} UTC`:"—"}function Qo(s){if(!s)return"—";const n=Date.parse(s);return Number.isFinite(n)?new Date(n).toLocaleDateString("pt-BR",{timeZone:"UTC"}):"—"}function Yt(s,n){if(s==null||!Number.isFinite(s)||!n)return"—";try{const c=new Intl.NumberFormat("pt-BR",{style:"currency",currency:n.toUpperCase()}),u=c.resolvedOptions().maximumFractionDigits??2;return He(c.format(s/10**u))}catch{return"—"}}function Zo(s){if(!s)return null;try{const n=new URL(s);return n.protocol==="https:"&&!n.username&&!n.password?n.href:null}catch{return null}}const el={video:"Vídeo",audio:"Áudio","3d":"3D",model:"3D"};function sl(s){const n=(s??[]).slice(0,12);return n.length===0?"":`
127<h2>Amostra de gerações</h2>
128<p class="sub">Amostra de até 12 mídias concluídas no período. Mídia isolada não comprova consumo de créditos pagos nem vínculo com a compra contestada.</p>
129<div class="gallery">${n.map(u=>{const m=(u.mediaType||"").toLowerCase(),_=Zo(u.thumbUrl),k=_?`<img src="${He(_)}" alt="${He(u.model||m||"geração")}" referrerpolicy="no-referrer" />`:`<div class="ph">${He(el[m]||m||"mídia")}</div>`,g=u.model?`<div class="gm">${He(u.model)}</div>`:"";return`<figure class="gcell">${k}${g}<figcaption>${He(da(u.createdAt))}</figcaption></figure>`}).join("")}</div>`}function al(s){const n=s??[];return n.length===0?"":`
130<h2>Ciclos de crédito / referência de fatura</h2>
131<p class="sub">Concessões de crédito da assinatura. A data do ciclo não comprova a data do pagamento; pode haver vários ciclos para a mesma fatura anual.</p>
132<table class="cyc">
133  <thead><tr><th>Data</th><th>Fatura</th><th>Créditos</th><th>Motivo</th></tr></thead>
134  <tbody>${n.map(u=>{const m=Qo(u.cycle_start||u.created_at),_=He(u.invoice_id||"—"),k=u.credits===null||u.credits===void 0?"—":He(u.credits),g=He(u.reason||"—");return`<tr><td>${m}</td><td class="mono">${_}</td><td class="num">${k}</td><td>${g}</td></tr>`}).join("")}</tbody>
135</table>`}function rl(s){var V;const{evidence:n,account:c,terms:u,generatedAt:m}=s,_=sl((V=s.generationsSample)==null?void 0:V.filter(C=>{const ee=Es(C.createdAt);return ee!==null&&Es(n.purchaseDate)!==null&&ee>=Es(n.purchaseDate)&&ee<=Es(n.cutoffAt)})),k=al(s.cycles),g=Object.entries(n.generationsByType).map(([C,ee])=>`${He(C)}: ${ee}`).join(" · ")||"—",l=n.consumed,h=n.policySummary,x=(C,ee)=>`<tr><td class="l">${He(C)}</td><td class="v">${ee}</td></tr>`,w=u.items.map(C=>`<li>${He(C)}</li>`).join(""),v=s.payment,R=v?[x("Pagamento selecionado",He(v.id)),x("Data do pagamento",da(v.paidAt)),x("Valor pago",Yt(v.amount,v.currency)),x("Valor devolvido em dinheiro",Yt(v.refundedAmount,v.currency)),x("Tipo",He(v.kind||"—")),x("Fatura / PaymentIntent",`${He(v.invoiceId||"—")} / ${He(v.paymentIntentId||"—")}`)].join(""):x("Pagamento selecionado","Não verificado; data informada manualmente."),$=n.auditRows.map(C=>`<tr><td class="mono">${He(C.id||"sem ID")}</td><td>${He(C.createdAt)}</td><td>${He(C.action)}<br/><span class="mono">${He(C.taskId||"sem task")}</span></td><td>${He(C.tokens)}</td><td>${He(C.state)}</td><td>${He(C.confirmedCredits)} / ${He(C.returnedCredits)}</td></tr>`).join("");return`<!doctype html><html lang="pt-BR"><head><meta charset="utf-8"><title>Prova de uso — ${He(c.email||c.userId)}</title>
136<style>
137  :root{color-scheme:light}
138  *{box-sizing:border-box}
139  body{font:13px/1.5 -apple-system,Segoe UI,Roboto,Arial,sans-serif;color:#111;margin:32px;background:#fff}
140  h1{font-size:19px;margin:0 0 2px}
141  h2{font-size:13px;text-transform:uppercase;letter-spacing:.04em;color:#555;margin:22px 0 6px;border-bottom:1px solid #e5e5e5;padding-bottom:4px}
142  .sub{color:#666;font-size:12px;margin:0 0 4px}
143  table{width:100%;border-collapse:collapse;margin-top:4px}
144  td{padding:4px 8px;border-bottom:1px solid #f0f0f0;vertical-align:top}
145  td.l{color:#666;width:42%}
146  td.v{font-weight:600}
147  .verdict{margin:14px 0;padding:12px 14px;border-radius:8px;font-weight:600}
148  .bad{background:#fdecec;border:1px solid #f3b4b4;color:#a01818}
149  .ok{background:#eafaf0;border:1px solid #a9e2c0;color:#166534}
150  ul{margin:6px 0 0;padding-left:18px}
151  li{margin:4px 0}
152  .foot{margin-top:22px;color:#888;font-size:11px;border-top:1px solid #e5e5e5;padding-top:8px}
153  .gallery{display:grid;grid-template-columns:repeat(4,1fr);gap:8px;margin-top:6px}
154  .gcell{margin:0;border:1px solid #e5e5e5;border-radius:6px;overflow:hidden;background:#fafafa;break-inside:avoid}
155  .gcell img{display:block;width:100%;height:96px;object-fit:cover;background:#eee}
156  .gcell .ph{display:flex;align-items:center;justify-content:center;width:100%;height:96px;background:#f0f0f0;color:#888;font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.05em}
157  .gcell .gm{padding:3px 6px 0;font-size:10px;font-weight:600;color:#444;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
158  .gcell figcaption{padding:1px 6px 5px;font-size:9px;color:#888}
159  table.cyc th{text-align:left;padding:4px 8px;border-bottom:1px solid #e5e5e5;color:#666;font-size:11px;text-transform:uppercase;letter-spacing:.03em}
160  table.cyc td{font-weight:400}
161  td.mono,.mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px}
162  td.num,.num{text-align:right;font-variant-numeric:tabular-nums;font-weight:600}
163  @media print{body{margin:12mm}.gcell,figure{break-inside:avoid}}
164</style></head><body>
165<h1>AI Club Studio — Prova de uso (disputa/chargeback)</h1>
166<p class="sub">Gerado em ${He(m)}</p>
167<div class="verdict ${l?"bad":"ok"}">${He(h)}</div>
168<p class="sub">Análise indicativa da política comercial. Direitos obrigatórios previstos na legislação aplicável permanecem preservados. Cancelamento impede cobranças futuras e continua disponível independentemente desta análise de reembolso.</p>
169${n.warnings.length?`<ul>${n.warnings.map(C=>`<li>${He(C)}</li>`).join("")}</ul>`:""}
170
171<h2>Conta</h2>
172<table>
173  ${x("E-mail",He(c.email||"—"))}
174  ${x("Apelido",He(c.nickname||"—"))}
175  ${x("ID do usuário",He(c.userId))}
176  ${x("Stripe customer",He(c.stripeCustomerId||"—"))}
177  ${x("Stripe subscription",He(c.stripeSubscriptionId||"—"))}
178</table>
179
180<h2>Assinatura / compra</h2>
181<table>
182  ${x("Plano",He(c.plan||"—"))}
183  ${x("Status",He(c.status||"—"))}
184  ${x("Intervalo",He(c.interval||"—"))}
185  ${x("Início da assinatura",da(c.subscriptionStartedAt))}
186  ${x("Renova em",da(c.subscriptionRenewsAt))}
187  ${x("Saldo atual (plano / avulso)",`${He(c.premiumCredits??"—")} / ${He(c.purchasedCredits??"—")}`)}
188  ${x("Data da compra contestada",n.purchaseDate?da(n.purchaseDate):"não informada")}
189  ${x("Data do pedido de reembolso",n.requestedAt?da(n.requestedAt):"não informada")}
190  ${x("Limite dos eventos analisados",da(n.cutoffAt))}
191  ${x("Janela de reembolso",`${n.windowDays} dias corridos da compra`)}
192  ${R}
193</table>
194${k}
195
196<h2>Eventos no período analisado</h2>
197<table>
198  ${x("Débitos registrados (inclui reservas)",String(n.grossConsumedCredits))}
199  ${x("Créditos devolvidos com vínculo",String(n.refundedCredits))}
200  ${x("Consumo líquido confirmado",String(n.netConsumedCredits))}
201  ${x("Créditos ainda reservados",String(n.heldCredits))}
202  ${x("Débitos sem confirmação suficiente",String(n.unverifiedCredits))}
203  ${x("Devoluções sem vínculo comprovado",String(n.unlinkedRefundCredits))}
204  ${x("Operações de consumo",String(n.consumptionCount))}
205  ${x("Gerações produzidas",`${n.generationsTotal} (${g})`)}
206  ${x("Primeiro consumo",da(n.firstConsumptionAt))}
207  ${x("Primeira geração",da(n.firstGenerationAt))}
208  ${x("Horas até o 1º uso após a compra",n.hoursToFirstUsage===null?"—":`${n.hoursToFirstUsage} h`)}
209  ${x(`Consumo nos ${n.windowDays} dias`,`${n.within7dConsumptionCount} operação(ões) · ${n.within7dConsumedCredits} créditos`)}
210  ${x(`Gerações nos ${n.windowDays} dias`,String(n.within7dGenerationCount))}
211</table>
212${_}
213
214<h2>Registros auditáveis</h2>
215<p class="sub">Datas originais ISO; créditos devolvidos são estornos de saldo, não reembolsos de pagamento. Estados: confirmed = consumo confirmado; held = reserva; refunded = devolvido; unverified = revisão; return = devolução; excluded = não usado como consumo.</p>
216<table class="cyc"><thead><tr><th>
216ID</th><th>Data</th><th>Ação / task</th><th>Valor assinado</th><th>Estado</th><th>Confirmado / devolvido</th></tr></thead><tbody>${$||'<tr><td colspan="6">Nenhum registro no período.</td></tr>'}</tbody></table>
217
218<h2>${He(u.title)}</h2>
219<p class="sub">Texto vigente consultado ao gerar o relatório; não comprova aceite do usuário nem a versão contratada na compra. ${He(u.url||"")} ${He(u.version||"")}</p>
220<p class="sub">${He(u.intro)}</p>
221<ul>${w}</ul>
222
223<p class="foot">Fonte: token_usage e generations. Mídias podem ter sido eliminadas pela retenção de 10 dias; ausência de mídia não prova ausência de uso. O período demonstra atividade da conta após a compra, sem atribuição automática a um lote específico de créditos.</p>
224</body></html>`}const ti=new Set(["success","succeeded","completed","complete"]),tl=new Set(["unknown","no_task_id","submit_error"]);function Ka(s){const n=(s==null?void 0:s.refund_task_id)??(s==null?void 0:s.release_task_id)??(s==null?void 0:s.settle_task_id)??(s==null?void 0:s.task_id)??(s==null?void 0:s.taskId);return typeof n!="string"||!n.trim()||tl.has(n.trim())?null:n.trim()}function Ir(s){return s===!0||s==="true"}function Nt(s){return Ir(s==null?void 0:s.byok)||(s==null?void 0:s.use_credits)===!1||(s==null?void 0:s.useCredits)===!1||(s==null?void 0:s.source)==="admin_manual_upload"||(s==null?void 0:s.source)==="manual_upload"}function nl(s){var c,u;if(!s.media_url||Nt(s.metadata))return!1;try{if(!["https:","http:"].includes(new URL(s.media_url).protocol))return!1}catch{return!1}const n=((c=s.metadata)==null?void 0:c.status)??((u=s.metadata)==null?void 0:u.provider_terminal_status);return!n||typeof n=="string"&&ti.has(n.toLowerCase())}function Qr(s){return/^(admin_|grant_|bonus_|add_|purchase[d_]|credit_purchase|subscription_credit|manual_|adjustment|correction)/i.test(s)}function il(s,n,c,u=7,m={}){var fe;const _=new Set,k=Es(c),g=Es(m.generatedAt)??Date.now(),l=Es(m.requestedAt),h=Math.min(l??g,g),x=Number.isFinite(u)&&u>0,w=k!==null&&x?k+u*864e5:null;let v=!1;const R=X=>{_.add(X),v=!0};(k===null||k>h)&&R("Informe uma data de compra válida, anterior ao limite da análise."),x||R("Prazo comercial inválido; revisão necessária."),l===null&&R("Data do pedido de reembolso não informada; o prazo não pode ser concluído pela data de hoje."),l!==null&&l>g&&R("Data do pedido está no futuro em relação ao relatório."),m.complete!==!0&&R("Histórico incompleto ou completude não verificada; ausência de registros não prova ausência de consumo.");const $=X=>{const me=Es(X);return me!==null&&k!==null&&me>=k&&me<=h},V=X=>$(X)&&w!==null&&Es(X)<=w,C=new Set,ee=s.filter(X=>!Number.isFinite(X.tokens_used)||Es(X.created_at)===null?(R("Há registros com quantidade ou data inválida; foram excluídos dos totais."),!1):X.id&&C.has(X.id)?(R("Há IDs de auditoria duplicados;
224 cada registro foi considerado uma única vez."),!1):(X.id&&C.add(X.id),Es(X.created_at)<=h)).sort((X,me)=>Es(X.created_at)-Es(me.created_at)||(X.id||"").localeCompare(me.id||"")),Z=ee.filter(X=>X.tokens_used>0&&!Oa(X.action,X.tokens_used)&&!Qr(X.action)&&!Nt(X.metadata)),p=new Map,z=new Map;let Q=0;for(const X of ee.filter(me=>Oa(me.action,me.tokens_used)&&!Qr(me.action))){const me=X.metadata||{},_e=[me.deduction_id,me.usage_id,me.reservation_id,...Array.isArray(me.deduction_ids)?me.deduction_ids:[]].filter(We=>typeof We=="string"&&!!We),$e=Ka(me),Ve=Z.filter(We=>Es(We.created_at)<=Es(X.created_at)&&(!X.user_id||!We.user_id||X.user_id===We.user_id)&&(_e.length>0?!!We.id&&_e.includes(We.id):!!$e&&Ka(We.metadata)===$e));let Je=Math.abs(X.tokens_used),we=0;for(const We of Ve){const Ge=Math.min(Je,We.tokens_used-(p.get(We)||0));p.set(We,(p.get(We)||0)+Ge),$(We.created_at)&&(we+=Ge),Je-=Ge}z.set(X,we),Je>0&&$(X.created_at)&&(Q+=Je,R("Devoluções sem vínculo suficiente com débitos foram separadas, sem subtração global."))}const ae=n.filter(X=>{var _e,$e;const me=((_e=X.metadata)==null?void 0:_e.completed_at)??(($e=X.metadata)==null?void 0:$e.completedAt);return $(X.created_at)&&nl(X)&&!(typeof me=="string"&&(Es(me)??1/0)>h)}),Y=new Set(ae.flatMap(X=>{const me=Ka(X.metadata);return me?[me,me.split("#")[0]]:[]})),B=new Set;for(const X of Z){const me=(fe=X.metadata)==null?void 0:fe.settled_credits;if(typeof me!="number"||!Number.isFinite(me))continue;const _e=Ka(X.metadata),$e=_e?Z.filter(Je=>Ka(Je.metadata)===_e):[X];if($e.reduce((Je,we)=>Je+we.tokens_used-(p.get(we)||0),0)!==me)for(const Je of $e)B.add(Je)}const G=[];let q=0,E=0,P=0,K=0,J=0,W=0,N=0,ce=0,D=null,i=null;for(const X of ee.filter(me=>$(me.created_at))){const me=X.metadata||{},_e={id:X.id||null,action:X.action,createdAt:X.created_at,taskId:Ka(me),tokens:X.tokens_used,state:"excluded",confirmedCredits:0,returnedCredits:0};if(G.push(_e),Qr(X.action)||Nt(me)||X.tokens_used===0)continue;if(Oa(X.action,X.tokens_used)){_e.state="return",_e.returnedCredits=z.get(X)||0;continue}q+=X.tokens_used;const $e=p.get(X)||0;E+=$e,_e.returnedCredits=$e;const Ve=Math.max(0,X.tokens_used-$e),Je=me.credit_state==="refunded"||Ir(me.refunded),we=me.credit_state==="settled"||Ir(me.settled);[me.settled_at,me.refunded_at].some(Ge=>typeof Ge=="string"&&(Es(Ge)??0)>h)?(_e.state="unverified",J+=Ve,R("Há débitos com estado atualizado após o pedido; o estado histórico precisa ser conferido manualmente.")):Ve===0?_e.state="refunded":Je?(_e.state="unverified",J+=Ve,R("Há débitos marcados como estornados sem devolução integral vinculada no período; não foram tratados como consumo.")):B.has(X)?(_e.state="unverified",J+=Ve,R("Acertos e devoluções vinculadas divergem do custo final registrado; concilie a operação antes de usar como prova.")):!we&&(me.credit_state==="held"||Ir(me.hold))?(_e.state="held",K+=Ve,R("Reservas pendentes não comprovam entrega nem consumo final de créditos.")):me.provider_terminal_status&&!ti.has(String(me.provider_terminal_status).toLowerCase())?(_e.state="unverified",J+=Ve,R("Há débitos sem sucesso terminal confirmado; verifique falhas e devoluções antes de decidir.")):we||_e.taskId&&Y.has(_e.taskId)?(_e.state="confirmed",_e.confirmedCredits=Ve,P+=Ve,W++,D=Ht(D,X.created_at),i=X.created_at,V(X.created_at)&&(N++,ce+=Ve)):(_e.state="unverified",J+=Ve,R("Débitos legados sem acerto ou geração vinculada exigem revisão; não comprovam consumo final por si só."))}const A={};let O=null,te=0;for(const X of ae){const me=X.media_type||"desconhecido";A[me]=(A[me]??0)+1,O=Ht(O,X.created_at),V(X.created_at)&&te++}_.add("Atividade no período não vincula automaticamente o consumo a uma compra ou lote de créditos específico."),_.add("Gerações sujeitas à retenção de 10 dias: ausência de mídia não prova ausência de uso.");const T=P>0,re=v?"review":l!==null&&w!==null&&l>w?"outside_window":T?"consumed":"eligible",ke={review:"Revisão necessária: os dados disponíveis não permitem concluir a elegibilidade ao reembolso comercial.",consumed:"Há consumo confirmado no período. A política comercial prevê ausência de consumo; confira o vínculo com a compra e os direitos legais antes de decidir.",outside_window:"O pedido informado ocorreu após a janela comercial. Direitos legais, cobranças indevidas e falhas do serviço exigem análise própria.",eligible:"Pedido dentro da janela comercial e nenhum consumo confirmado no histórico completo informado. Elegibilidade indicativa, sujeita à conferência do caso."};return{purchaseDate:k===null?null:new Date(k).toISOString(),windowDays:u,grossConsumedCredits:q,refundedCredits:E,netConsumedCredits:P,consumptionCount:W,firstConsumptionAt:D,lastConsumptionAt:i,within7dConsumptionCount:N,within7dConsumedCredits:ce,generationsTotal:ae.length,generationsByType:A,firstGenerationAt:O,within7dGenerationCount:te,hoursToFirstUsage:k!==null&&D?Math.round((Es(D)-k)/36e4)/10:null,consumed:T,refundEligibleByPolicy:re==="eligible",policyStatus:re,policySummary:ke[re],cutoffAt:new Date(h).toISOString(),requestedAt:l===null?null:new Date(l).toISOString(),heldCredits:K,unverifiedCredits:J,unlinkedRefundCredits:Q,warnings:[..._],auditRows:G,generationIds:ae.map(X=>X.id).filter(X=>!!X)}}const br=s=>
224new Date(s).toLocaleString("pt-BR",{timeZone:"America/Sao_Paulo"}),Zr=(s,n)=>{const c=new Intl.NumberFormat("pt-BR",{style:"currency",currency:n}),u=c.resolvedOptions().maximumFractionDigits;return c.format(s/10**u)},ol=s=>{try{const n=new URL(s||"");return n.protocol==="https:"&&n.hostname==="cdn.aiclubstudio.com"?n.href:null}catch{return null}};function ll({userId:s,email:n,nickname:c}){const{t:u}=kt(),[m,_]=r.useState(null),[k,g]=r.useState(""),[l,h]=r.useState(0),[x,w]=r.useState(""),[v,R]=r.useState(""),[$,V]=r.useState(!1),[C,ee]=r.useState(!1);r.useEffect(()=>{let G=!0;return _(null),g(""),w(""),R(""),F.functions.invoke("admin-dispute-evidence",{body:{userId:s}}).then(({data:q,error:E})=>{var K,J;if(!G)return;if(E||q!=null&&q.error||((K=q==null?void 0:q.billing)==null?void 0:K.user_id)!==s||!Array.isArray(q==null?void 0:q.usage)||!Array.isArray(q==null?void 0:q.generations)||!Array.isArray(q==null?void 0:q.purchases)||!Array.isArray(q==null?void 0:q.cycles)||!Array.isArray(q==null?void 0:q.warnings)||!Number.isFinite(Date.parse(q==null?void 0:q.generatedAt))){g("Não foi possível carregar a prova. Confira se a função de evidências está publicada e tente novamente.");return}const P=[...q.purchases].sort((W,N)=>Date.parse(N.paidAt)-Date.parse(W.paidAt));_({...q,purchases:P}),w(((J=P[0])==null?void 0:J.id)||"")}).catch(()=>{G&&g("Falha de conexão ao carregar a prova. Tente novamente.")}),()=>{G=!1}},[s,l]);const Z=m==null?void 0:m.purchases.find(G=>G.id===x),p=v?Date.parse(v):null,z=!v||Number.isFinite(p)&&!!Z&&!!m&&p>=Date.parse(Z.paidAt)&&p<=Date.parse(m.generatedAt),Q=r.useMemo(()=>m?il(m.usage,m.generations,(Z==null?void 0:Z.paidAt)??null,7,{requestedAt:v&&Number.isFinite(p)?new Date(p).toISOString():null,generatedAt:m.generatedAt,complete:m.complete===!0}):null,[m,Z,v,p]),ae=()=>{if(!m||!Q)return null;const G=m.billing,q=new Set(Q.generationIds);return{evidence:{...Q,warnings:[...new Set([...m.warnings,...Q.warnings])]},account:{userId:s,email:n,nickname:c,stripeCustomerId:G.stripe_customer_id,stripeSubscriptionId:G.stripe_subscription_id,plan:G.subscription_plan||G.plan_slug,status:G.subscription_status,interval:G.subscription_interval,subscriptionStartedAt:G.subscription_started_at,subscriptionRenewsAt:G.subscription_renews_at,premiumCredits:G.premium_credits,purchasedCredits:G.purchased_credits},payment:Z,terms:{title:u("legal.terms.s6Title",{lng:"pt"}),intro:u("legal.terms.s6Intro",{lng:"pt"}),url:"https://aiclubstudio.com/terms",version:u("legal.termsLastUpdated",{lng:"pt"}),items:[`${u("legal.terms.s6Item1Strong",{lng:"pt"})} ${u("legal.terms.s6Item1",{lng:"pt"})}`,`${u("legal.terms.s6Item2Pre",{lng:"pt"})}${u("legal.terms.s6Item2Strong",{lng:"pt"})}${u("legal.terms.s6Item2Post",{lng:"pt"})}`,u("legal.terms.s6Item3",{lng:"pt"}),u("legal.terms.s6Item4",{lng:"pt"}),`${u("legal.terms.s6Item5Pre",{lng:"pt"})}${u("legal.contactEmail",{lng:"pt"})}${u("legal.terms.s6Item5Post",{lng:"pt"})}`]},cycles:m.cycles,generatedAt:m.generatedAt,generationsSample:$?m.generations.filter(E=>q.has(E.id)).slice(0,12).map(E=>({thumbUrl:ol(E.thumbnail_url||(E.media_type==="image"?E.media_url:null)),mediaType:E.media_type,model:E.model,createdAt:E.created_at})):[]}},Y=async()=>{const G=ae();if(!G||!Z||!z)return;const q=window.open("","_blank","width=960,height=1000");if(!q){o.error("Permita pop-ups para imprimir a prova.");return}ee(!0);try{if(q.opener=null,q.document.write(rl(G)),q.document.close(),await Promise.race([Promise.all(Array.from(q.document.images).map(E=>E.decode().catch(()=>{}))),new Promise(E=>setTimeout(E,6e3))]),q.closed)return;Array.from(q.document.images).some(E=>!E.complete||!E.naturalWidth)&&o.warning("Algumas miniaturas não carregaram. Os registros de uso permanecem no relatório."),q.focus(),q.print()}catch{o.error("Não foi possível imprimir. Baixe os dados ou tente novamente.")}finally{ee(!1)}},B=()=>{const G=ae();if(!G||!Z||!z)return;const q=URL.createObjectURL(new Blob([JSON.stringify(G,null,2)],{type:"application/json"})),E=document.createElement("a");E.href=q,E.download=`evidencias-${s}-${Z.id}.json`,E.click(),setTimeout(()=>URL.revokeObjectURL(q),1e3)};return e.jsxs("section",{"aria-label":"Prova de uso para chargeback",className:"mb-4 space-y-4 rounded-xl border border-border bg-card/50 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-display text-base font-semibold",children:"Prova de uso / Chargeback"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Última cobrança, consumo de créditos e cláusula dos 7 dias, prontos para contestar disputa."})]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>h(G=>G+1),disabled:!m&&!k,children:[e.jsx(Qe,{className:"mr-2 h-4 w-4"}),"Atualizar prova"]})]}),k?e.jsx("div",{role:"alert",className:"text-sm text-destructive",children:k}):!m||!Q?e.jsxs("p",{role:"status",className:"flex items-center gap-2 text-sm",children:[e.jsx(he,{className:"h-4 w-4 animate-spin"}),"Carregando compras e registros de uso…"]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-sm",children:["Última cobrança paga localizada: ",e.jsx("strong",{children:m.purchases[0]?`${br(m.purchases[0].paidAt)} (Brasília) · ${Zr(m.purchases[0].amount,m.purchases[0].currency)}`:"não localizada"})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("label",{className:"space-y-1 text-xs",children:["Compra contestada",e.jsxs("select",{"aria-label":"Compra contestada",value:x,onChange:G=>w(G.target.value),className:"h-10 w-full min-w-0 rounded-md border border-input bg-background px-3 text-sm focus-visible:ring-2 focus-visible:ring-ring",children:[!m.purchases.length&&e.jsx("option",{value:"",children:"Nenhuma compra confirmada disponível"}),m.purchases.map(G=>e.jsxs("option",{value:G.id,children:[br(G.paidAt)," · ",Zr(G.amount,G.currency)," · ",G.id]},G.id))]})]}),e.jsxs("label",{htmlFor:"dispute-requested-at",className:"space-y-1 text-xs",children:["Data/hora do pedido de reembolso (opcional, horário deste computador)",e.jsx(je,{id:"dispute-requested-at",type:"datetime-local",value:v,onCh
224ange:G=>R(G.target.value),"aria-invalid":!z})]})]}),!z&&e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:"Informe um pedido entre a cobrança selecionada e a coleta dos dados."}),Z&&e.jsxs("p",{className:"break-all text-xs text-muted-foreground",children:["Cobrança: ",Z.id," · Fatura: ",Z.invoiceId||"não vinculada"," · Payment Intent: ",Z.paymentIntentId||"não informado",Z.refundedAmount>0&&` · Já reembolsado na Stripe: ${Zr(Z.refundedAmount,Z.currency)}`]}),e.jsx("div",{role:"status",className:"rounded-lg border border-border bg-secondary/40 p-3 text-sm",children:Q.policySummary}),e.jsxs("dl",{className:"grid grid-cols-2 gap-3 text-sm lg:grid-cols-4",children:[e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Consumo confirmado"}),e.jsxs("dd",{className:"font-semibold",children:[Q.netConsumedCredits," cr"]})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Reservas pendentes"}),e.jsxs("dd",{className:"font-semibold",children:[Q.heldCredits," cr"]})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Créditos sem confirmação"}),e.jsxs("dd",{className:"font-semibold",children:[Q.unverifiedCredits," cr"]})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-xs text-muted-foreground",children:"Mídias concluídas no período"}),e.jsx("dd",{className:"font-semibold",children:Q.generationsTotal})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Período: ",Z?br(Z.paidAt):"compra não selecionada"," até ",br(Q.cutoffAt)," (Brasília). Sem data do pedido, o relatório usa a data de coleta e não decide elegibilidade."]}),[...new Set([...m.warnings,...Q.warnings])].map(G=>e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:G},G)),e.jsxs("div",{className:"rounded-lg border border-border bg-background/80 p-3 text-xs",children:[e.jsx("p",{className:"font-semibold",children:"Política comercial (Termos §6)"}),e.jsxs("ul",{className:"mt-1 list-disc space-y-1 pl-4 text-muted-foreground",children:[e.jsx("li",{children:"Reembolso comercial só em até 7 dias da compra e se nenhum crédito foi consumido."}),e.jsx("li",{children:"Havendo consumo — mesmo dentro dos 7 dias — não há reembolso do valor já usado; há custo de provedor."}),e.jsx("li",{children:"Cancelar a renovação continua disponível e impede cobranças futuras."})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"A política comercial não limita direitos obrigatórios por lei. Os termos atuais não comprovam aceite na compra; esta tela não envia defesa nem reembolso."}),e.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[e.jsx("input",{type:"checkbox",checked:$,onChange:G=>V(G.target.checked)}),"Incluir até 12 miniaturas no relatório"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(y,{onClick:()=>void Y(),disabled:!Z||!z||C,children:[e.jsx(qo,{className:"mr-2 h-4 w-4"}),C?"Preparando impressão…":"Gerar PDF / Imprimir"]}),e.jsxs(y,{variant:"outline",onClick:B,disabled:!Z||!z,children:[e.jsx(na,{className:"mr-2 h-4 w-4"}),"Baixar evidências JSON"]})]})]})]})}const et={generate_image:"Gerar Imagem",generate_video:"Gerar Vídeo",upscale_image:"Upscale",generate_faceswap:"Model Swap",analyze_image_grade:"Editor — auto-grade",generate_captions:"Legendas",generate_photoshoot:"PhotoShoot",generate_constructor:"Constructor",describe_image:"Descrever Imagem",train_lora:"Treinar Personagem",caption_generation:"Caption"},dl=s=>{const n=s.startsWith("refund_"),c=s.replace("refund_","");let u=null;return c.startsWith("seedance_")?u=`Seedance 2.0 (${c.replace("seedance_","").replace(/_/g," ")})`:c.startsWith("kling_motion_")?u=`Kling Motion (${c.replace("kling_motion_","").replace(/_/g," ")})`:c.startsWith("wan27_")?u=`WAN 2.7 (${c.replace("wan27_","").replace(/_/g," ")})`:c.startsWith("wan30_")?u=`WAN 3.0 (${c.replace("wan30_","").replace(/_/g," ")})`:c.startsWith("happyhorse")?u=`HappyHorse 1.0 (${c.replace("happyhorse_","").replace(/_/g," ")})`:c==="kling_motion"?u="Kling Motion":c==="wan27_video"?u="WAN 2.7":c==="wan30_video"?u="WAN 3.0":c==="seedance_kie"?u="Seedance 2.0":c==="admin_correction_duplicate_refunds"&&(u="⚙️ Correção Admin"),u?n?`↩ ${u}`:u:null},cl=s=>s===Ei?"Liberação de reserva":null,Jt=s=>{const n=cl(s);if(n)return n;const c=dl(s);if(c)return c;if(s.startsWith("refund_")){const u=s.replace("refund_","");return`↩ ${et[u]||u}`}if(s.startsWith("settle_extra_")){const u=s.replace("settle_extra_","");return`↑ ${et[u]||u}`}return et[s]||s},Xt=s=>new Date(s).toLocaleDateString("pt-BR",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}),ml=s=>s&&(s.before_sub!==void 0||s.before_purchased!==void 0),ul=(s,n)=>!!(s&&(n?s.refunded_to_sub||s.refunded_to_purchased||s.released_to_
224sub||s.released_to_purchased:s.from_sub||s.from_purchased)),xl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,hl=new Set(["unknown","no_task_id"]),st=s=>{const n=(s==null?void 0:s.taskId)??(s==null?void 0:s.task_id);if(!n)return null;let c=String(n).trim();return c.endsWith("_upscale")&&(c=c.slice(0,-8)),!c||hl.has(c)||c.startsWith("ps_batch_")||c.startsWith("ps_err_")?null:c},pl=()=>{const[s,n]=r.useState([]),[c,u]=r.useState(!1),[m,_]=r.useState(""),[k,g]=r.useState(null),[l,h]=r.useState("all"),[x,w]=r.useState({}),[v,R]=r.useState({}),[$,V]=r.useState(null),[C,ee]=r.useState(null),Z=r.useRef(0),p=fr(),{startImpersonation:z}=bn(),Q="id, media_type, media_url, metadata",ae=async i=>{const A=st(i.metadata);if(!A||!i.user_id)return null;const O=A.split(",")[0].trim(),{data:te}=await F.from("generations").select(Q).eq("user_id",i.user_id).filter("metadata->>taskId","in",`("${A}","${O}")`).order("created_at",{ascending:!0}).limit(1);if(te!=null&&te[0])return te[0];const{data:T}=await F.from("generations").select(Q).eq("user_id",i.user_id).filter("metadata->>taskId","like",`${O}#%`).order("created_at",{ascending:!0}).limit(1);return(T==null?void 0:T[0])||null},Y=i=>{const A=i.media_url||"",O=i.metadata||{};return A.startsWith("error://")?{viewable:!1,note:`Geração FALHOU no provider: ${O.errorMessage||O.error||A.slice(8)||"sem detalhe"}`}:A.startsWith("processing://")?{viewable:!1,note:"Geração ainda em processamento — sem mídia pra abrir"}:i.media_type==="audio"?{viewable:!1,note:"Geração de áudio — visível só no Playground Áudio da conta do usuário"}:{viewable:!0}},B=i=>{const A=window.open("","_blank");ee(`${i.id}:admin`),(async()=>{try{const O=await ae(i);if(!O){A==null||A.close(),o.error("Geração não encontrada pra esse TaskID (limpa pelo cron ou fluxo sem vínculo)");return}const te=Y(O);if(!te.viewable){A==null||A.close(),o.info(te.note);return}const T=`/my-assets/${O.id}`;A?A.location.href=T:window.open(T,"_blank")}finally{ee(null)}})()},G=async i=>{if(i.user_id){ee(`${i.id}:user`);try{const A=!!st(i.metadata),O=await ae(i),te=i.nickname||i.email||i.user_id.slice(0,8);if(!await z(i.user_id,te))return;if(o.success(`Logado como: ${te}`),O){const re=Y(O);re.viewable?p(`/my-assets/${O.id}`):(re.note&&o.info(re.note),p(O.media_type==="audio"?"/playground/audio":"/my-assets"))}else A&&o.warning("Geração não encontrada pra esse TaskID — abrindo Meus Assets do usuário"),p("/my-assets")}finally{ee(null)}}},q=async()=>{var T;const[i,A]=await Promise.all([F.from("profiles").select("user_id, nickname"),F.functions.invoke("admin-list-emails")]),O={};(i.data||[]).forEach(re=>{O[re.user_id]=re.nickname||""});const te=((T=A.data)==null?void 0:T.emailMap)||{};return w(O),R(te),{pMap:O,eMap:te}},E=(i,A,O)=>i.map(te=>({...te,nickname:te.user_id&&A[te.user_id]||"",email:te.user_id&&O[te.user_id]||""})),P=async()=>{const i=++Z.current;u(!0),V(null),n([]);try{const{pMap:A,eMap:O}=await q(),{data:te,error:T}=await F.from("token_usage").select("*").not("metadata","is",null).order("created_at",{ascending:!1}).limit(200);if(T)throw T;if(i!==Z.current)return;n(E(te||[],A,O))}catch{i===Z.current&&o.error("Não foi possível carregar a auditoria. Tente atualizar.")}finally{i===Z.current&&u(!1)}},K=async i=>{const A=++Z.current;u(!0),V(i),n([]);try{let O=x,te=v;if(Object.keys(O).length===0){const re=await q();O=re.pMap,te=re.eMap}const T=await F.from("token_usage").select("*").eq("user_id",i).order("created_at",{ascending:!1}).limit(1e3);if(T.error)throw T.error;if(A!==Z.current)return;n(E(T.data||[],O,te))}catch{A===Z.current&&o.error("Não foi possível carregar os registros deste usuário. Tente atualizar.")}finally{A===Z.current&&u(!1)}},J=async()=>{const i=m.trim();if(!i)return;if(xl.test(i)){await K(i);return}let A=x,O=v;if(Object.keys(O).length===0){const fe=await q();A=fe.pMap,O=fe.eMap}const te=i.toLowerCase(),T=Object.entries(O).find(([,fe])=>fe.toLowerCase()===te);if(T){await K(T[0]);return}const re=Object.entries(A).find(([,fe])=>fe.toLowerCase()===te);if(re){await K(re[0]);return}const ke=Object.entries(O).find(([,fe])=>fe.toLowerCase().includes(te));if(ke){await K(ke[0]);return}o.error(`Usuário não encontrado: "${i}"`)},W=()=>{V(null),_(""),P()};r.useEffect(()=>{P()},[]);const N=s.filter(i=>{const A=Oa(i.action,i.tokens_used);if(l==="deductions"&&A||l==="refunds"&&!A)return!1;if(!m)return!0;const O=m.toLowerCase();return(i.nickname||"").toLowerCase().includes(O)||(i.email||"").toLowerCase().includes(O)||i.action.toLowerCase().includes(O)||(i.user_id||"").toLowerCase().includes(O)}),ce=$&&v[$]||"",D=$&&x[$]||"";return e.jsxs("div",{className:"glass rounded-xl p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 gap-4 flex-wrap",children:[e.jsx("h2",{className:"font-display font-semibold text-lg",children:"Auditoria de Créditos"}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("div",{className:"flex gap-1",children:["all","deductions","refunds"].map(i=>e.jsx(y,{size:"sm",variant:l===i?"default":"outline",onClick:()=>h(i),className:"text-xs",children:i==="all"?"Todos":i==="deductions"?"Deduções":"Reembolsos"},i))}),e.jsxs("div",{className:"relative w-56",children:[e.jsx(aa,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(je,{value:m,onChange:i=>_(i.target.value),onKeyDown:i=>{i.key==="Enter"&&J()},placeholder:"Email, nick ou UUID — Enter pra histórico",className:"pl-9 h-8 text-xs"})]}),e.jsxs(y,{size:"sm",variant:"default",onClick:J,disabled:c||!m.trim(),className:"text-xs gap-1",title:"Carrega os 1000 registros mais recentes; a prova de chargeback consulta o histórico separadamente",children:[e.jsx(di,{className:"w-3.5 h-3.5"})," Histórico do usuário"]}),e.jsx(y,{size:"sm",variant:"outline",onClick:$?()=>
224K($):P,disabled:c,children:e.jsx(Qe,{className:`w-4 h-4 ${c?"animate-spin":""}`})})]})]}),$&&e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2 px-3 py-2 rounded-md border border-primary/30 bg-primary/10",children:[e.jsxs("div",{className:"text-xs",children:["Mostrando ",e.jsx("span",{className:"font-semibold",children:"até 1000 registros recentes"})," de"," ",e.jsx("span",{className:"font-mono",children:ce||D||$})," ","— ",e.jsxs("span",{className:"text-muted-foreground",children:[s.length," registro(s)"]})]}),e.jsxs(y,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs gap-1",onClick:W,children:[e.jsx(Ga,{className:"w-3.5 h-3.5"})," Voltar aos recentes"]})]}),$&&e.jsx(ll,{userId:$,email:ce,nickname:D},$),c?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-auto max-h-[70vh]",children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{className:"text-xs",children:"Data"}),e.jsx(f,{className:"text-xs",children:"Usuário"}),e.jsx(f,{className:"text-xs",children:"Ação"}),e.jsx(f,{className:"text-xs text-center",children:"Créditos"}),e.jsx(f,{className:"text-xs text-center",children:"Antes (Sub/Avulso)"}),e.jsx(f,{className:"text-xs text-center",children:"Depois (Sub/Avulso)"}),e.jsx(f,{className:"text-xs text-center",children:"Pool"}),e.jsx(f,{className:"text-xs",children:"TaskID"}),e.jsx(f,{className:"text-xs w-24"})]})}),e.jsx(De,{children:N.length===0?e.jsx(b,{children:e.jsx(a,{colSpan:9,className:"text-center text-xs text-muted-foreground py-8",children:"Nenhum registro encontrado"})}):N.map(i=>{const A=Oa(i.action,i.tokens_used),O=i.metadata,te=ml(O),T=ul(O,A),re=st(O);return e.jsxs(b,{className:"text-xs",children:[e.jsx(a,{className:"text-[11px] text-muted-foreground whitespace-nowrap",children:Xt(i.created_at)}),e.jsx(a,{children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium truncate max-w-[120px]",children:i.nickname||"—"}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-[120px]",children:i.email||""})]})}),e.jsx(a,{children:e.jsx("span",{className:A?"text-green-600":"",children:Jt(i.action)})}),e.jsx(a,{className:"text-center",children:e.jsxs("span",{className:`font-semibold ${A?"text-green-600":"text-red-500"}`,children:[A?"+":"−",Math.abs(i.tokens_used)]})}),e.jsx(a,{className:"text-center",children:te?e.jsxs("span",{className:"font-mono text-[11px]",children:[O.before_sub??"?"," / ",O.before_purchased??"?"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(a,{className:"text-center",children:te?e.jsxs("span",{className:"font-mono text-[11px]",children:[O.after_sub??"?"," / ",O.after_purchased??"?"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(a,{className:"text-center",children:T?e.jsxs("div",{className:"flex gap-1 justify-center",children:[(A?O.refunded_to_sub||O.released_to_sub||0:O.from_sub||0)>0&&e.jsx(Re,{variant:"outline",className:"text-[10px] px-1",children:"Sub"}),(A?O.refunded_to_purchased||O.released_to_purchased||0:O.from_purchased||0)>0&&e.jsx(Re,{variant:"secondary",className:"text-[10px] px-1",children:"Avulso"})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(a,{className:"font-mono text-[10px]",children:re?e.jsxs("button",{onClick:()=>{navigator.clipboard.writeText(re),o.success("TaskId copiado")},className:"flex items-center gap-1 text-muted-foreground hover:text-foreground transition-colors max-w-[140px] truncate",title:re,children:[e.jsx("span",{className:"truncate",children:re}),e.jsx(An,{className:"w-3 h-3 shrink-0"})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(a,{children:e.jsxs("div",{className:"flex items-center gap-0.5",children:[O&&e.jsx(y,{size:"icon",variant:"ghost",className:"h-6 w-6",title:"Detalhes da operação",onClick:()=>g(i),children:e.jsx(ia,{className:"w-3.5 h-3.5"})}),re&&i.user_id&&e.jsx(y,{size:"icon",variant:"ghost",className:"h-6 w-6",title:"Abrir geração (como admin, nova aba)",disabled:C===`${i.id}:admin`,onClick:()=>B(i),children:C===`${i.id}:admin`?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(oa,{className:"w-3.5 h-3.5"})}),i.user_id&&e.jsx(y,{size:"icon",variant:"ghost",className:"h-6 w-6",title:re?"Ver na conta do usuário (logar como ele e abrir a geração)":"Logar como o usuário (abre Meus Assets dele)",disabled:C===`${i.id}:user`,onClick:()=>G(i),children:C===`${i.id}:user`?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(En,{className:"w-3.5 h-3.5"})})]})})]},i.id)})})]})}),e.jsx(ds,{open:!!k,onOpenChange:i=>!i&&g(null),children:e.jsxs(cs,{className:"max-w-lg",children:[e.jsx(ms,{children:e.jsx(us,{className:"text-sm",children:"Detalhes da Operação"})}),k&&e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Usuário"}),e.jsx("p",{className:"font-medium",children:k.nickname||"—"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:k.email})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Ação"}),e.jsx("p",{className:"font-medium",children:Jt(k.action)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Data"}),e.jsx("p",{children:Xt(k.created_at)})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Créditos"}),e.jsxs("p",{className:`font-bold ${Oa(k.action,k.tokens_used)?"text-green-600":"text-red-500"}`,children:[Oa(k.action,k.tokens_used)?"+":"−",Math.abs(k.tokens_used)]})]})]}),k.metadata&&e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-3 space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold text-muted-foreground",children:"Metadados de Auditoria"}),e.jsx("pre",{className:"text-[11px] font-mono whitespace-pre-wrap break-all bg-background/50 rounded p-2",children:JSON.stringify(k.metadata,null,2)})]})]})]})})]})};function Qt(s){return s.startsWith("processing://")?"processing":s.startsWith("error://")?"error":"completed"}const at=36;function gl(s){return s&&typeof s=="object"&&!Array.isArray(s)?s:{}}function Nr(s){return s==="completed"?"Concluída":s==="processing"?"Processando":"Falhou"}function rt(s){const n=gl(s.metadata),u=[n.appName,n.source,n.origin,n.feature,n.backend].find(m=>typeof m=="string"&&m.trim());return typeof u=="string"?u:"Sem origem informada"}function tt(s,n){return(s==null?void 0:s.email)||(s==null?void 0:s.nickname)||(s==null?void 0:s.username)||n}const jl=()=>{const{isAdmin:s}=Va(),[n,c]=r.useState([]),[u,m]=r.useState({}),[_,k]=r.useState(!0),[g,l]=r.useState(null),[h,x]=r.useState(0),[w,v]=r.useState(0),[R,$]=r.useState("all"),[V,C]=r.useState("all"),[ee,Z]=r.useState("24h"),[p,z]=r.useState(""),[Q,ae]=r.useState(""),[Y,B]=r.useState(""),[G,q]=r.useState({user:"",prompt:"",model:""});r.useEffect(()=>{const N=window.setTimeout(()=>q({user:p,prompt:Q,model:Y}),350);return()=>window.clearTimeout(N)},[Y,Q,p]);const E=r.useMemo(()=>{const N=G.user.trim().toLowerCase();return N?Object.entries(u).filter(([ce,D])=>[ce,D.email,D.nickname,D.username].some(i=>i==null?void 0:i.toLowerCase().includes(N))).map(([ce])=>ce):null},[G.user,u]),P=r.useCallback(async()=>{var A;if(!s)return;const[N,ce]=await Promise.all([F.from("profiles").select("user_id, nickname, username"),F.functions.invoke("admin-list-emails")]);if(N.error)throw N.error;if(ce.error)throw ce.error;const D=((A=ce.data)==null?void 0:A.emailMap)??{},i={};for(const O of N.data??[])i[O.user_id]={nickname:O.nickname,username:O.username,email:D[O.user_id]??null};for(const[O,te]of Object.entries(D))i[O]??(i[O]={nickname:null,username:null,email:te});m(i)},[s]),K=r.useCallback(async()=>
224{if(s){if((E==null?void 0:E.length)===0){c([]),v(0),k(!1);return}k(!0);try{let N=F.from("generations").select("*",{count:"exact"});if(R!=="all"&&(N=N.eq("media_type",R)),V==="processing"&&(N=N.like("media_url","processing://%")),V==="error"&&(N=N.like("media_url","error://%")),V==="completed"&&(N=N.not("media_url","like","processing://%").not("media_url","like","error://%")),ee!=="all"){const O=ee==="24h"?24:ee==="7d"?168:720;N=N.gte("created_at",new Date(Date.now()-O*60*60*1e3).toISOString())}E&&(N=N.in("user_id",E)),G.prompt.trim()&&(N=N.ilike("prompt",`%${G.prompt.trim()}%`)),G.model.trim()&&(N=N.ilike("model",`%${G.model.trim()}%`));const ce=h*at,{data:D,error:i,count:A}=await N.order("created_at",{ascending:!1}).range(ce,ce+at-1);if(i)throw i;c(D??[]),v(A??0)}catch(N){console.error("Failed to load generation audit",N),o.error("Não foi possível carregar a auditoria de gerações.")}finally{k(!1)}}},[G.model,G.prompt,s,E,R,h,ee,V]);if(r.useEffect(()=>{P().catch(N=>{console.error("Failed to load audit identities",N),o.error("Não foi possível carregar os dados dos usuários.")})},[P]),r.useEffect(()=>{K()},[K]),r.useEffect(()=>{x(0)},[G,R,ee,V]),!s)return null;const J=Math.max(1,Math.ceil(w/at)),W=g?Qt(g.media_url):null;return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("header",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-display text-2xl font-bold",children:"Auditoria de gerações"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm text-muted-foreground",children:"Visão administrativa opcional de mídias persistidas por todos os módulos. Os históricos nos geradores continuam mostrando somente a conta autenticada."})]}),e.jsxs(y,{variant:"outline",onClick:()=>void K(),disabled:_,className:"gap-2",children:[_?e.jsx(he,{className:"h-4 w-4 animate-spin"}):e.jsx(Qe,{className:"h-4 w-4"}),"Atualizar"]})]}),e.jsx("section",{"aria-label":"Filtros da auditoria",className:"rounded-xl border border-border/40 bg-card/50 p-4",children:e.jsxs("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-5",children:[e.jsxs("div",{className:"space-y-1.5 xl:col-span-2",children:[e.jsx(oe,{htmlFor:"audit-user",children:"Usuário"}),e.jsxs("div",{className:"relative",children:[e.jsx(aa,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(je,{id:"audit-user",value:p,onChange:N=>z(N.target.value),placeholder:"E-mail, nome ou ID",className:"pl-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{htmlFor:"audit-media",children:"Mídia"}),e.jsxs(as,{value:R,onValueChange:N=>$(N),children:[e.jsx(rs,{id:"audit-media",children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"all",children:"Todas"}),e.jsx(pe,{value:"image",children:"Imagens"}),e.jsx(pe,{value:"video",children:"Vídeos"}),e.jsx(pe,{value:"audio",children:"Áudios"}),e.jsx(pe,{value:"3d",children:"3D"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{htmlFor:"audit-state",children:"Estado"}),e.jsxs(as,{value:V,onValueChange:N=>C(N),children:[e.jsx(rs,{id:"audit-state",children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"all",children:"Todos"}),e.jsx(pe,{value:"completed",children:"Concluídas"}),e.jsx(pe,{value:"processing",children:"Processando"}),e.jsx(pe,{value:"error",children:"Falhas"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{htmlFor:"audit-period",children:"Período"}),e.jsxs(as,{value:ee,onValueChange:N=>Z(N),children:[e.jsx(rs,{id:"audit-period",children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"24h",children:"Últimas 24 horas"}),e.jsx(pe,{value:"7d",children:"Últimos 7 dias"}),e.jsx(pe,{value:"30d",children:"Últimos 30 dias"}),e.jsx(pe,{value:"all",children:"Todo o período"})]})]})]}),e.jsxs("div",{className:"space-y-1.5 xl:col-span-2",children:[e.jsx(oe,{htmlFor:"audit-prompt",children:"Prompt"}),e.jsx(je,{id:"audit-prompt",value:Q,onChange:N=>ae(N.target.value),placeholder:"Buscar no prompt"})]}),e.jsxs("div",{className:"space-y-1.5 xl:col-span-2",children:[e.jsx(oe,{htmlFor:"audit-model",children:"Modelo"}),e.jsx(je,{id:"audit-model",value:Y,onChange:N=>B(N.target.value),placeholder:"Buscar modelo ou engine"})]}),e.jsx("div",{className:"flex items-end",children:e.jsx(y,{variant:"ghost",className:"w-full",onClick:()=>{z(""),ae(""),B(""),$("all"),C("all"),Z("24h")},children:"Limpar filtros"})})]})}),e.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm text-muted-foreground",children:[e.jsxs("span",{children:[w.toLocaleStr
224ing("pt-BR")," gerações encontradas"]}),e.jsxs("span",{className:"tabular-nums",children:["Página ",h+1," de ",J]})]}),e.jsx("section",{"aria-busy":_,"aria-live":"polite","aria-label":"Gerações auditadas",className:"min-h-64",children:_?e.jsxs("div",{className:"flex min-h-64 items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(he,{className:"h-5 w-5 animate-spin"})," Carregando gerações…"]}):n.length===0?e.jsxs("div",{className:"flex min-h-64 flex-col items-center justify-center rounded-xl border border-dashed border-border/60 text-center text-muted-foreground",children:[e.jsx(aa,{className:"mb-3 h-8 w-8"}),e.jsx("p",{className:"font-medium text-foreground",children:"Nenhuma geração encontrada"}),e.jsx("p",{className:"text-sm",children:"Ajuste os filtros ou o período."})]}):e.jsx("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6",children:n.map(N=>{const ce=Qt(N.media_url),D=ce==="completed";return e.jsxs("button",{type:"button",onClick:()=>l(N),className:"group overflow-hidden rounded-xl border border-border/40 bg-card/50 text-left transition-colors hover:border-primary/60 hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsxs("div",{className:"relative aspect-square overflow-hidden bg-muted",children:[D&&N.media_type==="image"?e.jsx("img",{src:Za(N.thumbnail_url||N.media_url,480,80),onError:gt,alt:"Miniatura da geração auditada",loading:"lazy",width:480,height:480,className:"h-full w-full object-cover transition-transform group-hover:scale-[1.02]"}):null,D&&N.media_type==="3d"?e.jsx("div",{className:"flex h-full items-center justify-center text-primary",children:e.jsx(Bt,{className:"h-12 w-12","aria-label":"Modelo 3D"})}):null,D&&N.media_type==="video"?e.jsx("video",{src:`${N.media_url}#t=0.1`,preload:"metadata",muted:!0,playsInline:!0,"aria-label":"Miniatura de vídeo",className:"h-full w-full object-cover"}):null,!D||N.media_type==="audio"?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 px-3 text-center text-muted-foreground",children:[ce==="error"?e.jsx(Or,{className:"h-8 w-8 text-destructive"}):ce==="processing"?e.jsx(he,{className:"h-8 w-8 animate-spin"}):e.jsx(Fi,{className:"h-8 w-8"}),e.jsx("span",{className:"text-xs",children:ce==="completed"?"Áudio":Nr(ce)})]}):null,e.jsx(Re,{variant:ce==="error"?"destructive":"secondary",className:"absolute left-2 top-2 text-[10px]",children:Nr(ce)}),e.jsx("span",{className:"absolute bottom-2 right-2 rounded-md bg-background/85 p-1.5 text-foreground","aria-hidden":"true",children:e.jsx(ia,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"space-y-1.5 p-3",children:[e.jsx("p",{className:"truncate text-xs font-medium",title:tt(u[N.user_id],N.user_id),children:tt(u[N.user_id],N.user_id)}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",title:N.model||"Modelo não informado",children:N.model||"Modelo não informado"}),e.jsxs("div",{className:"flex items-center justify-between gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"truncate",title:rt(N),children:rt(N)}),e.jsx("time",{className:"shrink-0 tabular-nums",dateTime:N.created_at,children:new Date(N.created_at).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})})]})]})]},N.id)})})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsxs(y,{variant:"outline",size:"sm",disabled:h===0||_,onClick:()=>x(N=>Math.max(0,N-1)),children:[e.jsx(Ct,{className:"mr-1 h-4 w-4"}),"Anterior"]}),e.jsxs(y,{variant:"outline",size:"sm",disabled:h+1>=J||_,onClick:()=>x(N=>N+1),children:["Próxima",e.jsx(Sa,{className:"ml-1 h-4 w-4"})]})]}),e.jsx(ds,{open:!!g,onOpenChange:N=>{N||l(null)},children:e.jsx(cs,{className:"max-h-[90dvh] max-w-5xl overflow-y-auto",children:g?e.jsxs(e.Fragment,{children:[e.jsx(ms,{children:e.jsx(us,{children:"Detalhes da geração"})}),e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[minmax(0,1.35fr)_minmax(280px,0.65fr)]",children:[e.jsxs("div",{className:"flex min-h-72 items-center justify-center overflow-hidden rounded-xl bg-muted",children:[W==="completed"&&g.media_type==="image"?e.jsx("img",{src:g.media_url,alt:"Imagem completa da geração auditada",className:"max-h-[65dvh] w-full object-contain"}):null,W==="completed"&&g.media_type==="video"?e.jsx("video",{src:g.media_url,controls:!0,preload:"metadata",playsInl
224ine:!0,className:"max-h-[65dvh] w-full"}):null,W==="completed"&&g.media_type==="3d"?e.jsxs("div",{className:"p-8 text-center",children:[e.jsx(Bt,{className:"mx-auto mb-3 h-12 w-12 text-primary"}),e.jsx("p",{children:"Modelo 3D — formatos disponíveis nos metadados e no download original."})]}):null,W==="completed"&&g.media_type==="audio"?e.jsx("audio",{src:g.media_url,controls:!0,preload:"metadata",className:"w-[90%]"}):null,W!=="completed"?e.jsxs("div",{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Or,{className:Ue("mx-auto mb-3 h-9 w-9",W==="error"&&"text-destructive")}),e.jsx("p",{children:W?Nr(W):"Estado desconhecido"})]}):null]}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Usuário"}),e.jsx("p",{className:"break-all font-medium",children:tt(u[g.user_id],g.user_id)}),e.jsx("p",{className:"break-all text-xs text-muted-foreground",children:g.user_id})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tipo"}),e.jsx("p",{children:g.media_type})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Estado"}),e.jsx("p",{children:W?Nr(W):"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Modelo"}),e.jsx("p",{className:"break-words",children:g.model||"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Origem"}),e.jsx("p",{className:"break-words",children:rt(g)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Criada em"}),e.jsx("time",{dateTime:g.created_at,children:new Date(g.created_at).toLocaleString("pt-BR")})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Prompt"}),e.jsx("p",{className:"mt-1 max-h-44 overflow-y-auto whitespace-pre-wrap rounded-lg border border-border/40 bg-background/40 p-3 selection:bg-primary/30",children:g.prompt||"Sem prompt registrado"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"ID da geração"}),e.jsx("p",{className:"break-all font-mono text-xs",children:g.id})]}),W==="completed"?e.jsx(y,{asChild:!0,variant:"outline",className:"w-full gap-2",children:e.jsxs("a",{href:g.media_url,target:"_blank",rel:"noreferrer",children:[e.jsx(oa,{className:"h-4 w-4"}),"Abrir mídia original"]})}):null]})]}),e.jsxs("details",{className:"rounded-lg border border-border/40 p-3",children:[e.jsx("summary",{className:"cursor-pointer font-medium",children:"Metadados técnicos"}),e.jsx("pre",{className:"mt-3 max-h-72 overflow-auto whitespace-pre-wrap break-all rounded-md bg-muted p-3 text-xs",children:JSON.stringify(g.metadata,null,2)})]})]}):null})})]})},M=({children:s})=>e.jsx("code",{className:"text-xs bg-secondary px-1.5 py-0.5 rounded",children:s}),t=({children:s})=>e.jsx("code",{className:"bg-background/50 px-1 rounded",children:s}),Fe=({code:s})=>{const n=Dt();return e.jsx(e.Fragment,{children:n(s)})},fl=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-image"})," · Método ",e.jsx(M,{children:"generateContent"})]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Nome no App"}),e.jsx(f,{children:"ID Interno"}),e.jsx(f,{children:"Modelo Google API"}),e.jsx(f,{children:"Obs."})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsxs(a,{className:"font-medium flex items-center gap-2",children:[e.jsx(ca,{className:"w-3.5 h-3.5 text-yellow-500"})," Nano Banana 2"]}),e.jsx(a,{children:e.jsx(M,{children:"nano-banana-2"})}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3.1-flash-image"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Padrão. Rápido e boa qualidade."})]}),e.jsxs(b,{children:[e.jsxs(a,{className:"font-medium flex items-center gap-2",children:[e.jsx(ca,{className:"w-3.5 h-3.5 text-emerald-500"})," Nano Banana 2 Lite"]}),e.jsx(a,{children:e.jsx(M,{children:"nano-banana-2-lite"})}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3.1-flash-lite-image"})}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["1K only. Via Créditos = Kie ",e.jsx(M,{children:"nano-banana-2-lite"})," ($0.02, action_key ",e.jsx(M,{children:"nano_banana_2_lite_kie_1k"}),"); BYOK = Vertex."]})]}),e.jsxs(b,{children:[e.jsxs(a,{className:"font-medium flex items-center gap-2",children:[e.jsx(Xs,{className:"w-3.5 h-3.5 text-primary"})," Nano Banana Pro"]}),e.jsx(a,{children:e.jsx(M,{children:"nano-banana-pro"})}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3-pro-image"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Maior qualidade. Requer plano pago."})]})]})]}),e.jsxs(Ts,{type:"multiple",className:"w-full",children:[e.jsxs(Se,{value:"google-img-flow",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Fluxo Completo da Requisição"}),e.jsx(Ee,{children:e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"text-muted-foreground",children:["1. Usuário escolhe: ",e.jsx("strong",{children:"prompt"}),", ",e.jsx("strong",{children:"proporção"}),", ",e.jsx("strong",{children:"qualidade"}),", ",e.jsx("strong",{children:"modelo"}),", ",e.jsx("strong",{children:"quantidade"})," e opcionalmente ",e.jsx("strong",{children:"referências"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["2. Frontend monta body e chama ",e.jsx(t,{children:"generate-image"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["3. Edge Function busca API Key do usuário (provider: ",e.jsx(t,{children:"google_ai"}),")."]}),e.jsx("p",{className:"text-muted-foreground",children:"4. Mapeia modelo e qualidade → valores da API Google."}),e.jsxs("p",{className:"text-muted-foreground",children:["5. Monta texto com prefixo ",e.jsx(t,{children:'"Generate an image: "'})," + prompt."]}),e.jsxs("p",{className:"text-muted-foreground",children:["6. POST para ",e.jsx(t,{children:"generativelanguage.googleapis.com/v1beta/models/{model}:generateContent"}),"."]}),e.jsx("p",{className:"text-muted-foreground",children:"7. Resposta: imagem em base64 → upload B2 → retorna URL pública."}),e.jsx("p",{className:"text-muted-foreground",children:"8. Retry automático (até 2x) com backoff em caso de 429."})]})})]}),e.jsxs(Se,{value:"google-img-config",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"imageConfig & Mapeamentos"}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Parâmetro"}),e.jsx(f,{children:"Opções"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(t,{children:"aspectRatio"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(t,{children:"imageSize"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"1K, 2K, 4K"})]})]})]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Qualidade no App"}),e.jsx(f,{children:"imageSize"}),e.jsx(f,{children:"Obs."})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"1K"}),e.jsx(a,{children:e.jsx(t,{children:"1K"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Padrão"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"2K"}),e.jsx(a,{children:e.jsx(t,{children:"2K"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Alta resolução"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"4K"}),e.jsx(a,{children:e.jsx(t,{children:"4K"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Máxima (reduzida com muitas refs)"})]})]})]})]})})]})]})]}),vl=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-video"})," · Método ",e.jsx(M,{children:"predictLongRunning"})," (async c/ polling)"]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Nome no App"}),e.jsx(f,{children:"ID Interno"}),e.jsx(f,{children:"Modelo Google API"}),e.jsx(f,{children:"Obs."})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsxs(a,{className:"font-medium flex items-center gap-2",children:[e.jsx(Gi,{className:"w-3.5 h-3.5 text-green-500"})," Veo 3.1 Lite"]}),e.jsx(a,{children:e.jsx(M,{children:"veo-3.1-lite"})}),e.jsx(a,{children:e.jsx(M,{children:"veo-3.1-lite-generate-preview"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Econômico. Sem 4K."})]}),e.jsxs(b,{children:[e.jsxs(a,{className:"font-medium flex items-center gap-2",children:[e.jsx(ca,{className:"w-3.5 h-3.5 text-yellow-500"})," Veo 3.1 Fast"]}),e.jsx(a,{children:e.jsx(M,{children:"veo-3.1-fast"})}),e.jsx(a,{children:e.jsx(M,{children:"veo-3.1-fast-generate-preview"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Geração mais rápida."})]}),e.jsxs(b,{children:[e.jsxs(a,{className:"font-medium flex items-center gap-2",children:[e.jsx(Ra,{className:"w-3.5 h-3.5 text-blue-500"})," Veo 3.1"]}),e.jsx(a,{children:e.jsx(M,{children:"veo-3.1"})}),e.jsx(a,{children:e.jsx(M,{children:"veo-3.1-generate-preview"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Maior qualidade visual."})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Fluxo:"}),e.jsxs("p",{className:"text-muted-foreground",children:["1. Frontend envi
224a ",e.jsx(t,{children:"{ prompt, aspectRatio, duration, quality, model, startFrame?, endFrame? }"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["2. Chama ",e.jsx(t,{children:"predictLongRunning"})," → recebe ",e.jsx(t,{children:"operationName"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["3. Polling a cada 5s com ",e.jsx(t,{children:"{ action: 'poll', operationName }"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["4. Quando ",e.jsx(t,{children:"done: true"}),", vídeo é baixado e retornado."]})]})]}),bl=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-video-wavespeed"})," · ",e.jsx(Fe,{code:"Provedor B"})," REST API · Image-to-Video com polling"]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Variante"}),e.jsxs(f,{children:["Endpoint ",e.jsx(Fe,{code:"Provedor B"})]}),e.jsx(f,{children:"Resolução"}),e.jsx(f,{children:"LoRA"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsxs(a,{className:"font-medium flex items-center gap-2",children:[e.jsx(St,{className:"w-3.5 h-3.5 text-orange-500"})," WAN 2.2 Hot 480p"]}),e.jsx(a,{children:e.jsx(M,{children:"wan-2.2/i2v-480p"})}),e.jsx(a,{children:"480p"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Não"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"WAN 2.2 Hot 720p"}),e.jsx(a,{children:e.jsx(M,{children:"wan-2.2/i2v-720p"})}),e.jsx(a,{children:"720p"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Não"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"WAN 2.2 Hot 480p LoRA"}),e.jsx(a,{children:e.jsx(M,{children:"wan-2.2/i2v-480p-lora"})}),e.jsx(a,{children:"480p"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Sim (3+3+3)"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"WAN 2.2 Hot 720p LoRA"}),e.jsx(a,{children:e.jsx(M,{children:"wan-2.2/i2v-720p-lora"})}),e.jsx(a,{children:"720p"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Sim (3+3+3)"})]})]})]}),e.jsxs(Ts,{type:"multiple",className:"w-full",children:[e.jsxs(Se,{value:"wan-pricing",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Custos & Créditos"}),e.jsx(Ee,{children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Slug"}),e.jsx(f,{children:"Custo USD"}),e.jsx(f,{children:"× 2.00"}),e.jsx(f,{children:"Créditos"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"wan_hot_480p_5s"})}),e.jsx(a,{children:"$0.15"}),e.jsx(a,{children:"$0.30"}),e.jsx(a,{className:"font-semibold",children:"30"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"wan_hot_720p_5s"})}),e.jsx(a,{children:"$0.30"}),e.jsx(a,{children:"$0.60"}),e.jsx(a,{className:"font-semibold",children:"60"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"wan_hot_480p_8s"})}),e.jsx(a,{children:"$0.24"}),e.jsx(a,{children:"$0.48"}),e.jsx(a,{className:"font-semibold",children:"48"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"wan_hot_720p_8s"})}),e.jsx(a,{children:"$0.48"}),e.jsx(a,{children:"$0.96"}),e.jsx(a,{className:"font-semibold",children:"96"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"wan_hot_lora_480p_5s"})}),e.jsx(a,{children:"$0.20"}),e.jsx(a,{children:"$0.40"}),e.jsx(a,{className:"font-semibold",children:"40"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"wan_hot_lora_720p_5s"})}),e.jsx(a,{children:"$0.40"}),e.jsx(a,{children:"$0.80"}),e.jsx(a,{className:"font-semibold",children:"80"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"wan_hot_lora_480p_8s"})}),e.jsx(a,{children:"$0.32"}),e.jsx(a,{children:"$0.64"}),e.jsx(a,{className:"font-semibold",children:"64"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"wan_hot_lora_720p_8s"})}),e.jsx(a,{children:"$0.64"}),e.jsx(a,{children:"$1.28"}),e.jsx(a,{className:"font-semibold",children:"128"})]}),e.jsx(b,{children:e.jsx(a,{colSpan:4,className:"text-[10px] text-muted-foreground pt-2",children:"Fórmula: ceil(USD × 2.00 / $0.01) · 1 crédito = $0.01 USD"})})]})]})})]}),e.jsxs(Se,{value:"wan-flow",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Fluxo Completo"}),e.jsx(Ee,{children:e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"text-muted-foreground",children:["1. Frontend envi
224a ",e.jsx(t,{children:"{ prompt, resolution, duration, imageData, loras?, highNoiseLoras?, lowNoiseLoras? }"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["2. Edge Function faz ",e.jsx(t,{children:"deduct_credits"})," com slug calculado (resolução + duração + lora)."]}),e.jsx("p",{className:"text-muted-foreground",children:"3. Upload do start frame para B2 → URL pública."}),e.jsxs("p",{className:"text-muted-foreground",children:["4. POST para ",e.jsxs(t,{children:["(endpoint do ",e.jsx(Fe,{code:"Provedor B"}),")"]})," com ",e.jsx(t,{children:"PROVIDER_B_API_KEY"})," da plataforma."]}),e.jsxs("p",{className:"text-muted-foreground",children:["5. Retorna ",e.jsx(t,{children:"predictionId"})," para polling do frontend."]}),e.jsxs("p",{className:"text-muted-foreground",children:["6. Poll a cada 5s via ",e.jsx(t,{children:"predictions/{id}/result"}),"."]}),e.jsx("p",{className:"text-muted-foreground",children:"7. Quando completo: download vídeo → upload B2 → retorna URL."}),e.jsxs("p",{className:"text-muted-foreground",children:["8. Em 
224caso de erro: ",e.jsx(t,{children:"refund_credits"})," automático."]})]})})]}),e.jsxs(Se,{value:"wan-loras",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Suporte a LoRAs"}),e.jsx(Ee,{children:e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"text-muted-foreground",children:["• 3 categorias: ",e.jsx(t,{children:"loras"}),", ",e.jsx(t,{children:"high_noise_loras"}),", ",e.jsx(t,{children:"low_noise_loras"})]}),e.jsx("p",{className:"text-muted-foreground",children:"• Máximo 3 LoRAs por categoria (9 total)"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Formato: ",e.jsx(t,{children:"{ path: 'user/repo', scale: 1.0 }"})]}),e.jsx("p",{className:"text-muted-foreground",children:"• High noise: mudanças globais de estilo"}),e.jsx("p",{className:"text-muted-foreground",children:"• Low noise: refinamentos sutis"}),e.jsx("p",{className:"text-muted-foreground",children:"• URL aceita: HuggingFace (user/repo) ou link .safetensors"})]})})]})]})]}),Nl=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-wan-image"})," · ",e.jsxs("strong",{children:[e.jsx(Fe,{code:"Provedor A"})," REST API"]})," · Text-to-Image & Image Editing com polling interno"]}),e.jsxs("div",{className:"bg-cyan-500/10 border border-cyan-500/30 rounded-lg p-3 text-xs text-cyan-400",children:[e.jsx("strong",{children:"Provedor:"})," ",e.jsx(Fe,{code:"Provedor A"})," — Modelo Alibaba WAN 2.7 para geração e edição de imagens."]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Variante"}),e.jsxs(f,{children:["Modelo ",e.jsx(Fe,{code:"Provedor A"})]}),e.jsx(f,{children:"Resoluções"}),e.jsx(f,{children:"Custo USD"}),e.jsx(f,{children:"Créditos IA"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsxs(a,{className:"font-medium flex items-center gap-2",children:[e.jsx(ca,{className:"w-3.5 h-3.5 text-yellow-500"})," WAN 2.7 Image"]}),e.jsx(a,{children:e.jsx(M,{children:"wan/2-7-image"})}),e.jsx(a,{className:"text-xs",children:"1K, 2K, 4K (text-to-image apenas)"}),e.jsx(a,{children:"~$0.024/img"}),e.jsx(a,{children:"12"})]}),e.jsxs(b,{children:[e.jsxs(a,{className:"font-medium flex items-center gap-2",children:[e.jsx(At,{className:"w-3.5 h-3.5 text-purple-500"})," WAN 2.7 Image Pro"]}),e.jsx(a,{children:e.jsx(M,{children:"wan/2-7-image-pro"})}),e.jsx(a,{className:"text-xs",children:"1K, 2K, 4K (todos os modos)"}),e.jsx(a,{children:"~$0.06/img"}),e.jsx(a,{children:"30"})]})]})]}),e.jsxs(Ts,{type:"multiple",className:"w-full",children:[e.jsxs(Se,{value:"wan27-params",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Parâmetros"}),e.jsx(Ee,{children:e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"prompt"})," (string, ≤5000 chars): Descrição da imagem ou instrução de edição"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"input_urls"})," (array, ≤9 imgs): URLs de imagens de entrada para edição"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"resolution"}),": 1K, 2K, 4K"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"aspect_ratio"}),": 1:1, 16:9, 4:3, 21:9, 3:4, 9:16, 8:1, 1:8 (somente sem input_urls)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"n"}),": 1 (fixo — batch controlado pelo frontend)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"Desativados:"})," thinking_mode, color_palette, bbox_list, watermark, enable_sequential"]})]})})]}),e.jsxs(Se,{value:"wan27-flow",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Fluxo Completo"}),e.jsx(Ee,{children:e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"text-muted-foreground",children:["1. Frontend envi
224a via ",e.jsx(t,{children:"useImageQueue"}),' (provider: "kie")']}),e.jsxs("p",{className:"text-muted-foreground",children:["2. Roteado para ",e.jsx(t,{children:"generate-wan-image"})," edge function"]}),e.jsxs("p",{className:"text-muted-foreground",children:["3. Calcula ",e.jsx(t,{children:"actionKey"})," (ex: ",e.jsx(t,{children:"wan_27_image_pro_2k"}),")"]}),e.jsxs("p",{className:"text-muted-foreground",children:["4. ",e.jsx(t,{children:"deduct_credits"})," com slug calculado"]}),e.jsx("p",{className:"text-muted-foreground",children:"5. Upload de refs base64 para B2 → URLs públicas CDN"}),e.jsxs("p",{className:"text-muted-foreground",children:["6. POST para ",e.jsxs(t,{children:["(endpoint de criação do ",e.jsx(Fe,{code:"Provedor A"}),")"]})]}),e.jsxs("p",{className:"text-muted-foreground",children:["7. Polling interno (até 180s) via ",e.jsx(t,{children:"recordInfo"})]}),e.jsx("p",{className:"text-muted-foreground",children:"8. Download resultado → Upload B2 → Thumbnail → Retorna URL"}),e.jsx("p",{className:"text-muted-foreground",children:"9. Em 
224caso de erro: refund automático + log em error_logs"})]})})]})]})]}),yl=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-kling-motion"})," · ",e.jsxs("strong",{children:[e.jsx(Fe,{code:"Provedor A"})," REST API"]})," · Motion Control (Imagem + Vídeo de referência) com polling"]}),e.jsxs("div",{className:"bg-blue-500/10 border border-blue-500/30 rounded-lg p-3 text-xs text-blue-400",children:[e.jsx("strong",{children:"Provedor:"})," ",e.jsx(Fe,{code:"Provedor A"})," — Aplica o movimento de um vídeo de referência a uma imagem de personagem."]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Versão"}),e.jsxs(f,{children:["Modelo ",e.jsx(Fe,{code:"Provedor A"})]}),e.jsx(f,{children:"Resoluções"}),e.jsx(f,{children:"Custo USD/s"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsxs(a,{className:"font-medium flex items-center gap-2",children:[e.jsx(fa,{className:"w-3.5 h-3.5 text-blue-500"})," v2.6"]}),e.jsx(a,{children:e.jsx(M,{children:"kling-2.6/motion-control"})}),e.jsx(a,{className:"text-xs",children:"720p, 1080p"}),e.jsx(a,{className:"text-xs",children:"$0.03/s (720p) · $0.045/s (1080p)"})]}),e.jsxs(b,{children:[e.jsxs(a,{className:"font-medium flex items-center gap-2",children:[e.jsx(fa,{className:"w-3.5 h-3.5 text-purple-500"})," v3.0"]}),e.jsx(a,{children:e.jsx(M,{children:"kling-3.0/motion-control"})}),e.jsx(a,{className:"text-xs",children:"720p, 1080p"}),e.jsx(a,{className:"text-xs",children:"$0.10/s (720p) · $0.135/s (1080p)"})]})]})]}),e.jsxs(Ts,{type:"multiple",className:"w-full",children:[e.jsxs(Se,{value:"kling-params",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Parâmetros"}),e.jsx(Ee,{children:e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"input_urls"})," (array): URL da imagem do personagem (JPEG/PNG, máx 2048px)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"video_urls"})," (array): URL do vídeo de referência (máx 50MB)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"character_orientation"}),': "image" | "video"']}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"mode"}),': "720p" | "1080p"']}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"prompt"})," (opcional): Descrição adicional (máx 2500 chars)"]})]})})]}),e.jsxs(Se,{value:"kling-pricing",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Custos & Créditos"}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Custo dinâmico por segundo. Fórmula: ",e.jsx(t,{children:"ceil(custo_por_segundo × duração × 500)"})]}),e.jsx("p",{className:"text-xs font-semibold",children:"v2.6"}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Res"}),e.jsx(f,{children:"5s"}),e.jsx(f,{children:"10s"}),e.jsx(f,{children:"15s"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"720p"}),e.jsx(a,{children:"75"}),e.jsx(a,{children:"150"}),e.jsx(a,{children:"225"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"1080p"}),e.jsx(a,{children:"113"}),e.jsx(a,{children:"225"}),e.jsx(a,{children:"338"})]})]})]}),e.jsx("p",{className:"text-xs font-semibold mt-3",children:"v3.0"}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Res"}),e.jsx(f,{children:"5s"}),e.jsx(f,{children:"10s"}),e.jsx(f,{children:"15s"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"720p"}),e.jsx(a,{children:"250"}),e.jsx(a,{children:"500"}),e.jsx(a,{children:"750"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"1080p"}),e.jsx(a,{children:"338"}),e.jsx(a,{children:"675"}),e.jsx(a,{children:"1013"})]})]})]})]})})]}),e.jsxs(Se,{value:"kling-flow",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Fluxo Completo"}),e.jsx(Ee,{children:e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"text-muted-foreground",children:"1. Frontend faz upload prévio de imagem e vídeo para B2 (evita limite de memória)"}),e.jsxs("p",{className:"text-muted-foreground",children:["2. Env
224ia URLs + parâmetros para ",e.jsx(t,{children:"generate-kling-motion"})]}),e.jsx("p",{className:"text-muted-foreground",children:"3. Edge Function calcula créditos dinamicamente (custo/s × duração × 500)"}),e.jsx("p",{className:"text-muted-foreground",children:"4. Deduz créditos (premium primeiro, depois purchased)"}),e.jsxs("p",{className:"text-muted-foreground",children:["5. POST para ",e.jsxs(t,{children:["(endpoint de criação do ",e.jsx(Fe,{code:"Provedor A"}),")"]})]}),e.jsxs("p",{className:"text-muted-foreground",children:["6. Retorna ",e.jsx(t,{children:"taskId"})," para polling no frontend"]}),e.jsxs("p",{className:"text-muted-foreground",children:["7. Poll via ",e.jsxs(t,{children:["(endpoint de polling do ",e.jsx(Fe,{code:"Provedor A"}),")"]})]}),e.jsx("p",{className:"text-muted-foreground",children:"8. Quando completo: download vídeo → upload B2 → retorna URL CDN"}),e.jsx("p",{className:"text-muted-foreground",children:"9. Em caso de erro: refund automático dos créditos"})]})})]})]})]}),_l=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-wan27-video"})," · ",e.jsxs("strong",{children:[e.jsx(Fe,{code:"Provedor A"})," REST API"]})," · 4 modos: T2V, I2V, R2V, VideoEdit com polling"]}),e.jsxs("div",{className:"bg-purple-500/10 border border-purple-500/30 rounded-lg p-3 text-xs text-purple-400",children:[e.jsx("strong",{children:"Provedor:"})," ",e.jsx(Fe,{code:"Provedor A"})," — Modelo Alibaba WAN 2.7 para geração e edição de vídeos multimodais."]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Modo"}),e.jsxs(f,{children:["Modelo ",e.jsx(Fe,{code:"Provedor A"})]}),e.jsx(f,{children:"Descrição"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsxs(a,{className:"font-medium flex items-center gap-2",children:[e.jsx(Xs,{className:"w-3.5 h-3.5 text-purple-500"})," Text → Vídeo (T2V)"]}),e.jsx(a,{children:e.jsx(M,{children:"wan/2-7-text-to-video"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Gera vídeo a partir de prompt textual"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Img → Vídeo (I2V)"}),e.jsx(a,{children:e.jsx(M,{children:"wan/2-7-image-to-video"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Anima imagem (first/last frame, clip, áudio)"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Ref → Vídeo (R2V)"}),e.jsx(a,{children:e.jsx(M,{children:"wan/2-7-r2v"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Multi-referência (imgs, vídeos, voz)"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"VideoEdit"}),e.jsx(a,{children:e.jsx(M,{children:"wan/2-7-videoedit"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Edita vídeo existente com prompt + imagens"})]})]})]}),e.jsxs(Ts,{type:"multiple",className:"w-full",children:[e.jsxs(Se,{value:"wan27v-params",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Parâmetros por Modo"}),e.jsx(Ee,{children:e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-3",children:[e.jsx("p",{className:"font-semibold",children:"Comum a todos:"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"prompt"}),", ",e.jsx(t,{children:"resolution"})," (720p/1080p), ",e.jsx(t,{children:"duration"})," (2-10s)"]}),e.jsx("p",{className:"font-semibold mt-2",children:"T2V:"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"ratio"}),": 16:9, 9:16, 1:1, 4:3, 3:4"]}),e.jsx("p",{className:"font-semibold mt-2",children:"I2V:"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"first_frame_url"}),", ",e.jsx(t,{children:"last_frame_url"}),", ",e.jsx(t,{children:"first_clip_url"}),", ",e.jsx(t,{children:"driving_audio_url"})]}),e.jsx("p",{className:"font-semibold mt-2",children:"R2V:"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"reference_image[]"})," (máx 5), ",e.jsx(t,{children:"reference_video[]"})," (máx 5), ",e.jsx(t,{children:"first_frame"}),", ",e.jsx(t,{children:"reference_voice"})]}),e.jsx("p",{className:"font-semibold mt-2",children:"VideoEdit:"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"video_url"})," (obrigatório), ",e.jsx(t,{children:"image_url[]"})," (máx 3), ",e.jsx(t,{children:"audio_setting"})," (auto/origin)"]})]})})]}),e.jsxs(Se,{value:"wan27v-pricing",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Custos & Créditos"}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Custo dinâmico por segundo. Fórmula: ",e.jsx(t,{children:"ceil(custo_por_segundo × duração × 500)"})]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Res"}),e.jsx(f,{children:"$/s"}),e.jsx(f,{children:"2s"}),e.jsx(f,{children:"5s"}),e.jsx(f,{children:"10s"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"720p"}),e.jsx(a,{children:"$0.08"}),e.jsx(a,{children:"80"}),e.jsx(a,{children:"200"}),e.jsx(a,{children:"400"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"1080p"}),e.jsx(a,{children:"$0.12"}),e.jsx(a,{children:"120"}),e.jsx(a,{children:"300"}),e.jsx(a,{children:"600"})]})]})]})]})})]}),e.jsxs(Se,{value:"wan27v-flow",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Fluxo Completo"}),e.jsx(Ee,{children:e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"text-muted-foreground",children:["1. Frontend converte arquivos para base64 e envia para ",e.jsx(t,{children:"generate-wan27-video"})]}),e.jsx("p",{className:"text-muted-foreground",children:"2. Edge Function faz upload dos assets para B2 (imagens, vídeos, áudio)"}),e.jsx("p",{className:"text-muted-foreground",children:"3. Calcula créditos dinamicamente (res × duração × 500)"}),e.jsx("p",{className:"text-muted-foreground",children:"4. Deduz créditos (premium primeiro, depois purchased)"}),e.jsxs("p",{className:"text-muted-foreground",children:["5. POST para ",e.jsxs(t,{children:["(endpoint de criação do ",e.jsx(Fe,{code:"Provedor A"}),")"]})]}),e.jsxs("p",{className:"text-muted-foreground",children:["6. Retorna ",e.jsx(t,{children:"taskId"})," para polling no frontend"]}),e.jsxs("p",{className:"text-muted-foreground",children:["7. Poll via ",e.jsxs(t,{children:["(endpoint de polling do ",e.jsx(Fe,{code:"Provedor A"}),")"]})]}),e.jsx("p",{className:"text-muted-foreground",children:"8. Quando completo: download vídeo → upload B2 → retorna URL CDN"}
224),e.jsx("p",{className:"text-muted-foreground",children:"9. Em caso de erro: refund automático dos créditos"})]})})]})]})]}),wl=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-happyhorse"})," · ",e.jsxs("strong",{children:[e.jsx(Fe,{code:"Provedor A"})," REST API"]})," · 4 modos: T2V, I2V, R2V, VideoEdit com polling"]}),e.jsxs("div",{className:"bg-fuchsia-500/10 border border-fuchsia-500/30 rounded-lg p-3 text-xs text-fuchsia-400",children:[e.jsx("strong",{children:"Provedor:"})," ",e.jsx(Fe,{code:"Provedor A"})," — Modelo HappyHorse 1.0 (Alibaba ATH) para geração e edição multimodal de vídeos."]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Modo"}),e.jsxs(f,{children:["Modelo ",e.jsx(Fe,{code:"Provedor A"})]}),e.jsx(f,{children:"Descrição"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsxs(a,{className:"font-medium flex items-center gap-2",children:[e.jsx(Xs,{className:"w-3.5 h-3.5 text-fuchsia-500"})," Text → Vídeo (T2V)"]}),e.jsx(a,{children:e.jsx(M,{children:"happyhorse/text-to-video"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Gera vídeo a partir de prompt textual"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Img → Vídeo (I2V)"}),e.jsx(a,{children:e.jsx(M,{children:"happyhorse/image-to-video"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Anima imagem (first/last frame)"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Ref → Vídeo (R2V)"}),e.jsx(a,{children:e.jsx(M,{children:"happyhorse/reference-to-video"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Multi-referência (imagens, vídeos)"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"VideoEdit"}),e.jsx(a,{children:e.jsx(M,{children:"happyhorse/video-edit"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Edita vídeo existente com prompt + imagens"})]})]})]}),e.jsxs(Ts,{type:"multiple",className:"w-full",children:[e.jsxs(Se,{value:"happyhorse-params",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Parâmetros por Modo"}),e.jsx(Ee,{children:e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-3",children:[e.jsx("p",{className:"font-semibold",children:"Comum a todos:"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"prompt"}),", ",e.jsx(t,{children:"resolution"})," (720p/1080p), ",e.jsx(t,{children:"duration"})," (slider 3–15s)"]}),e.jsx("p",{className:"font-semibold mt-2",children:"T2V:"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"aspectRatio"}),": 16:9, 9:16, 1:1, 4:3, 3:4"]}),e.jsx("p",{className:"font-semibold mt-2",children:"I2V:"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"first_frame_url"}),", ",e.jsx(t,{children:"last_frame_url"})]}),e.jsx("p",{className:"font-semibold mt-2",children:"R2V:"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"reference_image[]"}),", ",e.jsx(t,{children:"reference_video[]"})]}),e.jsx("p",{className:"font-semibold mt-2",children:"VideoEdit:"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"video_url"})," (obrigatório), ",e.jsx(t,{children:"image_url[]"})]})]})})]}),e.jsxs(Se,{value:"happyhorse-pricing",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Custos & Créditos"}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Custo dinâmico por segundo via tiers ",e.jsx(t,{children:"happyhorse_720p"})," e ",e.jsx(t,{children:"happyhorse_1080p"})," (model_pricing_tiers)."]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Res"}),e.jsx(f,{children:"$/s"}),e.jsx(f,{children:"3s"}),e.jsx(f,{children:"5s"}),e.jsx(f,{children:"10s"}),e.jsx(f,{children:"15s"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"720p"}),e.jsx(a,{children:"$0.155"}),e.jsx(a,{children:"~82"}),e.jsx(a,{children:"~136"}),e.jsx(a,{children:"~272"}),e.jsx(a,{children:"~407"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"1080p"}),e.jsx(a,{children:"$0.265"}),e.jsx(a,{children:"~140"}),e.jsx(a,{children:"~232"}),e.jsx(a,{children:"~464"}),e.jsx(a,{children:"~696"})]})]})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground italic",children:"Valores aproximados com markup global × valor do crédito."})]})})]}),e.jsxs(Se,{value:"happyhorse-flow",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Fluxo Completo"}),e.jsx(Ee,{children:e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"text-muted-foreground",children:["1. Frontend faz eager-upload das mídias (B2) e envia para ",e.jsx(t,{children:"generate-happyhorse"})]}),e.jsx("p",{className:"text-muted-foreground",children:"2. Edge Function valida modo (t2v/i2v/r2v/videoedit) e monta payload"}),e.jsx("p",{className:"text-muted-foreground",children:"3. Calcula créditos via tier (res × duração × multiplicador global)"}),e.jsx("p",{className:"text-muted-foreground",children:"4. Deduz créditos (premium primeiro, depois purchased)"}),e.jsxs("p",{className:"text-muted-foreground",children:["5. POST para o endpoint do ",e.jsx(Fe,{code:"Provedor A"})," correspondente ao modo"]}),e.jsxs("p",{className:"text-muted-foreground",children:["6. Retorna ",e.jsx(t,{children:"taskId"})," para polling no frontend (15min timeout)"]}),e.jsx("p",{className:"text-muted-foreground",children:"7. Quando completo: download vídeo → upload B2 → retorna URL CDN"}),e.jsxs("p",{className:"text-muted-foreground",children:["8. Em 
224caso de erro: refund automático deduplicado por ",e.jsx(t,{children:"taskId"})]})]})})]})]})]}),kl=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-seedance"})," (",e.jsx(Fe,{code:"Provedor A"}),") · Text-to-Video (Multi Reference) & Image-to-Video (First & Last Frame) com polling"]}),e.jsxs("div",{className:"bg-emerald-500/10 border border-emerald-500/30 rounded-lg p-3 text-xs text-emerald-400",children:[e.jsx("strong",{children:"Provedor:"})," ",e.jsx(Fe,{code:"Provedor A"})," — disponível para todos os usuários."]}),e.jsxs(Ts,{type:"multiple",className:"w-full",children:[e.jsxs(Se,{value:"seedance-params",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Parâmetros"}),e.jsx(Ee,{children:e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"prompt"})," (string): Descrição do vídeo"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"duration"}),": 4 a 15 segundos (",e.jsx(Fe,{code:"Provedor A"}),")"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"resolution"}),": 480p, 720p"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"aspect_ratio"}),": 16:9, 9:16, 1:1, 4:3, 3:4, 21:9"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"T2V:"})," ",e.jsx(t,{children:"reference_images"}),", ",e.jsx(t,{children:"reference_videos"}),", ",e.jsx(t,{children:"reference_audios"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"I2V:"})," ",e.jsx(t,{children:"image"})," (start frame) + ",e.jsx(t,{children:"last_image"})," (opcional)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"generateAudio"}),": true/false (dobra o custo)"]})]})})]}),e.jsxs(Se,{value:"seedance-pricing",children:[e.jsxs(Ae,{className:"text-xs font-semibold",children:["Custos & Créditos (",e.jsx(Fe,{code:"Provedor A"}),")"]}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Custo por segundo. Créditos = USD × 500. Audio dobra o custo."}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Tier"}),e.jsx(f,{children:"Res"}),e.jsx(f,{children:"Com Ref Video ($/s)"}),e.jsx(f,{children:"Sem Ref Video ($/s)"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"Fast"}),e.jsx(a,{children:"480p"}),e.jsx(a,{children:"$0.045"}),e.jsx(a,{children:"$0.0775"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Fast"}),e.jsx(a,{children:"720p"}),e.jsx(a,{children:"$0.100"}),e.jsx(a,{children:"$0.165"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Pro"}),e.jsx(a,{children:"480p"}),e.jsx(a,{children:"$0.0575"}),e.jsx(a,{children:"$0.095"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Pro"}),e.jsx(a,{children:"720p"}),e.jsx(a,{children:"$0.125"}),e.jsx(a,{children:"$0.205"})]})]})]})]})})]}),e.jsxs(Se,{value:"seedance-flow",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Fluxo Completo"}),e.jsx(Ee,{children:e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"text-muted-foreground",children:["1. Frontend envia dados para ",e.jsx(t,{children:"generate-seedance"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["2. Edge Function calcula créditos: ",e.jsx(t,{children:"USD/s × duração × 500"})]}),e.jsx("p",{className:"text-muted-foreground",children:"3. Deduz créditos diretamente (pricing dinâmico)"}),e.jsx("p",{className:"text-muted-foreground",children:"4. Upload de refs para B2 → URLs públicas CDN"}),e.jsxs("p",{className:"text-muted-foreground",children:["5. POST para ",e.jsxs(t,{children:["(API do ",e.jsx(Fe,{code:"Provedor A"}),")"]})]}),e.jsxs("p",{className:"text-muted-foreground",children:["6. Retorna ",e.jsx(t,{children:"taskId"})," para polling"]}),e.jsx("p",{className:"text-muted-foreground",children:"7. Poll via edge function com action=poll"}),e.jsx("p",{className:"text-muted-foreground",children:"8. Quando completo: download vídeo → upload B2 → retorna URL"}
224),e.jsx("p",{className:"text-muted-foreground",children:"9. Em caso de erro: refund automático dos créditos"})]})})]})]})]}),Cl=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Modelo"}),e.jsx(f,{children:"ID Interno"}),e.jsx(f,{children:"Text-to-Image"}),e.jsx(f,{children:"Edit (img-to-img)"}),e.jsx(f,{children:"Refs Máx"})]})}),e.jsx(De,{children:e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Seedream 5.0 Pro"}),e.jsx(a,{children:e.jsx(M,{children:"seedream-5.0-pro"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"seedream/5-pro-text-to-image"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"seedream/5-pro-image-to-image"}),e.jsx(a,{children:"10"})]})})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Parâmetros"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"Via Provedor A (Kie)"})," desde 2026-07-09 (~22% mais barato). ",e.jsx(t,{children:"quality"}),": ",e.jsx(t,{children:"basic"}),"=1K $0.035 / ",e.jsx(t,{children:"high"}),"=2K $0.07 (seletor de qualidade). ",e.jsx(t,{children:"aspect_ratio"})," OBRIGATÓRIO, 7 valores (1:1, 4:3, 3:4, 16:9, 9:16, 2:3, 3:2); fora disso o edge mapeia pro mais próximo. Edit: refs via ",e.jsx(t,{children:"image_urls"})," (+$0.0025 por ref extra, 1ª grátis)."]}),e.jsx("p",{className:"text-muted-foreground",children:"• Sem LoRA. Sem strength."}),e.jsxs("p",{className:"text-muted-foreground",children:["• Edit: referências via array ",e.jsx(t,{children:"images"})," (URLs)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Legado: ",e.jsx(t,{children:"seedream-4.5"})," / ",e.jsx(t,{children:"seedream-5.0-lite"})," removidos (2026-07-08); edge aliasa pro 5.0 Pro."]})]})]}),Sl=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Modo"}),e.jsx(f,{children:"Endpoint"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"Text-to-Image"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"flux-2-klein-9b/text-to-image"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Edit (img-to-img)"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"flux-2-klein-9b/edit"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Text-to-Image LoRA"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"flux-2-klein-9b/text-to-image-lora"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Edit LoRA"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"flux-2-klein-9b/edit-lora"})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Parâmetros"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Até ",e.jsx("strong",{children:"3 referências"})," (array ",e.jsx(t,{children:"images"}),")"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Text-to-image: usa ",e.jsx(t,{children:"width"})," + ",e.jsx(t,{children:"height"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Edit: usa ",e.jsx(t,{children:"size"}),' string "WxH"']}),e.jsxs("p",{className:"text-muted-foreground",children:["• LoRA: até 3 URLs no array ",e.jsx(t,{children:"loras"})]}),e.jsx("p",{className:"text-muted-foreground",children:"• Sem strength"})]}),e.jsx(Ts,{type:"multiple",className:"w-full",children:e.jsxs(Se,{value:"flux-sizes",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Mapeamento Aspect Ratio → Dimensões"}),e.jsx(Ee,{children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Ratio"}),e.jsx(f,{children:"Width"}),e.jsx(f,{children:"Height"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"1:1"}),e.jsx(a,{children:"1024"}),e.jsx(a,{children:"1024"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"16:9"}),e.jsx(a,{children:"1024"}),e.jsx(a,{children:"576"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"9:16"}),e.jsx(a,{children:"576"}),e.jsx(a,{children:"1024"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"4:3"}),e.jsx(a,{children:"1024"}),e.jsx(a,{children:"768"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"3:4"}),e.jsx(a,{children:"768"}),e.jsx(a,{children:"1024"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"3:2"}),e.jsx(a,{children:"1024"}),e.jsx(a,{children:"683"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"2:3"}),e.jsx(a,{children:"683"}),e.jsx(a,{children:"1024"})]})]})]})})]})})]}),Al=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Modo"}),e.jsx(f,{children:"Endpoint"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"Text-to-Image"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"z-image/turbo"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Image-to-Image"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"z-image-turbo/image-to-image"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Text-to-Image LoRA"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"turbo-lora"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Image-to-Image LoRA"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"z-image-turbo/image-to-image-lora"})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Parâmetros"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"1 referência"})," max (campo ",e.jsx(t,{children:"image"})," — string singular, não array)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Sempre usa ",e.jsx(t,{children:"width"})," + ",e.jsx(t,{children:"height"})," (max 1536 por dimensão)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"Strength"}
224)," (0.0–1.0, padrão 0.6): controla fidelidade à referência"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• LoRA: até 3 URLs no array ",e.jsx(t,{children:"loras"})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Roteamento de Endpoint"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Ref + LoRA → ",e.jsx(t,{children:"image-to-image-lora"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Ref sem LoRA → ",e.jsx(t,{children:"image-to-image"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• LoRA sem ref → ",e.jsx(t,{children:"turbo-lora"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Sem ref, sem LoRA → ",e.jsx(t,{children:"z-image/turbo"})]})]}),e.jsx(Ts,{type:"multiple",className:"w-full",children:e.jsxs(Se,{value:"zimage-sizes",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Mapeamento Aspect Ratio → Dimensões"}),e.jsx(Ee,{children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Ratio"}),e.jsx(f,{children:"Width"}),e.jsx(f,{children:"Height"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"1:1"}),e.jsx(a,{children:"1024"}),e.jsx(a,{children:"1024"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"16:9"}),e.jsx(a,{children:"1024"}),e.jsx(a,{children:"576"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"9:16"}),e.jsx(a,{children:"576"}),e.jsx(a,{children:"1024"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"4:3"}),e.jsx(a,{children:"1024"}),e.jsx(a,{children:"768"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"3:4"}),e.jsx(a,{children:"768"}),e.jsx(a,{children:"1024"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"3:2"}),e.jsx(a,{children:"1024"}),e.jsx(a,{children:"683"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"2:3"}),e.jsx(a,{children:"683"}),e.jsx(a,{children:"1024"})]})]})]})})]})})]}),El=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"train-lora"})," · API ",e.jsx(M,{children:"z-image-lora-trainer"})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Fluxo de Treinamento"}),e.jsx("p",{className:"text-muted-foreground",children:"1. Usuário faz upload de imagens (mín. 4) ou arquivo ZIP com imagens + captions (.txt)."}),e.jsx("p",{className:"text-muted-foreground",children:"2. Se imagens individuais: Edge Function cria ZIP com JSZip, incluindo captions como .txt."}),e.jsx("p",{className:"text-muted-foreground",children:"3. ZIP é enviado para B2 → URL pública gerada."}),e.jsxs("p",{className:"text-muted-foreground",children:["4. POST para ",e.jsx(t,{children:"(endpoint do treinador interno)"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["5. Retorna ",e.jsx(t,{children:"taskId"})," → polling a cada 10s até ",e.jsx(t,{children:"completed"})," ou ",e.jsx(t,{children:"failed"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["6. Resultado: URL do LoRA treinado salva em ",e.jsx(t,{children:"lora_trainings.result_lora_url"}),"."]})]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Parâmetro"}),e.jsx(f,{children:"Tipo"}),e.jsx(f,{children:"Padrão"}),e.jsx(f,{children:"Range"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(t,{children:"steps"})}),e.jsx(a,{children:"int"}),e.jsx(a,{children:"1000"}),e.jsx(a,{children:"500–10000"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(t,{children:"learning_rate"})}),e.jsx(a,{children:"float"}),e.jsx(a,{children:"0.0001"}),e.jsx(a,{children:"0–1"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(t,{children:"lora_rank"})}),e.jsx(a,{children:"int"}),e.jsx(a,{children:"16"}),e.jsx(a,{children:"1–64"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(t,{children:"trigger_word"})}),e.jsx(a,{children:"string"}),e.jsx(a,{children:"p3r5on"}),e.jsx(a,{children:"—"})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Custo"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"125 Créditos IA"})," por treinamento (~$1.25 USD na ",e.jsx(Fe,{code:"Provedor B"}),")"]}),e.jsx("p",{className:"text-muted-foreground",children:"• Reembolso automático em c
224aso de falha da API"})]})]}),Rl=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-captions"})," · Modelo ",e.jsx(M,{children:"x-ai/grok-4"})," via OpenRouter"]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Fluxo"}),e.jsx("p",{className:"text-muted-foreground",children:"1. Usuário faz upload de imagens na aba Captions (/characters)."}),e.jsx("p",{className:"text-muted-foreground",children:"2. Para cada imagem: converte para base64, envia para Edge Function."}),e.jsxs("p",{className:"text-muted-foreground",children:["3. Edge Function busca system prompt customizado em ",e.jsx(t,{children:"admin_settings"})," (keys: ",e.jsx(t,{children:"caption_prompt_detailed"})," ou ",e.jsx(t,{children:"caption_prompt_booru"}),")."]}),e.jsxs("p",{className:"text-muted-foreground",children:["4. POST para ",e.jsx(t,{children:"openrouter.ai/api/v1/chat/completions"})," com visão multimodal."]}),e.jsx("p",{className:"text-muted-foreground",children:"5. Retorna caption de texto para cada imagem."}),e.jsx("p",{className:"text-muted-foreground",children:"6. Usuário pode editar captions e baixar como ZIP de arquivos .txt."})]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Estilo"}),e.jsx(f,{children:"Admin Setting Key"}),e.jsx(f,{children:"Descrição"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Detalhada"}),e.jsx(a,{children:e.jsx(M,{children:"caption_prompt_detailed"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Caption em linguagem natural descritiva"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Booru Tags"}),e.jsx(a,{children:e.jsx(M,{children:"caption_prompt_booru"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Tags separadas por vírgula estilo Danbooru"})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Custo"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"5 Créditos IA"})," por imagem (~$0.05 USD no OpenRouter)"]}),e.jsx("p",{className:"text-muted-foreground",children:"• System prompts editáveis via Admin → Configurações → Prompt Captions"})]})]}),Pl=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-faceswap"})," · Método ",e.jsx(M,{children:"generateContent"})," · API Key do usuário (",e.jsx(M,{children:"google_ai"}),")"]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Modelo"}),e.jsx(f,{children:"API Model"}),e.jsx(f,{children:"Condição"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"Nano Banana 2"}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3.1-flash-image"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Padrão"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Nano Banana Pro"}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3-pro-image"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"useProModel = true"})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Fluxo"}),e.jsxs("p",{className:"text-muted-foreground",children:["1. Recebe ",e.jsx(t,{children:"modelImages[]"})," (identidade) + ",e.jsx(t,{children:"referenceImage"})," (pose/cenário)."]}),e.jsxs("p",{className:"text-muted-foreground",children:["2. System prompt customizável via admin_settings (",e.jsx(t,{children:"faceswap_system_prompt"}),", variantes: detailed, concise, faithful)."]}),e.jsxs("p",{className:"text-muted-foreground",children:["3. POST ",e.jsx(t,{children:"generateContent"})," → imagem base64 → upload B2."]}),e.jsx("p",{className:"text-muted-foreground",children:"4. Retry: até 3x com backoff em 429."})]})]}),Il=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-photoshoot"})," · Método ",e.jsx(M,{children:"generateContent"})," · API Key do usuário (",e.jsx(M,{children:"google_ai"}),")"]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Modelo"}),e.jsx(f,{children:"API Model"})]})}),e.jsx(De,{children:e.jsxs(b,{children:[e.jsx(a,{children:"Nano Banana 2 (fixo)"}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3.1-flash-image"})})]})})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Fluxo"}),e.jsxs("p",{className:"text-muted-foreground",children:["1. Recebe ",e.jsx(t,{children:"modelImages[]"})," (identidade) + ",e.jsx(t,{children:"styleId"})," (ex: editorial_fashion, glamour_beauty)."]}),e.jsxs("p",{className:"text-muted-foreground",children:["2. System prompts de estilo hardcoded. Usuário pode criar estilos custom via ",e.jsx(t,{children:"user_photoshoot_styles"}),"."]}),e.jsx("p",{className:"text-muted-foreground",children:"3. Gera batches de 4 imagens. Retry individual por imagem."}),e.jsxs("p",{className:"text-muted-foreground",children:["4. Upload B2 + thumbnail + salva em ",e.jsx(t,{children:"generations"}),"."]})]})]}),Tl=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-ugc"})," · Método ",e.jsx(M,{children:"generateContent"})," · API Key do usuário (",e.jsx(M,{children:"google_ai"}),")"]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Função"}),e.jsx(f,{children:"Modelo"}),e.jsx(f,{children:"API Model"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"Agente (prompt enhancer)"}),e.jsx(a,{children:"Gemini 3.1 Flash Lite"}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3.1-flash-lite-preview"})})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Geração (padrão)"}),e.jsx(a,{children:"Nano Banana 2"}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3.1-flash-image"})})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Geração (pro)"}),e.jsx(a,{children:"Nano Banana Pro"}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3-pro-image"})})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Fluxo"}),e.jsx("p",{className:"text-muted-foreground",children:'1. Agente Flash Lite gera prompt detalhado de "foto amadora" a partir da descrição.'}),e.jsxs("p",{className:"text-muted-foreground",children:["2. Prompt aprimorado é passado ao modelo de imagem com ",e.jsx(t,{children:"modelImages[]"})," (identidade)."]}),e.jsx("p",{className:"text-muted-foreground",children:"3. Foco em realismo tipo celular: ruído, aberração cromática, iluminação natural."})]})]}),Ll=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-social-post"})," · Método ",e.jsx(M,{children:"generateContent"})," · API Key do usuário (",e.jsx(M,{children:"google_ai"}),")"]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Modelo"}),e.jsx(f,{children:"API Model"}),e.jsx(f,{children:"Condição"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"Nano Banana 2"}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3.1-flash-image"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Padrão"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Nano Banana Pro"}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3-pro-image"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:'model = "pro"'})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Fluxo"}),e.jsx("p",{className:"text-muted-foreground",children:"1. Recebe descrição do post + referencias opcionais + modelImages opcionais."}),e.jsxs("p",{className:"text-muted-foreground",children:["2. System prompt customizável via admin_settings (",e.jsx(t,{children:"design_creator_system_prompt"}),")."]}),e.jsx("p",{className:"text-muted-foreground",children:"3. Gera design completo com tipografia renderizada na imagem."})]})]}),Dl=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"inpaint-image"})," · Método ",e.jsx(M,{children:"generateContent"})," · API Key do usuário (",e.jsx(M,{children:"google_ai"}),")"]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Modelo"}),e.jsx(f,{children:"API Model"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"Nano Banana 2"}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3.1-flash-image"})})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Nano Banana Pro"}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3-pro-image"})})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Fluxo"}),e.jsxs("p",{className:"text-muted-foreground",children:["1. Recebe ",e.jsx(t,{children:"imageBase64"})," + ",e.jsx(t,{children:"maskBase64"})," (opcional) + ",e.jsx(t,{children:"prompt"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["2. Suporte a anotações com caneta (",e.jsx(t,{children:"compositeBase64"}),", ",e.jsx(t,{children:"hasPenAnnotations"}),")."]}),e.jsxs("p",{className:"text-muted-foreground",children:["3. Referência opcional via ",e.jsx(t,{children:"referenceBase64"}),"."]})]})]}),Ol=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"upscale-image"})," · Modelos combinados Google AI + ",e.jsx(Fe,{code:"Provedor B"})]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Modo"}),e.jsx(f,{children:"ID Interno"}),e.jsx(f,{children:"Modelos Usados"}),e.jsx(f,{children:"Obs."})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Combo Standard"}),e.jsx(a,{children:e.jsx(M,{children:"combo-nano-wavespeed"})}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Gemini (enhance) → ",e.jsx(M,{children:"image-upscaler"})]}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Upscale padrão"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Combo Ultimate"}),e.jsx(a,{children:e.jsx(M,{children:"combo-nano-wavespeed-ultimate"})}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Gemini (enhance) → ",e.jsx(M,{children:"ultimate-image-upscaler"})]}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Qualidade máxima"})]}),e.jsxs(b,{children:[e.jsxs(a,{className:"font-medium",children:[e.jsx(Fe,{code:"Provedor B"})," Direto"]}),e.jsxs(a,{children:[e.jsx(M,{children:"wavespeed"})," / ",e.jsx(M,{children:"wavespeed-ultimate"})]}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:[e.jsx(M,{children:"image-upscaler"})," ou ",e.jsx(M,{children:"ultimate-image-upscaler"})]}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Sem pré-processamento"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Gemini Puro"}),e.jsxs(a,{children:[e.jsx(M,{children:"nano-banana-2"})," / ",e.jsx(M,{children:"nano-banana-pro"})]}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:[e.jsx(M,{children:"gemini-3.1-flash-image"})," ou ",e.jsx(M,{children:"gemini-3-pro-image"})]}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Só enhance via IA"})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Fluxo Combo"}),e.jsxs("p",{className:"text-muted-foreground",children:["1. Step 1: Gemini ",e.jsx(t,{children:"generateContent"})," com prompt de enhance → imagem melhorada."]}),e.jsxs("p",{className:"text-muted-foreground",children:["2. Step 2: Upload B2 → ",e.jsx(Fe,{code:"Provedor B"})," ",e.jsx(t,{children:"image-upscaler"})," com URL da imagem."]}),e.jsxs("p",{className:"text-muted-foreground",children:["3. Polling até ",e.jsx(t,{children:"completed"})," → download + upload B2 → URL final."]}),e.jsx("p",{className:"text-muted-foreground",children:"4. Reembolso automático de créditos em caso de falha em qualquer step."})]})]}),Ml=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-dataset"})," · Método ",e.jsx(M,{children:"generateContent"})," · API Key do usuário (",e.jsx(M,{children:"google_ai"}),")"]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Modelo"}),e.jsx(f,{children:"API Model"})]})}),e.jsx(De,{children:e.jsxs(b,{children:[e.jsx(a,{children:"Nano Banana 2 (fixo)"}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3.1-flash-image"})})]})})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Fluxo"}),e.jsxs("p",{className:"text-muted-foreground",children:["1. Recebe ",e.jsx(t,{children:"modelImages[]"})," (identidade) + ",e.jsx(t,{children:"variations[]"})," (prompts de variação)."]}),e.jsx("p",{className:"text-muted-foreground",children:"2. Gera cada variação individualmente para treinamento de LoRA."}),e.jsxs("p",{className:"text-muted-foreground",children:["3. Upload B2 + thumbnail + salva em ",e.jsx(t,{children:"generations"}),"."]})]})]}),Fl=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"describe-image"})," · Engenharia reversa e imagem para vídeo"]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Modos do Detail Prompt"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Texto para imagem usa ",e.jsx(t,{children:"enhance-prompt"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Recriar imagem usa ",e.jsx(t,{children:"detailMode=recreate_image"})," e aceita texto ou JSON."]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Animar imagem usa ",e.jsx(t,{children:"detailMode=animate_image"}),", contexto opcional e duração de 1 a 15 segundos."]})]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Provedor"}),e.jsx(f,{children:"Modelo Padrão"}),e.jsx(f,{children:"Admin Setting"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"Google AI (padrão)"}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3.1-flash-lite-preview"})}),e.jsxs(a,{children:[e.jsx(M,{children:"describe_provider"})," = google_ai"]})]}),e.jsxs(b,{children:[e.jsx(a,{children:"OpenRouter"}),e.jsx(a,{children:"Configurável"}),e.jsxs(a,{children:[e.jsx(M,{children:"describe_provider"})," = openrouter"]})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Configuração via Admin Settings"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"describe_provider"}),' — "google_ai" ou "openrouter"']}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"describe_model"})," — modelo a usar"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"describe_system_prompt"})," — prompt do sistema"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"describe_video_system_prompt"})," — ficha modular para animar imagem"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"describe_max_tokens"})," — max tokens de resposta"]})]
224})]}),Zt=()=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"enhance-prompt"})," · Dois provedores com fallback"]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Cenário"}),e.jsx(f,{children:"Provedor"}),e.jsx(f,{children:"Modelo"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"Com LoRA ativo"}),e.jsx(a,{children:"OpenRouter"}),e.jsx(a,{children:e.jsx(M,{children:"x-ai/grok-4.3"})})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Sem LoRA"}),e.jsx(a,{children:"Google AI (user key)"}),e.jsx(a,{children:e.jsx(M,{children:"gemini-3.1-flash-lite-preview"})})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Lógica"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Com LoRA: Grok 4 Fast via OpenRouter (chave admin ",e.jsx(t,{children:"OPENROUTER_API_KEY"}),"). Retry com backoff em falha."]}),e.jsx("p",{className:"text-muted-foreground",children:"• Sem LoRA: Flash Lite via Google AI (chave do usuário). Suporte a imagens de referência como contexto visual."})]})]}),Ul=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"glass rounded-xl p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(oa,{className:"w-5 h-5 text-primary"}),e.jsx("h2",{className:"font-display font-bold text-xl",children:"Google AI Studio"}),e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:"Ativo"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Base URL: ",e.jsx(M,{children:"https://generativelanguage.googleapis.com/v1beta"})," · Chave via ",e.jsx(M,{children:"?key="})," · Provider: ",e.jsx(M,{children:"google_ai"})]}),e.jsxs(Ts,{type:"multiple",className:"w-full",children:[e.jsxs(Se,{value:"google-images",children:[e.jsx(Ae,{className:"font-semibold flex items-center gap-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ma,{className:"w-4 h-4 text-primary"})," Geração de Imagem"]})}),e.jsx(Ee,{children:e.jsx(fl,{})})]}),e.jsxs(Se,{value:"google-video",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fa,{className:"w-4 h-4 text-primary"})," Geração de Vídeo"]})}),e.jsx(Ee,{children:e.jsx(vl,{})})]}),e.jsxs(Se,{value:"wan-hot-video",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(St,{className:"w-4 h-4 text-orange-500"})," WAN 2.2 Hot (Vídeo ",e.jsx(Fe,{code:"Provedor B"}),")"]})}),e.jsx(Ee,{children:e.jsx(bl,{})})]}),e.jsxs(Se,{value:"wan-27-image",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ma,{className:"w-4 h-4 text-cyan-500"})," WAN 2.7 Image (",e.jsx(Fe,{code:"Provedor A"}),")"]})}),e.jsx(Ee,{children:e.jsx(Nl,{})})]}),e.jsxs(Se,{value:"seedance-video",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fa,{className:"w-4 h-4 text-emerald-500"})," Seedance 2.0 (Vídeo ",e.jsx(Fe,{code:"Provedor A"}),")"]})}),e.jsx(Ee,{children:e.jsx(kl,{})})]}),e.jsxs(Se,{value:"kling-motion",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fa,{className:"w-4 h-4 text-blue-500"})," Kling Motion Control (",e.jsx(Fe,{code:"Provedor A"}),")"]})}),e.jsx(Ee,{children:e.jsx(yl,{})})]}),e.jsxs(Se,{value:"wan-27-video",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fa,{className:"w-4 h-4 text-purple-500"})," WAN 2.7 Video (",e.jsx(Fe,{code:"Provedor A"}),")"]})}),e.jsx(Ee,{children:e.jsx(_l,{})})]}),e.jsxs(Se,{value:"happyhorse-video",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fa,{className:"w-4 h-4 text-fuchsia-500"})," HappyHorse 1.0 (Vídeo ",e.jsx(Fe,{code:"Provedor A"}),")"]})}),e.jsx(Ee,{children:e.jsx(wl,{})})]}),e.jsxs(Se,{value:"google-faceswap",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"w-4 h-4 text-primary"})," Face Swap"]})}),e.jsx(Ee,{children:e.jsx(Pl,{})})]}),e.jsxs(Se,{value:"google-photoshoot",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ci,{className:"w-4 h-4 text-primary"})," Photo Shoot"]})}),e.jsx(Ee,{children:e.jsx(Il,{})})]}),e.jsxs(Se,{value:"google-ugc",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"w-4 h-4 text-primary"})," UGC Creator"]})}),e.jsx(Ee,{children:e.jsx(Tl,{})})]}),e.jsxs(Se,{value:"google-design",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ui,{className:"w-4 h-4 text-primary"})," Design Creator"]})}),e.jsx(Ee,{children:e.jsx(Ll,{})})]}),e.jsxs(Se,{value:"google-inpaint",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mi,{className:"w-4 h-4 text-primary"})," Inpaint (Editor)"]})}),e.jsx(Ee,{children:e.jsx(Dl,{})})]}),e.jsxs(Se,{value:"google-upscale",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fo,{className:"w-4 h-4 text-primary"})," Upscaler"]})}),e.jsx(Ee,{children:e.jsx(Ol,{})})]}),e.jsxs(Se,{value:"google-dataset",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sr,{className:"w-4 h-4 text-primary"})," Dataset Creator"]})}),e.jsx(Ee,{children:e.jsx(Ml,{})})]}),e.jsxs(Se,{value:"google-describe",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"w-4 h-4 text-primary"})," Descrever Imagem"]})}),e.jsx(Ee,{children:e.jsx(Fl,{})})]}),e.jsxs(Se,{value:"google-enhance",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(er,{className:"w-4 h-4 text-primary"})," Aprimorar Prompt"]})}),e.jsx(Ee,{children:e.jsx(Zt,{})})]})]})]}),e.jsxs("div",{className:"glass rounded-xl p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(oa,{className:"w-5 h-5 text-primary"}),e.jsx("h2",{className:"font-display font-bold text-xl",children:e.jsx(Fe,{code:"Provedor B"})}),e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:"Ativo"}),e.jsxs(Re,{className:"text-[10px] bg-yellow-500/15 text-yellow-600 border-0",children:[e.jsx(At,{className:"w-3 h-3 mr-1"}),"Premium"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Base URL: ",e.jsxs(M,{children:["https://(API do ",e.jsx(Fe,{code:"Provedor B"}),")"]})," · Auth: ",e.jsx(M,{children:"Authorization: Bearer TOKEN"})," · Provider: ",e.jsx(M,{children:"wavespeed"})," · Edge Function: ",e.jsx(M,{children:"generate-image-wavespeed"})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"font-semibold text-foreground",children:["Fluxo Geral ",e.jsx(Fe,{code:"Provedor B"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["1. Frontend envi
224a ",e.jsx(t,{children:"{ prompt, model, aspectRatio, images?, useLora?, loraUrls?, strength? }"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["2. Edge Function busca API Key (provider: ",e.jsx(t,{children:"wavespeed"}),")."]}),e.jsx("p",{className:"text-muted-foreground",children:"3. Se ref images: upload p/ B2 → passa URLs no body."}),e.jsxs("p",{className:"text-muted-foreground",children:["4. POST ",e.jsxs(t,{children:["(endpoint do ",e.jsx(Fe,{code:"Provedor B"}),")"]})," com ",e.jsx(t,{children:"enable_sync_mode: true"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["5. Se timeout → polling 2s até ",e.jsx(t,{children:"completed"})," (max 50s)."]}),e.jsx("p",{className:"text-muted-foreground",children:"6. Download → upload B2 → retorna URL."})]}),e.jsxs(Ts,{type:"multiple",className:"w-full",children:[e.jsxs(Se,{value:"ws-seedream",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ca,{className:"w-4 h-4 text-yellow-500"})," Seedream 5.0 Pro"]})}),e.jsx(Ee,{children:e.jsx(Cl,{})})]}),e.jsxs(Se,{value:"ws-flux",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ca,{className:"w-4 h-4 text-blue-500"})," Flux 2 Klein"]})}),e.jsx(Ee,{children:e.jsx(Sl,{})})]}),e.jsxs(Se,{value:"ws-zimage",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xs,{className:"w-4 h-4 text-emerald-500"})," Z-Image Turbo"]})}),e.jsx(Ee,{children:e.jsx(Al,{})})]}),e.jsxs(Se,{value:"ws-qwen",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xs,{className:"w-4 h-4 text-teal-500"})," Qwen Image 2"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Modo"}),e.jsx(f,{children:"Endpoint"}),e.jsx(f,{children:"Custo"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"Text-to-Image"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"qwen-image-2.0/text-to-image"}),e.jsx(a,{className:"text-xs",children:"$0.03"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Edit (img-to-img)"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"qwen-image-2.0/edit"}),e.jsx(a,{className:"text-xs",children:"$0.03"})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Parâmetros"}),e.jsx("p",{className:"text-muted-foreground",children:"• Modelo 20B MMDiT — melhor renderização de texto (EN/CN)"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Resolução máx: até ",e.jsx(t,{children:"2K"})," via ",e.jsx(t,{children:"size"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Edit: até 3 imagens de referência via ",e.jsx(t,{children:"images"})]}),e.jsx("p",{className:"text-muted-foreground",children:"• Sem LoRA. Sem negative prompt. Sem strength."}),e.jsxs("p",{className:"text-muted-foreground",children:["• action_key T2I: ",e.jsx(t,{children:"qwen_image_2_t2i"})," (6 créditos)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• action_key Edit: ",e.jsx(t,{children:"qwen_image_2_edit"})," (6 créditos)"]})]}),e.jsx(Ts,{type:"multiple",className:"w-full",children:e.jsxs(Se,{value:"qwen-sizes",children:[e.jsx(Ae,{className:"text-xs font-semibold",children:"Mapeamento Aspect Ratio → Size"}),e.jsx(Ee,{children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Ratio"}),e.jsx(f,{children:"Size"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"1:1"}),e.jsx(a,{children:e.jsx(t,{children:"1024*1024"})})]}),e.jsxs(b,{children:[e.jsx(a,{children:"3:2"}),e.jsx(a,{children:e.jsx(t,{children:"1536*1024"})})]}),e.jsxs(b,{children:[e.jsx(a,{children:"2:3"}),e.jsx(a,{children:e.jsx(t,{children:"1024*1536"})})]}),e.jsxs(b,{children:[e.jsx(a,{children:"4:3"}),e.jsx(a,{children:e.jsx(t,{children:"1344*1008"})})]}),e.jsxs(b,{children:[e.jsx(a,{children:"3:4"}),e.jsx(a,{children:e.jsx(t,{children:"1008*1344"})})]}),e.jsxs(b,{children:[e.jsx(a,{children:"16:9"}),e.jsx(a,{children:e.jsx(t,{children:"1536*864"})})]}),e.jsxs(b,{children:[e.jsx(a,{children:"9:16"}),e.jsx(a,{children:e.jsx(t,{children:"864*1536"})})]}),e.jsxs(b,{children:[e.jsx(a,{children:"21:9"}),e.jsx(a,{children:e.jsx(t,{children:"1536*660"})})]})]})]})})]})})]})})]}),e.jsxs(Se,{value:"wavespeed-qwen3",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xs,{className:"w-4 h-4 text-teal-500"}),' Qwen Image 3 (WaveSpeed → Kie fallback) — "Nano Unlocked 2"']})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-qwen3-image"}),' · Submit + Poll · Roteamento automático T2I/Edit pela presença de imagens de referência. Usuário vê "Nano Unlocked 2" / "Nano Unlocked 2 Pro".']}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Variante"}),e.jsx(f,{children:"WaveSpeed principal"}),e.jsx(f,{children:"Custo real 1K / 2K"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"Base · Text-to-Image"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"alibaba/qwen-image-3.0/text-to-image"}),e.jsx(a,{className:"text-xs",children:"$0.03 / $0.03"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Base · Edit"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"alibaba/qwen-image-3.0/edit"}),e.jsx(a,{className:"text-xs",children:"$0.03 + $0.003/ref"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Pro · Text-to-Image"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"alibaba/qwen-image-3.0-pro/text-to-image"}),e.jsx(a,{className:"text-xs",children:"$0.04 / $0.075"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Pro · Edit"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"alibaba/qwen-image-3.0-pro/edit"}),e.jsx(a,{className:"text-xs",children:"$0.04 / $0.075 + $0.003/ref"})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Parâmetros e limites"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"Prompt: teto de 800 caracteres."})," A edge fn corta em fronteira de frase como proteção final."]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"images"}),": 1 a 3 referências no Edit."]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"aspect_ratio"}),": 15 opções — 1:1, 1:2, 2:1, 1:3, 3:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 9:21 e 21:9."]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"resolution"}),": 1K ou 2K (sem 4K). No Pro o 2K quase dobra o custo;
224 no base o preço é igual."]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"seed"}),": aleatório por padrão; aceita inteiro fixo de 0 a 2147483647."]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"enable_prompt_expansion"}),": configurável; padrão ligado. No Kie vira ",e.jsx(t,{children:"prompt_extend"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Safety/NSFW: o schema WaveSpeed não aceita esse campo; o Kie fallback recebe sempre ",e.jsx(t,{children:"nsfw_checker: false"}),"."]}),e.jsx("p",{className:"text-muted-foreground",children:"• action_keys distinguem T2I/Edit, Base/Pro, 1K/2K e 1/2/3 inputs. Reserva pelo custo WaveSpeed; fallback Kie liquida pelo custo real menor."}),e.jsx("p",{className:"text-muted-foreground",children:"• Fallback só após recusa conclusiva antes de taskId. Timeout, rede, 5xx ou resposta ambígua permanecem no mesmo provider para evitar geração/cobrança dupla."}),e.jsx("p",{className:"text-muted-foreground",children:"• Sem LoRA, strength ou negative prompt."})]})]})})]}),e.jsxs(Se,{value:"kie-gpt-image-25",children:[e.jsx(Ae,{children:"GPT Image 2.5 — Flare e Sunburst"}),e.jsxs(Ee,{children:[e.jsxs("p",{className:"text-sm",children:["Playground, Flows, Social Post e API/MCP usam os modelos ",e.jsx(M,{children:"gpt-image-2-5-flare"})," e ",e.jsx(M,{children:"gpt-image-2-5-sunburst"})," pela função ",e.jsx(M,{children:"generate-gpt-image"}),". Referências selecionam automaticamente image-to-image; sem referências, text-to-image."]}),e.jsx("p",{className:"text-sm mt-2",children:"Resoluções 1K, 2K e 4K; até 16 referências HTTPS e 20.000 caracteres. Proporções: auto, 1:1, 3:2, 2:3, 16:9, 9:16, 4:3, 3:4, 21:9, 27:16, 16:27, 9:8 e 8:9. Retrato do Social Post usa 3:4, com opção de proporção personalizada."}),e.jsxs("p",{className:"text-sm mt-2",children:["Kie: USD 0,03 / 0,05 / 0,08 por imagem em 1K / 2K / 4K. Créditos calculados pelo catálogo e margem atuais; famílias ",e.jsx(M,{children:"gpt_image_2_5_flare"})," e ",e.jsx(M,{children:"gpt_image_2_5_sunburst"}),", com chaves separadas por modo e resolução. Não aplicar restrições legadas de GPT Image 2 ao 2.5."]})]})]}),e.jsxs(Se,{value:"kie-gpt-image-2",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xs,{className:"w-4 h-4 text-emerald-500"})," GPT Image 2 (OpenAI via Kie.AI)"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-gpt-image"})," · Submit + Poll · Modelo OpenAI próxima geração para imagens com tipografia nítida e edição precisa."]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Modo"}),e.jsx(f,{children:"Modelo Kie"}),e.jsx(f,{children:"action_key"}),e.jsx(f,{children:"Custo"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"Text-to-Image"}),e.jsx(a,{className:"text-xs",children:e.jsx(t,{children:"gpt-image-2-text-to-image"})}),e.jsx(a,{className:"text-xs",children:e.jsx(t,{children:"gpt_image_2"})}),e.jsx(a,{className:"text-xs",children:"$0.06 · 11 créditos"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Image-to-Image"}),e.jsx(a,{className:"text-xs",children:e.jsx(t,{children:"gpt-image-2-image-to-image"})}),e.jsx(a,{className:"text-xs",children:e.jsx(t,{children:"gpt_image_2_edit"})}),e.jsx(a,{className:"text-xs",children:"$0.06 · 11 créditos"})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Parâmetros & Limites"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Endpoint: ",e.jsx(t,{children:"https://api.kie.ai/api/v1/jobs/createTask"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Input: ",e.jsx(t,{children:"prompt"})," (obrig.), ",e.jsx(t,{children:"nsfw_checker"})," (true), ",e.jsx(t,{children:"input_urls"})," (até 16 imgs no I2I)"]}),e.jsx("p",{className:"text-muted-foreground",children:"• Formatos suportados: JPEG, PNG, WEBP. Tamanho máx. por arquivo: 30MB"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Decisão automática: presença de ",e.jsx(t,{children:"images"})," no body → roteia para o modelo image-to-image"]}),e.jsx("p",{className:"text-muted-foreground",children:"• Sem variantes de resolução, sem aspect_ratio explícito (segue o input)"}),e.jsx("p",{className:"text-muted-foreground",children:"• Refund automático em falhas Kie (incluindo bloqueio de moderação NSFW/policy)"})]})]})})]}),e.jsxs(Se,{value:"kie-grok-imagine",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xs,{className:"w-4 h-4 text-emerald-500"})," Grok Imagine 2.0 (xAI via Kie.AI)"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Edge Function ",e.jsx(M,{children:"generate-grok-imagine"})," · Submit + Poll · Roteamento automático T2I/I2I baseado na presença de imagens de referência."]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Modo"}),e.jsx(f,{children:"Modelo Kie"}),e.jsx(f,{children:"action_key"}),e.jsx(f,{children:"Custo"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"Text-to-Image"}),e.jsx(a,{className:"text-xs",children:e.jsx(t,{children:"grok-imagine-image-2-0/text-to-image"})}),e.jsx(a,{className:"text-xs",children:e.jsx(t,{children:"grok_imagine_t2i"})}),e.jsx(a,{className:"text-xs",children:"$0.020 · 4 créditos"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Image Edit (até 5 refs)"}),e.jsx(a,{className:"text-xs",children:e.jsx(t,{children:"grok-imagine-image-2-0/image-edit"})}),e.jsx(a,{className:"text-xs",children:e.jsx(t,{children:"grok_imagine_i2i"})}),e.jsx(a,{className:"text-xs",children:"$0.020 · 4 créditos"})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Parâmetros & Roteamento"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Endpoint: ",e.jsx(t,{children:"https://api.kie.ai/api/v1/jobs/createTask"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Roteamento: presença de ",e.jsx(t,{children:"references"})," > 0 → I2I, caso contrário → T2I"]}),e.jsx("p",{className:"text-muted-foreground",children:"• Aspect ratios suportados: 1:1, 2:3, 3:2, 16:9, 9:16"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Limite de referências I2I: ",e.jsx("strong",{children:"até 5 imagens"})," (limite oficial Kie: ",e.jsx(t,{children:"image_urls"})," aceita até 5 URLs — upload prévio para B2)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"nsfw_checker: false"})," sempre enviado no payload (desativa filtro NSFW da Kie)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"Triplo reforço de aspect ratio"})," (Kie I2I tende a herdar a proporção da referência e ignorar o campo ",e.jsx(t,{children:"aspect_ratio"}),"):"]}),e.jsxs("p",{className:"text-muted-foreground ml-3",children:["1️⃣ Campo ",e.jsx(t,{children:"aspect_ratio"})," enviado no payload"]}),e.jsxs("p",{className:"text-muted-foreground ml-3",children:["2️⃣ ",e.jsx("strong",{children:"Center-crop"})," automático da imagem de referência via ",e.jsx(t,{children:"imagescript"}
224)," antes do upload ao B2 (força a proporção alvo já no input)"]}),e.jsxs("p",{className:"text-muted-foreground ml-3",children:["3️⃣ ",e.jsx("strong",{children:"Hint no prompt"})," — sufixo ",e.jsx(t,{children:"[Output: vertical portrait 9:16 aspect ratio composition...]"})," anexado automaticamente ao final do prompt do usuário"]}),e.jsx("p",{className:"text-muted-foreground",children:"• Refund automático em falhas Kie (timeout, policy, bloqueios)"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Refs: ",e.jsx("a",{className:"underline",href:"https://docs.kie.ai/market/grok-imagine-image-2-0/text-to-image",target:"_blank",rel:"noreferrer",children:"T2I docs"})," · ",e.jsx("a",{className:"underline",href:"https://docs.kie.ai/market/grok-imagine-image-2-0/image-to-image",target:"_blank",rel:"noreferrer",children:"Image Edit docs"})]})]})]})})]}),e.jsxs(Se,{value:"ws-lora",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ui,{className:"w-4 h-4 text-purple-500"})," LoRA Training (Z-Image)"]})}),e.jsx(Ee,{children:e.jsx(El,{})})]})]})]}),e.jsxs("div",{className:"glass rounded-xl p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(oa,{className:"w-5 h-5 text-primary"}),e.jsx("h2",{className:"font-display font-bold text-xl",children:"OpenRouter"}),e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:"Ativo"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Base URL: ",e.jsx(M,{children:"https://openrouter.ai/api/v1"})," · Auth: ",e.jsx(M,{children:"Authorization: Bearer OPENROUTER_API_KEY"})," · Secret: ",e.jsx(M,{children:"OPENROUTER_API_KEY"})," (admin)"]}),e.jsxs(Ts,{type:"multiple",className:"w-full",children:[e.jsxs(Se,{value:"or-captions",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lt,{className:"w-4 h-4 text-orange-500"})," Geração de Captions (Grok 4)"]})}),e.jsx(Ee,{children:e.jsx(Rl,{})})]}),e.jsxs(Se,{value:"or-enhance",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(er,{className:"w-4 h-4 text-orange-500"})," Aprimorar Prompt — LoRA (Grok 4 Fast)"]})}),e.jsx(Ee,{children:e.jsx(Zt,{})})]})]})]}),e.jsx("div",{className:"glass rounded-xl p-6 space-y-4",children:e.jsx(Ts,{type:"multiple",className:"w-full",children:e.jsxs(Se,{value:"costs",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ra,{className:"w-4 h-4 text-primary"})," Custos por API — Referência para Precificação"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Modelo"}),e.jsx(f,{children:"Provedor"}),e.jsx(f,{children:"Custo/imagem"}),e.jsx(f,{children:"Imagens/$1"}),e.jsx(f,{children:"Obs."})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Nano Banana 2"}),e.jsx(a,{children:e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:"Google"})}),e.jsx(a,{className:"text-xs",children:"Gratuito*"}),e.jsx(a,{className:"text-xs",children:"∞"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"*Free tier: ~1500 req/dia"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Nano Banana Pro"}),e.jsx(a,{children:e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:"Google"})}),e.jsx(a,{className:"text-xs",children:"~$0.07–$0.14"}),e.jsx(a,{className:"text-xs",children:"7–14"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Requer plano pago"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Seedream 5.0 Pro"}),e.jsx(a,{children:e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:e.jsx(Fe,{code:"Provedor A"})})}),e.jsx(a,{className:"text-xs",children:"$0.035 (1K) / $0.07 (2K)"}),e.jsx(a,{className:"text-xs",children:"~29 / ~14"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Qualidade máxima, seletor 1K/2K"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Flux 2 Klein"}),e.jsx(a,{children:e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:e.jsx(Fe,{code:"Provedor B"})})}),e.jsx(a,{className:"text-xs font-semibold text-primary",children:"$0.008"}),e.jsx(a,{className:"text-xs",children:"125"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Ultra econômico"})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Z-Image Turbo"}),e.jsx(a,{children:e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:e.jsx(Fe,{code:"Provedor B"})})}),e.jsx(a,{className:"text-xs font-semibold text-primary",children:"$0.006"}),e.jsx(a,{className:"text-xs",children:"~166"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Sub-segundo. Suporta LoRA + Strength."})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"LoRA Training"}),e.jsx(a,{children:e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:e.jsx(Fe,{code:"Provedor B"})})}),e.jsx(a,{className:"text-xs font-semibold text-primary",children:"$1.25"}),e.jsx(a,{className:"text-xs",children:"—"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"125 créditos. Treino de personagem."})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Qwen Image 2"}),e.jsx(a,{children:e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:e.jsx(Fe,{code:"Provedor B"})})}),e.jsx(a,{className:"text-xs font-semibold text-primary",children:"$0.03"}),e.jsx(a,{className:"text-xs",children:"6"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Melhor renderização de texto. T2I + Edit."})]}),e.jsxs(b,{children:[e.jsx(a,{className:"font-medium",children:"Captions (Grok 4)"}),e.jsx(a,{children:e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:"OpenRouter"})}),e.jsx(a,{className:"text-xs",children:"~$0.05"}),e.jsx(a,{className:"text-xs",children:"~20"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"5 créditos/imagem. Visão multimodal."})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Notas"}),e.jsx("p",{className:"text-muted-foreground",children:"• Google: custo depende do plano do usuário. Usuário paga própria chave."}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(Fe,{code:"Provedor B"}),": custo fixo/imagem. Usuário paga própria chave."]}),e.jsx("p",{className:"text-muted-foreground",children:"• OpenRouter: custo admin (chave OPENROUTER_API_KEY do sistema)."}),e.jsx("p",{className:"text-muted-foreground",children:"• Batch de 4 = 4× custo."}),e.jsxs("p",{className:"text-muted-foreground",children:["• Fonte: pricing oficial do ",e.jsx(Fe,{code:"Provedor B"})," (verificar painel admin externo)"]})]})]})})]})})}),e.jsx("div",{className:"glass rounded-xl p-6 space-y-4",children:e.jsxs(Ts,{type:"multiple",className:"w-full",children:[e.jsxs(Se,{value:"architecture",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rr,{className:"w-4 h-4 text-primary"})," Arquitetura & Autenticação"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"API Keys por Usuário"}),e.jsxs("p",{className:"text-muted-foreground",children:["Tabela ",e.jsx(t,{children:"user_api_keys"}
224)," (providers: ",e.jsx(t,{children:"google_ai"}),", ",e.jsx(t,{children:"wavespeed"}),"). Edge Functions buscam via service role."]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Edge Functions"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsx(t,{children:"generate-seedance"})," · ",e.jsx(t,{children:"generate-kling-motion"})," · ",e.jsx(t,{children:"generate-video-wavespeed"})," · ",e.jsx(t,{children:"generate-wan27-video"})," · ",e.jsx(t,{children:"generate-happyhorse"})]}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsx(t,{children:"generate-image"})," · ",e.jsx(t,{children:"generate-image-wavespeed"})," · ",e.jsx(t,{children:"generate-video"})," · ",e.jsx(t,{children:"generate-gpt-image"})]}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsx(t,{children:"generate-faceswap"})," · ",e.jsx(t,{children:"generate-photoshoot"})," · ",e.jsx(t,{children:"generate-ugc"})]}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsx(t,{children:"generate-social-post"})," · ",e.jsx(t,{children:"generate-dataset"})]}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsx(t,{children:"inpaint-image"})," · ",e.jsx(t,{children:"upscale-image"})," · ",e.jsx(t,{children:"enhance-prompt"})]}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsx(t,{children:"train-lora"})," · ",e.jsx(t,{children:"generate-captions"})," · ",e.jsx(t,{children:"describe-image"})]}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsx(t,{children:"admin-create-user"})," · ",e.jsx(t,{children:"admin-list-emails"})," · ",e.jsx(t,{children:"cleanup-old-generations"})]}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsx(t,{children:"admin-cleanup-past-due"})," · ",e.jsx(t,{children:"admin-sync-stripe"})," · ",e.jsx(t,{children:"admin-delete-user"})]}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsx(t,{children:"stripe-webhook"})," · ",e.jsx(t,{children:"create-checkout"})," · ",e.jsx(t,{children:"buy-credits"})]}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsx(t,{children:"check-subscription"})," · ",e.jsx(t,{children:"customer-portal"})," · ",e.jsx(t,{children:"coupon-stats"})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Autenticação & Papéis"}),e.jsxs("p",{className:"text-muted-foreground",children:["Trigger ",e.jsx(t,{children:"handle_new_user"})," cria perfil + role ",e.jsx(t,{children:"user"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["Papéis: admin, moderator, user. Função ",e.jsx(t,{children:"has_role()"}),"."]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Base URLs"}),e.jsxs("p",{className:"text-muted-foreground",children:["Google: ",e.jsx(t,{children:"generativelanguage.googleapis.com/v1beta"})]}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsx(Fe,{code:"Provedor B"}),": ",e.jsxs(t,{children:["(API do ",e.jsx(Fe,{code:"Provedor B"}),")"]})]})]})]})})]}),e.jsxs(Se,{value:"b2-storage",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sr,{className:"w-4 h-4 text-primary"})," Armazenamento Backblaze B2"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Estrutura de Pastas"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs(t,{children:["{user_id}","/images/"]})," — Imagens geradas"]}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs(t,{children:["{user_id}","/videos/"]})," — Vídeos gerados"]}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs(t,{children:["{user_id}","/references/"]}
224)," — Refs do usuário"]}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs(t,{children:["{user_id}","/presets/"]})," — Presets"]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Secrets"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsx(t,{children:"B2_KEY_ID"})," · ",e.jsx(t,{children:"B2_APP_KEY"})," · ",e.jsx(t,{children:"B2_BUCKET_NAME"})," · ",e.jsx(t,{children:"B2_ENDPOINT"})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Fluxo de Upload"}),e.jsxs("p",{className:"text-muted-foreground",children:["1. ",e.jsx(t,{children:"b2_authorize_account"})," → 2. ",e.jsx(t,{children:"b2_get_upload_url"})," → 3. ",e.jsx(t,{children:"b2_upload_file"})," c/ SHA-1"]}),e.jsx("p",{className:"text-muted-foreground",children:"Retries: 3x com backoff. Timeout: 180s."})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Refs & Presets"}),e.jsxs("p",{className:"text-muted-foreground",children:["URLs na coluna ",e.jsx(t,{children:"reference_images"})," da tabela ",e.jsx(t,{children:"generations"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["Presets em ",e.jsx(t,{children:"preset_images"}),". Proxy via ",e.jsx(t,{children:"proxy-image"})," (bypass CORS)."]})]})]})})]})]})}),e.jsxs("div",{className:"glass rounded-xl p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(qi,{className:"w-5 h-5 text-emerald-500"}),e.jsx("h2",{className:"font-display font-bold text-xl",children:"Pipeline de Otimização de Imagens"}),e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:"Implementado · Abril 2026"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed",children:["Sistema completo de otimização, mascaramento de domínio e proteção anti-cópia para todas as imagens exibidas na plataforma. Reduz egress, acelera o carregamento de galerias e mantém o branding consistente. Pipeline: ",e.jsx(M,{children:"B2 → cdn.aiclubstudio.com → img.aiclubstudio.com (Worker) → wsrv.nl → navegador"})]}),e.jsxs("div",{className:"bg-emerald-500/10 border border-emerald-500/30 rounded-lg p-3 text-xs text-emerald-400",children:[e.jsx("strong",{children:"Resumo:"})," Toda thumbnail/preview da galeria agora é servida em WebP otimizado, via domínio próprio ",e.jsx(t,{children:"img.aiclubstudio.com"}),", com proteção contra clique-direito e drag. O arquivo original em B2 permanece intacto para downloads em qualidade total."]}),e.jsxs(Ts,{type:"multiple",className:"w-full",children:[e.jsxs(Se,{value:"img-overview",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"w-4 h-4 text-emerald-500"})," Visão Geral & Arquitetura"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Problema resolvido"}),e.jsx("p",{className:"text-muted-foreground",children:"• Galerias carregavam PNGs originais (1-5MB cada) → lentidão massiva e altos custos de banda"}),e.jsx("p",{className:"text-muted-foreground",children:"• Sem proteção: usuários conseguiam baixar imagens via clique-direito e inspecionar URLs"}),e.jsx("p",{className:"text-muted-foreground",children:"• Domínio do proxy de otimização ficava exposto na barra de endereço"})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Solução implementada"}),e.jsxs("p",{className:"text-muted-foreground",children:["1. ",e.jsx("strong",{children:"Otimização on-the-fly"}),": wsrv.nl converte para WebP com qualidade adaptativa por tamanho"]}),e.jsxs("p",{className:"text-muted-foreground",children:["2. ",e.jsx("strong",{children:"Mascaramento de domínio"}),": Cloudflare Worker em ",e.jsx(t,{children:"img.aiclubstudio.com"})," proxia o wsrv invisivelmente"]}),e.jsxs("p",{className:"text-muted-foreground",children:["3. ",e.jsx("strong",{children:"Proteção anti-cópia"}),": bloqueio de menu de contexto, drag, seleção e long-press em todas as imagens"]}),e.jsxs("p",{className:"text-muted-foreground",children:["4. ",e.jsx("strong",{children:"Originais preservados"}),": download sempre busca o arquivo full do B2/CDN"]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Resultados"}),e.jsx("p",{className:"text-muted-foreground",children:"• Redução de ~85-95% no peso transferido (PNG 2MB → WebP 50-200KB)"}),e.jsx("p",{className:"text-muted-foreground",children:"• Cache de 24h na borda Cloudflare → galerias instantâneas em re-visitas"}),e.jsx("p",{className:"text-muted-foreground",children:"• Custo: $0/mês (free tier do Cloudflare Workers cobre 100k req/dia)"}),e.jsx("p",{className:"text-muted-foreground",children:"• Branding 100% consistente — wsrv.nl nunca aparece pro usuário"})]})]})})]}),e.jsxs(Se,{value:"img-frontend",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ra,{className:"w-4 h-4 text-blue-500"})," Camada 1 — Frontend (cdnImage.ts)"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Arquivo: ",e.jsx(M,{children:"src/lib/cdnImage.ts"})," · Helper central que constrói URLs otimizadas para todo o app."]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Função"}),e.jsx(f,{children:"O que faz"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"cdnImage(url, width, q?)"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"URL otimizada single-size em WebP. Quality adaptativa se omitid
224a."})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"cdnSrcSet(url, widths)"})}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Gera ",e.jsx(t,{children:"srcset"})," responsivo com 9 breakpoints (160-1920px)."]})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"isTransformable(url)"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Verifica se URL pode ser proxiada (CDN próprio ou Supabase Storage)."})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Quality adaptativa por tamanho"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ≤ 200px → ",e.jsx(t,{children:"q=72"})," (micro thumbs em listas)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ≤ 480px → ",e.jsx(t,{children:"q=80"})," (cards de galeria)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ≤ 900px → ",e.jsx(t,{children:"q=85"})," (preview médio)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• > 900px → ",e.jsx(t,{children:"q=90"})," (lightbox / fullscreen)"]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Configuração de host"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Default: ",e.jsx(t,{children:"img.aiclubstudio.com"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Override: variável ",e.jsx(t,{children:"VITE_IMG_PROXY_HOST"})," (ex: ",e.jsx(t,{children:"wsrv.nl"})," para debug local)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Formato URL final: ",e.jsx(t,{children:"https://{HOST}/?url={ENCODED}&w={WIDTH}&q={Q}&output=webp"})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Hosts transformáveis"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"cdn.aiclubstudio.com"})," (Backblaze B2 via CDN)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Qualquer URL contendo ",e.jsx(t,{children:"/storage/v1/object/public/"})," (Supabase Storage)"]}),e.jsx("p",{className:"text-muted-foreground",children:"• Outros domínios passam direto sem otimização (avatares de terceiros, etc.)"})]})]})})]}),e.jsxs(Se,{value:"img-components",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ma,{className:"w-4 h-4 text-purple-500"})," Camada 2 — Componentes Atualizados"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Componente"}),e.jsx(f,{children:"Função"}),e.jsx(f,{children:"Otimização aplicada"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"ThumbnailImage.tsx"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Cards da galeria principal"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"srcset + lazy load + cache + retry"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"ImageDisplay.tsx"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Preview pós-geração"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"cdnImage com width 900-1280"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"CommunityGallery.tsx"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Galeria pública da comunidade"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"srcset + proteção anti-cópia"})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Proteções aplicadas em todos os componentes"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsxs(t,{children:["onContextMenu=","{e => e.preventDefault()}"]}),' — bloqueia menu de "Salvar imagem como..."']}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsxs(t,{children:["draggable=","{false}"]})," — impede arrastar pra desktop ou nova aba"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"user-select: none"})," + ",e.jsx(t,{children:"WebkitTouchCallout: none"})," — bloqueia long-press no mobile"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"WebkitUserSelect: none"})," — Safari iOS"]})]}),e.jsxs("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-3 text-xs text-yellow-400",children:[e.jsx("strong",{children:"Importante:"}),' Essas proteções são "fricção" — bloqueiam ~95% dos usuários casuais. Usuários técnicos sempre conseguem baixar imagens via aba Network do DevTools (limitação inerente do HTML). Para proteção real, seria necessário DRM ou watermarking (não implementado).']})]})})]}),e.jsxs(Se,{value:"img-wsrv",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"w-4 h-4 text-cyan-500"})," Camada 3 — Proxy wsrv.nl (upstream)"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("strong",{children:"wsrv.nl"})," é um serviço gratuito e ilimitado de otimização de imagens, usado por milhares de sites em produção. Atua como upstream do nosso Worker — nunca exposto diretamente ao usuário."]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Parâmetro"}),e.jsx(f,{children:"Valor"}),e.jsx(f,{children:"Função"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"url"})}),e.jsx(a,{className:"text-xs",children:e.jsx(t,{children:"encodeURIComponent(originalUrl)"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"URL completa (com https) URL-encoded"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"w"})}),e.jsx(a,{className:"text-xs",children:"160-1920"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Largura do output em px"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"q"})}),e.jsx(a,{className:"text-xs",children:"72-90"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Quality adaptativa"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"output"})}),e.jsx(a,{className:"text-xs",children:e.jsx(t,{children:"webp"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Formato fixo — melhor compressão"})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Por que wsrv.nl ao invés de salvar thumbs no B2?"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"Zero storage extra"}),": sem arquivos derivados ocupando espaço"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"Zero egress"}),": wsrv serve do CDN próprio"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"Funciona retroativamente"}),": todas as imagens existentes ficam otimizadas instantaneamente"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"Flexibilidade total"}
224),": mudamos size/quality apenas trocando params da URL"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"Original intocado"}),": arquivo no B2 permanece em qualidade total para download"]})]})]})})]}),e.jsxs(Se,{value:"img-worker",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($a,{className:"w-4 h-4 text-orange-500"})," Camada 4 — Cloudflare Worker (mascaramento)"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Worker hospedado em ",e.jsx(M,{children:"img.aiclubstudio.com"})," — recebe requisições do frontend e faz proxy reverso para o wsrv.nl. O usuário final vê apenas o domínio próprio, sem nenhuma menção ao wsrv."]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Configuração no painel Cloudflare"}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Item"}),e.jsx(f,{children:"Valor"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:"Nome do Worker"}),e.jsx(a,{children:e.jsx(M,{children:"img-aiclubstudio"})})]}),e.jsx(a,{colSpan:2,className:"p-0"}),e.jsxs(b,{children:[e.jsx(a,{children:"Custom Domain"}),e.jsx(a,{children:e.jsx(M,{children:"img.aiclubstudio.com"})})]}),e.jsxs(b,{children:[e.jsx(a,{children:"DNS Type"}),e.jsxs(a,{children:[e.jsx(M,{children:"Worker"})," (auto-criado pela CF)"]})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Proxy Status"}),e.jsx(a,{children:"🟧 Proxied (obrigatório)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"SSL"}),e.jsx(a,{children:"Provisionado automaticamente"})]}),e.jsxs(b,{children:[e.jsx(a,{children:"Cache na borda"}),e.jsxs(a,{children:["24h (",e.jsx(t,{children:"cacheTtl: 86400"}),")"]})]})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Código do Worker (versão atual)"}),e.jsx("pre",{className:"bg-background/70 rounded p-3 overflow-x-auto text-[10px] leading-relaxed text-muted-foreground",children:`export default {
225  async fetch(request) {
226    const url = new URL(request.url);
227
228    // Favicon: serve do domínio principal pra evitar ícone do wsrv
229    if (url.pathname === '/favicon.ico' || url.pathname === '/favicon.png') {
230      return fetch('https://aiclubstudio.com/favicon.png', {
231        cf: { cacheTtl: 86400, cacheEverything: true },
232      });
233    }
234
235    // Bloqueia requisições sem ?url= (acessos diretos)
236    if (!url.searchParams.has('url')) {
237      return new Response('Not Found', { status: 404 });
238    }
239
240    const target = \`https://wsrv.nl\${url.pathname}\${url.search}\`;
241    const response = await fetch(target, {
242      headers: { 'User-Agent': 'Mozilla/5.0 (compatible; AIClubStudio/1.0)' },
243      cf: { cacheTtl: 86400, cacheEverything: true },
244    });
245
246    const newHeaders = new Headers(response.headers);
247    newHeaders.set('Cache-Control', 'public, max-age=86400, immutable');
248    newHeaders.set('Access-Control-Allow-Origin', '*');
249
250    return new Response(response.body, {
251      status: response.status,
252      statusText: response.statusText,
253      headers: newHeaders,
254    });
255  },
256};`})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Recursos do Worker"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"Proxy transparente"}),": repassa path + query string idênticos ao wsrv"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"Cache agressivo"}),": ",e.jsx(t,{children:"cacheEverything: true"})," + 24h TTL na borda CF"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"Cache no navegador"}),": ",e.jsx(t,{children:"max-age=86400, immutable"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"CORS livre"}),": ",e.jsx(t,{children:"Access-Control-Allow-Origin: *"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"Favicon próprio"}),": serve ",e.jsx(t,{children:"aiclubstudio.com/favicon.png"})," ao invés do wsrv"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx("strong",{children:"Bloqueio de scraping"}),": requisições sem ",e.jsx(t,{children:"?url="})," retornam 404"]})]}),e.jsxs("div",{className:"bg-blue-500/10 border border-blue-500/30 rounded-lg p-3 text-xs text-blue-400",children:[e.jsx("strong",{children:"Custo:"})," Free tier do Cloudflare Workers permite ",e.jsx("strong",{children:"100.000 requisições/
256dia gratuitas"}),". Estimativa atual: ~5-15k req/dia → confortavelmente dentro do free tier por anos."]})]})})]}),e.jsxs(Se,{value:"img-stepbystep",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(er,{className:"w-4 h-4 text-pink-500"})," Procedimento de Setup (passo a passo)"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Roteiro completo para reproduzir/ressetar o setup em outro domínio ou conta Cloudflare."}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"1. Criar o Cloudflare Worker"}),e.jsxs("p",{className:"text-muted-foreground",children:["a) Acessar ",e.jsx(t,{children:"dash.cloudflare.com"})," → Workers & Pages"]}),e.jsxs("p",{className:"text-muted-foreground",children:["b) Clicar em ",e.jsx(t,{children:"Create"})," → ",e.jsx(t,{children:"Create Worker"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["c) Escolher ",e.jsx(t,{children:"Start with Hello World!"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["d) Nomear como ",e.jsx(t,{children:"img-aiclubstudio"})," → Deploy"]}),e.jsxs("p",{className:"text-muted-foreground",children:["e) Clicar em ",e.jsx(t,{children:"Edit code"}),", apagar tudo e colar o código da seção anterior"]}),e.jsx("p",{className:"text-muted-foreground",children:"f) Save and Deploy"})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"2. Conectar o Custom Domain"}),e.jsxs("p",{className:"text-muted-foreground",children:["a) No Worker → Settings → Domains & Routes → ",e.jsx(t,{children:"+ Add"})," → ",e.jsx(t,{children:"Custom Domain"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["b) Digitar ",e.jsx(t,{children:"img.aiclubstudio.com"})," → Add Domain"]}),e.jsx("p",{className:"text-muted-foreground",children:'c) Cloudflare cria o DNS automaticamente (tipo "Worker", Proxied)'}),e.jsx("p",{className:"text-muted-foreground",children:"d) SSL provisionado em ~30s a 2min"}),e.jsxs("p",{className:"text-muted-foreground",children:["⚠️ Se houver registro AAAA antigo (",e.jsx(t,{children:"100::"}),") em ",e.jsx(t,{children:"img"}),", deletar antes"]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"3. Validar o pipeline"}),e.jsx("p",{className:"text-muted-foreground",children:"Acessar no navegador:"}),e.jsx("pre",{className:"bg-background/70 rounded p-2 text-[10px] overflow-x-auto text-muted-foreground",children:"https://img.aiclubstudio.com/?url=https://cdn.aiclubstudio.com/{path-real}.png&w=400&output=webp"}),e.jsx("p",{className:"text-muted-foreground",children:"Deve exibir a imagem otimizada com o domínio próprio na barra."})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"4. Ativar no frontend"}),e.jsxs("p",{className:"text-muted-foreground",children:["O default em ",e.jsx(t,{children:"cdnImage.ts"})," já é ",e.jsx(t,{children:"img.aiclubstudio.com"}),"."]}),e.jsxs("p",{className:"text-muted-foreground",children:["Para forçar host alternativo (debug): definir ",e.jsx(t,{children:"VITE_IMG_PROXY_HOST"})," no projeto."]})]})]})})]}),e.jsxs(Se,{value:"img-troubleshooting",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rr,{className:"w-4 h-4 text-red-500"})," Troubleshooting"]})}),e.jsx(Ee,{children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Sintoma"}),e.jsx(f,{children:"Causa provável"}),e.jsx(f,{children:"Solução"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{className:"text-xs",children:"Imagens não carregam (404 em todas)"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Worker fora do ar ou DNS quebrado"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Acessar Worker no painel CF, verificar deploy. Trocar VITE_IMG_PROXY_HOST=wsrv.nl temporariamente."})]}),e.jsxs(b,{children:[e.jsx(a,{className:"text-xs",children:"404 só em algumas imagens"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Arquivo original deletado do B2"}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Verificar URL original em ",e.jsx(t,{children:"cdn.aiclubstudio.com"}),". Se não existir, problema é no B2."]})]}),e.jsxs(b,{children:[e.jsxs(a,{className:"text-xs",children:["Favicon errado n
256a aba do ",e.jsx(t,{children:"img.aiclubstudio.com"})]}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Cache do navegador OU favicon principal incorreto"}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Garantir ",e.jsx(t,{children:"aiclubstudio.com/favicon.png"})," está acessível. Forçar reload com Ctrl+Shift+R."]})]}),e.jsxs(b,{children:[e.jsx(a,{className:"text-xs",children:"Galeria lenta apesar do WebP"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Cache CF não está hitando"}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Inspecionar header ",e.jsx(t,{children:"cf-cache-status"}),". Deve ser HIT após primeira req."]})]}),e.jsxs(b,{children:[e.jsx(a,{className:"text-xs",children:'Botão direito ainda mostra "Salvar"'}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Componente sem ",e.jsx(t,{children:"onContextMenu"})]}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Adicionar handler conforme padrão de ",e.jsx(t,{children:"ThumbnailImage.tsx"}),"."]})]}),e.jsxs(b,{children:[e.jsx(a,{className:"text-xs",children:"Erro CORS no console"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Worker sem header CORS"}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Verificar que ",e.jsx(t,{children:"Access-Control-Allow-Origin: *"})," está sendo setado."]})]})]})]})})]}),e.jsxs(Se,{value:"img-files",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sr,{className:"w-4 h-4 text-amber-500"})," Arquivos & Recursos"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Código no projeto"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"src/lib/cdnImage.ts"})," — Helper central de URLs otimizadas"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"src/components/ThumbnailImage.tsx"})," — Cards de galeria com lazy/retry"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"src/components/ImageDisplay.tsx"})," — Preview pós-geração"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"src/components/CommunityGallery.tsx"})," — Galeria pública"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"public/favicon.png"})," — Logo servido no domínio principal e proxy de favicon do Worker"]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Recursos externos"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Cloudflare Workers: ",e.jsx(t,{children:"dash.cloudflare.com"})," → Workers & Pages → ",e.jsx(t,{children:"img-aiclubstudio"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• wsrv.nl docs: ",e.jsx(t,{children:"https://wsrv.nl/docs"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• B2/CDN setup: ",e.jsx(t,{children:"public/docs/cloudflare-b2-setup.md"})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Variáveis de ambiente"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"VITE_IMG_PROXY_HOST"})," (opcional) — sobrescreve host do proxy. Default: ",e.jsx(t,{children:"img.aiclubstudio.com"})]})]})]})})]})]})]}),e.jsxs("div",{className:"glass rounded-xl p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Vi,{className:"w-5 h-5 text-fuchsia-500"}),e.jsx("h2",{className:"font-display font-bold text-xl",children:"Camuflagem de Provider Names (white-label F12)"}),e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:"Implementado · Maio 2026"})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Todas as chamadas de geração e armazenamento são roteadas por endpoints neutros pra esconder os nomes reais dos providers (kie.ai, WaveSpeed, OpenRouter, Backblaze B2, etc.) no Network tab do navegador. Plus 2 Cloudflare Transform Rules na zona principal pra resolver CORS e remover headers nativos B2 das respostas da CDN."}),e.jsxs("div",{className:"bg-fuchsia-500/10 border border-fuchsia-500/30 rounded-lg p-3 text-xs text-fuchsia-400",children:[e.jsx("strong",{children:"Pipeline:"})," Frontend chama ",e.jsx(t,{children:"/generate-asset"})," + ",e.jsx(t,{children:'op: "gen-iN/gen-vN"'})," → dispatcher server-side mapeia pro real edge fn → response volta sem leak. Uploads via ",e.jsx(t,{children:"/media-upload"}),", deletes via ",e.jsx(t,{children:"/media-delete"}),"."]}),e.jsxs(Ts,{type:"multiple",className:"w-full",children:[e.jsxs(Se,{value:"cam-overview",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jt,{className:"w-4 h-4 text-fuchsia-500"})," Visão Geral & Motivação"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Problema resolvido"}),e.jsxs("p",{className:"text-muted-foreground",children:["• F12 → Network mostrava nomes dos providers em cada invoke: ",e.jsx(t,{children:"/generate-image-wavespeed"}),", ",e.jsx(t,{children:"/generate-nano-banana"}),", ",e.jsx(t,{children:"/generate-kling-video"}),", etc."]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"/upload-to-b2"})," e ",e.jsx(t,{children:"/delete-from-b2"})," vazavam o storage backend (Backblaze B2)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Response headers da CDN incluíam ",e.jsx(t,{children:"X-Bz-*"})," nativos do Backblaze"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Download direto no ",e.jsx(t,{children:"downloadMedia.ts"})," dava CORS error vermelho no console (tinha fallback, mas poluía)"]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Solução em 3 camadas"}),e.jsxs("p",{className:"text-muted-foreground",children:["1. ",e.jsx("strong",{children:"Dispatcher único"}),": edge fn ",e.jsx(t,{children:"generate-asset"})," proxia internamente pras 14 fns provider-named"]}),e.jsxs("p",{className:"text-muted-foreground",children:["2. ",e.jsx("strong",{children:"Rename B2"}),": ",e.jsx(t,{children:"upload-to-b2"})," → ",e.jsx(t,{children:"media-upload"}),", ",e.jsx(t,{children:"delete-from-b2"})," → ",e.jsx(t,{children:"media-delete"})," (legacy continuam deployadas como safety net)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["3. ",e.jsx("strong",{children:"Cloudflare Transform Rules"})," na zona ",e.jsx(t,{children:"aiclubstudio.com"})," adicionam ",e.jsx(t,{children:"Access-Control-Allow-Origin: *"})," e removem todos headers ",e.jsx(t,{children:"X-Bz-*"})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Resultados"}),e.jsxs("p",{className:"text-muted-foreground",children:["• User curioso abrindo F12 vê SÓ ",e.jsx(t,{children:"/generate-asset"})," + ",e.jsx(t,{children:'op: "gen-iN"'})," opaco"]}),e.jsx("p",{className:"text-muted-foreground",children:"• Zero menção a kie/WaveSpeed/Nano Banana/Kling/Grok/Seedance/Veo/etc. no Network tab"}),e.jsx("p",{className:"text-muted-foreground",children:"• Response headers limpos — sem X-Bz-Content-Sha1/File-Id/File-Name/Upload-Timestamp"}),e.jsx("p",{className:"text-muted-foreground",children:"• Custo: $0/mês (Cloudflare Free permite até 10 Transform Rules)"})]}),e.jsxs("div",{className:"bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-3 text-xs text-yellow-400",children:[e.jsx("strong",{children:"Importante:"}),' Camuflagem é "fricção visual" — bloqueia 95% dos users casuais. Devs determinados ainda podem correlacionar resposta com provider via formato de taskId, timing, ou inspeção do binário. Pra ofuscação real seria necessário mascarar tudo (timings/IDs/etc.), fora de escopo. Admin via painel continua vendo nomes reais (per white-label rule).']})]})})]}
256),e.jsxs(Se,{value:"cam-dispatcher",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($a,{className:"w-4 h-4 text-blue-500"})," Camada 1 — Dispatcher ",e.jsx(M,{children:"generate-asset"})]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Edge function ",e.jsx(M,{children:"supabase/functions/generate-asset/index.ts"})," — proxy thin sem business logic. Recebe body com ",e.jsx(t,{children:"op"})," opaco, mapeia pra edge fn real via ",e.jsx(t,{children:"OP_MAP"}),", faz ",e.jsx(t,{children:"fetch()"}),"interno forwardando ",e.jsx(t,{children:"Authorization"})," + ",e.jsx(t,{children:"apikey"})," headers, retorna response. Aplica scrub regex em ",e.jsx(t,{children:"error"}),"/",e.jsx(t,{children:"errorMessage"})," pra remover provider tokens."]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-2",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"OP_MAP — opaque op → real edge fn"}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"op"}),e.jsx(f,{children:"Edge fn real"}),e.jsx(f,{children:"Provider"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-i1"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-image-wavespeed"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"WaveSpeed (z-image/qwen/seedream/flux-klein)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-i2"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-nano-banana"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"kie.ai (Nano Banana)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-i3"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-gpt-image"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"kie.ai (GPT Image 2)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-i4"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-grok-imagine"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"kie.ai (Grok Imagine 2.0)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-i5"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-happyhorse"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"kie.ai (HappyHorse 1.0)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-i6"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-wan-image"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"kie.ai (WAN 2.7 Image)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-i7"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-qwen3-image"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"WaveSpeed principal · Kie fallback (Nano Unlocked 2)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-v1"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-kling-motion"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"kie.ai (Kling Motion Control)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-v2"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-kling-video"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"kie.ai (Kling Video)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-v3"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-gemini-omni"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"kie.ai (Gemini Omni)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-v4"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-seedance"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"kie.ai (Seedance 2.0)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-v5"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-video-wavespeed"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"WaveSpeed (WAN 2.2 Hot)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-v6"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-ltx-video"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"WaveSpeed (LTX 2.3 Hot · spicy)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-v7"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-wan27-video"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"kie.ai (WAN 2.7 Video)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-v10"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-wan30-video"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Kie (WAN 3.0 / Prime) · RunningHub somente histórico"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"gen-v8"})}),e.jsx(a,{children:e.jsx(M,{children:"generate-video"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Google AI (Veo)"})]})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"font-semibold text-foreground",children:["Frontend helper — ",e.jsx(M,{children:"src/lib/edgeRouter.ts"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"FN_TO_OP"})," map (espelho de OP_MAP do server)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"routeFn(fn, body)"})," → translator transparente (fall-through se fn não tá no map)"]}
256),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"invokeFn(fn, opts)"})," → drop-in wrapper pra ",e.jsx(t,{children:"supabase.functions.invoke"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"useImageQueue"})," / ",e.jsx(t,{children:"useVideoQueue"})," / ",e.jsx(t,{children:"useSwapQueue"}),": ",e.jsx(t,{children:"invokeEdge*"})," wrappers plugados em ",e.jsx(t,{children:"routeFn"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"useVideoGeneration.ts"})," + ",e.jsx(t,{children:"ImageEditor.tsx"})," + ",e.jsx(t,{children:"SocialPostPanel.tsx"}),": direct invokes convertidos pra ",e.jsx(t,{children:"invokeFn"})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Scrub de provider tokens"}),e.jsxs("p",{className:"text-muted-foreground",children:["Regex aplicado APENAS em ",e.jsx(t,{children:"error"})," e ",e.jsx(t,{children:"errorMessage"})," da response. URLs/IDs/metadata passam intactos."]}),e.jsxs("p",{className:"text-muted-foreground",children:["Tokens scrubados: ",e.jsx(t,{children:"wavespeed"}),", ",e.jsx(t,{children:"kie.ai"}),", ",e.jsx(t,{children:"openrouter"}),", ",e.jsx(t,{children:"backblaze"}),", ",e.jsx(t,{children:"b2"}),", ",e.jsx(t,{children:"nano-banana"}),", ",e.jsx(t,{children:"kling"}),", ",e.jsx(t,{children:"seedance"}),", ",e.jsx(t,{children:"grok"}),", ",e.jsx(t,{children:"gpt-image"}),", ",e.jsx(t,{children:"gemini"}),", ",e.jsx(t,{children:"veo"}),", ",e.jsx(t,{children:"flux"}),", ",e.jsx(t,{children:"qwen"}),", ",e.jsx(t,{children:"seedream"}),", ",e.jsx(t,{children:"happyhorse"}),", ",e.jsx(t,{children:"ltx"}),", ",e.jsx(t,{children:"wan"}),", ",e.jsx(t,{children:"z-image-turbo"}),"."]})]})]})})]}),e.jsxs(Se,{value:"cam-media",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sr,{className:"w-4 h-4 text-purple-500"})," Camada 2 — Rename ",e.jsx(M,{children:"media-upload"})," / ",e.jsx(M,{children:"media-delete"})]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Antes"}),e.jsx(f,{children:"Depois"}),e.jsx(f,{children:"Função"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"upload-to-b2"})}),e.jsx(a,{children:e.jsx(M,{children:"media-upload"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Upload de imagens/vídeos pro B2 (refs, presets, avatars, character sheets, etc.)"})]}),e.jsxs(b,{children:[e.jsx(a,{children:e.jsx(M,{children:"delete-from-b2"})}),e.jsx(a,{children:e.jsx(M,{children:"media-delete"})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Delete de assets B2 + DB row de gerações"})]})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Estratégia de migração"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Novas fns são ",e.jsx("strong",{children:"cópias exatas"})," das antigas (helpers ",e.jsx(t,{children:"b2-upload.ts"}),", ",e.jsx(t,{children:"error-logger.ts"}),", ",e.jsx(t,{children:"thumbnail.ts"})," bundleados flatten no deploy)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Legacy ",e.jsx(t,{children:"upload-to-b2"})," e ",e.jsx(t,{children:"delete-from-b2"})," ",e.jsx("strong",{children:"continuam deployadas"})," como safety net — sem tráfego do frontend"]}),e.jsx("p",{className:"text-muted-foreground",children:"• 14 arquivos frontend atualizados pra apontar pros nomes novos (hooks + panels + Video.tsx)"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"AdminDatabaseTab.tsx"})," ainda lista os nomes antigos — admin pode ver, ok"]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Hard rule"}),e.jsxs("p",{className:"text-muted-foreground",children:["Toda feature nova que precisa B2 storage ",e.jsx("strong",{children:"tem que"})," chamar ",e.jsx(t,{children:"media-upload"})," / ",e.jsx(t,{children:"media-delete"}),". NUNCA ",e.jsx(t,{children:"upload-to-b2"})," / ",e.jsx(t,{children:"delete-from-b2"})," direto. Ver memory ",e.jsx(t,{children:"storage_rules.md"})," RULE 4."]})]})]})})]}),e.jsxs(Se,{value:"cam-cloudflare",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Dr,{className:"w-4 h-4 text-orange-500"})," Camada 3 — Cloudflare Transform Rules"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Zone ",e.jsx(M,{children:"aiclubstudio.com"})," (id ",e.jsx(M,{children:"bcc17875727088aacb339b1c28db2024"}),") → ruleset ",e.jsx(M,{children:"http_response_headers_transform"}),"(id ",e.jsx(M,{children:"35ed0adab53f49ca891c5cf34405e620"}),") tem 3 rules ativas:"]}),e.jsx("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-2",children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Rule"}),e.jsx(f,{children:"Expression"}),e.jsx(f,{children:"Ação"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsxs(a,{className:"text-xs",children:["Immutable media cache ",e.jsx("span",{className:"text-muted-foreground",children:"(pré-existente)"})]}),e.jsx(a,{className:"text-xs",children:e.jsx(t,{children:'http.host eq "cdn.aiclubstudio.com"'})}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Set ",e.jsx(t,{children:"Cache-Control: public, max-age=31536000, immutable"})]})]}),e.jsxs(b,{children:[e.jsxs(a,{className:"text-xs",children:["CORS allow for CDN media ",e.jsx("span",{className:"text-fuchsia-400",children:"(nova)"})]}),e.jsx(a,{className:"text-xs",children:e.jsx(t,{children:'http.host eq "cdn.aiclubstudio.com"'})}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Set ",e.jsx(t,{children:"Access-Control-Allow-Origin: *"})]})]}),e.jsxs(b,{children:[e.jsxs(a,{className:"text-xs",children:["Strip B2 origin headers ",e.jsx("span",{className:"text-fuchsia-400",children:"(nova)"})]}),e.jsx(a,{className:"text-xs",children:e.jsx(t,{children:'http.host eq "cdn.aiclubstudio.com"'})}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Remove ",e.jsx(t,{children:"X-Bz-Content-Sha1"}),", ",e.jsx(t,{children:"X-Bz-File-Id"}),", ",e.jsx(t,{children:"X-Bz-File-Name"}),", ",e.jsx(t,{children:"X-Bz-Upload-Timestamp"})]})]})]})]})}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Por que CORS allow?"}),e.jsxs("p",{className:"text-muted-foreground",children:["Em ",e.jsx(t,{children:"src/lib/downloadMedia.ts:39"})," o código tenta ",e.jsx(t,{children:"fetch()"})," direto da CDN. Sem header CORS, browser bloqueava → fallback automático pro ",e.jsx(t,{children:"proxy-image"})," (que funciona mas adiciona um hop). Com a rule, direct fetch funciona limpo, console sem erro vermelho, download ~30% mais rápido."]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Por que str
256ip X-Bz-*?"}),e.jsxs("p",{className:"text-muted-foreground",children:["Cloudflare passa por default os headers nativos do Backblaze B2 (",e.jsx(t,{children:"X-Bz-Content-Sha1"}),", ",e.jsx(t,{children:"X-Bz-File-Id"}),", etc). Esses headers vazam o provider de storage pra quem expande response headers no DevTools."]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Como criar/editar (CLI via API token)"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Endpoint: ",e.jsxs(t,{children:["POST https://api.cloudflare.com/client/v4/zones/","{ZONE_ID}","/rulesets/","{RULESET_ID}","/rules"]})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Token scope necessário: ",e.jsx(t,{children:"Zone → Transform Rules → Edit"})," + ",e.jsx(t,{children:"Zone → Zone → Read"})]}),e.jsx("p",{className:"text-muted-foreground",children:"• Limite Cloudflare Free: até 10 Transform Rules totais por zona"})]})]})})]}),e.jsxs(Se,{value:"cam-add-provider",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(er,{className:"w-4 h-4 text-emerald-500"})," Como adicionar uma fn provider nova"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Checklist completo quando adicionar nova edge fn de geração (ex: ",e.jsx(M,{children:"generate-novo-provider"}),"):"]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"1. Deploy normal da fn nova"}),e.jsxs("p",{className:"text-muted-foreground",children:["Cria ",e.jsx(t,{children:"supabase/functions/generate-novo-provider/index.ts"})," seguindo o padrão (auth check, submit+poll, taskId, etc.). Deploy via MCP ou CLI."]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"font-semibold text-foreground",children:["2. Adiciona entrada no ",e.jsx(t,{children:"OP_MAP"})," server-side"]}),e.jsxs("p",{className:"text-muted-foreground",children:["Em ",e.jsx(t,{children:"supabase/functions/generate-asset/index.ts"}),", adiciona próximo código sequencial:"]}),e.jsx("pre",{className:"bg-background/70 rounded p-2 text-[10px] overflow-x-auto text-muted-foreground",children:`const OP_MAP: Record<string, string> = {
257  // ...existing...
258  "gen-i7": "generate-novo-provider",  // se for image
259  // ou "gen-v9": "generate-novo-provider" se for video
260};`}),e.jsxs("p",{className:"text-muted-foreground",children:["Redeploy do ",e.jsx(t,{children:"generate-asset"})," (precisa autorização Supabase)."]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"font-semibold text-foreground",children:["3. Mesma entrada em ",e.jsx(t,{children:"FN_TO_OP"})," + ",e.jsx(t,{children:"AssetOp"})," type"]}),e.jsxs("p",{className:"text-muted-foreground",children:["Em ",e.jsx(t,{children:"src/lib/edgeRouter.ts"}),":"]}),e.jsx("pre",{className:"bg-background/70 rounded p-2 text-[10px] overflow-x-auto text-muted-foreground",children:`export type AssetOp =
261  // ...existing...
262  | "gen-i7"; // generate-novo-provider
263
264const FN_TO_OP: Record<string, AssetOp> = {
265  // ...existing...
266  "generate-novo-provider": "gen-i7",
267};`})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"font-semibold text-foreground",children:["4. Adicionar tokens de scrub em ",e.jsx(t,{children:"PROVIDER_TOKENS"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["Em ",e.jsx(t,{children:"generate-asset/index.ts"}),", se o provider tem nome novo que possa aparecer em error messages, adiciona regex:"]}),e.jsx("pre",{className:"bg-background/70 rounded p-2 text-[10px] overflow-x-auto text-muted-foreground",children:`const PROVIDER_TOKENS: Array<[RegExp, string]> = [
268  // ...existing...
269  [/novo-provider/gi, "modelo"],
270];`})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsxs("p",{className:"font-semibold text-foreground",children:["5. Frontend chama via ",e.jsx(t,{children:"invokeFn"})]}),e.jsx("p",{className:"text-muted-foreground",children:"No call site:"}),e.jsx("pre",{className:"bg-background/70 rounded p-2 text-[10px] overflow-x-auto text-muted-foreground",children:`import { invokeFn } from "@/lib/edgeRouter";
271
272// usa o NOME real da fn — invokeFn auto-routea via FN_TO_OP
273const { data, error } = await invokeFn("generate-novo-provider", { body });`}),e.jsxs("p",{className:"text-muted-foreground",children:["Se for usado via hooks ",e.jsx(t,{children:"useImageQueue"}),"/",e.jsx(t,{children:"useVideoQueue"}),"/",e.jsx(t,{children:"useSwapQueue"}),": já passa pelo ",e.jsx(t,{children:"routeFn"})," automaticamente, sem mudança nos hooks."]})]}),e.jsxs("div",{className:"bg-blue-500/10 border border-blue-500/30 rounded-lg p-3 text-xs text-blue-400",children:[e.jsx("strong",{children:"Smoke test pós-deploy:"})," Faz uma geração no browser, F12 → Network → confirma que aparece ",e.jsx(t,{children:"/generate-asset"})," e ",e.jsx("strong",{children:"NÃO"})," aparece ",e.jsx(t,{children:"/generate-novo-provider"}),". Se aparecer o nome real, algum call site não tá usando ",e.jsx(t,{children:"invokeFn"})," ainda — grep e ajusta."]})]})})]}),e.jsxs(Se,{value:"cam-files",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sr,{className:"w-4 h-4 text-amber-500"})," Arquivos & Referências"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Server-side"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"supabase/functions/generate-asset/index.ts"})," — Dispatcher (~135 linhas, autocontido, sem shared imports)"]}
273),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"supabase/functions/media-upload/index.ts"})," — Rename de upload-to-b2"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"supabase/functions/media-delete/index.ts"})," — Rename de delete-from-b2"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"supabase/functions/_shared/b2-upload.ts"})," + ",e.jsx(t,{children:"error-logger.ts"})," + ",e.jsx(t,{children:"thumbnail.ts"})," — Helpers compartilhados"]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Frontend"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"src/lib/edgeRouter.ts"})," — ",e.jsx(t,{children:"FN_TO_OP"}),", ",e.jsx(t,{children:"AssetOp"}),", ",e.jsx(t,{children:"routeFn()"}),", ",e.jsx(t,{children:"invokeFn()"}),", ",e.jsx(t,{children:"invokeAsset()"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"src/hooks/useImageQueue.ts"})," + ",e.jsx(t,{children:"useVideoQueue.ts"})," + ",e.jsx(t,{children:"useSwapQueue.ts"})," — Wrappers plugados"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"src/hooks/useVideoGeneration.ts"})," — 8 invokes migrados"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"src/components/ImageEditor.tsx"})," + ",e.jsx(t,{children:"SocialPostPanel.tsx"})," — direct invokes migrados"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"src/lib/downloadMedia.ts"})," — Download lib que usa proxy-image como fallback CORS"]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Recursos externos"}),e.jsxs("p",{className:"text-muted-foreground",children:["• Cloudflare Dashboard → ",e.jsx(t,{children:"aiclubstudio.com"})," → Rules → Transform Rules → Modify Response Header"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Cloudflare API docs: ",e.jsx(t,{children:"https://developers.cloudflare.com/rules/transform/response-header-modification/"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["• Supabase Edge Functions: ",e.jsx(t,{children:"https://supabase.com/dashboard/project/tyfwdwvbndsylqtvfzdh/functions"})]})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-4 text-xs space-y-1.5",children:[e.jsx("p",{className:"font-semibold text-foreground",children:"Commits"}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"b3785885"})," — Fase 1: Deploy dispatcher generate-asset"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"d8856a65"})," — Fase 2: Pilot Grok Imagine (gen-i4)"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"e0b5b1c3"})," — Fase 3: Expande pra todas 14 provider fns"]}),e.jsxs("p",{className:"text-muted-foreground",children:["• ",e.jsx(t,{children:"86666afe"})," — Fase 4: Rename B2 fns para media-upload/media-delete"]})]})]})})]}),e.jsxs(Se,{value:"cam-troubleshooting",children:[e.jsx(Ae,{className:"font-semibold",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rr,{className:"w-4 h-4 text-red-500"})," Troubleshooting"]})}),e.jsx(Ee,{children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Sintoma"}),e.jsx(f,{children:"Causa provável"}),e.jsx(f,{children:"Solução"})]})}),e.jsxs(De,{children:[e.jsxs(b,{children:[e.jsxs(a,{className:"text-xs",children:["F12 mostra ",e.jsx(t,{children:"/generate-XYZ"})," em vez de ",e.jsx(t,{children:"/generate-asset"})]}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Call site não tá usando ",e.jsx(t,{children:"invokeFn"})," OU FN_TO_OP não tem essa fn"]}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Grep ",e.jsx(t,{children:'supabase.functions.invoke("generate-XYZ")'})," e troca por ",e.jsx(t,{children:'invokeFn("generate-XYZ", ...)'}),". Confere ",e.jsx(t,{children:"FN_TO_OP"})," em ",e.jsx(t,{children:"edgeRouter.ts"}),"."]})]}),e.jsxs(b,{children:[e.jsx(a,{className:"text-xs",children:'Dispatcher retorna 400 "Operação inválida"'}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Frontend mandou ",e.jsx(t,{children:"op"})," que não existe em ",e.jsx(t,{children:"OP_MAP"})," server-side"]}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Confere se ",e.jsx(t,{children:"FN_TO_OP"})," (frontend) e ",e.jsx(t,{children:"OP_MAP"})," (server, ",e.jsx(t,{children:"generate-asset/index.ts"}),") estão sincronizados."]})]}),e.jsxs(b,{children:[e.jsx(a,{className:"text-xs",children:"Geração funciona mas créditos cobrados em duplicidade"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Dispatcher chamando inner fn DUAS vezes (não deve acontecer)"}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Confere logs do ",e.jsx(t,{children:"generate-asset"})," + inner fn. Dispatcher é pure proxy, charge fica na inner fn."]})]}),e.jsxs(b,{children:[e.jsxs(a,{className:"text-xs",children:["Headers ",e.jsx(t,{children:"X-Bz-*"})," ainda aparecem em algum response"]}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["URL não é ",e.jsx(t,{children:"cdn.aiclubstudio.com"})," ou cache hit antigo"]}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Confere ",e.jsx(t,{children:"http.host"}
273)," da rule. Ctrl+Shift+R pra forçar bypass de cache."]})]}),e.jsxs(b,{children:[e.jsx(a,{className:"text-xs",children:"Download dá CORS error vermelho no console"}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"Transform Rule de CORS desabilitada/removida OU cache antigo sem header"}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:[e.jsx(t,{children:"curl -sI https://cdn.aiclubstudio.com/...mp4 | grep -i access-control"})," — deve mostrar ",e.jsx(t,{children:"Access-Control-Allow-Origin: *"}),". Se não, re-add rule."]})]}),e.jsxs(b,{children:[e.jsx(a,{className:"text-xs",children:'Versão velha do código após deploy ("vídeos não carregam")'}),e.jsx(a,{className:"text-xs text-muted-foreground",children:"PWA Service Worker servindo JS cacheado"}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:["Hard refresh (",e.jsx(t,{children:"Ctrl+Shift+R"}),"). Ver memory ",e.jsx(t,{children:"feedback_deploy_sw_cache_gotcha.md"}),"."]})]})]})]})})]})]})]})]}),en={slug:"",title:"",description:"",cover_image_url:"",content_markdown:"",video_url:"",sort_order:0,is_published:!0};function nt(s){return s.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)}const $l=()=>{const[s,n]=r.useState([]),[c,u]=r.useState(!0),[m,_]=r.useState(!1),[k,g]=r.useState(null),[l,h]=r.useState(en),[x,w]=r.useState(!1),v=async()=>{u(!0);const{data:p,error:z}=await F.from("lessons").select("*").order("sort_order",{ascending:!0}).order("created_at",{ascending:!0});z?(o.error(`Erro ao carregar: ${z.message}`),n([])):n(p||[]),u(!1)};r.useEffect(()=>{v()},[]);const R=()=>{var p;g(null),h({...en,sort_order:(((p=s[s.length-1])==null?void 0:p.sort_order)??0)+10}),_(!0)},$=p=>{g(p.id),h({slug:p.slug,title:p.title,description:p.description||"",cover_image_url:p.cover_image_url||"",content_markdown:p.content_markdown,video_url:p.video_url||"",sort_order:p.sort_order,is_published:p.is_published}),_(!0)},V=async()=>{if(!l.title.trim()||!l.slug.trim()||!l.content_markdown.trim()){o.error("Título, slug e conteúdo são obrigatórios");return}w(!0);const p={slug:l.slug.trim(),title:l.title.trim(),description:l.description.trim()||null,cover_image_url:l.cover_image_url.trim()||null,content_markdown:l.content_markdown,video_url:l.video_url.trim()||null,sort_order:l.sort_order,is_published:l.is_published};try{if(k){const{error:z}=await F.from("lessons").update(p).eq("id",k);if(z)throw z;o.success("Aula atualizada")}else{const{error:z}=await F.from("lessons").insert(p);if(z)throw z;o.success("Aula criada")}_(!1),v()}catch(z){o.error(z.message||"Erro ao salvar")}finally{w(!1)}},C=async p=>{const{error:z}=await F.from("lessons").delete().eq("id",p);z?o.error(`Erro ao deletar: ${z.message}`):(o.success("Aula deletada"),v())},ee=async p=>{const{error:z}=await F.from("lessons").update({is_published:!p.is_published}).eq("id",p.id);z?o.error(`Erro: ${z.message}`):v()},Z=async(p,z)=>{const Q=s.findIndex(G=>G.id===p.id),ae=z==="up"?s[Q-1]:s[Q+1];if(!ae)return;const{error:Y}=await F.from("lessons").update({sort_order:ae.sort_order}).eq("id",p.id),{error:B}=await F.from("lessons").update({sort_order:p.sort_order}).eq("id",ae.id);Y||B?o.error("Erro ao reordenar"):v()};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"font-display font-semibold text-lg flex items-center gap-2",children:[e.jsx(Rn,{className:"w-5 h-5 text-primary"})," Universidade"]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Aulas e tutoriais exibidos em ",e.jsx("strong",{children:"/university"}),". Conteúdo em markdown (suporta listas, imagens, links, código, tabelas)."]})]}),e.jsxs(y,{size:"sm",onClick:R,className:"gap-1.5",children:[e.jsx(Us,{className:"w-4 h-4"}),"Nova aula"]})]}),e.jsx("div",{className:"rounded-xl border border-border/40 bg-card/50",children:c?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:'Nenhuma aula ainda. Clique em "Nova aula" pra começar.'}):e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{className:"w-12",children:"#"}),e.jsx(f,{children:"Título"}),e.jsx(f,{className:"font-mono text-[10px]",children:"Slug"}),e.jsx(f,{className:"w-24",children:"Status"}),e.jsx(f,{className:"text-right w-56",children:"Ações"})]})}),e.jsx(De,{children:s.map((p,z)=>e.jsxs(b,{children:[e.jsx(a,{className:"font-mono text-xs text-muted-foreground",children:p.sort_order}),e.jsx(a,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[p.cover_image_url&&e.jsx("img",{src:p.cover_image_url,alt:"",className:"w-8 h-8 rounded object-cover border border-border/40"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:p.title}),p.description&&e.jsx("p",{className:"text-[10px] text-muted-foreground line-clamp-1 max-w-md",children:p.description})]})]})}),e.jsx(a,{className:"font-mono text-[10px] text-muted-foreground",children:p.slug}),e.jsx(a,{children:e.jsx(Re,{variant:p.is_published?"default":"secondary",className:"text-[10px]",children:p.is_published?"Publicada":"Rascunho"})}),e.jsx(a,{className:"text-right",children:e.jsxs("div",{className:"inline-flex items-center gap-1",children:[e.jsx(y,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:z===0,onClick:()=>Z(p,"up"),title:"Subir",children:e.jsx(In,{className:"w-3.5 h-3.5"})}),e.jsx(y,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:z===s.length-1,onClick:()=>Z(p,"down"),title:"Descer",children:e.jsx(Jn,{className:"w-3.5 h-3.5"})}),e.jsx(y,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>ee(p),title:p.is_published?"Despublicar":"Publicar",children:p.is_published?e.jsx(Ln,{className:"w-3.5 h-3.5"}):e.jsx(ia,{className:"w-3.5 h-3.5"})}),e.jsx(y,{size:"icon",variant:"ghost",className:"h-7 w-7",asChild:!0,title:"Ver no site",children:e.jsx("a",{href:`/university/${p.slug}`,target:"_blank",rel:"noopener noreferrer",children:e.jsx(oa,{className:"w-3.5 h-3.5"})})}),e.jsx(y,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>$(p),title:"Editar",children:e.jsx($r,{className:"w-3.5 h-3.5"})}),e.jsxs(va,{children:[e.jsx(Nn,{asChild:!0,children:e.jsx(y,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",title:"Deletar",children:e.jsx(_s,{className:"w-3.5 h-3.5"})})}),e.jsxs(ba,{children:[e.jsxs(Na,{children:[e.jsxs(ya,{children:['Deletar "',p.title,'"?']}),e.jsx(_a,{children:"Ação irreversível. A aula sai do ar imediatamente pros users."})]}),e.jsxs(wa,{children:[e.jsx(ka,{children:"Cancelar"}),e.jsx(Ca,{onClick:()=>C(p.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Deletar"})]})]})]})]})})]}
273,p.id))})]})}),e.jsx(ds,{open:m,onOpenChange:_,children:e.jsxs(cs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(ms,{children:e.jsx(us,{children:k?"Editar aula":"Nova aula"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Título *"}),e.jsx(je,{value:l.title,onChange:p=>{const z=p.target.value;h(Q=>({...Q,title:z,slug:Q.slug===""||Q.slug===nt(Q.title)?nt(z):Q.slug}))},placeholder:"Como pegar sua chave do Google AI..."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(oe,{className:"text-xs",children:["Slug * ",e.jsx("span",{className:"text-muted-foreground",children:"(URL)"})]}),e.jsx(je,{value:l.slug,onChange:p=>h(z=>({...z,slug:nt(p.target.value)})),placeholder:"chave-google-ai-gratis",className:"font-mono text-xs"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Descrição curta"}),e.jsx(je,{value:l.description,onChange:p=>h(z=>({...z,description:p.target.value})),placeholder:"Resumo de 1-2 linhas — aparece no card da listagem"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(oe,{className:"text-xs",children:["URL da capa ",e.jsx("span",{className:"text-muted-foreground",children:"(opcional)"})]}),e.jsx(je,{value:l.cover_image_url,onChange:p=>h(z=>({...z,cover_image_url:p.target.value})),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(oe,{className:"text-xs",children:["URL do vídeo intro ",e.jsx("span",{className:"text-muted-foreground",children:"(opcional)"})]}),e.jsx(je,{value:l.video_url,onChange:p=>h(z=>({...z,video_url:p.target.value})),placeholder:"https://...mp4"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Conteúdo (Markdown) *"}),e.jsx(Ss,{value:l.content_markdown,onChange:p=>h(z=>({...z,content_markdown:p.target.value})),placeholder:`# Título da aula
274
275## Passo 1
276
277Texto explicativo...
278
279- Item 1
280- Item 2
281
282[Link](https://...)`,className:"font-mono text-xs min-h-[400px]"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Suporta GitHub-flavored markdown — headings, listas, links, tabelas, código, imagens, blockquote, etc."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 items-end",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Ordem (menor = aparece primeiro)"}),e.jsx(je,{type:"number",value:l.sort_order,onChange:p=>h(z=>({...z,sort_order:Number(p.target.value)||0}))})]}),e.jsxs("div",{className:"flex items-center gap-2 pb-1",children:[e.jsx(Vs,{checked:l.is_published,onCheckedChange:p=>h(z=>({...z,is_published:p}))}),e.jsx(oe,{className:"text-xs",children:l.is_published?"Publicada":"Rascunho (oculta dos users)"})]})]})]}),e.jsxs(Bs,{children:[e.jsx(y,{variant:"ghost",onClick:()=>_(!1),children:"Cancelar"}),e.jsxs(y,{onClick:V,disabled:x,className:"gap-2",children:[x&&e.jsx(he,{className:"w-4 h-4 animate-spin"}),k?"Salvar alterações":"Criar aula"]})]})]})})]})},it=[{id:"builtin-0",name:"Padrão — Recriação Detalhada",prompt:"You are an expert AI image prompt engineer. When given an image, produce a highly detailed text prompt in English to recreate it with an AI image generator. Output ONLY the prompt text."},{id:"builtin-1",name:"Estilo Artístico — Foco em Estética",prompt:"You are an expert art director. Analyze the image and produce a detailed prompt focusing on artistic style, color palette, lighting, composition, mood, and visual aesthetics. Describe the artistic techniques used. Output ONLY the English prompt."},{id:"builtin-2",name:"Personagem — Foco em Aparência",prompt:"You are an expert character designer. Analyze the image focusing on character appearance: facial features, hair, clothing, accessories, body language, expression, and pose. Include background and setting details. Output ONLY the English prompt."},{id:"builtin-3",name:"Técnico — Fotografia",prompt:"You are an expert photographer. Analyze the image as a photograph: describe camera angle, lens type, depth of field, lighting setup, exposure, color grading, and post-processing effects. Include subject and composition details. Output ONLY the English prompt."},{id:"builtin-4",name:"Minimalista — Essência",prompt:"You are a concise prompt engineer. Analyze the image and produce a short but effective prompt (under 100 words) capturing only the essential elements needed to recreate it. Be precise and avoid redundancy. Output ONLY the English prompt."}],Ha={describe_provider:"openrouter",describe_model:"x-ai/grok-4.3",describe_system_prompt:"",describe_video_system_prompt:"",describe_max_tokens:"4096"},sn=[{value:"gemini-3-flash-preview",label:"Gemini 3 Flash Preview"},{value:"gemini-3.1-pro-preview",label:"Gemini 3.1 Pro Preview"}],zl=()=>{const[s,n]=r.useState(Ha),[c,u]=r.useState(!0),[m,_]=r.useState(!1),[k,g]=r.useState([]),[l,h]=r.useState(""),[x,w]=r.useState(!1),[v,R]=r.useState(!1),[$,V]=r.useState(null),C=r.useCallback(async()=>{const{data:B}=await F.from("prompt_presets").select("id, name, prompt").order("created_at",{ascending:!0});g(B||[])},[]);r.useEffect(()=>{ee(),C()},[C]);const ee=async()=>{u(!0);try{const{data:B,error:G}=await F.from("admin_settings").select("key, value").in("key",["de
282scribe_provider","describe_model","describe_system_prompt","describe_video_system_prompt","describe_max_tokens"]);if(G)throw G;const q={};for(const E of B||[])q[E.key]=E.value;n({describe_provider:q.describe_provider||Ha.describe_provider,describe_model:q.describe_model||Ha.describe_model,describe_system_prompt:q.describe_system_prompt||Ha.describe_system_prompt,describe_video_system_prompt:q.describe_video_system_prompt||Ha.describe_video_system_prompt,describe_max_tokens:q.describe_max_tokens||Ha.describe_max_tokens})}catch(B){o.error("Erro ao carregar configurações"),console.error(B)}finally{u(!1)}},Z=async()=>{_(!0);try{const B=Object.entries(s);for(const[G,q]of B){const{error:E}=await F.from("admin_settings").upsert({key:G,value:q,updated_at:new Date().toISOString()},{onConflict:"key"});if(E)throw E}o.success("Configurações salvas com sucesso!")}catch(B){o.error(B.message||"Erro ao salvar")}finally{_(!1)}},p=B=>{const G={...s,describe_provider:B};B==="google_ai"?G.describe_model=sn[0].value:G.describe_model="x-ai/grok-4.3",n(G)},z=B=>{const q=[...it,...k].find(E=>E.id===B);q&&(n({...s,describe_system_prompt:q.prompt}),o.success(`Preset "${q.name}" carregado!`))},Q=async()=>{const B=l.trim(),G=s.describe_system_prompt.trim();if(!B){o.error("Digite um nome para o preset.");return}if(!G){o.error("O System Prompt atual está vazio.");return}R(!0);try{const{error:q}=await F.from("prompt_presets").insert({name:B,prompt:G});if(q)throw q;o.success(`Preset "${B}" criado!`),h(""),w(!1),C()}catch(q){o.error(q.message||"Erro ao criar preset")}finally{R(!1)}},ae=async B=>{V(B.id);try{const{error:G}=await F.from("prompt_presets").delete().eq("id",B.id);if(G)throw G;o.success(`Preset "${B.name}" excluído.`),C()}catch(G){o.error(G.message||"Erro ao excluir")}finally{V(null)}};if(c)return e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})});const Y=s.describe_provider==="google_ai";return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"glass rounded-xl p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(er,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-display font-semibold",children:"Detail Prompt"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Configurações dos agentes de engenharia reversa e animação de imagens."})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Provedor de IA"}),e.jsxs(as,{value:s.describe_provider,onValueChange:p,children:[e.jsx(rs,{className:"w-64",children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"openrouter",children:"OpenRouter (API Admin)"}),e.jsx(pe,{value:"google_ai",children:"Google AI (API do Usuário)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Y?"Usa a chave Google AI do próprio usuário (perfil). O custo é do usuário.":"Usa a chave OpenRouter do sistema (admin). O custo é da plataforma."})]}),Y&&e.jsxs("div",{className:"flex items-start gap-2.5 p-3 rounded-xl bg-primary/5 border border-primary/10",children:[e.jsx(Wi,{className:"w-4 h-4 text-primary/60 mt-0.5 shrink-0"}),e.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed",children:["Quando o provedor é ",e.jsx("strong",{children:"Google AI"}),", a Edge Function busca a chave ",e.jsx("code",{children:"google_ai"})," da tabela ",e.jsx("code",{children:"user_api_keys"})," do usuário autenticado."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"describe-model",children:Y?"Modelo Google AI":"Modelo OpenRouter"}),Y?e.jsxs(as,{value:s.describe_model,onValueChange:B=>n({...s,describe_model:B}),children:[e.jsx(rs,{className:"w-64",children:e.jsx(ts,{})}),e.jsx(ns,{children:sn.map(B=>e.jsx(pe,{value:B.value,children:B.label},B.value))})]}):e.jsx(je,{id:"describe-model",value:s.describe_model,onChange:B=>n({...s,describe_model:B.target.value}),placeholder:"ex: x-ai/grok-4.3",className:"font-mono text-sm"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"describe-tokens",children:"Max Tokens"}),e.jsx(je,{id:"describe-tokens",type:"number",value:s.describe_max_tokens,onChange:B=>n({...s,describe_max_tokens:B.target.value}),placeholder:"4096",className:"w-32"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Capacidade técnica da resposta do modelo, não limite de caracteres. O Detail Prompt só corta caracteres quando o usuário ativa o teto opcional."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs(oe,{className:"flex items-center gap-2",children:[e.jsx(Dn,{className:"w-3.5 h-3.5"}),"Templates de System Prompt"]}),(()=>{const G=[...it,...k].find(E=>E.prompt===s.describe_system_prompt),q=G&&k.some(E=>E.id===G.id);return e.jsxs("div",{className:"flex items-center justify-between gap-2 p-2.5 rounded-lg bg-secondary/50 border border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Template ativo:"}),e.jsx("span",{className:`text-xs font-medium ${G?"text-primary":"text-orange-400"}`,children:G?G.name:"Personalizado (sem template)"})]}),q&&e.jsxs(va,{children:[e.jsx(Nn,{asChild:!0,children:e.jsxs(y,{size:"sm",variant:"ghost",className:"h-7 px-2 text-destructive hover:text-destructive hover:bg-destructive/10 gap-1.5",children:[e.jsx(_s,{className:"w-3 h-3"}),e.jsx("span",{className:"text-[11px]",children:"Excluir"})]})}),e.jsxs(ba,{children:[e.jsxs(Na,{children:[e.jsxs(ya,{children:['Excluir template "',G.name,'"?']}),e.jsx(_a,{children:"Esta ação não pode ser desfeita. O template será removido permanentemente e não poderá ser recuperado."})]}),e.jsxs(wa,{children:[e.jsx(ka,{children:"Cancelar"}),e.jsx(Ca,{onClick:()=>ae(G),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Excluir permanentemente"})]})]})]})]})})(),e.jsxs(as,{value:"",onValueChange:z,children:[e.jsx(rs,{className:"w-full",children:e.jsx(ts,{placeholder:"Selecione um template para carregar..."})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"__header_builtin",disabled:!0,className:"text-[10px] uppercase tracking-wider text-muted-foreground font-medium",children:"Pré-definidos"}),it.map(B=>e.jsx(pe,{value:B.id,children:B.name},B.id)),k.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(pe,{value:"__header_custom",disabled:!0,className:"text-[10px] uppercase tracking-wider text-muted-foreground font-medium mt
282-1",children:"Seus Templates"}),k.map(B=>e.jsx(pe,{value:B.id,children:B.name},B.id))]})]})]}),x?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je,{value:l,onChange:B=>h(B.target.value),placeholder:"Nome do preset...",className:"text-xs h-8 flex-1",onKeyDown:B=>B.key==="Enter"&&Q()}),e.jsxs(y,{size:"sm",onClick:Q,disabled:v,className:"h-8 text-xs gap-1.5",children:[v?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Zs,{className:"w-3.5 h-3.5"}),"Salvar"]}),e.jsx(y,{size:"sm",variant:"ghost",onClick:()=>w(!1),className:"h-8 text-xs",children:"Cancelar"})]}):e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>w(!0),className:"h-8 text-xs gap-1.5",children:[e.jsx(Us,{className:"w-3.5 h-3.5"}),"Salvar prompt atual como preset"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Selecione um template para carregar no System Prompt, ou salve o prompt atual como novo template."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"describe-prompt",children:"System Prompt"}),e.jsx(Ss,{id:"describe-prompt",value:s.describe_system_prompt,onChange:B=>n({...s,describe_system_prompt:B.target.value}),placeholder:"Instruções para o agente de IA...",rows:8,className:"font-mono text-xs leading-relaxed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Prompt de sistema enviado ao modelo. Define como a IA analisa a imagem e gera o prompt de saída."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"describe-video-prompt",children:"System Prompt — imagem para vídeo"}),e.jsx(Ss,{id:"describe-video-prompt",value:s.describe_video_system_prompt,onChange:B=>n({...s,describe_video_system_prompt:B.target.value}),placeholder:"Vazio usa o padrão modular universal de vídeo definido na Edge Function.",rows:8,className:"font-mono text-xs leading-relaxed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controla a análise da imagem e a saída modular com sujeito, ambiente, movimento, timeline, áudio e continuidade. Vazio mantém o padrão seguro do código."})]})]}),e.jsxs(y,{onClick:Z,disabled:m,className:"gap-2",children:[m?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(Zs,{className:"w-4 h-4"}),m?"Salvando...":"Salvar Configurações"]})]}),e.jsxs("div",{className:"border-t border-border pt-6 mt-6",children:[e.jsxs("h3",{className:"text-lg font-semibold mb-2 flex items-center gap-2",children:[e.jsx(Ma,{className:"w-5 h-5"})," Backfill Thumbnails"]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Gera thumbnails WebP 600px para imagens antigas que não têm. Roda em lotes de 15."}),e.jsx(Bl,{})]})]})};function Bl(){const[s,n]=r.useState(!1),[c,u]=r.useState(null),[m,_]=r.useState(!1),k=r.useCallback(async()=>{n(!0);try{const{data:g,error:l}=await F.functions.invoke("backfill-thumbnails",{body:{batchSize:5}});if(l)throw l;return u(h=>({processed:((h==null?void 0:h.processed)??0)+(g.processed??0),failed:((h==null?void 0:h.failed)??0)+(g.failed??0),remaining:g.remaining??0})),g.remaining===0&&(o.success("✅ Todas as thumbnails foram geradas!"),_(!1)),g.remaining??0}catch(g){return o.error("Erro no backfill: "+(g.message||String(g))),_(!1),-1}finally{n(!1)}},[]);return r.useEffect(()=>{if(!m||s)return;const g=setTimeout(()=>{k().then(l=>{l<=0&&_(!1)})},1500);return()=>clearTimeout(g)},[m,s,k]),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(y,{onClick:()=>{u(null),_(!0)},disabled:s||m,className:"gap-2",children:[s||m?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(Qe,{className:"w-4 h-4"}),m?"Rodando em loop...":"Rodar Backfill (auto-loop)"]}),m&&e.jsx(y,{variant:"outline",onClick:()=>_(!1),children:"Parar"})]}),c&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["✅ ",c.processed," processadas | ❌ ",c.failed," falhas | 📦 ",c.remaining," restantes"]})]})}const ot=Object.keys({admin_settings:!0,credit_costs:!0,crm_contacts:!0,error_logs:!0,folders:!0,generation_folders:!0,generations:!0,preset_images:!0,presets:!0,profiles:!0,community_shares:!0,prompt_presets:!0,token_usage:!0,user_api_keys:!0,user_roles:!0,webhook_logs:!0,lora_trainings:!0,affiliates:!0,affiliate_commissions:!0,affiliate_applications:!0,user_photoshoot_styles:!0,user_loras:!0,keep_alive:!0,subscription_plans:!0,model_pricing_tiers:!0,community_categories:!0,community_posts:!0,community_likes:!0,community_favorites:!0,avatar_profiles:!0,banned_users:!0,community_reports:!0,api_keys:!0,api_key_usage:!0,user_prompt_templates:!0}),ql=["admin-create-user","admin-list-emails","cleanup-old-generations","delete-from-b2","describe-image","generate-image","generate-image-wavespeed","generate-video","proxy-image","upload-to-b2"],lt=50,Vl=()=>{const[s,n]=r.useState(null),[c,u]=r.useState([]),[m,_]=r.useState([]),[k,g]=r.useState(!1),[l,h]=r.useState(""),[x,w]=r.useState(0),[v,R]=r.useState(0),[$,V]=r.useState(null),[C,ee]=r.useState({}),[Z,p]=r.useState(!1),[z,Q]=r.useState(null),[ae,Y]=r.useState("overview"),[B,G]=r.useState({}),[q,E]=r.useState(!1),[P,K]=r.useState([]),[J,W]=r.useState(!1),[N,ce]=r.useState(null),[D,i]=r.useState(null),[A,O]=r.useState(""),[te,T]=r.useState(!1),[re,ke]=r.useState(!1),fe=r.useCallback(async()=>{E(!0);const H={};await Promise.all(ot.map(async xe=>{try{const{count:Ne}=await F.from(xe).select("*",{count:"exact",head:!0});H[xe]=Ne||0}catch{H[xe]=0}})),G(H),E(!1)},[]),X=r.useCallback(async()=>{var H;W(!0);try{const{data:xe,error:Ne}=await F.functions.invoke("admin-list-emails");if(Ne)throw Ne;K(xe.authUsers||[]),ce(((H=xe.authUsers)==null?void 0:H.length)??null)}catch(xe){o.error("Erro ao carregar auth users: "+xe.message)}finally{W(!1)}},[]);r.useEffect(()=>{fe(),X()},[fe,X]);const me=r.useCallback(async()=>
282{if(s){g(!0);try{const{count:H}=await F.from(s).select("*",{count:"exact",head:!0});w(H||0);let xe=F.from(s).select("*").range(v*lt,(v+1)*lt-1);["profiles","generations","folders","generation_folders","presets","preset_images","prompt_presets","token_usage","user_api_keys","error_logs","webhook_logs"].includes(s)?xe=xe.order("created_at",{ascending:!1}):s==="admin_settings"&&(xe=xe.order("updated_at",{ascending:!1}));const{data:Xe,error:bs}=await xe;if(bs)throw bs;Xe&&Xe.length>0?(_(Object.keys(Xe[0])),u(Xe)):(u([]),_([]))}catch(H){o.error(`Erro ao carregar ${s}: ${H.message}`)}finally{g(!1)}}},[s,v]);r.useEffect(()=>{s&&(R(0),h(""))},[s]),r.useEffect(()=>{ae==="table"&&s&&me()},[me,ae]);const _e=H=>{n(H),Y("table")},$e=()=>{Y("overview"),n(null),fe()},Ve=async H=>{if(confirm("Tem certeza que deseja excluir este registro?"))try{const{error:xe}=await F.from(s).delete().eq("id",H.id);if(xe)throw xe;o.success("Registro excluído"),me()}catch(xe){o.error(xe.message)}},Je=H=>{V(H);const xe={};for(const Ne of m)xe[Ne]=typeof H[Ne]=="object"?JSON.stringify(H[Ne],null,2):String(H[Ne]??"");ee(xe)},we=async()=>{if($){p(!0);try{const H={};for(const Ne of m){if(Ne==="id"||Ne==="created_at")continue;const Xe=typeof $[Ne]=="object"?JSON.stringify($[Ne]):String($[Ne]??"");if(C[Ne]!==Xe)try{H[Ne]=JSON.parse(C[Ne])}catch{H[Ne]=C[Ne]}}if(Object.keys(H).length===0){o.info("Nenhuma alteração detectada"),V(null),p(!1);return}const{error:xe}=await F.from(s).update(H).eq("id",$.id);if(xe)throw xe;o.success("Registro atualizado"),V(null),me()}catch(H){o.error(H.message)}finally{p(!1)}}},We=async()=>{if(!D)return;const H=parseInt(A);if(isNaN(H)||H===0){o.error("Informe um valor válido (positivo para adicionar, negativo para remover)");return}T(!0);try{const xe=(D.premium_credits||0)+H,{error:Ne}=await F.from("profiles").update({premium_credits:Math.max(0,xe)}).eq("id",D.id);if(Ne)throw Ne;o.success(`${H>0?"+":""}${H} créditos → saldo: ${Math.max(0,xe)}`),i(null),O(""),me()}catch(xe){o.error(xe.message)}finally{T(!1)}},Ge=()=>{if(c.length===0)return;const H=m.join(","),xe=c.map(gs=>m.map(hs=>{const As=gs[hs];return`"${(typeof As=="object"?JSON.stringify(As):String(As??"")).replace(/"/g,'""')}"`}).join(",")),Ne=[H,...xe].join(`
283`),Xe=new Blob([Ne],{type:"text/csv;charset=utf-8;"}),bs=URL.createObjectURL(Xe),Rs=document.createElement("a");Rs.href=bs,Rs.download=`${s}_${new Date().toISOString().slice(0,10)}.csv`,Rs.click(),URL.revokeObjectURL(bs),o.success("CSV exportado!")},ps=l?c.filter(H=>m.some(xe=>String(H[xe]??"").toLowerCase().includes(l.toLowerCase()))):c,be=Math.ceil(x/lt),ue=(H,xe=60)=>{const Ne=typeof H=="object"?JSON.stringify(H):String(H??"—");return Ne.length>xe?Ne.slice(0,xe)+"…":Ne},[Pe,ze]=r.useState(!1),[Ie,xs]=r.useState(null),Ps=H=>H==null?"NULL":typeof H=="boolean"?H?"TRUE":"FALSE":typeof H=="number"?String(H):typeof H=="object"?`'${JSON.stringify(H).replace(/'/g,"''")}'::jsonb`:`'${String(H).replace(/'/g,"''")}'`,Ze={admin_settings:`CREATE TABLE IF NOT EXISTS public.admin_settings (
284  id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
285  key text NOT NULL,
286  value text NOT NULL,
287  updated_at timestamptz NOT NULL DEFAULT now()
288);`,error_logs:`CREATE TABLE IF NOT EXISTS public.error_logs (
289  id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
290  function_name text NOT NULL,
291  error_message text NOT NULL,
292  error_code text,
293  user_id uuid,
294  request_body jsonb,
295  metadata jsonb,
296  created_at timestamptz NOT NULL DEFAULT now()
297);`,folders:`CREATE TABLE IF NOT EXISTS public.folders (
298  id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
299  name text NOT NULL,
300  user_id uuid NOT NULL,
301  created_at timestamptz NOT NULL DEFAULT now()
302);`,generation_folders:`CREATE TABLE IF NOT EXISTS public.generation_folders (
303  id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
304  generation_id uuid NOT NULL REFERENCES public.generations(id),
305  folder_id uuid NOT NULL REFERENCES public.folders(id)
306);`,generations:`CREATE TABLE IF NOT EXISTS public.generations (
307  id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
308  user_id uuid NOT NULL,
309  media_url text NOT NULL,
310  media_type text NOT NULL DEFAULT 'image',
311  prompt text,
312  model text,
313  aspect_ratio text,
314  quality text,
315  reference_images jsonb,
316  is_favorite boolean NOT NULL DEFAULT false,
317  created_at timestamptz NOT NULL DEFAULT now()
318);`,preset_images:`CREATE TABLE IF NOT EXISTS public.preset_images (
319  id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
320  preset_id uuid NOT NULL REFERENCES public.presets(id),
321  image_url text NOT NULL,
322  sort_order integer NOT NULL DEFAULT 0,
323  created_at timestamptz NOT NULL DEFAULT now()
324);`,presets:`CREATE TABLE IF NOT EXISTS public.presets (
325  id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
326  user_id uuid NOT NULL,
327  name text NOT NULL DEFAULT 'Novo Preset',
328  cover_image_url text,
329  created_at timestamptz NOT NULL DEFAULT now(),
330  updated_at timestamptz NOT NULL DEFAULT now()
331);`,profiles:`CREATE TABLE IF NOT EXISTS public.profiles (
332  id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
333  user_id uuid NOT NULL,
334  nickname text,
335  avatar_url text,
336  bio text,
337  is_premium boolean NOT NULL DEFAULT false,
338  premium_credits integer NOT NULL DEFAULT 0,
339  created_at timestamptz NOT NULL DEFAULT now(),
340  updated_at timestamptz NOT NULL DEFAULT now()
341);`,prompt_presets:`CREATE TABLE IF NOT EXISTS public.prompt_presets (
342  id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
343  name text NOT NULL,
344  prompt text NOT NULL,
345  created_at timestamptz NOT NULL DEFAULT now()
346);`,token_usage:`CREATE TABLE IF NOT EXISTS public.token_usage (
347  id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
348  user_id uuid,
349  action text NOT NULL,
350  tokens_used integer NOT NULL DEFAULT 0,
351  cost_estimate numeric DEFAULT 0,
352  created_at timestamptz NOT NULL DEFAULT now()
353);`,user_api_keys:`CREATE TABLE IF NOT EXISTS public.user_api_keys (
354  id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
355  user_id uuid NOT NULL,
356  provider text NOT NULL DEFAULT 'google_ai',
357  api_key text NOT NULL,
358  created_at timestamptz NOT NULL DEFAULT now(),
359  updated_at timestamptz NOT NULL DEFAULT now()
360);`,user_roles:`CREATE TABLE IF NOT EXISTS public.user_roles (
361  id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
362  user_id uuid NOT NULL,
363  role app_role NOT NULL DEFAULT 'user'
364);`,webhook_logs:`CREATE TABLE IF NOT EXISTS public.webhook_logs (
365  id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
366  event_type text NOT NULL,
367  email text,
368  user_id uuid,
369  status text NOT NULL DEFAULT 'received',
370  payload jsonb,
371  error_message text,
372  created_at timestamptz NOT NULL DEFAULT now()
373);`,crm_contacts:`CREATE TABLE IF NOT EXISTS public.crm_contacts (
374  id uuid NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
375  email text NOT NULL,
376  name text,
377  phone text,
378  status text NOT NULL DEFAULT 'lead',
379  hotmart_event text,
380  product_name text,
381  transaction_id text,
382  amount numeric(10,2),
383  notes text,
384  user_id uuid,
385  created_at timestamptz NOT NULL DEFAULT now(),
386  updated_at timestamptz NOT NULL DEFAULT now()
387);`},es=async()=>{const H=["-- =============================================",`-- Database export: ${new Date().toISOString()}`,`-- Tables: ${ot.join(", ")}`,"-- =============================================","","-- ========== ENUM TYPES ==========","DO $$ BEGIN","  CREATE TYPE app_role AS ENUM ('admin', 'moderator', 'user');","EXCEPTION WHEN duplicate_object THEN NULL;","END $$;","","-- ========== CREATE TABLES ==========",""],xe=["admin_settings","crm_contacts","error_logs","profiles","prompt_presets","token_usage","user_api_keys","user_roles","folders","generations","presets","generation_folders","preset_images","webhook_logs"];for(const Ne of xe)Ze[Ne]&&(H.push(Ze[Ne]),H.push(""));H.push("-- ========== INSERT DATA =========="),H.push("");for(const Ne of xe){const{data:Xe,error:bs}=await F.from(Ne).select("*");if(bs){H.push(`-- ERROR loading ${Ne}: ${bs.message}`);continue}if(!Xe||Xe.length===0){H.push(`-- ${Ne}: empty`),H.push("");continue}const Rs=Object.keys(Xe[0]);H.push(`-- ${Ne} (${Xe.length} rows)`);for(const gs of Xe){const hs=Rs.map(As=>Ps(gs[As]));H.push(`INSERT INTO public.${Ne} (${Rs.join(", ")}) VALUES (${hs.join(", ")});`)}H.push("")}return H.join(`
388`)},ws=async()=>{ze(!0);try{const H=await es(),xe=new Blob([H],{type:"text/sql;charset=utf-8;"}),Ne=URL.createObjectURL(xe),Xe=document.createElement("a");Xe.href=Ne,Xe.download=`database_export_${new Date().toISOString().slice(0,10)}.sql`,Xe.click(),URL.revokeObjectURL(Ne),o.success("SQL exportado com sucesso!")}catch(H){o.error("Erro ao exportar SQL: "+H.message)}finally{ze(!1)}},is=async()=>{ze(!0);try{const H=await es();xs(H)}catch(H){o.error("Erro ao gerar SQL: "+H.message)}finally{ze(!1)}},os=H=>H===1?"row":"rows";return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(y,{variant:ae!=="functions"?"default":"outline",size:"sm",onClick:()=>ae==="table"?$e():Y("overview"),className:"gap-2",children:[e.jsx(sr,{className:"w-4 h-4"})," Database"]}),e.jsx(y,{variant:ae==="functions"?"default":"outline",size:"sm",onClick:()=>Y("functions"),className:"gap-2",children:"⚡ Edge Functions"})]}),ae==="overview"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Database"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"View and manage the data stored in your app."})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(y,{variant:"destructive",size:"sm",onClick:async()=>{ke(!0);try{const H=await fetch("https://tyfwdwvbndsylqtvfzdh.supabase.co/functions/v1/cleanup-old-generations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({scheduled:!0})}),xe=await H.json();if(!H.ok)throw new Error(xe.error||"Erro");o.success(`Limpeza concluída: ${xe.deleted??0} gerações, ${xe.b2FilesRemoved??0} B2, ${xe.storageFilesRemoved??0} storage, ${xe.orphanRefsRemoved??0} refs, ${xe.appFilesRemoved??0} apps removidos`)}catch(H){o.error("Erro na limpeza: "+H.message)}finally{ke(!1)}},disabled:re,className:"gap-2",children:[re?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(St,{className:"w-3.5 h-3.5"}),"Limpar B2 (+10 dias)"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:is,disabled:Pe,className:"gap-2",children:[Pe?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(ia,{className:"w-3.5 h-3.5"}),"Visualizar SQL"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:ws,disabled:Pe,className:"gap-2",children:[Pe?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(na,{className:"w-3.5 h-3.5"}),"Exportar SQL"]}),e.jsx(y,{variant:"outline",size:"sm",onClick:fe,disabled:q,className:"gap-2",children:e.jsx(Qe,{className:`w-3.5 h-3.5 ${q?"animate-spin":""}`})})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:e.jsxs("button",{onClick:()=>Y("auth_users"),className:"flex items-center gap-4 p-4 rounded-xl border border-primary/30 bg-primary/5 hover:bg-primary/10 hover:border-primary/50 transition-all text-left group",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 border border-primary/20 flex items-center justify-center shrink-0",children:e.jsx(sa,{className:"w-4 h-4 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-semibold text-sm group-hover:text-primary transition-colors",children:"auth.users"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:N===null?"...":`${N} ${os(N)}`})]})]})}),e.jsx("h3",{className:"text-sm font-medium text-muted-foreground pt-2",children:"Public Tables"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:ot.map(H=>e.jsxs("button",{onClick:()=>_e(H),className:"flex items-center gap-4 p-4 rounded-xl border border-border/40 bg-secondary/20 hover:bg-secondary/40 hover:border-border/60 transition-all text-left group",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-secondary/50 border border-border/30 flex items-center justify-center shrink-0",children:e.jsx($o,{className:"w-4 h-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-semibold text-sm group-hover:text-primary transition-colors",children:H}),e.jsx("p",{className:"text-xs text-muted-foreground",children:q?"...":`${B[H]??0} ${os(B[H]??0)}`})]})]},H))})]}),ae==="functions"&&e.jsxs("div",{className:"glass rounded-xl p-6",children:[e.jsx("h2",{className:"font-display font-semibold mb-4 flex items-center gap-2",children:"⚡ Edge Functions Registradas"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3",children:ql.map(H=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-secondary/30 border border-border/30",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-primary shrink-0"}),e.jsx("span",{className:"text-sm font-mono",children:H})]},H))})]}),ae==="auth_users"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(y,{variant:"ghost",size:"sm",onClick:$e,className:"gap-1.5",children:[e.jsx(Lr,{className:"w-4 h-4"})," Overview"]}),e.jsx("span",{className:"text-muted-foreground",children:"/"}),e.jsx("h2",{className:"font-semibold",children:"auth.users"}),e.jsxs(Re,{variant:"outline",className:"text-xs",children:[P.length," usuários"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:X,className:"ml-auto gap-2",children:[e.jsx(Qe,{className:`w-3.5 h-3.5 ${J?"animate-spin":""}`})," Atualizar"]})]}),e.jsx("div",{className:"glass rounded-xl p-4 overflow-hidden",children:J?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):P.length===0?e.jsxs("div",{className:"text-center text-muted-foreground py-12",children:[e.jsx(sa,{className:"w-8 h-8 mx-auto mb-3 opacity-40"}),e.jsx("p",{className:"text-sm",children:"Nenhum usuário encontrado"})]}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{className:"text-xs",children:"id"}),e.jsx(f,{className:"text-xs",children:"email"}),e.jsx(f,{className:"text-xs",children:"provider"}),e.jsx(f,{className:"text-xs",children:"created_at"}),e.jsx(f,{className:"text-xs",children:"last_sign_in_at"}),e.jsx(f,{className:"text-xs",children:"email_confirmed_at"})]})}),e.jsx(De,{children:P.map(H=>e.jsxs(b,{children:[e.jsxs(a,{className:"text-xs font-mono max-w-[150px] truncate",title:H.id,children:[H.id.slice(0,8),"…"]}),e.jsx(a,{className:"text-xs",children:H.email}),e.jsx(a,{className:"text-xs",children:H.provider}),e.jsx(a,{className:"text-xs",children:H.created_at?new Date(H.created_at).toLocaleStr
388ing("pt-BR"):"—"}),e.jsx(a,{className:"text-xs",children:H.last_sign_in_at?new Date(H.last_sign_in_at).toLocaleString("pt-BR"):"—"}),e.jsx(a,{className:"text-xs",children:H.email_confirmed_at?new Date(H.email_confirmed_at).toLocaleString("pt-BR"):"—"})]},H.id))})]})})})]}),ae==="table"&&s&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(y,{variant:"ghost",size:"sm",onClick:$e,className:"gap-1.5",children:[e.jsx(Lr,{className:"w-4 h-4"})," Overview"]}),e.jsx("span",{className:"text-muted-foreground",children:"/"}),e.jsx("h2",{className:"font-semibold",children:s})]}),e.jsx("div",{className:"glass rounded-xl p-4",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(Re,{variant:"outline",className:"text-xs",children:[x," registros"]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-xs",children:[e.jsx(aa,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(je,{value:l,onChange:H=>h(H.target.value),placeholder:"Filtrar resultados...",className:"pl-10 h-9"})]}),e.jsxs("div",{className:"flex gap-2 ml-auto",children:[e.jsxs(y,{variant:"outline",size:"sm",onClick:me,className:"gap-2",children:[e.jsx(Qe,{className:"w-3.5 h-3.5"})," Atualizar"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:Ge,className:"gap-2",disabled:c.length===0,children:[e.jsx(na,{className:"w-3.5 h-3.5"})," CSV"]})]})]})}),e.jsxs("div",{className:"glass rounded-xl p-4 overflow-hidden",children:[k?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsxs("div",{className:"text-center text-muted-foreground py-12",children:[e.jsx(sr,{className:"w-8 h-8 mx-auto mb-3 opacity-40"}),e.jsx("p",{className:"text-sm",children:"Tabela vazia"})]}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[m.map(H=>e.jsx(f,{className:"text-xs whitespace-nowrap",children:H},H)),e.jsx(f,{className:"w-24 text-xs",children:"Ações"})]})}),e.jsx(De,{children:ps.map((H,xe)=>e.jsxs(b,{children:[m.map(Ne=>e.jsx(a,{className:"text-xs max-w-[200px] truncate",title:String(H[Ne]??""),children:ue(H[Ne])},Ne)),e.jsx(a,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(y,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>Q(H),title:"Detalhes",children:e.jsx(ia,{className:"w-3.5 h-3.5"})}),s==="profiles"&&e.jsx(y,{variant:"ghost",size:"icon",className:"h-7 w-7 text-primary hover:text-primary",onClick:()=>{i(H),O("")},title:"Adicionar créditos",children:e.jsx(ta,{className:"w-3.5 h-3.5"})}),e.jsx(y,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>Je(H),title:"Editar",children:e.jsx(Gt,{className:"w-3.5 h-3.5"})}),e.jsx(y,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:()=>Ve(H),title:"Excluir",children:e.jsx(_s,{className:"w-3.5 h-3.5"})})]})})]},H.id||xe))})]})}),be>1&&e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-4 border-t border-border/30",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Página ",v+1," de ",be]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(y,{variant:"outline",size:"sm",disabled:v===0,onClick:()=>R(v-1),children:e.jsx(Ct,{className:"w-4 h-4"})}),e.jsx(y,{variant:"outline",size:"sm",disabled:v>=be-1,onClick:()=>R(v+1),children:e.jsx(Sa,{className:"w-4 h-4"})})]})]})]})]}),e.jsx(ds,{open:!!z,onOpenChange:H=>!H&&Q(null),children:e.jsxs(cs,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(ms,{children:e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"w-4 h-4"})," Detalhes do Registro"]})}),z&&e.jsx("div",{className:"space-y-3",children:Object.entries(z).map(([H,xe])=>e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-semibold",children:H}),e.jsx("pre",{className:"text-xs bg-secondary/30 rounded-lg p-2 overflow-x-auto whitespace-pre-wrap break-all border border-border/20",children:typeof xe=="object"?JSON.stringify(xe,null,2):String(xe??"—")})]},H))})]})}),e.jsx(ds,{open:!!$,onOpenChange:H=>!H&&V(null),children:e.jsxs(cs,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(ms,{children:e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(Gt,{className:"w-4 h-4"})," Editar Registro"]})}),$&&e.jsxs("div",{className:"space-y-3",children:[m.map(H=>{var xe;return e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-semibold",children:H}),H==="id"||H==="created_at"?e.jsx("p",{className:"text-xs text-muted-foreground bg-secondary/20 rounded-lg p-2 border border-border/20",children:C[H]}):e.jsx("textarea",{value:C[H]||"",onChange:Ne=>ee({...C,[H]:Ne.target.value}),className:"w-full text-xs bg-secondary/30 rounded-lg p-2 border border-border/30 focus:border-primary/50 focus:outline-none resize-y min-h-[36px]",rows:(xe=C[H])!=null&&xe.includes(`
389`)?4:1})]},H)}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>V(null),children:[e.jsx(Ga,{className:"w-3.5 h-3.5 mr-1"})," Cancelar"]}),e.jsxs(y,{size:"sm",onClick:we,disabled:Z,className:"gap-2",children:[Z?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Zs,{className:"w-3.5 h-3.5"}),"Salvar"]})]})]})]})}),e.jsx(ds,{open:!!Ie,onOpenChange:H=>!H&&xs(null),children:e.jsxs(cs,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(ms,{children:e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(sr,{className:"w-4 h-4"})," SQL Export"]})}),e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsxs(y,{size:"sm",variant:"outline",className:"gap-2",onClick:()=>{Ie&&(navigator.clipboard.writeText(Ie),o.success("SQL copiado para a área de transferência!"))},children:[e.jsx(Zs,{className:"w-3.5 h-3.5"})," Copiar tudo"]}),e.jsxs(y,{size:"sm",variant:"outline",className:"gap-2",onClick:()=>
389{if(Ie){const H=new Blob([Ie],{type:"text/sql;charset=utf-8;"}),xe=URL.createObjectURL(H),Ne=document.createElement("a");Ne.href=xe,Ne.download=`database_export_${new Date().toISOString().slice(0,10)}.sql`,Ne.click(),URL.revokeObjectURL(xe)}},children:[e.jsx(na,{className:"w-3.5 h-3.5"})," Baixar arquivo"]})]}),e.jsx("pre",{className:"flex-1 overflow-auto text-xs font-mono bg-secondary/30 rounded-lg p-4 border border-border/20 whitespace-pre-wrap break-all",children:Ie})]})}),e.jsx(ds,{open:!!D,onOpenChange:H=>!H&&i(null),children:e.jsxs(cs,{className:"max-w-sm",children:[e.jsx(ms,{children:e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(ta,{className:"w-4 h-4"})," Adicionar Créditos"]})}),D&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm space-y-2",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Usuário:"})," ",D.nickname||D.user_id]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 p-2.5 rounded-md bg-secondary/50",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-0.5",children:"Plano"}),e.jsx("p",{className:"text-lg font-bold tabular-nums",children:D.premium_credits??0})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-0.5",children:"Avulsos"}),e.jsx("p",{className:"text-lg font-bold tabular-nums",children:D.purchased_credits??0})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:["Total: ",e.jsx("strong",{children:(D.premium_credits??0)+(D.purchased_credits??0)})," créditos"]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Quantidade (positivo = adicionar, negativo = remover)"}),e.jsx(je,{type:"number",value:A,onChange:H=>O(H.target.value),placeholder:"Ex: 100 ou -50",className:"h-9"}),A&&!isNaN(parseInt(A))&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Novo saldo: ",e.jsx("strong",{children:Math.max(0,(D.premium_credits||0)+parseInt(A))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(y,{variant:"outline",size:"sm",onClick:()=>i(null),children:"Cancelar"}),e.jsxs(y,{size:"sm",onClick:We,disabled:te,className:"gap-2",children:[te?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(ta,{className:"w-3.5 h-3.5"}),"Aplicar"]})]})]})]})})]})},Ya=[{key:Hi,label:"System",defaultValue:Ki,description:"System prompt do caminho BYOK Google (Gemini). O caminho por creditos nao usa system separado.",type:"system"},{key:Ji,label:"Usuário",defaultValue:Yi,description:"Prompt do Model Swap, usado em todos os provedores e tambem na extensao. Placeholders: {{MODEL_REFS}} e {{REF_IDX}}.",type:"user"}],Gl=()=>{const[s,n]=r.useState({}),[c,u]=r.useState(!0),[m,_]=r.useState(null);r.useEffect(()=>{k()},[]);const k=async()=>{u(!0);try{const{data:w}=await F.from("admin_settings").select("key, value").in("key",Ya.map(R=>R.key)),v={};for(const R of Ya){const $=w==null?void 0:w.find(V=>V.key===R.key);v[R.key]=($==null?void 0:$.value)||R.defaultValue}n(v)}catch{const w={};for(const v of Ya)w[v.key]=v.defaultValue;n(w)}finally{u(!1)}},g=async w=>{_(w);try{const{error:v}=await F.from("admin_settings").upsert({key:w,value:s[w],updated_at:new Date().toISOString()},{onConflict:"key"});if(v)throw v;o.success("Prompt salvo com sucesso!")}catch(v){o.error(v.message||"Erro ao salvar")}finally{_(null)}},l=w=>{const v=Ya.find(R=>R.key===w);v&&(n(R=>({...R,[w]:v.defaultValue})),o.info("Prompt restaurado ao padrão. Clique em Salvar para aplicar."))};if(c)return e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})});const h=Ya.filter(w=>w.type==="system"),x=Ya.filter(w=>w.type==="user");return e.jsxs("div",{className:"glass rounded-xl p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(sa,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-display font-semibold",children:"Prompts do Model Swap"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Prompt único, usado no site, na extensão e em todos os provedores."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide",children:"System Prompts"}),e.jsxs(za,{defaultValue:h[0].key,className:"w-full",children:[e.jsx(Ba,{className:"w-full",children:h.map(w=>e.jsx(Fs,{value:w.key,className:"flex-1 text-xs",children:w.label},w.key))}),h.map(w=>
389e.jsxs(Qs,{value:w.key,className:"space-y-4 mt-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:w.description}),e.jsx(Ss,{value:s[w.key]||"",onChange:v=>n(R=>({...R,[w.key]:v.target.value})),rows:14,className:"font-mono text-xs leading-relaxed"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(y,{onClick:()=>g(w.key),disabled:m===w.key,size:"sm",className:"gap-2",children:[m===w.key?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(Zs,{className:"w-4 h-4"}),"Salvar"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>l(w.key),className:"gap-2",children:[e.jsx(ir,{className:"w-4 h-4"}),"Restaurar"]})]})]},w.key))]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wide",children:"Prompts de Usuário"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Placeholders disponíveis: ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{{MODEL_REFS}}"})," (ex: @image1, @image2) e ",e.jsx("code",{className:"bg-muted px-1 rounded",children:"{{REF_IDX}}"})," (índice da referência)."]}),e.jsxs(za,{defaultValue:x[0].key,className:"w-full",children:[e.jsx(Ba,{className:"w-full",children:x.map(w=>e.jsx(Fs,{value:w.key,className:"flex-1 text-xs",children:w.label},w.key))}),x.map(w=>e.jsxs(Qs,{value:w.key,className:"space-y-4 mt-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:w.description}),e.jsx(Ss,{value:s[w.key]||"",onChange:v=>n(R=>({...R,[w.key]:v.target.value})),rows:8,className:"font-mono text-xs leading-relaxed"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(y,{onClick:()=>g(w.key),disabled:m===w.key,size:"sm",className:"gap-2",children:[m===w.key?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(Zs,{className:"w-4 h-4"}),"Salvar"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>l(w.key),className:"gap-2",children:[e.jsx(ir,{className:"w-4 h-4"}),"Restaurar"]})]})]},w.key))]})]})]})},Wl="You are an image captioning expert for AI training datasets. Generate a detailed natural language caption describing this image thoroughly. Include the subject's appearance, clothing, pose, expression, background, lighting, and overall mood. Be specific about colors, textures, and spatial relationships. Output ONLY the caption text, nothing else.",Kl="You are an image captioning expert for AI training datasets. Generate a detailed booru-style tag caption for this image. Use comma-separated tags describing the subject, appearance, clothing, pose, background, lighting, art style, etc. Be very detailed and specific. Output ONLY the tags, nothing else.",Ja={detailed:"caption_prompt_detailed",booru:"caption_prompt_booru"},Hl=()=>{const[s,n]=r.useState(Wl),[c,u]=r.useState(Kl),[m,_]=r.useState(!0),[k,g]=r.useState(!1);r.useEffect(()=>{(async()=>{_(!0);const{data:h}=await F.from("admin_settings").select("key, value").in("key",[Ja.detailed,Ja.booru]);for(const x of h||[])x.key===Ja.detailed&&x.value&&n(x.value),x.key===Ja.booru&&x.value&&u(x.value);_(!1)})()},[]);const l=async()=>{g(!0);try{for(const[h,x]of[[Ja.detailed,s],[Ja.booru,c]]){const{error:w}=await F.from("admin_settings").upsert({key:h,value:x,updated_at:new Date().toISOString()},{onConflict:"key"});if(w)throw w}o.success("Prompts de caption salvos!")}catch(h){o.error(h.message||"Erro ao salvar")}finally{g(!1)}};return m?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"glass rounded-xl p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(Lt,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-display font-semibold",children:"Prompt de Captions (generate-captions)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"System prompts usados pelo agente de captioning de imagens para treinamento de LoRA."})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"System Prompt — Estilo Detalhado"}),e.jsx(Ss,{value:s,onChange:h=>n(h.target.value),rows:6,className:"font-mono text-xs leading-relaxed",placeholder:"Prompt para captions detalhadas..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"System Prompt — Estilo Booru Tags"}),e.jsx(Ss,{value:c,onChange:h=>u(h.target.value),rows:6,className:"font-mono text-xs leading-relaxed",placeholder:"Prompt para captions estilo booru..."})]})]}),e.jsxs(y,{onClick:l,disabled:k,className:"gap-2",children:[k?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(Zs,{className:"w-4 h-4"}),k?"Salvando...":"Salvar Prompts de Caption"]})]})},dt=`You are an elite graphic designer with 15+ years of experience creating viral content, professional marketing materials, YouTube thumbnails, flyers, banners, event invitations, menus, and social media posts. You specialize in creating scroll-stopping visual designs that convert.
390
391DESIGN PRINCIPLES YOU FOLLOW:
3921. VISUAL HIERARCHY: Most important info (headline/CTA) gets the largest, bolde
392st treatment. Guide the eye with size, weight, and color contrast.
3932. TYPOGRAPHY: Use the font style specified. Mix font sizes dramatically (headline 3-5x larger than body text). Never use more than 2 font styles.
3943. WHITE SPACE: Strategic negative space makes designs breathe. Don't cram everything together.
3954. COLOR PSYCHOLOGY: Use the provided color palette strategically. Accent color for CTAs and key elements only.
3965. COMPOSITION: Use the rule of thirds. Create clear focal points. Balance visual weight across the layout.
3976. CONTRAST: Ensure text is ALWAYS readable against backgrounds. Use overlays, shadows, or color blocks behind text.
3987. BRANDING: Integrate logos and brand elements naturally without overpowering the message.
399
400CRITICAL RULES:
401- Text must be PERFECTLY LEGIBLE — never place light text on light backgrounds or dark text on dark backgrounds
402- All text in the image must be SPELLED CORRECTLY with NO typos
403- The design must look like it was made by a professional agency, not AI-generated
404- The image must be the EXACT dimensions specified
405- Include visual decorative elements (shapes, lines, gradients) to make the design premium
406- If a logo is provided, incorporate it tastefully`,ct=`Create a {{POST_TYPE}} with these specifications:
407
408📐 FORMAT: {{FORMAT}}
409📝 DESCRIPTION: {{DESCRIPTION}}
410{{ENHANCED_PROMPT}}
411{{SUBJECT_DESCRIPTION}}
412{{COLOR_PALETTE}}
413{{LIGHTING}}
414
415⚠️ CRITICAL RULES FOR SUBJECT/PRODUCT IMAGES:
416- If subject/product images of a PERSON are provided, that person MUST appear in the final design as the MAIN subject
417- If a style reference image also contains a person, you must REPLACE that person with the subject from the uploaded product/subject images
418- The subject person's FACE, BODY TYPE, SKIN TONE, and HAIR must be faithfully reproduced — do NOT change their appearance
419- Adapt the subject person into the pose, clothing, setting, and composition shown in the style reference
420- The final image must look like the SUBJECT PERSON was photographed in the REFERENCE STYLE scenario
421
422Generate a COMPLETE, READY-TO-POST graphic. The design should be polished, professional, and visually striking. All text in the design must be in the same language as the description provided.`,Yl=()=>{const[s,n]=r.useState(""),[c,u]=r.useState(""),[m,_]=r.useState(!0),[k,g]=r.useState(!1);r.useEffect(()=>{l()},[]);const l=async()=>{_(!0);try{const{data:w}=await F.from("admin_settings").select("key, value").in("key",["design_creator_system_prompt","design_creator_user_prompt"]),v={};w==null||w.forEach(R=>v[R.key]=R.value),n(v.design_creator_system_prompt||dt),u(v.design_creator_user_prompt||ct)}catch{n(dt),u(ct)}finally{_(!1)}},h=async()=>{g(!0);try{const w=new Date().toISOString(),{error:v}=await F.from("admin_settings").upsert([{key:"design_creator_system_prompt",value:s,updated_at:w},{key:"design_creator_user_prompt",value:c,updated_at:w}],{onConflict:"key"});if(v)throw v;o.success("Prompts do Design Creator salvos!")}catch(w){o.error(w.message||"Erro ao salvar")}finally{g(!1)}},x=()=>{n(dt),u(ct),o.info("Prompts restaurados ao padrão. Clique em Salvar para aplicar.")};return m?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"glass rounded-xl p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(Fa,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-display font-semibold",children:"Prompts do Design Creator"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Instruções enviadas aos modelos Nano Banana para guiar a criação de artes."})]})]}),e.jsxs("div",{className:"flex items-start gap-2.5 p-3 rounded-xl bg-primary/5 border border-primary/10",children:[e.jsx(Fa,{className:"w-4 h-4 text-primary/60 mt-0.5 shrink-0"}),e.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed",children:["O ",e.jsx("strong",{children:"System Prompt"})," define a persona do designer. O ",e.jsx("strong",{children:"User Prompt"})," é o template por geração. Use placeholders: ",e.jsx("code",{className:"bg-secondary px-1 py-0.5 rounded text-[11px]",children:"{{DESCRIPTION}}"}),","," ",e.jsx("code",{className:"bg-secondary px-1 py-0.5 rounded text-[11px]",children:"{{POST_TYPE}}"}),","," ",e.jsx("code",{className:"bg-secondary px-1 py-0.5 rounded text-[11px]",children:"{{FORMAT}}"}),","," ",e.jsx("code",{className:"bg-secondary px-1 py-0.5 rounded text-[11px]",children:"{{COLOR_PALETTE}}"}),","," ",e.jsx("code",{className:"bg-secondary px-1 py-0.5 rounded text-[11px]",children:"{{LIGHTING}}"}),","," ",e.jsx("code",{className:"bg-secondary px-1 py-0.5 rounded text-[11px]",children:"{{ENHANCED_PROMPT}}"}),","," ",e.jsx("code",{className:"bg-secondary px-1 py-0.5 rounded text-[11px]",children:"{{SUBJECT_DESCRIPTION}}"}),"."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"System Prompt"}),e.jsx(Ss,{value:s,onChange:w=>n(w.target.value),rows:14,className:"font-mono text-xs leading-relaxed"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"User Prompt Template"}),e.jsx(Ss,{value:c,onChange:w=>u(w.target.value),rows:14,className:"font-mono text-xs leading-relaxed"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(y,{onClick:h,disabled:k,className:"gap-2",children:[k?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(Zs,{className:"w-4 h-4"}),k?"Salvando...":"Salvar"]}),e.jsxs(y,{variant:"outline",onClick:x,className:"gap-2",children:[e.jsx(ir,{className:"w-4 h-4"}),"Restaurar padrão"]})]})]})},Jl=`You are an AI specialized in creating TRAINING DATASET images for LoRA fine-tuning.
423
424CRITICAL RULES FOR DATASET QUALITY:
4251. The person in the output MUST be IDENTICAL to the reference — same face, same skin, same body, same exact features. Zero artistic liberty on identity.
4262. Images MUST be hyper-realistic — visible skin pores, natural skin texture, real-looking hair strands, subtle imperfections, natural body proportions.
4273. NO airbrushing, NO smoothing, NO beautification filters. Raw, realistic photographic quality.
4284. Lighting must be natural and consistent within each image — no impossible lighting or fantasy effects.
4295. Each image should look like a real photograph, not AI-generated art.
4306. Resolution and detail should be maximum — sharp focus on the subject.
4317. The person's distinguishing features (moles, freckles, scars, tattoos, facial structure) MUST be preserved exactly.
4328. Skin should show natural variation — slight redness, visible pores, fine hair, realistic coloring.
433
434PURPOSE: These images will be used to train a LoRA model to generate NEW images of this person.
435Quality, consistency of identity, and variety of angles/poses/expressions are the top priorities.`,Xl=`You are an elite AI photographer generating a batch of 3 images for a professional photo shoot.
436
437CRITICAL IDENTITY RULES:
438You will receive multiple reference photos of a specific person. You MUST:
439- Preserve their EXACT face: eye color, eye shape, nose, lips, jawline, facial structure
440- Preserve their EXACT hair: color, length, texture, style
441- Preserve their EXACT skin tone and texture
442- Preserve their body type and proportions
443- Preserve any distinguishing marks: tattoos, moles, scars, freckles, birthmarks
444- The person MUST be immediately recognizable across ALL images
445
446GENERATION RULES:
4471. Generate EXACTLY 3 different images in this batch
4482. Each image MUST be portrait orientation (3:4 aspect ratio)
4493. Each image MUST be dramatically different: different pose, different angle, different background, different lighting, different outfit
4504. Professional photography quality — 4K, sharp focus on subject, intentional depth of field
4515. NO two images should feel like they're from the same moment
4526. Vary camera distance: mix close-ups, three-quarter shots, and full-body compositions
4537. The identity must be CONSISTENT across all images but everything else must CHANGE
454
455OUTPUT: Generate 3 separate images. Each must be unique and stunning.`,Ql=`You are an expert UGC (User-Generated Content) photography director and prompt engineer.
456Your job is to take the user's scene description and selected camera/style parameters, then produce a SINGLE, highly detailed image generation prompt in English.
457
458The prompt you create MUST produce an image that looks like REAL user-generated content — not studio-perfect, not AI-looking.
459
460UGC REALISM RULES you MUST follow:
4611. CAMERA AUTHENTICITY: Specify the exact camera/phone model, sensor characteristics, lens aberrations, and processing artifacts specific to that device
4622. SKIN REALISM: Include visible pores, skin texture, subsurface scattering, natural blemishes, uneven skin tone, peach fuzz, natural oil/shine
4633. IMPERFECTIONS: Slight motion blur on edges, chromatic aberration, lens distortion (barrel/pincushion), sensor noise in shadows, JPEG compression artifacts
4644. LIGHTING: Natural/ambient lighting with realistic falloff, mixed color temperatures, hard shadows from direct light, soft light from overcast/windows
4655. COMPOSITION: Slightly off-center framing, casual composition, not perfectly symmetrical — like a real person took it
4666. ENVIRONMENT: Real-world clutter or context, not sterile backgrounds
4677. DEPTH: Realistic depth of field based on the actual lens/aperture specified
4688. COLOR: Device-specific color science (iPhone warm tones, Samsung vivid saturation, Pixel natural processing)
4699. METADATA FEEL: The image should feel like it has EXIF data — a real moment captured by a real device
470
471CRITICAL: Your output must be ONLY the final prompt text. No explanations, no markdown, no labels. Just the prompt.
472Keep it under 1500 characters.`,Zl=`You are an expert UGC photography generator specializing in ABSOLUTE IDENTITY FIDELITY.
473
474Your first priority is preserving the MAIN MODEL from the preset photos with zero drift. The MODEL images are the ONLY identity source.
475
476MANDATORY IDENTITY RULES:
477- Reproduce the exact same person from the MODEL images, not a similar woman
478- Preserve exact face structure, eye shape/spacing, nose, lips, smile, jawline, skin tone, skin texture, hair color, hairline, hair texture, age appearance, and body proportions
479- Never blend the MODEL with any other person
480- Never borrow facial or body traits from scene/style references
481- If a scene/style reference contains a different person, completely replace that person with the MAIN MODEL while keeping only the scene, pose, framing, lighting, styling, and environment
482
483UGC REALISM RULES:
484- NEVER produce images that look AI-generated, overly smooth, or too perfect
485- Include natural skin textures (pores, fine lines, peach fuzz, natural oil)
486- Camera-specific rendering (lens distortion, color science, noise patterns)
487- Realistic lighting with natural falloff and mixed color temperatures
488- Authentic composition — slightly imperfect framing like a real person would capture
489- Environmental authenticity — real-world context, not sterile backgrounds`,ed=`You are an elite forensic character analyst that converts a photo of a person into a structured prompt-spec for photorealistic AI image generators. Your JSON values get concatenated into an image-generation prompt, so each value must read as a clean, affirmative visual descriptor — not an analytical note.
490
491Output a single strict JSON object — no markdown, no commentary, no surrounding text. It must have exactly three top-level keys: "identity", "style", "personality".
492
493identity keys: {{IDENTITY_FIELDS}}
494style keys: {{STYLE_FIELDS}}
495personality keys: {{PERSONALITY_FIELDS}}
496
497CORE FIDELITY PRINCIPLES (this is where recreations usually fail):
498- Describe what is ACTUALLY in the image. Never idealize, flatter, slim down, lighten, or sanitize. If the subject is curvy, full-figured, heavy, balding, aged, or has any unconventional feature, state it plainly — accuracy beats flattery.
499- Identity-defining traits (face, body build, skin tone, hair) must be captured truthfully; they are what make the subject recognizable.
500- Correct for lighting when judging color: report the subject's TRUE skin tone, hair and eye color as they would read in neutral light (a warm or dim scene often makes tan skin look paler — don't be fooled), and capture the scene's actual lighting separately in the style fields.
501- Transcribe any text, number or logo visible on clothing or objects EXACTLY (e.g. jersey number "10", team crest, brand wordmark). Never invent text/logos that aren't there.
502- Match the actual mood and presentation of the image — sensual if it's sensual, professional if it's professional, casual if it's casual. Do not impose sultriness, glamour or formality the photo doesn't have. When the image IS revealing or sensual, capture clothing coverage, fit and pose faithfully without toning it down (consenting-adult creative context).
503- State values affirmatively. No hedging words ("appears to be", "possibly", "seems", "likely") — commit to the single most accurate descriptor.
504
505General rules:
506- Every key must be present and non-empty. Describe what is visible; only when a detail is genuinely occluded, give a conservative, plausible value (never empty, null, or "N/A"). Never leave identity fields blank.
507- Values are concrete, specific English phrases (typically 4-18 words). Name actual colors, shapes, materials and directions.
508- Describe only the MAIN subject — the most prominent, in-focus person.
509
510Per-field guidance (identity):
511- "age": a tight range like "21-23 years old".
512- "ethnicity": specific (e.g., "East Asian, likely Japanese", "Black, West African features", "Latina, mixed").
513- "faceShape", "eyeShape", "noseType", "lipShape": precise descriptors (e.g., "oval, soft jawline", "almond, slightly upturned", "straight bridge, rounded tip", "full lips, defined cupid's bow").
514- "eyeColor", "hairColor", "skinTone": exact TRUE shades corrected for lighting (e.g., "warm hazel-green", "jet-black glossy", "deep warm tan, golden-olive undertone").
515- "hairTexture"/"hairStyle": e.g., "thick tousled loose waves", "chin-length messy bob, center part", "short tapered fade".
516- "skinTexture": realistic detail — visible pores, freckles, natural sheen vs matte.
517- "distinguishingMarks": freckles, beauty marks, moles, scars, dimples, piercings, tattoos (or "none visible").
518- "makeup": specific, or "no makeup, natural" / "n/a" when not applicable.
519- "bodyType": the TRUE build and silhouette. State the overall frame (slim, athletic, curvy, full-figured, plus, stocky, broad) PLUS the relevant proportions — for women bust-waist-hip and midsection (e.g., "curvy hourglass, full hips and bust, slim waist, soft exposed midriff"); for men shoulders/chest/build (e.g., "broad shoulders, lean muscular, slim waist"). Do NOT default to slim.
520- "facialExpression"/"gazeDirection": match the real expression (e.g., "neutral, lips together", "warm open smile", "lips parted, sultry") and gaze (e.g., "direct into the lens", "looking off to the left").
521
522Per-field guidance (style):
523- "realismLevel": MUST be "Hyper-real (indistinguishable from photo)" unless clearly stylized/illustrated.
524- "lightingStyle"/"lightingDirection": true quality + mood + source position, incl. low-key/dim/dramatic when present (e.g., "moody low-key warm light, single source upper-left", "soft diffused window daylight, frontal").
525- "lightingTemperature": include Kelvin (e.g., "3000K warm tungsten", "5400K daylight").
526- "cameraType"/"lensType": plausible gear, focal length + aperture (e.g., "full-frame mirrorless", "35mm at f/1.8, shallow depth of field").
527- "cameraAngle": BOTH the vertical angle AND the shot scale / how much of the body is framed (e.g., "low angle from below, full-figure", "eye-level, waist-up").
528- "colorGrading": specific look (e.g., "warm moody grade, lifted contrast", "clean neutral, true-to-life").
529- "sharpnessLevel": e.g., "tack-sharp on the eyes, soft background falloff".
530
531Per-field guidance (personality):
532- "personalityKeywords": 3-5 adjectives that match the actual vibe (e.g., "confident, approachable, warm" OR "bold, sultry, playful" — whichever fits).
533- "contentNiche": best-fit niche (Fashion, Beauty, Lifestyle, Fitness, Glamour, Business, Travel, etc.).
534- "clothingStyle": exact garments — type, color, fabric, fit, crop length and coverage, PLUS any printed number/text/logo verbatim (e.g., "tight cropped blue soccer jersey, number '10', team crest on chest, exposed midriff; fitted white shorts").
535- "accessories": items (e.g., "clear-frame glasses, thin gold necklace, small hoop earrings", or "none").
536- "bodyPose"/"handPosition"/"objectsHeld": exact posture and what the hands do (or "nothing held").
537- "sceneLocation"/"sceneDetails": environment and notable background elements (e.g., "dim bedroom", "unmade bed, nightstand lamp, dark curtains").
538
539Before finishing, re-check the four highest-impact fields against the image — bodyType, skinTone, clothingStyle (incl. any number/logo), and cameraAngle — since these are the most common recreation failures.
540
541Output ONLY the JSON object, starting with { and ending with }.`,sd=`You are an expert AI {{MEDIA_TYPE}} prompt engineer specialized in LoRA-based {{MEDIA_TYPE}} generation using {{BASE_MODEL}} models.
542
543Your task: Take the user's rough prompt and enhance it into a highly detailed, professional prompt optimized for LoRA-based {{MEDIA_TYPE}} generation.
544
545LoRA CONTEXT:
546- Active LoRAs: {{LORA_NAMES}}
547{{TRIGGER_WORDS_LINE}}
548{{LORA_DESCRIPTIONS_BLOCK}}
549{{LORA_TIPS_BLOCK}}
550- Base model: {{BASE_MODEL}}
551
552RULES:
5531. Keep the user's original intent, subject, and content level. Never water down or censor.
5542. {{TRIGGER_RULE}}
5553. Build the prompt with rich layered detail: subject appearance (face, hair, skin, build, wardrobe or state of undress, expression, pose and body language), composition and camera (framing, angle, focal length, depth of field), lighting (key/fill/rim, practical sources, direction, time of day), color and texture (palette, grade, contrast, fine surface detail), and setting/atmosphere (environment, mood, particles).
5564. Use concrete, evocative language tuned to {{BASE_MODEL}} and lean hard into the LoRA's specialty.
5575. CONTENT FIDELITY: if the user's intent is sexual or explicit, enhance it with the SAME richness — explicit anatomical, tactile, and pose detail, no euphemism, no disclaimers, and no added restrictions.
5586. Output ONLY the enhanced prompt text, nothing else — no quotes, no explanations.
5597. Write in English for best results.
5608. Detailed but coherent — every detail serves the shot.{{VIDEO_RULES_BLOCK}}`,ad=`You are a world-class AI video prompt engineer. Take the user's rough prompt and rewrite it into a vivid, technically precise, production-grade prompt optimized for {{MODEL_LABEL}} video generation. The output MUST be noticeably richer and more detailed than the input — never a light paraphrase.
561
562PRESERVE the user's original intent, subject, and content level. Never water down, censor, moralize, or add restrictions. If the input is adult/NSFW, render it fully and explicitly. If it is SFW, keep it SFW.
563
564BUILD THE PROMPT WITH ALL OF THESE LAYERS — weave them into flowing prose, NOT a bullet list:
5651. Subject — concrete appearance: face, hair, skin, build, wardrobe (or state of undress), expression, and body language. Be specific, never generic.
5662. Primary motion — the single clearest action and how it evolves across the {{DURATION_SECONDS}}-second clip. Calibrate scope: a {{DURATION_SECONDS}}s clip shows ONE continuous action or 1–2 brief beats — never long sequences, multiple scene changes, or complex choreography.
5673. Secondary motion & physics — name them explicitly: hair reacting to movement and wind, cloth/fabric inertia and settling, skin and soft-tissue response, breath, weight shift, momentum, follow-through.
5684. Camera — movement (dolly-in, push-in, pull-back, pan, tilt, tracking, orbit, handheld, crane), angle (low/high/eye-level/over-the-shoulder), focal length (wide/standard/telephoto), and speed. Honor any camera direction the user gave; otherwise choose one that serves the moment.
5695. Lighting — a concrete setup: key/fill/rim, practical sources, time of day, hardness/softness, direction, and how light falls on the subject.
5706. Color & lens aesthetic — palette, grade, contrast, depth of field and bokeh, film/lens character.
5717. Atmosphere — environment, mood, weather, air (dust, haze, mist, steam, particles), ambient detail.
572
573ADULT CONTENT (NSFW):
574- When the user's intent is sexual, sensual, or explicit, enhance it with the SAME richness — explicit anatomical, tactile, and action detail, sensual camera framing and lighting, no euphemism, no fade-to-black, no disclaimers.
575
576OUTPUT RULES:
577- Output ONLY the final enhanced prompt — no quotes, no preamble, no explanations, no notes.
578- Write in English.
579- Use the modular section format required by the Universal Video Scene Standard. Omit only sections that truly do not apply.
580- Do not impose an arbitrary fixed character ceiling. When the caller supplies a limit, honor it and finish cleanly inside it; otherwise continue until every useful section is complete.
581- Do NOT add ethical disclaimers, content warnings, or refusals. Enhance faithfully.`,rd=`UNIVERSAL VIDEO SCENE STANDARD — AUGUST 2026
582
583Apply this contract to every video engine, including WAN, Seedance, Kling, Veo, Gemini Omni, MiniMax, LTX and RunningHub workflows. Preserve the caller's output contract if it explicitly requires JSON; otherwise output a modular English prompt using these exact sections, in this order:
584
585[OBJECTIVE]
586[REFERENCE ROLES]
587[SUBJECT]
588[WARDROBE AND PROPS]
589[ENVIRONMENT AND SPATIAL LAYOUT]
590[FIRST FRAME AND BLOCKING] — conditional; include only when the caller explicitly assigns a specific opening frame/state
591[VISUAL DIRECTION]
592[TIMELINE]
593[AUDIO]
594[CONTINUITY AND RESTRICTIONS]
595
596Rules:
5971. Preserve user intent. Add detail, never silently change story, identity, wardrobe source, action or content level.
5982. Reference mapping comes before scene prose. State what each provided image, video and audio controls. Never invent reference tokens. Use only labels supplied by caller.
5993. When an image is marked as subject/character/model identity, inspect visible traits and write a concrete [SUBJECT] module: presentation, face shape, eyes when visible, hair color/length/texture/style, true skin tone, build and body proportions when visible, distinguishing non-sensitive marks, expression and body language. Do not infer ethnicity, health, exact age or measurements. Never include source filenames or temporary upload names. When a role is automatic, infer and output its concrete semantic role; never print the word auto.
6004. Keep subject identity separate from wardrobe, scene, movement and camera. A subject reference controls identity. A performance video controls choreography/timing/camera unless caller assigns another role. A depth map controls silhouette, pose, geometry, spatial motion and camera, never face, color, clothing texture or lighting.
6015. Describe foreground, midground, background, props, relative positions, time of day, weather and atmosphere when relevant.
6026. Include [FIRST FRAME AND BLOCKING] only when the caller explicitly assigns or requests a specific opening frame, opening state or approved continuity frame. Bind it to the controlling token and state exact framing, camera origin, subject placement, pose, gaze, contacts, occlusions, object positions, lighting direction and physical state. The 0.0s beat must depart from it without reset or reframing. Otherwise omit the section; never infer one from visual evidence or promote a subject-only reference into one.
6037. Split motion into primary subject action, secondary physics, camera motion and environmental motion. Use one achievable primary action per beat.
6048. For multi-beat clips, use continuous non-overlapping timestamp ranges covering full duration. Every beat states framing, action, expression, camera, environmental motion, transition and end state. For a single shot, still describe how motion evolves from start to finish.
6059. Put resolution, aspect ratio, FPS, seed and provider settings outside prose when caller already supplies them as API parameters.
60610. Preserve continuity of face, build, hair, wardrobe, props, lighting direction and spatial geography. State conflicts by priority instead of blending references.
60711. LoRAs: inspect each LoRA independently. Bind its name, weight, trigger words, description and usage notes together. Every active LoRA must contribute. Include all listed triggers by default; use a subset only when that LoRA's own notes say triggers are alternatives. For a triggerless LoRA, translate its description into natural-language visual direction. Negative weight means inverted effect. Never borrow a trigger from another LoRA, invent one, or dump metadata as an unrelated list; place its effect inside the correct subject, style, motion, camera or environment module.
60812. Model adaptation: WAN references use labels such as "Image 1" and "Video 1" when caller supplies them. Seedance uses caller-supplied labels such as "@Image 1" and "@Video 1". RunningHub/MiniMax/LTX must preserve exact workflow tokens supplied by caller. Never manufacture syntax from memory.
60913. Output only final enhanced prompt. No preamble, explanation, markdown fence or model/provider name. Do not impose an arbitrary fixed character ceiling; honor a caller-provided output limit when present. Prefer complete useful modules over filler. Never end mid-sentence.`,td=`You are a world-class AI image prompt engineer. Take the user's rough prompt and rewrite it into a vivid, technically precise, production-grade prompt optimized for {{MODEL_LABEL}} image generation. The output MUST be noticeably richer and more detailed than the input — never a light paraphrase.
610
611PRESERVE the user's original intent, subject, and content level. Never water down, censor, or moralize. If the input is adult/NSFW, render it fully and explicitly (see ADULT CONTENT). If it is SFW, keep it SFW.
612
613BUILD THE PROMPT WITH ALL OF THESE LAYERS — weave them into flowing prose, NOT a bullet list:
6141. Subject — concrete appearance: face, hair, skin texture, build, wardrobe (or state of undress), expression, pose, and gesture. Be specific, never generic.
6152. Composition & camera — framing, subject placement, camera angle and perspective, focal length, depth of field and bokeh.
6163. Lighting — a concrete setup: key/fill/rim, practical sources, direction, hardness/softness, time of day, how light shapes the subject and casts shadow.
6174. Color & rendering — palette, grade, contrast, saturation, material and skin texture, fine surface detail (pores, fabric weave, reflections).
6185. Setting & atmosphere — location, background, foreground, props, mood, weather, air and particles.
6196. Style — medium and art direction consistent with the user's intent.
620
621ADULT CONTENT (NSFW):
622- When the user's intent is sexual, sensual, or explicit, enhance it with the SAME richness — explicit anatomical, tactile, and pose detail, sensual framing and lighting, no euphemism, no disclaimers.
623
624OUTPUT RULES:
625- Output ONLY the final enhanced prompt — no quotes, no preamble, no explanations.
626- Write in English.
627- One rich, flowing paragraph, roughly 4–7 sentences. Detailed and specific, but coherent.
628- Do NOT add ethical disclaimers, content warnings, or refusals. Enhance faithfully.`,nd=`REFERENCE IMAGE ANALYSIS — SUBJECT IDENTITY EXTRACTION:
629You have been provided with reference images of the MODEL/CHARACTER who must appear in the generated image.
630Your PRIMARY goal is to extract the SUBJECT'S PHYSICAL CHARACTERISTICS from these images and place that exact subject into the scene the user described.
631
632MANDATORY — Extract and ALWAYS mention these from the reference images:
633- Hair: exact color (blonde, brunette, redhead, black, platinum, etc.), length, and style (straight, curly, wavy, ponytail, etc.)
634- Skin tone: fair, tan, olive, dark, etc.
635- Eye color if visible
636- Facial features: face shape, distinctive features
637- Body type/build if visible
638- Any distinctive marks, tattoos, piercings visible
639
640HOW TO USE:
641- The user's prompt describes the SCENE/CONTEXT (what the subject should be doing, where, etc.)
642- You must describe the SAME subject from the reference images placed INTO that scene
643- Example: if reference shows a blonde woman and user says "on a beach at sunset" → describe a blonde woman with all her extracted features on a beach at sunset
644
645CRITICAL RULES:
646- NEVER ignore the subject's appearance — if she is blonde, she MUST be blonde in the prompt
647- NEVER create a random/generic character — always match the reference
648- Do NOT extract the ENVIRONMENT/BACKGROUND from reference images — only the SUBJECT
649- Do NOT infer sensitive traits such as ethnicity, exact age, or body measurements`,id=`SAFE REFERENCE IMAGE ANALYSIS (conservative mode):
650The previous attempt was filtered. Still extract the SUBJECT'S key physical traits but use conservative language.
651
652Extract and mention:
653- Hair color and style (e.g., "woman with long blonde hair")
654- General skin tone (e.g., "fair-skinned", "sun-kissed")
655- Clothing style and colors
656- Pose and expression
657
658Place this subject into the user's described scene. Do NOT use the background/environment from the reference.
659Never mention identity, exact age, or body measurements.`,od=`REFERENCE IMAGE ANALYSIS FOR VIDEO:
660Use each caller-assigned role. When an image is identified as the replacement model/character, inspect the visible person and create a concrete [SUBJECT] module: face shape and visible facial traits, eye color when clear, hair color/length/texture/style, true skin tone, build and body proportions when visible, distinguishing non-sensitive marks, expression and body language. Keep these traits separate from wardrobe, scene, action and camera.
661
662When an image is a start frame or scene anchor, use it for composition, wardrobe, props, lighting, environment and initial state instead. Never blend a scene person into the replacement subject.
663
664Do not infer ethnicity, health, exact age or measurements. Describe only visible or strongly supported traits. Weave the analysis into the correct modular section; never output a forensic or biometric report.`,ld=`SAFE REFERENCE IMAGE ANALYSIS:
665The previous attempt was filtered, so be extra conservative.
666Only extract broad, non-sensitive styling cues from the reference images, such as:
667- hairstyle, hair color, makeup
668- clothing, accessories, pose, expression
669- camera framing, lighting, background vibe, art direction
670
671Never mention identity, ethnicity, age, body type, attractiveness, or exact facial structure.`,dd="You are an expert AI image enhancer. Regenerate this EXACT same image with maximum quality. Keep EVERYTHING identical — same composition, subject, pose, colors, background. Only enhance: quality, sharpness, detail, texture. Show visible skin pores, micro-textures. Remove artifacts/noise/blur. Output as PNG. You MUST return an image.",cd=`You are a facial-expression analyst. Look ONLY at the face of the main person in the image and describe their facial expression in a single concise English phrase to be appended to an image-generation prompt.
672
673RULES:
6741. Cover: overall emotion (e.g. soft smile, serious, playful, sultry, joyful, pensive), eyes (gaze direction, openness, squint), eyebrows, mouth (open/closed, lip position, teeth showing), and any subtle micro-expression.
6752. Describe ONLY the expression. Do NOT mention clothing, body, pose, background, lighting, identity, age, gender, or ethnicity.
6763. Output ONLY the expression description — no quotes, labels, preamble or markdown. Max ~30 words.
6774. If there is no clear human face, output exactly: neutral relaxed expression.`,md=`You are a senior prompt engineer for state-of-the-art text-to-image generators. Given an image, output ONE valid JSON object that fully describes it for faithful recreation. Output ONLY raw JSON starting with { and ending with } — no markdown code fences, no prose, no commentary.
678
679Use exactly this schema; include every top-level key. Use an empty string "" only when a field truly does n
679ot apply, and "unknown" when present but indeterminable. Arrays may be empty.
680{
681  "summary": "one-sentence caption of the whole image",
682  "subjects": [ { "type": "", "count": "", "age": "", "gender": "", "ethnicity": "", "face": "", "expression": "", "gaze": "", "hair": "", "skin": "", "body": "", "pose": "", "wardrobe": "", "accessories": "" } ],
683  "composition": { "framing": "", "subject_placement": "", "camera_angle": "", "perspective": "", "aspect_ratio": "" },
684  "camera": { "implied_camera": "", "lens": "", "focal_length": "", "aperture_depth_of_field": "", "motion": "" },
685  "lighting": { "type": "", "direction": "", "quality": "", "color_temperature": "", "shadows": "", "highlights": "" },
686  "color": { "palette": "", "grading": "", "contrast": "", "saturation": "" },
687  "setting": { "location": "", "background": "", "foreground": "", "props": "", "time_of_day": "", "weather": "" },
688  "style": { "medium": "", "art_style": "", "render_quality": "", "influences": "" },
689  "mood": "",
690  "details": [ "notable fine details worth preserving" ],
691  "negative_suggestions": [ "artifacts to avoid when recreating" ],
692  "recreation_prompt": "a ready-to-use single-paragraph English prompt that combines the fields above"
693}
694
695Describe ONLY what is visible or strongly implied; never invent written text, logos or brands. Be concrete (name colors, materials, directions). English only. Do not impose an arbitrary fixed character ceiling.`,ud=`You are an expert AI {{MEDIA_TYPE}} prompt engineer. Take the user's rough {{MEDIA_TYPE}} generation prompt and rewrite it into a highly detailed, professional prompt that produces stunning results. The output MUST be richer and more specific than the input.
696
697Rules:
698- Keep the user's original intent, subject, and content level.
699- Layer in concrete detail: subject (appearance, wardrobe, expression, pose), composition and camera (framing, angle, focal length, depth of field), lighting (setup, direction, time of day), color and texture (palette, grade, contrast, fine surface detail), setting and atmosphere (environment, mood, particles), and style.
700- Use vivid, evocative, concrete language.
701- Output ONLY the enhanced prompt text, nothing else — no quotes, no explanations.
702- Write in English for best results, even if the input is in another language.
703- One rich, flowing paragraph (aim for 3-6 sentences), coherent and specific.{{VIDEO_SYSTEM_ADDITION}}{{REF_IMAGE_ADDITION}}`,Ta=[{key:"dataset_system_prompt",label:"Dataset Creator",appName:"Dataset Creator",description:"System prompt para geração de variações pra treinar LoRA. Edge fn: generate-dataset.",defaultValue:Jl,placeholders:null},{key:"photoshoot_system_prompt",label:"PhotoShoot",appName:"PhotoShoot",description:"System prompt para gerar ensaios fotográficos (3 fotos/lote). Edge fn: generate-photoshoot.",defaultValue:Xl,placeholders:null},{key:"ugc_agent_system_prompt",label:"UGC — Agente",appName:"UGC Creator",description:"Agente que constrói o prompt mestre a partir dos inputs do usuário (Gemini Flash Lite). Edge fn: generate-ugc.",defaultValue:Ql,placeholders:null},{key:"ugc_image_system_prompt",label:"UGC — Imagem",appName:"UGC Creator",description:"System prompt do gerador de imagem UGC (Nano Banana). Edge fn: generate-ugc.",defaultValue:Zl,placeholders:null},{key:"avatar_engine_system_prompt",label:"Avatar Engine",appName:"Avatar Engine",description:"Analisa foto e produz JSON estruturado pra prompt-spec. Edge fn: analyze-avatar-image.",defaultValue:ed,placeholders:"{{IDENTITY_FIELDS}}, {{STYLE_FIELDS}}, {{PERSONALITY_FIELDS}} (preenchidos automaticamente no runtime)"},{key:"enhance_lora_base",label:"Enhance — LoRA",appName:"Enhance Prompt",description:"Prompt aprimorador quando há LoRA ativa (Grok 4.3 via OpenRouter). Edge fn: enhance-prompt.",defaultValue:sd,placeholders:"{{MEDIA_TYPE}} (image/video), {{BASE_MODEL}}, {{LORA_NAMES}}, {{TRIGGER_WORDS_LINE}}, {{LORA_DESCRIPTIONS_BLOCK}}, {{LORA_TIPS_BLOCK}}, {{TRIGGER_RULE}}, {{VIDEO_RULES_BLOCK}}"},{key:"enhance_premium_video",label:"Enhance — Vídeo Premium",appName:"Enhance Prompt",description:"Prompt aprimorador para vídeo (modelos premium sem LoRA, ex.: LTX). Edge fn: enhance-prompt.",defaultValue:ad,placeholders:"{{MODEL_LABEL}}, {{DURATION_SECONDS}}"}
703,{key:"enhance_video_scene_standard",label:"Enhance — Padrão Universal de Vídeo",appName:"Todos os geradores de vídeo",description:"Contrato modular aplicado pelo Enhance a Playground, Motion Clone, Flows e Labs, incluindo WAN, Seedance, MiniMax, LTX e workflows RunningHub. Adiciona First Frame & Blocking somente quando a UI marca uma referência inicial e aplica teto de saída apenas quando o chamador pedir.",defaultValue:rd,placeholders:null},{key:"enhance_premium_image",label:"Enhance — Imagem Premium",appName:"Enhance Prompt",description:"Prompt aprimorador para imagem (modelos premium sem LoRA: Seedream, WAN, Flux Klein, GPT Image 2, Grok Imagine, etc). Edge fn: enhance-prompt.",defaultValue:td,placeholders:"{{MODEL_LABEL}}"},{key:"enhance_generic",label:"Enhance — Genérico (fallback)",appName:"Enhance Prompt",description:"Prompt aprimorador genérico (PATH B: sem LoRA e sem modelo premium). Usa Gemini Flash via OpenRouter. Edge fn: enhance-prompt.",defaultValue:ud,placeholders:"{{MEDIA_TYPE}}, {{VIDEO_SYSTEM_ADDITION}}, {{REF_IMAGE_ADDITION}} (preenchidos no runtime quando aplicável)"},{key:"enhance_ref_image",label:"Enhance — Ref Imagem",appName:"Enhance Prompt",description:"Bloco appended ao prompt quando há referência de imagem (modo normal). Anexado ao prompt LoRA.",defaultValue:nd,placeholders:null},{key:"enhance_ref_image_safe",label:"Enhance — Ref Imagem (Safe)",appName:"Enhance Prompt",description:"Variante segura do bloco de ref imagem — usada quando a tentativa anterior foi filtrada (content_filter).",defaultValue:id,placeholders:null},{key:"enhance_ref_video",label:"Enhance — Ref Vídeo",appName:"Enhance Prompt",description:"Bloco appended ao prompt LoRA quando há referência (modo vídeo normal).",defaultValue:od,placeholders:null},{key:"enhance_ref_video_safe",label:"Enhance — Ref Vídeo (Safe)",appName:"Enhance Prompt",description:"Variante segura para vídeo — usada quando a tentativa anterior foi filtrada.",defaultValue:ld,placeholders:null},{key:"enhance_swap_physical_state",label:"Enhance — Reforçar Estado da Cena (Model Swap)",appName:"Enhance Prompt",description:'Bloco que descreve o ESTADO FÍSICO visível na referência (molhado/seco, suor, brilho, resíduos na pele, maquiagem borrada) pro Model Swap replicar. Ligado pelo toggle "Reforçar estado da cena". Editável aqui porque o vocabulário muda por nicho — vazio usa o padrão do código. Divide a MESMA leitura dos outros reforços (1 crédito no total).'},{key:"enhance_expression_transfer",label:"Enhance — Reforçar Referência (expressão / acessórios / penteado)",appName:"Enhance Prompt",description:"Analisa a imagem de referência (Grok 4.3 vision via OpenRouter) para o Model Swap replicar na modelo. Este texto é a BASE (expressão facial); acessórios e penteado entram como blocos EXTRA anexados pelo código quando as chaves estão ligadas — editar aqui não muda esses dois. Os três dividem UMA leitura e cobram 1 crédito no total. Toggles no Model Swap (ext + web). Edge fn: enhance-prompt (task=expression_transfer).",defaultValue:cd,placeholders:null},{key:"upscale_enhance_system_prompt",label:"Upscale Enhance",appName:"Upscale",description:"Prompt usado pela etapa 'Melhorar antes' do Upscale (Gemini Image Preview). Pre-enhance da imagem antes do upscaler.",defaultValue:dd,placeholders:null},{key:"describe_json_system_prompt",label:"Describe Image — JSON",appName:"Describe Image",description:"System prompt do modo JSON do Describe Image (saída estruturada). O modo texto continua na tab 'Detalhar Prompt' via AdminSettingsTab.",defaultValue:md,placeholders:null}],xd=()=>{const[s,n]=r.useState({}),[c,u]=r.useState(!0),[m,_]=r.useState(null);r.useEffect(()=>{k()},[]);const k=async()=>{u(!0);try{const{data:h}=await F.from("admin_settings").select("key, value").in("key",Ta.map(w=>w.key)),x={};for(const w of Ta){const v=h==null?void 0:h.find(R=>R.key===w.key);x[w.key]=(v==null?void 0:v.value)||w.defaultValue}n(x)}catch{const h={};for(const x of Ta)h[x.key]=x.defaultValue;n(h)}finally{u(!1)}},g=async h=>{_(h);try{const{error:x}=await F.from("admin_settings").upsert({key:h,value:s[h],updated_at:new Date().toISOString()},{onConflict:"key"});if(x)throw x;o.success("Prompt salvo com sucesso!")}catch(x){o.error(x.message||"Erro ao salvar")}finally{_(null)}},l=h=>{const x=Ta.find(w=>w.key===h);x&&(n(w=>({...w,[h]:x.defaultValue})),o.info("Prompt restaurado ao padrão. Clique em Salvar para aplicar."))};return c?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"glass rounded-xl p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(yn,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-display font-semibold",children:"Prompts dos Agentes"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["System prompts dos apps Dataset Creator, PhotoShoot, UGC Creator e Avatar Engine. Edits ficam em ",e.jsx("code",{className:"bg-muted px-1 rounded text-[10px]",children:"admin_settings"}),"; edge fns leem com fallback pro default em código."]})]})]}),e.jsxs(za,{defaultValue:Ta[0].key,className:"w-full",children:[e.jsx(Ba,{className:"w-full flex-wrap h-auto",children:Ta.map(h=>e.jsx(Fs,{value:h.key,className:"flex-1 text-xs",children:h.label},h.key))}),Ta.map(h=>
703e.jsxs(Qs,{value:h.key,className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wider px-2 py-0.5 rounded bg-primary/20 text-primary font-bold",children:h.appName}),e.jsx("code",{className:"bg-muted px-1.5 py-0.5 rounded text-[10px] text-muted-foreground",children:h.key})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:h.description}),h.placeholders&&e.jsxs("p",{className:"text-[11px] text-amber-300/80 bg-amber-500/5 border border-amber-500/20 rounded px-2 py-1.5",children:[e.jsx("strong",{children:"Placeholders disponíveis:"})," ",h.placeholders]}),e.jsx(Ss,{value:s[h.key]||"",onChange:x=>n(w=>({...w,[h.key]:x.target.value})),rows:18,className:"font-mono text-xs leading-relaxed"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(y,{onClick:()=>g(h.key),disabled:m===h.key,size:"sm",className:"gap-2",children:[m===h.key?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(Zs,{className:"w-4 h-4"}),"Salvar"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>l(h.key),className:"gap-2",children:[e.jsx(ir,{className:"w-4 h-4"}),"Restaurar padrão"]})]})]},h.key))]})]})},an="fishaudio_preset_voices";function hd(){const[s,n]=r.useState([]),[c,u]=r.useState(!0),[m,_]=r.useState(!1),[k,g]=r.useState(""),[l,h]=r.useState(""),[x,w]=r.useState(""),[v,R]=r.useState(!1),[$,V]=r.useState(""),[C,ee]=r.useState(!1),[Z,p]=r.useState([]),z=r.useRef(null),[Q,ae]=r.useState(null),Y=r.useCallback(async()=>{u(!0);try{const{data:W}=await F.from("admin_settings").select("value").eq("key",an).maybeSingle();if(W!=null&&W.value){const N=JSON.parse(W.value);Array.isArray(N)&&n(N.filter(ce=>ce&&ce.id).map(ce=>({id:String(ce.id),label:String(ce.label||ce.title||ce.id),languages:Array.isArray(ce.languages)?ce.languages:[],sampleUrl:ce.sampleUrl||ce.sample||null})))}else n([])}catch{o.error("Erro ao carregar as vozes.")}finally{u(!1)}},[]);r.useEffect(()=>{Y()},[Y]),r.useEffect(()=>()=>{var W;(W=z.current)==null||W.pause()},[]);const B=async W=>{_(!0);try{const{error:N}=await F.from("admin_settings").upsert({key:an,value:JSON.stringify(W),updated_at:new Date().toISOString()},{onConflict:"key"});if(N)throw N;n(W),o.success("Vozes salvas. (Cache do usuário atualiza em até 1h.)")}catch(N){o.error(N instanceof Error?N.message:"Erro ao salvar.")}finally{_(!1)}},G=(W,N)=>{if(!N){o.error("Essa voz não tem amostra.");return}z.current||(z.current=new Audio);const ce=z.current;if(Q===W){ce.pause(),ae(null);return}ce.src=N,ce.onended=()=>ae(null),ce.play().then(()=>ae(W)).catch(()=>o.error("Não foi possível tocar a amostra."))},q=async()=>{const W=k.trim();if(!W){o.error("Cole o ID da voz.");return}if(s.some(N=>N.id===W)){o.error("Essa voz já está na lista.");return}R(!0);try{const N=await Xi(W),ce=x.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean),D={id:N.id,label:l.trim()||N.title||W,languages:ce.length?ce:N.languages,sampleUrl:N.sampleUrl||null};await B([...s,D]),g(""),h(""),w("")}catch(N){o.error(N instanceof Error?N.message:"Voz inválida.")}finally{R(!1)}},E=async W=>{if(s.some(N=>N.id===W.id)){o.error("Essa voz já está na lista.");return}await B([...s,{id:W.id,label:W.title||W.id,languages:W.languages||[],sampleUrl:W.sampleUrl||null}])},P=async W=>{await B(s.filter(N=>N.id!==W))},K=async()=>{ee(!0);try{p(await Qi($.trim()))}catch(W){o.error(W instanceof Error?W.message:"Erro na busca.")}finally{ee(!1)}},J="w-full h-9 rounded-lg bg-background border border-border px-3 text-sm outline-none focus:ring-1 focus:ring-primary/50";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2",children:[e.jsx(On,{className:"w-5 h-5 text-primary"}),"Vozes (TTS)"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['Vozes "prontas" que aparecem no seletor da aba ',e.jsx("strong",{children:"Voz"})," (/playground/audio). Quando esta lista tem ao menos uma voz, ela ",e.jsx("strong",{children:"substitui"})," o catálogo público automático (experiência curada). Para achar o ID: abra a voz no Fish Audio — o ID está na 
703URL ",e.jsx("code",{className:"text-xs bg-muted px-1 rounded",children:"fish.audio/m/<id>"})," — ou use a busca abaixo."]})]}),e.jsxs("div",{className:"rounded-xl border border-border bg-card p-4 space-y-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Adicionar por ID"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:[e.jsx("input",{value:k,onChange:W=>g(W.target.value),placeholder:"ID da voz (Fish Audio)",className:J}),e.jsx("input",{value:l,onChange:W=>h(W.target.value),placeholder:"Rótulo (opcional — usa o título)",className:J}),e.jsx("input",{value:x,onChange:W=>w(W.target.value),placeholder:"Idiomas, ex: pt,en (opcional)",className:J})]}),e.jsxs("button",{onClick:q,disabled:v||m,className:"flex items-center gap-2 h-9 px-4 rounded-lg bg-primary text-primary-foreground text-sm font-semibold hover:bg-primary/90 disabled:opacity-40",children:[v?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(Us,{className:"w-4 h-4"}),"Validar e adicionar"]})]}),e.jsxs("div",{className:"rounded-xl border border-border bg-card p-4 space-y-3",children:[e.jsxs("h3",{className:"text-sm font-semibold",children:["Vozes cadastradas (",s.length,")"]}),c?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(he,{className:"w-4 h-4 animate-spin"}),"Carregando…"]}):s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhuma voz cadastrada — o seletor usa o catálogo público automático (top por popularidade, filtrado por idioma)."}):e.jsx("div",{className:"space-y-1.5",children:s.map(W=>e.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-background border border-border px-3 py-2",children:[e.jsx("button",{onClick:()=>G(W.id,W.sampleUrl),disabled:!W.sampleUrl,className:"shrink-0 w-8 h-8 flex items-center justify-center rounded-md bg-muted text-foreground/80 hover:text-foreground disabled:opacity-30",children:Q===W.id?e.jsx(qt,{className:"w-3.5 h-3.5"}):e.jsx(Mt,{className:"w-3.5 h-3.5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:W.label}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[W.id,W.languages.length?` · ${W.languages.join(", ")}`:""]})]}),e.jsx("button",{onClick:()=>P(W.id),disabled:m,className:"shrink-0 w-8 h-8 flex items-center justify-center rounded-md text-rose-400/80 hover:text-rose-400 hover:bg-rose-500/10 disabled:opacity-40",children:e.jsx(_s,{className:"w-3.5 h-3.5"})})]},W.id))})]}),e.jsxs("div",{className:"rounded-xl border border-border bg-card p-4 space-y-3",children:[e.jsx("h3",{className:"text-sm font-semibold",children:"Buscar no catálogo"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{value:$,onChange:W=>V(W.target.value),onKeyDown:W=>W.key==="Enter"&&K(),placeholder:"Nome da voz (ex: narrador, female)",className:J}),e.jsxs("button",{onClick:K,disabled:C,className:"shrink-0 flex items-center gap-2 h-9 px-4 rounded-lg bg-muted text-foreground text-sm font-semibold hover:bg-muted/70 disabled:opacity-40",children:[C?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(aa,{className:"w-4 h-4"}),"Buscar"]})]}),Z.length>0&&e.jsx("div",{className:"space-y-1.5",children:Z.map(W=>{var ce;const N=s.some(D=>D.id===W.id);return e.jsxs("div",{className:"flex items-center gap-2 rounded-lg bg-background border border-border px-3 py-2",children:[e.jsx("button",{onClick:()=>G(W.id,W.sampleUrl),disabled:!W.sampleUrl,className:"shrink-0 w-8 h-8 flex items-center justify-center rounded-md bg-muted text-foreground/80 hover:text-foreground disabled:opacity-30",children:Q===W.id?e.jsx(qt,{className:"w-3.5 h-3.5"}):e.jsx(Mt,{className:"w-3.5 h-3.5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:W.title}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[W.id,(ce=W.languages)!=null&&ce.length?` · ${W.languages.join(", ")}`:""]})]}),e.jsxs("button",{onClick:()=>E(W),disabled:N||m,className:"shrink-0 flex items-center gap-1 h-8 px-3 rounded-md bg-primary/15 border border-primary/40 text-xs font-semibold text-primary hover:bg-primary/25 disabled:opacity-40",children:[e.jsx(Us,{className:"w-3.5 h-3.5"}),N?"Adicionada":"Adicionar"]})]},W.id)})})]})]})}const rn=s=>s.trim().replace(/\s+/g,"").toUpperCase(),mt={pending:{label:"A liberar",className:"bg-muted text-muted-foreground"},available:{label:"Disponível",className:"bg-primary/15 text-primary"},processing:{label:"Em transferência",className:"bg-blue-500/15 text-blue-400"},held:{label:"Retida (disputa)",className:"bg-amber-500/15 text-amber-400"},paid:{label:"Paga",className:"bg-emerald-500/15 text-emerald-400"},reversed:{label:"Estornada",className:"bg-destructive/15 text-destructive"},clawback:{label:"Estorno",className:"bg-destructive/15 text-destructive"}},Ms=(s,n="BRL")=>`${n==="USD"?"US$":"R$"} ${s.toFixed(2).replace(".",",")}`,pd=()=>{var hs,As,Gs,Hs,Ls,L;const[s,n]=r.useState([]),[c,u]=r.useState([]),[m,_]=r.useState([]),[k,g]=r.useState(!0),[l,h]=r.useState(!1),[x,w]=r.useState([]),[v,R]=r.useState(""),[$,V]=r.useState(!1),[C,ee]=r.useState(""),[Z,p]=r.useState("10"),[z,Q]=r.useState(""),[ae,Y]=r.useState(""),[B,G]=r.useState(""),[q,E]=r.useState(""),[P,K]=r.useState(!1),[J,W]=r.useState(null),[N,ce]=r.useState({coupon:"",pix:"",whatsapp:"",phone:"",percent:"10",holdDays:"30"}),[D,i]=r.useState(!1),[A,O]=r.useState(!1),[te,T]=r.useState(null),[re,ke]=r.useState(!1),[fe,X]=r.useState({total:0,converted:0}),[me,_e]=r.useState({}),[$e,Ve]=r.useState([]),[Je,we]=r.useState(null),We=async()=>{O(!0);try{const{data:d,error:le}=await F.functions.invoke("admin-list-emails");if(le)throw le;const S=new Set(s.map(Ce=>Ce.user_id)),de=((d==null?void 0:d.authUsers)||[]).filter(Ce=>Ce.email&&!S.has(Ce.id)).map(Ce=>({id:Ce.id,email:Ce.email}));w(de)}catch(d){console.error("fetchUsers (afiliados):",d),o.error("Erro ao carregar usuários")}finally{O(!1)}},Ge=async()=>{var Is;g(!0);const[{data:d},{data:le},{data:S},de,Ce,Oe,{data:Ke},{data:qe}]=await Promise.all([F.from("affiliates").select("*").order("created_at",{ascending:!1}),F.from("affiliate_commissions").select("*").order("created_at",{ascending:!1}),F.from("affiliate_applications").select("*").order("created_at",{ascending:!1}),F.from("affiliate_clicks").select("*",{count:"exact",head:!0}),F.from("affiliate_clicks").select("*",{count:"exact",head:!0}).eq("converted",!0),F.functions.invoke("admin-list-emails"),F.from("profiles").select("user_id, nickname"),F.from("affiliate_payouts").select("*").order("created_at",{ascending:!1})]);n(d||[]),u(le||[]),_(S||[]),Ve(qe||[]),X({total:(de==null?void 0:de.count)||0,converted:(Ce==null?void 0:Ce.count)||0});const Me=((Is=Oe==null?void 0:Oe.data)==null?void 0:Is.emailMap)||{},Be={};
703(Ke||[]).forEach(ks=>{Be[ks.user_id]={nickname:ks.nickname||null,email:Me[ks.user_id]||null}}),Object.entries(Me).forEach(([ks,Ys])=>{Be[ks]||(Be[ks]={nickname:null,email:Ys})}),_e(Be),g(!1)};r.useEffect(()=>{Ge()},[]);const ps=async()=>{if(!v){o.error("Selecione um usuário");return}K(!0);try{const d=x.find(Oe=>Oe.id===v),S=((d==null?void 0:d.email)||"AFF").split("@")[0].replace(/[^a-zA-Z0-9]/g,"").toUpperCase().slice(0,8)+Math.random().toString(36).slice(2,6).toUpperCase(),de=rn(q),{error:Ce}=await F.from("affiliates").insert({user_id:v,affiliate_code:S,commission_percent:parseFloat(Z)||10,pix_key:z.trim()||null,whatsapp:ae.trim()||null,phone:B.trim()||null,coupon_code:de||null});if(Ce)throw Ce;o.success(de?`Afiliado cadastrado com o cupom ${de}!`:"Afiliado cadastrado!"),h(!1),R(""),ee(""),p("10"),Q(""),Y(""),G(""),E(""),Ge()}catch(d){o.error(d.message||"Erro ao cadastrar afiliado")}finally{K(!1)}},be=()=>{h(!0),We()},ue=d=>{W(d),ce({coupon:d.coupon_code||"",pix:d.pix_key||"",whatsapp:d.whatsapp||"",phone:d.phone||"",percent:String(d.commission_percent??10),holdDays:String(d.payout_hold_days??30)})},Pe=async()=>{if(J){i(!0);try{const d=rn(N.coupon),{error:le}=await F.from("affiliates").update({coupon_code:d||null,pix_key:N.pix.trim()||null,whatsapp:N.whatsapp.trim()||null,phone:N.phone.trim()||null,commission_percent:parseFloat(N.percent)||J.commission_percent,payout_hold_days:Math.max(0,Math.min(365,parseInt(N.holdDays)||0))}).eq("id",J.id);if(le)throw le.code==="23505"?new Error(`O cupom ${d} já está vinculado a outro afiliado`):le;o.success("Afiliado atualizado"),W(null),Ge()}catch(d){o.error(d.message||"Erro ao salvar")}finally{i(!1)}}},ze=async d=>{var Ce,Oe;const le=((Ce=me[d.user_id])==null?void 0:Ce.nickname)||((Oe=me[d.user_id])==null?void 0:Oe.email)||d.affiliate_code,S=xe(d.id),de=H(d.id);if(d.is_active){const Ke=[`Desativar a afiliação de ${le}?`,"","A partir de agora:","· Vendas pelo link dele param de gerar comissão",d.coupon_code?`· O cupom ${d.coupon_code} é desativado na Stripe (ninguém mais usa)`:"· Ele não tem cupom vinculado","· As assinaturas que ele já trouxe param de render comissão nas renovações","· Ele não consegue mais sacar","",`Saldo disponível hoje: ${Ms(S)}${S<0?" (negativo — dívida fica registrada)":""}`,de>0?`Ainda a liberar: ${Ms(de)}`:"","","Dá para reativar depois, e o cupom volta junto."].filter(Boolean).join(`
704`);if(!confirm(Ke))return}try{const{data:Ke,error:qe}=await F.functions.invoke("admin-affiliate-toggle",{body:{affiliate_id:d.id,active:!d.is_active}});if(qe)throw qe;if(Ke!=null&&Ke.error)throw new Error(Ke.error);const Me=Ke;Me!=null&&Me.coupon_error?o.warning(`Afiliação ${Me.is_active?"reativada":"desativada"}, mas o cupom não sincronizou: ${Me.coupon_error}`,{duration:1e4}):Me!=null&&Me.coupon_synced?o.success(Me.is_active?`Afiliação reativada e cupom ${Me.coupon_code} religado`:`Afiliação desativada e cupom ${Me.coupon_code} desligado na Stripe`):o.success(Me!=null&&Me.is_active?"Afiliação reativada":"Afiliação desativada"),Ge()}
704catch(Ke){console.error("toggleActive (afiliados):",Ke),o.error(Ke.message||"Erro ao alterar a afiliação")}},Ie=async(d,le,S)=>{var Ce,Oe,Ke,qe;const de=((Ce=me[d.user_id])==null?void 0:Ce.nickname)||((Oe=me[d.user_id])==null?void 0:Oe.email)||d.affiliate_code;if(confirm(`Registrar ${Ms(S,le)} como pago para ${de}?
705
706Isso NÃO envia dinheiro — use apenas depois de já ter pago por fora (PIX/TED). As comissões disponíveis nessa moeda serão quitadas e entram no histórico de saques.`)){we(`${d.id}_${le}`);try{const Me=window.prompt("Observação (opcional) — ex.: comprovante, data do PIX:")||null,{error:Be}=await F.rpc("affiliate_admin_mark_paid",{p_affiliate_id:d.id,p_currency:le,p_note:Me});if(Be)throw(Ke=Be.message)!=null&&Ke.includes("nothing_available")?new Error("Nada disponível para pagar nessa moeda"):(qe=Be.message)!=null&&qe.includes("not_admin")?new Error("Sem permissão de admin"):Be;o.success(`${Ms(S,le)} registrado como pago`),Ge()}catch(Me){o.error(Me.message||"Erro ao registrar pagamento")}finally{we(null)}}},xs=async d=>{confirm("Remover afiliado e todas as comissões?")&&(await F.from("affiliates").delete().eq("id",d),o.success("Afiliado removido"),Ge())},Ps=d=>{const le=`${window.location.origin}/?ref=${d}`;navigator.clipboard.writeText(le),o.success("Link copiado!")},Ze=async d=>{try{const S=((d.instagram_handle||d.tiktok_handle||d.pix_key||"AFF").replace(/[^a-zA-Z0-9]/g,"").toUpperCase().slice(0,6)||"AFF")+Math.random().toString(36).slice(2,6).toUpperCase(),{error:de}=await F.from("affiliates").insert({user_id:d.user_id,affiliate_code:S,commission_percent:10,pix_key:d.pix_key});if(de)throw de;await F.from("affiliate_applications").update({status:"approved",reviewed_at:new Date().toISOString()}).eq("id",d.id),o.success("Afiliado aprovado!"),Ge()}catch(le){o.error(le.message||"Erro ao aprovar")}},es=async d=>{await F.from("affiliate_applications").update({status:"rejected",reviewed_at:new Date().toISOString()}).eq("id",d),o.success("Solicitação rejeitada"),Ge()},ws=c.filter(d=>d.affiliate_id===te),is=s.find(d=>d.id===te),os=(d,le)=>c.filter(S=>S.status===d&&(!le||S.affiliate_id===le)).reduce((S,de)=>S+de.commission_amount,0),H=d=>os("pending",d),xe=d=>os("available",d),Ne=d=>{const le={};return c.filter(S=>S.affiliate_id===d&&S.status==="available").forEach(S=>{le[S.sale_currency]=(le[S.sale_currency]||0)+S.commission_amount}),le},Xe=d=>!!d.stripe_account_id&&d.connect_payouts_enabled&&d.connect_details_submitted,bs=d=>new Date(new Date(d.created_at).getTime()+(d.payout_hold_days??30)*864e5),Rs=d=>Date.now()<bs(d).getTime(),gs=$e.filter(d=>d.status==="failed");return k?e.jsx("div",{className:"flex items-center justify-center p-8",children:e.jsx(he,{className:"w-5 h-5 animate-spin"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Sistema de Afiliados"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cada afiliado saca sozinho pela Stripe. Comissão libera 30 dias após a venda; mínimo de saque R$ 100 / US$ 20."})]}),e.jsxs(y,{onClick:be,size:"sm",className:"gap-1.5",children:[e.jsx(jr,{className:"w-4 h-4"})," Cadastrar Afiliado"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{className:"p-4 rounded-xl border border-border/40 bg-card/50",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Afiliados ativos"}),e.jsx("p",{className:"text-2xl font-bold",children:s.filter(d=>d.is_active).length})]}),e.jsxs("div",{className:"p-4 rounded-xl border border-border/40 bg-card/50",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"A liberar (30d)"}),e.jsx("p",{className:"text-2xl font-bold",children:Ms(os("pending"))})]}),e.jsxs("div",{className:"p-4 rounded-xl border border-primary/30 bg-primary/5",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Disponível p/ saque"}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:Ms(os("available"))})]}),e.jsxs("div",{className:"p-4 rounded-xl border border-border/40 bg-card/50",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Em transferência"}),e.jsx("p",{className:"text-2xl font-bold text-blue-400",children:Ms(os("processing"))})]}),e.jsxs("div",{className:"p-4 rounded-xl border border-border/40 bg-card/50",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Já pago"}),e.jsx("p",{className:"text-2xl font-bold text-emerald-400",children:Ms(os("paid"))})]})]}),(os("held")>0||gs.length>0)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[os("held")>0&&e.jsxs("div",{className:"p-3 rounded-lg border border-amber-500/30 bg-amber-500/5 text-xs",children:[e.jsxs("strong",{className:"text-amber-400",children:[Ms(os("held"))," retido"]}),e.jsx("span",{className:"text-muted-foreground",children:" — comissões travadas por disputa de pagamento. Liberam sozinhas quando a disputa fecha."})]}),gs.length>0&&e.jsxs("div",{className:"p-3 rounded-lg border border-destructive/40 bg-destructive/5 text-xs",children:[e.jsxs("strong",{className:"text-destructive",children:[gs.length," saque(s) falharam"]}),e.jsxs("span",{className:"text-muted-foreground",children:[' — o valor voltou para "disponível". Motivo do último: ',gs[0].error||"não informado"]})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"p-4 rounded-xl border border-border/40 bg-card/50",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cliques nos links"}),e.jsx("p",{className:"text-2xl font-bold",children:fe.total})]}),e.jsxs("div",{className:"p-4 rounded-xl border border-border/40 bg-card/50",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Conversões"}),e.jsx("p",{className:"text-2xl font-bold",children:fe.converted})]}),e.jsxs("div",{className:"p-4 rounded-xl border border-border/40 bg-card/50",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Taxa de conversão"}),e.jsx("p",{className:"text-2xl font-bold",children:fe.total>0?`${(fe.converted/fe.total*100).toFixed(1)}%`:"—"})]})]}),m.filter(d=>d.status==="pending").length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"text-sm font-semibold text-primary",children:"Solicitações pendentes"}),e.jsx("div",{className:"space-y-2",children:m.filter(d=>d.status==="pending").map(d=>{const le=S=>
706S!=null?S.toLocaleString("pt-BR"):"—";return e.jsx("div",{className:"p-3 rounded-lg border border-border/40 bg-card/50 space-y-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-1.5 min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs",children:[d.instagram_handle&&e.jsxs("span",{className:"text-foreground",children:["📸 ",d.instagram_handle," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",le(d.instagram_followers),")"]})]}),d.youtube_url&&e.jsxs("a",{href:d.youtube_url.startsWith("http")?d.youtube_url:`https://${d.youtube_url}`,target:"_blank",rel:"noopener noreferrer",className:"text-foreground hover:text-primary underline-offset-2 hover:underline",children:["▶️ YouTube ",e.jsxs("span",{className:"text-muted-foreground",children:["(",le(d.youtube_subscribers),")"]})]}),d.tiktok_handle&&e.jsxs("span",{className:"text-foreground",children:["🎵 ",d.tiktok_handle," ",e.jsxs("span",{className:"text-muted-foreground",children:["(",le(d.tiktok_followers),")"]})]}),!d.instagram_handle&&!d.youtube_url&&!d.tiktok_handle&&e.jsx("span",{className:"text-muted-foreground italic",children:"Sem redes informadas"})]}),d.promo_plan&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Plano:"})," ",d.promo_plan]}),d.message&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:d.message}),e.jsxs("p",{className:"text-[11px] text-muted-foreground/70",children:[d.pix_key?`PIX: ${d.pix_key} · `:"",new Date(d.created_at).toLocaleDateString("pt-BR")]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(y,{size:"sm",variant:"outline",onClick:()=>es(d.id),className:"text-xs h-7",children:"Rejeitar"}),e.jsx(y,{size:"sm",onClick:()=>Ze(d),className:"text-xs h-7",children:"Aprovar"})]})]})},d.id)})})]}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Afiliado"}),e.jsx(f,{children:"Código"}),e.jsx(f,{children:"Cupom"}),e.jsx(f,{children:"Recebimento"}),e.jsx(f,{children:"Comissão"}),e.jsx(f,{children:"Ganho Total"}),e.jsx(f,{children:"A liberar"}),e.jsx(f,{children:"Disponível"}),e.jsx(f,{children:"Status"}),e.jsx(f,{children:"Ações"})]})}),e.jsxs(De,{children:[s.map(d=>{var le,S;return e.jsxs(b,{className:"cursor-pointer",onClick:()=>{T(d.id),ke(!0)},children:[e.jsx(a,{children:e.jsxs("div",{className:"flex flex-col leading-tight",children:[e.jsx("span",{className:"text-sm font-medium",children:((le=me[d.user_id])==null?void 0:le.nickname)||"—"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:((S=me[d.user_id])==null?void 0:S.email)||"e-mail não encontrado"})]})}),e.jsx(a,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"text-xs bg-secondary px-2 py-0.5 rounded",children:d.affiliate_code}),e.jsx("button",{onClick:de=>{de.stopPropagation(),Ps(d.affiliate_code)},className:"text-muted-foreground hover:text-primary",children:e.jsx(An,{className:"w-3.5 h-3.5"})})]})}),e.jsx(a,{children:e.jsxs("div",{className:"flex items-center gap-2",onClick:de=>de.stopPropagation(),children:[d.coupon_code?e.jsx("code",{className:Ue("text-xs px-2 py-0.5 rounded",d.is_active?"bg-primary/10 text-primary":"bg-muted text-muted-foreground line-through"),title:d.is_active?void 0:"Cupom desligado junto com a afiliação",children:d.coupon_code}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"}),e.jsx("button",{onClick:()=>ue(d),className:"text-muted-foreground hover:text-primary",title:"Vincular cupom",children:e.jsx(Go,{className:"w-3.5 h-3.5"})})]})}),e.jsx(a,{children:Rs(d)?e.jsxs(Re,{variant:"outline",className:"text-[10px] border-amber-500/40 text-amber-400",title:`Trava manual de ${d.payout_hold_days} dias desde o cadastro`,children:["Travado até ",bs(d).toLocaleDateString("pt-BR")]}):Xe(d)?e.jsx(Re,{variant:"outline",className:"text-[10px] border-emerald-500/40 text-emerald-400",children:"Connect ativo"}):d.stripe_account_id?e.jsx(Re,{variant:"outline",className:"text-[10px] border-amber-500/40 text-amber-400",title:"Conta criada, cadastro na Stripe incompleto",children:"Connect pendente"}):e.jsxs("div",{className:"flex flex-col leading-tight",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Sem Connect"}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:d.pix_key?`PIX: ${d.pix_key}`:"sem PIX"})]})}),e.jsxs(a,{children:[d.commission_percent,"%"]}),e.jsx(a,{children:Ms(d.total_earned)}),e.jsx(a,{className:"text-muted-foreground",children:Ms(H(d.id))}),e.jsxs(a,{className:Ue("font-medium",xe(d.id)<0?"text-destructive":"text-primary"),children:[Ms(xe(d.id)),xe(d.id)<0&&e.jsx("span",{className:"block text-[10px] font-normal",children:"a compensar"})]}),e.jsx(a,{children:e.jsx(Re,{variant:d.is_active?"default":"secondary",className:"text-[10px]",children:d.is_active?"Ativo":"Inativo"})}),e.jsx(a,{children:e.jsxs("div",{className:"flex items-center gap-1",onClick:de=>de.stopPropagation(),children:[e.jsx(y,{variant:"ghost",size:"sm",onClick:()=>ue(d),className:"text-xs h-7",children:"Editar"}),e.jsx(y,{variant:"ghost",size:"sm",onClick:()=>ze(d),className:"text-xs h-7",children:d.is_active?"Desativar":"Ativar"}),e.jsx(y,{variant:"ghost",size:"sm",onClick:()=>xs(d.id),className:"text-destructive h-7",children:e.jsx(_s,{className:"w-3.5 h-3.5"})})]})})]},d.id)}),s.length===0&&e.jsx(b,{children:e.jsx(a,{colSpan:10,className:"text-center text-muted-foreground py-8",children:"Nenhum afiliado cadastrado"})})]})]}),$e.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"text-sm font-semibold",children:"Saques"}),e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Data"}),e.jsx(f,{children:"Afiliado"}),e.jsx(f,{children:"Valor"}),e.jsx(f,{children:"Forma"}),e.jsx(f,{children:"Status"})]})}),e.jsx(De,{children:$e.map(d=>{const le=s.find(de=>de.id===d.affiliate_id),S=le?me[le.user_id]:void 0;return e.jsxs(b,{children:[e.jsx(a,{className:"text-xs",children:new Date(d.created_at).toLocaleDateString("pt-BR")}),e.jsx(a,{className:"text-xs",children:(S==null?void 0:S.nickname)||(S==null?void 0:S.email)||(le==null?void 0:le.affiliate_code)||"—"}),e.jsx(a,{className:"text-xs font-medium",children:Ms(d.amount,d.currency)}),e.jsxs(a,{className:"text-xs text-muted-foreground",children:[d.method==="manual"?"Manual (PIX/TED)":"Stripe",d.note&&e.jsx("span",{className:"block text-[10px]",children:d.note})]}),e.jsxs(a,{children:[e.jsx(Re,{variant:"secondary",className:Ue("text-[10px]",d.status==="paid"&&"bg-emerald-500/15 text-emerald-400",d.status==="processing"&&"bg-blue-500/15 text-blue-400",d.status==="failed"&&"bg-destructive/15 text-destructive"),children:d.status==="paid"?"Pago":d.status==="processing"?"Processando":"Falhou"}),d.status==="failed"&&d.error&&e.jsx("span",{className:"block text-[10px] text-destructive mt-0.5",children:d.error})]})]},d.id)})})]})]}),e.jsx(ds,{open:!!J,onOpenChange:d=>{d||W(null)},children:e.jsxs(cs,{className:"sm:max-w-sm",children:[e.jsx(ms,{children:e.jsxs(us,{children:["Editar afiliado",J&&e.jsxs("span",{className:"block text-xs font-normal text-muted-foreground mt-1",children:[(hs=me[J.user_id])!=null&&hs.nickname?`${(As=me[J.user_id])==null?void 0:As.nickname} · `:"",((Gs=me[J.user_id])==null?void 0:Gs.email)||J.affiliate_code]})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Cupom de desconto"}),e.jsx(je,{value:N.coupon,onChange:d=>ce(le=>({...le,coupon:d.target.value.toUpperCase()})),placeholder:"GALDINO10"}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:"Precisa existir como código promocional na Stripe. Deixe vazio para desvincular. Comissões já lançadas não são afetadas."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Comissão (%)"}),e.jsx(je,{type:"number",min:"1",max:"50",value:N.percent,onChange:d=>ce(le=>({...le,percent:d.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Trava extra de saque (dias)"}),e.jsx(je,{type:"number",min:"0",max:"365",value:N.holdDays,onChange:d=>ce(le=>({...le,holdDays:d.target.value}))}),e.jsxs("p",{className:"text-[11px] text-muted-foreground leading-snug",children:["Deixe ",e.jsx("strong",{children:"0"}
706)," (padrão). Cada comissão já libera sozinha 30 dias após a assinatura do cliente. Use aqui um valor maior só para segurar um afiliado específico por suspeita de fraude — conta a partir do cadastro dele."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Chave PIX"}),e.jsx(je,{value:N.pix,onChange:d=>ce(le=>({...le,pix:d.target.value})),placeholder:"CPF, e-mail ou chave aleatória"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"WhatsApp"}),e.jsx(je,{value:N.whatsapp,onChange:d=>ce(le=>({...le,whatsapp:d.target.value})),placeholder:"+55 11 99999-9999"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Telefone"}),e.jsx(je,{value:N.phone,onChange:d=>ce(le=>({...le,phone:d.target.value})),placeholder:"(11) 99999-9999"})]})]}),e.jsx(Bs,{children:e.jsxs(y,{onClick:Pe,disabled:D,className:"gap-1.5",children:[D?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(Ea,{className:"w-4 h-4"}),"Salvar"]})})]})}),e.jsx(ds,{open:l,onOpenChange:h,children:e.jsxs(cs,{className:"sm:max-w-sm",children:[e.jsx(ms,{children:e.jsx(us,{children:"Cadastrar Afiliado"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Selecionar usuário *"}),e.jsxs(io,{open:$,onOpenChange:V,children:[e.jsx(oo,{asChild:!0,children:e.jsxs(y,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[v?((Hs=x.find(d=>d.id===v))==null?void 0:Hs.email)||"Usuário selecionado":A?"Carregando...":"Buscar usuário...",e.jsx(Mo,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(lo,{className:"w-full p-0",align:"start",children:e.jsxs(Zi,{children:[e.jsx(eo,{placeholder:"Buscar por e-mail..."}),e.jsxs(so,{children:[e.jsx(ao,{children:"Nenhum usuário encontrado"}),e.jsx(ro,{className:"max-h-60 overflow-y-auto",children:x.map(d=>e.jsxs(to,{value:d.email,onSelect:()=>{R(d.id),V(!1)},children:[e.jsx(Ea,{className:Ue("mr-2 h-4 w-4",v===d.id?"opacity-100":"opacity-0")}),d.email]},d.id))})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Comissão (%)"}),e.jsx(je,{type:"number",value:Z,onChange:d=>p(d.target.value),min:"1",max:"50"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Cupom de desconto"}),e.jsx(je,{value:q,onChange:d=>E(d.target.value.toUpperCase()),placeholder:"GALDINO10"}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:"Precisa existir como código promocional na Stripe. Quem assinar usando este cupom gera comissão para este afiliado, mesmo sem passar pelo link dele."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Chave PIX"}),e.jsx(je,{value:z,onChange:d=>Q(d.target.value),placeholder:"CPF, e-mail ou chave aleatória"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"WhatsApp"}),e.jsx(je,{value:ae,onChange:d=>Y(d.target.value),placeholder:"+55 11 99999-9999"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Telefone"}),e.jsx(je,{value:B,onChange:d=>G(d.target.value),placeholder:"(11) 99999-9999"})]})]}),e.jsx(Bs,{children:e.jsxs(y,{onClick:ps,disabled:P,className:"gap-1.5",children:[P?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(jr,{className:"w-4 h-4"}),"Cadastrar"]})})]})}),e.jsx(ds,{open:re,onOpenChange:ke,children:e.jsxs(cs,{className:"sm:max-w-lg",children:[e.jsx(ms,{children:e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"w-5 h-5 text-primary"}),"Comissões — ",is?((Ls=me[is.user_id])==null?void 0:Ls.nickname)||((L=me[is.user_id])==null?void 0:L.email)||is.affiliate_code:""]})}),is&&e.jsxs("div",{className:"rounded-lg border border-border/40 bg-card/50 p-3 space-y-2",children:[Xe(is)?e.jsxs("p",{className:"text-[11px] text-muted-foreground leading-snug",children:[e.jsx("strong",{className:"text-emerald-400",children:"Recebe pela Stripe."})," O próprio afiliado saca no painel dele quando o saldo disponível passa de R$ 100 / US$ 20. Você não precisa fazer nada."]}):e.jsxs("p",{className:"text-[11px] text-muted-foreground leading-snug",children:[e.jsx("strong",{className:"text-amber-400",children:"Ainda não recebe pela Stripe."})," Enquanto não concluir o cadastro no painel de afiliado, o saldo acumula mas ele não consegue sacar. Se você pagar por fora (PIX/TED), registre abaixo para baixar do saldo."]}),Object.entries(Ne(is.id)).filter(([,d])=>d>0).length===0?e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Nada dis
706ponível para pagar no momento."}):e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(Ne(is.id)).filter(([,d])=>d>0).map(([d,le])=>e.jsxs(y,{variant:"outline",size:"sm",className:"text-[11px] h-7 gap-1.5",disabled:Je===`${is.id}_${d}`,onClick:()=>Ie(is,d,le),children:[Je===`${is.id}_${d}`?e.jsx(he,{className:"w-3 h-3 animate-spin"}):e.jsx(nr,{className:"w-3 h-3"}),"Registrar ",Ms(le,d)," como pago por fora"]},d))})]}),ws.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Nenhuma comissão registrada"}):e.jsx("div",{className:"max-h-80 overflow-y-auto",children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Data"}),e.jsx(f,{children:"Comprador"}),e.jsx(f,{children:"Venda"}),e.jsx(f,{children:"Comissão"}),e.jsx(f,{children:"Status"})]})}),e.jsx(De,{children:ws.map(d=>{var le,S;return e.jsxs(b,{children:[e.jsx(a,{className:"text-xs",children:new Date(d.created_at).toLocaleDateString("pt-BR")}),e.jsx(a,{className:"text-xs",children:d.buyer_email||"—"}),e.jsx(a,{className:"text-xs",children:Ms(d.sale_amount,d.sale_currency)}),e.jsx(a,{className:"text-xs font-medium text-primary",children:Ms(d.commission_amount,d.sale_currency)}),e.jsxs(a,{children:[e.jsx(Re,{variant:"secondary",className:Ue("text-[10px]",d.commission_type==="clawback"?mt.clawback.className:(le=mt[d.status])==null?void 0:le.className),children:d.commission_type==="clawback"?"Estorno a compensar":((S=mt[d.status])==null?void 0:S.label)||d.status}),d.status==="pending"&&d.available_at&&e.jsxs("span",{className:"block text-[10px] text-muted-foreground mt-0.5",children:["libera ",new Date(d.available_at).toLocaleDateString("pt-BR")]})]})]},d.id)})})]})})]})})]})},gd=()=>{const[s,n]=r.useState([]),[c,u]=r.useState(!0),[m,_]=r.useState(null),k=async()=>{u(!0),n(await $i()),u(!1)};r.useEffect(()=>{k()},[]);const g=async(l,h)=>{if(m)return;let x;if(h==="rejected"){const v=window.prompt("Motivo da rejeição (opcional):","");if(v===null)return;x=v||void 0}_(l.id);const w=await zi(l,h,x);_(null),w?(n(v=>v.filter(R=>R.id!==l.id)),Ft({title:h==="approved"?"Flow aprovado":"Flow rejeitado"})):Ft({title:"Falha na ação",variant:"destructive"})};return c?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-primary"})}):s.length?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(l=>{const h=!!l.pending_submitted_at&&l.status==="approved",x=(h?l.pending_thumbnail_url:null)||l.thumbnail_url;return e.jsxs("div",{className:"rounded-2xl border border-border/40 bg-card/60 overflow-hidden flex flex-col",children:[e.jsxs("div",{className:"aspect-video bg-black/30 overflow-hidden relative",children:[x?e.jsx("img",{src:Za(x,600,75),alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground/30",children:e.jsx(jt,{className:"w-8 h-8"})}),e.jsxs("span",{className:"absolute top-2 left-2 inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-black/60 text-[10px] text-white",children:[e.jsx(Un,{className:"w-3 h-3"})," Flow"]}),h&&e.jsxs("span",{className:"absolute top-2 right-2 inline-flex items-center gap-1 px-1.5 py-0.5 rounded-md bg-amber-500/90 text-[10px] font-semibold text-white",children:[e.jsx(Qe,{className:"w-3 h-3"})," Atualização"]})]}),e.jsxs("div",{className:"p-3 flex flex-col gap-1.5 flex-1",children:[e.jsx("h3",{className:"text-sm font-semibold line-clamp-1",children:l.title}),e.jsx("p",{className:"text-[11px] text-muted-foreground line-clamp-3 flex-1",children:l.description}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsxs("button",{onClick:()=>g(l,"approved"),disabled:m===l.id,className:"flex-1 inline-flex items-center justify-center gap-1 h-8 rounded-lg bg-emerald-500/90 text-white text-xs font-semibold hover:bg-emerald-500 disabled:opacity-50",children:[m===l.id?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Ea,{className:"w-3.5 h-3.5"}),"Aprovar"]}),e.jsxs("button",{onClick:()=>g(l,"rejected"),disabled:m===l.id,className:"flex-1 inline-flex items-center justify-center gap-1 h-8 rounded-lg bg-secondary text-foreground text-xs font-semibold hover:bg-secondary/70 disabled:opacity-50",children:[e.jsx(Ga,{className:"w-3.5 h-3.5"}),"Rejeitar"]})]})]})]},l.id)})}):e.jsx("div",{className:"text-center py-16 text-sm text-muted-foreground",children:"Nenhum flow pen
706dente."})},ut=s=>s.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"").slice(0,40),jd=()=>{const[s,n]=r.useState([]),[c,u]=r.useState(!0),[m,_]=r.useState(null),[k,g]=r.useState(!1),l=r.useCallback(async()=>{u(!0);const{data:$,error:V}=await F.from("community_categories").select("*").order("sort_order",{ascending:!0});V&&o.error(V.message),n($||[]),u(!1)},[]);r.useEffect(()=>{l()},[l]);const h=()=>{var $;_({id:"",name:"",slug:"",description:"",icon:"Sparkles",sort_order:((($=s[s.length-1])==null?void 0:$.sort_order)??0)+10,is_active:!0}),g(!0)},x=async()=>{var Z;if(!m)return;const $=m.name.trim();if(!$){o.error("Nome é obrigatório");return}const V=((Z=m.slug)==null?void 0:Z.trim())||ut($),C={name:$,slug:V,description:m.description||"",icon:m.icon||"Sparkles",sort_order:m.sort_order??0,is_active:m.is_active},{error:ee}=m.id?await F.from("community_categories").update(C).eq("id",m.id):await F.from("community_categories").insert(C);if(ee){o.error(ee.message);return}o.success(m.id?"Categoria atualizada":"Categoria criada"),g(!1),_(null),l()},w=async $=>{const{error:V}=await F.from("community_categories").update({is_active:!$.is_active}).eq("id",$.id);if(V){o.error(V.message);return}l()},v=async $=>{if(!confirm(`Remover categoria "${$.name}"? Posts existentes ficarão sem categoria.`))return;const{error:V}=await F.from("community_categories").delete().eq("id",$.id);if(V){o.error(V.message);return}o.success("Removida"),l()},R=async($,V)=>{const C=s.findIndex(Z=>Z.id===$.id),ee=s[C+V];ee&&(await Promise.all([F.from("community_categories").update({sort_order:ee.sort_order}).eq("id",$.id),F.from("community_categories").update({sort_order:$.sort_order}).eq("id",ee.id)]),l())};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-semibold flex items-center gap-2",children:[e.jsx(bt,{className:"w-5 h-5 text-primary"}),"Categorias da Comunidade"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Crie, edite e organize as categorias usadas nos envios da galeria."})]}),e.jsxs(y,{onClick:h,className:"gap-2",children:[e.jsx(Us,{className:"w-4 h-4"}),"Nova categoria"]})]}),c?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-primary"})}):s.length===0?e.jsx("div",{className:"text-center py-16 text-sm text-muted-foreground",children:"Nenhuma categoria criada."}):e.jsx("div",{className:"rounded-xl border border-border/40 overflow-hidden",children:s.map(($,V)=>e.jsxs("div",{className:"flex items-center gap-3 p-3 border-b border-border/30 last:border-0 bg-card/30",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("button",{onClick:()=>R($,-1),disabled:V===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30",children:e.jsx(In,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>R($,1),disabled:V===s.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30",children:e.jsx(Jn,{className:"w-3.5 h-3.5"})})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium truncate",children:$.name}),e.jsxs(Re,{variant:"outline",className:"text-[10px]",children:["/",$.slug]}),!$.is_active&&e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:"Inativa"})]}),$.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:$.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vs,{checked:$.is_active,onCheckedChange:()=>w($)}),e.jsx(y,{size:"sm",variant:"ghost",onClick:()=>{_($),g(!0)},children:e.jsx($r,{className:"w-3.5 h-3.5"})}),e.jsx(y,{size:"sm",variant:"ghost",onClick:()=>v($),className:"text-red-400 hover:text-red-300",children:e.jsx(_s,{className:"w-3.5 h-3.5"})})]})]},$.id))}),e.jsx(ds,{open:k,onOpenChange:$=>{$||(g(!1),_(null))}
706,children:e.jsxs(cs,{children:[e.jsxs(ms,{children:[e.jsx(us,{children:m!=null&&m.id?"Editar categoria":"Nova categoria"}),e.jsx(ra,{children:"Categorias ajudam a organizar os envios da comunidade."})]}),m&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{className:"text-xs",children:"Nome"}),e.jsx(je,{value:m.name,onChange:$=>_({...m,name:$.target.value,slug:m.id?m.slug:ut($.target.value)}),placeholder:"Ex.: Cinematográfico"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{className:"text-xs",children:"Slug"}),e.jsx(je,{value:m.slug,onChange:$=>_({...m,slug:ut($.target.value)}),placeholder:"cinematografico"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{className:"text-xs",children:"Descrição (opcional)"}),e.jsx(je,{value:m.description||"",onChange:$=>_({...m,description:$.target.value})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(oe,{className:"text-xs",children:"Ativa"}),e.jsx(Vs,{checked:m.is_active,onCheckedChange:$=>_({...m,is_active:$})})]})]}),e.jsxs(Bs,{children:[e.jsx(y,{variant:"ghost",onClick:()=>{g(!1),_(null)},children:"Cancelar"}),e.jsx(y,{onClick:x,children:"Salvar"})]})]})})]})},cr="__none__",fd=s=>s.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"").slice(0,40),vd=()=>{const{user:s}=Va(),[n,c]=r.useState("pending"),[u,m]=r.useState([]),[_,k]=r.useState(!0),[g,l]=r.useState({pending:0,approved:0,rejected:0,featured:0,publicReq:0}),[h,x]=r.useState([]),[w,v]=r.useState({}),[R,$]=r.useState(null),[V,C]=r.useState(""),[ee,Z]=r.useState(!1),[p,z]=r.useState(!1),[Q,ae]=r.useState(null),Y=r.useCallback(async()=>{const{data:i}=await F.from("community_categories").select("id, name").eq("is_active",!0).order("sort_order",{ascending:!0}).order("name",{ascending:!0});x(i||[])},[]),B=r.useCallback(async()=>{const[i,A,O,te,T]=await Promise.all([F.from("community_posts").select("*",{count:"exact",head:!0}).eq("status","pending"),F.from("community_posts").select("*",{count:"exact",head:!0}).eq("status","approved"),F.from("community_posts").select("*",{count:"exact",head:!0}).eq("status","rejected"),F.from("community_posts").select("*",{count:"exact",head:!0}).eq("featured_in_landing",!0),F.from("community_posts").select("*",{count:"exact",head:!0}).eq("pending_public",!0)]);l({pending:i.count||0,approved:A.count||0,rejected:O.count||0,featured:te.count||0,publicReq:T.count||0})},[]),G=r.useCallback(async()=>{k(!0);try{let i=F.from("community_posts").select("id, user_id, generation_id, category_id, title, status, rejection_reason, created_at, approved_at, like_count, view_count, suggested_category, featured_in_landing, pending_public, visibility").order("created_at",{ascending:!1}).limit(80);i=n==="public-req"?i.eq("pending_public",!0):i.eq("status",n);const{data:A,error:O}=await i;if(O)throw O;if(!A||A.length===0){m([]);return}const te=A.map(we=>we.generation_id),T=[...new Set(A.map(we=>we.user_id))],re=[...new Set(A.map(we=>we.category_id).filter(Boolean))],[ke,fe,X]=await Promise.all([F.from("generations").select("id, media_url, thumbnail_url, prompt, media_type, reference_images").in("id",te),F.from("profiles").select("user_id, nickname").in("user_id",T),re.length?F.from("community_categories").select("id, name").in("id",re):Promise.resolve({data:[]})]),me=new Map((ke.data||[]).map(we=>[we.id,we])),_e=new Map((fe.data||[]).map(we=>[we.user_id,we])),$e=new Map((X.data||[]).map(we=>[we.id,we])),Ve=A.map(we=>({...we,generation:me.get(we.generation_id),profile:_e.get(we.user_id)||null,category:we.category_id?$e.get(we.category_id):null})).filter(we=>we.generation);m(Ve);const Je={};Ve.forEach(we=>{Je[we.id]=we.category_id||cr}),v(Je)}catch(i){o.error(i.message)}finally{k(!1)}},[n]);r.useEffect(()=>{Y()},[Y]),r.useEffect(()=>{B(),G()},[n,B,G]);const q=async i=>{const A=w[i],O=A&&A!==cr?A:null,{error:te}=await F.from("community_posts").update({status:"approved",approved_at:new Date().toISOString(),approved_by:s==null?void 0:s.id,category_id:O}).eq("id",i);if(te){o.error(te.message);return}F.functions.invoke("community-publish-assets",{body:{post_id:i}}).then(({error:T})=>{T&&console.warn("[approve] copy assets failed:",T)}),o.success("Aprovado!"),G(),B()},E=async(i,A)=>{var ke;v(fe=>({...fe,[i]:A}));const O=u.find(fe=>fe.id===i);if(!O||O.status==="pending")return;const te=A===cr?null:A,{error:T}=await F.from("community_posts").update({category_id:te}).eq("id",i);if(T){o.error(T.message);return}const re=((ke=h.find(fe=>fe.id===te))==null?void 0:ke.name)||"Sem categoria";o.success(`Categoria alterada: ${re}`),m(fe=>fe.map(X=>X.id===i?{...X,category_id:te,category:te?{name:re}:null}:X))},P=i=>{$(i),C("")},K=async()=>
706{if(!R)return;Z(!0);const{error:i}=await F.from("community_posts").update({status:"rejected",rejection_reason:V.trim()||null}).eq("id",R);if(Z(!1),i){o.error(i.message);return}o.info("Rejeitado"),$(null),C(""),G(),B()},J=async i=>{if(!confirm("Remover este post permanentemente?"))return;const{error:A}=await F.from("community_posts").delete().eq("id",i);if(A){o.error(A.message);return}o.success("Removido"),G(),B()},W=async(i,A)=>{const{error:O}=await F.rpc("decide_public_request",{p_id:i,p_approve:A});if(O){o.error(O.message);return}o.success(A?"Aprovado — agora é público!":"Pedido recusado (segue privado)"),G(),B()},N=async(i,A)=>{const{error:O}=await F.functions.invoke("admin-toggle-landing-feature",{body:{postId:i,featured:!A}});if(O){o.error(O.message||"Falha ao atualizar destaque");return}m(te=>te.map(T=>T.id===i?{...T,featured_in_landing:!A}:T)),l(te=>({...te,featured:Math.max(0,te.featured+(A?-1:1))})),o.success(A?"Removido da landing":"Adicionado à landing")},ce=async i=>{const A=(i.suggested_category||"").trim();if(!A)return;const O=A.slice(0,60),te=fd(O);let T=null;const{data:re,error:ke}=await F.from("community_categories").insert({name:O,slug:te,icon:"Sparkles",is_active:!0,sort_order:999}).select("id").single();if(ke){const{data:X}=await F.from("community_categories").select("id").eq("slug",te).maybeSingle();if(T=(X==null?void 0:X.id)||null,!T){o.error(ke.message);return}}else T=re.id;const{error:fe}=await F.from("community_posts").update({status:"approved",approved_at:new Date().toISOString(),approved_by:s==null?void 0:s.id,category_id:T}).eq("id",i.id);if(fe){o.error(fe.message);return}F.functions.invoke("community-publish-assets",{body:{post_id:i.id}}).then(({error:X})=>{X&&console.warn("[approve+cat] copy assets failed:",X)}),o.success(`Categoria "${O}" criada e post aprovado!`),Y(),G(),B()},D=i=>{var A;return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-card/40 overflow-hidden relative",children:[i.status==="approved"&&e.jsx("button",{type:"button",onClick:()=>N(i.id,i.featured_in_landing),title:i.featured_in_landing?"Remover da landing":"Destacar na landing",className:"absolute top-2 right-2 z-10 w-9 h-9 rounded-full backdrop-blur-md border flex items-center justify-center transition-all "+(i.featured_in_landing?"bg-primary/20 border-primary/60 text-primary hover:bg-primary/30 shadow-[0_0_20px_-4px_hsl(var(--primary)/0.6)]":"bg-background/70 border-border/40 text-muted-foreground hover:text-foreground hover:border-primary/40"),children:e.jsx(ar,{className:"w-4 h-4 "+(i.featured_in_landing?"fill-primary":"")})}),e.jsx("div",{className:"aspect-square bg-black",children:i.generation.media_type==="video"?e.jsx("video",{src:`${i.generation.media_url}#t=0.1`,poster:i.generation.thumbnail_url&&Za(i.generation.thumbnail_url,400)||void 0,className:"w-full h-full object-cover",controls:!0,playsInline:!0,preload:"metadata"}):e.jsx("img",{src:Za(i.generation.thumbnail_url||i.generation.media_url,400),alt:"",className:"w-full h-full object-cover",loading:"lazy",decoding:"async"})}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("p",{className:"text-sm font-medium line-clamp-1",children:i.title||"Sem título"}),i.category&&e.jsx(Re,{variant:"outline",className:"text-[9px] shrink-0",children:i.category.name})]}),e.jsx("div",{className:"text-[11px] text-muted-foreground max-h-28 overflow-y-auto whitespace-pre-wrap break-words rounded-md bg-muted/30 p-2 leading-snug select-text",children:i.generation.prompt||"Sem prompt"}),Array.isArray(i.generation.reference_images)&&i.generation.reference_images.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[e.jsx(Ma,{className:"w-3 h-3"}),"Referências (",i.generation.reference_images.length,")"]}),e.jsx("div",{className:"grid grid-cols-4 gap-1",children:i.generation.reference_images.map((O,te)=>e.jsx("button",{type:"button",onClick:()=>ae(O),className:"aspect-square rounded-md overflow-hidden border border-border/40 bg-black hover:border-primary/50 transition-colors",title:"Ver referência em tamanho grande",children:e.jsx("img",{src:Za(O,120),alt:`Referência ${te+1}`,className:"w-full h-full object-cover",loading:"lazy",decoding:"async",onError:gt})},te))})]}),e.jsxs("div",{className:"flex items-center justify-between text-[10px] text-muted-foreground",children:[e.jsxs("span",{children:["@",((A=i.profile)==null?void 0:A.nickname)||"user"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(xi,{className:"w-2.5 h-2.5"}),i.like_count]}),e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(ia,{className:"w-2.5 h-2.5"}),i.view_count]})]})]}),i.suggested_category&&e.jsxs("div",{className:"flex items-start gap-1.5 p-2 rounded-md bg-amber-500/10 border border-amber-500/30",children:[e.jsx(mo,{className:"w-3 h-3 text-amber-400 shrink-0 mt-0.5"}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("p",{className:"text-[10px] text-amber-300/90 leading-tight",children:["Sugestão de categoria: ",e.jsx("span",{className:"font-semibold",children:i.suggested_category})]})})]}),i.rejection_reason&&e.jsxs("p",{className:"text-[10px] text-red-400 italic",children:["Motivo: ",i.rejection_reason]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(bt,{className:"w-3 h-3 text-muted-foreground shrink-0"}),e.jsxs(as,{value:w[i.id]||cr,onValueChange:O=>E(i.id,O),children:[e.jsx(rs,{className:"h-7 text-[11px]",children:e.jsx(ts,{placeholder:"Sem categoria"})}),e.jsxs(ns,{children:[e.jsx(pe,{value:cr,className:"text-[11px]",children:"Sem categoria"}),h.map(O=>e.jsx(pe,{value:O.id,className:"text-[11px]",children:O.name},O.id))]})]})]}),e.jsxs("div",{className:"flex gap-1.5 pt-1 flex-wrap",children:[n==="public-req"&&e.jsxs(e.Fragment,{children:[e.jsxs(y,{size:"sm",onClick:()=>W(i.id,!0),className:"flex-1 h-8 gap-1 text-[11px]",children:[e.jsx(Dr,{className:"w-3 h-3"}),"Aprovar público"]}),e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>W(i.id,!1),className:"flex-1 h-8 gap-1 text-[11px]",children:[e.jsx(Da,{className:"w-3 h-3"}),"Recusar"]})]}),n!=="public-req"&&n!=="approved"&&e.jsxs(y,{size:"sm",onClick:()=>q(i.id),className:"flex-1 h-8 gap-1 text-[11px]",children:[e.jsx(nr,{className:"w-3 h-3"}),"Aprovar"]}),n!=="public-req"&&n!=="rejected"&&e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>P(i.id),className:"flex-1 h-8 gap-1 text-[11px]",children:[e.jsx(Da,{className:"w-3 h-3"}),"Rejeitar"]}),n==="approved"&&e.jsx(y,{size:"sm",variant:"outline",onClick:()=>J(i.id),className:"h-8 w-8 p-0 text-red-400 border-red-400/40 hover:bg-red-500/10",title:"Remover da comunidade",children:e.jsx(_s,{className:"w-3 h-3"})}),i.suggested_category&&n==="pending"&&e.jsxs(y,{size:"sm",onClick:()=>ce(i),className:"w-full h-8 gap-1 text-[11px] bg-amber-500/20 hover:bg-amber-500/30 text-amber-200 border border-amber-500/40",variant:"outline",children:[e.jsx(Et,{className:"w-3 h-3"}),"Criar categoria sugerida + aprovar"]})]})]})]},i.id)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-semibold flex items-center gap-2",children:[e.jsx(Xs,{className:"w-5 h-5 text-primary"}),"Comunidade"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Gerencie envios pendentes e categorias da galeria pública."})]}),e.jsxs(za,{defaultValue:"moderation",className:"w-full",children:[e.jsxs(Ba,{children:[e.jsxs(Fs,{value:"moderation",className:"gap-1.5",children:[e.jsx(_n,{className:"w-3.5 h-3.5"}),"Moderação"]}),e.jsxs(Fs,{value:"categories",className:"gap-1.5",children:[e.jsx(bt,{className:"w-3.5 h-3.5"}),"Categorias"]}),e.jsxs(Fs,{value:"flows",className:"gap-1.5",children:[e.jsx(Un,{className:"w-3.5 h-3.5"}),"Flows"]})]}),e.jsxs(Qs,{value:"moderation",className:"space-y-6 mt-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx(za,{value:n,onValueChange:i=>c(i),children:e.jsxs(Ba,{children:[e.jsxs(Fs,{value:"pending",className:"gap-1.5",children:[e.jsx(co,{className:"w-3.5 h-3.5"}),"Pendentes ",e.jsx(Re,{variant:"secondary",className:"ml-1",children:g.pending})]}),e.jsxs(Fs,{value:"approved",className:"gap-1.5",children:[e.jsx(nr,{className:"w-3.5 h-3.5"}),"Aprovados ",e.jsx(Re,{variant:"secondary",className:"ml-1",children:g.a
706pproved})]}),e.jsxs(Fs,{value:"rejected",className:"gap-1.5",children:[e.jsx(Da,{className:"w-3.5 h-3.5"}),"Rejeitados ",e.jsx(Re,{variant:"secondary",className:"ml-1",children:g.rejected})]}),e.jsxs(Fs,{value:"public-req",className:"gap-1.5",children:[e.jsx(Dr,{className:"w-3.5 h-3.5"}),"Pedidos públicos ",e.jsx(Re,{variant:"secondary",className:"ml-1",children:g.publicReq})]})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Re,{variant:"outline",className:"gap-1.5 h-7 px-2.5 border-primary/40 bg-primary/10 text-primary text-[11px]",title:"Posts marcados aparecem no carrossel da landing page",children:[e.jsx(ar,{className:"w-3 h-3 fill-primary"}),g.featured," ",g.featured===1?"destaque":"destaques"," na landing"]}),e.jsxs(y,{size:"sm",onClick:()=>z(!0),className:"gap-2",children:[e.jsx(or,{className:"w-3.5 h-3.5"}),"Criar post manual"]})]})]}),n==="approved"&&e.jsxs("p",{className:"text-xs text-muted-foreground -mt-2",children:[e.jsx(ar,{className:"w-3 h-3 inline-block mr-1 text-primary fill-primary"}),"Clique na estrela de um post aprovado pra destacá-lo no carrossel da landing. Se houver menos de 6 destaques, o carrossel mostra todos os aprovados."]}),_?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-primary"})}):u.length===0?e.jsx("div",{className:"text-center py-16 text-sm text-muted-foreground",children:"Nenhum post nesta fila."}):e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-4",children:u.map(D)})]}),e.jsx(Qs,{value:"categories",className:"mt-6",children:e.jsx(jd,{})}),e.jsx(Qs,{value:"flows",className:"mt-6",children:e.jsx(gd,{})})]}),e.jsx(ds,{open:!!R,onOpenChange:i=>{i||($(null),C(""))},children:e.jsxs(cs,{className:"sm:max-w-md",children:[e.jsxs(ms,{children:[e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(Da,{className:"w-4 h-4 text-red-400"}),"Rejeitar publicação"]}),e.jsx(ra,{className:"text-xs",children:"Informe o motivo (opcional). O autor poderá ver esta mensagem."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5",children:["Conteúdo de baixa qualidade","Prompt incompleto","Conteúdo inadequado","Fora do tema","Duplicado"].map(i=>e.jsx(y,{type:"button",size:"sm",variant:"outline",onClick:()=>C(i),className:"h-7 text-[11px] rounded-full",children:i},i))}),e.jsx(Ss,{autoFocus:!0,value:V,onChange:i=>C(i.target.value),placeholder:"Descreva o motivo da rejeição…",rows:4,maxLength:300,className:"resize-none text-sm"}),e.jsxs("p",{className:"text-[10px] text-muted-foreground text-right",children:[V.length,"/300"]})]}),e.jsxs(Bs,{className:"gap-2 sm:gap-2",children:[e.jsx(y,{variant:"outline",onClick:()=>{$(null),C("")},disabled:ee,children:"Cancelar"}),e.jsxs(y,{variant:"destructive",onClick:K,disabled:ee,className:"gap-1.5",children:[ee?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Da,{className:"w-3.5 h-3.5"}),"Rejeitar"]})]})]})}),e.jsx(no,{open:p,onOpenChange:z,categories:h,onCreated:()=>{G(),B(),c("approved")}}),e.jsx(ds,{open:!!Q,onOpenChange:i=>{i||ae(null)},children:e.jsxs(cs,{className:"max-w-3xl p-2 bg-black/95 border-border/40",children:[e.jsx(ms,{className:"sr-only",children:e.jsx(us,{children:"Imagem de referência"})}),Q&&e.jsx("img",{src:Za(Q,1280),alt:"Referência",className:"w-full max-h-[80vh] object-contain rounded-md",onError:gt})]})})]})},bd={chargeback:"Chargeback",manual:"Manual",fraud_pattern:"Padrão de fraude"},Nd={chargeback:"bg-red-500/15 text-red-400 border-red-400/30",manual:"bg-amber-500/15 text-amber-400 border-amber-400/30",fraud_pattern:"bg-purple-500/15 text-purple-400 border-purple-400/30"},yd=()=>{const{user:s}=Va(),[n,c]=r.useState([]),[u,m]=r.useState(!0),[_,k]=r.useState(""),[g,l]=r.useState(!1),[h,x]=r.useState(!1),[w,v]=r.useState(!1),[R,$]=r.useState(""),[V,C]=r.useState(""),[ee,Z]=r.useState(""),[p,z]=r.useState(""),[Q,ae]=r.useState(""),[Y,B]=r.useState("manual"),[G,q]=r.useState(""),E=async()=>{m(!0);let N=F.from("banned_users").select("*").order("banned_at",{ascending:!1}).limit(500);g||(N=N.is("unbanned_at",null));const{data:ce,error:D}=await N;if(m(!1),D){o.error(`Erro ao carregar bans: ${D.message}`);return}c(ce||[])};r.useEffect(()=>{E()},[g]);const P=r.useMemo(()=>{const N=_.trim().toLowerCase();return N?n.filter(ce=>(ce.email||"").toLowerCase().includes(N)||(ce.stripe_customer_id||"").toLowerCase().includes(N)||(ce.card_fingerprint||"").toLowerCase().includes(N)||(ce.ip_address||"").toLowerCase().includes(N)||(ce.dispute_id||"").toLowerCase().includes(N)||(ce.reason||"").toLowerCase().includes(N)):n},[n,_]),K=()=>{$(""),C(""),Z(""),z(""),ae(""),B("manual"),q("")},J=async()=>{const N=R.trim().toLowerCase()||null,ce=V.trim()||null,D=ee.trim()||null,i=p.trim()||null;if(!N&&!ce&&!D&&!i){o.error("Informe ao menos um identificador (email, customer_id, card fingerprint ou IP).");return}if(!Q.trim()){o.error("Motivo é obrigatório.");return}v(!0);const{error:A}=await F.from("banned_users").insert({email:N,stripe_customer_id:ce,card_fingerprint:D,ip_address:i,reason:Q.trim(),source:Y,notes:G.trim()||null,banned_by:(s==null?void 0:s.id)||null});if(v(!1),A){o.error(`Erro: ${A.message}`);return}o.success("Ban registrado."),x(!1),K(),E()},W=async N=>{if(!confirm("Revogar este ban? O usuário voltará a poder fazer signup/checkout."))return;const{error:ce}=await F.from("banned_users").update({unbanned_at:new Date().toISOString(),unbanned_by:(s==null?void 0:s.id)||null}).eq("id",N);if(ce){o.error(`Erro: ${ce.message}`);return}o.success("Ban revogado."),E()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-display font-semibold flex items-center gap-2",children:[e.jsx(tr,{className:"w-5 h-5 text-red-400"})," Banimentos"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Lista de chargebacks automáticos e bans manuais. Bloqueia signup, checkout e compra de créditos."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(y,{variant:"outline",size:"sm",onClick:()=>l(!g),children:g?"Ocultar revogados":"Mostrar revogados"}),e.jsxs(y,{size:"sm",onClick:()=>x(!0),className:"gap-1.5",children:[e.jsx(Us,{className:"w-4 h-4"})," Banir manual"]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(aa,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}
706),e.jsx(je,{value:_,onChange:N=>k(N.target.value),placeholder:"Buscar por email, customer_id, IP, fingerprint, dispute, motivo...",className:"pl-9"})]}),u?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(he,{className:"w-5 h-5 animate-spin text-primary"})}):P.length===0?e.jsx("div",{className:"rounded-xl border border-border/40 bg-card/50 p-10 text-center text-sm text-muted-foreground",children:_?"Nenhum ban corresponde à busca.":"Nenhum banimento ativo."}):e.jsx("div",{className:"rounded-xl border border-border/40 overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-secondary/40 text-xs uppercase tracking-wider text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2 px-3",children:"Identificadores"}),e.jsx("th",{className:"text-left py-2 px-3",children:"Motivo"}),e.jsx("th",{className:"text-left py-2 px-3",children:"Origem"}),e.jsx("th",{className:"text-left py-2 px-3",children:"Data"}),e.jsx("th",{className:"text-left py-2 px-3",children:"Status"}),e.jsx("th",{className:"text-right py-2 px-3",children:"Ações"})]})}),e.jsx("tbody",{children:P.map(N=>{const ce=!N.unbanned_at;return e.jsxs("tr",{className:"border-t border-border/30 hover:bg-secondary/20",children:[e.jsxs("td",{className:"py-2 px-3 align-top space-y-0.5",children:[N.email&&e.jsxs("div",{className:"font-mono text-xs",children:[e.jsx("span",{className:"text-muted-foreground/70",children:"email:"})," ",N.email]}),N.stripe_customer_id&&e.jsxs("div",{className:"font-mono text-[10px] text-muted-foreground",children:[e.jsx("span",{className:"text-muted-foreground/70",children:"cust:"})," ",N.stripe_customer_id]}),N.card_fingerprint&&e.jsxs("div",{className:"font-mono text-[10px] text-muted-foreground",children:[e.jsx("span",{className:"text-muted-foreground/70",children:"card:"})," ",N.card_fingerprint.slice(0,16),"…"]}),N.ip_address&&e.jsxs("div",{className:"font-mono text-[10px] text-muted-foreground",children:[e.jsx("span",{className:"text-muted-foreground/70",children:"ip:"})," ",N.ip_address]})]}),e.jsxs("td",{className:"py-2 px-3 align-top",children:[e.jsx("p",{className:"text-xs",children:N.reason}),N.dispute_id&&e.jsxs("p",{className:"text-[10px] text-muted-foreground/70 font-mono mt-0.5",children:["dispute: ",N.dispute_id]}),N.notes&&e.jsx("p",{className:"text-[10px] text-muted-foreground/70 mt-0.5",children:N.notes})]}),e.jsx("td",{className:"py-2 px-3 align-top",children:e.jsx(Re,{variant:"outline",className:`text-[10px] ${Nd[N.source]}`,children:bd[N.source]})}),e.jsxs("td",{className:"py-2 px-3 align-top text-[11px] text-muted-foreground whitespace-nowrap",children:[new Date(N.banned_at).toLocaleDateString("pt-BR")," ",new Date(N.banned_at).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})]}),e.jsx("td",{className:"py-2 px-3 align-top",children:ce?e.jsx(Re,{className:"bg-red-500/20 text-red-400 border-red-400/40 text-[10px]",children:"Ativo"}):e.jsxs(Re,{variant:"outline",className:"text-[10px] border-muted-foreground/40 text-muted-foreground",children:["Revogado ",new Date(N.unbanned_at).toLocaleDateString("pt-BR")]})}),e.jsx("td",{className:"py-2 px-3 align-top text-right",children:ce&&e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>W(N.id),className:"gap-1 text-[11px]",children:[e.jsx(ir,{className:"w-3 h-3"})," Revogar"]})})]},N.id)})})]})}),e.jsx(ds,{open:h,onOpenChange:N=>{N||(x(!1),K())},children:e.jsxs(cs,{className:"max-w-md",children:[e.jsxs(ms,{children:[e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(tr,{className:"w-4 h-4 text-red-400"})," Banir manualmente"]}),e.jsx(ra,{className:"text-xs",children:"Informe ao menos um identificador. Bloqueia signup (por email), checkout/buy-credits (por email, customer ou IP)."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Email"}),e.jsx(je,{value:R,onChange:N=>$(N.target.value),placeholder:"[email protected]",type:"email"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Stripe Customer ID"}),e.jsx(je,{value:V,onChange:N=>C(N.target.value),placeholder:"cus_...",className:"font-mono text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Card fingerprint"}),e.jsx(je,{value:ee,onChange:N=>Z(N.target.value),placeholder:"hash do cartão (Stripe payment_method_details.card.fingerprint)",className:"font-mono text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"IP address"}),e.jsx(je,{value:p,onChange:N=>z(N.target.value),placeholder:"123.45.67.89",className:"font-mono text-xs"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Motivo *"}),e.jsx(je,{value:Q,onChange:N=>ae(N.target.value),placeholder:"Cliente abusivo / fraude detectada / etc"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Origem"}),e.jsxs(as,{value:Y,onValueChange:N=>B(N),children:[e.jsx(rs,{children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"manual",children:"Manual (decisão do admin)"}),e.jsx(pe,{value:"fraud_pattern",children:"Padrão de fraude detectado"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(oe,{className:"text-xs",children:"Notas (opcional)"}),e.jsx(Ss,{value:G,onChange:N=>q(N.target.value),rows:2,placeholder:"Contexto adicional..."})]}
706),(R||V||ee||p)&&Q.trim()===""&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg bg-amber-500/10 border border-amber-400/30 p-2 text-xs text-amber-300",children:[e.jsx(qs,{className:"w-3.5 h-3.5 mt-0.5 shrink-0"})," Informe um motivo antes de banir."]})]}),e.jsxs(Bs,{children:[e.jsx(y,{variant:"outline",onClick:()=>{x(!1),K()},children:"Cancelar"}),e.jsxs(y,{onClick:J,disabled:w,className:"gap-1.5",children:[w?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(tr,{className:"w-4 h-4"}),"Banir"]})]})]})})]})},_d={profile:"Perfil",post:"Publicação",flow:"Workflow"},wd=()=>{const{user:s}=Va(),n=fr(),[c,u]=r.useState([]),[m,_]=r.useState({}),[k,g]=r.useState(!0),[l,h]=r.useState(null),x=r.useCallback(async()=>{g(!0);const{data:V,error:C}=await F.from("reports").select("*").eq("status","open").order("created_at",{ascending:!1}).limit(300);if(C){o.error(`Erro: ${C.message}`),g(!1);return}const ee=V||[];u(ee);const Z=Array.from(new Set(ee.filter(p=>p.target_type==="profile").map(p=>p.target_id)));if(Z.length){const{data:p}=await F.from("profiles").select("user_id, username, nickname").in("user_id",Z),z={};for(const Q of p||[])z[Q.user_id]=Q.username||Q.nickname||Q.user_id;_(z)}g(!1)},[]);r.useEffect(()=>{x()},[x]);const w=async(V,C)=>{h(V.id);const{error:ee}=await F.from("reports").update({status:C,reviewed_at:new Date().toISOString(),reviewed_by:(s==null?void 0:s.id)||null}).eq("id",V.id);if(h(null),ee){o.error(`Erro: ${ee.message}`);return}u(Z=>Z.filter(p=>p.id!==V.id)),o.success(C==="actioned"?"Marcada como resolvida.":"Denúncia dispensada.")},v=async V=>{if(!confirm("Banir o autor deste conteúdo? Bloqueia signup/checkout (por e-mail) e marca a denúncia como resolvida."))return;h(V.id);const{data:C,error:ee}=await F.functions.invoke("admin-ban-from-report",{body:{report_id:V.id}});if(h(null),ee||C!=null&&C.error){o.error((C==null?void 0:C.error)||"Falha ao banir o autor.");return}u(Z=>Z.filter(p=>p.id!==V.id)),o.success(C!=null&&C.already_banned?"Autor já estava banido — denúncia resolvida.":"Autor banido e denúncia resolvida.")},R=async V=>{if(V.target_type==="profile"||!confirm("Remover este conteúdo da plataforma? A publicação some dos perfis e feeds."))return;h(V.id);const C=V.target_type==="post"?"community_posts":"community_flows",{error:ee}=await F.from(C).delete().eq("id",V.target_id);if(ee){h(null),o.error(`Erro ao remover: ${ee.message}`);return}await w(V,"actioned")},$=V=>
706{if(V.target_type==="profile"){const C=m[V.target_id];C?n(`/social/@${C}`):o.error("Perfil sem username")}else V.target_type==="flow"?n(`/playground/community/flow/${V.target_id}`):n(`/playground/community/${V.target_id}`)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-display font-semibold flex items-center gap-2",children:[e.jsx(Mn,{className:"w-5 h-5 text-destructive"})," Denúncias"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Conteúdos e perfis denunciados por usuários. Revise, remova o conteúdo ou bane o autor (aba Banimentos)."})]}),k?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(he,{className:"w-5 h-5 animate-spin text-primary"})}):c.length===0?e.jsx("div",{className:"rounded-xl border border-border/40 bg-card/50 p-10 text-center text-sm text-muted-foreground",children:"Nenhuma denúncia pendente. 🎉"}):e.jsx("div",{className:"space-y-2",children:c.map(V=>e.jsxs("div",{className:"rounded-xl border border-border/40 bg-card/40 p-3 flex items-start gap-3 flex-wrap",children:[e.jsx(Re,{variant:"outline",className:"text-[10px] shrink-0",children:_d[V.target_type]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm text-foreground",children:V.target_type==="profile"&&m[V.target_id]?`@${m[V.target_id]}`:V.target_id}),V.reason&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:V.reason}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-0.5",children:new Date(V.created_at).toLocaleString("pt-BR")})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>$(V),className:"gap-1 text-[11px]",children:[e.jsx(oa,{className:"w-3 h-3"})," Ver"]}),V.target_type!=="profile"&&e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>R(V),disabled:l===V.id,className:"gap-1 text-[11px] text-destructive hover:text-destructive",children:[e.jsx(_s,{className:"w-3 h-3"})," Remover"]}),e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>v(V),disabled:l===V.id,className:"gap-1 text-[11px] text-destructive hover:text-destructive",children:[e.jsx(tr,{className:"w-3 h-3"})," Banir"]}),e.jsxs(y,{size:"sm",variant:"outline",onClick:()=>w(V,"actioned"),disabled:l===V.id,className:"gap-1 text-[11px]",children:[e.jsx(Ea,{className:"w-3 h-3"})," Resolver"]}),e.jsxs(y,{size:"sm",variant:"ghost",onClick:()=>w(V,"dismissed"),disabled:l===V.id,className:"gap-1 text-[11px]",children:[e.jsx(Ga,{className:"w-3 h-3"})," Dispensar"]})]})]},V.id))})]})},tn={...Object.fromEntries(uo.map(s=>{var n;return[s,{provider:"Provedor A",model:`GPT Image 2.5 ${s.includes("flare")?"Flare":"Sunburst"} (${(n=s.split("_").pop())==null?void 0:n.toUpperCase()})`,category:s.includes("_edit_")?"Edição":"Geração"}]})),flux_klein_t2i:{provider:"Provedor B",model:"Flux 2 Klein",category:"Geração"},flux_klein_edit:{provider:"Provedor B",model:"Flux 2 Klein (Edit)",category:"Geração"},flux_klein_lora:{provider:"Provedor B",model:"Flux 2 Klein (LoRA)",category:"Geração"},flux_klein_t2i_lora:{provider:"Provedor B",model:"Flux 2 Klein (T2I+LoRA)",category:"Geração"},z_image_turbo_t2i:{provider:"Provedor B",model:"Z-Image Turbo",category:"Geração"},z_image_turbo_i2i:{provider:"Provedor B",model:"Z-Image Turbo (I2I)",category:"Geração"},z_image_turbo_lora:{provider:"Provedor B",model:"Z-Image Turbo (LoRA)",category:"Geração"},z_image_turbo_i2i_lora:{provider:"Provedor B",model:"Z-Image Turbo (I2I+LoRA)",category:"Geração"},z_image_turbo_inpaint:{provider:"Provedor B",model:"Z-Image Turbo (Inpaint)",category:"Edição"},seedream_5_0_pro_1k:{provider:"Provedor A",model:"Seedream 5.0 Pro (1K)",category:"Geração"},seedream_5_0_pro_2k:{provider:"Provedor A",model:"Seedream 5.0 Pro (2K)",category:"Geração"},upscaler_standard:{provider:"Provedor B",model:"Image Upscaler",category:"Edição"},upscaler_ultimate:{provider:"Provedor B",model:"Ultimate Upscaler",category:"Edição"},rh_upscale_2k:{provider:"RunningHub",model:"SeedVR2 Upscaler (2K)",category:"Edição"},rh_upscale_3k:{provider:"RunningHub",model:"SeedVR2 Upscaler (3K)",category:"Edição"},rh_upscale_4k:{provider:"RunningHub",model:"SeedVR2 Upscaler (4K)",category:"Edição"},rh_video_upscale_quality:{provider:"RunningHub",model:"SeedVR2 3B (Video Upscaler)",category:"Edição"},rh_video_upscale_maximum:{provider:"RunningHub",model:"SeedVR2 7B (Video Upscaler)",category:"Edição"},rh_video_upscale_experimental:{provider:"RunningHub",model:"FlashVSR (Video Upscaler)",category:"Edição"},caption_generation:{provider:"OpenRouter",model:"Grok 4 Fast",category:"Utilidade"},lora_training:{provider:"Provedor B",model:"LoRA Trainer",category:"Treinamento"},nano_banana_2_kie_1k:{provider:"Provedor A",model:"Nano Banana 2 (1K)",category:"Geração"},nano_banana_2_kie_2k:{provider:"Provedor A",model:"Nano Banana 2 (2K)",category:"Geração"},nano_banana_2_kie_4k:{provider:"Provedor A",model:"Nano Banana 2 (4K)",category:"Geração"},nano_banana_pro_kie_2k:{provider:"Provedor A",model:"Nano Banana Pro (1K/2K)",category:"Geração"},nano_banana_pro_kie_4k:{provider:"Provedor A",model:"Nano Banana Pro (4K)",category:"Geração"},gpt_image_2:{provider:"Provedor A",model:"GPT Image 2 (T2I)",category:"Geração"},gpt_image_2_edit:{provider:"Provedor A",model:"GPT Image 2 (I2I)",category:"Edição"},grok_imagine_t2i:{provider:"Provedor A",model:"Grok Imagine 2.0 (T2I)",category:"Geração"},grok_imagine_t2i_pro:{provider:"Provedor A",model:"Grok Imagine legado (T2I Pro)",category:"Geração"},grok_imagine_i2i:{provider:"Provedor A",model:"Grok Imagine 2.0 (Edit)",category:"Edição"}},yr=[{name:"Geração de Imagem (Playground)",provider:"API do Usuário",model:"Gemini (Imagen)",category:"Geração",costType:"user_api"},{name:"Geração de Vídeo (Veo 3.1)",provider:"API do Usuário",model:"Veo 3.1 Lite / Fast / Full",category:"Geração",costType:"user_api"},{name:"Model Swap (Gemini)",provider:"API do Usuário",model:"Gemini 2.0 Flash",category:"Geração",costType:"user_api"},{name:"Editor de Imagem (Inpaint Gemini)",provider:"API do Usuário",model:"Gemini (Imagen)",category:"Edição",costType:"user_api"},{name:"Descrever Imagem (Playground)",provider:"API do Usuário",model:"Gemini",category:"Utilidade",costType:"user_api"},{name:"Prompt Detailing",provider:"API do Usuário",model:"Gemini 3.1 Flash Preview",category:"Utilidade",costType:"user_api"},{name:"Seedance Director",provider:"API do Usuário",model:"Gemini 3.1 Flash Preview",category:"Utilidade",costType:"user_api"},{name:"WAN 2.7 Video (T2V · I2V · R2V · Edit)",provider:"Provedor A",model:"WAN 2.7 (família)",category:"Geração",costType:"dynamic",dynamicNote:"720p: $0.08/s · 1080p: $0.12/s",endpoint:"generate-wan27-video"},{name:"WAN 3.0 (T2V · I2V · R2V · Fast)",provider:"Kie / WaveSpeed / RunningHub (seleção admin)",model:"WAN 3.0 / Prime",category:"Geração",costType:"dynamic",dynamicNote:"480p/720p/1080p · modos, preço e cobrança seguem o provedor ativo",endpoint:"generate-wan30-video"},{name:"HappyHorse 1.0 (T2V · I2V · R2V · Edit)",provider:"Provedor A",model:"HappyHorse 1.0 (família)",category:"Geração",costType:"dynamic",dynamicNote:"720p: $0.155/s · 1080p: $0.265/s",endpoint:"generate-happyhorse"},{name:"Speech to Text",provider:"Browser API",model:"Web Speech API",category:"Utilidade",costType:"free"},{name:"Download / ZIP",provider:"Nenhum",model:"JSZip (local)",category:"Utilidade",costType:"free"},{name:"Google Drive Upload",provider:"OAuth (Usuário)",model:"Drive API v3",category:"Utilidade",costType:"free"},{name:"Favoritos / Pastas",provider:"Supabase",model:"Database",category:"Utilidade",costType:"free"},{name:"Galeria Comunitária",provider:"Supabase",model:"Database",category:"Utilidade",costType:"free"},{name:"Presets de Referência",provider:"Supabase + B2",model:"Database + Storage",category:"Utilidade",costType:"free"}],_r={Geração:"bg-blue-500/20 text-blue-400 border-blue-500/30",
706Edição:"bg-purple-500/20 text-purple-400 border-purple-500/30",Utilidade:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",Treinamento:"bg-orange-500/20 text-orange-400 border-orange-500/30"},kd=()=>{const s=Dt(),[n,c]=r.useState([]),[u,m]=r.useState(!0);if(r.useEffect(()=>{(async()=>{const[{data:h},{data:x}]=await Promise.all([F.from("credit_costs").select("action_key, label, credits_charged, wavespeed_cost_usd, description, is_active").eq("is_active",!0).order("action_key"),F.from("credit_cost_internals").select("action_key, api_endpoint")]),w=new Map((x||[]).map(v=>[v.action_key,v.api_endpoint]));c((h||[]).map(v=>({...v,api_endpoint:w.get(v.action_key)??""}))),m(!1)})()},[]),u)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})});const _=n.length+yr.length,k=n.length,g=yr.length,l=new Set([...n.map(h=>{var x;return((x=tn[h.action_key])==null?void 0:x.provider)||"Desconhecido"}),...yr.map(h=>h.provider)]);return e.jsxs("div",{className:"glass rounded-xl p-6 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ra,{className:"w-5 h-5 text-primary"}),e.jsxs("div",{children:[e.jsx("h2",{className:"font-display font-semibold text-lg",children:"Mapa do Sistema"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Todas as funcionalidades, IAs utilizadas e custos associados"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-primary",children:_}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Funcionalidades"})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-blue-400",children:k}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Usam Créditos"})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-400",children:g}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Gratuitas / API Usuário"})]}),e.jsxs("div",{className:"bg-secondary/50 rounded-lg p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-orange-400",children:l.size}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Provedores de IA"})]})]}),e.jsx("div",{className:"rounded-lg border border-border/50 overflow-hidden",children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{className:"bg-secondary/30",children:[e.jsx(f,{className:"text-xs",children:"Funcionalidade"}),e.jsx(f,{className:"text-xs",children:"Categoria"}),e.jsx(f,{className:"text-xs",children:"Provedor IA"}),e.jsx(f,{className:"text-xs",children:"Modelo"}),e.jsx(f,{className:"text-xs text-center",children:"Créditos"}),e.jsx(f,{className:"text-xs text-center",children:"Custo API (USD)"}),e.jsx(f,{className:"text-xs",children:"Endpoint / API"}),e.jsx(f,{className:"text-xs text-center",children:"Status"})]})}),e.jsxs(De,{children:[n.map(h=>{const x=h.action_key.startsWith("seedance"),w=h.action_key.startsWith("wan_27_image"),v=h.action_key.startsWith("wan_27_video")||h.action_key.startsWith("wan27_video"),R=h.action_key.startsWith("kling_motion"),$=tn[h.action_key]||(x?{provider:"Provedor A",model:"Seedance 2.0",category:"Geração"}:w?{provider:"Provedor A",model:"WAN 2.7 Image",category:"Geração"}:v?{provider:"Provedor A",model:"WAN 2.7 Video",category:"Geração"}:R?{provider:"Provedor A",model:h.action_key.includes("3.0")||h.action_key.includes("_3_")?"Kling 3.0 Motion":"Kling 2.6 Motion",category:"Geração"}:{provider:"—",model:"—",category:"Utilidade"}),V=_r[$.category]||_r.Utilidade;return e.jsxs(b,{className:"hover:bg-secondary/20",children:[e.jsx(a,{children:e.jsxs("div",{children:[e.jsx("span",{className:"text-sm font-medium",children:h.label}),h.description&&e.jsx("p",{className:"text-[10px] text-muted-foreground leading-tight mt-0.5",children:h.description})]})}),e.jsx(a,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium border ${V}`,children:$.category})}),e.jsx(a,{className:"text-xs",children:s($.provider)}),e.jsx(a,{className:"text-xs font-mono text-muted-foreground",children:$.model}),e.jsx(a,{className:"text-center",children:e.jsxs("span",{className:"text-sm font-semibold text-primary flex items-center justify-center gap-1",children:[e.jsx(ca,{className:"w-3 h-3"})," ",h.credits_charged]})}),e.jsx(a,{className:"text-center",children:h.wavespeed_cost_usd>0?e.jsxs("span",{className:"text-xs font-mono flex items-center justify-center gap-1 text-yellow-500",children:[e.jsx(Ua,{className:"w-3 h-3"})," ",h.wavespeed_cost_usd.toFixed(4)]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),e.jsx(a,{children:e.jsx("code",{className:"text-[10px] bg-secondary/60 px-1.5 py-0.5 rounded text-muted-foreground break-all",children:h.api_endpoint||"—"})}),e.jsx(a,{className:"text-center",children:h.is_active?e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-full bg-emerald-500",title:"Ativo"}):e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-full bg-red-500",title:"Inativo"})})]},h.action_key)}),yr.map(h=>{const x=_r[h.category]||_r.Utilidade;return e.jsxs(b,{className:"hover:bg-secondary/20",children:[e.jsx(a,{children:e.jsx("span",{className:"text-sm font-medium",children:h.name})}),e.jsx(a,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-medium border ${x}`,children:h.category})}),e.jsx(a,{className:"text-xs",children:s(h.provider)}),e.jsx(a,{className:"text-xs font-mono text-muted-foreground",children:h.model}),e.jsx(a,{className:"text-center",children:h.costType==="user_api"?e.jsx(Re,{variant:"outline",className:"text-[10px]",children:"API Usuário"}):h.costType==="dynamic"?e.jsx(Re,{variant:"outline",className:"text-[10px] bg-
706orange-500/20 text-orange-400 border-orange-500/30",children:"Dinâmico /s"}):e.jsx(Re,{variant:"secondary",className:"text-[10px] bg-emerald-500/20 text-emerald-400 border-emerald-500/30",children:"Grátis"})}),e.jsx(a,{className:"text-center",children:h.dynamicNote?e.jsx("span",{className:"text-[10px] font-mono text-orange-400",children:h.dynamicNote}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),e.jsx(a,{children:h.costType==="dynamic"?e.jsx("code",{className:"text-[10px] bg-secondary/60 px-1.5 py-0.5 rounded text-muted-foreground",children:h.endpoint||"—"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"})}),e.jsx(a,{className:"text-center",children:e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:"Sempre ativo"})})]},h.name)})]})]})}),(()=>{const h=[...hi.map(x=>({chave:x.value,label:x.label,tipo:"Vídeo",archivedAt:x.archivedAt,reason:x.reason})),...pi.map(x=>({chave:x.values.join(", "),label:x.label,tipo:"Imagem",archivedAt:x.archivedAt,reason:x.reason}))];return h.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qa,{className:"w-4 h-4 text-amber-400"}),e.jsx("h3",{className:"text-sm font-semibold text-foreground",children:"Modelos arquivados"}),e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:h.length})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Fora do seletor de geração para todos, inclusive admin. O código de geração continua no repositório e o histórico antigo segue tocando — reativar é mover a entrada de volta para",e.jsx("code",{className:"mx-1 bg-secondary/60 px-1 py-0.5 rounded",children:"ENGINE_FAMILIES"}),"em ",e.jsx("code",{className:"bg-secondary/60 px-1 py-0.5 rounded",children:"src/lib/videoEngineCatalog.ts"}),"."]}),e.jsx("div",{className:"rounded-lg border border-white/[0.08] overflow-hidden",children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{className:"text-xs",children:"Modelo"}),e.jsx(f,{className:"text-xs",children:"Tipo"}),e.jsx(f,{className:"text-xs",children:"Chave"}),e.jsx(f,{className:"text-xs",children:"Arquivado em"}),e.jsx(f,{className:"text-xs",children:"Motivo"})]})}),e.jsx(De,{children:[...h].sort((x,w)=>w.archivedAt.localeCompare(x.archivedAt)).map(x=>e.jsxs(b,{children:[e.jsx(a,{className:"text-xs font-medium text-foreground",children:x.label}),e.jsx(a,{children:e.jsx(Re,{variant:"secondary",className:"text-[10px]",children:x.tipo})}),e.jsx(a,{children:e.jsx("code",{className:"text-[10px] bg-secondary/60 px-1.5 py-0.5 rounded text-muted-foreground",children:x.chave})}),e.jsx(a,{className:"text-xs text-muted-foreground tabular-nums",children:x.archivedAt}),e.jsx(a,{className:"text-xs text-muted-foreground",children:x.reason})]},x.chave))})]})})]})})(),e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["* Dados de créditos e custo API são lidos diretamente da tabela ",e.jsx("code",{children:"credit_costs"})," em tempo real."]})]})},xt=5.5,nn=.2,on={name:"",slug:"",price_usd:0,price_brl:0,annual_price_usd:0,annual_price_brl:0,monthly_credits:0,is_legacy:!1,is_active:!0,sort_order:0,stripe_monthly_price_id:null,stripe_annual_price_id:null,stripe_product_id:null,description:""},Cd=()=>{const[s,n]=r.useState([]),[c,u]=r.useState(!0),[m,_]=r.useState(!1),[k,g]=r.useState(!1),[l,h]=r.useState(null),[x,w]=r.useState(on),v=async()=>{u(!0);const{data:Y,error:B}=await F.from("subscription_plans").select("*").order("sort_order",{ascending:!0});B?o.error(B.message):n(Y||[]),u(!1)};r.useEffect(()=>{v()},[]);const R=()=>{h(null),w({...on,sort_order:s.length*10}),g(!0)},$=Y=>{h(Y),w({...Y}),g(!0)},V=Y=>{const B=parseFloat(Y)||0,G=Math.round(B*xt*100)/100,q=Math.round(B*12*(1-nn)*100)/100,E=Math.round(q*xt*100)/100,P=Math.round(B*100);w(K=>({...K,price_usd:B,price_brl:G,annual_price_usd:q,annual_price_brl:E,monthly_credits:P}))},C=Y=>{const B=Y.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"");w(G=>({...G,name:Y,slug:B}))},ee=async()=>{if(!x.name||!x.slug){o.error("Nome e slug são obrigatórios");return}_(!0);try{if(l){const{error:Y}=await F.from("subscription_plans").update(x).eq("id",l.id);if(Y)throw Y;o.success("Plano atualizado!")}else{const{error:Y}=await F.from("subscription_plans").insert(x);if(Y)throw Y;o.success("Plano criado!")}g(!1),v()}catch(Y){o.error(Y.message)}finally{_(!1)}},Z=async Y=>{if(!confirm(`Remover o plano "${Y.name}"? Isso não afeta assinantes existentes.`))return;const{error:B}=await F.from("subscription_plans").delete().eq("id",Y.id);B?o.error(B.message):(o.success("Plano removido"),v())},p=async Y=>{const{error:B}=await F.from("subscription_plans").update({is_active:!Y.is_active}).eq("id",Y.id);B?o.error(B.message):v()},{legacyPlans:z,newPlans:Q}=r.useMemo(()=>({legacyPlans:s.filter(Y=>Y.is_legacy),newPlans:s.filter(Y=>!Y.is_legacy)}),[s]),ae=(Y,B)=>B==="USD"?`$${Y.toFixed(2)}`:`R$${Y.toFixed(2)}`;return c?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-primary"})}):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-xl font-bold",children:"Planos de Assinatura"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Gerencie planos, créditos e preços. Conversão: $1 = R$",xt," | Desconto anual: ",nn*100,"%"]})]}),e.jsxs(y,{onClick:R,size:"sm",className:"gap-2",children:[e.jsx(Us,{className:"w-4 h-4"})," Novo Plano"]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Q.filter(Y=>Y.is_active).map(Y=>e.jsxs(la,{className:"p-4 bg-card/60 border-border/40",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"font-semibold text-sm",children:Y.name}),e.jsx(Re,{variant:"outline",className:"text-xs",children:Y.is_legacy?"
706Legacy":"Novo"})]}),e.jsxs("div",{className:"text-2xl font-bold text-primary",children:["$",Y.price_usd]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["R$",Y.price_brl," / mês"]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1",children:[e.jsx(ta,{className:"w-3 h-3"})," ",Y.monthly_credits.toLocaleString()," créditos"]})]},Y.id))}),z.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(qa,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("h3",{className:"font-semibold text-sm text-muted-foreground",children:"Planos Legados (clientes antigos)"})]}),e.jsx(ln,{plans:z,onEdit:$,onDelete:Z,onToggle:p,formatCurrency:ae})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx($n,{className:"w-4 h-4 text-primary"}),e.jsx("h3",{className:"font-semibold text-sm",children:"Planos Atuais"})]}),e.jsx(ln,{plans:Q,onEdit:$,onDelete:Z,onToggle:p,formatCurrency:ae})]}),e.jsx(ds,{open:k,onOpenChange:g,children:e.jsxs(cs,{className:"max-w-lg",children:[e.jsx(ms,{children:e.jsx(us,{children:l?"Editar Plano":"Novo Plano"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(oe,{children:"Nome"}),e.jsx(je,{value:x.name,onChange:Y=>C(Y.target.value),placeholder:"Ex: Creator"})]}),e.jsxs("div",{children:[e.jsx(oe,{children:"Slug"}),e.jsx(je,{value:x.slug,onChange:Y=>w(B=>({...B,slug:Y.target.value})),placeholder:"creator"})]})]}),e.jsxs("div",{children:[e.jsx(oe,{children:"Preço Mensal (USD)"}),e.jsxs("div",{className:"relative",children:[e.jsx(Ua,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(je,{type:"number",min:0,step:1,value:x.price_usd||"",onChange:Y=>V(Y.target.value),className:"pl-9",placeholder:"50"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 p-3 rounded-lg bg-secondary/30 border border-border/30",children:[e.jsxs("div",{className:"text-xs space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Mensal BRL"}),e.jsxs("p",{className:"font-semibold",children:["R$",x.price_brl.toFixed(2)]})]}),e.jsxs("div",{className:"text-xs space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Anual USD (−20%)"}),e.jsxs("p",{className:"font-semibold",children:["$",x.annual_price_usd.toFixed(2)]})]}),e.jsxs("div",{className:"text-xs space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Anual BRL"}),e.jsxs("p",{className:"font-semibold",children:["R$",x.annual_price_brl.toFixed(2)]})]}),e.jsxs("div",{className:"text-xs space-y-1",children:[e.jsx("p",{className:"text-muted-foreground",children:"Créditos/mês"}),e.jsx("p",{className:"font-semibold text-primary",children:x.monthly_credits.toLocaleString()})]})]}),e.jsxs("div",{children:[e.jsx(oe,{children:"Descrição"}),e.jsx(Ss,{value:x.description,onChange:Y=>w(B=>({...B,description:Y.target.value})),placeholder:"Ideal para criadores...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(oe,{children:"Ordem"}),e.jsx(je,{type:"number",value:x.sort_order,onChange:Y=>w(B=>({...B,sort_order:parseInt(Y.target.value)||0}))})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-6",children:[e.jsx(Vs,{checked:x.is_legacy,onCheckedChange:Y=>w(B=>({...B,is_legacy:Y}))}),e.jsx(oe,{children:"Legado"}),e.jsx(Vs,{checked:x.is_active,onCheckedChange:Y=>w(B=>({...B,is_active:Y}))}),e.jsx(oe,{children:"Ativo"})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t border-border/30",children:[e.jsx("p",{className:"text-xs text-muted-foreground font-medium",children:"IDs do Stripe (preenchidos na próxima fase)"}),e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[e.jsx(je,{value:x.stripe_product_id||"",onChange:Y=>w(B=>({...B,stripe_product_id:Y.target.value||null})),placeholder:"prod_...",className:"text-xs h-8"}),e.jsx(je,{value:x.stripe_monthly_price_id||"",onChange:Y=>w(B=>({...B,stripe_monthly_price_id:Y.target.value||null})),placeholder:"price_... (mensal)",className:"text-xs h-8"}
706),e.jsx(je,{value:x.stripe_annual_price_id||"",onChange:Y=>w(B=>({...B,stripe_annual_price_id:Y.target.value||null})),placeholder:"price_... (anual)",className:"text-xs h-8"})]})]}),e.jsxs(y,{onClick:ee,disabled:m,className:"w-full",children:[m&&e.jsx(he,{className:"w-4 h-4 animate-spin mr-2"}),l?"Salvar Alterações":"Criar Plano"]})]})]})})]})},ln=({plans:s,onEdit:n,onDelete:c,onToggle:u,formatCurrency:m})=>e.jsx("div",{className:"rounded-lg border border-border/40 overflow-hidden",children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{className:"bg-secondary/20",children:[e.jsx(f,{className:"text-xs",children:"Plano"}),e.jsx(f,{className:"text-xs",children:"Mensal"}),e.jsx(f,{className:"text-xs",children:"Anual"}),e.jsx(f,{className:"text-xs",children:"Créditos"}),e.jsx(f,{className:"text-xs",children:"Stripe"}),e.jsx(f,{className:"text-xs",children:"Status"}),e.jsx(f,{className:"text-xs w-24",children:"Ações"})]})}),e.jsx(De,{children:s.map(_=>e.jsxs(b,{className:_.is_active?"":"opacity-50",children:[e.jsxs(a,{children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-sm",children:_.name}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-2",children:["(",_.slug,")"]})]}),_.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:_.description})]}),e.jsxs(a,{className:"text-xs",children:[e.jsx("div",{children:m(_.price_usd,"USD")}),e.jsx("div",{className:"text-muted-foreground",children:m(_.price_brl,"BRL")})]}),e.jsxs(a,{className:"text-xs",children:[e.jsx("div",{children:m(_.annual_price_usd,"USD")}),e.jsx("div",{className:"text-muted-foreground",children:m(_.annual_price_brl,"BRL")})]}),e.jsx(a,{children:e.jsx("span",{className:"text-sm font-semibold text-primary",children:_.monthly_credits.toLocaleString()})}),e.jsx(a,{children:_.stripe_product_id?e.jsx(Re,{variant:"outline",className:"text-xs bg-green-500/10 text-green-400 border-green-500/30",children:"Vinculado"}):e.jsx(Re,{variant:"outline",className:"text-xs",children:"Pendente"})}),e.jsx(a,{children:e.jsx(Vs,{checked:_.is_active,onCheckedChange:()=>u(_)})}),e.jsx(a,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(y,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>n(_),children:e.jsx($r,{className:"w-3.5 h-3.5"})}),e.jsx(y,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:()=>c(_),children:e.jsx(_s,{className:"w-3.5 h-3.5"})})]})})]},_.id))})]})});function Sd(s){if(!s)return!1;const n=s.toLowerCase();return n==="year"||n==="annual"||n==="yearly"}function Ad(s){return s.filter(n=>n.is_paid&&!n.is_partner&&n.subscription_plan&&n.subscription_plan!=="free")}function Ed(s,n){const c=new Map;for(const l of n)c.set(l.slug.toLowerCase(),l);let u=0,m=0,_=0,k=0;const g=new Map;for(const l of s){const h=(l.plan_slug||l.subscription_plan||"").toLowerCase(),x=c.get(h);if(!x){k++;continue}const w=Sd(l.subscription_interval),v=w?(x.annual_price_usd||x.price_usd*12*.8)/12:x.price_usd;u+=v,w?_++:m++;const R=g.get(h)||{slug:h,name:x.name,monthlyCount:0,annualCount:0,totalCount:0,mrrUsd:0,arrUsd:0};R.totalCount++,w?R.annualCount++:R.monthlyCount++,R.mrrUsd+=v,R.arrUsd=R.mrrUsd*12,g.set(h,R)}return{mrrUsd:u,arrUsd:u*12,monthlyCount:m,annualCount:_,unmappedCount:k,breakdown:Array.from(g.values()).sort((l,h)=>h.mrrUsd-l.mrrUsd)}}function Rd(s,n){return n>0?s/n:0}function Pd(s,n=30,c=Date.now()){const u=c+n*24*60*60*1e3;return s.filter(m=>{if(!m.subscription_renews_at)return!1;const _=new Date(m.subscription_renews_at).getTime();return _>=c&&_<=u}).length}const Id=[7,30],dn=5,mr=s=>`$${s.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`,fs=s=>s.toLocaleString("pt-BR"),Ot=s=>new Date(Date.now()-s*864e5).toISOString();function La({titulo:s,icone:n,onRefresh:c,carregando:u,erro:m,children:_,acao:k}){return e.jsxs("div",{className:"glass rounded-xl p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(n,{className:"w-4 h-4 text-primary shrink-0"}),e.jsx("h3",{className:"font-display font-semibold text-sm truncate",children:s})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[k&&e.jsxs("button",{onClick:k.onClick,className:"text-[12px] text-primary/80 hover:text-primary flex items-center gap-0.5",children:[k.label," ",e.jsx(gi,{className:"w-3 h-3"})]}),c&&e.jsx("button",{onClick:c,disabled:u,className:"p-1 text-muted-foreground hover:text-foreground disabled:opacity-50",children:u?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Qe,{className:"w-3.5 h-3.5"})})]})]}),m?e.jsx("p",{className:"text-sm text-destructive/90",children:m}):_]})}function Ns({label:s,valor:n,sub:c,alerta:u,onClick:m}){return e.jsxs("div",{onClick:m,className:Ue("rounded-lg border p-3",m&&"cursor-pointer hover:border-primary/40 transition-colors",u?"border-amber-500/40 bg-amber-500/5":"border-border/50 bg-card/30"),children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground mb-1",children:s}),e.jsx("p",{className:Ue("text-xl font-semibold tabular-nums",u&&"text-amber-400"),children:n}),c&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:c})]})}function Td(){const[s,n]=r.useState(null),[c,u]=r.useState(null),[m,_]=r.useState(!1),k=r.useCallback(async()=>{_(!0),u(null);try{const[g,l,h]=await Promise.all([F.from("profiles").select("subscription_plan, plan_
706slug, subscription_interval, subscription_renews_at, is_paid, is_partner").eq("is_paid",!0).not("is_partner","is",!0).neq("subscription_plan","free"),F.from("subscription_plans").select("slug, name, price_usd, annual_price_usd"),F.from("profiles").select("*",{count:"exact",head:!0}).eq("is_paid",!1).not("is_partner","is",!0).gt("trial_ends_at",new Date().toISOString())]);if(g.error)throw g.error;if(l.error)throw l.error;const x=Ad(g.data||[]),w=Ed(x,l.data||[]);n({mrr:w.mrrUsd,arr:w.arrUsd,pagantes:x.length,arpu:Rd(w.mrrUsd,x.length),trials:h.count??0,renov:Pd(x,30),semPlano:w.unmappedCount})}catch(g){u((g==null?void 0:g.message)||"Não consegui carregar.")}finally{_(!1)}},[]);return r.useEffect(()=>{k()},[k]),{d:s,erro:c,carregando:m,carregar:k}}const yt={novos:["checkout.session.completed","subscription_activated","subscription_reactivated"],cancelou:["customer.subscription.deleted","subscription_revoked"],reembolso:["charge.refunded"],chargeback:["charge.dispute.created"],pastDue:["subscription_past_due"]};function Ld(s){const[n,c]=r.useState(null),[u,m]=r.useState(null),[_,k]=r.useState(!1),g=r.useCallback(async()=>{k(!0),m(null);try{const l=Ot(s),h=Object.keys(yt),x=await Promise.allSettled(h.map(v=>F.from("webhook_logs").select("*",{count:"exact",head:!0}).in("event_type",yt[v]).gte("created_at",l))),w={};h.forEach((v,R)=>{const $=x[R];w[v]=$.status==="fulfilled"?$.value.count??0:0}),c(w)}catch(l){m((l==null?void 0:l.message)||"Não consegui carregar.")}finally{k(!1)}},[s]);return r.useEffect(()=>{g()},[g]),{d:n,erro:u,carregando:_,carregar:g}}function Dd(){const[s,n]=r.useState(null),[c,u]=r.useState(null),[m,_]=r.useState(!1),k=r.useCallback(async()=>{_(!0),u(null);try{const{data:g,error:l}=await F.functions.invoke("admin-provider-balance",{body:{}});if(l)throw l;n(Array.isArray(g==null?void 0:g.saldos)?g.saldos:[])}catch(g){u((g==null?void 0:g.message)||"Provedores indisponíveis.")}finally{_(!1)}},[]);return r.useEffect(()=>{k()},[k]),{d:s,erro:c,carregando:m,carregar:k}}function Od(){const[s,n]=r.useState(null),[c,u]=r.useState(null),[m,_]=r.useState(!1),k=r.useCallback(async()=>{_(!0),u(null);try{const g=Ot(1),[l,h,x,w]=await Promise.allSettled([F.functions.invoke("labs-comfy-rh",{body:{action:"admin-status"}}),F.functions.invoke("labs-upscale-rh",{body:{action:"status"}}),F.from("generations").select("*",{count:"exact",head:!0}).gte("created_at",g).like("media_url","processing://%"),F.from("error_logs").select("*",{count:"exact",head:!0}).gte("created_at",g)]),v=(R,$)=>{var V,C;return R.status==="fulfilled"&&Number(((C=(V=R.value)==null?void 0:V.data)==null?void 0:C[$])??0)||0};n({emVoo:x.status==="fulfilled"?x.value.count??0:0,travadas:v(l,"stale")+v(h,"stale"),presos:v(l,"creditosPresos"),erros24h:w.status==="fulfilled"?w.value.count??0:0})}catch(g){u((g==null?void 0:g.message)||"Não consegui carregar.")}finally{_(!1)}},[]);return r.useEffect(()=>{k()},[k]),{d:s,erro:c,carregando:m,carregar:k}}function Md(){const[s,n]=r.useState(null),[c,u]=r.useState(null),[m,_]=r.useState(!1),k=r.useCallback(async()=>{_(!0),u(null);try{const g=(x,w)=>w(F.from(x).select("*",{count:"exact",head:!0})),l=await Promise.allSettled([g("support_tickets",x=>x.in("status",["open","waiting_user"])),g("community_posts",x=>x.eq("status","pending")),g("community_posts",x=>x.eq("pending_public",!0)),g("community_reports",x=>x.eq("status","open")),g("affiliate_applications",x=>x.eq("status","pending")),g("affiliate_payouts",x=>x.eq("status","failed"))]),h=x=>l[x].status==="fulfilled"?l[x].value.count??0:0;n({tickets:h(0),posts:h(1),publicos:h(2),denuncias:h(3),afiliados:h(4),saques:h(5)})}catch(g){u((g==null?void 0:g.message)||"Não consegui carregar.")}finally{_(!1)}},[]);return r.useEffect(()=>{k()},[k]),{d:s,erro:c,carregando:m,carregar:k}}function Fd(s){const[n,c]=r.useState(null),[u,m]=r.useState(null),[_,k]=r.useState(!1),g=r.useCallback(async()=>{k(!0),m(null);try{const l=Ot(s),h=await Promise.allSettled([F.from("generations").select("*",{count:"exact",head:!0}).eq("media_type","image").gte("created_at",l),F.from("generations").select("*",{count:"exact",head:!0}).eq("media_type","video").gte("created_at",l),F.from("profiles").select("*",{count:"exact",head:!0}).gte("created_at",l)]),x=w=>h[w].status==="fulfilled"?h[w].value.count??0:0;c({imagens:x(0),videos:x(1),usuarios:x(2)})}catch(l){m((l==null?void 0:l.message)||"Não consegui carregar.")}finally{k(!1)}},[s]);return r.useEffect(()=>{g()},[g]),{d:n,erro:u,carregando:_,carregar:g}}function Ud(){const[s,n]=r.useState(null),[c,u]=r.useState(null),[m,_]=r.useState(!1),k=r.useCallback(async()=>{_(!0),u(null);try{const{data:g,error:l}=await F.from("webhook_logs").select("id, created_at, event_type, email").in("event_type",Object.values(yt).flat()).order("created_at",{ascending:!1}).limit(8);if(l)throw l;n(g||[])}catch(g){u((g==null?void 0:g.message)||"Não consegui carregar.")}finally{_(!1)}},[]);return r.useEffect(()=>{k()},[k]),{d:s,erro:c,carregando:m,carregar:k}}const cn=()=>{const s=fr(),[n,c]=r.useState(30),u=Td(),m=Ld(n),_=Dd(),k=Od(),g=Md(),l=Fd(n),h=Ud(),x=r.useMemo(()=>{var R,$,V,C;const v=[];for(const ee of _.d||[])ee.ok&&typeof ee.usd=="number"&&ee.usd<dn&&v.push({texto:`${ee.label}: saldo ${mr(ee.usd)}`,ir:"/admin/creditos"}),ee.ok||v.push({texto:`${ee.label}: sem leitura de saldo`,ir:"/admin/creditos"});return(R=k.d)!=null&&R.presos&&v.push({texto:`${fs(k.d.presos)} créditos presos`,ir:"/admin/recuperacao"}),($=k.d)!=null&&$.travadas&&v.push({texto:`${fs(k.d.travadas)} gerações travadas`,ir:"/admin/recuperacao"}),(V=m.d)!=null&&V.chargeback&&v.push({texto:`${fs(m.d.chargeback)} chargeback(s) em ${n}d`,ir:"/admin/receita"}),(C=g.d)!=null&&C.denuncias&&v.push({texto:`${fs(g.d.denuncias)} denúncia(s) aberta(s)`,ir:"/admin/comunidade"}),v},[_.d,k.d,m.d,g.d,n]),w=()=>
706{u.carregar(),m.carregar(),_.carregar(),k.carregar(),g.carregar(),l.carregar(),h.carregar()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-display font-bold text-xl",children:"Painel de Controle"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Resumo do que exige sua atenção hoje."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex rounded-lg border border-border/60 overflow-hidden",children:Id.map(v=>e.jsxs("button",{onClick:()=>c(v),className:Ue("px-3 py-1.5 text-xs font-medium transition-colors",n===v?"bg-primary/15 text-primary":"text-muted-foreground hover:text-foreground"),children:[v,"d"]},v))}),e.jsxs(y,{variant:"outline",size:"sm",onClick:w,className:"gap-2",children:[e.jsx(Qe,{className:"w-4 h-4"})," Atualizar"]})]})]}),x.length>0&&e.jsxs("div",{className:"rounded-xl border border-amber-500/30 bg-amber-500/5 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(qs,{className:"w-4 h-4 text-amber-400"}),e.jsx("span",{className:"text-sm font-semibold text-amber-400",children:"Precisa de atenção"})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:x.map((v,R)=>e.jsx("button",{onClick:()=>s(v.ir),className:"px-2.5 py-1 rounded-md bg-amber-500/10 border border-amber-500/25 text-[12px] text-amber-300 hover:bg-amber-500/20 transition-colors",children:v.texto},R))})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(La,{titulo:"Dinheiro agora",icone:Ua,onRefresh:u.carregar,carregando:u.carregando,erro:u.erro,acao:{label:"Receita",onClick:()=>s("/admin/receita")},children:u.d?e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsx(Ns,{label:"MRR",valor:mr(u.d.mrr)}),e.jsx(Ns,{label:"ARR",valor:mr(u.d.arr)}),e.jsx(Ns,{label:"ARPU",valor:mr(u.d.arpu)}),e.jsx(Ns,{label:"Assinantes",valor:fs(u.d.pagantes)}),e.jsx(Ns,{label:"Em trial",valor:fs(u.d.trials)}),e.jsx(Ns,{label:"Renovam em 30d",valor:fs(u.d.renov)}),u.d.semPlano>0&&e.jsx(Ns,{label:"Sem plano mapeado",valor:fs(u.d.semPlano),alerta:!0,sub:"não entram no MRR"})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando…"})}),e.jsx(La,{titulo:"Caixa nos provedores",icone:zn,onRefresh:_.carregar,carregando:_.carregando,erro:_.erro,children:_.d?_.d.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum provedor respondeu."}):e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:_.d.map((v,R)=>{const $=v.ok&&typeof v.usd=="number"&&v.usd<dn;return e.jsxs("div",{className:Ue("rounded-lg border p-3",v.ok?$?"border-amber-500/40 bg-amber-500/5":"border-border/50 bg-card/30":"border-destructive/30 bg-destructive/5"),children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground mb-1",children:v.label}),v.ok?e.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[typeof v.usd=="number"&&e.jsx("span",{className:Ue("text-lg font-semibold tabular-nums",$&&"text-amber-400"),children:mr(v.usd)}),typeof v.credits=="number"&&e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:[fs(v.credits)," cr"]}),v.nota&&e.jsx("span",{className:"text-xs text-muted-foreground",children:v.nota}),v.usd==null&&v.credits==null&&!v.nota&&e.jsxs("details",{className:"w-full",children:[e.jsx("summary",{className:"text-xs text-amber-400/90 cursor-pointer",children:"respondeu, mas sem saldo legível — ver resposta"}),e.jsx("pre",{className:"mt-1 text-[10px] text-muted-foreground/80 whitespace-pre-wrap break-all max-h-32 overflow-auto",children:JSON.stringify(v.raw??{},null,1)})]})]}):e.jsx("p",{className:"text-xs text-destructive/90",children:v.erro||"indisponível"})]},`${v.provider}-${R}`)})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Consultando…"})}),e.jsx(La,{titulo:`Movimento · ${n} dias`,icone:Fn,onRefresh:m.carregar,carregando:m.carregando,erro:m.erro,children:m.d?e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsx(Ns,{label:"Novos",valor:fs(m.d.novos)}),e.jsx(Ns,{label:"Cancelaram",valor:fs(m.d.cancelou),alerta:m.d.cancelou>0}),e.jsx(Ns,{label:"Reembolsos",valor:fs(m.d.reembolso),alerta:m.d.reembolso>0}),e.jsx(Ns,{label:"Chargebacks",valor:fs(m.d.chargeback),alerta:m.d.chargeback>0}),e.jsx(Ns,{label:"Past due",valor:fs(m.d.pastDue),alerta:m.d.pastDue>0})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando…"})}),e.jsx(La,{titulo:"Saúde da operação",icone:Yn,onRefresh:k.carregar,carregando:k.carregando,erro:k.erro,acao:{label:"Recuperação",onClick:()=>s("/admin/recuperacao")},children:k.d?e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(Ns,{label:"Em voo (24h)",valor:fs(k.d.emVoo)}),e.jsx(Ns,{label:"Travadas",valor:fs(k.d.travadas),alerta:k.d.travadas>0,onClick:()=>s("/admin/recuperacao")}),e.jsx(Ns,{label:"Créditos presos",valor:fs(k.d.presos),alerta:k.d.presos>0,onClick:()=>s("/admin/recuperacao")}),e.jsx(Ns,{label:"Erros (24h)",valor:fs(k.d.erros24h),onClick:()=>s("/admin/logs")}
706)]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando…"})}),e.jsx(La,{titulo:"Esperando você",icone:Qn,onRefresh:g.carregar,carregando:g.carregando,erro:g.erro,children:g.d?e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsx(Ns,{label:"Tickets",valor:fs(g.d.tickets),alerta:g.d.tickets>0,onClick:()=>s("/admin/tickets")}),e.jsx(Ns,{label:"Posts pendentes",valor:fs(g.d.posts),onClick:()=>s("/admin/comunidade")}),e.jsx(Ns,{label:"Pedidos públicos",valor:fs(g.d.publicos),onClick:()=>s("/admin/comunidade")}),e.jsx(Ns,{label:"Denúncias",valor:fs(g.d.denuncias),alerta:g.d.denuncias>0,onClick:()=>s("/admin/comunidade")}),e.jsx(Ns,{label:"Afiliados",valor:fs(g.d.afiliados),onClick:()=>s("/admin/afiliados")}),e.jsx(Ns,{label:"Saques falhados",valor:fs(g.d.saques),alerta:g.d.saques>0,onClick:()=>s("/admin/afiliados")})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando…"})}),e.jsx(La,{titulo:`Uso · ${n} dias`,icone:sa,onRefresh:l.carregar,carregando:l.carregando,erro:l.erro,children:l.d?e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(Ns,{label:"Imagens",valor:fs(l.d.imagens)}),e.jsx(Ns,{label:"Vídeos",valor:fs(l.d.videos)}),e.jsx(Ns,{label:"Novos usuários",valor:fs(l.d.usuarios)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando…"})})]}),e.jsx(La,{titulo:"Últimos eventos de cobrança",icone:fa,onRefresh:h.carregar,carregando:h.carregando,erro:h.erro,acao:{label:"Ver tudo",onClick:()=>s("/admin/receita")},children:h.d?h.d.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nada recente."}):e.jsx("div",{className:"space-y-1",children:h.d.map(v=>e.jsxs("div",{className:"flex items-center justify-between gap-3 text-[12px] py-1 border-b border-border/30 last:border-0",children:[e.jsx("span",{className:"font-mono text-muted-foreground truncate",children:v.event_type}),e.jsx("span",{className:"truncate text-muted-foreground/80 flex-1 min-w-0",children:v.email||"—"}),e.jsx("span",{className:"text-muted-foreground/60 shrink-0 tabular-nums",children:new Date(v.created_at).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})})]},v.id))}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando…"})})]})},$d=5.5,ur=(s,n)=>{const c=n==="BRL"?s*$d:s;return new Intl.NumberFormat(n==="BRL"?"pt-BR":"en-US",{style:"currency",currency:n,minimumFractionDigits:0,maximumFractionDigits:0}).format(c)},Xa=s=>new Intl.NumberFormat("pt-BR").format(s),zd=s=>{if(!s)return!1;const n=s.toLowerCase();return n==="year"||n==="annual"||n==="yearly"},Bd=()=>{const[s,n]=r.useState(!0),[c,u]=r.useState(!1),[m,_]=r.useState([]),[k,g]=r.useState([]),[l,h]=r.useState([]),[x,w]=r.useState("USD"),[v,R]=r.useState(30),$=async()=>{u(!0);try{const[P,K,J]=await Promise.all([F.from("profiles").select("user_id, nickname, subscription_plan, plan_slug, subscription_interval, subscription_started_at, subscription_renews_at, trial_ends_at, is_paid, is_premium, is_partner, stripe_subscription_id, created_at"),F.from("subscription_plans").select("slug, name, price_usd, price_brl, annual_price_usd, annual_price_brl, monthly_credits, is_active, is_legacy").order("sort_order",{ascending:!0}),F.from("webhook_logs").select("id, created_at, event_type, user_id, email, payload").in("event_type",["checkout.session.completed","subscription_activated","subscription_reactivated","customer.subscription.deleted","customer.subscription.updated","subscription_revoked","subscription_past_due","charge.refunded","charge.dispute.created","invoice.payment_succeeded"]).order("created_at",{ascending:!1}).limit(500)]);if(P.error)throw P.error;if(K.error)throw K.error;if(J.error)throw J.error;_(P.data||[]),g(K.data||[]),h(J.data||[])}catch(P){o.error(P.message||"Erro ao carregar receita")}finally{n(!1),u(!1)}};r.useEffect(()=>{$()},[]);const V=r.useMemo(()=>{const P=new Map;for(const K of k)P.set(K.slug.toLowerCase(),K);return P},[k]),C=r.useMemo(()=>m.filter(P=>P.is_paid&&!P.is_partner&&P.subscription_plan&&P.subscription_plan!=="free"),[m]),ee=r.useMemo(()=>{const P=Date.now();return m.filter(K=>!K.is_paid&&!K.is_partner&&K.trial_ends_at&&new Date(K.trial_ends_at).getTime()>P)},[m]),Z=r.useMemo(()=>m.filter(P=>P.is_partner).length,[m]),{mrrUsd:p,arrUsd:z,monthlyCount:Q,annualCount:ae,breakdown:Y,unmappedCount:B}=r.useMemo(()=>{let P=0,K=0,J=0,W=0;const N=new Map;
706for(const D of C){const i=(D.plan_slug||D.subscription_plan||"").toLowerCase(),A=V.get(i);if(!A){W++;continue}const O=zd(D.subscription_interval),te=O?(A.annual_price_usd||A.price_usd*12*.8)/12:A.price_usd;P+=te,O?J++:K++;const T=N.get(i)||{slug:i,name:A.name,monthlyCount:0,annualCount:0,totalCount:0,mrrUsd:0,arrUsd:0};T.totalCount++,O?T.annualCount++:T.monthlyCount++,T.mrrUsd+=te,T.arrUsd=T.mrrUsd*12,N.set(i,T)}const ce=Array.from(N.values()).sort((D,i)=>i.mrrUsd-D.mrrUsd);return{mrrUsd:P,arrUsd:P*12,monthlyCount:K,annualCount:J,breakdown:ce,unmappedCount:W}},[C,V]),G=r.useMemo(()=>{const P=Date.now()-v*24*60*60*1e3,K=C.filter(te=>te.subscription_started_at&&new Date(te.subscription_started_at).getTime()>=P).length,J=m.filter(te=>te.is_paid&&!te.is_partner&&te.created_at&&new Date(te.created_at).getTime()>=P).length;let W=0,N=0,ce=0,D=0,i=0,A=0;for(const te of l)if(!(new Date(te.created_at).getTime()<P))switch(te.event_type){case"customer.subscription.deleted":case"subscription_revoked":W++;break;case"charge.refunded":N++;break;case"charge.dispute.created":ce++;break;case"subscription_past_due":D++;break;case"invoice.payment_succeeded":i++;break;case"checkout.session.completed":A++;break}const O=C.length>0?W/(C.length+W)*100:0;return{newSubs:K,newPaying:J,churnEvents:W,churnRate:O,refundEvents:N,chargebackEvents:ce,pastDueEvents:D,invoicePaidEvents:i,checkoutCompletedEvents:A}},[C,m,l,v]),q=r.useMemo(()=>{const P=Date.now(),K=P+30*24*60*60*1e3;return C.filter(J=>{if(!J.subscription_renews_at)return!1;const W=new Date(J.subscription_renews_at).getTime();return W>=P&&W<=K}).length},[C]);if(s)return e.jsx("div",{className:"flex justify-center py-24",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})});const E=C.length>0?p/C.length:0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"font-display font-semibold text-lg flex items-center gap-2",children:[e.jsx(Ua,{className:"w-5 h-5 text-primary"})," Receita & Assinaturas"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"MRR calculado de assinaturas ativas (parceiros e admin excluídos). Anuais convertidos em equivalente mensal."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(as,{value:x,onValueChange:P=>w(P),children:[e.jsx(rs,{className:"w-[110px] h-9 text-xs",children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"USD",children:"USD ($)"}),e.jsx(pe,{value:"BRL",children:"BRL (R$)"})]})]}),e.jsxs(as,{value:String(v),onValueChange:P=>R(Number(P)),children:[e.jsx(rs,{className:"w-[120px] h-9 text-xs",children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"7",children:"Últimos 7d"}),e.jsx(pe,{value:"30",children:"Últimos 30d"}),e.jsx(pe,{value:"90",children:"Últimos 90d"})]})]}),e.jsxs(y,{size:"sm",variant:"outline",className:"gap-2",onClick:$,disabled:c,children:[c?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Qe,{className:"w-3.5 h-3.5"}),"Atualizar"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ja,{icon:Fn,label:"MRR",value:ur(p,x),sub:`ARR: ${ur(z,x)}`,highlight:!0}),e.jsx(ja,{icon:sa,label:"Assinantes ativos",value:Xa(C.length),sub:`${Q} mensais · ${ae} anuais`}),e.jsx(ja,{icon:Ua,label:"ARPU",value:ur(E,x),sub:"Receita média por assinante (mês)"}),e.jsx(ja,{icon:Xs,label:"Trial ativos",value:Xa(ee.length),sub:`${Z} parceiros (não contam)`})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ja,{icon:jr,label:`Novos assinantes (${v}d)`,value:Xa(G.newSubs),sub:`+${G.newPaying} contas pagas criadas`,accent:"positive"}),e.jsx(ja,{icon:Do,label:`Churn (${v}d)`,value:Xa(G.churnEvents),sub:`${G.churnRate.toFixed(1)}% taxa estimada`,accent:"negative"}),e.jsx(ja,{icon:Vo,label:"Renovações próximas (30d)",value:Xa(q),sub:"Assinaturas ativas com renovação no horizonte"}),e.jsx(ja,{icon:Bo,label:`Problemas (${v}d)`,value:Xa(G.refundEvents+G.chargebackEvents+G.pastDueEvents),sub:`${G.refundEvents} reembolsos · ${G.chargebackEvents} chargebacks · ${G.pastDueEvents} past_due`,accent:G.refundEvents+G.chargebackEvents>0?"negative":void 0})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-card/50 p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"font-display font-semibold flex items-center gap-2",children:[e.jsx(wn,{className:"w-4 h-4 text-primary"})," Receita por Plano"]}),B>0&&e.jsxs(Re,{variant:"outline",className:"text-[10px] border-orange-500/50 text-orange-500",children:[B," assinante(s) sem plano mapeado"]})]}),Y.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"Nenhum assinante ativo encontrado."}):e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Plano"}),e.jsx(f,{className:"text-right",children:"Mensais"}),e.jsx(f,{className:"text-right",children:"Anuais"}),e.jsx(f,{className:"text-right",children:"Total"}),e.jsx(f,{className:"text-right",children:"MRR"}),e.jsx(f,{className:"text-right",children:"ARR"}),e.jsx(f,{className:"text-right",children:"% MRR"})]})}),e.jsx(De,{children:Y.map(P=>{const K=p>0?P.mrrUsd/p*100:0;return e.jsxs(b,{children:[e.jsx(a,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:P.name}),e.jsx(Re,{variant:"outline",className:"text-[10px] font-mono",children:P.slug})]})}),e.jsx(a,{className:"text-right tabular-nums text-muted-foreground",children:P.monthlyCount}),e.jsx(a,{className:"text-right tabular-nums text-muted-foreground",children:P.annualCount}),e.jsx(a,{className:"text-right tabular-nums font-medium",children:P.totalCount}),e.jsx(a,{className:"text-right tabular-nums font-semibold text-primary",children:ur(P.mrrUsd,x)}),e.jsx(a,{className:"text-right tabular-nums text-muted-foreground",children:ur(P.arrUsd,x)}),e.jsxs(a,{className:"text-right tabular-nums text-xs text-muted-foreground",children:[K.toFixed(1),"%"]})]},P.slug)})})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-card/50 p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"font-display font-semibold flex items-center gap-2",children:[e.jsx(go,{className:"w-4 h-4 text-primary"})," Eventos Recentes de Cobrança"]}),e.jsx(Re,{variant:"secondary",className:"text-xs",children:l.length})]}),l.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"Nenhum evento registrado."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{className:"w-40",children:"Data"}),e.jsx(f,{children:"Evento"}),e.jsx(f,{children:"Email / Usuário"}),e.jsx(f,{children:"Detalhes"})]})}),e.jsx(De,{children:l.slice(0,50).map(P=>{const K=qd(P.event_type),J=Vd(P.payload);return e.jsxs(b,{children:[e.jsx(a,{className:"text-xs text-muted-foreground whitespace-nowrap",children:new Date(P.created_at).toLocaleStr
706ing("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}),e.jsx(a,{children:e.jsx(Re,{variant:K.variant,className:Ue("text-[10px]",K.className),children:K.label})}),e.jsx(a,{className:"text-xs",children:P.email||(P.user_id?e.jsxs("span",{className:"font-mono text-muted-foreground",children:[P.user_id.slice(0,8),"…"]}):"—")}),e.jsx(a,{className:"text-xs text-muted-foreground max-w-md truncate",title:J,children:J})]},P.id)})})]})})]})]})},ja=({icon:s,label:n,value:c,sub:u,highlight:m,accent:_})=>e.jsxs("div",{className:Ue("rounded-xl border border-border/40 bg-card/50 p-5",m&&"border-primary/30 bg-primary/5"),children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:Ue("w-9 h-9 rounded-lg flex items-center justify-center",m?"bg-primary/15":_==="positive"?"bg-green-500/15":_==="negative"?"bg-red-500/15":"bg-secondary"),children:e.jsx(s,{className:Ue("w-4 h-4",m?"text-primary":_==="positive"?"text-green-500":_==="negative"?"text-red-500":"text-muted-foreground")})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n})]}),e.jsx("p",{className:"text-2xl font-display font-bold tabular-nums",children:c}),u&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:u})]}),qd=s=>{switch(s){case"checkout.session.completed":return{label:"Checkout",variant:"outline",className:"border-blue-500/50 text-blue-400"};case"subscription_activated":return{label:"Ativada",variant:"outline",className:"border-green-500/50 text-green-500"};case"subscription_reactivated":return{label:"Reativada",variant:"outline",className:"border-green-500/50 text-green-500"};case"invoice.payment_succeeded":return{label:"Pagamento OK",variant:"outline",className:"border-emerald-500/50 text-emerald-500"};case"customer.subscription.updated":return{label:"Atualizada",variant:"outline",className:"border-zinc-500/50 text-zinc-400"};case"customer.subscription.deleted":case"subscription_revoked":return{label:"Cancelada",variant:"outline",className:"border-red-500/50 text-red-500"};case"subscription_past_due":return{label:"Past Due",variant:"outline",className:"border-orange-500/50 text-orange-500"};case"charge.refunded":return{label:"Reembolso",variant:"outline",className:"border-orange-500/50 text-orange-400"};case"charge.dispute.created":return{label:"Chargeback",variant:"destructive"};default:return{label:s,variant:"outline"}}},Vd=s=>{var n,c,u,m,_,k;if(!s)return"—";try{const g=[],l=((n=s==null?void 0:s.data)==null?void 0:n.object)||(s==null?void 0:s.object)||s;return(l==null?void 0:l.amount_total)!=null?g.push(`${(l.amount_total/100).toFixed(2)} ${(l.currency||"usd").toUpperCase()}`):(l==null?void 0:l.amount)!=null?g.push(`${(l.amount/100).toFixed(2)} ${(l.currency||"usd").toUpperCase()}`):(l==null?void 0:l.amount_paid)!=null&&g.push(`${(l.amount_paid/100).toFixed(2)} ${(l.currency||"usd").toUpperCase()}`),(c=l==null?void 0:l.plan)!=null&&c.nickname?g.push(l.plan.nickname):(_=(m=(u=l==null?void 0:l.lines)==null?void 0:u.data)==null?void 0:m[0])!=null&&_.description?g.push(l.lines.data[0].description):(k=l==null?void 0:l.metadata)!=null&&k.plan_slug&&g.push(`plano: ${l.metadata.plan_slug}`),l!=null&&l.reason&&g.push(l.reason),l!=null&&l.cancellation_reason&&g.push(`motivo: ${l.cancellation_reason}`),g.length>0?g.join(" · "):"—"}catch{return"—"}},Gd={"seedream-4.5":"bytedance/seedream-v4.5/edit","seedream-5.0-lite":"bytedance/seedream-v5.0-lite/edit","z-image-turbo":"wavespeed-ai/z-image/turbo","flux-2-klein":"wavespeed-ai/flux-2-klein-9b/edit","qwen-image-2":"wavespeed-ai/qwen-image-2.0/edit","qwen-image-2-pro":"wavespeed-ai/qwen-image-2.0-pro/edit","ltx-2.3-hot":"wavespeed-ai/ltx-2.3-spicy/image-to-video-lora","ltx-2.3-t2v":"wavespeed-ai/ltx-2.3/text-to-video","ltx-2.3-i2v":"wavespeed-ai/ltx-2.3/image-to-video","ltx-2.3-t2v-lora":"wavespeed-ai/ltx-2.3/text-to-video-lora","ltx-2.3-i2v-lora":"wavespeed-ai/ltx-2.3/image-to-video-lora"},Wd=Object.keys(Gd).filter(s=>!s.startsWith("seedream-")),Kd=()=>{const[s,n]=r.useState([]),[c,u]=r.useState(!0),[m,_]=r.useState(null),[k,g]=r.useState(""),[l,h]=r.useState(""),[x,w]=r.useState("qwen-image-2-pro"),[v,R]=r.useState("wavespeed"),[$,V]=r.useState(""),[C,ee]=r.useState(""),[Z,p]=r.useState("fast"),[z,Q]=r.useState("720p"),[ae,Y]=r.useState(!1),B=async()=>{var P;u(!0);try{const{data:K,error:J}=await F.from("generations").select("id, user_id, created_at, prompt, model, media_url, metadata").or("media_url.like.error://%,media_url.like.processing://timeout").order("created_at",{ascending:!1}).limit(80);if(J)throw J;const W=(K||[]).filter(i=>{const A=i.metadata||{},O=!!A.taskId;if(A.recoveryDismissed===!0)return!1;const te=A.recoverable===!0||A.errorCode==="PROVIDER_TIMEOUT"||A.errorCode==="TIMEOUT"||A.recoveryPending===!0||A.status==="timeout";return O&&te}),N=[...new Set(W.map(i=>
706i.user_id))];let ce={},D={};if(N.length>0){const[i,A]=await Promise.all([F.functions.invoke("admin-list-emails"),F.from("profiles").select("user_id, nickname").in("user_id",N)]);ce=((P=i.data)==null?void 0:P.emailMap)||{},(A.data||[]).forEach(O=>{D[O.user_id]=O.nickname||""})}n(W.map(i=>({...i,user_email:ce[i.user_id]||"",user_nickname:D[i.user_id]||""})))}catch(K){o.error(K.message||"Erro ao listar pendentes")}finally{u(!1)}};r.useEffect(()=>{B()},[]);const G=async P=>{if(await ji({title:"Descartar esta geração?",description:"Sai da fila de recuperação. Se ainda houver créditos reservados, eles voltam pro usuário agora. A geração continua no histórico dele.",confirmLabel:"Descartar",destructive:!0})){_(P.id);try{const{data:J,error:W}=await F.functions.invoke("labs-comfy-rh",{body:{action:"recovery-dismiss",generationId:P.id}});if(W)throw W;if(J!=null&&J.error)throw new Error(J.error);const N=Number((J==null?void 0:J.creditsRefunded)||0);o.success(N>0?`Descartada. ${N} crédito(s) devolvidos.`:"Descartada. Não havia crédito reservado."),B()}catch(J){o.error(J.message||"Falha ao descartar")}finally{_(null)}}},q=async P=>{const K=P.metadata||{},J=K.taskId;if(!J){o.error("Sem taskId — não é possível recuperar");return}_(P.id);try{const W=K.backend==="rh",{data:N,error:ce}=W?await F.functions.invoke("labs-comfy-rh",{body:{action:"recover",taskId:J}}):await F.functions.invoke("admin-recover-wavespeed-prediction",{body:{predictionId:J,userId:P.user_id,generationId:P.id,model:P.model||K.model||null,actionKey:K.actionKey||null,aspectRatio:K.aspectRatio||null,prompt:P.prompt||null}});if(ce)throw ce;if(N!=null&&N.error)throw new Error(N.error);if(W&&(N==null?void 0:N.status)==="falhou"){const D=typeof N.creditsRefunded=="number"?N.creditsRefunded:0,i=N.jaResolvida?"O saldo já tinha sido resolvido antes.":D>0?`${D} crédito(s) devolvidos.`:"Não havia crédito reservado.";o.success(`Sem resultado no provedor (${N.motivo}). ${i}`)}else o.success(`Recuperado! Mídia em ${N.mediaUrl||N.imageUrl}`);B()}catch(W){o.error(W.message||"Falha ao recuperar")}finally{_(null)}},E=async()=>{if(!k.trim()||!l.trim()){o.error("taskId e userId são obrigatórios");return}Y(!0);try{let P,K;if(v==="kie-veo"){const J={fast:"veo-3.1-fast",lite:"veo-3.1-lite",quality:"veo-3.1"},W=`veo_3_1_${Z}_${z}`;({data:P,error:K}=await F.functions.invoke("admin-recover-kie-veo",{body:{taskId:k.trim(),userId:l.trim(),prompt:$.trim()||null,aspectRatio:C.trim()||null,quality:z,model:J[Z],actionKey:W}}))}else({data:P,error:K}=await F.functions.invoke("admin-recover-wavespeed-prediction",{body:{predictionId:k.trim(),userId:l.trim(),model:x}}));if(K)throw K;if(P!=null&&P.error)throw new Error(P.error);P!=null&&P.alreadyExists?o.info(`Já existia: ${P.generationId}`):o.success(`Geração criada! ID: ${P.generationId}`),g(""),h(""),V(""),ee(""),B()}catch(P){o.error(P.message||"Falha ao recuperar")}finally{Y(!1)}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"font-display font-semibold text-lg flex items-center gap-2",children:[e.jsx(Ar,{className:"w-5 h-5 text-primary"})," Recuperação de Predições"]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Gerações que falharam por timeout do provedor (5xx) mas onde o job pode ter completado no WaveSpeed. Clique em ",e.jsx("strong",{children:"Recuperar"})," para buscar o resultado, salvar no B2 e atualizar o registro."]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-card/50 p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"font-display font-semibold flex items-center gap-2",children:[e.jsx(qs,{className:"w-4 h-4 text-orange-400"}),"Pendentes",e.jsx(Re,{variant:"secondary",className:"text-xs",children:s.length})]}),e.jsxs(y,{size:"sm",variant:"outline",className:"gap-2",onClick:B,disabled:c,children:[c?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Qe,{className:"w-3.5 h-3.5"}),"Atualizar"]})]}),c?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(nr,{className:"w-6 h-6 mx-auto mb-2 opacity-50"}),"Nenhuma predição pendente de recuperação."]}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{className:"w-32",children:"Data"}),e.jsx(f,{children:"Usuário"}),e.jsx(f,{children:"Modelo"}),e.jsx(f,{children:"Prompt"}),e.jsx(f,{className:"font-mono text-[10px]",children:"Task ID"}),e.jsx(f,{children:"Código"}),e.jsx(f,{className:"text-right",children:"Ação"})]})}),e.jsx(De,{children:s.map(P=>{var J;const K=P.metadata||{};return e.jsxs(b,{children:[e.jsx(a,{className:"text-xs text-muted-foreground whitespace-nowrap",children:new Date(P.created_at).toLocaleStr
706ing("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}),e.jsx(a,{children:e.jsxs("div",{className:"text-xs",children:[e.jsx("p",{className:"font-medium",children:P.user_nickname?`@${P.user_nickname}`:"—"}),e.jsx("p",{className:"text-[10px] text-muted-foreground truncate max-w-[160px]",children:P.user_email||P.user_id.slice(0,8)})]})}),e.jsx(a,{className:"text-xs",children:P.model||K.model||"—"}),e.jsx(a,{className:"text-xs max-w-xs truncate",title:P.prompt||"",children:((J=P.prompt)==null?void 0:J.slice(0,60))||"—"}),e.jsxs(a,{className:"text-[10px] font-mono text-muted-foreground",children:[(K.taskId||"").slice(0,16),"…"]}),e.jsx(a,{children:e.jsx(Re,{variant:"outline",className:Ue("text-[10px]",K.errorCode==="PROVIDER_TIMEOUT"&&"border-orange-500/50 text-orange-400",K.errorCode==="TIMEOUT"&&"border-orange-500/50 text-orange-400"),children:K.errorCode||K.status||"?"})}),e.jsx(a,{className:"text-right",children:e.jsxs("div",{className:"flex items-center gap-1.5 justify-end",children:[e.jsxs(y,{size:"sm",onClick:()=>q(P),disabled:m===P.id,className:"gap-1.5 h-7 text-[11px]",children:[m===P.id?e.jsx(he,{className:"w-3 h-3 animate-spin"}):e.jsx(Ar,{className:"w-3 h-3"}),"Recuperar"]}),e.jsxs(y,{size:"sm",variant:"ghost",onClick:()=>G(P),disabled:m===P.id,className:"gap-1.5 h-7 text-[11px] text-muted-foreground hover:text-destructive",title:"Descartar: sai da fila e devolve o que estiver reservado",children:[e.jsx(_s,{className:"w-3 h-3"}),"Descartar"]})]})})]},P.id)})})]})})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-card/50 p-6 space-y-4",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-display font-semibold flex items-center gap-2",children:[e.jsx(aa,{className:"w-4 h-4 text-primary"}),"Recuperação Manual"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Use quando você sabe o taskId do provedor mas a geração não está na lista acima. Cria uma nova geração para o usuário com o resultado recuperado."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{className:"text-xs",children:"Provedor"}),e.jsxs("select",{value:v,onChange:P=>R(P.target.value),className:"h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-xs",children:[e.jsx("option",{value:"wavespeed",children:"WaveSpeed (imagens)"}),e.jsx("option",{value:"kie-veo",children:"Kie Veo 3.1 (vídeo)"})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{className:"text-xs",children:"User ID (UUID)"}),e.jsx(je,{value:l,onChange:P=>h(P.target.value),placeholder:"789f5c41-...",className:"h-9 text-xs font-mono"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{className:"text-xs",children:v==="kie-veo"?"Task ID (Kie)":"Prediction ID (WaveSpeed)"}),e.jsx(je,{value:k,onChange:P=>g(P.target.value),placeholder:v==="kie-veo"?"e075428ec1a4e4018f1b015e6f7d852a":"63767bdb264d45a9...",className:"h-9 text-xs font-mono"})]}),v==="wavespeed"?e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{className:"text-xs",children:"Modelo"}),e.jsx("select",{value:x,onChange:P=>w(P.target.value),className:"h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-xs",children:Wd.map(P=>e.jsx("option",{value:P,children:P},P))})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{className:"text-xs",children:"Tier"}),e.jsxs("select",{value:Z,onChange:P=>p(P.target.value),className:"h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-xs",children:[e.jsx("option",{value:"fast",children:"Fast"}),e.jsx("option",{value:"lite",children:"Lite"}),e.jsx("option",{value:"quality",children:"Quality"})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{className:"text-xs",children:"Resolução"}),e.jsxs("select",{value:z,onChange:P=>Q(P.target.value),className:"h-9 w-full rounded-md border border-input bg-background px-3 py-1 text-xs",children:[e.jsx("option",{value:"720p",children:"720p"}),e.jsx("option",{value:"1080p",children:"1080p"}),e.jsx("option",{value:"4k",children:"4k"})]})]})]})]}),v==="kie-veo"&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{className:"text-xs",children:"Aspect Ratio (opcional)"}),e.jsx(je,{value:C,onChange:P=>ee(P.target.value),placeholder:"9:16 ou 16:9",className:"h-9 text-xs"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{className:"text-xs",children:"Prompt (opcional)"}),e.jsx(je,{value:$,onChange:P=>V(P.target.value),placeholder:"Cinematic 5-second...",className:"h-9 text-xs"})]})]}),e.jsxs(y,{onClick:E,disabled:ae||!k||!l,className:"gap-2",children:[ae?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Ar,{className:"w-3.5 h-3.5"}),"Recuperar"]})]})]})},mn={width:"Largura inicial",height:"Altura inicial",seed:"Seed",steps:"Steps iniciais",cfg:"CFG inicial",sampler:"Sampler inicial",scheduler:"Scheduler inicial",upscaleEnabled:"Ativar upscale por difusão",upscaleFactor:"Fator de ampliação",upscaleSteps:"Steps do upscale",upscaleCfg:"CFG do upscale",upscaleSampler:"Sampler do upscale",upscaleScheduler:"Scheduler do upscale",upscaleDenoise:"Denoise do upscale",colorMatchEnabled:"Preservar cores da imagem inicial",faceEnabled:"Ativar detalhe facial",faceSteps:"Steps do detalhe facial",faceCfg:"CFG do detalhe facial",faceSampler:"Sampler do detalhe facial",faceScheduler:"Scheduler do detalhe facial",faceDenoise:"Denoise do detalhe facial",faceSize:"Tamanho do detalhe facial",skinEnabled:"Ativar contraste de pele",skinBlend:"Intensidade do contraste",seedvr2Enabled:"Ativar refinamento final",seedvr2Resolution:"Resolução SeedVR2",seedvr2Blend:"Mistura com upscale convencional"},Hd=[{id:"generation",title:"Imagem inicial",description:"Dimensões e amostragem da primeira imagem."},{id:"upscale",title:"Ampliação por difusão",description:"Amplia e refina a imagem em tiles.",toggle:"upscaleEnabled"},{id:"face",title:"Detalhe facial automático",description:"Detecta rostos e refina apenas essas regiões.",toggle:"faceEnabled"},{id:"skin",title:"Contraste de pele",description:"Mistura o tratamento de contraste com a imagem anterior.",toggle:"skinEnabled"},{id:"seedvr2",title:"Refinamento final · SeedVR2",description:"Processa a imagem e mistura com o upscale convencional.",toggle:"seedvr2Enabled"}],un="min-h-11 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";function Yd({value:s,onChange:n,refinementsOnly:c=!1}){const{t:u}=kt(),m=r.useId();return e.jsx("div",{className:"space-y-4",children:Hd.filter(_=>!c||_.id!=="generation").map(_=>e.jsxs("fieldset",{className:"rounded-xl border border-border bg-card p-4",children:[e.jsx("legend",{className:"px-2 text-sm font-semibold",children:u(`krea2Cloud.moody.stages.${_.id}.title`,_.title)}),e.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:u(`krea2Cloud.moody.stages.${_.id}.description`,_.description)}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 xl:grid-cols-3",children:Object.entries(No).filter(([,k])=>k.stage===_.id).map(([k,g])=>{const l=k,h=_.toggle&&l!==_.toggle&&!s[_.toggle],x=`${m}-${l}`;return e.jsx("div",{className:h?"opacity-50":"",children:typeof g.default=="boolean"?e.jsxs("label",{htmlFor:x,className:"flex min-h-11 cursor-pointer items-center gap-3 text-sm",children:[e.jsx("input",{id:x,type:"checkbox",className:"h-4 w-4 accent-primary",disabled:!!h,checked:s[l],onChange:w=>n({...s,[l]:w.target.checked})}),u(`krea2Cloud.moody.inputs.${l}`,mn[l])]}):e.jsxs(e.Fragment,{children:[e.jsx("label",{htmlFor:x,className:"mb-1.5 block text-sm font-medium",children:u(`krea2Cloud.moody.inputs.${l}`,mn[l])}),"options"in g?e.jsx("select",{id:x,className:un,disabled:!!h,value:s[l],onChange:w=>n({...s,[l]:w.target.value}),children:g.options.map(w=>e.jsx("option",{value:w,children:w}
706,w))}):e.jsx("input",{id:x,className:un,type:"number",disabled:!!h,min:g.min,max:g.max,step:g.step,value:Number.isNaN(s[l])?"":s[l],onChange:w=>n({...s,[l]:w.target.value===""?NaN:Number(w.target.value)})})]})},l)})})]},_.id))})}function Jd(){const s=r.useId(),[n,c]=r.useState("krea2t2i"),[u,m]=r.useState(""),[_,k]=r.useState(!0),[g,l]=r.useState(""),[h,x]=r.useState(0),[w,v]=r.useState(yo),[R,$]=r.useState(!1);r.useEffect(()=>{let C=!1;return k(!0),l(""),F.functions.invoke("labs-comfy-rh",{body:{action:"workflow-active",family:"krea2"}}).then(({data:ee,error:Z})=>{if(C)return;if(Z||!(ee!=null&&ee.graph))throw new Error("Não foi possível carregar o workflow ativo.");const p=Gr("krea2",ee).graph;m(p),c(p),v(Gr("krea2",ee).moodySettings),$(!1)}).catch(ee=>{C||l(ee.message)}).finally(()=>{C||k(!1)}),()=>{C=!0}},[h]);const V=async()=>{k(!0),l("");try{const{data:C,error:ee}=await F.functions.invoke("labs-comfy-rh",{body:{action:"workflow-activate",family:"krea2",graph:n,moodySettings:_o(w)}});if(ee||!(C!=null&&C.graph)){let Z=(C==null?void 0:C.error)||"Não foi possível ativar o workflow.";if((ee==null?void 0:ee.context)instanceof Response){const p=await ee.context.json().catch(()=>null);Z=(p==null?void 0:p.error)||Z}throw new Error(Z)}m(Gr("krea2",C).graph),$(!1)}catch(C){l(C instanceof Error?C.message:"Falha ao salvar.")}finally{k(!1)}};return e.jsxs("section",{className:"max-w-2xl space-y-5","aria-label":"Workflow ativo",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Workflow ativo · Krea2"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Escolha o workflow e configure seus refinamentos. No Labs, o usuário escolhe prompt, modelo, LoRAs e proporção da imagem."})]}),e.jsx("label",{htmlFor:s,className:"block text-sm font-medium",children:"Workflow do Krea2"}),e.jsxs("select",{id:s,value:n,disabled:_||!u,onChange:C=>c(C.target.value),className:"min-h-11 w-full rounded-md border border-input bg-background px-3",children:[e.jsx("option",{value:"krea2t2i",children:"Krea2 · padrão (Turbo / RAW)"}),e.jsx("option",{value:"krea2moody",children:"Krea2 · Moody 4KHD v2 · 15 LoRAs · imagem direta"})]}),u&&e.jsxs("p",{role:"status",className:"text-sm",children:["Ativo: ",u==="krea2moody"?"Moody 4KHD v2":"Krea2 padrão"]}),n==="krea2moody"&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"A estimativa usa cobranças concluídas do mesmo checkpoint e configuração, com margem de reserva. Ajustes ainda sem amostras usam uma estimativa inicial baseada nas medições. O custo real é acertado ao concluir."}),n==="krea2moody"&&e.jsxs("fieldset",{disabled:_,className:"space-y-4",children:[e.jsx("legend",{className:"mb-3 font-medium",children:"Refinamentos do workflow"}),e.jsx(Yd,{refinementsOnly:!0,value:w,onChange:C=>{v(C),$(!0)}})]}),g&&e.jsx("p",{role:"alert",className:"text-sm text-destructive",children:g}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(y,{disabled:_||!u||n===u&&!R,onClick:V,children:_?"Aguarde…":n===u?"Salvar ajustes":"Ativar workflow"}),e.jsx(y,{variant:"outline",disabled:_,onClick:()=>x(C=>C+1),children:"Recarregar"})]})]})}function Xd(){const[s,n]=r.useState([]),[c,u]=r.useState(100),[m,_]=r.useState(!1),[k,g]=r.useState(null),[l,h]=r.useState({id:"",label:"",email:"",apiKey:"",notas:""}),[x,w]=r.useState(!1),[v,R]=r.useState(null),[$,V]=r.useState(null),[C,ee]=r.useState({}),Z=[{key:"krea2t2i",label:"Krea 2 T2I"},{key:"upscale4k",label:"Upscaler 4K"},{key:"lipsync",label:"Lip Sync"}],p=async E=>{V(E.id),ee(P=>({...P,[E.id]:Z.map(K=>({...K,ok:!1,msg:"na fila…"}))}));for(const P of Z){ee(K=>({...K,[E.id]:(K[E.id]||[]).map(J=>J.key===P.key?{...J,msg:"gerando…"}:J)}));try{const K=await Q({action:"accounts-test",id:E.id,target:P.key}),J=((K==null?void 0:K.resultados)||[])[0]||{};ee(W=>({...W,[E.id]:(W[E.id]||[]).map(N=>N.key===P.key?{...N,ok:!!J.ok,aquecendo:!!J.aquecendo,taskId:J.taskId,msg:J.aquecendo?`aceita e aquecendo (${J.incerto?"fila do provedor":J.code===813?"na fila":"rodando"})`:J.ok?`${J.segundos}s · $${Number(J.custoUsd??0).toFixed(4)}`:`${J.etapa?J.etapa+": ":""}${J.erro||"falhou"}`}:N)}))}catch(K){ee(J=>({...J,[E.id]:(J[E.id]||[]).map(W=>W.key===P.key?{...W,ok:!1,msg:K.message||"erro"}:W)}))}}V(null),ae(!0),o.success(`${E.label}: teste dos fluxos concluído`)},z=async(E,P)=>{if(P.taskId)try{const K=await Q({action:"accounts-test-check",id:E,taskId:P.taskId}),J=K!=null&&K.concluido?`${K.execSeg}s · $${Number(K.custoUsd??0).toFixed(4)}`:K!=null&&K.aquecendo?`ainda ${K.msg}`:(K==null?void 0:K.erro)||"falhou";ee(W=>({...W,[E]:(W[E]||[]).map(N=>N.key===P.key?{...N,ok:!!(K!=null&&K.ok),aquecendo:!!(K!=null&&K.aquecendo),msg:J}:N)}))}catch(K){o.error(K.message||"Erro")}},Q=r.useCallback(async E=>{var J;const{data:P,error:K}
706=await F.functions.invoke("labs-comfy-rh",{body:E});if(K){const W=K==null?void 0:K.context,N=W?await((J=W.json)==null?void 0:J.call(W).catch(()=>null)):null;throw new Error((N==null?void 0:N.error)||K.message)}if(P!=null&&P.error)throw new Error(P.error);return P},[]),ae=r.useCallback(async(E=!1)=>{E||_(!0);try{const P=await Q({action:"accounts-list"});n((P==null?void 0:P.contas)||[]),P!=null&&P.teto&&u(P.teto)}catch(P){o.error(P.message||"Erro ao ler contas")}finally{E||_(!1)}},[Q]);r.useEffect(()=>{ae()},[ae]);const Y=()=>{h({id:"",label:"",email:"",apiKey:"",notas:""}),g("__nova__")},B=E=>{h({id:E.id,label:E.label,email:E.email||"",apiKey:"",notas:E.notas||""}),g(E.id)},G=async()=>{if(!(!l.id.trim()||!l.label.trim())){w(!0);try{await Q({action:"accounts-upsert",id:l.id.trim(),label:l.label.trim(),email:l.email.trim(),notas:l.notas.trim(),...l.apiKey.trim()?{apiKey:l.apiKey.trim()}:{}}),o.success(l.apiKey.trim()?"Conta salva e chave guardada no cofre.":"Conta salva."),g(null),h(E=>({...E,apiKey:""})),ae(!0)}catch(E){o.error(E.message||"Erro")}finally{w(!1)}}},q=async()=>{const E=v;if(R(null),!!E)try{await Q({action:E.tipo==="chave"?"accounts-clear-key":"accounts-delete",id:E.conta.id}),o.success(E.tipo==="chave"?"Chave apagada do cofre.":"Conta removida."),ae(!0)}catch(P){o.error(P.message||"Erro")}};return e.jsxs("div",{className:"rounded-lg border border-border/40 bg-card/40 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-sm",children:"Contas do provedor"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Teto de ",e.jsx("strong",{children:c})," gerações simultâneas por conta. A chave fica cifrada no cofre — nem eu nem você conseguimos lê-la de volta, só substituir ou apagar."]})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>ae(),disabled:m,className:"gap-1.5",children:[m?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Qe,{className:"w-3.5 h-3.5"}),"Atualizar"]}),e.jsxs(y,{size:"sm",onClick:Y,className:"gap-1.5",children:[e.jsx(Us,{className:"w-3.5 h-3.5"})," Nova conta"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[s.map(E=>{var P;return e.jsxs("div",{className:Ue("rounded-md border p-3 space-y-2",E.ativo?"border-border/40 bg-background/40":"border-border/20 bg-background/20 opacity-60"),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium text-sm",children:E.label}),e.jsx("span",{className:"px-1.5 py-px rounded bg-muted/50 border border-border/40 text-[10px] font-mono",children:E.id}),E.email&&e.jsx("span",{className:"text-[11px] text-muted-foreground",children:E.email}),!E.ativo&&e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"desligada"}),e.jsx("span",{className:"flex-1"}),E.temChave?e.jsxs("span",{className:"flex items-center gap-1 text-[11px] text-emerald-400/90",children:[e.jsx(Ea,{className:"w-3 h-3"}),"chave ",E.origem==="secret"?"no secret":"no cofre"]}):e.jsxs("span",{className:"flex items-center gap-1 text-[11px] text-amber-400/90",children:[e.jsx(qs,{className:"w-3 h-3"})," sem chave"]})]}),E.saldo&&e.jsxs("div",{className:"flex gap-4 text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:["Wallet ",e.jsxs("strong",{className:Ue(E.saldo.usd<3&&"text-amber-400"),children:["$",E.saldo.usd.toFixed(3)]})]}),e.jsxs("span",{children:["Rodando ",e.jsx("strong",{children:E.saldo.rodando}),"/",c]}),e.jsxs("span",{children:["Coins ",E.saldo.coins]}),E.saldo.tipo&&e.jsx("span",{className:"text-muted-foreground/60",children:E.saldo.tipo})]}),E.erro&&e.jsxs("p",{className:"text-[11px] text-amber-400",children:["⚠️ ",E.erro]}),E.notas&&e.jsx("p",{className:"text-[11px] text-muted-foreground/70",children:E.notas}),((P=C[E.id])==null?void 0:P.length)>0&&e.jsx("div",{className:"space-y-0.5",children:C[E.id].map(K=>e.jsxs("p",{className:Ue("text-[11px] flex items-center gap-1.5",K.ok?K.aquecendo?"text-sky-400/90":"text-emerald-400/90":K.msg.endsWith("…")?"text-muted-foreground":"text-amber-400"),children:[e.jsxs("span",{children:[K.ok?K.aquecendo?"◐":"✓":K.msg.endsWith("…")?"·":"⚠️"," ",K.label,": ",K.msg]}),K.aquecendo&&K.taskId&&e.jsx("button",{type:"button",onClick:()=>z(E.id,K),className:"underline decoration-dotted hover:text-foreground shrink-0",children:"conferir"})]},K.key))}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(y,{variant:"outline",size:"sm",className:"h-7 text-[11px]",onClick:()=>B(E),children:E.temChave?"Substituir chave":"Definir chave"}),e.jsxs(y,{variant:"outline",size:"sm",className:"h-7 text-[11px]",disabled:!E.temChave||!!$,onClick:()=>p(E),children:[$===E.id?e.jsx(he,{className:"w-3 h-3 mr-1 animate-spin"}):e.jsx(Ra,{className:"w-3 h-3 mr-1"}),"Testar e aquecer fluxos"]}),e.jsxs(y,{variant:"outline",size:"sm",className:"h-7 text-[11px]",onClick:()=>Q({action:"accounts-toggle",id:E.id,ativo:!E.ativo}).then(()=>ae(!0)).catch(K=>o.error(K.message)),children:[E.ativo?e.jsx(si,{className:"w-3 h-3 mr-1"}):e.jsx(ai,{className:"w-3 h-3 mr-1"}),E.ativo?"Desligar":"Ligar"]}),E.origem==="cofre"&&e.jsx(y,{variant:"outline",size:"sm",className:"h-7 text-[11px] text-amber-400",onClick:()=>R({tipo:"chave",conta:E}),children:"Apagar chave"}),E.id!=="main"&&e.jsxs(y,{variant:"outline",size:"sm",className:"h-7 text-[11px] text-destructive",onClick:()=>R({tipo:"conta",conta:E}),children:[e.jsx(_s,{className:"w-3 h-3 mr-1"})," Remover"]})]})]},E.id)}),!s.length&&!m&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Nenhuma conta cadastrada."})]}),e.jsx(ds,{open:!!k,onOpenChange:E=>{E||g(null)},children:e.jsxs(cs,{children:[e.jsx(ms,{children:e.jsx(us,{children:k==="__nova__"?"Nova conta":`Conta ${l.id}`})}),e.jsxs("div",{className:"space-y-3",children:[k==="__nova__"&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Identificador"}),e.jsx("input",{value:l.id,onChange:E=>h({...l,id:E.target.value}),placeholder:"b",className:"w-full h-9 px-3 rounded-md bg-background border border-border/40 text-sm font-mono outline-none focus:border-primary/60"}
706),e.jsx("p",{className:"text-[10px] text-muted-foreground/60",children:"Minúsculas, números, - ou _. Fica gravado em cada geração e NÃO muda depois."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Nome"}),e.jsx("input",{value:l.label,onChange:E=>h({...l,label:E.target.value}),placeholder:"Conta secundária",className:"w-full h-9 px-3 rounded-md bg-background border border-border/40 text-sm outline-none focus:border-primary/60"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"E-mail da conta no provedor"}),e.jsx("input",{value:l.email,onChange:E=>h({...l,email:E.target.value}),placeholder:"[email protected]",className:"w-full h-9 px-3 rounded-md bg-background border border-border/40 text-sm outline-none focus:border-primary/60"}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60",children:"Só pra você saber qual conta é. Não é secreto."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Chave da API"}),e.jsx("input",{type:"password",value:l.apiKey,onChange:E=>h({...l,apiKey:E.target.value}),placeholder:k==="__nova__"?"cole a chave":"cole a nova chave (vazio = mantém a atual)",className:"w-full h-9 px-3 rounded-md bg-background border border-border/40 text-sm font-mono outline-none focus:border-primary/60"}),e.jsx("p",{className:"text-[10px] text-amber-400/80",children:"Vai direto pro cofre cifrado. Depois de salvar, não tem como ver de novo — só substituir."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Notas"}),e.jsx("input",{value:l.notas,onChange:E=>h({...l,notas:E.target.value}),className:"w-full h-9 px-3 rounded-md bg-background border border-border/40 text-sm outline-none focus:border-primary/60"})]})]}),e.jsxs(Bs,{children:[e.jsx(y,{variant:"outline",onClick:()=>g(null),children:"Cancelar"}),e.jsxs(y,{onClick:G,disabled:x||!l.id.trim()||!l.label.trim(),children:[x&&e.jsx(he,{className:"w-3.5 h-3.5 animate-spin mr-1.5"}),"Salvar"]})]})]})}),e.jsx(va,{open:!!v,onOpenChange:E=>{E||R(null)},children:e.jsxs(ba,{children:[e.jsxs(Na,{children:[e.jsx(ya,{children:(v==null?void 0:v.tipo)==="chave"?"Apagar a chave desta conta?":"Remover a conta?"}),e.jsx(_a,{children:(v==null?void 0:v.tipo)==="chave"?`A chave de "${v==null?void 0:v.conta.label}" some do cofre e não tem como recuperar — vai precisar pegar outra no provedor. Gerações em andamento nessa conta vão falhar no poll.`:`"${v==null?void 0:v.conta.label}" sai da lista e a chave é apagada do cofre. Gerações antigas que rodaram nela não vão mais conseguir ser reconciliadas.`})]}),e.jsxs(wa,{children:[e.jsx(ka,{children:"Cancelar"}),e.jsx(Ca,{onClick:q,children:"Confirmar"})]})]})})]})}async function Cs(s,n){const{data:{session:c}}=await F.auth.getSession();if(!c)throw new Error("Sessão expirada");const u=await fetch("https://tyfwdwvbndsylqtvfzdh.supabase.co/functions/v1/admin-comfyui-pod",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${c.access_token}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InR5Zndkd3ZibmRzeWxxdHZmemRoIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzIzNDAzNjQsImV4cCI6MjA4NzkxNjM2NH0.KGd8GMawqyMQEQouhRdeOBk079fChRxszRniEupHcr4"},body:JSON.stringify({action:s,...n||{}})}),m=await u.json();if(!u.ok)throw new Error(m.error||`HTTP ${u.status}`);return m}const Qd=[{id:"krea2t2i",label:"Krea 2 T2I Simple",file:"Krea-2/t2i-simple.json"},{id:"krea2pornmaster",label:"Krea 2 T2I PornMaster",file:"Krea-2/t2i-pornmaster.json"},{id:"krea2fineporn",label:"Krea 2 T2I FinePorn v3.1",file:"Krea-2/t2i-fineporn.json"}],Zd=s=>
706s?s.replace("NVIDIA GeForce ","").replace("NVIDIA ",""):"—",xn=s=>s==null?"—":`${(s/1e3).toFixed(1)}s`,Tr=s=>s>=1e9?`${(s/1e9).toFixed(2)} GB`:s>=1e6?`${(s/1e6).toFixed(1)} MB`:`${(s/1e3).toFixed(0)} KB`;function ec(){var bs,Rs,gs,hs,As,Gs,Hs,Ls,L,d,le;const[s,n]=r.useState(null),[c,u]=r.useState(!0),[m,_]=r.useState(null),[k,g]=r.useState(()=>localStorage.getItem("comfyui_editor_gpu")||"auto");r.useEffect(()=>{try{localStorage.setItem("comfyui_editor_gpu",k)}catch{}},[k]);const l="byok",[h,x]=r.useState(null),[w,v]=r.useState(!1),[R,$]=r.useState({}),[V,C]=r.useState(null),[ee,Z]=r.useState(!1),[p,z]=r.useState("runninghub"),[Q,ae]=r.useState(null),[Y,B]=r.useState(!1),[G,q]=r.useState(null),[E,P]=r.useState(null),[K,J]=r.useState(!1),[W,N]=r.useState(""),[ce,D]=r.useState(!1),[i,A]=r.useState("3"),[O,te]=r.useState(!1),[T,re]=r.useState(null),[ke,fe]=r.useState(Qd),[X,me]=r.useState(null),[_e,$e]=r.useState(null),[Ve,Je]=r.useState(null),[we,We]=r.useState(null),Ge=r.useRef(null),ps=r.useCallback(async()=>{v(!0);try{x(await Cs("storage"))}catch(S){o.error(S.message||"Erro ao listar o storage")}finally{v(!1)}},[]),be=r.useCallback(async(S,de)=>{var Ce;me(S);try{const Oe=await Cs("get-workflow",{workflowId:S});if(!(Oe!=null&&Oe.graph))throw new Error((Oe==null?void 0:Oe.error)||"Sem graph");const Ke=new Blob([JSON.stringify(Oe.graph,null,2)],{type:"application/json"}),qe=URL.createObjectURL(Ke),Me=document.createElement("a");Me.href=qe,Me.download=`${Oe.label||((Ce=de.split("/").pop())==null?void 0:Ce.replace(/\.json$/,""))||S}.json`,document.body.appendChild(Me),Me.click(),Me.remove(),URL.revokeObjectURL(qe)}catch(Oe){o.error(Oe.message||"Falha ao baixar workflow")}finally{me(null)}},[]),ue=r.useCallback(async(S=!1)=>{S||u(!0);try{const de=await Cs("status",{target:l});n(de)}catch(de){S||o.error(de.message||"Erro ao carregar status")}finally{S||u(!1)}},[l]);r.useEffect(()=>(ue(),ps(),Cs("list-workflows").then(S=>{var de;(de=S==null?void 0:S.workflows)!=null&&de.length&&fe(S.workflows)}).catch(()=>{}),Cs("endpoint-config").then(ae).catch(()=>{}),Cs("get-pin").then(P).catch(()=>{}),Cs("spend-history").then(S=>We(S.snapshots||[])).catch(()=>{}),Cs("list-workers").then(S=>q(S.workers||[])).catch(()=>{}),F.from("admin_settings").select("value").eq("key","comfyui_editor_max_hours").maybeSingle().then(({data:S})=>{S!=null&&S.value&&A(S.value)}),Ge.current=setInterval(()=>ue(!0),15e3),()=>{Ge.current&&clearInterval(Ge.current)}),[ue,ps]);const Pe=async()=>{if(Q){B(!0);try{const S=await Cs("update-endpoint",Q);S.ok?o.success("Config do endpoint atualizada"):o.error(S.error||"Falha ao salvar")}catch(S){o.error(S.message)}finally{B(!1)}}},ze=async()=>{te(!0);const{error:S}=await F.from("admin_settings").upsert({key:"comfyui_editor_max_hours",value:i},{onConflict:"key"});te(!1),S?o.error("Falha ao salvar limite"):o.success(`Watchdog: editor desliga sozinho após ${i}h`)},Ie=async()=>{try{const S=await Cs("purge-queue");S.ok?(o.success("Fila limpa"),ue(!0)):o.error(S.error||"Falha")}catch(S){o.error(S.message)}},xs=async S=>{try{const de=await Cs("kill-worker",{podId:S});de.ok?(o.success(`Worker ${S.slice(0,8)}… reciclado`),Cs("list-workers").then(Ce=>q(Ce.workers||[])).catch(()=>{})):o.error(de.error||"Falha")}catch(de){o.error(de.message)}},Ps=async()=>{const S=parseInt(W,10);if(S){D(!0);try{const de=await Cs("expand-volume",{sizeGb:S});de.ok?(o.success(`Volume expandido pra ${de.to}GB ($${de.monthlyUsd}/mês)`),N(""),ps()):o.error(de.error||"Falha ao expandir")}catch(de){o.error(de.message)}finally{D(!1)}}},Ze=()=>Cs("get-pin").then(P).catch(()=>{}),es=async S=>{J(!0);try{const de=await Cs("set-pin",{version:S});de.ok?(o.success(`Build da ${S} disparado`,{description:de.note}),setTimeout(Ze,4e3)):o.error(de.error||"Falha ao disparar build")}catch(de){o.error(de.message)}finally{J(!1)}},ws=async S=>{J(!0);try{const de=await Cs("apply-image",{version:S});de.ok?(o.success(`Endpoint agora na ${S}`,{description:de.note}),Ze()):o.error(de.error||"Falha ao aplicar")}catch(de){o.error(de.message)}finally{J(!1)}},is=async()=>{_("start");try{const S=await Cs("start",{gpu:k,target:l});S.ok?(o.success(S.alreadyRunning?"Editor já estava ligado":S.note||"Editor ligando — pronto em ~3-5 min"),ue(!0)):o.error(S.error||"Falha ao ligar")}catch(S){o.error(S.message||"Falha ao ligar")}finally{_(null)}},os=async()=>{_("stop");try{const S=await Cs("stop",{target:l});S.ok?(o.success("Editor desligado — workflows salvos ficam no volume"),ue(!0)):o.error(S.error||"Falha ao desligar")}catch(S){o.error(S.message||"Falha ao desligar")}finally{_(null)}},H=async()=>
706{if(V){Z(!0);try{const S=await Cs("delete",{key:V.deleteKey,isPrefix:V.isPrefix,confirm:!0});S.ok?(o.success(`Deletado: ${V.name.split("/").pop()||V.name}`),C(null),ps()):o.error(S.error||"Falha ao deletar")}catch(S){o.error(S.message||"Falha ao deletar")}finally{Z(!1)}}},xe=(s==null?void 0:s.editor)??null,Ne=(s==null?void 0:s.serverless.health)??null,Xe=xe!=null&&xe.lastStartedAt?Math.max(0,Math.round((Date.now()-new Date(xe.lastStartedAt).getTime())/6e4)):null;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-xl font-bold flex items-center gap-2",children:[e.jsx(wo,{className:"w-5 h-5 text-primary"})," ComfyUI"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:"Execução de workflows do Labs — RunningHub (gerenciado) e RunPod (BYOK + testes internos)."})]}),p==="runpod"&&e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>ue(),disabled:c,className:"gap-1.5",children:[c?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Qe,{className:"w-3.5 h-3.5"}),"Atualizar"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>z("runninghub"),className:Ue("h-8 px-3.5 rounded-full text-[12px] font-medium transition-all",p==="runninghub"?"bg-primary text-primary-foreground":"bg-white/[0.04] text-white/60 border border-white/[0.08] hover:text-white"),children:"RunningHub"}),e.jsxs("button",{onClick:()=>z("runpod"),className:Ue("h-8 px-3.5 rounded-full text-[12px] font-medium transition-all",p==="runpod"?"bg-primary text-primary-foreground":"bg-white/[0.04] text-white/60 border border-white/[0.08] hover:text-white"),children:["RunPod ",e.jsx("span",{className:"opacity-60",children:"(BYOK + testes)"})]})]}),p==="runninghub"&&e.jsx(sc,{}),p==="runpod"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-xl border border-border/50 bg-card/40 p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"space-y-1.5 min-w-0",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(Ra,{className:"w-4 h-4 text-primary"})," Editor ComfyUI (pod interativo)"]}),e.jsx("span",{className:"inline-flex w-fit items-center h-6 px-2 rounded-full text-[10px] bg-primary/15 border border-primary/50 text-primary font-medium",children:"Minha conta (BYOK)"}),(s==null?void 0:s.byokError)&&e.jsxs("p",{className:"text-[11px] text-amber-400 flex items-center gap-1.5",children:[e.jsx(qs,{className:"w-3 h-3"})," ",s.byokError]}),!(s!=null&&s.byokError)&&e.jsx("p",{className:"text-[10px] text-muted-foreground/70",children:"Roda e cobra na SUA conta RunPod (mesmo volume do Importar). Watchdog NÃO desliga sozinho — desligue ao terminar."}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(vt,{className:Ue("w-3 h-3",xe?xe.ready?"text-emerald-400":"text-amber-400":"text-muted-foreground")}),xe?xe.ready?e.jsx("span",{className:"text-emerald-400 font-medium",children:"Rodando e pronto"}):e.jsx("span",{className:"text-amber-400 font-medium",children:"Ligando (ComfyUI ainda subindo...)"}):e.jsx("span",{className:"text-muted-foreground",children:"Desligado"})]}),xe&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["GPU ",Zd(xe.gpu)," · ",xe.costPerHr!=null?`$${xe.costPerHr}/h`:"",Xe!=null?` · ligado há ${Xe} min`:"",xe.costPerHr!=null&&Xe!=null?` · ~$${(xe.costPerHr/60*Xe).toFixed(2)} nesta sessão`:""]}),e.jsx("p",{className:"text-[11px] text-muted-foreground/70",children:"Workflows salvos (Ctrl+S) persistem no volume entre sessões. Modelos e custom nodes já montados."}),e.jsxs("div",{className:"flex items-center gap-2 pt-1 flex-wrap",children:[ke.map(S=>{var Oe,Ke;const de=(((Ke=(Oe=h==null?void 0:h.groups)==null?void 0:Oe["Workflows salvos (editor)"])==null?void 0:Ke.files)||[]).some(qe=>qe.name.endsWith(S.file)),Ce=_e===S.id;return e.jsxs("div",{className:"inline-flex items-center rounded-md border border-border/40 overflow-hidden",children:[e.jsxs(y,{size:"sm",variant:"ghost",disabled:T!==null,onClick:async()=>{re(S.id);try{const qe=await Cs("push-workflow",{workflowId:S.id,target:l});qe.ok?($e(S.id),setTimeout(()=>$e(Me=>Me===S.id?null:Me),12e3),setTimeout(()=>{ps()},8e4),o.success(qe.byokInstaller?`Instalador rodando na sua conta (~1 min). Quando o ComfyUI terminar de subir, abra/recarregue (F5) e procure "${qe.file}" no menu Workflows.`:`Workflow "${qe.label}" enviado — abra/recarregue (F5) o ComfyUI e procure "${qe.file}" no menu Workflows.`)):o.error(qe.error||"Falha ao enviar workflow")}catch(qe){o.error(qe.message||"Falha ao enviar workflow")}finally{re(null)}},title:de?"Já está no volume do RunPod — clique pra reenviar (atualizar após editar o graph)":void 0,className:"h-7 px-2 text-[11px] gap-1 rounded-none",children:[T===S.id?e.jsx(he,{className:"w-3 h-3 animate-spin"}):Ce||de?e.jsx(Ea,{className:"w-3 h-3 text-emerald-400"}):e.jsx(or,{className:"w-3 h-3"}),Ce?e.jsx("span",{className:"text-emerald-400",children:"Enviado ✓"}):de?e.jsxs(e.Fragment,{children:['Reenviar "',S.label,'"']}):e.jsxs(e.Fragment,{children:['Enviar "',S.label,'"']})]}),de&&!Ce&&e.jsx("span",{className:"px-1.5 text-[9px] text-emerald-400/90 uppercase tracking-wider border-l border-border/40 self-stretch flex items-center",children:"no volume"}),e.jsx("div",{className:"w-px h-4 bg-border/40"}),e.jsxs(y,{size:"sm",variant:"ghost",disabled:X!==null,onClick:()=>be(S.id,S.file),title:"Baixar o JSON do workflow pra rodar localmente (sem subir pod)",className:"h-7 px-2 text-[11px] gap-1 rounded-none",children:[X===S.id?e.jsx(he,{className:"w-3 h-3 animate-spin"}):e.jsx(na,{className:"w-3 h-3"}),"JSON"]})]},S.id)}
706),e.jsx("span",{className:"text-[10px] text-muted-foreground/70",children:"Enviar = grava no menu Workflows do ComfyUI · JSON = baixa pra rodar local · ✓ no volume = já está no RunPod"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Watchdog: desligar sozinho após"}),e.jsx("input",{type:"number",min:1,max:24,value:i,onChange:S=>A(S.target.value),className:"w-14 h-7 px-2 rounded-md bg-background border border-border/40 text-xs text-center outline-none focus:border-primary/60"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"horas"}),e.jsx(y,{size:"sm",variant:"outline",onClick:ze,disabled:O,className:"h-7 px-2 text-[11px]",children:O?e.jsx(he,{className:"w-3 h-3 animate-spin"}):"Salvar"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[(xe==null?void 0:xe.ready)&&xe.url&&e.jsx(y,{asChild:!0,variant:"outline",className:"gap-1.5",children:e.jsxs("a",{href:xe.url,target:"_blank",rel:"noreferrer",children:[e.jsx(oa,{className:"w-4 h-4"})," Abrir ComfyUI"]})}),xe?e.jsxs(y,{onClick:os,disabled:m!==null,variant:"destructive",className:"gap-1.5",children:[m==="stop"?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(si,{className:"w-4 h-4"}),"Desligar"]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("select",{value:k,onChange:S=>g(S.target.value),className:"h-9 px-2 rounded-md bg-background border border-border/40 text-xs outline-none focus:border-primary/60 cursor-pointer",title:"GPU do editor",children:[e.jsx("option",{value:"auto",children:"GPU: Auto (melhor disponível)"}),e.jsx("option",{value:"5090",children:"RTX 5090 · 32GB · $0.99/h"}),e.jsx("option",{value:"4090",children:"RTX 4090 · 24GB · $0.69/h"}),e.jsx("option",{value:"3090",children:"RTX 3090 · 24GB · $0.46/h"}),e.jsx("option",{value:"a5000",children:"RTX A5000 · 24GB · ~$0.26/h"}),e.jsx("option",{value:"a4000",children:"RTX A4000 · 16GB · ~$0.17/h (só ver fluxo)"})]}),e.jsxs(y,{onClick:is,disabled:m!==null,className:"gap-1.5",children:[m==="start"?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(ai,{className:"w-4 h-4"}),"Ligar editor"]})]})]})]}),xe&&!xe.ready&&e.jsxs("p",{className:"mt-3 text-[11px] text-amber-400/80 flex items-center gap-1.5",children:[e.jsx(qs,{className:"w-3 h-3"})," Cobra ~$",xe.costPerHr??"0.3-0.7","/h enquanto ligado — desligue quando terminar de editar."]})]}),e.jsxs("div",{className:"rounded-xl border border-border/50 bg-card/40 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx($a,{className:"w-4 h-4 text-primary"})," Endpoint Serverless (gerações dos workflows)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(y,{size:"sm",variant:"outline",className:"h-7 px-2 text-[11px]",onClick:async()=>{try{const S=await Cs("bootlog");Je(S.log||"(vazio)")}catch(S){o.error(S.message)}},children:"Boot log"}),e.jsx(y,{size:"sm",variant:"outline",className:"h-7 px-2 text-[11px] text-destructive hover:text-destructive",onClick:Ie,children:"Limpar fila"})]})]}),Q&&e.jsxs("div",{className:"flex items-end gap-3 flex-wrap rounded-lg border border-border/40 bg-background/50 px-3 py-2.5",children:[e.jsx(ht,{label:"Workers mín (quente 24/7)",value:Q.workersMin,min:0,max:2,onChange:S=>ae({...Q,workersMin:S})}),e.jsx(ht,{label:"Workers máx",value:Q.workersMax,min:1,max:5,onChange:S=>ae({...Q,workersMax:S})}),e.jsx(ht,{label:"Idle timeout (s)",value:Q.idleTimeout,min:2,max:300,onChange:S=>ae({...Q,idleTimeout:S})}),e.jsxs(y,{size:"sm",onClick:Pe,disabled:Y,className:"h-8 gap-1.5",children:[Y?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):null," Aplicar"]}),Q.workersMin>0&&e.jsx("p",{className:"w-full text-[10px] text-amber-400/90",children:"⚠ Workers mín > 0 = GPU quente cobrando 24/7 (~$0.7-1.1/h cada). Use só em horário de pico."})]}),G&&G.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-semibold",children:"Workers"}),G.map(S=>e.jsxs("div",{className:"flex items-center gap-2 text-xs py-1 px-2 rounded bg-background/60 border border-border/30",children:[e.jsx("span",{className:"font-mono text-muted-foreground flex-1",children:S.id}),e.jsx("span",{className:Ue("px-1.5 py-0.5 rounded text-[10px] font-semibold",S.desiredStatus==="RUNNING"?"bg-emerald-500/15 text-emerald-400":"bg-muted text-muted-foreground"),children:S.desiredStatus}),e.jsx("button",{onClick:()=>xs(S.id),title:"Reciclar (mata o worker;
706 um novo sobe limpo)",className:"text-muted-foreground/50 hover:text-destructive transition-colors",children:e.jsx(Qe,{className:"w-3.5 h-3.5"})})]},S.id)),e.jsx("p",{className:"text-[10px] text-muted-foreground/60",children:"Reciclar = matar o worker (útil quando um worker fica zumbi com versão/estado velho). Novo worker sobe limpo na próxima geração."})]}),Ne?e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsx(zs,{label:"Workers ativos",value:`${(((bs=Ne.workers)==null?void 0:bs.running)??0)+(((Rs=Ne.workers)==null?void 0:Rs.ready)??0)}`}),e.jsx(zs,{label:"Aguardando GPU",value:`${((gs=Ne.workers)==null?void 0:gs.throttled)??0}`,warn:(((hs=Ne.workers)==null?void 0:hs.throttled)??0)>0}),e.jsx(zs,{label:"Jobs na fila",value:`${((As=Ne.jobs)==null?void 0:As.inQueue)??0}`,warn:(((Gs=Ne.jobs)==null?void 0:Gs.inQueue)??0)>3}),e.jsx(zs,{label:"Completos / Falhas",value:`${((Hs=Ne.jobs)==null?void 0:Hs.completed)??0} / ${((Ls=Ne.jobs)==null?void 0:Ls.failed)??0}`})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:c?"Carregando...":"Sem dados do endpoint."}),(((L=s==null?void 0:s.serverless.recentRequests)==null?void 0:L.length)??0)>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-semibold mb-2",children:"Últimas gerações"}),e.jsx("div",{className:"space-y-1",children:s.serverless.recentRequests.map(S=>e.jsxs("div",{className:"flex items-center gap-3 text-xs py-1.5 px-2 rounded-md bg-background/60 border border-border/30",children:[e.jsx("span",{className:Ue("px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase",S.status==="COMPLETED"?"bg-emerald-500/15 text-emerald-400":S.status==="FAILED"?"bg-red-500/15 text-red-400":"bg-amber-500/15 text-amber-400"),children:S.status}),S.gpu&&S.gpu!=="auto"&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] font-semibold bg-sky-500/15 text-sky-400",children:S.gpu}),e.jsxs("span",{className:"font-mono text-muted-foreground truncate flex-1",children:[S.id.slice(0,13),"…"]}),e.jsxs("span",{className:"text-muted-foreground",children:["fila ",xn(S.delayTimeMs)]}),e.jsxs("span",{className:"text-muted-foreground",children:["exec ",xn(S.executionTimeMs)]}),e.jsx("span",{className:"font-medium",children:S.estCostUsd!=null?`~$${S.estCostUsd}`:"—"})]},S.id))}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-1.5",children:"Custo estimado (execução + boot médio). Fila não é cobrada; boot e execução são."})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/50 bg-card/40 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(ko,{className:"w-4 h-4 text-primary"})," Storage (Network Volume)"]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:ps,disabled:w,className:"gap-1.5",children:[w?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Qe,{className:"w-3.5 h-3.5"}),"Recarregar"]})]}),h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1.5",children:[e.jsxs("span",{className:"text-muted-foreground",children:[h.volumeId," · ",h.datacenter," · ",h.objectCount," arquivos"]}),e.jsxs("span",{className:"font-medium",children:[Tr(h.usedBytes)," de ",h.capacityGb," GB"]})]}),e.jsx("div",{className:"h-2 rounded-full bg-background/80 border border-border/40 overflow-hidden",children:e.jsx("div",{className:Ue("h-full rounded-full transition-all",h.usedBytes/(h.capacityGb*1e9)>.85?"bg-red-500":"bg-primary"),style:{width:`${Math.min(100,h.usedBytes/(h.capacityGb*1e9)*100)}%`}})})]}),e.jsx("div",{className:"space-y-2",children:Object.entries(h.groups).sort((S,de)=>de[1].totalBytes-S[1].totalBytes).map(([S,de])=>e.jsxs("div",{className:"rounded-lg border border-border/40 bg-background/50",children:[e.jsxs("button",{onClick:()=>$(Ce=>({...Ce,[S]:!Ce[S]})),className:"w-full flex items-center gap-2 px-3 py-2 text-left",children:[R[S]?e.jsx(Cr,{className:"w-3.5 h-3.5 text-muted-foreground"}):e.jsx(Sa,{className:"w-3.5 h-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium flex-1",children:S}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[de.files.length," item",de.files.length!==1?"s":""]}),e.jsx("span",{className:"text-xs font-semibold w-20 text-right",children:Tr(de.totalBytes)})]}),R[S]&&e.jsx("div",{className:"px-3 pb-2.5 space-y-1",children:de.files.sort((Ce,Oe)=>Oe.sizeBytes-Ce.sizeBytes).map(Ce=>e.jsxs("div",{className:"flex items-center gap-2 text-xs py-1 px-2 rounded bg-card/60 group/file",children:[e.jsx("span",{className:"font-mono text-muted-foreground truncate flex-1",title:Ce.name,children:Ce.isPrefix?Ce.name:Ce.name.split("/").pop()||Ce.name}),Ce.usedBy.length>0&&e.jsxs("span",{className:"shrink-0 px-1.5 py-0.5 rounded bg-primary/15 text-primary text-[9px] font-semibold",title:`Usado por: ${Ce.usedBy.join(", ")}`,children:[Ce.usedBy.length," workflow",Ce.usedBy.length>
7061?"s":""]}),e.jsx("span",{className:"shrink-0 font-medium",children:Tr(Ce.sizeBytes)}),e.jsx("button",{onClick:()=>C(Ce),className:"shrink-0 text-muted-foreground/40 hover:text-destructive transition-colors opacity-0 group-hover/file:opacity-100",title:"Deletar",children:e.jsx(_s,{className:"w-3.5 h-3.5"})})]},Ce.name))})]},S))}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60",children:"Modelo novo entra pelo fluxo de adicionar workflow (o download vai direto pro volume). O badge indica quantos workflows de produção usam o arquivo."}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Expandir volume pra"}),e.jsx("input",{type:"number",min:101,max:500,placeholder:"150",value:W,onChange:S=>N(S.target.value),className:"w-20 h-7 px-2 rounded-md bg-background border border-border/40 text-xs text-center outline-none focus:border-primary/60"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"GB"}),e.jsx(y,{size:"sm",variant:"outline",onClick:Ps,disabled:ce||!W,className:"h-7 px-2 text-[11px]",children:ce?e.jsx(he,{className:"w-3 h-3 animate-spin"}):"Expandir"}),e.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:"só aumenta, não encolhe · $0.07/GB/mês"})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:w?"Listando arquivos do volume...":"Sem dados do storage."})]}),e.jsxs("div",{className:"rounded-xl border border-border/50 bg-card/40 p-5 space-y-3",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(zn,{className:"w-4 h-4 text-primary"})," Conta RunPod"]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:[e.jsx(zs,{label:"Saldo",value:(s==null?void 0:s.account.balanceUsd)!=null?`$${s.account.balanceUsd.toFixed(2)}`:"—",warn:((s==null?void 0:s.account.balanceUsd)??99)<15}),e.jsx(zs,{label:"Burn atual",value:(s==null?void 0:s.account.spendPerHrUsd)!=null?`$${s.account.spendPerHrUsd.toFixed(2)}/h`:"—"}),e.jsx(zs,{label:"Storage (volume 100GB)",value:`$${(s==null?void 0:s.account.volumeMonthlyUsd)??7}/mês`})]}),((s==null?void 0:s.account.balanceUsd)??99)<15&&e.jsxs("p",{className:"text-[11px] text-red-400 flex items-center gap-1.5",children:[e.jsx(qs,{className:"w-3 h-3"})," Saldo baixo — se zerar, o RunPod DELETA o volume (modelos). Recarregue ou ative auto-recharge no painel RunPod."]}),we&&we.length>1&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-semibold mb-2",children:"Histórico de saldo (burn)"}),e.jsx("div",{className:"space-y-1",children:we.slice(0,14).map((S,de)=>{const Ce=we[de+1],Oe=Ce?Math.max(0,(Ce.balance_usd??0)-(S.balance_usd??0)):null;return e.jsxs("div",{className:"flex items-center gap-3 text-xs py-1 px-2 rounded bg-background/60 border border-border/30",children:[e.jsx("span",{className:"text-muted-foreground w-32 shrink-0",children:new Date(S.taken_at).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}),e.jsxs("span",{className:"font-medium w-20",children:["$",Number(S.balance_usd).toFixed(2)]}),Oe!=null&&Oe>0&&e.jsxs("span",{className:"text-amber-400/90",children:["−$",Oe.toFixed(2)," no período"]})]},S.taken_at)})}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-1.5",children:"Snapshot a cada ~5h (watchdog). Alerta de saldo baixo por email: automático, 1x/24h."})]}),e.jsxs("div",{className:"rounded-lg border border-border/40 bg-background/50 px-3 py-2.5 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-semibold",children:"ComfyUI produção"}),e.jsx("span",{className:"font-mono text-sm font-semibold",children:(E==null?void 0:E.applied)??"—"}),(E==null?void 0:E.latestRelease)&&E.latestRelease===E.applied&&e.jsx("span",{className:"text-[11px] text-emerald-400",children:"✓ na última release"}
706),e.jsx("button",{onClick:Ze,className:"text-muted-foreground/50 hover:text-foreground transition-colors",title:"Atualizar status",children:e.jsx(Qe,{className:"w-3 h-3"})})]}),(E==null?void 0:E.build)&&E.build.status!=="completed"&&e.jsxs("p",{className:"text-[11px] text-amber-400 flex items-center gap-1.5",children:[e.jsx(he,{className:"w-3 h-3 animate-spin"})," Build em andamento (",E.build.status,")…"," ",e.jsx("a",{href:E.build.url,target:"_blank",rel:"noreferrer",className:"underline",children:"acompanhar"})]}),(E==null?void 0:E.latestRelease)&&E.latestRelease!==E.applied&&e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:["última release: ",e.jsx("span",{className:"font-mono text-foreground",children:E.latestRelease})]}),(d=E.availableTags)!=null&&d.includes(E.latestRelease)?e.jsxs(y,{size:"sm",disabled:K,onClick:()=>ws(E.latestRelease),className:"h-7 px-2 text-[11px] gap-1",children:[K?e.jsx(he,{className:"w-3 h-3 animate-spin"}):null,"Aplicar ",E.latestRelease," no endpoint"]}):e.jsxs(y,{size:"sm",variant:"outline",disabled:K||E.build!=null&&E.build.status!=="completed",onClick:()=>es(E.latestRelease),className:"h-7 px-2 text-[11px] gap-1",children:[K?e.jsx(he,{className:"w-3 h-3 animate-spin"}):null,"1. Buildar imagem ",E.latestRelease," (~15 min)"]})]}),(((le=E==null?void 0:E.availableTags)==null?void 0:le.length)??0)>1&&e.jsxs("p",{className:"text-[10px] text-muted-foreground/70",children:["Versões prontas pra aplicar (rollback = aplicar a anterior):"," ",E.availableTags.map(S=>e.jsx("button",{onClick:()=>ws(S),disabled:K||S===E.applied,className:Ue("font-mono underline-offset-2 mr-2",S===E.applied?"text-emerald-400 no-underline cursor-default":"underline hover:text-foreground"),children:S},S))]}),e.jsx("p",{className:"text-[10px] text-amber-400/70",children:"⚠ Depois de aplicar versão nova, TESTE uma geração — release nova já quebrou workflow no passado (v0.28.0)."})]})]}),e.jsx(ds,{open:Ve!==null,onOpenChange:S=>!S&&Je(null),children:e.jsxs(cs,{className:"max-w-2xl",children:[e.jsx(ms,{children:e.jsx(us,{children:"Boot log dos workers"})}),e.jsx("pre",{className:"text-[11px] font-mono bg-background/80 border border-border/40 rounded-md p-3 max-h-[50vh] overflow-auto whitespace-pre-wrap",children:Ve})]})}),e.jsx(tc,{target:V,deleting:ee,onCancel:()=>C(null),onConfirm:H})]})]})}function sc(){var ce;const[s,n]=r.useState(null),[c,u]=r.useState(!0),[m,_]=r.useState(null),[k,g]=r.useState(!0),l=async D=>{const{data:{session:i}}=await F.auth.getSession();if(!i)throw new Error("sem sessão");return(await fetch("https://tyfwdwvbndsylqtvfzdh.supabase.co/functions/v1/runninghub-run",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i.access_token}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InR5Zndkd3ZibmRzeWxxdHZmemRoIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzIzNDAzNjQsImV4cCI6MjA4NzkxNjM2NH0.KGd8GMawqyMQEQouhRdeOBk079fChRxszRniEupHcr4"},body:JSON.stringify({action:D})})).json()},h=async(D=!1)=>{D||u(!0);try{const[i,A,O]=await Promise.all([l("account"),F.functions.invoke("labs-comfy-rh",{body:{action:"admin-status"}}).then(te=>te.data??null).catch(()=>null),F.functions.invoke("labs-upscale-rh",{body:{action:"status"}}).then(te=>te.data??null).catch(()=>null)]);n({...i,workflowsConfigured:[...(i==null?void 0:i.workflowsConfigured)||[],...(A==null?void 0:A.workflows)||[],...(O==null?void 0:O.workflows)||[]],inFlight:((A==null?void 0:A.inFlight)??0)+((O==null?void 0:O.inFlight)??0),stale:((A==null?void 0:A.stale)??0)+((O==null?void 0:O.stale)??0),creditosPresos:(A==null?void 0:A.creditosPresos)??0,presos:(A==null?void 0:A.presos)??[]})}catch(i){n({ok:!1,error:String(i)})}finally{D||u(!1)}},x=async()=>{g(!0);try{_(await l("audit"))}catch{_(null)}finally{g(!1)}},[w,v]=r.useState(null),[R,$]=r.useState([]),[V,C]=r.useState([]),[ee,Z]=r.useState(null),p=r.useMemo(()=>[...V].sort((D,i)=>Number(i.ativo)-Number(D.ativo)),[V]),z=V.filter(D=>D.ativo).length,Q=V.length-z,ae=r.useCallback(async D=>{Z(D.id);try{const{data:i,error:A}=await F.functions.invoke("labs-comfy-rh",{body:{action:D.ativo?"checkpoint-archive":"checkpoint-restore",id:D.id}}),O=i;if(A||O!=null&&O.error)throw new Error((O==null?void 0:O.error)||(A==null?void 0:A.message)||"Erro");Array.isArray(O.checkpoints)&&C(O.checkpoints),o.success(D.ativo?`"${D.label}" foi arquivado.`:`"${D.label}" foi restaurado.`)}catch(i){o.error((i==null?void 0:i.message)||"Erro")}finally{Z(null)}},[]),Y=r.useCallback(async()=>{try{const{data:D,error:i}=await F.functions.invoke("labs-comfy-rh",{body:{action:"checkpoint-list"}});if(i||D!=null&&D.error)return;Array.isArray(D.checkpoints)&&C(D.checkpoints)}catch{}},[]);r.useEffect(()=>{Y()},[Y]);const B=async D=>{if(!(D==="checkpoint-seed"&&!confirm(`Semear o catálogo de checkpoints?
707
708Isso atualiza apenas as entradas gerenciadas pela semente do código (checkpoint padrão dos grafos e modelos adicionais aprovados), incluindo template, steps, CFG, shift, sampler e versão. O restante do catálogo não muda.
709
710Só continue se a intenção for restaurar a semente.`))){v(D);try{const{data:i,error:A}=await F.functions.invoke("labs-comfy-rh",{body:{action:D}});if(A||i!=null&&i.error)throw new Error((i==null?void 0:i.error)||(A==null?void 0:A.message)||"Falhou");const O=i;if(Array.isArray(O.probe)&&$(O.probe),Array.isArray(O.resultado)){const te=O.resultado.filter(re=>re.ok).length,T=O.resultado.filter(re=>!re.ok);T.length?o.warning(`${te} gravado(s), ${T.length} sem checkpoint legível`,{description:T.map(re=>`${re.template}: ${re.motivo||re.erro}`).join(" · ")}):o.success(`Catálogo semeado (${te} checkpoints)`),await B("checkpoint-probe");return}o.success("Grafos conferidos")}catch(i){o.error((i==null?void 0:i.message)||"Falha no catálogo de checkpoints")}finally{v(null)}}},[G,q]=r.useState(""),[E,P]=r.useState(!1),K=async()=>{if(G.trim()){P(!0);try{const{data:{session:D}}=await F.auth.getSession();if(!D)return;const i=async O=>(await fetch(`https://tyfwdwvbndsylqtvfzdh.supabase.co/functions/v1/${O}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D.access_token}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InR5Zndkd3ZibmRzeWxxdHZmemRoIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzIzNDAzNjQsImV4cCI6MjA4NzkxNjM2NH0.KGd8GMawqyMQEQouhRdeOBk079fChRxszRniEupHcr4"},body:JSON.stringify({action:"recover",taskId:G.trim()})})).json();let A=await i("runninghub-run");for(const O of["labs-comfy-rh","labs-upscale-rh"]){if(!(A!=null&&A.wrongFunction))break;A=await i(O)}if(A.ok&&A.status==="recuperado"){const O=A.settleRefunded??A.creditsRefunded;o.success(`Recuperado${O?` (+${O}cr devolvidos ao user)`:""}`,{description:A.mediaUrl||A.imageUrl}),q(""),x()}else A.ok&&A.status==="rodando"?o.info("Task ainda rodando no provider — tente de novo em alguns minutos."):A.ok&&A.status==="falhou"?(o.warning(`Task falhou no provider — créditos ${A.creditsRefunded?"refundados":"já estavam refundados"}.`),x()):o.error(A.error||"Falha na recuperação.")}catch(D){o.error(D.message)}finally{P(!1)}}};r.useEffect(()=>{h(),x()},[]);const[J,W]=r.useState("conta");r.useEffect(()=>{if(J!=="conta")return;const D=setInterval(()=>h(!0),15e3);return()=>clearInterval(D)},[J]);const N=(s==null?void 0:s.ok)&&Number(s.remainMoney)<5;return e.jsxs("div",{className:"rounded-xl border border-border/50 bg-card/40 p-5 space-y-4",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-1.5 pb-1",children:[["conta","Conta"],["loras","Catálogo de LoRAs"],["auditoria","Auditoria"],["workflows","Workflows"]].map(([D,i])=>e.jsx("button",{type:"button",onClick:()=>W(D),className:Ue("px-2.5 py-1 rounded-md text-[11px] font-medium transition-colors",J===D?"bg-primary/15 text-primary":"text-muted-foreground hover:text-foreground"),children:i},D))}),J==="workflows"&&e.jsx(Jd,{}),J==="loras"?e.jsx(rc,{}):e.jsxs(e.Fragment,{children:[J==="conta"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(vt,{className:Ue("w-4 h-4",s!=null&&s.ok?"text-emerald-400":"text-amber-400")}),"Conta RunningHub ",s!=null&&s.apiType?`(${s.apiType})`:""]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Workflows do Labs executam na workflow API do RunningHub. Wallet paga por segundo de GPU."})]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>h(),disabled:c,className:"gap-1.5",children:[c?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Qe,{className:"w-3.5 h-3.5"}),"Atualizar"]})]}),e.jsx(Xd,{}),s!=null&&s.ok?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsx(zs,{label:`Wallet (${s.currency||"USD"})`,value:`$${s.remainMoney??"?"}`,warn:N}),e.jsx(zs,{label:"Coins (consumer)",value:`${s.remainCoins??"?"}`}),e.jsx(zs,{label:"Em voo (nosso)",value:`${s.inFlight??"?"}`,warn:(s.stale??0)>0,hint:`provedor: ${s.currentTaskCounts??"?"}`}),e.jsx(zs,{label:"Concorrência",value:"100"})]}),N&&e.jsx("p",{className:"text-xs text-amber-400",children:"⚠️ Wallet baixo — recarregar em runninghub.ai → Enterprise-Shared → Recharge Wallet."}),(s.stale??0)>0&&e.jsxs("p",{className:"text-xs text-amber-400",children:["⚠️ ",s.stale,' geração(ões) há mais de 15 min em "processando" — provável órfã. Reconciliar em /admin/recuperacao.']}),(s.creditosPresos??0)>0&&e.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/[0.06] p-2.5 space-y-1.5",children:[e.jsxs("p",{className:"text-xs text-destructive/90",children:["💰 ",s.creditosPresos," cobrança(s) reservadas sem acerto nem devolução (mais de 1h)."]}),e.jsx("div",{className:"space-y-1",children:(s.presos||[]).map(D=>e.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[e.jsxs("span",{className:"font-mono text-muted-foreground
710/70 shrink-0",children:[D.credits,"cr"]}),e.jsxs("span",{className:"flex-1 truncate text-muted-foreground/80",title:`${D.motivo}${D.taskId?` · task ${D.taskId}`:" · sem taskId"}`,children:[D.motivo,D.taskId?"":" (sem taskId — recover não alcança)"]}),e.jsx("span",{className:"text-muted-foreground/40 shrink-0",children:new Date(D.at).toLocaleString()}),e.jsx("button",{type:"button",className:"shrink-0 underline text-destructive/80 hover:text-destructive",onClick:async()=>{if(confirm(`Devolver ${D.credits} crédito(s)?
711
712Confira ANTES no provedor se a geração realmente não aconteceu — se ela saiu, devolver significa pagar a imagem do nosso bolso.`))try{await F.functions.invoke("labs-comfy-rh",{body:{action:"liberar-hold",deductionId:D.id}}).then(({data:i,error:A})=>{if(A||i!=null&&i.error)throw new Error((i==null?void 0:i.error)||(A==null?void 0:A.message))}),o.success(`${D.credits} crédito(s) devolvidos.`),h(!0)}catch(i){o.error((i==null?void 0:i.message)||"Erro")}},children:"devolver"})]},D.id))})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-semibold mb-2",children:"Workflows configurados"}),e.jsx("ul",{className:"space-y-1",children:(s.workflowsConfigured||[]).map(D=>e.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[e.jsx(vt,{className:Ue("w-3 h-3 shrink-0",D.configured?"text-emerald-400":"text-red-400")}),e.jsx("span",{className:"font-mono text-xs",children:D.key}),e.jsx("span",{className:"text-xs text-muted-foreground",children:D.configured?"workflowId configurado":"FALTA secret RUNNINGHUB_WF_* com o workflowId"})]},D.key))})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:c?"Consultando conta...":`Sem resposta da integração${s!=null&&s.error?` (${s.error})`:""} — edge fn runninghub-run deployada?`})]}),J==="auditoria"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"pt-4 border-t border-border/30 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-semibold",children:"Auditoria de gerações (custo real × créditos)"}),e.jsxs(y,{variant:"ghost",size:"sm",onClick:x,disabled:k,className:"gap-1.5 h-7 text-xs",children:[k?e.jsx(he,{className:"w-3 h-3 animate-spin"}):e.jsx(Qe,{className:"w-3 h-3"}),"Atualizar"]})]}),(m==null?void 0:m.ok)&&m.totals&&e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsx(zs,{label:"Créditos cobrados",value:`${m.totals.credits}`}),e.jsx(zs,{label:"Receita equiv.",value:`$${m.totals.revenueUsd}`}),e.jsx(zs,{label:"Custo provider",value:`$${m.totals.costUsd}`}),e.jsx(zs,{label:"Margem",value:m.totals.revenueUsd>0?`${Math.round((1-m.totals.costUsd/m.totals.revenueUsd)*100)}%`:"—",warn:m.totals.revenueUsd>0&&1-m.totals.costUsd/m.totals.revenueUsd<.35})]}),m!=null&&m.ok&&(((ce=m.items)==null?void 0:ce.length)??0)>0?e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:[e.jsx("th",{className:"text-left py-1.5 pr-3 font-semibold",children:"Quando"}),e.jsx("th",{className:"text-left py-1.5 pr-3 font-semibold",children:"Workflow"}),e.jsx("th",{className:"text-left py-1.5 pr-3 font-semibold",children:"User"}),e.jsx("th",{className:"text-right py-1.5 pr-3 font-semibold",children:"Áudio"}),e.jsx("th",{className:"text-right py-1.5 pr-3 font-semibold",children:"Exec"}),e.jsx("th",{className:"text-right py-1.5 pr-3 font-semibold",children:"Créditos"}),e.jsx("th",{className:"text-right py-1.5 pr-3 font-semibold",children:"Custo real"}),e.jsx("th",{className:"text-right py-1.5 font-semibold",children:"Margem"})]})}),e.jsx("tbody",{children:m.items.map((D,i)=>e.jsxs("tr",{className:"border-t border-border/20",children:[e.jsx("td",{className:"py-1.5 pr-3 text-muted-foreground whitespace-nowrap",children:new Date(D.createdAt).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"})}),e.jsx("td",{className:"py-1.5 pr-3 font-mono",children:D.workflow}),e.jsxs("td",{className:"py-1.5 pr-3 font-mono text-muted-foreground",children:[D.userId,"…"]}),e.jsx("td",{className:"py-1.5 pr-3 text-right",children:D.audioSeconds!=null?`${D.audioSeconds}s`:"—"}),e.jsx("td",{className:"py-1.5 pr-3 text-right text-muted-foreground",children:D.execSec!=null?`${D.execSec}s`:D.taskStatus}),e.jsxs("td",{className:"py-1.5 pr-3 text-right font-medium",children:[D.credits,D.refunded&&e.jsx("span",{className:"ml-1 text-[9px] text-amber-400",children:"(refund)"})]}),e.jsx("td",{className:"py-1.5 pr-3 text-right",children:D.costUsd!=null?`$${D.costUsd}`:"—"}),e.jsx("td",{className:Ue("py-1.5 text-right font-semibold",D.marginPct==null?"text-muted-foreground":D.marginPct<35?"text-amber-400":"text-emerald-400"),children:D.marginPct!=null?`${D.marginPct}%`:"—"})]},i))})]}
712),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-1.5",children:"Custo real vem da fatura do provider por task. Margem = 1 − custo/receita-equivalente dos créditos. Amarelo = margem abaixo de 35%."})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:k?"Carregando auditoria...":"Nenhuma geração registrada ainda."})]}),e.jsxs("div",{className:"pt-4 border-t border-border/30 space-y-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-semibold",children:"Recuperar task órfã"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"text",value:G,onChange:D=>q(D.target.value.trim()),placeholder:"taskId (da auditoria acima ou do card de erro)",className:"flex-1 h-9 px-3 rounded-md bg-background border border-border/40 text-sm font-mono outline-none focus:border-primary/60"}),e.jsxs(y,{variant:"outline",onClick:K,disabled:E||!G,className:"gap-1.5",children:[E?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Qe,{className:"w-3.5 h-3.5"}),"Recuperar"]})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60",children:"Consulta o provider pelo taskId: completou → salva o resultado e entrega ao dono (com acerto de créditos); falhou → refunda; rodando → avisa."})]})]}),J==="conta"&&e.jsx(e.Fragment,{children:e.jsxs("div",{className:"pt-4 border-t border-border/30 space-y-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-semibold",children:"Catálogo de checkpoints"}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(y,{variant:"outline",onClick:()=>B("checkpoint-probe"),disabled:!!w,className:"gap-1.5",children:[w==="checkpoint-probe"?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Qe,{className:"w-3.5 h-3.5"}),"Conferir grafos"]}),e.jsxs(y,{variant:"outline",onClick:()=>B("checkpoint-seed"),disabled:!!w,className:"gap-1.5",children:[w==="checkpoint-seed"?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Us,{className:"w-3.5 h-3.5"}),"Semear / atualizar"]})]}),R.length>0&&e.jsx("div",{className:"space-y-1",children:R.map(D=>e.jsxs("div",{className:"flex items-center gap-2 text-[12px] font-mono",children:[e.jsx("span",{className:D.bate?"text-primary":"text-amber-400",children:D.bate?"=":"≠"}),e.jsx("span",{className:"text-muted-foreground w-36 shrink-0",children:D.template}),e.jsx("span",{className:"truncate",title:`grafo: ${D.fileNameNoProvedor??"?"} · catálogo: ${D.fileNameNoCatalogo??"—"}`,children:D.fileNameNoProvedor??(D.configurado?"não consegui ler":"sem secret")})]},D.template))}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60",children:'"Semear" lê o arquivo dos checkpoints padrão nos próprios grafos e usa a origem verificada nos modelos adicionais. O provedor não valida esse campo: nome errado vira geração que roda, falha e cobra.'}),V.length>0&&e.jsxs("div",{className:"pt-3 mt-1 border-t border-border/20 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-semibold",children:"Modelos no catálogo"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground/50",children:[z," ativos · ",Q," arquivados"]}),e.jsx("button",{type:"button",onClick:Y,className:"text-muted-foreground/60 hover:text-foreground",title:"Recarregar",children:e.jsx(Qe,{className:"w-3 h-3"})})]}),p.map(D=>e.jsxs("div",{className:Ue("flex items-center gap-2 text-[12px] py-1 px-2 rounded border border-border/20 bg-background/30 transition-colors duration-150 hover:border-primary/35 hover:bg-primary/[0.07] focus-within:border-primary/40 focus-within:bg-primary/[0.07]",!D.ativo&&"border-amber-400/20 bg-amber-400/[0.03]"),children:[e.jsx("span",{className:"font-medium truncate max-w-[13rem]",children:D.label}),D.quantization&&e.jsx("span",{className:"shrink-0 px-1 py-px rounded bg-muted/50 border border-border/40 text-[9px] font-mono",children:D.quantization}),D.versionName?e.jsx("span",{className:"shrink-0 px-1 py-px rounded bg-primary/10 border border-primary/25 text-[9px] font-mono text-primary/80",title:"Versão do checkpoint",children:vo(D.versionName)}):e.jsx("span",{className:"shrink-0 text-[9px] font-mono text-muted-foreground
712/25",title:"Sem versão preenchida",children:"sem versão"}),!D.ativo&&e.jsx("span",{className:"shrink-0 px-1 py-px rounded border border-amber-400/30 text-[9px] uppercase tracking-wider text-amber-400/80",children:"Arquivado"}),!D.validatedAt&&e.jsx("span",{className:"shrink-0 px-1 py-px rounded border border-amber-400/30 text-[9px] uppercase tracking-wider text-amber-400/70",title:"Nenhuma geração completou com este checkpoint ainda — o nome do arquivo não foi provado",children:"nunca validado"}),e.jsxs("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70",children:[D.steps,"st · cfg ",D.cfg," · ",D.sampler,"/",D.scheduler," · shift ",D.shift]}),e.jsx("span",{className:"truncate font-mono text-[10px] text-muted-foreground/50 flex-1 min-w-0",title:D.fileName,children:D.fileName}),e.jsxs("span",{className:"shrink-0 flex items-center gap-1.5",children:[D.sourceUrl?e.jsx("a",{href:D.sourceUrl,target:"_blank",rel:"noopener noreferrer",title:"Página no provedor",className:"text-muted-foreground hover:text-primary",children:e.jsx($a,{className:"w-3 h-3"})}):e.jsx($a,{className:"w-3 h-3 text-muted-foreground/20"}),D.civitaiUrl?e.jsx("a",{href:D.civitaiUrl,target:"_blank",rel:"noopener noreferrer",title:"Página no CivitAI",className:"text-muted-foreground hover:text-primary",children:e.jsx(oa,{className:"w-3 h-3"})}):e.jsx(oa,{className:"w-3 h-3 text-muted-foreground/20"}),e.jsxs("button",{type:"button",onClick:()=>void ae(D),disabled:ee===D.id,className:Ue("inline-flex items-center gap-1 text-[10px] disabled:opacity-50",D.ativo?"text-muted-foreground/60 hover:text-amber-400":"text-amber-400/80 hover:text-primary"),title:D.ativo?"Arquivar e remover do seletor de geração":"Restaurar no seletor de geração",children:[ee===D.id?e.jsx(he,{className:"w-3 h-3 animate-spin"}):D.ativo?e.jsx(qa,{className:"w-3 h-3"}):e.jsx(Qe,{className:"w-3 h-3"}),D.ativo?"Arquivar":"Restaurar"]})]})]},D.id))]})]})})]})]})}function ac({onUsarLink:s}){const[n,c]=r.useState([]),[u,m]=r.useState(!0),[_,k]=r.useState(!1),g=r.useCallback(async x=>{const{data:w,error:v}=await F.functions.invoke("labs-comfy-rh",{body:x});if(v)throw new Error(v.message);if(w!=null&&w.error)throw new Error(w.error);return w},[]),l=r.useCallback(async()=>{m(!0);try{const x=await g({action:"lora-request-list",todos:!0,status:"pendente"});c((x==null?void 0:x.pedidos)??[]),((x==null?void 0:x.pedidos)??[]).length>0&&k(!0)}catch{}finally{m(!1)}},[g]);r.useEffect(()=>{l()},[l]);const h=r.useCallback(async(x,w)=>{try{await g({action:"lora-request-resolve",id:x,status:w}),c(v=>v.filter(R=>R.id!==x)),o.success(w==="aprovada"?"Pedido aprovado.":"Pedido recusado.")}catch(v){o.error((v==null?void 0:v.message)||"Não consegui atualizar.")}},[g]);return u||n.length===0?null:e.jsxs("div",{className:"rounded-lg border border-amber-400/30 bg-amber-400/[0.04] p-2.5 space-y-2",children:[e.jsxs("button",{type:"button",onClick:()=>k(x=>!x),className:"flex items-center gap-2 w-full text-left",children:[e.jsxs("span",{className:"text-[11px] uppercase tracking-wider font-semibold text-amber-300/90 flex-1",children:["Pedidos de LoRA · ",n.length]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:_?"recolher":"ver"})]}),_&&e.jsx("div",{className:"space-y-1",children:n.map(x=>e.jsxs("div",{className:"flex items-center gap-2 text-[11px] rounded bg-white/[0.03] px-2 py-1.5",children:[e.jsx("span",{className:"text-muted-foreground/70 shrink-0",children:x.user_id}),e.jsx("a",{href:x.civitai_url,target:"_blank",rel:"noreferrer",className:"flex-1 truncate text-primary/80 hover:underline",title:x.note||x.civitai_url,children:x.civitai_url}),e.jsx("button",{type:"button",onClick:()=>{s(x.civitai_url),o.info("Link no campo de importação abaixo.")},className:"px-1.5 h-6 rounded text-[10px] bg-white/[0.06] border border-white/10 hover:bg-white/[0.12]",children:"usar link"}),e.jsx("button",{type:"button",onClick:()=>void h(x.id,"aprovada"),className:"px-1.5 h-6 rounded text-[10px] bg-emerald-500/20 text-emerald-200 hover:bg-emerald-500/30",children:"aprovada"}),e.jsx("button",{type:"button",onClick:()=>void h(x.id,"recusada"),className:"px-1.5 h-6 rounded text-[10px] bg-white/[0.06] text-white/60 hover:bg-white/[0.12]",children:"recusar"})]},x.id))})]})}function rc(){const[s,n]=r.useState([]),[c,u]=r.useState(!1),[m,_]=r.useState(""),[k,g]=r.useState(""),[l,h]=r.useState(""),[x,w]=r.useState(!1),[v,R]=r.useState(null),[$,V]=r.useState(""),[C,ee]=r.useState(""),[Z,p]=r.useState(""),[z,Q]=r.useState(""),[ae,Y]=r.useState(""),[B,G]=r.useState(""),[q,E]=r.useState(null),[P,K]=r.useState(""),[J,W]=r.useState(null),N=r.useCallback(async j=>{const{data:ne,error:se}=await F.functions.invoke("labs-comfy-rh",{body:j});if(se){const ve=se==null?void 0:se.context;if(ve!=null&&ve.clone)try{const ye=await ve.clone().json();if(ye!=null&&ye.error)throw new Error(ye.error)}catch(ye){if(ye instanceof Error)throw ye}throw new Error(se.message||"Erro")}if(ne!=null&&ne.error)throw new Error(ne.error);return ne},[]),[ce,D]=r.useState(null),i=r.useCallback(async()=>{u(!0),D(null);try{const j=await N({action:"lora-list",scope:"global",gerenciar:!0});n((j==null?void 0:j.entries)||[])}catch(j){D((j==null?void 0:j.message)||"Não foi possível carregar o catálogo.")}finally{u(!1)}},[N]);r.useEffect(()=>{i()},[i]);const A=async()=>{var ne;const j=m.trim();if(j){w(!0);try{const se=await N({action:"lora-add",.../^https?:\/\//i.test(j)?{url:j}:{name:j},...k.trim()?{civitaiUrl:k.trim()}:{},...l.trim()?{versionName:l.trim()}:{}});o[se!=null&&se.already?"info":"success"](se!=null&&se.already?"Já estava no catálogo.":`"${((ne=se==null?void 0:se.entry)==null?void 0:ne.label)||j}" no catálogo.`),_(""),g(""),h(""),i()}catch(se){o.error(se.message||"Erro")}finally{w(!1)}}},O=async j=>{try{await N({action:"lora-global-remove",id:j,confirmar:!0}),o.success("Removida."),i()}catch(ne){o.error(ne.message||"Erro")}},[te,T]=r.useState(null),re=r.useCallback(async j=>{T(null),W(j);try{const ne=await N({action:"lora-global-remove",id:j.id});ne!=null&&ne.ensaio&&T({presets:ne.presets??0,exemplos:ne.exemplos??[]})}catch{}},[N]),[ke,fe]=r.useState(null),[X,me]=r.useState(""),[_e,$e]=r.useState("Krea 2"),[Ve,Je]=r.useState(""),[we,We]=r.useState(""),[Ge,ps]=r.useState(""),[be,ue]=r.useState(""),[Pe,ze]=r.useState(""),[Ie,xs]=r.useState(null),[Ps,Ze]=r.useState(0),[es,ws]=r.useState(!1),[is,os]=r.useState(null),[H,xe]=r.useState(null),[Ne,Xe]=r.useState(null),[bs,Rs]=r.useState(null),[gs,hs]=r.useState({}),As=r.useRef(null),[Gs,Hs]=r.useState(!1),[Ls,L]=r.useState(null),d=r.useRef(!1),[le,S]=r.useState({}),[de,Ce]=r.useState(!1),Oe=r.useRef(!1),Ke=r.useCallback(async()=>{var ne;const j=we.trim();if(!(!j||es)){ws(!0);try{const se=await qr(j);se.label&&me(se.label.slice(0,60)),se.baseModel&&$e(se.baseModel),(ne=se.triggers)!=null&&ne.length&&ps(se.triggers.join(", ")),se.note&&ze(se.note.slice(0,800)),se.versionName&&Je(String(se.versionName).slice(0,40)),typeof se.recommendedStrength=="number"&&ue(String(se.recommendedStrength)),os(se.fileName||null),xe(se.knownMd5||null),Xe(se.sha256||null),Rs(se.sizeBytes?Math.round(se.sizeBytes/1048576):null),o.success(se.knownMd5?"Campos preenchidos. Esse arquivo já está no provedor — o envio será só o cadastro.":"Campos preenchidos pelo CivitAI.")}catch(se){o.error(se.message||"Não consegui ler esse link.")}finally{ws(!1)}}},[we,es]),qe=r.useCallback(()=>{fe(null),me(""),Je(""),We(""),ps(""),ue(""),ze(""),os(null),xe(null),Xe(null),Rs(null)},[]),Me="aic_admin_lora_fila",[Be,Is]=r.useState([]),[ks,Ys]=r.useState(!1),Ye=r.useRef(!1),Js=r.useRef([]);r.useEffect(()=>{Js.current=Be},[Be]),r.useEffect(()=>{try{const j=JSON.parse(localStorage.getItem(Me)||"[]");Array.isArray(j)&&j.length&&Is(j.map(ne=>ne.status==="rodando"?{...ne,status:"fila",fase:void 0,pct:0}:ne))}catch{}},[]),r.useEffect(()=>{try{if(!Be.length){localStorage.removeItem(Me);return}localStorage.setItem(Me,JSON.stringify(Be.map(({fase:j,pct:ne,...se})=>se)))}catch{}},[Be]);const ua=r.useCallback(()=>{const j=we.trim();if(!j||!is||!X.trim()){o.error("Busque o link primeiro — a fila leva o que já foi conferido.");return}if(Be.some(ne=>ne.url===j&&ne.status==="fila")){o.info("Esse link já está na fila.");return}Is(ne=>[...ne,{id:`q${Date.now()}${Math.random().toString(36).slice(2,5)}`,url:j,label:X.trim(),baseModel:_e.trim(),fileName:is,versionName:Ve.trim()||void 0,triggers:Ge.split(",").map(se=>
712se.trim()).filter(Boolean),note:Pe.trim()||void 0,weight:be.trim()?Number(be.replace(",",".")):void 0,knownMd5:H||void 0,sha256:Ne||void 0,mb:bs,status:"fila"}]),qe(),o.success("Na fila. Cole o próximo link.")},[we,is,X,_e,Ve,Ge,Pe,be,H,Ne,bs,Be,qe]),$s=r.useCallback(async()=>{var ve;if(ks)return;Ye.current=!1,Ys(!0);let j=0,ne=0,se=0;try{for(;!Ye.current;){const ye=Js.current.find(js=>js.status==="fila");if(!ye)break;const ls=ye.id;Js.current=Js.current.map(js=>js.id===ls?{...js,status:"rodando"}:js),Is(js=>js.map(Ds=>Ds.id===ls?{...Ds,status:"rodando",fase:"conferindo",pct:0}:Ds));try{const js=await qr(ye.url);if(js.existente){Is(Ds=>Ds.map(Os=>Os.id===ls?{...Os,status:"existe",motivo:js.existente.label}:Os)),se++;continue}await Vr({url:ye.url,fileName:js.fileName||ye.fileName,knownMd5:js.knownMd5||ye.knownMd5,sha256:js.sha256||ye.sha256,label:ye.label,baseModel:ye.baseModel||js.baseModel,versionName:ye.versionName,civitaiUrl:ye.url,triggers:(ve=ye.triggers)!=null&&ve.length?ye.triggers:js.triggers,note:ye.note??js.note??void 0,recommendedStrength:ye.weight??js.recommendedStrength,escopo:"global"},(Ds,Os)=>Is(Ks=>Ks.map(Br=>Br.id===ls?{...Br,fase:Ds,pct:Os}:Br))),Is(Ds=>Ds.map(Os=>Os.id===ls?{...Os,status:"ok",fase:void 0}:Os)),j++}catch(js){Is(Ds=>Ds.map(Os=>Os.id===ls?{...Os,status:"erro",fase:void 0,motivo:(js==null?void 0:js.message)||"falhou"}:Os)),ne++}}}finally{Ys(!1),i();const ye=Ye.current?" (interrompido)":"";ne?o.warning(`${j} importada(s), ${se} já existia(m), ${ne} com erro${ye}.`):o.success(`${j} importada(s), ${se} já existia(m)${ye}.`)}},[ks,i]),ea=r.useCallback(j=>{const ne=new Set(j),se=ve=>ne.has(ve.id)?{...ve,status:"fila",motivo:void 0,fase:void 0,pct:0}:ve;Js.current=Js.current.map(se),Is(ve=>ve.map(se)),ks||$s()},[ks,$s]),lr=r.useCallback(async()=>{if(!is||!X.trim()||Ie)return;let j="iniciando";try{await Vr({url:we.trim(),fileName:is,knownMd5:H||void 0,sha256:Ne||void 0,label:X.trim(),baseModel:_e.trim(),versionName:Ve.trim()||void 0,civitaiUrl:we.trim(),triggers:Ge.split(",").map(ne=>ne.trim()).filter(Boolean),note:Pe.trim()||void 0,recommendedStrength:be.trim()?Number(be.replace(",",".")):void 0,escopo:"global"},(ne,se)=>{j=ne,xs(ne),Ze(se)}),o.success(`"${X.trim()}" no catálogo da casa.`),qe(),i()}catch(ne){const se=j==="downloading"?"baixando do CivitAI":j==="uploading"?"enviando pro provedor":j==="saving"?"salvando no catálogo":"preparando";o.error(`Falhou ${se}: ${(ne==null?void 0:ne.message)||"erro desconhecido"}`),console.error("[admin lora civitai]",j,ne)}finally{xs(null),Ze(0)}},[we,is,H,Ne,X,_e,Ve,Ge,be,Pe,Ie,qe,i]),Wa=r.useCallback(async()=>{if(!ke||!X.trim()||Ie)return;let j="iniciando";try{await bo({file:ke,label:X.trim(),baseModel:_e.trim(),versionName:Ve.trim()||void 0,civitaiUrl:we.trim()||void 0,triggers:Ge.split(",").map(ne=>ne.trim()).filter(Boolean),note:Pe.trim()||void 0,recommendedStrength:be.trim()?Number(be.replace(",",".")):void 0,escopo:"global"},(ne,se)=>{j=ne,xs(ne),Ze(se)}),o.success(`"${X.trim()}" no catálogo da casa.`),qe(),i()}catch(ne){const se=j==="hashing"?"lendo o arquivo":j==="uploading"?"enviando pro provedor":j==="saving"?"salvando no catálogo":"preparando";o.error(`Falhou ${se}: ${(ne==null?void 0:ne.message)||"erro desconhecido"}`),console.error("[admin lora upload]",j,ne)}finally{xs(null),Ze(0)}},[ke,X,_e,Ve,we,Ge,be,Pe,Ie,qe,i]),vr=j=>{const ne=String(j||"").match(/modelVersionId=(\d+)/);return ne?ne[1]:null},Pa=r.useMemo(()=>{const j=new Set,ne=new Set;for(const se of s){if(se.source!=="upload")continue;const ve=vr(se.civitaiUrl);ve&&j.add(ve),se.civitaiUrl&&ne.add(se.civitaiUrl.trim().toLowerCase())}return se=>{if(se.migratedTo)return!0;const ve=vr(se.civitaiUrl);return ve&&j.has(ve)?!0:!!se.civitaiUrl&&ne.has(se.civitaiUrl.trim().toLowerCase())}},[s]),dr=r.useCallback(async(j,ne=!0)=>{var se;if(!j.civitaiUrl)return S(ve=>({...ve,[j.id]:{tipo:"bloqueada",motivo:"Sem link do CivitAI — baixe e envie o arquivo à mão."}})),!1;try{S(ls=>({...ls,[j.id]:{tipo:"rodando",pct:0,fase:"lendo o CivitAI"}}));const ve=await qr(j.civitaiUrl),ye=await Vr({url:j.civitaiUrl,fileName:ve.fileName,knownMd5:ve.knownMd5,sha256:ve.sha256,label:j.label||ve.label,baseModel:j.baseModel||ve.baseModel,versionName:j.versionName||ve.ver
712sionName||void 0,civitaiUrl:j.civitaiUrl,triggers:(se=j.triggers)!=null&&se.length?j.triggers:ve.triggers,note:j.note||ve.note||void 0,recommendedStrength:j.recommendedStrength??ve.recommendedStrength,escopo:"global"},(ls,js)=>S(Ds=>({...Ds,[j.id]:{tipo:"rodando",pct:js,fase:ls}})));return await N({action:"lora-global-update",id:j.id,migratedTo:ye.id}).catch(ls=>console.warn("[migrar] carimbo falhou",j.id,ls)),S(ls=>({...ls,[j.id]:{tipo:"migrada"}})),ne&&i(),!0}catch(ve){return S(ye=>({...ye,[j.id]:{tipo:"erro",motivo:(ve==null?void 0:ve.message)||"erro desconhecido"}})),!1}},[N,i]),zr=r.useCallback(async()=>{const j=s.filter(ye=>ye.source!=="upload"&&!Pa(ye)&&ye.civitaiUrl);if(!j.length){o.info("Nada pra migrar.");return}Oe.current=!1,Ce(!0);let ne=0,se=0;for(const ye of j){if(Oe.current)break;await dr(ye,!1)?ne++:se++}Ce(!1),i();const ve=Oe.current?" (interrompido)":"";se?o.warning(`${ne} migrada(s), ${se} não${ve}. Veja o motivo em cada linha.`):o.success(`${ne} migrada(s)${ve}.`)},[s,Pa,dr,i]),I=()=>({graph:"krea2t2i",checkpointId:null,rhAccount:null}),U=r.useCallback(async()=>{if(As.current)return As.current;L("gerando base");try{const j=await Ri(I(),ne=>L(`base: ${ne}`));return As.current=j,j}finally{L(null)}},[]),ie=r.useCallback(async j=>{try{const ne=await U();hs(ve=>({...ve,[j.id]:{tipo:"rodando",fase:"enviando"}}));const se=await Pi(j.id,ne,I(),ve=>hs(ye=>({...ye,[j.id]:{tipo:"rodando",fase:ve}})));return hs(ve=>({...ve,[j.id]:{tipo:se.aplica?"aplica":"nao-aplica",diff:se.diff}})),N({action:"lora-global-update",id:j.id,canaryOk:se.aplica,canaryDiff:se.diff}).catch(()=>o.warning("Testei, mas não consegui salvar o resultado.")),se.aplica||o.warning(`"${j.label||j.name}" NÃO aplica (diferença ${se.diff.toFixed(3)}).`,{duration:15e3,action:{label:"Esconder da geração",onClick:async()=>{try{await N({action:"lora-global-update",id:j.id,hidden:!0}),o.success("Escondida da geração."),i()}catch(ve){o.error((ve==null?void 0:ve.message)||"Erro")}}}}),se.aplica}catch(ne){return hs(se=>({...se,[j.id]:{tipo:"erro",motivo:(ne==null?void 0:ne.message)||"erro"}})),!1}},[U,N,i]),ge=r.useCallback(async()=>{var Os;const ne=Ks=>Ks.canaryOk===!0&&Ks.canaryAt&&Date.now()-new Date(Ks.canaryAt).getTime()<2592e6,se=s.filter(Ks=>Ks.source==="upload"&&!Ks.hidden),ve=se.filter(Ks=>!ne(Ks));if(!se.length){o.info("Nada pra testar.");return}if(!ve.length){o.success("Todas já foram provadas nos últimos 30 dias.");return}const ye=se.length-ve.length,ls=(ve.length+1)*3;if(!confirm(`Testar ${ve.length} LoRA(s)?
713
714`+(ye?`${ye} já provada(s) nos últimos 30 dias — puladas.
715`:"")+`São ${ve.length+1} gerações reais (a base + uma por LoRA), ~${ls} créditos no total.
716Leva vários minutos e a aba precisa ficar aberta.
717
718As imagens do teste entram no seu histórico — são ruído, dá pra apagar depois.`))return;d.current=!1,Hs(!0);let js=0;for(const Ks of ve){if(d.current)break;((Os=gs[Ks.id])==null?void 0:Os.tipo)!=="aplica"&&(await ie(Ks)||js++)}Hs(!1);const Ds=d.current?" (interrompido)":"";js?o.warning(`${js} LoRA(s) não aplicam${Ds}. Veja as marcadas em vermelho.`):o.success(`Todas aplicam${Ds}.`)},[s,gs,ie]),ss=async(j,ne,se)=>{var ye;const ve=v;if(ve)try{const ls=await N({action:"lora-global-update",id:ve.id,...j});o.success(ne?ne(ls):`Nome: ${((ye=ls==null?void 0:ls.entry)==null?void 0:ye.name)??"atualizado"}`),(se==null?void 0:se.fecharAoFim)!==!1&&R(null),i()}catch(ls){o.error(ls.message||"Erro")}},Ws=()=>{const j=ae.split(/[,\n]/).map(ne=>ne.trim()).filter(Boolean).slice(0,12);ss({triggers:j},()=>j.length?`Trigger words: ${j.join(", ")}`:"Trigger words removidas.",{fecharAoFim:!1})},Ia=()=>{const j=B.split(/[,\n]/).map(ne=>ne.trim().toLowerCase()).filter(Boolean).slice(0,6);ss({tags:j},()=>j.length?`Categorias: ${j.join(", ")}`:"Categorias removidas.",{fecharAoFim:!1})};return e.jsxs("div",{className:"pt-4 border-t border-border/30 space-y-2",children:[e.jsx(ac,{onUsarLink:j=>{We(j)}}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground font-semibold flex-1",children:"Catálogo de LoRAs (todos os usuários)"}),(()=>{const j=s.filter(ne=>{var se;return ne.source==="upload"&&!ne.hidden&&!((se=ne.tags)!=null&&se.length)}).length;return j>0?e.jsxs("span",{className:"text-[10px] px-1.5 py-px rounded border border-amber-400/30 text-amber-400/80",title:"Sem categoria — peça a análise pra classificar em lote",children:[j," sem categoria"]}):null}
718)(),e.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:s.length}),e.jsx("button",{type:"button",onClick:i,className:"text-muted-foreground/60 hover:text-foreground",children:e.jsx(Qe,{className:Ue("w-3 h-3",c&&"animate-spin")})})]}),ce&&e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2",children:[e.jsxs("p",{className:"flex-1 text-[11px] text-destructive",children:["Falha ao carregar o catálogo — a lista abaixo NÃO reflete o que está salvo. ",ce]}),e.jsx("button",{type:"button",onClick:i,className:"text-[11px] underline text-destructive hover:opacity-80",children:"Tentar de novo"})]}),e.jsxs("div",{className:"grid gap-1.5 sm:grid-cols-2",children:[e.jsx("input",{type:"text",value:m,onChange:j=>_(j.target.value),placeholder:"nome-do-arquivo.safetensors (ou link do catálogo)",className:"h-9 px-3 rounded-md bg-background border border-border/40 text-sm font-mono outline-none focus:border-primary/60"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("input",{type:"text",value:k,onChange:j=>g(j.target.value),onKeyDown:j=>{j.key==="Enter"&&!x&&A()},placeholder:"link do CivitAI (traz nome, gatilhos, descrição)",className:"flex-1 h-9 px-3 rounded-md bg-background border border-border/40 text-sm font-mono outline-none focus:border-primary/60"}),e.jsx("input",{type:"text",value:l,onChange:j=>h(j.target.value),onKeyDown:j=>{j.key==="Enter"&&!x&&A()},placeholder:"v1.0",className:"w-24 shrink-0 h-9 px-3 rounded-md bg-background border border-border/40 text-sm font-mono outline-none focus:border-primary/60"})]})]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:A,disabled:x||!m.trim(),className:"gap-1.5",children:[x?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(Us,{className:"w-3.5 h-3.5"}),"Publicar no catálogo"]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-border/40 space-y-2",children:[e.jsx("p",{className:"text-[12px] font-medium",children:"Enviar arquivo pro catálogo"}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60",children:"Vai pelo nosso acesso, sem criar página no provedor — então não tem como sair da lista dele sozinha, que é o que derruba geração de vez em quando. Em troca, ela não tem link de origem lá (só o do CivitAI, se você preencher)."}),e.jsxs("p",{className:"text-[10px] text-muted-foreground/60",children:["Cole o link do CivitAI e clique ",e.jsx("span",{className:"font-medium",children:"Buscar"}),": dá pra importar direto, sem baixar na máquina. O arquivo escolhido abaixo só é necessário pra LoRA que não está no CivitAI. Modelo que exige login usa seu Token CivitAI (Perfil → RunPod)."]}),e.jsxs("label",{className:"flex items-center gap-2 h-9 px-3 rounded-md bg-background border border-dashed border-border/50 text-[12px] cursor-pointer hover:border-primary/50",children:[e.jsx(or,{className:"w-3.5 h-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate flex-1 text-muted-foreground",children:ke?`${ke.name} · ${(ke.size/1048576).toFixed(0)} MB`:"Escolher .safetensors (opcional)"}),e.jsx("input",{type:"file",accept:".safetensors",className:"hidden",disabled:!!Ie,onChange:j=>{var se;const ne=(se=j.target.files)==null?void 0:se[0];ne&&(fe(ne),X||me(ne.name.replace(/\.safetensors$/i,"").slice(0,60)))}})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[e.jsx("input",{type:"text",value:X,onChange:j=>me(j.target.value),placeholder:"Nome exibido",disabled:!!Ie,className:"h-9 px-3 rounded-md bg-background border border-border/40 text-sm outline-none focus:border-primary/60"}),e.jsx("input",{type:"text",value:_e,onChange:j=>$e(j.target.value),placeholder:"Modelo base",disabled:!!Ie,className:"h-9 px-3 rounded-md bg-background border border-border/40 text-sm outline-none focus:border-primary/60"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("input",{type:"text",value:we,onChange:j=>We(j.target.value),onKeyDown:j=>{j.key==="Enter"&&Ke()},placeholder:"link do CivitAI (opcional)",disabled:!!Ie,className:"flex-1 min-w-0 h-9 px-3 rounded-md bg-background border border-border/40 text-sm font-mono outline-none focus:border-primary/60"}),e.jsx(y,{variant:"secondary",size:"sm",className:"h-9 shrink-0",onClick:Ke,disabled:!we.trim()||es||!!Ie,children:es?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):"Buscar"})]}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx("input",{type:"text",value:Ve,onChange:j=>Je(j.target.value),placeholder:"v1.0",disabled:!!Ie,className:"flex-1 h-9 px-3 rounded-md bg-background border border-border/40 text-sm font-mono outline-none focus:border-primary/60"}),e.jsx("input",{type:"text",value:be,onChange:j=>ue(j.target.value),inputMode:"decimal",placeholder:"peso",disabled:!!Ie,className:"w-20 shrink-0 h-9 px-3 rounded-md bg-background border border-border/40 text-sm font-mono outline-none focus:border-primary/60"})]}),e.jsx("input",{type:"text",value:Ge,onChange:j=>ps(j.target.value),placeholder:"gatilhos, separados por vírgula",disabled:!!Ie,className:"col-span-2 h-9 px-3 rounded-md bg-background border border-border/40 text-sm outline-none focus:border-primary/60"}),e.jsx("textarea",{value:Pe,onChange:j=>ze(j.target.value),placeholder:"descrição (o que ela faz, como usar)",disabled:!!Ie,rows:3,className:"col-span-2 px-3 py-2 rounded-md bg-background border border-border/40 text-sm outline-none focus:border-primary/60 resize-y"})]}),Ie&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"h-1 rounded-full bg-muted/40 overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${Ps}%`}})}
718),e.jsxs("p",{className:"text-[10px] text-muted-foreground/70",children:[Ie==="downloading"?"Baixando do CivitAI":Ie==="hashing"?"Lendo o arquivo":Ie==="uploading"?"Enviando pro provedor":"Salvando"," · ",Ps,"%"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[is&&e.jsxs(y,{variant:"default",size:"sm",onClick:lr,disabled:!!Ie||!X.trim(),className:"gap-1.5",children:[Ie?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(na,{className:"w-3.5 h-3.5"}),H?"Cadastrar (já está no provedor)":`Baixar e enviar${bs?` · ${bs} MB`:""}`]}),is&&e.jsxs(y,{variant:"outline",size:"sm",onClick:ua,disabled:!X.trim(),className:"gap-1.5",children:[e.jsx($t,{className:"w-3.5 h-3.5"}),"+ fila",bs?` · ${bs} MB`:""]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:Wa,disabled:!!Ie||!ke||!X.trim(),className:"gap-1.5",children:[Ie?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(or,{className:"w-3.5 h-3.5"}),"Enviar arquivo escolhido"]})]}),Be.length>0&&e.jsxs("div",{className:"rounded-md border border-border/50 bg-background/40 p-2 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-[11px] font-semibold flex-1",children:["Fila · ",Be.filter(j=>j.status==="fila").length," pendente(s)",Be.some(j=>j.status==="ok")&&` · ${Be.filter(j=>j.status==="ok").length} ok`,Be.some(j=>j.status==="existe")&&` · ${Be.filter(j=>j.status==="existe").length} já tinha`,Be.some(j=>j.status==="erro")&&` · ${Be.filter(j=>j.status==="erro").length} erro`]}),ks?e.jsx(y,{variant:"outline",size:"sm",className:"h-6 text-[10px]",onClick:()=>{Ye.current=!0,o.info("Vai parar depois da atual.")},children:"Parar"}):e.jsxs(y,{variant:"default",size:"sm",className:"h-6 text-[10px] gap-1",onClick:$s,disabled:!Be.some(j=>j.status==="fila"),children:[e.jsx(na,{className:"w-3 h-3"})," Processar"]}),Be.some(j=>j.status==="erro")&&e.jsxs(y,{variant:"outline",size:"sm",className:"h-6 text-[10px] gap-1",onClick:()=>ea(Be.filter(j=>j.status==="erro").map(j=>j.id)),children:[e.jsx(Qe,{className:"w-3 h-3"})," Tentar os ",Be.filter(j=>j.status==="erro").length," com erro"]}),e.jsx(y,{variant:"ghost",size:"sm",className:"h-6 text-[10px]",onClick:()=>Is(j=>j.filter(ne=>ne.status==="fila"||ne.status==="rodando")),disabled:ks&&!Be.some(j=>j.status!=="fila"&&j.status!=="rodando"),children:"Limpar concluídos"})]}),e.jsx("p",{className:"text-[9.5px] text-muted-foreground",children:'Uma por vez. Mantenha a aba aberta enquanto roda — o download passa por aqui. Dá pra continuar enfileirando com o lote rodando. A lista fica salva no refresh; some só em "Limpar concluídos" ou na lixeira.'}),e.jsx("div",{className:"space-y-0.5 max-h-56 overflow-y-auto",children:Be.map(j=>e.jsxs("div",{className:"text-[10.5px] rounded px-1.5 py-1 bg-white/[0.03]",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:Ue("px-1 rounded text-[9px] shrink-0 w-16 text-center",j.status==="ok"?"bg-emerald-500/20 text-emerald-300":j.status==="erro"?"bg-red-500/20 text-red-300":j.status==="existe"?"bg-white/10 text-white/50":j.status==="rodando"?"bg-primary/25 text-primary":"bg-white/[0.06] text-white/40"),children:j.status==="rodando"?`${j.pct??0}%`:j.status==="existe"?"já tinha":j.status}),e.jsx("a",{href:j.url,target:"_blank",rel:"noopener noreferrer",className:"flex-1 truncate hover:text-primary hover:underline underline-offset-2",title:j.url,children:j.label}),j.baseModel&&e.jsx("span",{className:"shrink-0 rounded-md border border-border/50 bg-muted/40 px-1.5 py-0.5 text-[10px] font-medium text-foreground/80",title:`Modelo base: ${j.baseModel}`,children:j.baseModel}),j.versionName&&e.jsx(fo,{version:j.versionName,label:"Versão"}),j.mb?e.jsxs("span",{className:"text-muted-foreground shrink-0",children:[j.mb," MB"]}):null,j.status==="existe"&&j.motivo&&e.jsx("span",{className:"text-muted-foreground/70 truncate max-w-[10rem]",title:j.motivo,children:j.motivo}),j.status==="erro"&&e.jsxs("button",{type:"button",onClick:()=>ea([j.id]),className:"shrink-0 inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-white/[0.06] hover:bg-white/[0.12] text-white/70 hover:text-foreground",children:[e.jsx(Qe,{className:"w-3 h-3"})," tentar"]}),j.status!=="rodando"&&e.jsx("button",{type:"button",onClick:()=>Is(ne=>ne.filter(se=>
718se.id!==j.id)),className:"text-muted-foreground/60 hover:text-foreground shrink-0","aria-label":"Remover",children:e.jsx(_s,{className:"w-3 h-3"})})]}),j.status==="erro"&&j.motivo&&e.jsx("p",{className:"mt-0.5 pl-[4.5rem] text-[9.5px] text-red-300/80 break-words",children:j.motivo})]},j.id))})]})]}),(()=>{const j=s.filter(ve=>ve.source==="upload"&&!ve.hidden),ne=j.filter(ve=>{var ye;return((ye=gs[ve.id])==null?void 0:ye.tipo)==="nao-aplica"}).length,se=j.filter(ve=>{var ye;return((ye=gs[ve.id])==null?void 0:ye.tipo)==="aplica"}).length;return j.length?e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2 p-2.5 rounded-md bg-primary/5 border border-primary/20",children:[e.jsxs("p",{className:"text-[11px] text-muted-foreground/80 flex-1 min-w-[18rem]",children:[e.jsx("span",{className:"font-medium",children:"Teste de aplicação."})," ","Gera uma imagem com a LoRA em peso ",Ii," e compara com uma sem LoRA nenhuma, mesma seed. Se saírem parecidas, ela cobra e não aplica.",(se>0||ne>0)&&e.jsxs(e.Fragment,{children:[" "," · ",e.jsxs("span",{className:"text-emerald-400/90",children:[se," ok"]}),ne>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsxs("span",{className:"text-destructive font-medium",children:[ne," não aplicam"]})]})]}),Ls&&e.jsxs("span",{className:"block text-primary/80",children:[Ls,"…"]})]}),Gs?e.jsxs(y,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>{d.current=!0,o.info("Parando após a atual…")},children:[e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"})," Parar"]}):e.jsxs(y,{variant:"secondary",size:"sm",className:"gap-1.5",onClick:ge,children:[e.jsx(fi,{className:"w-3.5 h-3.5"})," Testar todas (",j.length,")"]})]}):null})(),(()=>{const j=s.filter(ye=>ye.source!=="upload"),ne=s.length-j.length,se=j.filter(ye=>!Pa(ye)&&ye.civitaiUrl),ve=j.filter(ye=>!Pa(ye)&&!ye.civitaiUrl).length;return j.length?e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2 p-2.5 rounded-md bg-amber-500/5 border border-amber-500/20",children:[e.jsxs("p",{className:"text-[11px] text-muted-foreground/80 flex-1 min-w-[18rem]",children:[e.jsx("span",{className:"font-medium text-amber-500/90",children:j.length})," cadastradas pelo link do provedor, fora da geração · ",e.jsx("span",{className:"font-medium text-emerald-400/90",children:ne})," já enviadas por API.",se.length>0&&e.jsxs(e.Fragment,{children:[" Faltam ",e.jsx("span",{className:"font-medium",children:se.length})," migrar."]}),ve>0&&e.jsxs(e.Fragment,{children:[" ",e.jsxs("span",{className:"text-muted-foreground/60",children:[ve," sem link do CivitAI — só à mão."]})]}),e.jsx("span",{className:"block text-muted-foreground/60",children:"Sem teto de tamanho (o do sistema é 1,5 GB). Arquivo grande leva minutos e precisa da aba aberta — o lote vai um por vez justamente por isso."})]}),de?e.jsxs(y,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>{Oe.current=!0,o.info("Parando após a atual…")},children:[e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"})," Parar"]}):se.length>0&&e.jsxs(y,{variant:"default",size:"sm",className:"gap-1.5",onClick:zr,children:[e.jsx($t,{className:"w-3.5 h-3.5"})," Migrar todas (",se.length,")"]})]}):null})(),e.jsx(Ti,{entries:s,loading:c,onRefresh:i,size:"md",showProviderLink:!0,groupBy:"origin",onCanario:j=>{ie(j)},canario:j=>gs[j.id]??null,onMigrate:j=>{dr(j)},migracao:j=>{if(j.source==="upload")return null;const ne=le[j.id];return ne||(Pa(j)?{tipo:"migrada"}:j.civitaiUrl?{tipo:"pronta"}:{tipo:"bloqueada",motivo:"Sem link do CivitAI — baixe e envie o arquivo à mão."})},onToggleHidden:async j=>{const ne=!j.hidden;n(se=>se.map(ve=>ve.id===j.id?{...ve,hidden:ne}:ve));try{await N({action:"lora-global-update",id:j.id,hidden:ne})}catch(se){n(ve=>ve.map(ye=>ye.id===j.id?{...ye,hidden:!ne}:ye)),o.error(se.message||"Não consegui mudar a visibilidade.")}},weightField:"recommendedStrength",onPatch:async(j,ne)=>{const se=s;n(ve=>ve.map(ye=>ye.id===j?{...ye,...ne}:ye));try{await N({action:"lora-global-update",id:j,...ne})}catch(ve){n(se),o.error(ve.message||"Erro")}},mostrarPendencias:!0,onRemove:j=>re(j),onEnrich:j=>{K(""),E(j)},onFixName:j=>{V(j.name),Y((j.triggers||[]).join(", ")),G((j.tags||[]).join(", ")),ee(""),p(j.civitaiUrl||""),Q(""),R(j)},emptyText:"Nenhuma LoRA no catálogo ainda."}
718),e.jsx("p",{className:"text-[10px] text-muted-foreground/60",children:"A LoRA já precisa existir no ambiente do provedor — aqui só se informa o nome do arquivo. Envio de arquivo é pelo perfil, e fica privado de quem enviou."}),e.jsx(va,{open:!!v,onOpenChange:j=>{j||R(null)},children:e.jsxs(ba,{children:[e.jsxs(Na,{children:[e.jsx(ya,{children:"Nome do arquivo no provedor"}),e.jsx(_a,{children:"É o único campo que o provedor valida. Errado, ele recusa o fluxo inteiro e ninguém gera — nem quem não marcou esta LoRA."})]}),e.jsx("input",{type:"text",value:$,onChange:j=>V(j.target.value),onKeyDown:j=>{j.key==="Enter"&&$.trim()&&ss({name:$.trim()})},placeholder:"nome-do-arquivo.safetensors",className:"h-9 px-3 rounded-md bg-background border border-border/40 text-sm font-mono outline-none focus:border-primary/60"}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60",children:v!=null&&v.url?"Ou releia direto da página do catálogo — é o caminho certo quando o nome entrou truncado.":"Esta entrada não tem link do catálogo salvo, então só dá pra digitar."}),e.jsxs(wa,{className:"gap-2 sm:justify-between",children:[e.jsxs(y,{variant:"outline",size:"sm",disabled:!(v!=null&&v.url),onClick:()=>ss({reresolve:!0}),className:"gap-1.5",children:[e.jsx(Qe,{className:"w-3.5 h-3.5"})," Reler do link"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ka,{children:"Cancelar"}),e.jsx(Ca,{disabled:!$.trim()||$.trim()===(v==null?void 0:v.name),onClick:()=>ss({name:$.trim()}),children:"Salvar nome"})]})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-border/40 space-y-2",children:[e.jsx("p",{className:"text-[12px] font-medium",children:"Link da página no provedor"}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60",children:"Trocar aqui quando a LoRA foi deletada e subida de novo — o id da página muda, e o link antigo passa a abrir uma página vazia. O arquivo segue gerando, então isso não aparece sozinho."}),(v==null?void 0:v.url)&&e.jsx("a",{href:v.url,target:"_blank",rel:"noopener noreferrer",className:"block text-[10px] font-mono text-primary/70 hover:text-primary truncate",children:v.url}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"text",value:C,onChange:j=>ee(j.target.value),placeholder:"https://www.runninghub.ai/model/public/…",className:"flex-1 h-9 px-3 rounded-md bg-background border border-border/40 text-sm font-mono outline-none focus:border-primary/60"}),e.jsx(y,{size:"sm",variant:"secondary",disabled:!C.trim(),onClick:()=>ss({url:C.trim()},j=>{var ne;return`Link trocado · arquivo: ${((ne=j==null?void 0:j.entry)==null?void 0:ne.name)??"-"}`}),children:"Trocar"})]})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-border/40 space-y-2",children:[e.jsx("p",{className:"text-[12px] font-medium",children:"Metadados do CivitAI"}),Z?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[10px] text-muted-foreground/60",children:"Relê a página e sobrescreve nome, base, versão, gatilhos, descrição e peso sugerido. O arquivo não é tocado — se você renomeou à mão, o nome do autor volta."}),e.jsx("a",{href:Z,target:"_blank",rel:"noopener noreferrer",className:"block text-[10px] font-mono text-primary/70 hover:text-primary truncate",children:Z})]}):e.jsx("p",{className:"text-[10px] text-muted-foreground/60",children:"Esta entrada não tem link do CivitAI salvo — cole um abaixo pra vincular e já trazer os dados."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"text",value:z,onChange:j=>Q(j.target.value),placeholder:Z?"colar outro link (opcional)":"https://civitai.com/models/…",className:"flex-1 h-9 px-3 rounded-md bg-background border border-border/40 text-sm font-mono outline-none focus:border-primary/60"}),e.jsxs(y,{size:"sm",variant:"secondary",disabled:!z.trim()&&!Z,onClick:()=>ss({civitaiUrl:z.trim()||Z},j=>{var ne;return`Atualizado: ${((ne=j==null?void 0:j.entry)==null?void 0:ne.label)??"-"}`}),className:"gap-1.5",children:[e.jsx(Qe,{className:"w-3.5 h-3.5"}),"Atualizar"]})]})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-border/40 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Trigger words"}
718),e.jsx("p",{className:"text-[11px] text-muted-foreground/70",children:"Separe por vírgula. Deixe vazio pra remover. Elas entram no prompt automaticamente quando a LoRA está marcada."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"text",value:ae,onChange:j=>Y(j.target.value),onKeyDown:j=>{j.key==="Enter"&&Ws()},placeholder:"PAWG, Thick",className:"flex-1 h-9 px-3 rounded-md bg-background border border-border/40 text-sm font-mono outline-none focus:border-primary/60"}),e.jsx(y,{size:"sm",variant:"secondary",onClick:Ws,children:"Salvar"})]})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-border/40 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Categorias"}),e.jsx("p",{className:"text-[11px] text-muted-foreground/70",children:'Separe por vírgula; a primeira agrupa a lista de geração. Existentes: realismo, fotografia, estetica, corpo, seios, genitalia, nudez, lingerie, bdsm, atos, utilidade. Vazio remove (cai em "outros").'}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"text",value:B,onChange:j=>G(j.target.value),onKeyDown:j=>{j.key==="Enter"&&Ia()},placeholder:"seios, realismo",className:"flex-1 h-9 px-3 rounded-md bg-background border border-border/40 text-sm font-mono outline-none focus:border-primary/60"}),e.jsx(y,{size:"sm",variant:"secondary",onClick:Ia,children:"Salvar"})]})]})]})}),e.jsx(va,{open:!!q,onOpenChange:j=>{j||E(null)},children:e.jsxs(ba,{children:[e.jsxs(Na,{children:[e.jsx(ya,{children:"Link do CivitAI"}),e.jsxs(_a,{children:['Traz nome, modelo base, versão, gatilhos, descrição e peso sugerido para "',(q==null?void 0:q.label)||(q==null?void 0:q.name),'".']})]}),e.jsx("input",{type:"text",value:P,onChange:j=>K(j.target.value),placeholder:"https://civitai.com/models/...",className:"h-9 px-3 rounded-md bg-background border border-border/40 text-sm font-mono outline-none focus:border-primary/60"}),e.jsxs(wa,{children:[e.jsx(ka,{children:"Cancelar"}),e.jsx(Ca,{disabled:!P.trim(),onClick:async()=>{const j=q,ne=P.trim();if(E(null),!(!j||!ne))try{await N({action:"lora-global-update",id:j.id,civitaiUrl:ne}),o.success("Informações atualizadas."),i()}catch(se){o.error(se.message||"Erro")}},children:"Buscar"})]})]})}),e.jsx(va,{open:!!J,onOpenChange:j=>{j||W(null)},children:e.jsxs(ba,{children:[e.jsxs(Na,{children:[e.jsx(ya,{children:"Remover do catálogo?"}),e.jsxs(_a,{children:['"',(J==null?void 0:J.label)||(J==null?void 0:J.name),'" some para TODOS os usuários. O arquivo continua no provedor — só sai da lista.']})]}),te&&te.presets>0&&e.jsxs("div",{className:"rounded-md border border-amber-400/30 bg-amber-400/[0.06] px-3 py-2",children:[e.jsxs("p",{className:"text-[12px] text-amber-200/90",children:[te.presets," preset(s) usam esta LoRA e vão aplicar sem ela."]}),te.exemplos.length>0&&e.jsx("p",{className:"text-[11px] text-amber-200/60 mt-0.5 truncate",children:te.exemplos.join(" · ")})]}),e.jsxs(wa,{children:[e.jsx(ka,{children:"Cancelar"}),e.jsx(Ca,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{const j=J;W(null),j&&O(j.id)},children:"Remover"})]})]})})]})}function tc({target:s,deleting:n,onCancel:c,onConfirm:u}){return e.jsx(ds,{open:!!s,onOpenChange:m=>!m&&!n&&c(),children:e.jsxs(cs,{className:"max-w-md",children:[e.jsx(ms,{children:e.jsxs(us,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(_s,{className:"w-4 h-4"})," Deletar do volume?"]})}),s&&e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsxs("p",{className:"font-mono text-xs bg-background/80 border border-border/40 rounded-md px-2.5 py-2 break-all",children:[s.name," · ",Tr(s.sizeBytes)]}),s.isPrefix&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Isto é uma pasta — ",e.jsx("strong",{children:"todos os arquivos dentro dela"})," serão removidos."]}),s.usedBy.length>0?e.jsxs("div",{className:"rounded-md border border-red-500/40 bg-red-500/10 px-3 py-2.5 space-y-1",children:[e.jsxs("p",{className:"text-xs font-semibold text-red-400 flex items-center gap-1.5",children:[e.jsx(qs,{className:"w-3.5 h-3.5"})," Workflows que VÃO QUEBRAR:"]}),e.jsx("ul",{className:"text-xs text-red-300 list-disc list-inside",children:s.usedBy.map(m=>e.jsx("li",{children:m},m))}),e.jsx("p",{className:"text-[10px] text-red-300/70",children:"Gerações destes workflows vão falhar até o arquivo ser baixado de novo pro volume."})]}):e.jsx("p",{className:"text-xs text-emerald-400",children:"Nenhum workflow de produção usa este arquivo."}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"A remoção é permanente no volume. Se o modelo estiver no backup (Drive/HuggingFace), dá pra baixar de novo depois."})]}),e.jsxs(Bs,{className:"gap-2",children:[e.jsx(y,{variant:"outline",onClick:c,disabled:n,children:"Cancelar"}),e.jsxs(y,{variant:"destructive",onClick:u,disabled:n,className:"gap-1.5",children:[n?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(_s,{className:"w-4 h-4"}),"Deletar permanentemente"]})]})]})})}const ht=({label:s,value:n,min:c,max:u,onChange:m})=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-semibold mb-1",children:s}),e.jsx("input",{type:"number",min:c,max:u,value:n,onChange:_=>m(parseInt(_.target.value||"0",10)),className:"w-24 h-8 px-2 rounded-md bg-background border border-border/40 text-sm text-center outline-none focus:border-primary/60"})]}),zs=({label:s,value:n,warn:c,hint:u})=>e.jsxs("div",{className:"rounded-lg border border-border/40 bg-background/60 px-3 py-2.5",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground font-semibold",children:s}),e.jsx("p",{className:Ue("text-lg font-bold mt-0.5",c?"text-amber-400":"text-foreground"),children:n}
718),u&&e.jsx("p",{className:"text-[10px] text-muted-foreground/60 -mt-0.5",children:u})]});function nc(s){const n=Date.now()-new Date(s).getTime(),c=Math.floor(n/6e4);if(c<1)return"now";if(c<60)return`${c}m`;const u=Math.floor(c/60);return u<24?`${u}h`:`${Math.floor(u/24)}d`}const ic=()=>{const{t:s}=kt(),{tickets:n,loading:c}=Li("all"),{ticketId:u}=kn(),m=fr(),[_,k]=r.useState("all"),[g,l]=r.useState(""),h=r.useMemo(()=>n.filter(R=>{if(_!=="all"&&R.status!==_)return!1;if(g.trim()){const $=g.toLowerCase();if(!R.subject.toLowerCase().includes($)&&!(R.email||"").toLowerCase().includes($))return!1}return!0}),[n,_,g]),x=Di(n,u),w=x?zt(x):null;r.useEffect(()=>{w&&w!==u&&m(`/admin/tickets/${w}`,{replace:!0})},[w,u,m]);const v=n.filter(R=>R.status==="open"||R.status==="waiting_user").length;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-primary/15 flex items-center justify-center",children:e.jsx(Pn,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"font-display text-lg font-bold leading-tight",children:s("admin.tickets.title")}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[s("admin.tickets.openCount",{count:v})," • ",n.length," ",s("admin.tickets.total")]})]})]}),e.jsxs("div",{className:"grid md:grid-cols-[320px_1fr] gap-3 h-[calc(100vh-220px)] min-h-[500px]",children:[e.jsxs("div",{className:"flex flex-col rounded-xl border border-border/40 bg-card/30 overflow-hidden",children:[e.jsxs("div",{className:"p-2 space-y-2 border-b border-border/40",children:[e.jsxs("div",{className:"relative",children:[e.jsx(aa,{className:"w-3.5 h-3.5 absolute left-2 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(je,{value:g,onChange:R=>l(R.target.value),placeholder:s("admin.tickets.searchPlaceholder"),className:"h-8 pl-7 text-xs"})]}),e.jsxs(as,{value:_,onValueChange:R=>k(R),children:[e.jsx(rs,{className:"h-8 text-xs",children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"all",children:s("admin.tickets.allStatuses")}),e.jsx(pe,{value:"open",children:s("support.status.open")}),e.jsx(pe,{value:"waiting_user",children:s("support.status.waiting_user")}),e.jsx(pe,{value:"resolved",children:s("support.status.resolved")}),e.jsx(pe,{value:"closed",children:s("support.status.closed")})]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto scrollbar-thin",children:c?e.jsx("div",{className:"flex justify-center p-8",children:e.jsx(he,{className:"w-5 h-5 animate-spin text-muted-foreground"})}):h.length===0?e.jsx("p",{className:"text-center text-xs text-muted-foreground p-6",children:s("admin.tickets.emptyFiltered")}):e.jsx("ul",{className:"divide-y divide-border/30",children:h.map(R=>{const $=R.id===(x==null?void 0:x.id);return e.jsx("li",{children:e.jsxs("button",{onClick:()=>m(`/admin/tickets/${zt(R)}`),className:`w-full text-left px-3 py-2.5 hover:bg-secondary/40 transition-colors ${$?"bg-secondary/60":""}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("p",{className:"text-sm font-medium truncate flex-1",children:R.subject}),e.jsx("span",{className:"text-[10px] text-muted-foreground shrink-0",children:nc(R.last_message_at)})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground truncate mt-0.5",children:R.email||R.user_id.slice(0,8)}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[e.jsx(Oi,{status:R.status}),e.jsx("span",{className:"text-[10px] text-muted-foreground/70",children:s(`support.categories.${R.category}`)})]})]})},R.id)})})})]}),e.jsx("div",{className:"rounded-xl border border-border/40 bg-card/30 overflow-hidden flex flex-col min-h-0",children:u&&!x?e.jsx("p",{role:"status",className:"p-6 text-sm text-muted-foreground",children:s(c?"common.loading":"support.ticketUnavailable")}):e.jsx(Mi,{ticket:x,isAdmin:!0},x==null?void 0:x.id)})]})]})},oc={geometry:"Geometria",color:"Cor",texture:"Textura",marker:"Marcadores",timing:"Tempo",audio:"Áudio",encoder:"Encoder",layout:"Enquadramento"},lc={geometry:"Crop, rotação, flip, perspective — alteram a estrutura geométrica do frame.",color:"Hue, brilho, contraste, saturação e temperatura — alteram a paleta sem mudar conteúdo.",texture:"Ruído, granulação, blur, vinheta e borda — alteram a textura visual.",marker:"Marcadores opcionais usados pra rastreio interno (não camuflam).",timing:"Velocidade, frame rate e padding de intro — alteram tempo e amostragem temporal.",audio:"Pitch shift do áudio independente da velocidade — quebra fingerprints de áudio.",encoder:"Parâmetros do x264 — variar GOP/preset/CRF muda a assinatura do bitstream.",layout:"Aspect ratio é controlado pelo seletor de Plataforma na UI principal. Este campo aqui só pra referência."},dc=[{key:"cropPixels",label:"Crop",kind:"slider",group:"geometry",min:0,max:20,step:1,format:s=>`${s} px`,description:"Pixels removidos de cada lado (simétrico)."},{key:"cropAsymmetry",label:"Assimetria do crop",kind:"slider",group:"geometry",min:0,max:10,step:1,format:s=>`±${s} px`,description:"Quanto cada lado pode variar do crop base. Quebra o grid do pHash."},{key:"rotateDeg",label:"Rotação",kind:"slider",group:"geometry",min:0,max:3,step:.1,format:s=>`${s.toFixed(1)}°`},{key:"perspectiveSkew",label:"Perspective skew",kind:"slider",group:"geometry",min:0,max:2,step:.1,format:s=>s===0?"off":`${s.toFixed(1)}°`,description:"Distorção 2D sutil. Quebra DCT mais que rotação pura."},{key:"scaleRoundtrip",label:"Scale roundtrip",kind:"slider",group:"geometry",min:1,max:1.1,step:.01,format:s=>s<=1.001?"off":`${s.toFixed(2)}×`,description:"Upscale e volta — força re-resample de todos os pixels."},{key:"subPixelShift",label:"Sub-pixel shift",kind:"slider",group:"geometry",min:0,max:1.5,step:.1,format:s=>s===0?"off":`±${s.toFixed(1)} px`,description:"Desloca o centro por valor sub-pixel antes do draw. Quebra alinhamento JPEG block grid contra pixels — custo zero, ganho alto."},{key:"barrelDistortion",label:"Lens distortion",kind:"slider",group:"geometry",min:-.15,max:.15,step:.01,format:s=>s===0?"off":s>0?`+${s.toFixed(2)} barril`:`${s.toFixed(2)} pincushion`,description:"Distorção radial não-linear. Positivo = wide-angle (barril), negativo = pincushion."},{key:"flipHorizontal",label:"Espelhar horizontal",kind:"toggle",group:"geometry",description:"Cuidado: TikTok/Meta detectam flips explicitamente."},{key:"hueShift",label:"Hue shift",kind:"slider",group:"color",min:-30,max:30,step:1,format:s=>`${s}°`},{key:"brightness",label:"Brilho",kind:"slider",group:"color",min:.8,max:1.2,step:.01,format:s=>s.toFixed(2)},{key:"contrast",label:"Contraste",kind:"slider",group:"color",min:.8,max:1.2,step:.01,format:s=>s.toFixed(2)},{key:"saturation",label:"Saturação",kind:"slider",group:"color",min:.5,max:1.5,step:.
71801,format:s=>s.toFixed(2)},{key:"temperature",label:"Temperatura",kind:"slider",group:"color",min:-30,max:30,step:1,format:s=>s===0?"neutro":s>0?`+${s} quente`:`${s} frio`,description:"Desloca R/B. Independente do hue."},{key:"luminanceCurve",label:"Curva tonal",kind:"slider",group:"color",min:-.3,max:.3,step:.02,format:s=>s===0?"neutro":s>0?`+${s.toFixed(2)} S-curve`:`${s.toFixed(2)} lift`,description:"S-curve = aumenta contraste tonal (sombra → mais escura, alta-luz → mais clara). Negativo = inverso (lift shadows)."},{key:"vibrance",label:"Vibrance seletiva",kind:"slider",group:"color",min:0,max:.5,step:.02,format:s=>s===0?"off":s.toFixed(2),description:"Aumenta saturação só onde já não está saturado. Mimic camera de celular."},{key:"noiseAmount",label:"Ruído RGB",kind:"slider",group:"texture",min:0,max:30,step:1},{key:"filmGrain",label:"Film grain",kind:"slider",group:"texture",min:0,max:30,step:1},{key:"perlinAmount",label:"Perlin grain",kind:"slider",group:"texture",min:0,max:30,step:1,description:"Noise estruturada com correlação espacial. Parece grain de filme/foto real, menos detectável como noise injetado."},{key:"chromaticAberration",label:"Chromatic aberration",kind:"slider",group:"texture",min:0,max:3,step:.1,format:s=>s===0?"off":`${s.toFixed(1)} px`,description:"Offset R/B por px sub-pixel. Mimic de lente barata. Quebra hashes baseados em edges."},{key:"claheAmount",label:"Local contrast (CLAHE)",kind:"slider",group:"texture",min:0,max:1,step:.05,format:s=>s===0?"off":s.toFixed(2),description:"Aumenta contraste local por região (mimic HDR de celular)."},{key:"microBlur",label:"Micro blur",kind:"slider",group:"texture",min:0,max:2,step:.1,format:s=>`${s.toFixed(1)} px`},{key:"vignette",label:"Vinheta",kind:"slider",group:"texture",min:0,max:.6,step:.02,format:s=>s.toFixed(2)},{key:"border",label:"Borda",kind:"slider",group:"texture",min:0,max:40,step:1,format:s=>`${s} px`},{key:"jpegRecompress",label:"Two-pass JPEG",kind:"toggle",group:"texture",description:"Encode + decode + shift de 4-7px + re-encode. Re-alinha DCT grid e quebra fingerprint de bloco JPEG."},{key:"invisiblePixel",label:"Pixel invisível",kind:"toggle",group:"marker",description:"Marcador único por arquivo. Não camufla contra pHash."}],cc=[{key:"cropPixels",label:"Crop",kind:"slider",group:"geometry",min:0,max:20,step:1,format:s=>`${s} px`},{key:"cropAsymmetry",label:"Assimetria do crop",kind:"slider",group:"geometry",min:0,max:10,step:1,format:s=>`±${s} px`,description:"Quanto cada lado pode variar do crop base."},{key:"rotateDeg",label:"Rotação",kind:"slider",group:"geometry",min:0,max:3,step:.1,format:s=>`${s.toFixed(1)}°`},{key:"perspectiveSkew",label:"Perspective skew",kind:"slider",group:"geometry",min:0,max:2,step:.1,format:s=>s===0?"off":`${s.toFixed(1)}°`},{key:"scaleRoundtrip",label:"Scale roundtrip",kind:"slider",group:"geometry",min:1,max:1.1,step:.01,format:s=>s<=1.001?"off":`${s.toFixed(2)}×`},{key:"flipHorizontal",label:"Espelhar horizontal",kind:"toggle",group:"geometry",description:"TikTok/Meta detectam flips explicitamente."},{key:"hueShift",label:"Hue shift",kind:"slider",group:"color",min:-30,max:30,step:1,format:s=>`${s}°`},{key:"brightness",label:"Brilho",kind:"slider",group:"color",min:-.2,max:.2,step:.01,format:s=>s.toFixed(2)},{key:"contrast",label:"Contraste",kind:"slider",group:"color",min:.8,max:1.3,step:.01,format:s=>s.toFixed(2)},{key:"saturation",label:"Saturação",kind:"slider",group:"color",min:.5,max:1.8,step:.01,format:s=>s.toFixed(2)},{key:"temperature",label:"Temperatura",kind:"slider",group:"color",min:-30,max:30,step:1,format:s=>s===0?"neutro":s>0?`+${s} quente`:`${s} frio`},{key:"noiseStrength",label:"Ruído",kind:"slider",group:"texture",min:0,max:40,step:1},{key:"speed",label:"Velocidade",kind:"slider",group:"timing",min:.9,max:1.1,step:.01,format:s=>`${s.toFixed(2)}×`},{key:"targetFps",label:"Frame rate alvo",kind:"slider",group:"timing",min:0,max:60,step:.01,format:s=>s===0?"manter original":`${s.toFixed(2)} fps`,description:"0 = manter. 29.97 / 24 / 30.5 quebram amostragem temporal."},{key:"introPadding",label:"Padding de intro",kind:"slider",group:"timing",min:0,max:1e3,step:50,format:s=>s===0?"off":`${s} ms`,description:"Black frames + silêncio antes do conteúdo. Shifta keyframes."},{key:"pitchShift",label:"Pitch shift",kind:"slider",group:"audio",min:-6,max:6,step:.5,format:s=>s===0?"neutro":`${s>0?"+":""}${s.toFixed(1)}%`,description:"Altera pitch sem mexer no tempo. Quebra Chromaprint. Não engana Content ID em música licenciada."},{key:"gopJitter",label:"Randomizar GOP",kind:"toggle",group:"encoder",description:"Keyframe interval randômico por render (30-90 frames)."},{key:"encoderJitter",label:"Variar parâmetros x264",kind:"toggle",group:"encoder",description:"Preset/CRF/tune aleatórios por render — muda assinatura do bitstream."}];function mc(s){const n=new Map;for(const c of s){const u=n.get(c.group)??[];u.push(c),n.set(c.group,u)}return n}const uc=["geometry","color","texture","timing","audio","encoder","marker","layout"],hn="cloak_presets";function pt(s){const n={},c={};for(const u of qn)n[u]={...s.image[u]},c[u]={...s.video[u]};return{image:n,video:c}}function xc(){const[s,n]=r.useState(()=>pt(Vt)),[c,u]=r.useState("image"),[m,_]=r.useState("medium"),[k,g]=r.useState(!0),[l,h]=r.useState(!1);r.useEffect(()=>{F.from("admin_settings").select("value").eq("key",hn).maybeSingle().then(({data:C}
718)=>{if(C!=null&&C.value)try{n(So(JSON.parse(C.value)))}catch{}g(!1)})},[]);const w=mc(c==="image"?dc:cc),v=s[c][m],R=(C,ee)=>{n(Z=>{const p=pt(Z);return p[c][m][C]=ee,p})},$=()=>{n(C=>{const ee=pt(C);return ee[c][m]={...Vt[c][m]},ee}),o.message("Preset restaurado pro padrão (salve pra aplicar).")},V=async()=>{h(!0);const{error:C}=await F.from("admin_settings").upsert({key:hn,value:JSON.stringify(s)},{onConflict:"key"});h(!1),C?o.error("Falha ao salvar presets."):o.success("Presets do camuflador salvos.")};return k?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-primary"})}):e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"font-display text-xl font-bold tracking-tight flex items-center gap-2",children:[e.jsx(Cn,{className:"w-5 h-5 text-primary"}),"Camuflador — Presets"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 max-w-2xl",children:['Ajuste as intensidades (Leve/Médio/Forte/UGC) usadas no app "Camuflar Criativos". Salvo em ',e.jsx("span",{className:"font-mono text-xs",children:"admin_settings.cloak_presets"})," e aplicado pra todos os usuários (com fallback pros defaults)."]})]}),e.jsxs(y,{onClick:V,disabled:l,className:"gap-2 shrink-0",children:[l?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(Zs,{className:"w-4 h-4"}),"Salvar e aplicar"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("div",{className:"inline-flex rounded-lg border border-border/50 bg-card/40 p-1",children:["image","video"].map(C=>e.jsx("button",{onClick:()=>u(C),className:Ue("px-3 py-1.5 rounded-md text-xs font-semibold transition-all",c===C?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"),children:C==="image"?"Imagem":"Vídeo"},C))}),e.jsx("div",{className:"inline-flex flex-wrap gap-1.5",children:qn.map(C=>e.jsx("button",{onClick:()=>_(C),className:Ue("px-3 py-1.5 rounded-full text-xs font-medium border transition-all",m===C?"bg-primary text-primary-foreground border-primary":"border-border/50 bg-card/40 text-muted-foreground hover:text-foreground"),children:Ao[C]},C))}),e.jsxs(y,{variant:"ghost",size:"sm",onClick:$,className:"gap-1.5 text-muted-foreground hover:text-foreground ml-auto",children:[e.jsx(ir,{className:"w-3.5 h-3.5"})," Restaurar padrão"]})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-4",children:uc.map(C=>{const ee=w.get(C);return!ee||ee.length===0?null:e.jsxs("div",{className:"rounded-xl border border-border/40 bg-card/30 p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:oc[C]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug mt-0.5",children:lc[C]})]}),e.jsx("div",{className:"space-y-3",children:ee.map(Z=>{const p=v[Z.key];return Z.kind==="toggle"?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vs,{checked:!!p,onCheckedChange:z=>R(Z.key,z)}),e.jsxs("div",{className:"flex-1",children:[e.jsx("span",{className:"text-xs font-medium",children:Z.label}),Z.description&&e.jsx("p",{className:"text-[10px] text-muted-foreground leading-tight",children:Z.description})]})]},Z.key):e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium",children:Z.label}),e.jsx("span",{className:"text-[10px] font-mono text-primary",children:Z.format?Z.format(p):String(p)})]}),e.jsx(Co,{value:[p],onValueChange:z=>R(Z.key,z[0]),min:Z.min??0,max:Z.max??1,step:Z.step??.01}),Z.description&&e.jsx("p",{className:"text-[10px] text-muted-foreground leading-tight",children:Z.description})]},Z.key)})})]},C)})})]})}async function vs(s){const{data:n,error:c}=await F.functions.invoke("admin-mailbox",{body:s});if(c)throw new Error(c.message||"Falha ao acessar a caixa de e-mail");if(n!=null&&n.error)throw new Error(n.error);return n}const pn=(s,n,c=20,u)=>vs({action:"list",view:s,limit:c,...n?{after:n}:{}
718,...u!=null&&u.trim()?{search:u.trim()}:{}}),hc=async(s,n)=>(await vs({action:"get",folder:s,id:n})).message,pc=async(s,n)=>(await vs({action:"get-attachments",folder:s,id:n})).attachments,gc=async s=>(await vs({action:"list-thread",id:s})).messages,wr=(s,n)=>vs({action:"update-state",items:s,patch:n}),jc=()=>vs({action:"get-notification-settings"}),fc=s=>vs({action:"save-notification-settings",...s}),vc=()=>vs({action:"list-folders"}),bc=s=>vs({action:"create-folder",name:s}),Nc=(s,n)=>vs({action:"rename-folder",id:s,name:n}),yc=s=>vs({action:"delete-folder",id:s}),_c=async()=>(await vs({action:"get-settings"})).settings,wc=s=>vs({action:"save-settings",settings:s}),kc=async()=>(await vs({action:"list-drafts"})).drafts,Cc=s=>vs({action:"save-draft",draft:s}),Sc=s=>vs({action:"delete-draft",id:s}),Ac=async s=>(await vs({action:"list-notes",id:s})).notes,Ec=async(s,n)=>(await vs({action:"add-note",id:s,note:n})).note,Rc=s=>vs({action:"cancel-send",id:s}),Pc=async()=>(await vs({action:"list-rules"})).rules,Ic=s=>vs({action:"save-rule",rule:s}),Tc=s=>vs({action:"delete-rule",id:s}),ni=async()=>(await vs({action:"list-templates"})).templates,Lc=s=>vs({action:"save-template",template:s}),Dc=s=>vs({action:"delete-template",id:s}),Oc=async()=>(await vs({action:"report"})).rows;async function Mc(s){const n=s.name.replace(/[^a-zA-Z0-9._-]/g,"_").slice(-180),c=`drafts/${crypto.randomUUID()}/${n}`,{error:u}=await F.storage.from("admin-mailbox").upload(c,s,{contentType:s.type||"application/octet-stream"});if(u)throw u;return{filename:s.name,path:c}}const Fc=s=>vs({action:"send",...s});function Qa(s){return s.split(/[;,]/).map(n=>n.trim()).filter(Boolean)}function Ur(s){const n=s.match(/^\s*([^<]+?)\s*<([^>]+)>\s*$/);return n?{name:n[1].trim(),email:n[2].trim()}:{name:s,email:s}}function Uc(s){return s?{delivered:"Entregue",opened:"Aberto",clicked:"Clicado",bounced:"Rejeitado",complained:"Spam",sent:"Enviado",scheduled:"Agendado",delivery_delayed:"Atrasado"}[s]||s.replace(/_/g," "):"Enviado"}function xr(s){var n;return{id:s.id,source_folder:s.source_folder,from:s.from,to:s.to,subject:s.subject,created_at:s.created_at,has_attachments:s.has_attachments??!!((n=s.attachments)!=null&&n.length)}}function $c(s,n){var c;return n==="unread"?!s.is_read:n==="read"?s.is_read:n==="replied"?s.source_folder==="inbox"&&s.is_replied:n==="pending_reply"?s.source_folder==="inbox"&&!s.is_replied:n==="attachments"?s.has_attachments??!!((c=s.attachments)!=null&&c.length):!0}const gn={name:"",match_field:"from",match_operator:"contains",match_value:"",target_folder_id:"",mark_read:!1,enabled:!0,position:100},jn={name:"",subject:"",body:""};function zc({open:s,onOpenChange:n,folders:c,onTemplatesChange:u}){const[m,_]=r.useState([]),[k,g]=r.useState([]),[l,h]=r.useState(gn),[x,w]=r.useState(jn),[v,R]=r.useState(!1),[$,V]=r.useState(!1),C=r.useCallback(async()=>{V(!0);try{const[p,z]=await Promise.all([Pc(),ni()]);_(p),g(z),u(z)}catch(p){o.error("Não foi possível carregar automações",{description:p instanceof Error?p.message:void 0})}finally{V(!1)}},[u]);r.useEffect(()=>{s&&C()},[C,s]);const ee=async p=>{p.preventDefault(),R(!0);try{await Ic(l),h(gn),await C(),o.success("Regra salva")}catch(z){o.error("Falha ao salvar regra",{description:z instanceof Error?z.message:void 0})}finally{R(!1)}},Z=async p=>{p.preventDefault(),R(!0);try{await Lc(x),w(jn),await C(),o.success("Resposta pronta salva")}catch(z){o.error("Falha ao salvar resposta",{description:z instanceof Error?z.message:void 0})}finally{R(!1)}};return e.jsx(ds,{open:s,onOpenChange:n,children:e.jsxs(cs,{className:"max-h-[90dvh] overflow-y-auto sm:max-w-3xl",children:[e.jsxs(ms,{children:[e.jsx(us,{children:"Produtividade da caixa"}),e.jsx(ra,{children:"Organize novos e-mails automaticamente e reutilize respostas frequentes."})]}),e.jsxs(za,{defaultValue:"rules",children:[e.jsxs(Ba,{children:[e.jsx(Fs,{value:"rules",children:"Regras"}),e.jsx(Fs,{value:"templates",children:"Respostas prontas"})]}),e.jsxs(Qs,{value:"rules",className:"space-y-5 pt-3",children:[e.jsxs("form",{onSubmit:ee,className:"space-y-4 rounded-xl border p-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"rule-name",children:"Nome da regra"}),e.jsx(je,{id:"rule-name",value:l.name,onChange:p=>h(z=>({...z,name:p.target.value})),required:!0,maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Pasta de destino"}),e.jsxs(as,{value:l.target_folder_id,onValueChange:p=>h(z=>({...z,target_folder_id:p})),required:!0,children:[e.jsx(rs,{children:e.jsx(ts,{placeholder:"Escolha a pasta"})}),e.jsx(ns,{children:c.map(p=>e.jsx(pe,{value:p.id,children:p.name},p.id))})]})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Campo"}),e.jsxs(as,{value:l.match_field,onValueChange:p=>h(z=>({...z,match_field:p})),children:[e.jsx(rs,{children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"from",children:"Remetente"}),e.jsx(pe,{value:"to",children:"Destinatário"}
718),e.jsx(pe,{value:"subject",children:"Assunto"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Condição"}),e.jsxs(as,{value:l.match_operator,onValueChange:p=>h(z=>({...z,match_operator:p})),children:[e.jsx(rs,{children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"contains",children:"Contém"}),e.jsx(pe,{value:"equals",children:"É igual"}),e.jsx(pe,{value:"ends_with",children:"Termina com"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"rule-value",children:"Valor"}),e.jsx(je,{id:"rule-value",value:l.match_value,onChange:p=>h(z=>({...z,match_value:p.target.value})),required:!0,maxLength:320})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Vs,{checked:l.mark_read,onCheckedChange:p=>h(z=>({...z,mark_read:p}))}),"Marcar como lido"]}),e.jsxs(y,{disabled:v||!c.length,className:"gap-2",children:[e.jsx(Us,{className:"h-4 w-4"}),"Salvar regra"]})]}),c.length?e.jsx("p",{className:"text-xs text-muted-foreground",children:"Vale para novos recebimentos. A primeira regra compatível será aplicada."}):e.jsx("p",{className:"text-xs text-amber-500",children:"Crie uma pasta antes de criar regras."})]}),$?e.jsx(he,{className:"mx-auto h-5 w-5 animate-spin"}):e.jsx("div",{className:"space-y-2",children:m.map(p=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:p.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[p.match_field," · ",p.match_operator," · ",p.match_value]})]}),e.jsx(y,{size:"icon",variant:"ghost","aria-label":`Excluir ${p.name}`,onClick:async()=>{await Tc(p.id),await C(),o.success("Regra excluída")},children:e.jsx(_s,{className:"h-4 w-4"})})]},p.id))})]}),e.jsxs(Qs,{value:"templates",className:"space-y-5 pt-3",children:[e.jsxs("form",{onSubmit:Z,className:"space-y-4 rounded-xl border p-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"template-name",children:"Nome"}),e.jsx(je,{id:"template-name",value:x.name,onChange:p=>w(z=>({...z,name:p.target.value})),required:!0,maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"template-subject",children:"Assunto opcional"}),e.jsx(je,{id:"template-subject",value:x.subject,onChange:p=>w(z=>({...z,subject:p.target.value})),maxLength:998})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"template-body",children:"Resposta"}),e.jsx(Ss,{id:"template-body",rows:7,value:x.body,onChange:p=>w(z=>({...z,body:p.target.value})),required:!0,maxLength:1e4})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(y,{disabled:v,className:"gap-2",children:[e.jsx(Us,{className:"h-4 w-4"}),"Salvar resposta"]})})]}),e.jsx("div",{className:"space-y-2",children:k.map(p=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium",children:p.name}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:p.subject||p.body})]}),e.jsx(y,{size:"icon",variant:"ghost","aria-label":`Excluir ${p.name}`,onClick:async()=>{await Dc(p.id),await C(),o.success("Resposta excluída")},children:e.jsx(_s,{className:"h-4 w-4"})})]},p.id))})]})]})]})})}function _t(s,n){if(!n.length)return!1;const c=[...new Set(n.flatMap(g=>Object.keys(g)))],u=g=>`"${(Array.isArray(g)?g.join("; "):g==null?"":String(g)).split('"').join('""')}"`,m=`\uFEFF${c.map(u).join(",")}\r
719${n.map(g=>c.map(l=>u(g[l])).join(",")).join(`\r
720`)}`,_=URL.createObjectURL(new Blob([m],{type:"text/csv;charset=utf-8"})),k=document.createElement("a");return k.href=_,k.download=s,k.click(),URL.revokeObjectURL(_),!0}const Bc=[{id:"inbox",label:"Recebidos",icon:Qn},{id:"sent",label:"Enviados",icon:It},{id:"starred",label:"Favoritos",icon:ar}
720,{id:"archive",label:"Arquivados",icon:qa},{id:"spam",label:"Spam",icon:Tt},{id:"trash",label:"Lixeira",icon:_s}],wt=s=>{const n=new Date(s);return Wo(n)?Aa(n,"HH:mm"):Ko(n)?"Ontem":Aa(n,"dd 'de' MMM",{locale:Mr})},qc=s=>s==="bounced"||s==="complained"?"destructive":s==="opened"||s==="clicked"||s==="delivered"?"default":"secondary",Vc=(s,n)=>{if(n||typeof DOMParser>"u")return s;const c=new DOMParser().parseFromString(s,"text/html");return c.querySelectorAll("img").forEach(u=>{const m=u.getAttribute("src")||"";/^https?:/i.test(m)&&(u.removeAttribute("src"),u.setAttribute("data-blocked-src",m),u.setAttribute("alt",u.getAttribute("alt")||"Imagem externa bloqueada"))}),`<!doctype html>${c.documentElement.outerHTML}`},kr=()=>({to:"",cc:"",bcc:"",subject:"",body:"",replyingTo:null,draftKey:`new_${crypto.randomUUID()}`,idempotencyKey:`admin_${crypto.randomUUID().replace(/-/g,"_")}`,scheduledAt:"",attachments:[]}),ii=({folders:s,messages:n,disabled:c,onMove:u,onCreate:m})=>{const _=n.length&&n.every(k=>k.custom_folder_id===n[0].custom_folder_id)?n[0].custom_folder_id:void 0;return e.jsxs(Gn,{children:[e.jsx(Wn,{asChild:!0,children:e.jsxs(y,{type:"button",variant:"ghost",size:"sm",disabled:c,className:"gap-2",children:[e.jsx(Tn,{className:"h-4 w-4","aria-hidden":"true"}),"Pasta"]})}),e.jsxs(Kn,{align:"start",className:"min-w-52",children:[s.map(k=>e.jsxs(gr,{onClick:()=>u(k.id,k.name),className:"gap-2",children:[e.jsx("span",{className:"w-4",children:_===k.id?e.jsx(Ea,{className:"h-4 w-4","aria-hidden":"true"}):null}),e.jsx("span",{className:"truncate",children:k.name})]},k.id)),s.length?e.jsx(ft,{}):null,n.some(k=>k.custom_folder_id)?e.jsxs(e.Fragment,{children:[e.jsxs(gr,{onClick:()=>u(null),className:"gap-2",children:[e.jsx(Ga,{className:"h-4 w-4","aria-hidden":"true"}),"Remover da pasta"]}),e.jsx(ft,{})]}):null,e.jsxs(gr,{onClick:m,className:"gap-2",children:[e.jsx(Et,{className:"h-4 w-4","aria-hidden":"true"}),"Criar nova pasta"]})]})]})},Gc=({message:s,selected:n,checked:c,updating:u,dragging:m,canDrag:_,actions:k})=>{var Z;const g=r.useRef(null),l=r.useRef(!1),h=r.useRef(!1),x=r.useRef({x:0,y:0}),w=s.source_folder==="inbox"?Ur(s.from):{name:s.to.join(", "),email:s.to.join(", ")},v=s.has_attachments??!!((Z=s.attachments)!=null&&Z.length),R=v||s.source_folder==="inbox"&&s.is_replied||s.priority==="urgent"||s.priority==="high"||s.workflow_status==="resolved"||s.source_folder==="sent",$=()=>{g.current&&clearTimeout(g.current),g.current=null};r.useEffect(()=>()=>{g.current&&clearTimeout(g.current)},[]);const V=p=>{var Q;if(!_||p.pointerType==="mouse"&&p.button!==0)return;x.current={x:p.clientX,y:p.clientY};const z=p.currentTarget;if($(),p.pointerType==="mouse"){(Q=z.setPointerCapture)==null||Q.call(z,p.pointerId);return}g.current=setTimeout(()=>{var ae;l.current=!0,h.current=!0,(ae=z.setPointerCapture)==null||ae.call(z,p.pointerId),k.beginDrag(s,{x:p.clientX,y:p.clientY})},400)},C=p=>{const z=Math.hypot(p.clientX-x.current.x,p.clientY-x.current.y);!l.current&&p.pointerType==="mouse"&&p.buttons&1&&z>8?(l.current=!0,h.current=!0,k.beginDrag(s,{x:p.clientX,y:p.clientY})):!l.current&&z>8&&$(),l.current&&(p.preventDefault(),k.updatePointerDrag(p.clientX,p.clientY))},ee=p=>{$(),l.current&&(p.preventDefault(),l.current=!1,k.finishPointerDrag())};return e.jsxs("div",{style:{contentVisibility:"auto",containIntrinsicSize:"88px"},className:`group grid grid-cols-[2.5rem_minmax(0,1fr)] border-b border-border px-3 transition-[background-color,opacity] hover:bg-muted/40 ${n?"bg-muted/60":""} ${m?"bg-primary/10 opacity-60":""}`,children:[e.jsxs("div",{className:"flex shrink-0 flex-col items-center gap-1 py-3",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center",children:e.jsx(Vn,{checked:c,onCheckedChange:()=>k.toggleChecked(s.id),"aria-label":`Selecionar ${s.subject||"e-mail sem assunto"}`})}),e.jsx(y,{size:"icon",variant:"ghost",className:"h-8 w-8",disabled:u,onClick:()=>void k.changeState([s],{is_starred:!s.is_starred},s.is_starred?"Removido dos favoritos":"Adicionado aos favoritos"),"aria-label":s.is_starred?"Remover dos favoritos":"Adicionar aos favoritos",children:e.jsx(ar,{className:`h-4 w-4 ${s.is_starred?"fill-amber-400 text-amber-500":"text-muted-foreground"}`})})]}),e.jsxs("button",{onPointerDown:V,onPointerMove:C,onPointerUp:ee,onPointerCancel:()=>{$(),l.current=!1,h.current=!1,k.cancelDrag()},onClick:()=>
720{if(h.current){h.current=!1;return}k.openMessage(s)},className:`grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] content-start gap-x-2 px-2 py-3 pr-1 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring ${_?"cursor-grab active:cursor-grabbing":""}`,"aria-label":`${w.name} ${wt(s.created_at)} ${s.subject||"(Sem assunto)"}${v?" Possui anexo":""}`,children:[e.jsx(To,{className:`col-start-1 row-span-3 mt-0.5 h-4 w-4 text-muted-foreground transition-opacity ${_?"opacity-40 group-hover:opacity-100":"opacity-0"}`,"aria-hidden":"true"}),e.jsxs("div",{className:"col-start-2 flex min-w-0 items-start justify-between gap-3",children:[e.jsxs("span",{className:`flex min-w-0 items-center gap-2 truncate text-sm leading-5 ${s.is_read?"font-medium":"font-bold"}`,children:[s.is_read?null:e.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full bg-primary","aria-label":"Não lido"}),e.jsx("span",{className:"truncate",children:w.name})]}),e.jsx("time",{className:"shrink-0 pt-0.5 text-xs text-muted-foreground",children:wt(s.created_at)})]}),e.jsx("p",{className:`col-start-2 mt-1.5 truncate text-sm leading-5 ${s.is_read?"text-muted-foreground":"font-semibold text-foreground"}`,children:s.subject||"(Sem assunto)"}),R?e.jsxs("div",{className:"col-start-2 mt-2.5 flex min-h-6 flex-wrap items-center gap-2",children:[v?e.jsx(Fr,{className:"h-3.5 w-3.5 text-muted-foreground","aria-label":"Possui anexo"}):null,s.source_folder==="inbox"&&s.is_replied?e.jsxs(Re,{variant:"secondary",className:"gap-1 text-xs",children:[e.jsx(Er,{className:"h-3 w-3","aria-hidden":"true"}),"Respondido"]}):null,s.priority==="urgent"||s.priority==="high"?e.jsx(Re,{variant:"destructive",className:"text-xs",children:s.priority==="urgent"?"Urgente":"Alta"}):null,s.workflow_status==="resolved"?e.jsx(Re,{variant:"outline",className:"text-xs",children:"Resolvido"}):null,s.source_folder==="sent"&&e.jsx(Re,{variant:qc(s.last_event),className:"text-xs",children:Uc(s.last_event)})]}):null]})]})},Wc=({enabled:s,loading:n,hasMore:c,onLoad:u})=>{const m=r.useRef(null);return r.useEffect(()=>{const _=m.current;if(!s||n||!c||!_)return;const k=_.closest("[data-radix-scroll-area-viewport]"),g=new IntersectionObserver(([l])=>{l.isIntersecting&&(g.disconnect(),u())},{root:k,rootMargin:"160px 0px"});return g.observe(_),()=>g.disconnect()},[s,c,n,u]),s?e.jsx("div",{ref:m,className:"px-3 py-4 text-center text-xs text-muted-foreground","aria-live":"polite",children:n?"Carregando mais e-mails…":c?"Role para carregar mais":"Fim da lista"}):null},Kc=({state:s,actions:n})=>e.jsxs("section",{className:`${s.selected?"hidden xl:flex":"flex"} min-h-0 flex-col border-r border-border`,"aria-label":"Lista de e-mails",children:[e.jsxs("div",{className:"space-y-3 border-b border-border p-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(aa,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground","aria-hidden":"true"}),e.jsx(je,{id:"mailbox-search",value:s.search,onChange:c=>n.setSearch(c.target.value),placeholder:"Buscar em toda a caixa",className:"min-h-11 pl-9","aria-label":"Buscar e-mails"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vn,{checked:s.allVisibleChecked,onCheckedChange:n.toggleAllVisible,"aria-label":"Selecionar e-mails visíveis"}),e.jsxs(as,{value:s.filter,onValueChange:c=>n.setFilter(c),children:[e.jsx(rs,{className:"min-h-11 flex-1","aria-label":"Filtrar mensagens",children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"all",children:"Todos"}),e.jsx(pe,{value:"unread",children:"Não lidos"}),e.jsx(pe,{value:"read",children:"Lidos"}),e.jsx(pe,{value:"replied",children:"Respondidos"}),e.jsx(pe,{value:"pending_reply",children:"A responder"}),e.jsx(pe,{value:"attachments",children:"Com anexos"})]})]})]}),s.checkedMessages.length?e.jsxs("div",{className:"flex flex-wrap gap-1 rounded-lg bg-muted/50 p-2",role:"toolbar","aria-label":"Ações nos e-mails selecionados",children:[e.jsx(ii,{folders:s.folders,messages:s.checkedMessages,disabled:s.activity.updating,onMove:(c,u)=>void n.changeState(s.checkedMessages,{custom_folder_id:c},c?`Salvos em ${u}
720`:"Removidos da pasta"),onCreate:n.openFolderEditor}),s.checkedMessages.some(c=>c.source_folder==="inbox")?e.jsxs(e.Fragment,{children:[e.jsx(y,{size:"sm",variant:"ghost",disabled:s.activity.updating,onClick:()=>void n.changeState(s.checkedMessages.filter(c=>c.source_folder==="inbox"),{is_read:!0},"Marcados como lidos"),"aria-label":"Marcar como lidos",children:e.jsx(Po,{className:"h-4 w-4"})}),e.jsx(y,{size:"sm",variant:"ghost",disabled:s.activity.updating,onClick:()=>void n.changeState(s.checkedMessages.filter(c=>c.source_folder==="inbox"),{is_read:!1},"Marcados como não lidos"),"aria-label":"Marcar como não lidos",children:e.jsx(Zn,{className:"h-4 w-4"})})]}):null,s.view==="archive"||s.view==="spam"||s.view==="trash"?e.jsx(y,{size:"sm",variant:"ghost",disabled:s.activity.updating,onClick:()=>void n.restoreMessages(s.checkedMessages),"aria-label":"Restaurar",children:e.jsx(Hn,{className:"h-4 w-4"})}):e.jsx(y,{size:"sm",variant:"ghost",disabled:s.activity.updating,onClick:()=>void n.changeState(s.checkedMessages,{bucket:"archive"},"E-mails arquivados"),"aria-label":"Arquivar",children:e.jsx(qa,{className:"h-4 w-4"})}),s.checkedMessages.every(c=>c.source_folder==="inbox")&&s.view!=="spam"&&s.view!=="trash"?e.jsx(y,{size:"sm",variant:"ghost",disabled:s.activity.updating,onClick:()=>void n.changeState(s.checkedMessages,{bucket:"spam"},"Movidos para spam"),"aria-label":"Marcar como spam",children:e.jsx(Tt,{className:"h-4 w-4"})}):null,s.view!=="trash"?e.jsx(y,{size:"sm",variant:"ghost",disabled:s.activity.updating,onClick:()=>void n.changeState(s.checkedMessages,{bucket:"trash"},"Movidos para lixeira"),"aria-label":"Mover para lixeira",children:e.jsx(_s,{className:"h-4 w-4"})}):null,e.jsxs("span",{className:"ml-auto self-center px-1 text-xs text-muted-foreground",children:[s.checkedMessages.length," selecionado(s)"]})]}):null]}),e.jsxs(Rt,{className:"min-h-0 flex-1",children:[s.activity.loading&&!s.messages.length?e.jsx("div",{className:"p-10 text-center text-sm text-muted-foreground",children:"Carregando e-mails…"}):s.visibleMessages.length?s.displayedMessages.map(c=>{var u;return e.jsx(Gc,{message:c,selected:((u=s.selected)==null?void 0:u.id)===c.id,checked:s.checkedIds.has(c.id),updating:s.activity.updating,dragging:s.draggingIds.has(c.id),canDrag:!!s.folders.length&&!s.activity.updating,actions:{beginDrag:n.beginDrag,cancelDrag:n.cancelDrag,changeState:n.changeState,finishPointerDrag:n.finishPointerDrag,openMessage:n.openMessage,toggleChecked:n.toggleChecked,updatePointerDrag:n.updatePointerDrag}},c.id)}):e.jsxs("div",{className:"p-10 text-center",children:[e.jsx(qa,{className:"mx-auto mb-3 h-8 w-8 text-muted-foreground","aria-hidden":"true"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nenhum e-mail encontrado."})]}),e.jsx(Wc,{enabled:s.pageMode==="continuous"&&s.filter==="all",loading:s.activity.loading,hasMore:s.pagination.hasMore,onLoad:()=>void n.loadMessages(s.pagination.cursor)})]}),e.jsxs("footer",{className:"flex min-h-14 items-center gap-2 border-t border-border px-3 py-2",children:[e.jsxs(as,{value:s.pageMode,onValueChange:c=>n.setPageMode(c),children:[e.jsx(rs,{className:"h-9 min-w-0 flex-1 text-xs","aria-label":"Quantidade de e-mails por página",children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"continuous",children:"Rolagem contínua"}),e.jsx(pe,{value:"20",children:"20 por página"}),e.jsx(pe,{value:"50",children:"50 por página"}),e.jsx(pe,{value:"100",children:"100 por página"})]})]}),s.pageMode==="continuous"?e.jsxs("span",{className:"shrink-0 text-xs text-muted-foreground",children:[s.visibleMessages.length," carregados"]}):e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(y,{type:"button",variant:"ghost",size:"icon",className:"h-9 w-9",onClick:n.previousPage,disabled:s.pageIndex===0||s.activity.loading,"aria-label":"Página anterior",children:e.jsx(Ct,{className:"h-4 w-4","aria-hidden":"true"})}),e.jsxs("span",{className:"min-w-16 text-center text-xs text-muted-foreground",children:["Página ",s.pageIndex+1]}),e.jsx(y,{type:"button",variant:"ghost",size:"icon",className:"h-9 w-9",onClick:n.nextPage,disabled:!s.canNextPage||s.activity.loading,"aria-label":"Próxima página",children:e.jsx(Sa,{className:"h-4 w-4","aria-hidden":"true"})})]})]})]}
720),Hc=({selected:s,sender:n,view:c,activity:u,detailLoading:m,attachmentsLoading:_,folders:k,currentUserId:g,blockRemoteImages:l,externalImagesAllowed:h,thread:x,notes:w,noteDraft:v,actions:R})=>{var $,V;return e.jsx("section",{className:`${s?"row-span-2 flex xl:row-span-1":"hidden xl:flex"} min-h-0 min-w-0 flex-col`,"aria-label":"Conteúdo do e-mail",children:s?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"shrink-0 border-b border-border p-4 sm:p-6",children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3",children:[e.jsx(y,{variant:"ghost",size:"icon",onClick:R.close,className:"xl:hidden","aria-label":"Voltar para lista",children:e.jsx(Ga,{className:"h-5 w-5","aria-hidden":"true"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h2",{className:"break-words text-xl font-semibold",children:s.subject||"(Sem assunto)"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:Aa(new Date(s.created_at),"dd 'de' MMMM 'de' yyyy, HH:mm",{locale:Mr})})]})]}),e.jsxs("div",{className:"mb-4 flex flex-wrap gap-1",role:"toolbar","aria-label":"Ações da mensagem",children:[e.jsx(ii,{folders:k,messages:[s],disabled:u.updating,onMove:(C,ee)=>void R.changeState([s],{custom_folder_id:C},C?`Salvo em ${ee}`:"Removido da pasta"),onCreate:R.openFolderEditor}),e.jsxs(y,{variant:"ghost",size:"sm",disabled:u.updating,onClick:()=>void R.changeState([s],{is_starred:!s.is_starred},s.is_starred?"Removido dos favoritos":"Adicionado aos favoritos"),className:"gap-2",children:[e.jsx(ar,{className:`h-4 w-4 ${s.is_starred?"fill-amber-400 text-amber-500":""}`,"aria-hidden":"true"}),"Favorito"]}),s.source_folder==="inbox"?e.jsxs(e.Fragment,{children:[e.jsxs(y,{variant:"ghost",size:"sm",disabled:u.updating,onClick:()=>void R.changeState([s],{is_read:!s.is_read},s.is_read?"Marcado como não lido":"Marcado como lido"),className:"gap-2",children:[e.jsx(Zn,{className:"h-4 w-4","aria-hidden":"true"}),s.is_read?"Não lido":"Lido"]}),e.jsxs(y,{variant:s.is_replied?"secondary":"ghost",size:"sm",disabled:u.updating,onClick:()=>void R.changeState([s],{is_replied:!s.is_replied},s.is_replied?"Marcado como não respondido":"Marcado como respondido"),className:"gap-2",children:[e.jsx(Er,{className:"h-4 w-4","aria-hidden":"true"}),s.is_replied?"Respondido":"Marcar respondido"]})]}):null,c==="archive"||c==="spam"||c==="trash"?e.jsxs(y,{variant:"ghost",size:"sm",disabled:u.updating,onClick:()=>void R.restore([s]),className:"gap-2",children:[e.jsx(Hn,{className:"h-4 w-4","aria-hidden":"true"}),"Restaurar"]}):e.jsxs(y,{variant:"ghost",size:"sm",disabled:u.updating,onClick:()=>void R.changeState([s],{bucket:"archive"},"E-mail arquivado"),className:"gap-2",children:[e.jsx(qa,{className:"h-4 w-4","aria-hidden":"true"}),"Arquivar"]}),s.source_folder==="inbox"&&c!=="spam"&&c!=="trash"?e.jsxs(y,{variant:"ghost",size:"sm",disabled:u.updating,onClick:()=>void R.changeState([s],{bucket:"spam"},"Movido para spam"),className:"gap-2",children:[e.jsx(Tt,{className:"h-4 w-4","aria-hidden":"true"}),"Spam"]}):null,c!=="trash"?e.jsxs(y,{variant:"ghost",size:"sm",disabled:u.updating,onClick:()=>void R.changeState([s],{bucket:"trash"},"Movido para lixeira"),className:"gap-2 text-destructive hover:text-destructive",children:[e.jsx(_s,{className:"h-4 w-4","aria-hidden":"true"}),"Lixeira"]}):null,s.source_folder==="inbox"?e.jsxs(y,{variant:"outline",size:"sm",onClick:()=>R.reply(s),className:"ml-auto gap-2",children:[e.jsx(Er,{className:"h-4 w-4","aria-hidden":"true"}),"Responder"]}):null,g?e.jsxs(y,{variant:s.assigned_to===g?"secondary":"ghost",size:"sm",onClick:()=>void R.changeState([s],{assigned_to:s.assigned_to===g?null:g},s.assigned_to===g?"Atendimento liberado":"Atendimento assumido"),className:"gap-2",children:[e.jsx(Wt,{className:"h-4 w-4"}),s.assigned_to===g?"Comigo":"Assumir"]}):null]}),e.jsxs("div",{className:"mb-4 grid gap-2 sm:grid-cols-2",children:[e.jsxs(as,{value:s.workflow_status||"open",onValueChange:C=>void R.changeState([s],{workflow_status:C},"Status atualizado"),children:[e.jsx(rs,{className:"min-h-11","aria-label":"Status do atendimento",children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"open",children:"Aberto"}),e.jsx(pe,{value:"pending",children:"Pendente"}),e.jsx(pe,{value:"resolved",children:"Resolvido"})]})]}),e.jsxs(as,{value:s.priority||"normal",onValueChange:C=>void R.changeState([s],{priority:C},"Prioridade atualizada"),children:[e.jsx(rs,{className:"min-h-11","aria-label":"Prioridade",children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"low",children:"Prioridade baixa"}),e.jsx(pe,{value:"normal",children:"Prioridade normal"}),e.jsx(pe,{value:"high",children:"Prioridade alta"}),e.jsx(pe,{value:"urgent",children:"Urgente"})]})]})]}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"De:"})," ",n==null?void 0:n.name," ",e.jsxs("span",{className:"text-muted-foreground",children:["<",n==null?void 0:n.email,">"]})]}),e.jsxs("p",{className:"break-all",children:[e.jsx("span",{className:"text-muted-foreground",children:"Para:"}
720)," ",s.to.join(", ")]}),($=s.cc)!=null&&$.length?e.jsxs("p",{className:"break-all",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cc:"})," ",s.cc.join(", ")]}):null]})]}),e.jsx(Rt,{className:"min-h-0 flex-1",children:e.jsxs("div",{className:"p-4 sm:p-6",children:[x.length>1?e.jsxs("div",{className:"mb-5 overflow-hidden rounded-xl border border-border",children:[e.jsxs("div",{className:"border-b border-border bg-muted/30 px-4 py-3 text-sm font-semibold",children:["Conversa · ",x.length," mensagens"]}),e.jsx("div",{className:"divide-y divide-border",children:x.map(C=>e.jsxs("button",{type:"button",className:`flex w-full items-center gap-3 px-4 py-3 text-left transition-colors hover:bg-muted/50 ${C.id===s.id?"bg-primary/10":""}`,onClick:()=>R.openLinkedReply(C),children:[e.jsx("span",{className:`h-2.5 w-2.5 shrink-0 rounded-full ${C.source_folder==="sent"?"bg-primary":"bg-sky-500"}`}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm font-medium",children:C.source_folder==="sent"?`Enviado para ${C.to.join(", ")}`:Ur(C.from).name}),e.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:C.subject})]}),e.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:wt(C.created_at)})]},C.id))})]}):null,l&&s.html&&!h?e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-2 rounded-lg border border-border bg-muted/40 px-3 py-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Io,{className:"h-4 w-4"}),"Imagens externas bloqueadas para proteger sua privacidade."]}),e.jsx(y,{size:"sm",variant:"ghost",onClick:R.allowImages,children:"Carregar imagens"})]}):null,s.html?e.jsx("iframe",{title:`Conteúdo: ${s.subject}`,sandbox:"allow-popups allow-popups-to-escape-sandbox",srcDoc:Vc(s.html,!l||h),className:"h-[clamp(560px,68dvh,880px)] w-full rounded-xl border border-border bg-white"}):s.text?e.jsx("div",{className:"whitespace-pre-wrap rounded-xl border border-border bg-background p-5 text-sm leading-7",children:s.text}):m?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Carregando conteúdo…"}):e.jsx("div",{className:"whitespace-pre-wrap rounded-xl border border-border bg-background p-5 text-sm leading-7",children:"Mensagem sem conteúdo."}),_?e.jsxs("p",{className:"mt-4 flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Qe,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}),"Carregando anexos…"]}):null,(V=s.attachments)!=null&&V.length?e.jsxs("div",{className:"mt-5",children:[e.jsxs("h3",{className:"mb-2 text-sm font-semibold",children:["Anexos (",s.attachments.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:s.attachments.map(C=>C.download_url?e.jsxs("a",{href:C.download_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex min-h-11 items-center gap-2 rounded-lg border border-border px-3 text-sm hover:bg-muted",children:[e.jsx(Fr,{className:"h-4 w-4","aria-hidden":"true"}),C.filename]},C.id):e.jsxs("span",{className:"inline-flex min-h-11 items-center gap-2 rounded-lg border border-border px-3 text-sm text-muted-foreground",children:[e.jsx(Fr,{className:"h-4 w-4","aria-hidden":"true"}),C.filename]},C.id))})]}):null,s.reply_email_id?e.jsxs(y,{variant:"outline",className:"mt-5 gap-2",onClick:()=>R.openLinkedReply(s),children:[e.jsx(Er,{className:"h-4 w-4"}),"Ver resposta enviada"]}):null,e.jsxs("div",{className:"mt-8 border-t border-border pt-5",children:[e.jsxs("h3",{className:"mb-3 flex items-center gap-2 text-sm font-semibold",children:[e.jsx(Wt,{className:"h-4 w-4"}),"Notas internas"]}),e.jsx("div",{className:"space-y-2",children:w.map(C=>e.jsxs("div",{className:"rounded-lg bg-muted/50 p-3 text-sm",children:[e.jsx("p",{className:"whitespace-pre-wrap",children:C.body}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:Aa(new Date(C.created_at),"dd/MM/yyyy HH:mm",{locale:Mr})})]},C.id))}),e.jsxs("form",{onSubmit:R.saveNote,className:"mt-3 flex gap-2",children:[e.jsx(je,{value:v,onCh
720ange:C=>R.setNoteDraft(C.target.value),placeholder:"Adicionar nota que só admins veem",maxLength:4e3,"aria-label":"Nota interna"}),e.jsx(y,{type:"submit",variant:"outline",disabled:!v.trim(),children:"Adicionar"})]})]})]})})]}):e.jsxs("div",{className:"m-auto max-w-sm p-8 text-center",children:[e.jsx(Pt,{className:"mx-auto mb-4 h-10 w-10 text-muted-foreground","aria-hidden":"true"}),e.jsx("h2",{className:"font-semibold",children:"Selecione uma mensagem"}),e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Abra um e-mail para ler, organizar e responder."})]})})},Yc=()=>{const{user:s}=Va(),[n]=vi(),[c,u]=r.useState("inbox"),[m,_]=r.useState("all"),[k,g]=r.useState([]),[l,h]=r.useState(null),[x,w]=r.useState(new Set),[v,R]=r.useState({loading:!0,detail:!1,updating:!1,sending:!1}),[$,V]=r.useState(""),[C,ee]=r.useState(""),[Z,p]=r.useState({hasMore:!1,cursor:null}),[z,Q]=r.useState("continuous"),[ae,Y]=r.useState(0),[B,G]=r.useState(!1),[q,E]=r.useState(()=>kr()),[P,K]=r.useState([]),[J,W]=r.useState({signature:`
721
722Atenciosamente,
723Equipe AI Club Studio`,block_remote_images:!0,undo_send_seconds:15,default_page_mode:"continuous"}),[N,ce]=r.useState(!1),[D,i]=r.useState(!1),[A,O]=r.useState(!1),[te,T]=r.useState([]),[re,ke]=r.useState(!1),[fe,X]=r.useState([]),[me,_e]=r.useState([]),[$e,Ve]=r.useState(null),[Je,we]=r.useState(""),[We,Ge]=r.useState({open:!1,loading:!1,saving:!1,enabled:!1,email:""}),[ps,be]=r.useState([]),[ue,Pe]=r.useState({open:!1,saving:!1,folder:null,name:""}),[ze,Ie]=r.useState(null),[xs,Ps]=r.useState(!1),[Ze,es]=r.useState(null),ws=r.useRef(null),is=r.useRef(new Map),os=r.useRef(0),H=r.useCallback(async()=>{try{const I=await vc();be(I.folders)}catch(I){o.error("Não foi possível carregar as pastas",{description:I instanceof Error?I.message:void 0})}},[]),xe=r.useCallback(async I=>{const U=!!I;R(ie=>({...ie,loading:!0}));try{const ie=z==="continuous"?50:Number(z),ge=C?await pn(c,I,ie,C):await pn(c,I,ie);return g(ss=>U?[...ss,...ge.messages]:ge.messages),p({hasMore:ge.has_more,cursor:ge.next_cursor}),U||(os.current+=1,Ve(null),h(null),w(new Set)),!0}catch(ie){return o.error("Não foi possível carregar os e-mails",{description:ie instanceof Error?ie.message:void 0}),!1}finally{R(ie=>({...ie,loading:!1}))}},[z,C,c]),Ne=async()=>{const[I]=await Promise.all([xe(),H()]);I&&o.success("Caixa atualizada")};r.useEffect(()=>{xe()},[xe]),r.useEffect(()=>{H()},[H]),r.useEffect(()=>{const I=window.setTimeout(()=>ee($.trim()),350);return()=>window.clearTimeout(I)},[$]),r.useEffect(()=>{Promise.all([_c(),kc(),ni()]).then(([I,U,ie])=>{W(I),Q(I.default_page_mode),K(U),T(ie)}).catch(()=>{})},[]),r.useEffect(()=>{Y(0)},[m,z,$,c]);const Xe=r.useMemo(()=>k.filter(I=>$c(I,m)),[m,k]),bs=r.useMemo(()=>k.filter(I=>x.has(I.id)),[x,k]),Rs=k.filter(I=>!I.is_read).length,gs=z==="continuous"?null:Number(z),hs=gs?Xe.slice(ae*gs,(ae+1)*gs):Xe,As=!!hs.length&&hs.every(I=>x.has(I.id)),Gs=!!(gs&&((ae+1)*gs<Xe.length||m==="all"&&Z.hasMore)),Hs=async()=>{!gs||!Gs||(ae+1)*gs>=Xe.length&&Z.hasMore&&!await xe(Z.cursor)||Y(I=>I+1)},Ls=(I,U)=>{g(ie=>ie.map(ge=>I.has(ge.id)?{...ge,...typeof U.is_read=="boolean"?{is_read:U.is_read}:{},...typeof U.is_starred=="boolean"?{is_starred:U.is_starred}:{},...typeof U.is_replied=="boolean"?{is_replied:U.is_replied,replied_at:U.is_replied?new Date().toISOString():null}:{},...Object.prototype.hasOwnProperty.call(U,"custom_folder_id")?{custom_folder_id:U.custom_folder_id??null}:{},...U.bucket?{mailbox_bucket:U.bucket}:{},...U.workflow_status?{workflow_status:U.workflow_status}:{},...U.priority?{priority:U.priority}:{},...Object.prototype.hasOwnProperty.call(U,"assigned_to")?{assigned_to:U.assigned_to??null}:{},...Object.prototype.hasOwnProperty.call(U,"snoozed_until")?{snoozed_until:U.snoozed_until??null}:{}}:ge)),h(ie=>ie&&I.has(ie.id)?{...ie,...typeof U.is_read=="boolean"?{is_read:U.is_read}:{},...typeof U.is_starred=="boolean"?{is_starred:U.is_starred}:{},...typeof U.is_replied=="boolean"?{is_replied:U.is_replied,replied_at:U.is_replied?new Date().toISOString():null}:{},...Object.prototype.hasOwnProperty.call(U,"custom_folder_id")?{custom_folder_id:U.custom_folder_id??null}:{},...U.bucket?{mailbox_bucket:U.bucket}:{},...U.workflow_status?{workflow_status:U.workflow_status}:{},...U.priority?{priority:U.priority}:{},...Object.prototype.hasOwnProperty.call(U,"assigned_to")?{assigned_to:U.assigned_to??null}:{},...Object.prototype.hasOwnProperty.call(U,"snoozed_until")?{snoozed_until:U.snoozed_until??null}:{}}:ie)},L=async(I,U,ie)=>{if(I.length){R(ge=>({...ge,updating:!0}));try{await wr(I.map(xr),U);const ge=new Set(I.map(j=>j.id));Ls(ge,U);const ss=c.startsWith("folder:")?c.slice(7):null,Ws=Object.prototype.hasOwnProperty.call(U,"custom_folder_id");(!!U.bucket||c==="starred"&&U.is_starred===!1||!!(ss&&Ws&&U.custom_folder_id!==ss))&&await xe(),(Ws||U.bucket)&&await H(),w(new Set),o.success(ie)}catch(ge){o.error("Não foi possível atualizar os e-mails",{description:ge instanceof Error?ge.message:void 0})}finally{R(ge=>({...ge,updating:!1}))}}},d=I=>{ws.current=I,es(I)},le=(I,U)=>{const ge={messages:x.has(I.id)?bs:[I],overFolderId:null,point:U};d(ge)},S=()=>d(null),de=(I,U=(ie=>(ie=ws.current)==null?void 0:ie.point)()??null)=>{const ge=ws.current;ge&&d({...ge,overFolderId:I,point:U})},Ce=(I,U)=>{var ss;const ie=document.elementFromPoint(I,U),ge=((ss=ie==null?void 0:ie.closest("[data-mail-folder-id]"))==null?void 0:ss.dataset.mailFolderId)||null;de(ge,{x:I,y:U})},Oe=I=>{var ge;const U=((ge=ws.current)==null?void 0:ge.messages)||[];if(S(),!U.length||U.every(ss=>
723ss.custom_folder_id===I.id))return;const ie=U.length===1?`Salvo em ${I.name}`:`${U.length} e-mails salvos em ${I.name}`;L(U,{custom_folder_id:I.id},ie)},Ke=()=>{const I=ps.find(U=>{var ie;return U.id===((ie=ws.current)==null?void 0:ie.overFolderId)});I?Oe(I):S()},qe=async I=>{const U=I.filter(ge=>ge.source_folder==="inbox"),ie=I.filter(ge=>ge.source_folder==="sent");R(ge=>({...ge,updating:!0}));try{await Promise.all([U.length?wr(U.map(xr),{bucket:"inbox"}):Promise.resolve(),ie.length?wr(ie.map(xr),{bucket:"sent"}):Promise.resolve()]),await xe(),o.success("E-mails restaurados")}catch(ge){o.error("Não foi possível restaurar",{description:ge instanceof Error?ge.message:void 0})}finally{R(ge=>({...ge,updating:!1}))}},Me=async I=>{var ne;const U=++os.current,ie=is.current.get(I.id),ge=ie?{...ie,...I,html:ie.html,text:ie.text,attachments:ie.attachments}:I,ss=!!(ge.html||ge.text);ke(!1),h({...ge,is_read:!0}),X([]),_e([]),Ls(new Set([I.id]),{is_read:!0}),R(se=>({...se,detail:!ss}));const Ws=ss?Promise.resolve(ge):hc(I.source_folder,I.id),Ia=Ac(I.id).catch(()=>[]),j=gc(I.id).catch(()=>[]);try{const se=await Ws;if(U!==os.current)return;is.current.set(I.id,se),h({...se,is_read:!0}),R(ve=>({...ve,detail:!1})),Promise.all([Ia,j]).then(([ve,ye])=>{U===os.current&&(X(ve),_e(ye))}),se.has_attachments&&!((ne=se.attachments)!=null&&ne.length)?(Ve(se.id),pc(se.source_folder,se.id).then(ve=>{if(U!==os.current)return;const ye={...se,attachments:ve};is.current.set(se.id,ye),h(ls=>(ls==null?void 0:ls.id)===se.id?{...ls,attachments:ve}:ls)}).catch(()=>{}).finally(()=>{U===os.current&&Ve(null)})):Ve(null),I.is_read||wr([xr(se)],{is_read:!0}).catch(()=>{o.error("O e-mail abriu, mas não foi possível salvar o status de leitura")})}catch(se){if(U!==os.current)return;o.error("Não foi possível abrir o e-mail",{description:se instanceof Error?se.message:void 0})}finally{U===os.current&&R(se=>({...se,detail:!1}))}},Be=async I=>{const U=I.reply_email_id&&I.id===(l==null?void 0:l.id)?I.reply_email_id:I.id,ie=U===I.reply_email_id?"sent":I.source_folder,ss=[...me,...k].find(Ws=>Ws.id===U)||{...I,id:U,source_folder:ie,mailbox_bucket:ie,html:null,text:null,attachments:[]};await Me(ss)};r.useEffect(()=>{const I=n.get("email");if(!I||l||v.loading)return;const U=k.find(ie=>ie.id===I);U&&Me(U)},[v.loading,k,l,n]);const Is=I=>{w(U=>{const ie=new Set(U);return ie.has(I)?ie.delete(I):ie.add(I),ie})},ks=()=>{w(I=>{const U=new Set(I);return As?hs.forEach(ie=>U.delete(ie.id)):hs.forEach(ie=>U.add(ie.id)),U})},Ys=I=>{var U;if(I){const ie=((U=I.reply_to)==null?void 0:U[0])||Ur(I.from).email,ge=P.find(ss=>ss.draft_key===`reply_${I.id}`);E({...kr(),replyingTo:I,draftKey:`reply_${I.id}`,idempotencyKey:(ge==null?void 0:ge.idempotency_key)||`admin_${crypto.randomUUID().replace(/-/g,"_")}`,to:(ge==null?void 0:ge.to_addresses.join(", "))||ie,cc:(ge==null?void 0:ge.cc_addresses.join(", "))||"",bcc:(ge==null?void 0:ge.bcc_addresses.join(", "))||"",subject:(ge==null?void 0:ge.subject)||(I.subject.toLowerCase().startsWith("re:")?I.subject:`Re: ${I.subject}`),body:(ge==null?void 0:ge.body)||J.signature.trimStart(),scheduledAt:ge!=null&&ge.scheduled_at?new Date(ge.scheduled_at).toISOString().slice(0,16):"",attachments:(ge==null?void 0:ge.attachment_paths)||[]})}else{const ie=P.find(ge=>ge.draft_key==="new");E(ie?{...kr(),draftKey:"new",idempotencyKey:ie.idempotency_key,to:ie.to_addresses.join(", "),cc:ie.cc_addresses.join(", "),bcc:ie.bcc_addresses.join(", "),subject:ie.subject,body:ie.body,scheduledAt:ie.scheduled_at?new Date(ie.scheduled_at).toISOString().slice(0,16):"",attachments:ie.attachment_paths||[]}:{...kr(),draftKey:"new",body:J.signature.trimStart()})}G(!0)};r.useEffect(()=>{if(!B||!q.to&&!q.subject&&!q.body)return;const I=window.setTimeout(()=>{var U;Cc({draft_key:q.draftKey,to_addresses:Qa(q.to),cc_addresses:Qa(q.cc),bcc_addresses:Qa(q.bcc),subject:q.subject,body:q.body,replying_to_provider_id:((U=q.replyingTo)==null?void 0:U.id)||null,idempotency_key:q.idempotencyKey,scheduled_at:q.scheduledAt?new Date(q.scheduledAt).toISOString():null,attachment_paths:q.attachments}).then(({draft:ie})=>K(ge=>[ie,...ge.filter(ss=>ss.id!==ie.id&&ss.draft_key!==ie.draft_key)])).catch(()=>{})},700);return()=>window.clearTimeout(I)},[q,B]);const Ye=async I=>{const U=Array.from(I.target.files||[]);if(U.length){if(U.reduce((ie,ge)=>ie+ge.size,0)>30*1024*1024)return o.error("Anexos devem somar no máximo 30 MB");R(ie=>({...ie,updating:!0}));try{const ie=await Promise.all(U.map(Mc));E(ge=>({...ge,attachments:[...ge.attachments,...ie].slice(0,20)})),o.success(`${ie.length} anexo(s) preparado(s)`)}catch(ie){o.error("Falha ao enviar anexo",{description:ie instanceof Error?ie.message:void 0})}finally{R(ie=>({...ie,updating:!1})),I.target.value=""}}},Js=async I=>{var U;I.preventDefault(),R(ie=>({...ie,sending:!0}));try{const ie=q.scheduledAt?new Date(q.scheduledAt).toISOString():!q.replyingTo&&J.undo_send_seconds>0?new Date(Date.now()+J.undo_send_seconds*1e3).toISOString():void 0,ge=await Fc({to:Qa(q.to),cc:Qa(q.cc),bcc:Qa(q.bcc),subject:q.subject,text:q.body,inReplyTo:(U=q.replyingTo)==null?void 0:U.message_id,replyingTo:q.replyingTo?xr(q.replyingTo):void 0,idempotencyKey:q.idempotencyKey,scheduledAt:ie,attachments:q.attachments});q.replyingTo&&ge.reply_marked&&Ls(new Set([q.replyingTo.id]),{is_replied:!0}),o.success(ie?"E-mail agendado pela Resend":q.replyingTo?"Resposta enviada pela Resend":"E-mail enviado pela Resend",{description:q.replyingTo&&!ge.reply_marked?"Envio confirmado, mas não foi possível salvar a marca Respondido.":void 0,...ie&&!q.scheduledAt?{action:{label:"Desfazer",onClick:()=>void Rc(ge.id).then(()=>o.success("Envio cancelado")).catch(()=>o.error("Não foi possível cancelar"))}}:{}}
723),await Sc(q.draftKey).catch(()=>{}),K(ss=>ss.filter(Ws=>Ws.draft_key!==q.draftKey)),G(!1),c==="sent"&&await xe()}catch(ie){o.error("Não foi possível enviar",{description:ie instanceof Error?ie.message:void 0})}finally{R(ie=>({...ie,sending:!1}))}},ua=async()=>{Ge(I=>({...I,open:!0,loading:!0}));try{const I=await jc();Ge({open:!0,loading:!1,saving:!1,enabled:I.enabled,email:I.notification_email})}catch(I){Ge(U=>({...U,loading:!1})),o.error("Não foi possível carregar os avisos",{description:I instanceof Error?I.message:void 0})}},$s=async I=>{I.preventDefault(),Ge(U=>({...U,saving:!0}));try{await fc({enabled:We.enabled,notification_email:We.email.trim()}),Ge(U=>({...U,open:!1,saving:!1})),o.success(We.enabled?"Avisos por e-mail ativados":"Avisos por e-mail desativados")}catch(U){Ge(ie=>({...ie,saving:!1})),o.error("Não foi possível salvar os avisos",{description:U instanceof Error?U.message:void 0})}},ea=async I=>{I.preventDefault(),i(!0);try{await wc(J),ce(!1),Q(J.default_page_mode),o.success("Preferências salvas")}catch(U){o.error("Não foi possível salvar preferências",{description:U instanceof Error?U.message:void 0})}finally{i(!1)}},lr=async I=>{if(I.preventDefault(),!(!l||!Je.trim()))try{const U=await Ec(l.id,Je);X(ie=>[...ie,U]),we(""),o.success("Nota interna adicionada")}catch(U){o.error("Não foi possível salvar nota",{description:U instanceof Error?U.message:void 0})}},Wa=(I=null)=>{Pe({open:!0,saving:!1,folder:I,name:(I==null?void 0:I.name)||""})},vr=async I=>{I.preventDefault();const U=ue.name.trim();if(U){Pe(ie=>({...ie,saving:!0}));try{ue.folder?await Nc(ue.folder.id,U):await bc(U),await H(),Pe({open:!1,saving:!1,folder:null,name:""}),o.success(ue.folder?"Pasta renomeada":"Pasta criada")}catch(ie){Pe(ge=>({...ge,saving:!1})),o.error("Não foi possível salvar a pasta",{description:ie instanceof Error?ie.message:void 0})}}},Pa=async()=>{if(ze){Ps(!0);try{await yc(ze.id),c===`folder:${ze.id}`&&u("inbox"),Ie(null),await H(),o.success("Pasta excluída",{description:"Os e-mails continuam na caixa."})}catch(I){o.error("Não foi possível excluir a pasta",{description:I instanceof Error?I.message:void 0})}finally{Ps(!1)}}};r.useEffect(()=>{const I=U=>{var ge;const ie=U.target;if(!(ie!=null&&ie.matches('input, textarea, [contenteditable="true"]'))){if(U.key==="/"){U.preventDefault(),(ge=document.getElementById("mailbox-search"))==null||ge.focus();return}if(U.key.toLowerCase()==="r"&&(l==null?void 0:l.source_folder)==="inbox"){U.preventDefault(),Ys(l);return}if(U.key.toLowerCase()==="e"&&l){U.preventDefault(),L([l],{bucket:"archive"},"E-mail arquivado");return}if(U.key.toLowerCase()==="s"&&l){U.preventDefault(),L([l],{is_starred:!l.is_starred},l.is_starred?"Removido dos favoritos":"Adicionado aos favoritos");return}if((U.key.toLowerCase()==="j"||U.key.toLowerCase()==="k")&&hs.length){U.preventDefault();const ss=hs.findIndex(Ia=>Ia.id===(l==null?void 0:l.id)),Ws=U.key.toLowerCase()==="j"?Math.min(hs.length-1,ss+1):Math.max(0,ss<=0?0:ss-1);Me(hs[Ws])}}};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)});const dr=l?Ur(l.from):null,zr=async()=>{try{const I=await Oc();_t(`aiclub-emails-${Aa(new Date,"yyyy-MM-dd")}.csv`,I),o.success(`${I.length} e-mail(s) exportado(s)`)}catch(I){o.error("Falha ao exportar e-mails",{description:I instanceof Error?I.message:void 0})}};return e.jsxs("div",{className:"flex h-[calc(100dvh-2rem)] min-h-0 flex-col gap-5 overflow-hidden sm:h-[calc(100dvh-3rem)] lg:h-[calc(100dvh-4rem)]",children:[e.jsxs("header",{className:"flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"flex items-center gap-2 text-2xl font-bold",children:[e.jsx(Pt,{className:"size-6","aria-hidden":"true"}),"E-mails"]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Organize, acompanhe e responda mensagens do AI Club Studio pela Resend."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(y,{variant:"outline",onClick:()=>void Ne(),disabled:v.loading,className:"min-h-11 gap-2",children:[e.jsx(Qe,{className:`h-4 w-4 ${v.loading?"animate-spin":""}`,"aria-hidden":"true"}),"Atualizar"]}),e.jsxs(y,{variant:"outline",onClick:()=>void ua(),className:"min-h-11 gap-2",children:[e.jsx(Bi,{className:"h-4 w-4","aria-hidden":"true"}),"Avisos"]}),e.jsxs(y,{variant:"outline",onClick:()=>ce(!0),className:"min-h-11 gap-2",children:[e.jsx(xo,{className:"h-4 w-4","aria-hidden":"true"}),"Preferências"]}),e.jsxs(y,{variant:"outline",onClick:()=>O(!0),className:"min-h-11 gap-2",children:[e.jsx(er,{className:"h-4 w-4","aria-hidden":"true"}),"Automações"]}),e.jsxs(y,{variant:"outline",onClick:()=>void zr(),className:"min-h-11 gap-2",children:[e.jsx(na,{className:"h-4 w-4","aria-hidden":"true"}),"Exportar"]}),P.length?e.jsxs(y,{variant:"outline",onClick:()=>Ys(),className:"min-h-11 gap-2",children:[e.jsx(Eo,{className:"h-4 w-4","aria-hidden":"true"}),"Rascunho ",e.jsx(Re,{variant:"secondary",children:P.length})]}):null,e.jsx(y,{asChild:!0,variant:"outline",className:"min-h-11 gap-2",children:e.jsxs(Sn,{to:"/admin/email-marketing",children:[e.jsx(Fa,{className:"h-4 w-4","aria-hidden":"true"}),"Marketing"]})}),e.jsxs(y,{onClick:()=>Ys(),className:"min-h-11 gap-2",children:[e.jsx(ei,{className:"h-4 w-4","aria-hidden":"true"}),"Escrever"]})]})]}),e.jsxs("div",{className:"grid min-h-0 flex-1 grid-rows-[auto_minmax(0,1fr)] overflow-hidden rounded-2xl border border-border bg-card xl:grid-cols-[230px_380px_minmax(0,1fr)] xl:grid-rows-[minmax(0,1fr)] 2xl:gr
723id-cols-[240px_420px_minmax(0,1fr)]",children:[e.jsxs("nav",{className:`${l?"hidden xl:flex":"flex"} min-h-0 flex-col border-b border-border p-3 xl:border-b-0 xl:border-r`,"aria-label":"Pastas da caixa de e-mail",children:[e.jsx("div",{className:"grid grid-cols-2 gap-1 sm:grid-cols-3 xl:grid-cols-1",children:Bc.map(I=>e.jsxs(y,{variant:c===I.id?"secondary":"ghost",onClick:()=>u(I.id),className:"min-h-11 justify-start gap-2 px-3",children:[e.jsx(I.icon,{className:"h-4 w-4","aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:I.label}),I.id==="inbox"&&c==="inbox"&&Rs>0?e.jsx(Re,{variant:"secondary",className:"ml-auto px-1.5",children:Rs}):null]},I.id))}),e.jsxs("div",{className:"mt-4 border-t border-border pt-3",children:[e.jsxs("div",{className:"mb-2 flex min-h-11 items-center justify-between px-3",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Pastas"}),e.jsx(y,{type:"button",variant:"ghost",size:"icon",className:"h-11 w-11",onClick:()=>Wa(),"aria-label":"Criar pasta",children:e.jsx(Et,{className:"h-4 w-4","aria-hidden":"true"})})]}),e.jsx("div",{className:"space-y-1",children:ps.length?ps.map(I=>{const U=`folder:${I.id}`,ie=c===U,ge=(Ze==null?void 0:Ze.overFolderId)===I.id;return e.jsxs("div",{"data-mail-folder-id":I.id,className:`flex items-center gap-1 rounded-xl transition-[background-color,box-shadow] ${ge?"bg-primary/15 ring-2 ring-primary ring-offset-2 ring-offset-card":""}`,children:[e.jsxs(y,{variant:ie?"secondary":"ghost",onClick:()=>u(U),className:"min-h-11 min-w-0 flex-1 justify-start gap-2 px-3",children:[ie?e.jsx(Sr,{className:"h-4 w-4 shrink-0","aria-hidden":"true"}):e.jsx(Uo,{className:"h-4 w-4 shrink-0","aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:ge?"Solte aqui":I.name}),I.message_count>0&&!ge?e.jsx(Re,{variant:"secondary",className:"ml-auto px-1.5",children:I.message_count}):null]}),e.jsxs(Gn,{children:[e.jsx(Wn,{asChild:!0,children:e.jsx(y,{type:"button",variant:"ghost",size:"icon",className:"h-11 w-11 shrink-0","aria-label":`Ações da pasta ${I.name}`,children:e.jsx(Ro,{className:"h-4 w-4","aria-hidden":"true"})})}),e.jsxs(Kn,{align:"end",children:[e.jsxs(gr,{onClick:()=>Wa(I),className:"gap-2",children:[e.jsx($r,{className:"h-4 w-4","aria-hidden":"true"}),"Renomear"]}),e.jsx(ft,{}),e.jsxs(gr,{onClick:()=>Ie(I),className:"gap-2 text-destructive focus:text-destructive",children:[e.jsx(_s,{className:"h-4 w-4","aria-hidden":"true"}),"Excluir pasta"]})]})]})]},I.id)}):e.jsx("p",{className:"px-3 py-2 text-xs leading-5 text-muted-foreground",children:"Crie pastas para organizar recebidos e enviados."})})]})]}),e.jsx(Kc,{state:{activity:v,allVisibleChecked:As,canNextPage:Gs,checkedIds:x,checkedMessages:bs,displayedMessages:hs,draggingIds:new Set((Ze==null?void 0:Ze.messages.map(I=>I.id))||[]),filter:m,folders:ps,messages:k,pageIndex:ae,pageMode:z,pagination:Z,search:$,selected:l,view:c,visibleMessages:Xe},actions:{beginDrag:le,cancelDrag:S,changeState:L,finishPointerDrag:Ke,loadMessages:xe,nextPage:()=>void Hs(),openFolderEditor:()=>Wa(),openMessage:Me,previousPage:()=>Y(I=>Math.max(0,I-1)),restoreMessages:qe,setFilter:_,setPageMode:Q,setSearch:V,toggleAllVisible:ks,toggleChecked:Is,updatePointerDrag:Ce}}),e.jsx(Hc,{selected:l,sender:dr,view:c,activity:v,detailLoading:v.detail,attachmentsLoading:$e===(l==null?void 0:l.id),folders:ps,currentUserId:s==null?void 0:s.id,blockRemoteImages:J.block_remote_images,externalImagesAllowed:re,thread:me,notes:fe,noteDraft:Je,actions:{changeState:L,close:()=>{os.current+=1,Ve(null),h(null)},openFolderEditor:()=>Wa(),reply:Ys,restore:qe,allowImages:()=>ke(!0),setNoteDraft:we,saveNote:lr,openLinkedReply:Be}})]}),e.jsx("div",{className:"sr-only",role:"status","aria-live":"polite",children:Ze?`Arrastando ${Ze.messages.length} e-mail${Ze.messages.length===1?"":"s"}. Solte em uma pasta.`:""}),Ze!=null&&Ze.point?e.jsxs("div",{className:"pointer-events-none fixed z-[100] flex -translate-x-1/2 -translate-y-full items-center gap-2 rounded-full bg-primary px-3 py-2 text-sm font-semibold text-primary-foreground shadow-xl motion-reduce:transition-none",style:{left:Ze.point.x,top:Ze.point.y-12},"aria-hidden":"true",children:[e.jsx(Tn,{className:"h-4 w-4"}),Ze.messages.length===1?"1 e-mail":`${Ze.messages.length} e-mails`]}):null,e.jsx(ds,{open:ue.open,onOpenChange:I=>Pe(U=>({...U,open:I}
723)),children:e.jsxs(cs,{children:[e.jsxs(ms,{children:[e.jsx(us,{children:ue.folder?"Renomear pasta":"Criar pasta"}),e.jsx(ra,{children:"Use um nome curto para encontrar os e-mails rapidamente."})]}),e.jsxs("form",{onSubmit:vr,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"mail-folder-name",children:"Nome da pasta"}),e.jsx(je,{id:"mail-folder-name",value:ue.name,onChange:I=>Pe(U=>({...U,name:I.target.value})),maxLength:60,autoFocus:!0,required:!0,placeholder:"Ex.: Clientes"})]}),e.jsxs(Bs,{children:[e.jsx(y,{type:"button",variant:"ghost",onClick:()=>Pe(I=>({...I,open:!1})),children:"Cancelar"}),e.jsx(y,{type:"submit",disabled:ue.saving||!ue.name.trim(),children:ue.saving?"Salvando…":ue.folder?"Salvar nome":"Criar pasta"})]})]})]})}),e.jsx(va,{open:!!ze,onOpenChange:I=>{!I&&!xs&&Ie(null)},children:e.jsxs(ba,{children:[e.jsxs(Na,{children:[e.jsxs(ya,{children:["Excluir pasta “",ze==null?void 0:ze.name,"”?"]}),e.jsx(_a,{children:"A pasta será removida, mas nenhum e-mail será excluído. As mensagens continuam em Recebidos, Enviados ou na categoria atual."})]}),e.jsxs(wa,{children:[e.jsx(ka,{disabled:xs,children:"Cancelar"}),e.jsx(Ca,{disabled:xs,onClick:I=>{I.preventDefault(),Pa()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:xs?"Excluindo…":"Excluir pasta"})]})]})}),e.jsx(Wr,{open:B,onOpenChange:G,children:e.jsxs(Kr,{className:"w-full overflow-y-auto sm:max-w-xl",children:[e.jsxs(Hr,{children:[e.jsx(Yr,{children:q.replyingTo?"Responder e-mail":"Novo e-mail"}),e.jsx(Jr,{children:"Envio seguro por [email protected] via Resend."})]}),e.jsxs("form",{onSubmit:Js,className:"mt-6 space-y-4",children:[te.length?e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Resposta pronta"}),e.jsxs(as,{onValueChange:I=>{const U=te.find(ie=>ie.id===I);U&&E(ie=>({...ie,subject:ie.subject||U.subject,body:`${U.body}${J.signature}`}))},children:[e.jsx(rs,{children:e.jsx(ts,{placeholder:"Inserir modelo"})}),e.jsx(ns,{children:te.map(I=>e.jsx(pe,{value:I.id,children:I.name},I.id))})]})]}):null,e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"mail-to",children:"Para"}),e.jsx(je,{id:"mail-to",type:"text",inputMode:"email",value:q.to,onChange:I=>E(U=>({...U,to:I.target.value})),placeholder:"[email protected]",required:!0})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"mail-cc",children:"Cc"}),e.jsx(je,{id:"mail-cc",value:q.cc,onChange:I=>E(U=>({...U,cc:I.target.value})),placeholder:"Opcional"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"mail-bcc",children:"Cco"}),e.jsx(je,{id:"mail-bcc",value:q.bcc,onChange:I=>E(U=>({...U,bcc:I.target.value})),placeholder:"Opcional"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"mail-subject",children:"Assunto"}),e.jsx(je,{id:"mail-subject",value:q.subject,onChange:I=>E(U=>({...U,subject:I.target.value})),required:!0,maxLength:998})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"mail-body",children:"Mensagem"}),e.jsx(Ss,{id:"mail-body",value:q.body,onChange:I=>E(U=>({...U,body:I.target.value})),required:!0,rows:14,placeholder:"Escreva sua mensagem…"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"mail-attachments",children:"Anexos"}),e.jsx(je,{id:"mail-attachments",type:"file",multiple:!0,onChange:I=>void Ye(I),disabled:v.updating}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Até 20 arquivos e 30 MB por seleção."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"mail-schedule",children:"Agendar opcionalmente"}),e.jsx(je,{id:"mail-schedule",type:"datetime-local",value:q.scheduledAt,onChange:I=>E(U=>({...U,scheduledAt:I.target.value})),min:new Date(Date.now()+6e4).toISOString().slice(0,16)})]})]}),q.attachments.length?e.jsx("div",{className:"flex flex-wrap gap-2",children:q.attachments.map(I=>e.jsxs(Re,{variant:"secondary",className:"gap-1 py-1",children:[e.jsx(Fr,{className:"h-3 w-3"}),I.filename,e.jsx("button",{type:"button",onClick:()=>E(U=>({...U,attachments:U.attachments.filter(ie=>ie.path!==I.path)})),"aria-label":`Remover ${I.filename}`,children:e.jsx(Ga,{className:"h-3 w-3"})})]},I.path))}):null,!q.replyingTo&&!q.scheduledAt&&J.undo_send_seconds>0?e.jsxs("p",{className:"rounded-lg bg-muted/50 px-3 py-2 text-xs text-muted-foreground",children:["Envio ficará aguardando ",J.undo_send_seconds,"s para permitir desfazer."]}):null,e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(y,{type:"button",variant:"ghost",onClick:()=>G(!1),children:"Cancelar"}),e.jsxs(y,{type:"submit",disabled:v.sending,className:"gap-2",children:[e.jsx(It,{className:"h-4 w-4","aria-hidden":"true"}),v.sending?"Enviando…":"Enviar e-mail"]})]})]})]})}),e.jsx(zc,{open:A,onOpenChange:O,folders:ps,onTemplatesChange:T}),e.jsx(Wr,{open:N,onOpenChange:ce,children:e.jsxs(Kr,{className:"w-full overflow-y-auto sm:max-w-md",children:[e.jsxs(Hr,{children:[e.jsx(Yr,{children:"Preferências da caixa"}),e.jsx(Jr,{children:"Assinatura, privacidade, paginação e janela para desfazer envios."})]}),e.jsxs("form",{onSubmit:ea,className:"mt-6 space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"mail-signature",children:"Assinatura padrão"}),e.jsx(Ss,{id:"mail-signature",rows:6,value:J.signature,onChange:I=>W(U=>({...U,signature:I.target.value})),maxLength:4e3})]}),e.jsxs("div",{className:"flex min-h-14 items-center justify-between gap-4 roun
723ded-xl border border-border p-4",children:[e.jsxs("div",{children:[e.jsx(oe,{htmlFor:"mail-images",children:"Bloquear imagens externas"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Evita tracking pixels ao abrir mensagens."})]}),e.jsx(Vs,{id:"mail-images",checked:J.block_remote_images,onCheckedChange:I=>W(U=>({...U,block_remote_images:I}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"mail-undo",children:"Tempo para desfazer envio"}),e.jsxs(as,{value:String(J.undo_send_seconds),onValueChange:I=>W(U=>({...U,undo_send_seconds:Number(I)})),children:[e.jsx(rs,{id:"mail-undo",children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"0",children:"Enviar imediatamente"}),e.jsx(pe,{value:"10",children:"10 segundos"}),e.jsx(pe,{value:"15",children:"15 segundos"}),e.jsx(pe,{value:"30",children:"30 segundos"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"mail-default-page",children:"Visualização padrão"}),e.jsxs(as,{value:J.default_page_mode,onValueChange:I=>W(U=>({...U,default_page_mode:I})),children:[e.jsx(rs,{id:"mail-default-page",children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"continuous",children:"Rolagem contínua"}),e.jsx(pe,{value:"20",children:"20 por página"}),e.jsx(pe,{value:"50",children:"50 por página"}),e.jsx(pe,{value:"100",children:"100 por página"})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(y,{type:"button",variant:"ghost",onClick:()=>ce(!1),children:"Cancelar"}),e.jsx(y,{type:"submit",disabled:D,children:D?"Salvando…":"Salvar preferências"})]})]})]})}),e.jsx(Wr,{open:We.open,onOpenChange:I=>Ge(U=>({...U,open:I})),children:e.jsxs(Kr,{className:"w-full sm:max-w-md",children:[e.jsxs(Hr,{children:[e.jsx(Yr,{children:"Avisos de novos e-mails"}),e.jsx(Jr,{children:"Receba no seu e-mail pessoal um resumo quando chegar mensagem nova no domínio do AI Club Studio."})]}),We.loading?e.jsx("p",{className:"mt-6 text-sm text-muted-foreground",children:"Carregando configuração…"}):e.jsxs("form",{onSubmit:$s,className:"mt-6 space-y-5",children:[e.jsxs("div",{className:"flex min-h-14 items-center justify-between gap-4 rounded-xl border border-border p-4",children:[e.jsxs("div",{children:[e.jsx(oe,{htmlFor:"mail-notification-enabled",children:"Avisar novos recebimentos"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Pode ser desligado a qualquer momento."})]}),e.jsx(Vs,{id:"mail-notification-enabled",checked:We.enabled,onCheckedChange:I=>Ge(U=>({...U,enabled:I}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"mail-notification-email",children:"E-mail para receber avisos"}),e.jsx(je,{id:"mail-notification-email",type:"email",inputMode:"email",autoComplete:"email",value:We.email,onChange:I=>Ge(U=>({...U,email:I.target.value})),placeholder:"[email protected]",required:We.enabled}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"O endereço pode ser trocado depois. O aviso contém remetente, destinatário e assunto, sem copiar corpo ou anexos."})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(y,{type:"button",variant:"ghost",onClick:()=>Ge(I=>({...I,open:!1})),children:"Cancelar"}),e.jsx(y,{type:"submit",disabled:We.saving,children:We.saving?"Salvando…":"Salvar avisos"})]})]})]})})]})};async function ma(s){const{data:n,error:c}=await F.functions.invoke("admin-email-marketing",{body:s});if(c)throw c;if(n!=null&&n.error)throw new Error(n.error);return n}const Jc=()=>ma({action:"overview"}),Xc=s=>ma({action:"create-segment",name:s}),Qc=s=>ma({action:"create-contact",...s}),Zc=(s,n)=>ma({action:"import-contacts",contacts:s,segmentId:n}),em=(s,n)=>ma({action:"toggle-contact",id:s,unsubscribed:n}),sm=s=>ma({action:"create-campaign",campaign:s}),am=s=>ma({action:"create-experiment",experiment:s}),rm=(s,n)=>ma({action:"send-campaign",id:s,scheduledAt:n}),tm=(s,n)=>ma({action:"send-experiment",experimentId:s,scheduledAt:n}),nm={campaigns:[],contacts:[],segments:[],topics:[],reputation:{window_days:30,sent:0,delivered:0,opened:0,clicked:0,bounced:0,complained:0,failed:0,suppressed:0,delivery_rate:0,bounce_rate:0,complaint_rate:0}}
723,im={novidade:{subject:"Novidade do AI Club Studio",body:`Olá {{{contact.first_name|tudo bem}}},
724
725Temos uma novidade preparada para ajudar sua empresa a crescer com mais consistência.`,cta:"Conhecer novidade"},conteudo:{subject:"Conteúdo novo para você",body:`Olá {{{contact.first_name|tudo bem}}},
726
727Preparamos um conteúdo prático que pode ajudar nas próximas decisões do seu negócio.`,cta:"Acessar conteúdo"},oferta:{subject:"Uma condição especial do AI Club Studio",body:`Olá {{{contact.first_name|tudo bem}}},
728
729Abrimos uma condição especial por tempo limitado para empresas que querem acelerar sua presença digital.`,cta:"Quero saber mais"},reativacao:{subject:"Podemos voltar a conversar?",body:`Olá {{{contact.first_name|tudo bem}}},
730
731Faz algum tempo desde nosso último contato. Queremos entender seus próximos objetivos e ver como podemos ajudar.`,cta:"Falar com o AI Club Studio"}},om={draft:"Rascunho",scheduled:"Agendada",sending:"Enviando",sent:"Enviada",canceled:"Cancelada",failed:"Falhou"},fn=(s,n)=>{var c;return((c=s.metrics)==null?void 0:c[`email.${n}`])||0};function lm(){const[s,n]=r.useState(nm),[c,u]=r.useState(!0),[m,_]=r.useState(!1),[k,g]=r.useState(!1),[l,h]=r.useState(""),[x,w]=r.useState(!1),[v,R]=r.useState({email:"",firstName:"",lastName:"",segmentId:""}),[$,V]=r.useState(!1),[C,ee]=r.useState(""),[Z,p]=r.useState(""),[z,Q]=r.useState(!1),[ae,Y]=r.useState({name:"",segmentId:"",subject:"",previewText:"",bodyText:"",ctaLabel:"",ctaUrl:""}),[B,G]=r.useState(!1),[q,E]=r.useState({segmentId:"",subject:"",bodyText:""}),[P,K]=r.useState(null),[J,W]=r.useState(""),N=async()=>{u(!0);try{n(await Jc())}catch(T){o.error("Não foi possível carregar email marketing",{description:T instanceof Error?T.message:void 0})}finally{u(!1)}};r.useEffect(()=>{N()},[]);const ce=r.useMemo(()=>s.contacts.filter(T=>!T.unsubscribed).length,[s.contacts]),D=async T=>{T.preventDefault(),_(!0);try{await Xc(l),g(!1),h(""),await N(),o.success("Segmento criado")}catch(re){o.error("Falha ao criar segmento",{description:re instanceof Error?re.message:void 0})}finally{_(!1)}},i=async T=>{T.preventDefault(),_(!0);try{await Qc(v),w(!1),R({email:"",firstName:"",lastName:"",segmentId:""}),await N(),o.success("Contato adicionado")}catch(re){o.error("Falha ao adicionar contato",{description:re instanceof Error?re.message:void 0})}finally{_(!1)}},A=async T=>{T.preventDefault();const re=C.split(/\r?\n/).map(ke=>{const[fe,X,me]=ke.split(/[;,]/).map(_e=>_e.trim());return{email:fe,firstName:X,lastName:me}}).filter(ke=>ke.email);if(re.length){_(!0);try{await Zc(re,Z||void 0),V(!1),ee(""),await N(),o.success(`${re.length} contato(s) importado(s)`)}catch(ke){o.error("Falha na importação",{description:ke instanceof Error?ke.message:void 0})}finally{_(!1)}}},O=async T=>{T.preventDefault();const re=s.segments.find(ke=>ke.id===ae.segmentId);if(re){_(!0);try{if(B){const ke=s.segments.find(fe=>fe.id===q.segmentId);if(!ke)throw new Error("Selecione o segmento da variante B");await am({name:ae.name,variants:[{...ae,segmentName:re.name},{...ae,segmentId:q.segmentId,segmentName:ke.name,subject:q.subject,bodyText:q.bodyText}]})}else await sm({...ae,segmentName:re.name});Q(!1),Y({name:"",segmentId:"",subject:"",previewText:"",bodyText:"",ctaLabel:"",ctaUrl:""}),E({segmentId:"",subject:"",bodyText:""}),G(!1),await N(),o.success(B?"Teste A/B salvo como rascunho":"Campanha salva como rascunho")}catch(ke){o.error("Falha ao criar campanha",{description:ke instanceof Error?ke.message:void 0})}finally{_(!1)}}},te=async T=>{if(T.preventDefault(),!!P){_(!0);try{const re=J?new Date(J).toISOString():void 0;P.experiment_id?await tm(P.experiment_id,re):await rm(P.id,re),K(null),W(""),await N(),o.success(re?"Campanha agendada":"Envio da campanha iniciado")}catch(re){o.error("Falha ao enviar campanha",{description:re instanceof Error?re.message:void 0})}finally{_(!1)}}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("header",{className:"flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between",children:[e.jsxs("div",{children:[e.jsx(y,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-3 mb-2 gap-2",children:e.jsxs(Sn,{to:"/admin/emails",children:[e.jsx(Lr,{className:"h-4 w-4"}),"Voltar para caixa"]})}),e.jsxs("h1",{className:"flex items-center gap-2 text-2xl font-bold",children:[e.jsx(Fa,{className:"h-6 w-6"}),"Email Marketing"]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Contatos, segmentos, campanhas, consentimento e métricas pela Resend."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(y,{variant:"outline",onClick:()=>{_t(`aiclub-marketing-${Aa(new Date,"yyyy-MM-dd")}
731.csv`,s.campaigns),o.success("Relatório exportado")},disabled:!s.campaigns.length,className:"min-h-11 gap-2",children:[e.jsx(na,{className:"h-4 w-4"}),"Exportar"]}),e.jsxs(y,{variant:"outline",onClick:()=>void N(),disabled:c,className:"min-h-11 gap-2",children:[e.jsx(Qe,{className:`h-4 w-4 ${c?"animate-spin":""}`}),"Atualizar"]}),e.jsxs(y,{onClick:()=>Q(!0),disabled:!s.segments.length,className:"min-h-11 gap-2",children:[e.jsx(ei,{className:"h-4 w-4"}),"Nova campanha"]})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 xl:grid-cols-4",children:[e.jsxs(la,{children:[e.jsxs(xa,{className:"pb-2",children:[e.jsx(ha,{children:"Contatos ativos"}),e.jsx(pa,{className:"text-3xl",children:ce})]}),e.jsx(ga,{children:e.jsxs("p",{className:"text-xs text-muted-foreground",children:[s.contacts.length-ce," descadastrado(s)"]})})]}),e.jsxs(la,{children:[e.jsxs(xa,{className:"pb-2",children:[e.jsx(ha,{children:"Segmentos"}),e.jsx(pa,{className:"text-3xl",children:s.segments.length})]}),e.jsx(ga,{children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"Audiências para campanhas"})})]}),e.jsxs(la,{children:[e.jsxs(xa,{className:"pb-2",children:[e.jsx(ha,{children:"Campanhas"}),e.jsx(pa,{className:"text-3xl",children:s.campaigns.length})]}),e.jsx(ga,{children:e.jsxs("p",{className:"text-xs text-muted-foreground",children:[s.campaigns.filter(T=>T.status==="draft").length," ","rascunho(s)"]})})]}),e.jsxs(la,{children:[e.jsxs(xa,{className:"pb-2",children:[e.jsx(ha,{children:"Compliance"}),e.jsxs(pa,{className:"flex items-center gap-2 text-lg",children:[e.jsx(_n,{className:"h-5 w-5 text-emerald-500"}),"Descadastro ativo"]})]}),e.jsx(ga,{children:e.jsx("p",{className:"text-xs text-muted-foreground",children:"Resend bloqueia contatos descadastrados."})})]})]}),e.jsxs(za,{defaultValue:"campaigns",children:[e.jsxs(Ba,{className:"h-auto flex-wrap justify-start",children:[e.jsx(Fs,{value:"campaigns",children:"Campanhas"}),e.jsx(Fs,{value:"contacts",children:"Contatos"}),e.jsx(Fs,{value:"segments",children:"Segmentos"}),e.jsx(Fs,{value:"reputation",children:"Saúde de entrega"})]}),e.jsx(Qs,{value:"campaigns",className:"mt-4",children:e.jsxs(la,{children:[e.jsxs(xa,{children:[e.jsx(pa,{children:"Campanhas"}),e.jsx(ha,{children:"Crie rascunhos, revise e confirme envio imediato ou agendado."})]}),e.jsx(ga,{className:"overflow-x-auto",children:c?e.jsx("div",{className:"flex min-h-40 items-center justify-center",children:e.jsx(he,{className:"h-6 w-6 animate-spin"})}):s.campaigns.length?e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Campanha"}),e.jsx(f,{children:"Segmento"}),e.jsx(f,{children:"Status"}),e.jsx(f,{children:"Entregues"}),e.jsx(f,{children:"Aberturas"}),e.jsx(f,{className:"text-right",children:"Ação"})]})}),e.jsx(De,{children:s.campaigns.map(T=>e.jsxs(b,{children:[e.jsxs(a,{children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[T.name,T.variant?e.jsxs(Re,{variant:"outline",children:["Variante ",T.variant]}):null]}),e.jsx("div",{className:"max-w-72 truncate text-xs text-muted-foreground",children:T.subject})]}),e.jsx(a,{children:T.segment_name}),e.jsxs(a,{children:[e.jsx(Re,{variant:T.status==="failed"?"destructive":T.status==="sent"?"default":"secondary",children:om[T.status]}),T.scheduled_at?e.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:Aa(new Date(T.scheduled_at),"dd/MM HH:mm",{locale:Mr})}):null]}),e.jsx(a,{children:fn(T,"delivered")}),e.jsx(a,{children:fn(T,"opened")}),e.jsx(a,{className:"text-right",children:T.status==="draft"&&T.variant!=="B"?e.jsxs(y,{size:"sm",onClick:()=>K(T),className:"gap-2",children:[e.jsx(It,{className:"h-4 w-4"}),T.experiment_id?"Revisar teste":"Revisar envio"]}):T.status==="draft"?e.jsx("span",{className:"text-xs text-muted-foreground",children:"Envia junto com A"}):e.jsx(nr,{className:"ml-auto h-5 w-5 text-muted-foreground"})})]},T.id))})]}):e.jsxs("div",{className:"py-12 text-center text-sm text-muted-foreground",children:[e.jsx(Fa,{className:"mx-auto mb-3 h-8 w-8"}),"Nenhuma campanha criada."]})})]})}),e.jsx(Qs,{value:"contacts",className:"mt-4",children:e.jsxs(la,{children:[e.jsxs(xa,{className:"flex-row items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(pa,{children:"Contatos"}),e.jsx(ha,{children:"Somente contatos com consentimento devem permanecer inscritos."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(y,{variant:"outline",onClick:()=>{_t(`aiclub-contatos-${Aa(new Date,"yyyy-MM-dd")}.csv`,s.contacts),o.success("Contatos exportados")},disabled:!s.contacts.length,className:"gap-2",children:[e.jsx(na,{className:"h-4 w-4"}),"Exportar"]}),e.jsxs(y,{variant:"outline",onClick:()=>V(!0),className:"gap-2",children:[e.jsx(or,{className:"h-4 w-4"}),"Importar"]}),e.jsxs(y,{onClick:()=>w(!0),className:"gap-2",children:[e.jsx(Us,{className:"h-4 w-4"}),"Contato"]})]})]}),e.jsxs(ga,{className:"overflow-x-auto",children:[e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Contato"}),e.jsx(f,{children:"E-mail"}),e.jsx(f,{children:"Inscrito"})]})}),e.jsx(De,{children:s.contacts.map(T=>e.jsxs(b,{children:[e.jsx(a,{children:[T.first_name,T.last_name].filter(
731Boolean).join(" ")||"Sem nome"}),e.jsx(a,{children:T.email}),e.jsx(a,{children:e.jsx(Vs,{checked:!T.unsubscribed,"aria-label":`Inscrição de ${T.email}`,onCheckedChange:async re=>{try{await em(T.id,!re),n(ke=>({...ke,contacts:ke.contacts.map(fe=>fe.id===T.id?{...fe,unsubscribed:!re}:fe)})),o.success(re?"Contato inscrito":"Contato descadastrado")}catch(ke){o.error("Não foi possível atualizar contato",{description:ke instanceof Error?ke.message:void 0})}}})})]},T.id))})]}),s.contacts.length?null:e.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:"Nenhum contato cadastrado."})]})]})}),e.jsx(Qs,{value:"segments",className:"mt-4",children:e.jsxs(la,{children:[e.jsxs(xa,{className:"flex-row items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(pa,{children:"Segmentos"}),e.jsx(ha,{children:"Separe contatos por interesse, origem ou etapa comercial."})]}),e.jsxs(y,{onClick:()=>g(!0),className:"gap-2",children:[e.jsx(Us,{className:"h-4 w-4"}),"Segmento"]})]}),e.jsxs(ga,{children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:s.segments.map(T=>e.jsxs("div",{className:"flex min-h-20 items-center gap-3 rounded-xl border border-border p-4",children:[e.jsx(sa,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:T.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Audiência Resend"})]})]},T.id))}),s.segments.length?null:e.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:"Crie primeiro segmento para iniciar campanhas."})]})]})}),e.jsx(Qs,{value:"reputation",className:"mt-4",children:e.jsxs(la,{children:[e.jsxs(xa,{children:[e.jsxs(pa,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"Saúde de entrega"]}),e.jsxs(ha,{children:["Eventos da Resend nos últimos ",s.reputation.window_days," ","dias. Não representa nota oficial do domínio."]})]}),e.jsxs(ga,{children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[["Entrega",`${s.reputation.delivery_rate}%`,s.reputation.delivered],["Bounces",`${s.reputation.bounce_rate}%`,s.reputation.bounced],["Reclamações",`${s.reputation.complaint_rate}%`,s.reputation.complained],["Suprimidos",String(s.reputation.suppressed),s.reputation.suppressed]].map(([T,re,ke])=>e.jsxs("div",{className:"rounded-xl border p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:T}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:re}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ke," evento(s)"]})]},String(T)))}),e.jsxs("div",{className:"mt-4 rounded-xl bg-muted/40 p-4 text-sm text-muted-foreground",children:["Base: ",s.reputation.sent," envios. Aberturas:"," ",s.reputation.opened,". Cliques: ",s.reputation.clicked,". Falhas: ",s.reputation.failed,"."]})]})]})})]}),e.jsx(ds,{open:k,onOpenChange:g,children:e.jsxs(cs,{children:[e.jsxs(ms,{children:[e.jsx(us,{children:"Novo segmento"}),e.jsx(ra,{children:"Ex.: Leads, Clientes ativos ou Restaurantes."})]}),e.jsxs("form",{onSubmit:D,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"segment-name",children:"Nome"}),e.jsx(je,{id:"segment-name",value:l,onChange:T=>h(T.target.value),required:!0,maxLength:100,autoFocus:!0})]}),e.jsxs(Bs,{children:[e.jsx(y,{type:"button",variant:"ghost",onClick:()=>g(!1),children:"Cancelar"}),e.jsx(y,{disabled:m,children:m?"Criando…":"Criar segmento"})]})]})]})}),e.jsx(ds,{open:x,onOpenChange:w,children:e.jsxs(cs,{children:[e.jsxs(ms,{children:[e.jsx(us,{children:"Novo contato"}),e.jsx(ra,{children:"Adicione somente pessoas que autorizaram comunicações de marketing."})]}),e.jsxs("form",{onSubmit:i,className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"contact-first",children:"Nome"}),e.jsx(je,{id:"contact-first",value:v.firstName,onChange:T=>R(re=>({...re,firstName:T.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"contact-last",children:"Sobrenome"}),e.jsx(je,{id:"contact-last",value:v.lastName,onChange:T=>R(re=>({...re,lastName:T.target.value}))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"contact-email",children:"E-mail"}),e.jsx(je,{id:"contact-email",type:"email",inputMode:"email",value:v.email,onChange:T=>R(re=>({...re,email:T.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Segmento"}),e.jsxs(as,{value:v.segmentId||"none",onValueChange:T=>R(re=>({...re,segmentId:T==="none"?"":T})),children:[e.jsx(rs,{children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"none",children:"Sem segmento"}),s.segments.map(T=>e.jsx(pe,{value:T.id,children:T.name},T.id))]})]})]}),e.jsxs(Bs,{children:[e.jsx(y,{type:"button",variant:"ghost",onClick:()=>w(!1),children:"Cancelar"}),e.jsx(y,{disabled:m,children:m?"Salvando…":"Adicionar contato"})]})]})]})}),e.jsx(ds,{open:$,onOpenChange:V,children:e.jsxs(cs,{children:[e.jsxs(m
731s,{children:[e.jsx(us,{children:"Importar contatos"}),e.jsx(ra,{children:"Até 100 linhas no formato e-mail; nome; sobrenome. Confirme consentimento antes de importar."})]}),e.jsxs("form",{onSubmit:A,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"contact-import",children:"Contatos"}),e.jsx(Ss,{id:"contact-import",rows:10,value:C,onChange:T=>ee(T.target.value),placeholder:"[email protected]; Ana; Silva",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Segmento"}),e.jsxs(as,{value:Z||"none",onValueChange:T=>p(T==="none"?"":T),children:[e.jsx(rs,{children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"none",children:"Sem segmento"}),s.segments.map(T=>e.jsx(pe,{value:T.id,children:T.name},T.id))]})]})]}),e.jsxs(Bs,{children:[e.jsx(y,{type:"button",variant:"ghost",onClick:()=>V(!1),children:"Cancelar"}),e.jsxs(y,{disabled:m,className:"gap-2",children:[e.jsx(or,{className:"h-4 w-4"}),m?"Importando…":"Importar"]})]})]})]})}),e.jsx(ds,{open:z,onOpenChange:Q,children:e.jsxs(cs,{className:"max-h-[90dvh] overflow-y-auto sm:max-w-2xl",children:[e.jsxs(ms,{children:[e.jsx(us,{children:"Nova campanha"}),e.jsx(ra,{children:"Será criada como rascunho. Envio exige confirmação separada."})]}),e.jsxs("form",{onSubmit:O,className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-xl border p-4",children:[e.jsxs("div",{children:[e.jsx(oe,{htmlFor:"campaign-ab",children:"Teste A/B"}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"Duas versões para segmentos distintos, sem destinatário duplicado."})]}),e.jsx(Vs,{id:"campaign-ab",checked:B,onCheckedChange:G})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"campaign-name",children:"Nome interno"}),e.jsx(je,{id:"campaign-name",value:ae.name,onChange:T=>Y(re=>({...re,name:T.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Modelo"}),e.jsxs(as,{onValueChange:T=>{const re=im[T];Y(ke=>({...ke,subject:re.subject,bodyText:re.body,ctaLabel:re.cta}))},children:[e.jsx(rs,{children:e.jsx(ts,{placeholder:"Escolher modelo"})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"novidade",children:"Novidade"}),e.jsx(pe,{value:"conteudo",children:"Conteúdo"}),e.jsx(pe,{value:"oferta",children:"Oferta"}),e.jsx(pe,{value:"reativacao",children:"Reativação"})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Segmento"}),e.jsxs(as,{value:ae.segmentId,onValueChange:T=>Y(re=>({...re,segmentId:T})),required:!0,children:[e.jsx(rs,{children:e.jsx(ts,{placeholder:"Escolha audiência"})}),e.jsx(ns,{children:s.segments.map(T=>e.jsx(pe,{value:T.id,children:T.name},T.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"campaign-subject",children:"Assunto"}),e.jsx(je,{id:"campaign-subject",value:ae.subject,onChange:T=>Y(re=>({...re,subject:T.target.value})),required:!0,maxLength:998})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"campaign-preview",children:"Prévia"}),e.jsx(je,{id:"campaign-preview",value:ae.previewText,onChange:T=>Y(re=>({...re,previewText:T.target.value})),maxLength:200})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"campaign-body",children:"Mensagem"}),e.jsx(Ss,{id:"campaign-body",rows:10,value:ae.bodyText,onChange:T=>Y(re=>({...re,bodyText:T.target.value})),required:!0})]}),B?e.jsxs("div",{className:"space-y-4 rounded-xl border border-primary/30 bg-primary/5 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Variante B"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Use uma audiência diferente da variante A."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{children:"Segmento B"}),e.jsxs(as,{value:q.segmentId,onValueChange:T=>E(re=>({...re,segmentId:T})),required:!0,children:[e.jsx(rs,{children:e.jsx(ts,{placeholder:"Escolha outra audiência"})}),e.jsx(ns,{children:s.segments.filter(T=>T.id!==ae.segmentId).map(T=>e.jsx(pe,{value:T.id,children:T.name},T.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"campaign-subject-b",children:"Assu
731nto B"}),e.jsx(je,{id:"campaign-subject-b",value:q.subject,onChange:T=>E(re=>({...re,subject:T.target.value})),required:!0,maxLength:998})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"campaign-body-b",children:"Mensagem B"}),e.jsx(Ss,{id:"campaign-body-b",rows:8,value:q.bodyText,onChange:T=>E(re=>({...re,bodyText:T.target.value})),required:!0})]})]}):null,e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"campaign-cta",children:"Texto do botão"}),e.jsx(je,{id:"campaign-cta",value:ae.ctaLabel,onChange:T=>Y(re=>({...re,ctaLabel:T.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"campaign-url",children:"Link HTTPS"}),e.jsx(je,{id:"campaign-url",type:"url",value:ae.ctaUrl,onChange:T=>Y(re=>({...re,ctaUrl:T.target.value})),placeholder:"https://"})]})]}),e.jsxs(Bs,{children:[e.jsx(y,{type:"button",variant:"ghost",onClick:()=>Q(!1),children:"Cancelar"}),e.jsx(y,{disabled:m,children:m?"Salvando…":"Salvar rascunho"})]})]})]})}),e.jsx(ds,{open:!!P,onOpenChange:T=>{!T&&!m&&(K(null),W(""))},children:e.jsxs(cs,{children:[e.jsxs(ms,{children:[e.jsx(us,{children:"Confirmar campanha"}),e.jsxs(ra,{children:["Esta ação enviará “",P==null?void 0:P.subject,"” para segmento “",P==null?void 0:P.segment_name,"”. Contatos de
731scadastrados serão excluídos automaticamente pela Resend."]})]}),e.jsxs("form",{onSubmit:te,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"campaign-schedule",children:"Agendar opcionalmente"}),e.jsx(je,{id:"campaign-schedule",type:"datetime-local",value:J,onChange:T=>W(T.target.value),min:new Date(Date.now()+6e4).toISOString().slice(0,16)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Vazio envia agora. Horário usa fuso deste dispositivo."})]}),e.jsxs("div",{className:"rounded-xl border border-amber-500/30 bg-amber-500/10 p-4 text-sm",children:[e.jsx("strong",{children:"Revise audiência e conteúdo."})," Envio imediato não pode ser desfeito pelo painel."]}),e.jsxs(Bs,{children:[e.jsx(y,{type:"button",variant:"ghost",onClick:()=>K(null),children:"Cancelar"}),e.jsxs(y,{disabled:m,className:"gap-2",children:[e.jsx(Oo,{className:"h-4 w-4"}),m?"Confirmando…":J?"Agendar campanha":"Enviar agora"]})]})]})]})})]})}const vn=[{title:"Principal",items:[{id:"overview",label:"Painel de Controle",icon:zo},{id:"users",label:"Usuários",icon:sa},{id:"revenue",label:"Receita & MRR",icon:Ua},{id:"recovery",label:"Recuperação",icon:Ar},{id:"logs",label:"Logs de Erros",icon:qs},{id:"generation-audit",label:"Gerações",icon:Ma},{id:"credits",label:"Créditos",icon:ta},{id:"pricing-tiers",label:"Preços por Segundo",icon:ca},{id:"credit-audit",label:"Auditoria",icon:Qe},{id:"plans",label:"Planos",icon:$n},{id:"database",label:"Banco de Dados",icon:sr},{id:"affiliates",label:"Afiliados",icon:At},{id:"community",label:"Comunidade",icon:Xs},{id:"tickets",label:"Tickets de Suporte",icon:Pn},{id:"bans",label:"Banimentos",icon:tr},{id:"reports",label:"Denúncias",icon:Mn},{id:"comfyui",label:"ComfyUI",icon:Ra},{id:"system-map",label:"Mapa do Sistema",icon:Ra},{id:"cloakify-presets",label:"Camuflador",icon:Cn},{id:"university",label:"Universidade",icon:Rn},{id:"voices",label:"Vozes (TTS)",icon:On},{id:"docs",label:"Documentação IA",icon:Dn}]},{title:"Comunicação",items:[{id:"emails",label:"Caixa de entrada",icon:Pt},{id:"email-marketing",label:"Email Marketing",icon:Fa}]},{title:"Templates de Prompt",items:[{id:"prompt-describe",label:"Detalhar Prompt",icon:bi},{id:"prompt-design-creator",label:"Design Creator",icon:Fa},{id:"prompt-faceswap",label:"Model Swap",icon:sa},{id:"prompt-caption",label:"Captions",icon:Lt},{id:"prompt-agents",label:"Agentes (UGC/Photoshoot/Dataset/Avatar)",icon:yn}]}],oi={"visao-geral":"overview",usuarios:"users",receita:"revenue",recuperacao:"recovery",logs:"logs",geracoes:"generation-audit",creditos:"credits","precos-por-segundo":"pricing-tiers",auditoria:"credit-audit",planos:"plans","banco-de-dados":"database",afiliados:"affiliates",comunidade:"community",banimentos:"bans",denuncias:"reports","mapa-do-sistema":"system-map",documentacao:"docs",universidade:"university",tickets:"tickets",camuflador:"cloakify-presets","detalhar-prompt":"prompt-describe","design-creator":"prompt-design-creator","model-swap":"prompt-faceswap",captions:"prompt-caption",agentes:"prompt-agents",vozes:"voices",comfyui:"comfyui",emails:"emails","email-marketing":"email-marketing"},dm=Object.fromEntries(Object.entries(oi).map(([s,n])=>[n,s])),px=()=>{const s=fr(),{tab:n}=kn(),{isAdmin:c,loading:u}=Va(),{startImpersonation:m}=bn(),[_,k]=r.useState(!0),g=n&&oi[n]||"overview",l=L=>{const d=dm[L]||"visao-geral";s(`/admin/${d}`,{replace:!0})},[h,x]=r.useState([]),[w,v]=r.useState({totalUsers:0,totalImages:0,totalVideos:0}),[R,$]=r.useState(""),[V,C]=r.useState("all"),[ee,Z]=r.useState("all"),[p,z]=r.useState("newest"),[Q,ae]=r.useState(!0),[Y,B]=r.useState(!1),[G,q]=r.useState(""),[E,P]=r.useState(""),[K,J]=r.useState(""),[W,N]=r.useState(!1),[ce,D]=r.useState(!1),[i,A]=r.useState(!1),[O,te]=r.useState([]),[T,re]=r.useState(!1),[ke,fe]=r.useState(""),[X,me]=r.useState(null),[_e,$e]=r.useState(null),[Ve,Je]=r.useState(""),[we,We]=r.useState("purchased"),[Ge,ps]=r.useState(!1),[be,ue]=r.useState(null),[Pe,ze]=r.useState(null),[Ie,xs]=r.useState([]);r.useEffect(()=>{!u&&!c&&s("/playground/image",{replace:!0}),!u&&c&&!n&&s("/admin/visao-geral",{replace:!0})},[u,c,s,n]),r.useEffect(()=>{c&&(es(),Ze(),Ps())},[c]);const Ps=async()=>{const{data:L}=await F.from("subscription_plans").select("slug, name, monthly_credits").eq("is_active",!0).order("sort_order");if(L){const d=new Set(["premium","maker","pro","studio","creator"]);xs(L.map(le=>({slug:le.slug,name:le.name,monthly_credits:le.monthly_credits,is_premium_tier:d.has(le.slug.toLowerCase())})))}},Ze=async()=>{var L;re(!0);try{const[d,le,S]=await Promise.all([F.from("error_logs").select("*").order("created_at",{ascending:!1}).limit(200),F.from("profiles").select("user_id, nickname"),F.functions.invoke("admin-list-emails")]),de={};
731(le.data||[]).forEach(Ke=>{de[Ke.user_id]=Ke.nickname||""});const Ce=((L=S.data)==null?void 0:L.emailMap)||{},Oe=(d.data||[]).map(Ke=>({...Ke,user_nickname:Ke.user_id&&de[Ke.user_id]||"",user_email:Ke.user_id&&Ce[Ke.user_id]||""}));te(Oe)}catch(d){console.error("Failed to fetch logs:",d)}finally{re(!1)}},es=async()=>{var L;ae(!0);try{const[d,le,S,de,Ce,Oe]=await Promise.all([F.from("profiles").select("user_id, nickname, avatar_url, is_premium, is_paid, is_partner, premium_credits, purchased_credits, subscription_plan, subscription_status, plan_slug, subscription_renews_at, subscription_started_at, subscription_interval, trial_ends_at, credits_expire_at, created_at, stripe_customer_id, stripe_subscription_id"),F.from("user_roles").select("user_id, role"),F.from("generations").select("*",{count:"exact",head:!0}).eq("media_type","image"),F.from("generations").select("*",{count:"exact",head:!0}).eq("media_type","video"),F.functions.invoke("admin-list-emails"),F.from("webhook_logs").select("user_id, event_type").in("event_type",["customer.subscription.deleted","charge.refunded","charge.dispute.created","subscription_revoked"]).order("created_at",{ascending:!1})]),Ke=d.data,qe=le.data,Me=S.count,Be=de.count,Is=((L=Ce.data)==null?void 0:L.emailMap)||{},ks={};(Oe.data||[]).forEach(Ye=>{!Ye.user_id||ks[Ye.user_id]||(Ye.event_type==="charge.dispute.created"?ks[Ye.user_id]="chargeback":Ye.event_type==="charge.refunded"?ks[Ye.user_id]="refunded":(Ye.event_type==="customer.subscription.deleted"||Ye.event_type==="subscription_revoked")&&(ks[Ye.user_id]="canceled"))});const Ys=(Ke||[]).map(Ye=>{const Js=qe==null?void 0:qe.find(lr=>lr.user_id===Ye.user_id),ua=ks[Ye.user_id]||null,$s=Ye.subscription_status;let ea=null;return $s==="past_due"||$s==="unpaid"||$s==="incomplete"||$s==="incomplete_expired"||$s==="payment_failed"?ea="canceled":$s==="canceled"?ea=ua==="chargeback"?"chargeback":ua==="refunded"?"refunded":"canceled":$s==="active"||$s==="trialing"?ea="active":ua&&!Ye.is_paid?ea=ua:Ye.is_paid&&(ea="active"),{user_id:Ye.user_id,nickname:Ye.nickname,avatar_url:Ye.avatar_url,email:Is[Ye.user_id]||"",role:(Js==null?void 0:Js.role)||"user",is_premium:Ye.is_premium??!1,is_paid:Ye.is_paid??!1,is_partner:Ye.is_partner??!1,premium_credits:Ye.premium_credits??0,purchased_credits:Ye.purchased_credits??0,subscription_plan:Ye.subscription_plan||(Ye.plan_slug??"free"),subscription_status:$s,plan_slug:Ye.plan_slug||null,subscription_started_at:Ye.subscription_started_at||null,subscription_renews_at:Ye.subscription_renews_at||null,stripe_customer_id:Ye.stripe_customer_id||null,stripe_subscription_id:Ye.stripe_subscription_id||null,created_at:Ye.created_at,account_status:ea}});x(Ys),v({totalUsers:Ys.length,totalImages:Me||0,totalVideos:Be||0})}catch(d){o.error(d.message)}finally{ae(!1)}},ws=async(L,d)=>{try{await F.from("user_roles").delete().eq("user_id",L);const{error:le}=await F.from("user_roles").insert({user_id:L,role:d});if(le)throw le;o.success("Papel atualizado!"),es()}catch(le){o.error(le.message)}},is=async(L,d)=>{var le,S;try{let de;if(d==="free")de={is_paid:!1,is_premium:!1,subscription_plan:"free",plan_slug:null,premium_credits:0,manual_plan_override:!0};else{const qe=Ie.find(Be=>Be.slug===d);if(!qe){o.error("Plano não encontrado");return}const Me=jo(new Date,1).toISOString();de={is_paid:!0,is_premium:qe.is_premium_tier,subscription_plan:d,plan_slug:d,premium_credits:qe.monthly_credits,credits_expire_at:Me,subscription_started_at:new Date().toISOString(),subscription_renews_at:Me,subscription_interval:"month",subscription_status:"active",manual_plan_override:!0}}const{error:Ce}=await F.from("profiles").update(de).eq("user_id",L);if(Ce)throw Ce;const Oe=d==="free"?"Free":((le=Ie.find(qe=>qe.slug===d))==null?void 0:le.name)||d,Ke=(S=h.find(qe=>qe.user_id===L))==null?void 0:S.is_partner;o.success(Ke&&d!=="free"?`Plano alterado para ${Oe}! Parceiro: créditos renovam todo mês nesta data.`:`Plano alterado para ${Oe}! (override manual ativo)`),x(qe=>qe.map(Me=>Me.user_id===L?{...Me,...de}:Me))}catch(de){o.error(de.message)}},os=async(L,d)=>{try{const{error:le}=await F.from("profiles").update({is_partner:d}).eq("user_id",L);if(le)throw le;o.success(d?"Marcado como Parceiro!":"Parceiro removido"),x(S=>S.map(de=>de.user_id===L?{...de,is_partner:d}:de))}catch(le){o.error(le.message)}},H=async L=>{if(confirm("Tem certeza que deseja remover este usuário? Esta ação é irreversível."))try{const{data:d,error:le}=await F.functions.invoke("admin-delete-user",{body:{userId:L}});if(le)throw le;if(d!=null&&d.error)throw new Error(d.error);o.success("Usuário removido do sistema"),es()}catch(d){o.error(d.message)}},xe=async()=>
731{if(!G||!E){o.error("E-mail e senha são obrigatórios");return}D(!0);try{const{data:L,error:d}=await F.functions.invoke("admin-create-user",{body:{email:G,password:E,fullName:K}});if(d)throw d;if(L!=null&&L.error)throw new Error(L.error);o.success(`Usuário ${G} criado com sucesso!`),B(!1),q(""),P(""),J(""),es()}catch(L){o.error(L.message||"Erro ao criar usuário")}finally{D(!1)}},Ne=async()=>{if(!_e)return;const L=parseInt(Ve);if(isNaN(L)||L===0){o.error("Informe um valor válido");return}ps(!0);try{const d=we==="premium"?"premium_credits":"purchased_credits",le=we==="premium"?_e.premium_credits||0:_e.purchased_credits||0,S=Math.max(0,le+L),{error:de}=await F.from("profiles").update({[d]:S}).eq("user_id",_e.user_id);if(de)throw de;const Ce=we==="premium"?"plano":"avulsos";o.success(`${L>0?"+":""}${L} créditos ${Ce} → saldo: ${S}`),x(Oe=>Oe.map(Ke=>Ke.user_id===_e.user_id?{...Ke,[d]:S}:Ke)),$e(null),Je("")}catch(d){o.error(d.message)}finally{ps(!1)}},Xe=async L=>{if(!L.email){o.error("E-mail do usuário não encontrado");return}ue(L.user_id);try{const{data:d,error:le}=await F.functions.invoke("admin-sync-stripe",{body:{userId:L.user_id,email:L.email}});if(le)throw le;if(d!=null&&d.error)throw new Error(d.error);o.success(`Stripe sincronizado: ${d.plan||"free"} ${d.is_trialing?"(trial)":""}`),es()}catch(d){o.error(d.message||"Erro ao sincronizar Stripe")}finally{ue(null)}},bs=async()=>{var L;A(!0);try{const{data:d,error:le}=await F.functions.invoke("admin-cleanup-past-due");if(le)throw le;if(d!=null&&d.error)throw new Error(d.error);const S=((L=d.processed)==null?void 0:L.filter(de=>de.status==="revoked"))||[];S.length>0?(o.success(`${S.length} usuário(s) past_due revogados com sucesso`),es()):o.info(`Nenhum usuário para revogar (${d.total_past_due} encontrados no Stripe, todos já tratados)`)}catch(d){o.error(d.message||"Erro ao limpar past_due")}finally{A(!1)}},Rs=async L=>{const d=h.find(de=>de.user_id===L);if(!d){o.error("Usuário não encontrado");return}ze(L);const le=d.nickname||d.email||d.user_id.slice(0,8);await m(L,le)&&(o.success(`Logado como: ${le}`),s("/playground/image")),ze(null)},gs=L=>L.subscription_status==="past_due"?"past_due":L.subscription_status==="payment_failed"?"payment_failed":L.subscription_status==="unpaid"?"unpaid":L.subscription_status==="incomplete"||L.subscription_status==="incomplete_expired"?"incomplete":L.account_status==="chargeback"?"chargeback":L.account_status==="refunded"?"refunded":L.account_status==="canceled"?"canceled":L.account_status==="active"?"active":"none",hs=h.filter(L=>{const d=(L.nickname||"").toLowerCase().includes(R.toLowerCase())||(L.email||"").toLowerCase().includes(R.toLowerCase())||L.user_id.includes(R),le=(L.subscription_plan||"free").toLowerCase(),S=V==="all"||le===V||V==="free"&&!L.is_paid,de=ee==="all"||gs(L)===ee;return d&&S&&de}).sort((L,d)=>{const le=new Date(L.created_at).getTime(),S=new Date(d.created_at).getTime();return p==="newest"?S-le:le-S});if(u||!c&&!u)return null;const As=()=>{switch(g){case"overview":return e.jsx(cn,{});case"revenue":return e.jsx(Bd,{});case"recovery":return e.jsx(Kd,{});case"comfyui":return e.jsx(ec,{});case"plans":return e.jsx(Cd,{});case"credits":return e.jsx(Jo,{});case"pricing-tiers":return e.jsx(Xo,{});case"credit-audit":return e.jsx(pl,{});case"generation-audit":return e.jsx(jl,{});case"database":return e.jsx(Vl,{});case"docs":return e.jsx(Ul,{});case"university":return e.jsx("div",{className:"rounded-xl border border-border/40 bg-card/50 p-6",children:e.jsx($l,{})});case"voices":return e.jsx("div",{className:"rounded-xl border border-border/40 bg-card/50 p-6",children:e.jsx(hd,{})});case"affiliates":return e.jsx("div",{className:"rounded-xl border border-border/40 bg-card/50 p-6",children:e.jsx(pd,{})});case"community":return e.jsx("div",{className:"rounded-xl border border-border/40 bg-card/50 p-6",children:e.jsx(vd,{})});case"bans":return e.jsx("div",{className:"rounded-xl border border-border/40 bg-card/50 p-6",children:e.jsx(yd,{})});case"reports":return e.jsx("div",{className:"rounded-xl border border-border/40 bg-card/50 p-6",children:e.jsx(wd,{})});case"system-map":return e.jsx(kd,{});case"tickets":return e.jsx("div",{className:"rounded-xl border border-border/40 bg-card/50 p-6",children:e.jsx(ic,{})});case"emails":return e.jsx(Yc,{});case"email-marketing":return e.jsx(lm,{});case"cloakify-presets":return e.jsx("div",{className:"rounded-xl border border-border/40 bg-card/50 p-6",children:e.jsx(xc,{})});case"prompt-describe":return e.jsx(zl,{});case"prompt-design-creator":return e.jsx(Yl,{});case"prompt-faceswap":return e.jsx(Gl,{});case"prompt-caption":return e.jsx(Hl,{});case"prompt-agents":return e.jsx(xd,{});case"logs":return Hs();case"users":return Gs();default:return e.jsx(cn,{})}},Gs=()=>e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4 mb-6",children:[{icon:sa,value:w.totalUsers,label:"Usuários",highlight:!0},{icon:Ma,value:w.totalImages,label:"Imagens geradas"},{icon:yi,value:w.totalVideos,label:"Vídeos gerados"}].map((L,d)=>e.jsxs("div",{className:Ue("rounded-xl border border-border/40 bg-card/50 p-5 flex items-center gap-4",L.highlight&&"border-primary/30 bg-primary/5"),children:[e.jsx("div",{className:Ue("w-10 h-10 rounded-lg flex items-center justify-center",L.highlight?"bg-primary/15":"bg-secondary"),children:e.jsx(L.icon,{className:Ue("w-5 h-5",L.highlight?"text-primary":"text-muted-foreground")})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-display font-bold",children:L.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:L.label})]})]},d))}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-card/50 p-6",children:[e.jsxs("div",{className:"flex flex-col gap-4 mb-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("h2",{className:"font-display font-semibold flex items-center gap-2 text-lg",children:["Gestão de Usuários",e.jsx(Re,{variant:"secondary",className:"text-xs",children:hs.length})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(y,{size:"sm",variant:"destructive",className:"gap-2",onClick:bs,disabled:i,children:[i?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(qs,{className:"w-4 h-4"}),"Limpar Past Due"]}),e.jsxs(ds,{open:Y,onOpenChange:B,children:[e.jsx(_i,{asChild:!0,children:e.jsxs(y,{size:"sm",className:"gap-2",children:[e.jsx(jr,{className:"w-4 h-4"})," Novo Usuário"]})}),e.jsxs(cs,{className:"sm:max-w-md",children:[e.jsx(ms,{children:e.jsx(us,{children:"Cadastrar Novo Usuário"})}),e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"new-name",children:"Nome completo"}),e.jsx(je,{id:"new-name",value:K,onChange:L=>J(L.target.value),placeholder:"Nome do usuário"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"new-email",children:"E-mail *"}),e.jsx(je,{id:"new-email",type:"email",value:G,onChange:L=>q(L.target.value),placeholder:"[email protected]",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{htmlFor:"new-password",children:"Senha *"}),e.jsxs("div",{className:"relative",children:[e.jsx(je,{id:"new-password",type:W?"text":"password",value:E,onChange:L=>P(L.target.value),placeholder:"Mínimo 6 caracteres",className:"pr-10",required:!0,minLength:6}),e.jsx("button",{type:"button",onClick:()=>N(!W),className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:W?e.jsx(Ln,{className:"w-4 h-4"}):e.jsx(ia,{className:"w-4 h-4"})})]})]}),e.jsxs(y,{onClick:xe,className:"w-full gap-2",disabled:ce,children:[ce?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(jr,{className:"w-4 h-4"}),ce?"Criando...":"Criar Usuário"]})]})]})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative w-64",children:[e.jsx(aa,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(je,{value:R,onChange:L=>$(L.target.value),placeholder:"Buscar por nome, e-mail...",className:"pl-10 h-9"})]}),e.jsxs(as,{value:V,onValueChange:C,children:[e.jsx(rs,{className:"w-[140px] h-9 text-xs",children:e.jsx(ts,{placeholder:"Plano"})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"all",children:"Todos os planos"}),e.jsx(pe,{value:"free",children:"Free"}),Ie.map(L=>e.jsx(pe,{value:L.slug,children:L.name},L.slug))]})]}),e.jsxs(as,{value:ee,onValueChange:Z,children:[e.jsx(rs,{className:"w-[160px] h-9 text-xs",children:e.jsx(ts,{placeholder:"Status"})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"all",children:"Todos os status"}),e.jsx(pe,{value:"active",children:"Ativo"}),e.jsx(pe,{value:"past_due",children:"Atrasado"}),e.jsx(pe,{value:"payment_failed",children:"Pagamento falhou"}),e.jsx(pe,{value:"unpaid",children:"Não pago"}),e.jsx(pe,{value:"incomplete",children:"Incompleto"}),e.jsx(pe,{value:"canceled",children:"Cancelado"}),e.jsx(pe,{value:"refunded",children:"Reembolsado"}),e.jsx(pe,{value:"chargeback",children:"Chargeback"}),e.jsx(pe,{value:"none",children:"Sem status"})]})]}),e.jsxs(as,{value:p,onValueChange:L=>
731z(L),children:[e.jsx(rs,{className:"w-[140px] h-9 text-xs",children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"newest",children:"Mais recentes"}),e.jsx(pe,{value:"oldest",children:"Mais antigos"})]})]})]})]}),Q?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{children:"Usuário"}),e.jsx(f,{children:"Papel"}),e.jsx(f,{children:"Plano"}),e.jsx(f,{children:"Parceiro"}),e.jsx(f,{className:"text-right",children:"Plano"}),e.jsx(f,{className:"text-right",children:"Avulsos"}),e.jsx(f,{children:"Renovação"}),e.jsx(f,{children:"Status"}),e.jsx(f,{children:"Desde"}),e.jsx(f,{children:"Stripe"})]})}),e.jsxs(De,{children:[hs.map(L=>{var d,le;return e.jsxs(b,{children:[e.jsx(a,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-secondary overflow-hidden flex items-center justify-center shrink-0",children:L.avatar_url?e.jsx("img",{src:L.avatar_url,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((le=(d=L.nickname)==null?void 0:d[0])==null?void 0:le.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:L.nickname||"Sem nome"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:L.email||L.user_id.slice(0,8)+"..."})]})]})}),e.jsx(a,{children:e.jsxs(as,{value:L.role,onValueChange:S=>ws(L.user_id,S),children:[e.jsx(rs,{className:"w-32 h-8 text-xs",children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"user",children:"Usuário"}),e.jsx(pe,{value:"moderator",children:"Moderador"}),e.jsx(pe,{value:"admin",children:"Admin"})]})]})}),e.jsx(a,{children:(()=>{var Me;const S=L.subscription_status==="past_due"||L.subscription_status==="canceled"||L.subscription_status==="unpaid"||L.subscription_status==="incomplete"||L.subscription_status==="incomplete_expired"||L.subscription_status==="payment_failed",de=L.subscription_plan&&L.subscription_plan!=="free"?L.subscription_plan:"free",Ce=S?"free":de,Oe=Ie.find(Be=>Be.slug===Ce),Ke=!S&&((Oe==null?void 0:Oe.is_premium_tier)??L.is_premium),qe=S&&de!=="free"?`Plano original: ${((Me=Ie.find(Be=>Be.slug===de))==null?void 0:Me.name)||de} (sem acesso por ${L.subscription_status})`:void 0;return e.jsxs(as,{value:Ce,onValueChange:Be=>is(L.user_id,Be),children:[e.jsx(rs,{title:qe,className:Ue("w-[140px] h-8 text-xs font-semibold border-0",Ce==="free"?"bg-secondary text-muted-foreground":Ke?"bg-yellow-500/15 text-yellow-500":"bg-green-500/15 text-green-500"),children:e.jsx(ts,{})}),e.jsxs(ns,{children:[e.jsx(pe,{value:"free",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Lo,{className:"w-3.5 h-3.5 text-muted-foreground"})," Free"]})}),Ie.map(Be=>e.jsx(pe,{value:Be.slug,children:e.jsxs("span",{className:"flex items-center gap-2",children:[Be.is_premium_tier?e.jsx(wn,{className:"w-3.5 h-3.5 text-yellow-500"}):e.jsx(rr,{className:"w-3.5 h-3.5 text-green-500"}),Be.name]})},Be.slug))]})]})})()}),e.jsx(a,{children:e.jsxs("button",{onClick:()=>os(L.user_id,!L.is_partner),className:Ue("inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold transition-colors",L.is_partner?"bg-blue-500/15 text-blue-400":"bg-secondary text-muted-foreground hover:text-foreground"),children:[e.jsx(Xs,{className:"w-3 h-3"}),L.is_partner?"Parceiro":"—"]})}),e.jsx(a,{className:"text-right",children:e.jsxs(y,{variant:"ghost",size:"sm",className:Ue("gap-1 h-7 px-2 tabular-nums",L.premium_credits>0?"text-primary hover:text-primary":"text-muted-foreground"),onClick:()=>{$e(L),Je(""),We("premium")},title:"Gerenciar créditos do plano",children:[e.jsx(ta,{className:"w-3.5 h-3.5"}),L.premium_credits]})}),e.jsx(a,{className:"text-right",children:e.jsxs(y,{variant:"ghost",size:"sm",className:Ue("gap-1 h-7 px-2 tabular-nums",L.purchased_credits>0?"text-primary hover:text-primary":"text-muted-foreground"),onClick:()=>{$e(L),Je(""),We("purchased")},title:"Gerenciar créditos avulsos",children:[e.jsx(ta,{className:"w-3.5 h-3.5"}),L.purchased_credits]})}),e.jsx(a,{className:"text-xs text-muted-foreground",children:L.subscription_renews_at?new Date(L.subscription_renews_at).toLocaleDateString("pt-BR"):"—"}),e.jsx(a,{children:(()=>{const S=L.subscription_status==="past_due"?{icon:Or,label:"Atrasado",cls:"bg-amber-500/10 border-amber-500/40 text-amber-500"}:L.subscription_status==="payment_failed"?{icon:qs,label:"Pagamento falhou",cls:"bg-amber-500/10 border-amber-500/40 text-amber-500"}:L.subscription_status==="unpaid"?{icon:tr,label:"Não pago",cls:"bg-red-500/10 border-red-500/40 text-red-400"}:L.subscription_status==="incomplete"||L.subscription_status==="incomplete_expired"?{icon:Or,label:"Incompleto",cls:"bg-orange-500/10 border-orange-500/40 text-orange-400"}:L.account_status==="chargeback"?{icon:Da,label:"Chargeback",cls:"bg-red-500/15 border-red-500/50 text-red-400"}:L.account_status==="refunded"?{icon:Qe,label:"Reembolsado",cls:"bg-orange-500/10 border-orange-500/40 text-orange-400"}:L.account_status==="canceled"?{icon:Da,label:"Cancelado",cls:"bg-red-500/10 border-red-500/40 text-red-400"}:L.account_status==="active"?{icon:nr,label:"Ativo",cls:"bg-green-500/10 border-green-500/40 text-green-400"}:null;if(!S)return e.jsx("span",{className:"text-xs text-muted-foreground",children:"—"});const de=S.icon;
731return e.jsxs("span",{className:Ue("inline-flex items-center gap-1.5 whitespace-nowrap rounded-full border px-2.5 py-1 text-[11px] font-medium leading-none",S.cls),children:[e.jsx(de,{className:"w-3 h-3 shrink-0"}),S.label]})})()}),e.jsx(a,{className:"text-xs text-muted-foreground",children:new Date(L.created_at).toLocaleDateString("pt-BR")}),e.jsx(a,{children:e.jsxs("div",{className:"flex flex-col gap-2",children:[L.stripe_customer_id||L.stripe_subscription_id?e.jsxs("div",{className:"flex flex-col gap-0.5",children:[L.stripe_customer_id&&e.jsx("a",{href:`https://dashboard.stripe.com/customers/${L.stripe_customer_id}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline",children:"Cliente ↗"}),L.stripe_subscription_id?e.jsxs("a",{href:`https://dashboard.stripe.com/subscriptions/${L.stripe_subscription_id}`,target:"_blank",rel:"noopener noreferrer",className:"text-[10px] text-primary/80 hover:text-primary hover:underline font-mono truncate max-w-[140px]",title:`Abrir assinatura ${L.stripe_subscription_id}`,children:[L.stripe_subscription_id.slice(0,18),"… ↗"]}):L.stripe_customer_id&&e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"sem assinatura"})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"— sem stripe"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(y,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-primary",onClick:()=>Xe(L),disabled:be===L.user_id,title:"Sincronizar com Stripe",children:be===L.user_id?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(Qe,{className:"w-4 h-4"})}),e.jsx(y,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-primary",onClick:()=>Rs(L.user_id),disabled:Pe===L.user_id,title:"Logar como este usuário",children:Pe===L.user_id?e.jsx(he,{className:"w-4 h-4 animate-spin"}):e.jsx(En,{className:"w-4 h-4"})}),e.jsx(y,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>H(L.user_id),children:e.jsx(_s,{className:"w-4 h-4"})})]})]})})]},L.user_id)}),hs.length===0&&e.jsx(b,{children:e.jsx(a,{colSpan:10,className:"text-center text-muted-foreground py-8",children:"Nenhum usuário encontrado"})})]})]})})]}),e.jsx(ds,{open:!!_e,onOpenChange:L=>!L&&$e(null),children:e.jsxs(cs,{className:"sm:max-w-sm",children:[e.jsx(ms,{children:e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(ta,{className:"w-4 h-4"})," Gerenciar Créditos IA"]})}),_e&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm space-y-2",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Usuário:"})," ",_e.nickname||_e.email]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 p-2.5 rounded-md bg-secondary/50",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-0.5",children:"Plano"}),e.jsx("p",{className:"text-lg font-bold tabular-nums",children:_e.premium_credits})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wider text-muted-foreground mb-0.5",children:"Avulsos"}),e.jsx("p",{className:"text-lg font-bold tabular-nums",children:_e.purchased_credits})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:["Total: ",e.jsx("strong",{children:_e.premium_credits+_e.purchased_credits})," créditos"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(oe,{className:"text-xs text-muted-foreground",children:"Tipo de crédito"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(y,{variant:we==="premium"?"default":"outline",size:"sm",className:"flex-1 h-8 text-xs",onClick:()=>We("premium"),children:"Plano"}),e.jsx(y,{variant:we==="purchased"?"default":"outline",size:"sm",className:"flex-1 h-8 text-xs",onClick:()=>We("purchased"),children:"Avulsos"})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(oe,{className:"text-xs text-muted-foreground",children:"Quantidade (positivo = adicionar, negativo = remover)"}),e.jsx(je,{type:"number",value:Ve,onChange:L=>Je(L.target.value),placeholder:"Ex: 100 ou -50",className:"h-9"}),Ve&&!isNaN(parseInt(Ve))&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Novo saldo ",we==="premium"?"plano":"avulsos",": ",e.jsx("strong",{children:Math.max(0,(we==="premium"?_e.premium_credits:_e.purchased_credits)+parseInt(Ve))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(y,{variant:"outline",size:"sm",onClick:()=>$e(null),children:"Cancelar"}),e.jsxs(y,{size:"sm",onClick:Ne,disabled:Ge,className:"gap-2",children:[Ge?e.jsx(he,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(ta,{className:"w-3.5 h-3.5"}),"Aplicar"]})]})]})]})})]}),Hs=()=>e.jsxs("div",{className:"rounded-xl border border-border/40 bg-card/50 p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 gap-4 flex-wrap",children:[e.jsxs("h2",{className:"font-display font-semibold flex items-center gap-2 text-lg",children:["Logs de Erros",e.jsx(Re,{variant:"secondary",className:"text-xs",children:O.length})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative w-64",children:[e.jsx(aa,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(je,{value:ke,onChange:L=>fe(L.target.value),placeholder:"Filtrar por função, erro, usuário...",className:"pl-10 h-9"})]}),e.jsxs(y,{variant:"outline",size:"sm",onClick:Ze,className:"gap-2",children:[e.jsx(Qe,{className:"w-3.5 h-3.5"})," Atualizar"]}),O.length>0&&e.jsxs(y,{variant:"destructive",size:"sm",className:"gap-2",onClick:async()=>
731{if(!confirm("Tem certeza que deseja limpar todos os logs de erros?"))return;const{error:L}=await F.from("error_logs").delete().neq("id","00000000-0000-0000-0000-000000000000");if(L){o.error("Erro ao limpar logs");return}te([]),o.success("Logs limpos com sucesso")},children:[e.jsx(_s,{className:"w-3.5 h-3.5"})," Limpar"]})]})]}),T?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(he,{className:"w-6 h-6 animate-spin text-muted-foreground"})}):O.length===0?e.jsxs("div",{className:"text-center text-muted-foreground py-12",children:[e.jsx(qs,{className:"w-8 h-8 mx-auto mb-3 opacity-40"}),e.jsx("p",{className:"text-sm",children:"Nenhum erro registrado"})]}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Te,{children:[e.jsx(Le,{children:e.jsxs(b,{children:[e.jsx(f,{className:"w-36",children:"Data"}),e.jsx(f,{className:"w-40",children:"Usuário"}),e.jsx(f,{className:"w-36",children:"Função"}),e.jsx(f,{className:"w-28",children:"Código"}),e.jsx(f,{children:"Erro"}),e.jsx(f,{className:"w-48",children:"Ação Tentada"}),e.jsx(f,{className:"w-16"})]})}),e.jsx(De,{children:O.filter(L=>{if(!ke)return!0;const d=ke.toLowerCase();return L.function_name.toLowerCase().includes(d)||L.error_message.toLowerCase().includes(d)||(L.error_code||"").toLowerCase().includes(d)||(L.user_id||"").toLowerCase().includes(d)||(L.user_nickname||"").toLowerCase().includes(d)||(L.user_email||"").toLowerCase().includes(d)}).map(L=>{const d=L.request_body,le=[];d&&(d.prompt&&le.push(`Prompt: "${typeof d.prompt=="string"?d.prompt.slice(0,60):d.prompt}${typeof d.prompt=="string"&&d.prompt.length>60?"…":""}"`),d.model&&le.push(`Modelo: ${d.model}`),d.aspect_ratio&&le.push(`Ratio: ${d.aspect_ratio}`),d.quality&&le.push(d.quality));const S=le.length>0?le.join(" · "):"—";return e.jsxs(b,{className:"cursor-pointer hover:bg-muted/70",onClick:()=>me(L),children:[e.jsx(a,{className:"text-xs text-muted-foreground whitespace-nowrap",children:new Date(L.created_at).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})}),e.jsx(a,{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:L.user_nickname||"Desconhecido"}),e.jsx("p",{className:"text-[10px] text-muted-foreground truncate",children:L.user_email||(L.user_id?L.user_id.slice(0,12)+"…":"Sem usuário")})]})}),e.jsx(a,{children:e.jsx(Re,{variant:"outline",className:"text-xs font-mono",children:L.function_name})}),e.jsx(a,{children:L.error_code&&e.jsx(Re,{variant:"destructive",className:"text-xs",children:L.error_code})}),e.jsxs(a,{className:"text-xs max-w-xs truncate",title:L.error_message,children:[L.error_message.substring(0,100),L.error_message.length>100?"…":""]}),e.jsxs(a,{className:"text-xs text-muted-foreground max-w-[200px] truncate",title:S,children:[S.substring(0,80),S.length>80?"…":""]}),e.jsx(a,{children:e.jsx(y,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:de=>{de.stopPropagation(),me(L)},children:e.jsx(ia,{className:"w-3.5 h-3.5"})})})]},L.id)})})]})}),e.jsx(ds,{open:!!X,onOpenChange:L=>!L&&me(null),children:e.jsxs(cs,{className:"sm:max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(ms,{children:e.jsxs(us,{className:"flex items-center gap-2",children:[e.jsx(qs,{className:"w-4 h-4 text-destructive"})," Detalhes do Erro"]})}),X&&e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"rounded-lg bg-secondary/50 p-4 space-y-2",children:[e.jsx("h4",{className:"font-semibold text-xs uppercase text-muted-foreground tracking-wider",children:"Usuário"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Nome"}),e.jsx("p",{className:"font-medium",children:X.user_nickname||"Desconhecido"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"E-mail"}),e.jsx("p",{className:"font-medium",children:X.user_email||"—"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"User ID"}),e.jsx("p",{className:"font-mono text-xs",children:X.user_id||"—"})]})]})]}),e.jsxs("div",{className:"rounded-lg bg-destructive/10 p-4 space-y-2",children:[e.jsx("h4",{className:"font-semibold text-xs uppercase text-muted-foreground tracking-wider",children:"Erro"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Função"}),e.jsx(Re,{variant:"outline",className:"font-mono",children:X.function_name})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Código"}),e.jsx("p",{children:X.error_code||"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Data/Hora"}
731),e.jsx("p",{children:new Date(X.created_at).toLocaleString("pt-BR")})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Mensagem"}),e.jsx("p",{className:"text-xs bg-background/50 rounded p-2 whitespace-pre-wrap break-all",children:X.error_message})]})]}),X.request_body&&e.jsxs("div",{className:"rounded-lg bg-secondary/50 p-4 space-y-2",children:[e.jsx("h4",{className:"font-semibold text-xs uppercase text-muted-foreground tracking-wider",children:"O que o usuário estava tentando fazer"}),e.jsx("pre",{className:"text-xs bg-background/50 rounded p-3 overflow-x-auto whitespace-pre-wrap break-all max-h-60",children:JSON.stringify(X.request_body,null,2)})]}),X.metadata&&e.jsxs("div",{className:"rounded-lg bg-secondary/50 p-4 space-y-2",children:[e.jsx("h4",{className:"font-semibold text-xs uppercase text-muted-foreground tracking-wider",children:"Metadata"}),e.jsx("pre",{className:"text-xs bg-background/50 rounded p-3 overflow-x-auto whitespace-pre-wrap break-all max-h-60",children:JSON.stringify(X.metadata,null,2)})]})]})]})})]}),Ls=vn.flatMap(L=>L.items).find(L=>L.id===g);return u?e.jsx("div",{className:"h-screen bg-background flex items-center justify-center",children:e.jsx(he,{className:"w-8 h-8 animate-spin text-muted-foreground"})}):c?e.jsxs("div",{className:"h-screen bg-background flex overflow-hidden",children:[e.jsxs("aside",{className:Ue("h-full border-r border-border/40 bg-card/30 backdrop-blur-sm flex flex-col shrink-0 transition-all duration-300",_?"w-64":"w-14"),children:[e.jsxs("div",{className:"h-14 flex items-center gap-3 px-3 border-b border-border/30 shrink-0",children:[e.jsx("button",{onClick:()=>k(!_),className:"w-8 h-8 rounded-lg flex items-center justify-center hover:bg-secondary transition-colors text-muted-foreground hover:text-foreground",children:e.jsx(Ni,{className:"w-4 h-4"})}),_&&e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(rr,{className:"w-5 h-5 text-primary shrink-0"}),e.jsx("span",{className:"font-display font-bold text-sm truncate",children:"Painel Admin"})]})]}),e.jsx(Rt,{className:"flex-1 py-2",children:vn.map(L=>e.jsxs("div",{className:"mb-1",children:[_&&e.jsx("p",{className:"px-4 py-2 text-[10px] uppercase tracking-widest text-muted-foreground/60 font-semibold",children:L.title}),e.jsx("nav",{className:"space-y-0.5 px-2",children:L.items.map(d=>{const le=g===d.id;return e.jsxs("button",{onClick:()=>l(d.id),title:_?void 0:d.label,className:Ue("w-full flex items-center gap-3 rounded-lg text-sm transition-all duration-150",_?"px-3 py-2":"px-0 py-2 justify-center",le?"bg-primary/10 text-primary font-medium shadow-sm":"text-muted-foreground hover:text-foreground hover:bg-secondary/60"),children:[e.jsx(d.icon,{className:Ue("shrink-0",_?"w-4 h-4":"w-4.5 h-4.5")}),_&&e.jsx("span",{className:"truncate",children:d.label})]},d.id)})})]},L.title))}),e.jsx("div",{className:"border-t border-border/30 p-2 shrink-0",children:e.jsxs("button",{onClick:()=>s("/playground/image"),className:Ue("w-full flex items-center gap-3 rounded-lg text-sm text-muted-foreground hover:text-foreground hover:bg-secondary/60 transition-colors",_?"px-3 py-2":"px-0 py-2 justify-center"),children:[e.jsx(Lr,{className:"w-4 h-4 shrink-0"}),_&&e.jsx("span",{children:"Voltar ao Studio"})]})})]}),e.jsxs("main",{className:"flex-1 flex flex-col min-w-0 overflow-hidden",children:[e.jsx("header",{className:"h-14 flex items-center gap-3 px-6 border-b border-border/30 bg-card/20 backdrop-blur-sm shrink-0",children:e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(rr,{className:"w-4 h-4 text-primary"}),e.jsx("span",{className:"text-muted-foreground",children:"Admin"}),e.jsx(Sa,{className:"w-3.5 h-3.5 text-muted-foreground/50"}),e.jsx("span",{className:"font-medium",children:Ls==null?void 0:Ls.label})]})}),e.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:As()})]})]}):null};export{px as default};

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