PageSourceSearch

https://brik.space/assets/ToolEditorSwitch-CozFpYWq.js

js brik.space collected 2026-09-25 19:07:00 UTC 470,421 bytes, 98 lines download raw bytes

1import{ad as Ha,j as e,r as n,bN as Xc,bT as sf,bO as rf,bQ as af,bR as of,bS as lf,c1 as go,ak as Hs,ai as ua,g2 as cf,at as Fr,du as Ki,d3 as Xo,d4 as vr,c0 as Zn,d5 as $s,d1 as Vs,d6 as bo,cl as Nn,S as Cu,a2 as Hr,a0 as In,e as Wt,k as za,y as df,$ as Qc,ah as ed,bZ as gs,d as D,bU as uf,bV as ir,bX as lr,g3 as pf,g4 as Sd,an as Ko,dn as xf,c5 as Ci,bg as ff,am as mf,bo as kl,a5 as la,a6 as ca,a7 as ju,a8 as da,a9 as ku,g5 as hf,g6 as gf,ca as Nu,g7 as bf,cH as Yo,cG as Su,O as po,K as Nl,P as Sl,b$ as vf,F as Ua,al as Tl,g8 as yf,g9 as Fa,ga as _f,bn as wf,G as td,gb as wl,fp as nd,gc as Cf,gd as jf,ge as xo,gf as fo,gg as mo,dv as Tu,bY as kf,gh as Nf,gi as Sf,gj as Tf,b as Rf,gk as Ef,bt as If,cF as sd,bi as nt,b5 as $n,fD as Df,b3 as yn,fC as Mf,b8 as rd,fR as Af,fF as Td,gl as $a,gm as Pf,b4 as Of,cs as Lf,dO as Bf,ba as Ff,dN as $f,aa as pa,a1 as Vf,a4 as Hi,a as ql,gn as Ru,c as Eu,f as Iu,t as Du,x as Mu,go as Au,gp as Pu,i as Ho,bp as Ou,gq as Rl,dW as La,gr as zo,bM as Ss,dY as Uo,gs as Lu,gt as Bu,gu as El,gv as Fu,gw as $u,f$ as Vu,gx as Hu,gy as zu,gz as Uu,gA as Bc,gB as Gu,gC as Wu,gD as qu,b1 as Ku,cn as Yu,gE as Zu,b2 as Ju,gF as Il,gG as Xu,d2 as uc,gH as Hf,u as zf}from"./appBoot-DBJ5ahS-.js";import{C as Uf,g as Gf,r as Qu}from"./toolMetadata-Dk22e5E7.js";import{P as Wf,E as xn,a as _n,u as qf,T as Kf,b as Yf,c as Zf,R as Rd,d as Jf,e as ho,f as Xf,M as ep,g as tp,h as Qf,i as np,j as sp,S as rp,k as em,l as tm,m as nm,I as sm,L as rm,C as am,n as Ed,o as om,p as im,q as lm}from"./RenderQueueButton-3ZJG_Kp8.js";import{D as ap,L as cm,A as dm}from"./DrawerIcon-CffYQhS9.js";import{i as um,r as op}from"./recentlyOpened-BGCMeDm0.js";import{u as pm}from"./useMutation-CVbFNMDW.js";import{s as xm,f as ip,p as lp,r as fm,M as mm,T as hm}from"./agentApi-BE8CpOtk.js";import{C as cp,F as dp,u as gm,a as bm,e as vm,i as pc,g as ym,f as _m}from"./ComposerInputRow-rYqRM6Nd.js";import{u as wm}from"./useTypingPlaceholder-Bg-sEOBH.js";import{t as $r,E as Cm}from"./select-mYfN2Yhb.js";import{C as up}from"./ChevronDownIcon-Cb4TsSYn.js";import{a as pp,e as jm,f as Dl,g as km,d as ad,M as Nm,c as xc,o as Sm,t as Tm}from"./menuChrome-COhsT6e1.js";import{u as Rm,C as Em,M as Id,V as xp,a as od,b as fp}from"./VoiceMicButton-CfdN6aO-.js";import{P as Ga,a as Wa,b as qa}from"./popover-CmdtPS_f.js";import{T as Kl}from"./InlineAlert-CmjZ0mJH.js";import{D as id,b as Yl,E as Im}from"./EditPencilIcon-BDq6aUPt.js";import{C as Dm}from"./ConfirmDialog-DTes442I.js";import{i as Zo,p as ji,P as fc}from"./PlanQuestionsCard-BkYTE9I2.js";import{F as mp}from"./file-text-BjQi5VFk.js";import{G as Mm}from"./grip-vertical-KTht7oFY.js";import{C as Qo}from"./check-fawfteD7.js";import{C as Yi}from"./copy-C5y9_lBu.js";import{C as vo}from"./chevron-down-BYZ3KCAq.js";import{C as yo}from"./chevron-right-OW5kRsB0.js";import{D as zi}from"./DisabledReasonTooltip-DItpBETh.js";import{a as Am,C as hp,P as Pm,X as Om}from"./TextBadge-Db4WDafm.js";import{u as Zl,C as Lm,M as Bm,P as Fm,S as $m,L as Vm,a as Jt,p as Hm,b as Dd,c as zm,d as Um,t as Go,e as Ml,f as Vr,g as Al,T as Gm}from"./ToolControlsPanel-BbgmHVue.js";import{P as gp}from"./palette-vj8vymSI.js";import{b as Wm,S as bp}from"./UserMenuQuota-D9Ehdw55.js";import{E as Pl}from"./eye-DCWNi5ZW.js";import{S as qm}from"./search-BEvRKCBB.js";import{S as vp}from"./sparkles-C0yk9Y3H.js";import{E as yp}from"./eye-off-DiIjT93E.js";import{T as _p}from"./trash-2-CafyFSBh.js";import{V as wp,R as Cp}from"./CreateToolIcon-Bq31l9gm.js";import{T as jp,w as ld,H as Ui}from"./TextInput-Gs4WX3rx.js";import{A as Md}from"./ArrowForwardIcon-C9SQ-6Ub.js";import{A as Km}from"./arrow-left-EKDq__14.js";import{A as Ad}from"./arrow-right-BxNQ9qxu.js";import{p as Ym,a as lo,b as kp}from"./biButtons-CAjKF8Lv.js";import{t as Ie}from"./toast-D7mIkDp8.js";import{Y as Pd,P as Zm,H as Np}from"./MediaManagerHost-BZkm0ppg.js";import{T as Gi,k as Jm,L as Xm}from"./SettingsModal-Bv96OYTI.js";import{P as Bi}from"./plus-B9Rowqz7.js";import{S as Qm}from"./save-CrsZ3hp7.js";import{C as eh}from"./circle-alert-DCik7gyE.js";import{P as th}from"./play-BueORstv.js";import{U as Fi}from"./upload-BL-MVQb1.js";import{C as nh}from"./camera-CBxUIxWv.js";import{V as sh}from"./video-BZgZouom.js";import{B as Fc}
1from"./Badge-phHZR525.js";import{D as rh,a as ah,b as oh,d as Od}from"./dropdown-menu-CrOP99rX.js";import{H as ih}from"./HomeHeader-2DaHh80L.js";import{I as lh}from"./IdleOverlay-ofSZpZK8.js";import{G as $c}from"./globe-bzNdGsl7.js";import{u as cd,D as Wi}from"./RemixIcon-nWMPugOJ.js";import"./index-BpR0y34i.js";import"./PricingPlanCard-C9upKWjI.js";import"./CustomPlanModal-BREC5qBa.js";import{I as ch,a as Sp}from"./fontPreviewLoader-B4CegDxY.js";import{A as dh}from"./arrow-up-5hSJ38gb.js";import{C as uh}from"./chevron-left-D2Oa25lU.js";import{S as ph}from"./square-pen-CjCZTKCb.js";import{u as xh}from"./UserAvatar-DKeljiE9.js";import{r as fh,f as mh,m as hh}from"./toolStillCapture-B-qCfsAo.js";import{A as Tp}from"./timeline-CCJAy-E_.js";import{T as Rp,D as Ep}from"./toolControls-CYSc6lnV.js";import{u as gh}from"./appMenuStyles-5xG4t4vY.js";import{u as Ip}from"./useRemixTool-Cieq9I6K.js";import{e as Dp}from"./isTypingTarget-CCUyq5t2.js";import{e as dd}from"./extractPosterFromBlob-DavU4x_F.js";import{c as Ld,d as qi,n as ud,a as Ol,g as Ll,b as Wo,e as Mp}from"./toolTags-C7XPDdUj.js";import{D as bh,b as vh,r as yh,n as Jo,w as Bl,s as Ap,a as Pp,c as Op,d as Ba,M as _h}from"./toolName-DgTml39u.js";import"./index-Jq0mIgmH.js";import"./ControlRenderer-BNQv_RWY.js";import"./mediaManager-DB55-abD.js";import"./media-manager.data-hooks-Dw7yvSdn.js";import"./color-5hdXErkH.js";import"./fontUrls-QOAwkfmO.js";import"./link-CFnmRDl_.js";import"./switch-IOfMfd7I.js";import"./index-CvgpAMRp.js";import"./BrikLoader-Bo90r9Lm.js";import"./usePlanCheckout-x8DXJsbW.js";import"./PlanChangePreviewDialog-C23Skg0g.js";import"./brand-BR0WcRE0.js";import"./billingAnalytics-Bnz1JGZ4.js";import"./PlanCard-DRtdLSWM.js";import"./info-Cuh2X9ye.js";import"./reactExport-BVzVRrLr.js";import"./ControlRendererV2-B3F0T2tm.js";import"./TextArea-CVpKQ4m9.js";import"./SegmentedButtons-DQqH3UzN.js";import"./box-7pAX9Wdr.js";import"./atom-CYbIbger.js";import"./textarea-m42LLlJd.js";import"./download-CJzqyR4n.js";import"./square-Bvjfp-i8.js";import"./bookmark-Gq_I3p7G.js";import"./workspace-CgMtad6L.js";import"./docs-CCdFHTo2.js";import"./image-Bk-C9Eih.js";import"./index-C1psWGM9.js";import"./chevron-up-BPq_fwxF.js";import"./gem-CoBlSF31.js";import"./sharedUserMedia-BkQoJR7s.js";import"./usePricingCheckout-DezcXkx8.js";import"./ChevronRightIcon-jNDHrE4b.js";import"./useInfiniteQuery-D8I9l9N1.js";import"./music-ehrWv10W.js";import"./film-gODazmK4.js";import"./formatBytes-BUdPTGxu.js";import"./index-C5GYCJi6.js";import"./folder-BzG562IW.js";import"./three.module-BTt32e3U.js";/**
2 * @license lucide-react v0.475.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 wh=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]],Ch=Ha("Activity",wh);/**
7 * @license lucide-react v0.475.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 jh=[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]],Lp=Ha("BookOpen",jh);/**
12 * @license lucide-react v0.475.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 kh=[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]],Nh=Ha("Brain",kh);/**
17 * @license lucide-react v0.475.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 Sh=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],Th=Ha("Ellipsis",Sh);/**
22 * @license lucide-react v0.475.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 Rh=[["path",{d:"M12.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v9.5",key:"1couwa"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M13.378 15.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1y4qbx"}]],Bd=Ha("FilePen",Rh);/**
27 * @license lucide-react v0.475.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 Eh=[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}],["path",{d:"m15 5 3 3",key:"1w25hb"}]],Ih=Ha("PencilLine",Eh);/**
32 * @license lucide-react v0.475.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 Dh=[["line",{x1:"4",x2:"4",y1:"21",y2:"14",key:"1p332r"}],["line",{x1:"4",x2:"4",y1:"10",y2:"3",key:"gb41h5"}],["line",{x1:"12",x2:"12",y1:"21",y2:"12",key:"hf2csr"}],["line",{x1:"12",x2:"12",y1:"8",y2:"3",key:"1kfi7u"}],["line",{x1:"20",x2:"20",y1:"21",y2:"16",key:"1lhrwl"}],["line",{x1:"20",x2:"20",y1:"12",y2:"3",key:"16vvfq"}],["line",{x1:"2",x2:"6",y1:"14",y2:"14",key:"1uebub"}],["line",{x1:"10",x2:"14",y1:"8",y2:"8",key:"1yglbp"}],["line",{x1:"18",x2:"22",y1:"16",y2:"16",key:"1jxqpz"}]],Bp=Ha("SlidersVertical",Dh);/**
37 * @license lucide-react v0.475.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 Mh=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]],Ah=Ha("Wrench",Mh);function Fp({className:t}){return e.jsx("svg",{viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":!0,
41children:e.jsx("path",{d:"M7.5 1.25C4.05 1.25 1.25 4.05 1.25 7.5C1.25 10.95 4.05 13.75 7.5 13.75C10.95 13.75 13.75 10.95 13.75 7.5C13.75 4.05 10.95 1.25 7.5 1.25ZM6.875 12.4563C4.40625 12.15 2.5 10.05 2.5 7.5C2.5 7.1125 2.55 6.74375 2.63125 6.38125L5.625 9.375V10C5.625 10.6875 6.1875 11.25 6.875 11.25V12.4563ZM11.1875 10.8687C11.025 10.3625 10.5625 10 10 10H9.375V8.125C9.375 7.78125 9.09375 7.5 8.75 7.5H5V6.25H6.25C6.59375 6.25 6.875 5.96875 6.875 5.625V4.375H8.125C8.8125 4.375 9.375 3.8125 9.375 3.125V2.86875C11.2063 3.6125 12.5 5.40625 12.5 7.5C12.5 8.8 12 9.98125 11.1875 10.8687Z",fill:"currentColor"})})}function pd({className:t}){return e.jsx("svg",{viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":!0,children:e.jsx("path",{d:"M11 8.17L6.49 3.66C8.07 2.61 9.96 2 12 2C17.52 2 22 6.48 22 12C22 14.04 21.39 15.93 20.34 17.51L18.88 16.05C19.59 14.87 20 13.48 20 12C20 8.65 17.93 5.78 15 4.59V5C15 6.1 14.1 7 13 7H11V8.17ZM21.19 21.19L19.78 22.6L17.51 20.33C15.93 21.39 14.04 22 12 22C6.48 22 2 17.52 2 12C2 9.96 2.61 8.07 3.66 6.49L1.39 4.22L2.8 2.81L21.19 21.19ZM11 18C9.9 18 9 17.1 9 16V15L4.21 10.21C4.08 10.79 4 11.38 4 12C4 16.08 7.05 19.44 11 19.93V18Z",fill:"currentColor"})})}function Ph({className:t}){return e.jsxs("svg",{viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":!0,children:[e.jsx("path",{d:"M10.5187 2.5L9.375 1.25H5.625L4.48125 2.5H1.25V12.5H13.75V2.5H10.5187ZM7.5 10.625C5.775 10.625 4.375 9.225 4.375 7.5C4.375 5.775 5.775 4.375 7.5 4.375C9.225 4.375 10.625 5.775 10.625 7.5C10.625 9.225 9.225 10.625 7.5 10.625Z",fill:"currentColor"}),e.jsx("path",{d:"M7.5 9.375C8.53553 9.375 9.375 8.53553 9.375 7.5C9.375 6.46447 8.53553 5.625 7.5 5.625C6.46447 5.625 5.625 6.46447 5.625 7.5C5.625 8.53553 6.46447 9.375 7.5 9.375Z",fill:"var(--product-white-00)"})]})}function $p({className:t}){return e.jsx("svg",{viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":!0,children:e.jsx("path",{d:"M7.5 12.5C10.2614 12.5 12.5 10.2614 12.5 7.5C12.5 4.73858 10.2614 2.5 7.5 2.5C4.73858 2.5 2.5 4.73858 2.5 7.5C2.5 10.2614 4.73858 12.5 7.5 12.5Z",fill:"currentColor"})})}function Oh({className:t}){return e.jsx("svg",{viewBox:"0 0 22 22",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":!0,children:e.jsx("path",{d:"M5.5 5.5H16.5V16.5H5.5V5.5Z",fill:"currentColor"})})}function Lh({className:t}){return e.jsxs("svg",{viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":!0,children:[e.jsx("path",{d:"M4.21875 6.5625L1.40625 9.375L4.21875 12.1875",fill:"currentColor"}),e.jsx("path",{d:"M4.21875 12.1875L1.40625 9.375L4.21875 6.5625M1.40625 9.375L9.375 9.375C10.2452 9.375 11.0798 9.0293 11.6952 8.41394C12.3105 7.79859 12.6563 6.96399 12.6563 6.09375C12.6563 5.22351 12.3105 4.38891 11.6952 3.77356C11.0798 3.1582 10.2452 2.8125 9.375 2.8125L4.21875 2.8125",stroke:"currentColor",strokeWidth:"1.5"})]})}function Bh({className:t}){return e.jsx("svg",{viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":!0,children:e.jsx("path",{d:"M7.5 10C8.1875 10 8.75 10.5625 8.75 11.25C8.75 11.9375 8.1875 12.5 7.5 12.5C6.8125 12.5 6.25 11.9375 6.25 11.25C6.25 10.5625 6.8125 10 7.5 10ZM7.5 6.25C8.1875 6.25 8.75 6.8125 8.75 7.5C8.75 8.1875 8.1875 8.75 7.5 8.75C6.8125 8.75 6.25 8.1875 6.25 7.5C6.25 6.8125 6.8125 6.25 7.5 6.25ZM7.5 2.5C8.1875 2.5 8.75 3.0625 8.75 3.75C8.75 4.4375 8.1875 5 7.5 5C6.8125 5 6.25 4.4375 6.25 3.75C6.25 3.0625 6.8125 2.5 7.5 2.5Z",fill:"currentColor"})})}function Fh({className:t}){return e.jsx("svg",{viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":!0,children:e.jsx("path",{d:"M8.125 1.875C5.01875 1.875 2.5 4.39375 2.5 7.5H0.625L3.05625 9.93125L3.1 10.0188L5.625 7.5H3.75C3.75 5.08125 5.70625 3.125 8.125 3.125C10.5437 3.125 12.5 5.08125 12.5 7.5C12.5 9.91875 10.5437 11.875 8.125 11.875C6.91875 11.875 5.825 11.3813 5.0375 10.5875L4.15 11.475C5.16875 12.4937 6.56875 13.125 8.125 13.125C11.2312 13.125 13.75 10.6062 13.75 7.5C13.75 4.39375 11.2312 1.875 8.125 1.875ZM7.5 5V8.125L10.1562 9.7L10.6375 8.89375L8.4375 7.5875V5H7.5Z",fill:"currentColor"})})}function $h({className:t}){return e.jsxs("svg",{viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":!0,
41children:[e.jsx("rect",{width:"15",height:"15",fill:"var(--product-black-00)"}),e.jsx("path",{d:"M9.36429 7.38571C10.45 7.62857 11.2786 8.41429 11.2786 9.48571V9.82857C11.2786 11.5571 9.79286 12.5 7.73571 12.5H3.72143V2.5H7.66429C9.76429 2.5 11.0071 3.45714 11.0071 4.97143V5.25714C11.0071 6.38571 10.1786 7.14286 9.36429 7.38571ZM7.50714 3.74286H5.09286V6.78571H7.53571C8.93571 6.78571 9.63571 6.24286 9.63571 5.31429V5.17143C9.63571 4.14286 8.80714 3.74286 7.50714 3.74286ZM9.90714 9.54286C9.90714 8.52857 9.12143 8.02857 7.62143 8.02857H5.09286V11.2571H7.62143C9.12143 11.2571 9.90714 10.7429 9.90714 9.71429V9.54286Z",fill:"var(--product-white-00)"})]})}function Vh({className:t}){return e.jsx("svg",{viewBox:"0 0 22 22",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":!0,children:e.jsx("path",{d:"M3.66667 11L4.95917 12.2925L10.0833 7.1775V18.3333H11.9167V7.1775L17.0317 12.3017L18.3333 11L11 3.66667L3.66667 11Z",fill:"currentColor"})})}function Fd({className:t}){return e.jsx("svg",{viewBox:"0 0 23 22",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":!0,children:[[13.329,6.78,4.582,2.661],[7.28,9.149,2.661,4.582],[15.692,12.834,2.661,4.582],[9.649,15.198,4.582,2.661]].map(([s,r,a,o])=>e.jsx("rect",{x:s-a/2,y:r-o/2,width:a,height:o,transform:`rotate(-6.34 ${s} ${r})`,fill:"currentColor"},`${s},${r}`))})}function xd({planKey:t,cost:s,remaining:r,dailyRemaining:a,monthlyRemaining:o,dailyResetAt:i,dailyLimit:l,monthlyLimit:c,chrome:x="legacy"}){const[h,y]=n.useState(!1),{variant:u}=Xc({remaining:r,cost:s,dailyRemaining:a,monthlyRemaining:o});if(Rm({bannerName:u?sf(u):void 0,bannerPlace:"tool_editor",visible:u!==null}),!u&&!h)return null;const w=u?rf(u,{planLabel:lf(t),resetTime:of(i),resetDuration:af(i)}).bannerMessage:null;return e.jsxs(e.Fragment,{children:[u&&w?e.jsx(Em,{message:w,place:"tool_editor",variant:u,chrome:x,onUpgradeClick:()=>y(!0)}):null,h?x==="new-design"?e.jsx(Am,{open:h,onOpenChange:y}):e.jsx(Wf,{open:h,onOpenChange:y}):null]})}function Vp({show:t}){return t?e.jsx("div",{"data-testid":xn.adminEditingBanner.root,className:"shrink-0 flex items-center justify-center gap-2 bg-amber-50 border-t border-amber-200 px-4 py-2 text-xs text-amber-800 font-medium",children:e.jsx("span",{children:"Admin mode — editing another user's tool. Publish/Update will save to their account."})}):null}function Hp({collapsed:t,onExpand:s,gutter:r=20,chrome:a="legacy"}){const o=a==="new-design";return e.jsx("div",{"data-testid":xn.chatExpandButton.root,className:`hidden lg:flex absolute top-0 z-20 transition-opacity duration-[400ms] ease-out ${t?"opacity-100":"opacity-0 pointer-events-none"}`,style:{left:r},children:o?e.jsx(go,{content:"Expand",children:e.jsx("button",{type:"button","data-testid":xn.chatExpandButton.button,onClick:s,className:"flex size-[50px] items-center justify-center border border-solid transition-colors hover:bg-[var(--product-grey-01)]",style:{background:"var(--product-white-00)",borderColor:"var(--product-grey-02)",color:"var(--product-grey-05)"},"aria-label":"Expand chat panel",children:e.jsx(ap,{className:"size-[15px]"})})}):e.jsx("button",{type:"button","data-testid":xn.chatExpandButton.button,onClick:s,className:"flex items-center justify-center h-[40px] w-[40px] rounded-[10px] border border-[#e1e1e1] bg-white text-[#7d7d7d] hover:bg-[#f5f5f5] transition-colors","aria-label":"Expand chat panel",title:"Expand",children:e.jsx("svg",{viewBox:"0 0 11.1 11.1",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"size-[11px] scale-x-[-1]","aria-hidden":!0,children:e.jsx("path",{d:"M3.88333 0.55V10.55M7.8 4.05L6.3 5.55L7.8 7.05M3.21667 0.55H7.88333C8.81675 0.55 9.28347 0.55 9.63998 0.731656C9.95359 0.891445 10.2086 1.14641 10.3683 1.46002C10.55 1.81654 10.55 2.28325 10.55 3.21667V7.88333C10.55 8.81675 10.55 9.28347 10.3683 9.63998C10.2086 9.95359 9.95359 10.2086 9.63998 10.3683C9.28347 10.55 8.81675 10.55 7.88333 10.55H3.21667C2.28325 10.55 1.81654 10.55 1.46002 10.3683C1.14641 10.2086 0.891445 9.95359 0.731656 9.63998C0.55 9.28347 0.55 8.81675 0.55 7.88333V3.21667C0.55 2.28325 0.55 1.81654 0.731656 1.46002C0.891445 1.14641 1.14641 0.891445 1.46002 0.731656C1.81654 0.55 2.28325 0.55 3.21667 0.55Z",stroke:"black",strokeWidth:"1.1",strokeLinecap:"round",strokeLinejoin:"round"})})})})}const Hh=320;function zp({collapsed:t,children:s,gutter:r=20,width:a=Hh,collapseMode:o="slide"}){const i=o==="instant";return e.jsx(Hs.div,{"data-testid":xn.chatSidebar.root,className:"hidden lg:block absolute top-0 bottom-0 z-30",style:{left:r,width:a,pointerEvents:t?"none":"auto",visibility:t?"hidden":"visible",transition:t&&!i?"visibility 0s linear 400ms":"visibility 0s linear 0s"},initial:{opacity:0,x:-20}
41,animate:{opacity:1,x:0},transition:{duration:.5,ease:[.4,0,.2,1],delay:0},children:e.jsx("div",{className:`flex flex-col h-full gap-[5px] ${i?"":"transition-transform duration-[400ms] ease-out"}`,style:{transform:t&&!i?`translateX(-${a+r}px)`:"translateX(0)"},children:s})})}const zh={done:[{frequency:523.25,startAt:0,duration:.12},{frequency:659.25,startAt:.1,duration:.18}],attention:[{frequency:880,startAt:0,duration:.1},{frequency:880,startAt:.16,duration:.14}]};let ml=null;function Uh(){if(typeof window>"u")return null;const t=window;return window.AudioContext??t.webkitAudioContext??null}function Gh(){const t=Uh();return t?((!ml||ml.state==="closed")&&(ml=new t),ml):null}function Wh(t){const s=Gh();if(!s)return;(s.state==="suspended"?s.resume():Promise.resolve()).then(()=>{const a=s.currentTime,o=s.createGain();o.gain.value=.15,o.connect(s.destination);for(const i of zh[t]){const l=s.createOscillator(),c=s.createGain();l.type="sine",l.frequency.value=i.frequency;const x=a+i.startAt;c.gain.setValueAtTime(0,x),c.gain.linearRampToValueAtTime(1,x+.01),c.gain.exponentialRampToValueAtTime(.001,x+i.duration),l.connect(c),c.connect(o),l.start(x),l.stop(x+i.duration+.02)}}).catch(()=>{})}const Up={done:"✓ Agent done",attention:"● Needs your input"},qh={done:"Your Brik agent finished its turn.",attention:"Your Brik agent is waiting for your answer."},Kh=1e3;let Cl=null,$i=null,jl=null;function Vc(){var t;Cl&&(clearInterval(Cl),Cl=null),jl&&(jl(),jl=null),$i!==null&&(document.title=$i,$i=null);try{(t=navigator.clearAppBadge)==null||t.call(navigator)}catch{}}function Yh(t){var i;if(typeof document>"u")return;Vc(),$i=document.title;const s=Up[t];let r=!0;document.title=s,Cl=setInterval(()=>{document.title=r?$i??"":s,r=!r},Kh);const a=()=>{Vc()};window.addEventListener("focus",a);const o=()=>{document.visibilityState==="visible"&&a()};document.addEventListener("visibilitychange",o),jl=()=>{window.removeEventListener("focus",a),document.removeEventListener("visibilitychange",o)};try{(i=navigator.setAppBadge)==null||i.call(navigator,1)}catch{}}function Zh(t){if(!(typeof window>"u"||typeof Notification>"u")&&Notification.permission==="granted"&&document.visibilityState!=="visible")try{const s=new Notification(Up[t],{body:qh[t],tag:"brik-agent-attention"});s.onclick=()=>{window.focus(),s.close(),Vc()}}catch{}}function Jh(){typeof window>"u"||typeof Notification>"u"||Notification.permission==="default"&&Notification.requestPermission().catch(()=>{})}function Xh(t){Yh(t),Zh(t)}function Qh(){const t=ua(cf),s=n.useRef(t);s.current=t;const r=n.useCallback(l=>{s.current&&(Wh(l),Xh(l))},[]),a=n.useCallback(()=>r("done"),[r]),o=n.useCallback(()=>r("attention"),[r]),i=n.useCallback(()=>{s.current&&Jh()},[]);return{notifyAgentDone:a,notifyAgentNeedsAttention:o,primeNotifications:i}}const e1=3,t1=1,n1=6e4,s1=5e3;function r1(t){return t.reason==="keepalive_timeout"}function a1(t,{timeoutMs:s=n1,isCompleted:r,onTimeout:a}){let o=Date.now(),i=!1;const l=setInterval(()=>{if(!i&&!r()&&Date.now()-o>s){i=!0;const c=Date.now()-o;console.warn("[sseResilience] Keepalive timeout — aborting stalled connection",{idleMs:c}),a==null||a({idleMs:c,timeoutMs:s}),t.abort("keepalive_timeout")}},s1);return{beat:()=>{o=Date.now()},clear:()=>clearInterval(l)}}async function o1(t,{sseAbort:s,onBeforeRetry:r}){if(s.signal.aborted)return"aborted";const a={midStreamRetries:0,preHandshakeRetries:0};let o=await t(a);for(;o==="retry_mid_stream"||o==="retry_pre_handshake";){if(s.signal.aborted||(o==="retry_mid_stream"?a.midStreamRetries++:a.preHandshakeRetries++,r==null||r(),await i1(s.signal),s.signal.aborted))return"aborted";o=await t(a)}return o}function i1(t){return t.aborted?Promise.resolve():new Promise(s=>{let r;const a=()=>{clearTimeout(r),document.removeEventListener("visibilitychange",o),t.removeEventListener("abort",a),s()},o=()=>{document.hidden||a()};t.addEventListener("abort",a,{once:!0}),document.hidden?document.addEventListener("visibilitychange",o):r=setTimeout(a,1e3)})}function l1(){if(typeof navigator>"u")return null;const t=navigator.connection;return t&&typeof t=="object"?t:null}function c1(t={},s=Date.now){const r=s();let a=0,o=0,i="",l=-1,c=0,x=0,h=0,y=0,u=typeof document<"u"&&document.hidden?r:0;u&&(h=1);const w=()=>
41{if(document.hidden){u=s(),h+=1;return}u&&(y+=s()-u,u=0)};typeof document<"u"&&document.addEventListener("visibilitychange",w);const _=v=>v?s()-v:null;return{recordEvent(v,j){a+=1,c=s(),v&&(i=v),typeof j=="number"&&(l=j),v==="keepalive"&&(o+=1,x=c)},snapshot(v={}){const j=l1(),A=y+(u?s()-u:0);return{...t,streamDurationMs:s()-r,eventCount:a,keepaliveCount:o,lastEventType:i||"none",lastSeq:l,msSinceLastEvent:_(c),msSinceLastKeepalive:_(x),tabWasHidden:h>0,tabHiddenCount:h,tabHiddenMs:A,...typeof document<"u"?{visibilityState:document.visibilityState}:{},...typeof navigator<"u"?{navigatorOnline:navigator.onLine,userAgent:navigator.userAgent}:{},...j?{effectiveType:j.effectiveType??j.type,downlinkMbps:j.downlink,rttMs:j.rtt,saveData:j.saveData}:{},...v}},dispose(){typeof document<"u"&&document.removeEventListener("visibilitychange",w)}}}const Gp="brik:admin:debugMode";function d1(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Gp)==="1"}catch{return!1}}function fd(t=!1){const[s,r]=n.useState(d1);n.useEffect(()=>{if(t)try{window.localStorage.setItem(Gp,s?"1":"0")}catch{}},[s,t]);const a=n.useCallback(()=>{t&&r(i=>!i)},[t]),o=n.useCallback(i=>{t&&r(i)},[t]);return{debugMode:t&&s,toggle:a,setDebugMode:o}}const Hc="flex size-[36px] shrink-0 items-center justify-center transition-colors",u1={fontFamily:"var(--product-font)",minHeight:76,maxHeight:112},p1="AI can make mistakes. Always double‑check the results.",x1=[],$d=()=>{};function f1({attachments:t=x1,onAddFiles:s=$d,onRemoveAttachment:r=$d,modelControl:a,extraActions:o,onSend:i,sendDisabled:l=!1,sendDisabledReason:c,generating:x=!1,onStop:h,disclaimer:y=p1,textareaClassName:u,textareaStyle:w,className:_,...v}){return e.jsx("div",{className:"shrink-0",children:e.jsxs("div",{className:"flex flex-col items-start border-t border-solid",style:{borderColor:"var(--product-grey-02)"},children:[e.jsx("div",{className:"flex w-full flex-col items-stretch justify-end border-b border-solid",style:{borderColor:"var(--product-grey-02)",background:"var(--product-white-00)"},children:e.jsx(cp,{...v,chrome:"new-design",className:_,attachments:t,onAddFiles:s,onRemoveAttachment:r,textareaClassName:u??"text-product-text placeholder-[var(--product-grey-05)] text-[var(--product-black-00)]",textareaStyle:{...u1,...w},leftSlot:a?e.jsx("div",{className:"flex min-w-0 flex-1",children:a}):null,rightSlot:e.jsxs("div",{className:"flex items-center",children:[o,x?e.jsx(go,{content:"Stop",children:e.jsx("button",{type:"button",onClick:h,className:Hc,style:{background:"var(--product-black-00)",color:"var(--product-white-00)"},"aria-label":"Stop generating",children:e.jsx("span",{className:"size-[10px] bg-current"})})}):e.jsx(go,{content:l&&c?c:"Send",children:e.jsx("button",{type:"button",onClick:()=>{l||i()},"aria-disabled":l||void 0,className:`${Hc} ${l?"cursor-not-allowed opacity-40":""}`,style:{background:"var(--product-black-00)",color:"var(--product-white-00)"},"aria-label":"Send",children:e.jsx(Vh,{className:"size-[22px] shrink-0"})})})]})})}),y===null?null:e.jsx("div",{className:"flex h-[50px] w-full items-center px-[8px] py-[12px]",style:{background:"var(--product-white-00)"},children:e.jsx("p",{className:"flex-1 font-product-book text-product-tiny-subs",style:{fontFamily:"var(--product-font-book)",color:"var(--product-grey-05)"},children:y})})]})})}const qo=({model:t,selected:s,onSelect:r,chrome:a="legacy"})=>{const o=t.isAdminOnly&&t.color?{color:t.color}:void 0;return a==="new-design"?e.jsxs("button",{type:"button",onClick:r,className:`${pp} touch-manipulation transition-colors hover:bg-[var(--product-grey-02)]`,style:o,children:[e.jsx(Id,{model:t,className:jm,tone:"mono"}),e.jsx("span",{className:Dl,children:t.name}),s?e.jsx("span",{className:km,children:"Selected"}):null]}):e.jsxs("button",{type:"button",onClick:r,className:`flex w-full items-center gap-[8px] text-left px-3 py-[5px] text-[12px] text-[#262626] touch-manipulation hover:bg-[#f5f5f5] ${s?"font-medium":""}`,style:o,children:[e.jsx(Id,{model:t}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.name}),s?e.jsx("span",{className:"shrink-0",children:"✓"}):null]})};function m1({input:t,setInput:s,handleKeyDown:r,syncTextareaHeight:a,setComposerFocused:o,inputRef:i,displayPlaceholder:l,messages:c,isCreditExhausted:x,chatAuthBlocked:h,attach:y,sendFileInteraction:u,sendToolEditorAction:w,availableModels:_,selectedModel:v,setSelectedModel:j,isAdmin:A,showSupervisorPicker:I,selectedSupervisorModel:O,setSelectedSupervisorModel:L,selectedArtDirectorModel:P,setSelectedArtDirectorModel:V,handleModelChange:re,generating:X,stopGeneration:je,sendBlocked:he,sendBlockedReason:me,sendMessage:T}){var ae,ve,ue;const ee=h?"Sign in to send":x?"Out of credits":void 0;return e.jsx(f1,{value:t,onChange:s,onKeyDown:r,onInput:a,onFocus:()=>o(!0),onBlur:()=>o(!1),textareaRef:i,placeholder:l,rows:c.length===0?3:1,disabled:x||h,attachDisabledReason:ee,attachments:y.attachments,attachmentsUploading:y.isUploading,onAddFiles:y.addFiles,onDragStart:()=>u({action_type:"drag_started",source:"drag_drop"}),onRemoveAttachment:y.removeAttachment,onPasteText:y.addPastedText,onPickAction:z=>{w(`chat_panel_upload_${z}`),u({action_type:"picker_opened",source:"file_picker",file_kind:z})},generating:X,onStop:()=>{w("chat_panel_stop_generating"),je()},sendDisabled:he,sendDisabledReason:me??void 0,onSend:()=>{w("chat_panel_send_message"),T()},warning:(()=>{const z=_.find($=>
41$.id===v);return!y.hasPendingBinary||!z||z.supportsFileParts?null:e.jsxs("div",{className:"flex items-start gap-[6px] px-[12px] pt-[12px] text-[11px] leading-[1.3]",style:{fontFamily:"var(--product-font)",color:"#b45309"},children:[e.jsx(Kl,{className:"mt-[1px] size-[13px] shrink-0"}),e.jsxs("span",{children:[z.name," can’t read video or PDF — switch to a Gemini model to include it, otherwise it’ll be dropped. Code/text references are still sent."]})]})})(),modelControl:A?e.jsxs(Ga,{onOpenChange:z=>{z&&w("chat_panel_model_select_dropdown")},children:[e.jsxs(Wa,{className:"flex min-w-0 flex-1 items-center gap-[8px] overflow-hidden border-0 px-[8px] py-[4px] text-product-text shadow-none transition-colors hover:bg-[var(--product-grey-01)]",style:{fontFamily:"var(--product-font)",background:"transparent",color:"var(--product-black-00)"},"aria-label":"Models",children:[e.jsxs("span",{className:"min-w-0 flex-1 truncate text-left",children:[I?e.jsxs(e.Fragment,{children:[e.jsx("span",{style:{color:"var(--product-grey-05)"},children:"Sup"})," ",((ae=_.find(z=>z.id===O))==null?void 0:ae.name)??O,e.jsx("span",{style:{color:"var(--product-grey-05)"},className:"mx-[6px]",children:"·"})]}):null,e.jsx("span",{style:{color:"var(--product-grey-05)"},children:"AD"})," ",((ve=_.find(z=>z.id===P))==null?void 0:ve.name)??P,e.jsx("span",{style:{color:"var(--product-grey-05)"},className:"mx-[6px]",children:"·"}),e.jsx("span",{style:{color:"var(--product-grey-05)"},children:"CC"})," ",((ue=_.find(z=>z.id===v))==null?void 0:ue.name)??v]}),e.jsx(up,{className:"size-[15px] shrink-0"})]}),e.jsxs(qa,{align:"start",side:"top",sideOffset:Nm,onOpenAutoFocus:z=>z.preventDefault(),onCloseAutoFocus:z=>z.preventDefault(),className:`z-[70] max-h-[min(70vh,420px)] overflow-y-auto overscroll-contain ${ad}`,children:[I?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:xc,children:"Supervisor"}),e.jsx("div",{className:"flex flex-col",children:_.map(z=>e.jsx(qo,{chrome:"new-design",model:z,selected:z.id===O,onSelect:()=>{w("chat_panel_supervisor_model_select_dropdown"),L(z.id)}},`sup-${z.id}`))})]}):null,e.jsx("div",{className:xc,children:"Art Director"}),e.jsx("div",{className:"flex flex-col",children:_.map(z=>e.jsx(qo,{chrome:"new-design",model:z,selected:z.id===P,onSelect:()=>{w("chat_panel_art_director_model_select_dropdown"),V(z.id)}},`ad-${z.id}`))}),e.jsx("div",{className:xc,children:"Coder"}),e.jsx("div",{className:"flex flex-col",children:_.map(z=>e.jsx(qo,{chrome:"new-design",model:z,selected:z.id===v,onSelect:()=>j(z.id)},`cc-${z.id}`))})]})]}):e.jsx(od,{models:_.filter(z=>!z.isAdminOnly),value:v,onValueChange:re,chrome:"new-design",onOpenClick:()=>w("chat_panel_model_select_dropdown"),triggerClassName:"h-auto min-w-0 flex-1 gap-[8px] overflow-hidden rounded-none border-0 bg-transparent px-[8px] py-[4px] text-product-text font-[family-name:var(--product-font)] text-[var(--product-black-00)] shadow-none ring-0 transition-colors hover:bg-[var(--product-grey-01)] focus:ring-0 [&>span]:truncate [&>svg]:size-[15px] [&>svg]:shrink-0 [&>svg]:opacity-100"}),extraActions:e.jsx(xp,{value:t,onChange:s,disabled:x||h,disabledReason:ee,surface:"editor_chat",buttonClassName:`${Hc} text-[var(--product-grey-05)] hover:text-[var(--product-black-00)] disabled:opacity-40`,iconClassName:"size-[22px] shrink-0",productTooltip:!0})})}const ki=_n.revertDialog,h1="Revert to this version?";function g1({open:t,onOpenChange:s,onConfirm:r}){return Fr({open:t,modalName:h1}),e.jsxs(Ki,{open:t,onOpenChange:s,"data-testid":ki.root,gridLineTestId:ki.gridLine,children:[e.jsx(Xo,{title:"Revert to this version?",close:e.jsx(vr,{"data-testid":ki.close,children:e.jsx(Zn,{className:"size-[15px] shrink-0"})})}),e.jsx($s,{className:"items-center",children:e.jsx("p",{className:"min-w-0 flex-1 text-product-text text-[var(--product-grey-05)]",children:"This will restore the tool code from this point. All messages after this will be permanently deleted. This cannot be undone."})}),e.jsx(Vs,{}),e.jsxs(bo,{children:[e.jsx(vr,{asChild:!0,children:e.jsxs(Nn,{size:"big",skin:"standard",priority:"secondary",className:"min-w-0 flex-1 border-0","data-testid":ki.cancel,children:[e.jsx(Zn,{className:"size-[15px] shrink-0"}),e.jsx("span",{className:"whitespace-nowrap",children:"Cancel"})]})}),e.jsxs(Nn,{size:"big",skin:"error",priority:"primary",className:"min-w-0 flex-1 border-0","data-testid":ki.confirm,onClick:r,children:[e.jsx(id,{className:"size-[15px] shrink-0"}),e.jsx("span",{className:"whitespace-nowrap",children:"Revert & Delete"})]})]})]})}const md={panel:{root:"ui-v2-chat-panel",scroll:"ui-v2-chat-panel-scroll",stack:"ui-v2-chat-panel-stack"},agentBubble:{revertButton:"ui-v2-chat-agent-revert"},header:{root:"ui-v2-chat-header",title:"ui-v2-chat-header-title",historyButton:"ui-v2-chat-header-history",collapseButton:"ui-v2-chat-header-collapse"}};function b1(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function zc(t){if(!t)return"";let s=b1(t);return s=s.replace(/```(\w*)\n([\s\S]*?)```/g,(r,a,o)=>`<pre class="bg-[#f0f0f0] border border-[var(--product-grey-02-legacy)] rounded-[10px] p-3 my-2 overflow-x-auto text-xs text-[#262626]"><code class="language-${a||"text"}">${o.trim()}</code></pre>`),s=s.replace(/`([^`]+)`/g,'<code class="bg-[var(--product-grey-02-legacy)] text-[#262626] px-1 rounded text-xs">$1</code>'),s=s.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),s=s.replace(/\n/g,"<br>"),s}function v1({children:t}){return e.jsxs("div",{className:"flex w-full flex-col items-start gap-[12px] overflow-hidden px-[16px] py-[12px]",children:[e.jsx($h,{className:"size-[15px] shrink-0"}),t]})}const y1=md.agentBubble;function Wp({content:t,isStreaming:s,buttonMode:r="none",onRevert:a=void 0,children:o}){const l=(!t||!t.trim())&&!s;return e.jsxs(v1,{children:[l?e.jsx("div",{className:"w-full min-w-0 text-product-text italic ",style:{fontFamily:"var(--product-font)",color:"var(--product-grey-05)"},children:"Version restored"}):e.jsx("div",{dir:Zo(t)?"rtl":"ltr",className:"w-full min-w-0 break-words text-product-text",style:{fontFamily:"var(--product-font)",color:"var(--product-black-00)"},dangerouslySetInnerHTML:{__html:zc(t)+(s?'<span class="animate-pulse ml-0.5">│</span>':"")}}),o,r!=="none"&&a&&!s&&e.jsxs(Nn,{type:"button",size:"small",skin:"standard",priority:"secondary",onClick:a,"data-testid":y1.revertButton,style:{fontFamily:"var(--product-font)"},children:[e.jsx(Lh,{className:"size-[15px] shrink-0"}),r==="undo"?"Undo":"Revert to this version"]})]})}const hl=md.header;function Vd({testId:t,label:s,active:r,onClick:a,children:o}){return e.jsx(go,{content:s,children:e.jsx("button",{type:"button","data-testid":t,onClick:a,"aria-label":s,"aria-pressed":r,className:"flex size-[24px] shrink-0 items-center justify-center rounded-[4px] transition-colors hover:bg-[var(--product-grey-01)]",style:{color:r?"var(--product-black-00)":"var(--product-grey-05)"},children:e.jsx("span",{className:"block size-[15px]",children:o})})})}function _1({title:t,extraActions:s,onToggleHistory:r,historyOpen:a,onCollapse:o}){return e.jsxs("div",{"data-testid":hl.root,className:"flex h-[50px] w-full shrink-0 items-center justify-between overflow-hidden border-b border-solid pl-[12px] pr-[8px] py-[8px]",style:{borderColor:"var(--product-grey-02)"},children:[e.jsx("p",{"data-testid":hl.title,className:"shrink-0 whitespace-nowrap capitalize text-product-title",style:{fontFamily:"var(--product-font)",color:"var(--product-black-00)"},children:t}),e.jsxs("div",{className:"flex shrink-0 items-center gap-[2px]",children:[s,r&&e.jsx(Vd,{testId:hl.historyButton,label:"Versions history",active:a,onClick:r,children:e.jsx(Fh,{className:"size-full"})}),o&&e.jsx(Vd,{testId:hl.collapseButton,label:"Collapse chat panel",onClick:o,children:e.jsx(ap,{className:"size-full"})})]})]})}function w1({files:t}){return!t||t.length===0?null:e.jsx("div",{className:"flex flex-wrap gap-[8px]",children:t.map((s,r)=>{if(s.kind==="video")return e.jsx(Cu,{fallbackUrl:s.url,streamUrl:s.stream_url,streamFormat:s.stream_format,muted:!0,controls:!0,className:"size-20 object-cover border border-solid border-[var(--product-grey-02)]"},r);const a=s.kind==="document",o=s.name||(a?"Document":"Snippet");return e.jsxs("div",{className:"flex max-w-[180px] items-center gap-[6px] border border-solid border-[var(--product-grey-02)] bg-[var(--product-white-00)] px-[10px] py-[6px] text-product-text text-[var(--product-grey-05)]",children:[a?e.jsx(mp,{className:"size-[14px] shrink-0"}):e.jsx(dp,{className:"size-[14px] shrink-0"}),e.jsx("span",{className:"truncate",children:o})]},r)})})}function qp({content:t,images:s,referenceFiles:r,compact:a}){return e.jsx("div",{className:"flex w-full flex-col items-end",children:e.jsxs("div",{className:`flex flex-col items-start gap-[10px] p-[12px] ${a?"max-w-[85%]":"w-[250px]"}`,style:{background:"var(--product-grey-02)"},children:[s&&s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-[8px]",children:s.map((o,i)=>e.jsx("img",{src:o,alt:`Attached image ${i+1}`,className:"size-20 object-cover"},i))}),e.jsx(w1,{files:r}),t&&e.jsx("div",{dir:Zo(t)?"rtl":"ltr",className:"w-full min-w-0 
41whitespace-pre-wrap break-words text-product-text",style:{fontFamily:"var(--product-font)",color:"var(--product-grey-05)"},children:t})]})})}const mc=md.panel;function C1({messages:t,renderMessage:s,revertFor:r,header:a,composer:o,messagesHidden:i=!1,afterMessages:l,belowMessages:c,overlay:x,children:h,working:y=!1,sharedEdges:u="none",scrollRef:w,onScroll:_,bottomRef:v}){return e.jsxs("div",{"data-testid":mc.root,className:`flex h-full w-full min-w-0 shrink-0 flex-col items-stretch justify-between overflow-hidden border-solid ${y?"border chat-working-border":u==="top-left"?"border-b border-r":"border"}`,style:{background:y?void 0:"var(--product-white-00)",borderColor:y?"transparent":"var(--product-grey-02)",fontFamily:"var(--product-font)",fontWeight:400},children:[h,e.jsxs("div",{className:"flex min-h-0 w-full flex-1 flex-col",children:[a&&e.jsx(_1,{title:a.title,extraActions:a.extraActions,onToggleHistory:a.onToggleHistory,historyOpen:a.historyOpen,onCollapse:a.onCollapse}),e.jsxs("div",{className:`relative flex min-h-0 flex-1 flex-col ${i?"hidden":""}`,children:[e.jsxs("div",{ref:w,"data-testid":mc.scroll,onScroll:_,className:"chat-scroll min-h-0 flex-1 overflow-y-auto",children:[e.jsxs("div",{"data-testid":mc.stack,className:"flex flex-col gap-[12px] pt-[12px]",children:[t.map(j=>{const A=s==null?void 0:s(j);if(A!==void 0)return A;if(j.role==="user")return e.jsx(qp,{content:j.content,images:j.images,referenceFiles:j.reference_files},j.id);if(j.role==="assistant"){const I=r==null?void 0:r(j);return e.jsx(Wp,{content:j.content,isStreaming:j.isStreaming,buttonMode:(I==null?void 0:I.mode)??"none",onRevert:I==null?void 0:I.onRevert},j.id)}return null}),l]}),e.jsx("div",{ref:v,className:"h-1"})]}),x]}),c,i?e.jsx("div",{className:"flex min-h-0 flex-1 flex-col justify-stretch",children:o}):o]})]})}const gl="bg-[#fdf2f8] text-[#db2777] rounded";function j1(t,s){const r=t.replace(/\r\n/g,`
42`).split(`
43`),a=s.replace(/\r\n/g,`
44`).split(`
45`),o=r.length,i=a.length,l=Array.from({length:o+1},()=>new Array(i+1).fill(0));for(let y=o-1;y>=0;y--)for(let u=i-1;u>=0;u--)l[y][u]=r[y]===a[u]?l[y+1][u+1]+1:Math.max(l[y+1][u],l[y][u+1]);const c=new Set;let x=0,h=0;for(;x<o&&h<i;)if(r[x]===a[h])x++,h++;else if(l[x+1][h]>=l[x][h+1])x++;else{const y=a[h].trim();y&&c.add(y),h++}for(;h<i;){const y=a[h].trim();y&&c.add(y),h++}return c}function bl(t,s){const r=[],a=/\*\*([^*]+)\*\*|`([^`]+)`/g;let o=0,i=0,l;for(;(l=a.exec(t))!==null;)l.index>
45o&&r.push(t.slice(o,l.index)),l[1]!==void 0?r.push(e.jsx("strong",{className:"font-semibold text-[#262626]",children:l[1]},`${s}-b${i}`)):l[2]!==void 0&&r.push(e.jsx("code",{className:"bg-[#f0f0f0] text-[#262626] px-1 rounded text-[11px] font-mono",children:l[2]},`${s}-c${i}`)),o=l.index+l[0].length,i++;return o<t.length&&r.push(t.slice(o)),r}function k1(t,s){const r=t.replace(/\r\n/g,`
46`).split(`
47`),a=[];let o=[],i=[];const l=h=>s.has(h.trim()),c=()=>{if(!o.length)return;const h=`blk${a.length}`,y=o;a.push(e.jsx("p",{className:"mb-2 last:mb-0 leading-[17px]",children:y.map((u,w)=>e.jsxs(n.Fragment,{children:[w>0&&e.jsx("br",{}),e.jsx("span",{className:u.added?`${gl} px-0.5`:void 0,children:bl(u.text,`${h}-${w}`)})]},w))},h)),o=[]},x=()=>{if(!i.length)return;const h=`blk${a.length}`,y=i;a.push(e.jsx("ul",{className:"list-disc pl-4 mb-2 last:mb-0 space-y-0.5",children:y.map((u,w)=>e.jsx("li",{className:`leading-[17px] ${u.added?`${gl} px-0.5`:""}`,children:bl(u.text,`${h}-${w}`)},w))},h)),i=[]};for(const h of r){const y=h.trimEnd();if(!y.trim()){c(),x();continue}const u=y.match(/^(#{1,3})\s+(.*)$/),w=y.match(/^\s*[-*•]\s+(.*)$/),_=y.match(/^\*\*.+\*\*:?$/);if(u){c(),x();const v=u[1].length,j=`blk${a.length}`;a.push(e.jsx("div",{className:`font-semibold text-[#262626] ${v===1?"text-[13px]":"text-[12px]"} mt-2 first:mt-0 mb-1 ${l(y)?`${gl} px-0.5`:""}`,children:bl(u[2],j)},j))}else if(w)c(),i.push({text:w[1],added:l(y)});else if(_){c(),x();const v=`blk${a.length}`;a.push(e.jsx("div",{className:`font-semibold text-[#262626] text-[12px] mt-2 first:mt-0 mb-1 ${l(y)?`${gl} px-0.5`:""}`,children:bl(y,v)},v))}else x(),o.push({text:y,added:l(y)})}return c(),x(),a}const Hd=({open:t,brief:s,previousBrief:r,onClose:a})=>{const[o,i]=n.useState(null),[l,c]=n.useState(!1),x=n.useRef(null),h=v=>{if(v.target.closest("button"))return;const j=v.currentTarget.parentElement.getBoundingClientRect();x.current={dx:v.clientX-j.left,dy:v.clientY-j.top},v.currentTarget.setPointerCapture(v.pointerId)},y=v=>{x.current&&i({x:v.clientX-x.current.dx,y:v.clientY-x.current.dy})},u=v=>{x.current=null,v.currentTarget.releasePointerCapture(v.pointerId)},w=()=>{var v;(v=navigator.clipboard)==null||v.writeText(s).then(()=>{c(!0),window.setTimeout(()=>c(!1),1200)}).catch(()=>{})};if(!t)return null;const _=r&&r!==s?j1(r,s):new Set;return e.jsxs("div",{className:`fixed z-50 w-[360px] max-h-[70vh] flex flex-col bg-white border border-[#e5e5e5] rounded-[12px] shadow-lg ${o?"":"top-[64px] right-4"}`,style:o?{top:o.y,left:o.x,right:"auto"}:void 0,children:[e.jsxs("div",{onPointerDown:h,onPointerMove:y,onPointerUp:u,className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-[#e5e5e5] shrink-0 cursor-move select-none touch-none",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx(Mm,{className:"w-3.5 h-3.5 text-[#c4c4c4] shrink-0"}),e.jsx("span",{className:"text-[12px] font-medium text-black tracking-[-0.24px]",children:"Design Brief"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx("button",{type:"button",onClick:w,"aria-label":"Copy brief to clipboard",title:"Copy brief",className:"flex items-center justify-center w-5 h-5 rounded-[6px] text-[#a3a3a3] hover:bg-[#f5f5f5] hover:text-[#525252] transition-colors",children:l?e.jsx(Qo,{className:"w-3.5 h-3.5 text-[#16a34a]"}):e.jsx(Yi,{className:"w-3.5 h-3.5"})}),e.jsx("button",{type:"button",onClick:a,"aria-label":"Close brief",className:"flex items-center justify-center w-5 h-5 rounded-[6px] text-[#a3a3a3] hover:bg-[#f5f5f5] hover:text-[#525252] transition-colors",children:e.jsx(Hr,{className:"w-3.5 h-3.5"})})]})]}),e.jsx("div",{className:"overflow-y-auto px-3 py-2.5 text-[12px] text-[#525252]",children:s.trim()?k1(s,_):e.jsx("div",{className:"text-[#a3a3a3] italic",children:"No brief yet."})})]})};function N1({content:t,isStreaming:s,buttonMode:r="none",onRevert:a=void 0,mobile:o=!1}){const l=(!t||!t.trim())&&!s;return o?e.jsxs("div",{className:"flex w-full flex-col items-start gap-[10px] mt-[10px] px-[12px]",children:[l?e.jsx("div",{className:"w-full min-w-0 text-[14px] font-normal italic leading-[1.4] tracking-[-0.28px] text-[#737373]",children:"Version restored"}):e.jsx("div",{dir:Zo(t)?"rtl":"ltr",className:"w-full min-w-0 break-words text-[14px] font-normal leading-[1.4] tracking-[-0.28px] text-black",dangerouslySetInnerHTML:{__html:zc(t)+(s?'<span class="animate-pulse ml-0.5 text-[#737373]">│</span>':"")}}),r!=="none"&&a&&!s&&e.jsx("div",{className:"flex w-full justify-start",children:e.jsx("button",{className:"text-[10px] px-[8px] py-[3px] rounded-[6px] border border-[#d0d0d0] text-[#999] bg-transparent cursor-pointer hover:bg-[#f0f0f0] hover:border-[#bbb] hover:text-[#777] transition-colors",onClick:a,children:r==="undo"?"↩ Undo":"↻ Revert to this version"})})]}):e.jsxs("div",{className:"flex flex-col justify-center items-start gap-[10px] w-full p-[20px] rounded-[10px] border-0 bg-[#e8e8e8]/0 mt-[5
47px] mb-0",children:[e.jsxs("svg",{viewBox:"0 0 21.45 21.45",fill:"black",xmlns:"http://www.w3.org/2000/svg",className:"size-[12px] shrink-0","aria-hidden":!0,children:[e.jsx("path",{d:"M4.29004 4.29C4.29004 1.9207 6.21074 0 8.58004 0H12.87C15.2393 0 17.16 1.9207 17.16 4.29H4.29004Z"}),e.jsx("path",{d:"M4.29004 12.87C4.29004 10.5007 6.21074 8.57996 8.58004 8.57996H12.87C15.2393 8.57996 17.16 10.5007 17.16 12.87H4.29004Z"}),e.jsx("path",{d:"M4.29004 21.45C4.29004 19.0807 6.21074 17.16 8.58004 17.16H12.87C15.2393 17.16 17.16 19.0807 17.16 21.45H4.29004Z"}),e.jsx("path",{d:"M0 8.58004C0 6.21074 1.9207 4.29004 4.29 4.29004V21.45C1.9207 21.45 0 19.5293 0 17.16V8.58004Z"}),e.jsx("path",{d:"M17.1599 4.29004C19.5292 4.29004 21.4499 6.21074 21.4499 8.58004H17.1599V4.29004Z"}),e.jsx("path",{d:"M17.1599 12.87C19.5292 12.87 21.4499 14.7907 21.4499 17.16H17.1599V12.87Z"}),e.jsx("path",{d:"M21.45 8.57996C21.45 10.9493 19.5293 12.87 17.16 12.87V8.57996H21.45Z"}),e.jsx("path",{d:"M21.45 17.16C21.45 19.5293 19.5293 21.45 17.16 21.45V17.16H21.45Z"})]}),l?e.jsx("div",{className:"text-[12px] italic text-[#737373] leading-[1.4] tracking-[-0.24px] w-full min-w-0",children:"Version restored"}):e.jsx("div",{dir:Zo(t)?"rtl":"ltr",className:"text-[12px] text-black break-words leading-[1.4] tracking-[-0.24px] w-full min-w-0",dangerouslySetInnerHTML:{__html:zc(t)+(s?'<span class="animate-pulse ml-0.5 text-[#737373]">│</span>':"")}}),r!=="none"&&a&&!s&&e.jsx("div",{className:"flex w-full justify-start mt-[20px]",children:e.jsx("button",{className:"text-[10px] px-[8px] py-[3px] rounded-[6px] border border-[#d0d0d0] text-[#999] bg-transparent cursor-pointer hover:bg-[#f0f0f0] hover:border-[#bbb] hover:text-[#777] transition-colors",onClick:a,children:r==="undo"?"↩ Undo":"↻ Revert to this version"})})]})}function S1({content:t}){const[s,r]=n.useState(!1),a=t.split(`
48
49`),o=(a.length>1?a.slice(1).join(`
50
51`):t).trim();return e.jsxs("div",{className:"mx-3 my-2 text-[11px] text-[#737373]",children:[e.jsxs("button",{type:"button",onClick:()=>r(i=>!i),className:"flex items-center gap-1.5 w-full hover:text-[#525252] transition-colors",children:[s?e.jsx(vo,{className:"w-3 h-3"}):e.jsx(yo,{className:"w-3 h-3"}),e.jsx("span",{"aria-hidden":!0,children:"⟳"}),e.jsx("span",{children:"Auto-fixing — triggered by:"})]}),s&&o&&e.jsx("pre",{className:"mt-1 ml-[18px] text-[10px] text-[#c2185b] whitespace-pre-wrap font-mono bg-white border border-[#e5e5e5] rounded-[6px] p-2 max-h-48 overflow-y-auto",children:o})]})}function T1({creditBannerVisible:t,billingSummary:s,nextActionCost:r,input:a,setInput:o,handleKeyDown:i,syncTextareaHeight:l,setComposerFocused:c,inputRef:x,displayPlaceholder:h,messages:y,mobileBubbles:u,composerMaxHeightPx:w,isCreditExhausted:_,chatAuthBlocked:v,attach:j,sendFileInteraction:A,sendToolEditorAction:I,availableModels:O,selectedModel:L,setSelectedModel:P,isAdmin:V,showSupervisorPicker:re,selectedSupervisorModel:X,setSelectedSupervisorModel:je,selectedArtDirectorModel:he,setSelectedArtDirectorModel:me,handleModelChange:T,generating:ee,stopGeneration:ae,sendBlocked:ve,sendBlockedReason:ue,sendMessage:z}){var $,W,ne,F;return e.jsxs("div",{className:"shrink-0 flex flex-col gap-[15px]",children:[e.jsxs("div",{className:t?"flex flex-col gap-0":void 0,children:[(s==null?void 0:s.credits)&&e.jsx(xd,{planKey:s.plan_key,cost:r,remaining:s.credits.remaining,dailyRemaining:s.credits.daily_remaining,monthlyRemaining:s.credits.monthly_remaining,dailyResetAt:(($=s.resets)==null?void 0:$.daily_reset_at)??null,dailyLimit:s.credits.daily_limit,monthlyLimit:s.credits.monthly_limit}),e.jsx("div",{className:t?"relative z-10 -mt-[10px]":void 0,children:e.jsx(cp,{value:a,onChange:o,onKeyDown:i,onInput:l,onFocus:()=>c(!0),onBlur:()=>c(!1),textareaRef:x,placeholder:h,rows:y.length===0?3:1,textareaClassName:u?"text-[14px]":"text-[12px]",textareaStyle:{minHeight:y.length===0?60:20,maxHeight:w},className:t?"border-[#be22b1] rounded-t-[15px]":void 0,disabled:_||v,attachDisabledReason:v?"Sign in to send":_?"Out of credits":void 0,attachments:j.attachments,attachmentsUploading:j.isUploading,onAddFiles:j.addFiles,onDragStart:()=>A({action_type:"drag_started",source:"drag_drop"}),onRemoveAttachment:j.removeAttachment,onPasteText:j.addPastedText,onPickAction:te=>{I(`chat_panel_upload_${te}`),A({action_type:"picker_opened",source:"file_picker",file_kind:te})},warning:(()=>{const te=O.find(Le=>Le.id===L);
51return!j.hasPendingBinary||!te||te.supportsFileParts?null:e.jsxs("div",{className:"flex items-start gap-[6px] text-[11px] text-[#b45309] leading-[1.4]",children:[e.jsx(Kl,{className:"size-[13px] shrink-0 mt-[1px]"}),e.jsxs("span",{children:[te.name," can’t read video or PDF — switch to a Gemini model to include it, otherwise it’ll be dropped. Code/text references are still sent."]})]})})(),leftSlot:V?e.jsxs(Ga,{onOpenChange:te=>{te&&I("chat_panel_model_select_dropdown")},children:[e.jsx(Wa,{className:"h-[30px] w-auto min-w-0 inline-flex items-center gap-[6px] bg-transparent border-0 shadow-none px-[8px] py-0 text-[12px] font-medium text-black/50 tracking-[-0.24px] hover:bg-[#f5f5f5] rounded-[8px] transition-colors","aria-label":"Models",children:e.jsxs("span",{className:"truncate",children:[re?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-black/40",children:"Sup"})," ",((W=O.find(te=>te.id===X))==null?void 0:W.name)??X,e.jsx("span",{className:"text-black/30 mx-[6px]",children:"·"})]}):null,e.jsx("span",{className:"text-black/40",children:"AD"})," ",((ne=O.find(te=>te.id===he))==null?void 0:ne.name)??he,e.jsx("span",{className:"text-black/30 mx-[6px]",children:"·"}),e.jsx("span",{className:"text-black/40",children:"CC"})," ",((F=O.find(te=>te.id===L))==null?void 0:F.name)??L]})}),e.jsxs(qa,{align:"start",side:"top",sideOffset:8,onOpenAutoFocus:te=>te.preventDefault(),onCloseAutoFocus:te=>te.preventDefault(),className:"z-[70] w-[280px] max-h-[min(70vh,420px)] overflow-y-auto overscroll-contain p-0 bg-white border-[#e5e5e5]",children:[re?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-wide text-black/50",children:"Supervisor"}),e.jsx("div",{className:"flex flex-col pb-1",children:O.map(te=>e.jsx(qo,{model:te,selected:te.id===X,onSelect:()=>{I("chat_panel_supervisor_model_select_dropdown"),je(te.id)}},`sup-${te.id}`))}),e.jsx("div",{className:"h-px bg-[#e5e5e5]"})]}):null,e.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-wide text-black/50",children:"Art Director"}),e.jsx("div",{className:"flex flex-col pb-1",children:O.map(te=>e.jsx(qo,{model:te,selected:te.id===he,onSelect:()=>{I("chat_panel_art_director_model_select_dropdown"),me(te.id)}},`ad-${te.id}`))}),e.jsx("div",{className:"h-px bg-[#e5e5e5]"}),e.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] font-semibold uppercase tracking-wide text-black/50",children:"Coder"}),e.jsx("div",{className:"flex flex-col pb-1",children:O.map(te=>e.jsx(qo,{model:te,selected:te.id===L,onSelect:()=>P(te.id)},`cc-${te.id}`))})]})]}):e.jsx(od,{models:O.filter(te=>!te.isAdminOnly),value:L,onValueChange:T,onOpenClick:()=>I("chat_panel_model_select_dropdown"),triggerClassName:"h-[30px] w-auto min-w-0 gap-[6px] bg-transparent border-0 shadow-none px-[8px] py-0 text-[12px] font-medium text-black/50 tracking-[-0.24px] ring-0 focus:ring-0 hover:bg-[#f5f5f5] rounded-[8px] transition-colors"}),rightSlot:e.jsxs("div",{className:"flex items-center gap-[5px]",children:[e.jsx(xp,{value:a,onChange:o,disabled:_||v,disabledReason:v?"Sign in to send":_?"Out of credits":void 0,surface:"editor_chat",buttonClassName:"shrink-0 w-[30px] h-[30px] flex items-center justify-center rounded-[10px] text-[#7d7d7d] hover:text-black disabled:opacity-40 transition-colors",iconClassName:"size-[14px] shrink-0"}),ee?e.jsx(zi,{label:"Stop",children:e.jsx("button",{type:"button",onClick:()=>{I("chat_panel_stop_generating"),ae()},className:"shrink-0 w-[30px] h-[30px] flex items-center justify-center rounded-[5px] bg-black text-white hover:bg-[#333] transition-colors","aria-label":"Stop generating",children:e.jsx("div",{className:"w-2 h-2 bg-white rounded-[2px]"})})}):e.jsx(zi,{label:"Send",disabled:ve,reason:ue,children:e.jsx("button",{type:"button",onClick:()=>{ve||(I("chat_panel_send_message"),z())},"aria-disabled":ve||void 0,className:`shrink-0 w-[30px] h-[30px] flex items-center justify-center rounded-[5px] bg-black text-white transition-colors ${ve?"opacity-40 cursor-not-allowed":"hover:bg-[#7D7D7D]"}`,"aria-label":"Send",children:e.jsx("svg",{width:"11",height:"11",viewBox:"0 0 11.0995 11.0996",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,
51children:e.jsx("path",{d:"M4.99996 10.5498V1.87691L0.938435 5.93844C0.723647 6.15323 0.37588 6.15323 0.161091 5.93844C-0.0536971 5.72365 -0.0536971 5.37588 0.161091 5.16109L5.16109 0.161095L5.24703 0.0907822C5.46054 -0.0503622 5.75042 -0.0269209 5.93844 0.161095L10.9384 5.16109C11.1532 5.37588 11.1532 5.72365 10.9384 5.93844C10.7236 6.15323 10.3759 6.15323 10.1611 5.93844L6.09957 1.87691V10.5498C6.09957 10.8535 5.85352 11.0996 5.54976 11.0996C5.24601 11.0996 4.99996 10.8535 4.99996 10.5498Z",fill:"currentColor"})})})})]})})})]}),e.jsx("div",{className:"flex items-center justify-center px-[10px]",children:e.jsx("p",{className:"font-normal text-[10px] tracking-[-0.2px] text-[#7d7d7d] flex-1",children:"AI can make mistakes. Always double‑check the results"})})]})}function R1({errors:t,disabled:s,onFix:r}){return e.jsx("div",{className:"shrink-0 rounded-[16px] border border-red-200 bg-red-50 overflow-hidden mb-1.5",children:e.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5",children:[e.jsx(Kl,{className:"w-4 h-4 text-red-500 shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-[11px] font-medium text-red-800",children:[t.length," console error",t.length!==1?"s":""," detected in preview"]}),e.jsx("p",{className:"mt-0.5 text-[10px] text-red-600",children:"Click “Fix with AI” to resolve automatically."})]}),e.jsx("button",{onClick:r,disabled:s,className:"shrink-0 text-[11px] font-medium text-white bg-red-600 hover:bg-red-700 rounded-full px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:"Fix with AI"})]})})}function E1({scrollContainerRef:t,onScroll:s,bottomRef:r,overlay:a,newDesign:o=!1,children:i}){return e.jsxs("div",{"data-testid":xn.chatMessageList.root,className:"relative flex-1 min-h-0 flex flex-col",children:[e.jsxs("div",{ref:t,"data-testid":xn.chatMessageList.scroll,onScroll:s,className:"flex-1 overflow-y-auto min-h-0",children:[o?e.jsx("div",{"data-testid":xn.chatMessageList.stack,className:"flex flex-col gap-[12px] pt-[12px]",children:i}):i,e.jsx("div",{ref:r,className:"h-1"})]}),a]})}function I1({className:t}){return e.jsx("svg",{viewBox:"0 0 13.0997 13.0997",fill:"none",overflow:"visible",preserveAspectRatio:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":!0,children:e.jsx("path",{d:"M9.32617 7.8897C9.31988 7.81308 9.31067 7.81114 9.32031 7.83013C9.30914 7.80827 9.29139 7.79052 9.26953 7.77935C9.28853 7.789 9.28658 7.77978 9.20996 7.77349C9.12638 7.76666 9.01217 7.76665 8.81641 7.76665H4.2832C4.08744 7.76665 3.97322 7.76666 3.88965 7.77349C3.81303 7.77978 3.81108 7.78899 3.83008 7.77935C3.80822 7.79052 3.79047 7.80827 3.7793 7.83013C3.78894 7.81114 3.77973 7.81308 3.77344 7.8897C3.76661 7.97328 3.7666 8.0875 3.7666 8.28326V12.0001H9.33301V8.28326C9.33301 8.0875 9.333 7.97328 9.32617 7.8897ZM9.33301 1.44634C9.17929 1.29453 9.12736 1.24806 9.07324 1.2149C9.00325 1.17205 8.92648 1.1403 8.84668 1.12115C8.77137 1.10313 8.68447 1.09966 8.33301 1.09966H3.7666V2.81646C3.7666 3.01222 3.76661 3.12644 3.77344 3.21001C3.77973 3.28663 3.78894 3.28858 3.7793 3.26958C3.79047 3.29144 3.80822 3.3092 3.83008 3.32036C3.81108 3.31072 3.81303 3.31994 3.88965 3.32622C3.97322 3.33305 4.08744 3.33306 4.2832 3.33306H8.81641C9.01217 3.33306 9.12638 3.33305 9.20996 3.32622C9.28658 3.31994 9.28853 3.31072 9.26953 3.32036C9.29139 3.3092 9.30914 3.29144 9.32031 3.26958C9.31067 3.28858 9.31988 3.28663 9.32617 3.21001C9.333 3.12644 9.33301 3.01222 9.33301 2.81646V1.44634ZM3.26344e-08 3.75005C3.26344e-08 3.19915 -0.000193786 2.75272 0.0292969 2.39165C0.0593072 2.02435 0.122451 1.69685 0.277344 1.39263C0.521821 0.912817 0.912765 0.521873 1.39258 0.277396C1.6968 0.122503 2.02429 0.0593596 2.3916 0.0293493C2.62237 0.0105012 2.88792 0.0053107 3.19336 0.0029821C3.20106 0.00266225 3.20902 5.24152e-05 3.2168 5.24152e-05C3.2237 5.64123e-05 3.23047 0.00272616 3.2373 0.0029821C3.39719 0.00198078 3.56797 5.24152e-05 3.75 5.24152e-05H8.33301C8.63272 5.0913e-05 8.8722 -0.00366716 9.10352 0.0518102C9.29568 0.0979458 9.47993 0.174136 9.64844 
510.277396C9.85134 0.401768 10.0184 0.574149 10.2305 0.786185L10.2666 0.822318C10.2699 0.825529 10.2731 0.828792 10.2764 0.832084L12.3135 2.86919C12.5255 3.08123 12.6979 3.24833 12.8223 3.45122C12.9255 3.61973 13.0017 3.80398 13.0479 3.99615C13.1033 4.22747 13.0996 4.46694 13.0996 4.76665V9.34966C13.0996 9.90056 13.0998 10.347 13.0703 10.7081C13.0403 11.0754 12.9772 11.4029 12.8223 11.7071C12.5778 12.1869 12.1868 12.5778 11.707 12.8223C11.4028 12.9772 11.0753 13.0404 10.708 13.0704C10.477 13.0892 10.2111 13.0944 9.90527 13.0967C9.8979 13.097 9.89026 13.0997 9.88281 13.0997C9.87558 13.0997 9.86849 13.097 9.86133 13.0967C9.70173 13.0977 9.53127 13.0997 9.34961 13.0997H3.75C3.56797 13.0997 3.39719 13.0977 3.2373 13.0967C3.23047 13.097 3.2237 13.0997 3.2168 13.0997C3.20902 13.0997 3.20106 13.0971 3.19336 13.0967C2.88792 13.0944 2.62237 13.0892 2.3916 13.0704C2.02429 13.0404 1.6968 12.9772 1.39258 12.8223C0.912765 12.5778 0.521821 12.1869 0.277344 11.7071C0.122451 11.4029 0.0593072 11.0754 0.0292969 10.7081C-0.000193806 10.347 3.26344e-08 9.90056 3.26344e-08 9.34966V3.75005ZM10.4336 2.81646C10.4336 2.99395 10.4332 3.16017 10.4219 3.29888C10.41 3.44397 10.3831 3.60695 10.3008 3.76861C10.1841 3.99754 9.99748 4.18419 9.76855 4.30083C9.6069 4.38313 9.44391 4.41007 9.29883 4.42193C9.16012 4.43324 8.9939 4.43365 8.81641 4.43365H4.2832C4.10571 4.43365 3.93949 4.43324 3.80078 4.42193C3.6557 4.41007 3.49271 4.38313 3.33105 4.30083C3.10212 4.18419 2.91547 3.99754 2.79883 3.76861C2.71653 3.60695 2.68959 3.44397 2.67773 3.29888C2.66642 3.16017 2.66602 2.99395 2.66602 2.81646V1.11333C2.60092 1.11647 2.53959 1.12031 2.48145 1.12505C2.18202 1.14952 2.01505 1.19498 1.8916 1.25786C1.61877 1.39688 1.39683 1.61882 1.25781 1.89165C1.19493 2.0151 1.14946 2.18207 1.125 2.4815C1.10004 2.78734 1.09961 3.18121 1.09961 3.75005V9.34966C1.09961 9.9185 1.10004 10.3124 1.125 10.6182C1.14946 10.9176 1.19493 11.0846 1.25781 11.2081C1.39683 11.4809 1.61877 11.7028 1.8916 11.8418C2.01505 11.9047 2.18202 11.9502 2.48145 11.9747C2.53958 11.9794 2.60094 11.9823 2.66602 11.9854V8.28326C2.66602 8.10576 2.66642 7.93954 2.67773 7.80083C2.68959 7.65575 2.71653 7.49276 2.79883 7.33111C2.91547 7.10218 3.10212 6.91553 3.33105 6.79888C3.49271 6.71659 3.6557 6.68964 3.80078 6.67779C3.93949 6.66647 4.10571 6.66607 4.2832 6.66607H8.81641C8.9939 6.66607 9.16012 6.66647 9.29883 6.67779C9.44391 6.68964 9.6069 6.71658 9.76855 6.79888C9.99748 6.91553 10.1841 7.10217 10.3008 7.33111C10.3831 7.49276 10.41 7.65575 10.4219 7.80083C10.4332 7.93954 10.4336 8.10576 10.4336 8.28326V11.9854C10.4987 11.9823 10.56 11.9794 10.6182 11.9747C10.9176 11.9502 11.0846 11.9047 11.208 11.8418C11.4808 11.7028 11.7028 11.4809 11.8418 11.2081C11.9047 11.0846 11.9501 10.9176 11.9746 10.6182C11.9996 10.3124 12 9.9185 12 9.34966V4.76665C12 4.41519 11.9965 4.3283 11.9785 4.25298C11.9594 4.17319 11.9276 4.09641 11.8848 4.02642C11.8442 3.96029 11.7851 3.89649 11.5361 3.64751L10.4336 2.54497V2.81646Z",fill:"currentColor"})})}function D1({className:t}){return e.jsx("svg",{viewBox:"0 0 11.0997 11.0997",fill:"none",overflow:"visible",preserveAspectRatio:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":!0,children:e.jsx("path",{d:"M8.3061e-06 8.16418V3.98938C8.06954e-06 3.58125 -0.00104354 3.24202 0.0214927 2.96594C0.0445847 2.68331 0.095322 2.41801 0.222665 2.16809C0.418356 1.78431 0.730417 1.47207 1.11427 1.27649C1.36411 1.14921 1.62861 1.09938 1.91114 1.07629C2.18735 1.05372 2.52712 1.05383 2.93556 1.05383H5.02247C5.32623 1.05383 5.57227 1.30085 5.57227 1.60461C5.57205 1.90817 5.32608 2.15442 5.02247 2.15442H2.93556C2.50903 2.15442 2.222 2.15492 2.00098 2.17297C1.78638 2.1905 1.6823 2.22179 1.61329 2.25695C1.43638 2.34718 1.29232 2.49114 1.20216 2.66809C1.16706 2.73705 1.1357 2.84068 1.11817 3.05481C1.10012 3.27578 1.09962 3.56298 1.09962 3.98938V8.16418C1.09962 8.59068 1.10012 8.87774 1.11817 9.09875C1.13571 9.31336 1.16699 9.41744 1.20216 9.48645C1.29235 9.66338 1.43635 9.80739 1.61329 9.89758C1.6823 9.93274 1.78638 9.96403 2.00098 9.98156C2.222 9.99961 2.50905 10.0001 2.93556 10.0001H7.11036C7.53675 10.0001 7.82396 9.99962 8.04493 9.98156C8.25905 9.96404 8.36269 9.93268 8.43165 9.89758C8.6086 9.80742 8.75256 9.66335 8.84278 9.48645C8.87794 9.41744 8.90923 9.31336 8.92677 9.09875C8.94482 8.87774 8.94532 8.59071 8.94532 8.16418V6.07727C8.94532 5.77365 9.19156 5.52769 9.49513 5.52746C9.79888 5.52746 10.0459 5.77351 10.0459 6.07727V8.16418C10.0459 8.57261 10.046 8.91238 10.0234 9.18859C10.0004 9.47112 9.95053 9.73563 9.82325 9.98547C9.62767 10.3693 9.31543 10.6814 8.93165 10.8771C8.68173 11.0044 8.41643 11.0552 8.1338 11.0782C7.85772 11.1008 7.51849 11.0997 7.11036 11.0997H2.93556C2.52712 11.0997 2.18735 11.1008 1.91114 11.0782C1.62855 11.0551 1.36416 11.0044 1.11427 10.8771C0.73032 10.6814 0.418324 10.3694 0.222665 9.98547C0.0953396 9.73558 0.0445889 9.47118 0.0214927 9.18859C-0.00107471 8.91238 8.3061e-06 8.57261 8.3061e-06 8.16418ZM8.36134 0.469845C8.98785 -0.156593 10.0034 -0.156637 10.6299 0.469845C11.2564 1.09633 11.2563 2.11189 10.6299 2.7384L5.87696 7.49133C5.72372 7.64457 5.58654 7.78743 5.41798 7.89074C5.27992 7.97535 5.12913 8.03749 4.97169 8.07531C4.77937 8.12148 4.58107 8.11829 4.36427 8.11828H3.5312
516C3.22786 8.11804 2.98171 7.87187 2.98145 7.56848V6.73547C2.98145 6.51866 2.97825 6.32037 3.02442 6.12805C3.06225 5.97061 3.12439 5.81982 3.20899 5.68176C3.31231 5.5132 3.45516 5.37601 3.60841 5.22277L8.36134 0.469845ZM4.08204 7.0177H4.36427C4.63327 7.01769 4.67849 7.01471 4.71485 7.00598C4.76009 6.9951 4.80311 6.97658 4.84278 6.95227C4.87467 6.93272 4.90926 6.90337 5.09962 6.71301L9.85255 1.96106C10.0494 1.76412 10.0495 1.44409 9.85255 1.24719C9.65564 1.05028 9.33561 1.05033 9.13868 1.24719L4.38673 6.00012C4.19638 6.19047 4.16701 6.22507 4.14747 6.25695C4.12316 6.29663 4.10464 6.33965 4.09376 6.38488C4.08503 6.42124 4.08204 6.46647 4.08204 6.73547V7.0177Z",fill:"currentColor"})})}function M1({className:t}){return e.jsx("svg",{viewBox:"0 0 12.1 11.1508",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":!0,children:e.jsx("path",{d:"M11.55 6.41296L10.4336 5.2962L9.31649 6.41296M10.6008 5.57539C10.6008 8.35084 8.35084 10.6008 5.57539 10.6008C2.79995 10.6008 0.55 8.35084 0.55 5.57539C0.55 2.79995 2.79995 0.55 5.57539 0.55C7.41911 0.55 9.03092 1.54287 9.90533 3.0231M5.57539 2.78351V5.57539L7.25052 6.69215",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",strokeLinejoin:"round"})})}function A1({isAdmin:t,briefWindowOpen:s,onToggleBrief:r,debugMode:a,onToggleDebug:o,onToggleVersions:i,versionsOpen:l,onCollapse:c}){return e.jsxs("div",{className:"flex items-center justify-between pt-[15px] pb-[5px] shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-[8px]",children:[e.jsx("img",{src:"/images/chat/icon-chat-console-sparkles.svg",alt:"",width:12,height:12,className:"size-[12px] shrink-0","aria-hidden":!0}),e.jsx("span",{className:"text-[12px] font-medium text-black tracking-[-0.24px] whitespace-nowrap",children:"Chat 
51Console"})]}),e.jsxs("div",{className:"flex items-center gap-[5px]",children:[t&&e.jsxs("div",{className:"flex items-center gap-[6px]",children:[e.jsx("button",{type:"button",onClick:r,className:`flex items-center gap-[6px] h-[26px] px-[10px] py-[5px] rounded-[5px] border text-[10px] font-medium tracking-[-0.2px] transition-colors ${s?"border-blue-300 text-blue-600 bg-blue-50":"border-[#e8e8e8] text-[#a3a3a3] hover:bg-[#f5f5f5]"}`,title:"Admin: show current design brief",children:"Brief"}),e.jsx("button",{type:"button",onClick:o,className:`flex items-center gap-[5px] h-[26px] px-[10px] rounded-[5px] border text-[10px] font-medium tracking-[-0.2px] transition-colors ${a?"border-orange-300 text-orange-600 bg-orange-50":"border-[#e1e1e1] bg-white text-black hover:bg-[#f5f5f5]"}`,title:"Admin: toggle debug view",children:a?"Debug on":"Debug"})]}),i&&e.jsx("button",{type:"button","data-testid":xn.chatPanel.versionsButton,onClick:i,className:l?"flex size-[26px] items-center justify-center rounded-[5px] bg-black text-white transition-colors shrink-0":"flex size-[26px] items-center justify-center rounded-[5px] border border-[#e1e1e1] bg-white text-black hover:bg-[#f5f5f5] transition-colors shrink-0","aria-label":"Versions history","aria-pressed":l,title:"Versions history",children:e.jsx(M1,{className:"size-[10px]"})}),c&&e.jsx("button",{type:"button",onClick:c,className:"flex items-center justify-center size-[26px] rounded-[5px] border border-[#e1e1e1] bg-white hover:bg-[#f5f5f5] transition-colors shrink-0","aria-label":"Collapse chat panel",title:"Collapse",children:e.jsx("svg",{viewBox:"0 0 11.1 11.1",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"size-[10px]","aria-hidden":!0,children:e.jsx("path",{d:"M3.88333 0.55V10.55M7.8 4.05L6.3 5.55L7.8 7.05M3.21667 0.55H7.88333C8.81675 0.55 9.28347 0.55 9.63998 0.731656C9.95359 0.891445 10.2086 1.14641 10.3683 1.46002C10.55 1.81654 10.55 2.28325 10.55 3.21667V7.88333C10.55 8.81675 10.55 9.28347 10.3683 9.63998C10.2086 9.95359 9.95359 10.2086 9.63998 10.3683C9.28347 10.55 8.81675 10.55 7.88333 10.55H3.21667C2.28325 10.55 1.81654 10.55 1.46002 10.3683C1.14641 10.2086 0.891445 9.95359 0.731656 9.63998C0.55 9.28347 0.55 8.81675 0.55 7.88333V3.21667C0.55 2.28325 0.55 1.81654 0.731656 1.46002C0.891445 1.14641 1.14641 0.891445 1.46002 0.731656C1.81654 0.55 2.28325 0.55 3.21667 0.55Z",stroke:"black",strokeWidth:"1.1",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})}function zd({files:t}){return!t||t.length===0?null:e.jsx("div",{className:"flex flex-wrap gap-2",children:t.map((s,r)=>{if(s.kind==="video")return e.jsx(Cu,{fallbackUrl:s.url,streamUrl:s.stream_url,streamFormat:s.stream_format,muted:!0,controls:!0,className:"w-20 h-20 object-cover rounded-[10px] border border-[#e5e5e5]"},r);const a=s.kind==="document",o=s.name||(a?"Document":"Snippet");return e.jsxs("div",{className:"flex items-center gap-[6px] max-w-[180px] px-[10px] py-[6px] rounded-[10px] border border-[#e5e5e5] bg-[#f7f7f7] text-[12px] text-[#525252]",children:[a?e.jsx(mp,{className:"size-[14px] shrink-0"}):e.jsx(dp,{className:"size-[14px] shrink-0"}),e.jsx("span",{className:"truncate",children:o})]},r)})})}function P1({content:t,images:s,referenceFiles:r,userName:a,mobile:o}){return o?e.jsx("div",{className:"flex w-full justify-end mt-[10px]",children:e.jsxs("div",{className:"flex max-w-[85%] flex-col items-start gap-[10px] rounded-[20px] bg-[#e9e9e9] p-[15px]",children:[s&&s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map((i,l)=>e.jsx("img",{src:i,alt:`Attached image ${l+1}`,className:"w-20 h-20 object-cover rounded-[10px] border border-[#e5e5e5]"},l))}),e.jsx(zd,{files:r}),t&&e.jsx("div",{dir:Zo(t)?"rtl":"ltr",className:"whitespace-pre-wrap break-words text-[14px] font-normal leading-[1.4] tracking-[-0.28px] text-black",children:t})]})}):e.jsxs("div",{className:"flex flex-col justify-center items-start gap-[10px] w-full p-[20px] rounded-[10px] border border-[#e1e1e1] bg-white shadow-none mt-[5px] mb-0",children:[e.jsxs("div",{className:"flex items-center gap-[6px]",children:[e.jsx("svg",{viewBox:"0 0 13.1 13.1",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"size-[12px] shrink-0","aria-hidden":!0,
51children:e.jsx("path",{d:"M2.53978 11.013C2.90477 10.1531 3.75695 9.55 4.75 9.55H8.35C9.34305 9.55 10.1952 10.1531 10.5602 11.013M8.95 5.05C8.95 6.37548 7.87548 7.45 6.55 7.45C5.22452 7.45 4.15 6.37548 4.15 5.05C4.15 3.72452 5.22452 2.65 6.55 2.65C7.87548 2.65 8.95 3.72452 8.95 5.05ZM12.55 6.55C12.55 9.86371 9.86371 12.55 6.55 12.55C3.23629 12.55 0.55 9.86371 0.55 6.55C0.55 3.23629 3.23629 0.55 6.55 0.55C9.86371 0.55 12.55 3.23629 12.55 6.55Z",stroke:"black",strokeWidth:"1.1",strokeLinecap:"round",strokeLinejoin:"round"})}),a&&e.jsx("span",{className:"text-[11px] font-medium text-[#525252] tracking-[-0.22px]",children:a})]}),s&&s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map((i,l)=>e.jsx("img",{src:i,alt:`Attached image ${l+1}`,className:"w-20 h-20 object-cover rounded-[10px] border border-[#e5e5e5]"},l))}),e.jsx(zd,{files:r}),t&&e.jsx("div",{dir:Zo(t)?"rtl":"ltr",className:"text-[12px] text-[#7d7d7d] break-words leading-[1.4] tracking-[-0.24px] w-full min-w-0 whitespace-pre-wrap",children:t})]})}function O1({onSuggestion:t}){return null}const Uc={supervisor:"Supervisor",artDirector:"Art Director",coder:"Coder"},Kp={supervisor:{accent:"#475569",tint:"#f1f5f9"},artDirector:{accent:"#b45309",tint:"#fffbeb"},coder:{accent:"#0f766e",tint:"#f0fdfa"}};function Ni(t){return t==="artDirector"||t==="coder"?t:"supervisor"}let Ud=0;function L1(){return Ud+=1,`turn-${Ud}-${Date.now()}`}function Pa(t,s,r){const a=[...t];if(r.toolResult!==void 0&&!r.toolCall&&!r.reasoningDelta&&!r.replyDelta&&!r.artDirector)for(let c=a.length-1;c>=0;c--){if(a[c].agent!==s)continue;const x={...a[c]},h=[...x.toolCalls||[]];return h.length&&(h[h.length-1]={...h[h.length-1],result:r.toolResult}),x.toolCalls=h,a[c]=x,a}const o=a[a.length-1],i=!o||o.agent!==s,l=i?{id:L1(),agent:s,startedAt:Date.now()}:{...o};if(i?a.push(l):a[a.length-1]=l,r.reasoningDelta&&(l.reasoning=(l.reasoning||"")+r.reasoningDelta),r.replyDelta&&(l.reply=(l.reply||"")+r.replyDelta),r.toolCall&&(l.toolCalls=[...l.toolCalls||[],r.toolCall]),r.toolResult!==void 0){const c=[...l.toolCalls||[]];c.length&&(c[c.length-1]={...c[c.length-1],result:r.toolResult}),l.toolCalls=c}return r.artDirector!==void 0&&(l.artDirector=r.artDirector),a}function B1(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function F1(t){if(!t)return"";let s=B1(t);return s=s.replace(/```(\w*)\n([\s\S]*?)```/g,(r,a,o)=>`<pre class="bg-[#f0f0f0] border border-[#e5e5e5] rounded-[10px] p-3 my-2 overflow-x-auto text-xs text-[#262626]"><code class="language-${a||"text"}">${o.trim()}</code></pre>`),s=s.replace(/`([^`]+)`/g,'<code class="bg-[#e5e5e5] text-[#262626] px-1 rounded text-xs">$1</code>'),s=s.replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>"),s=s.replace(/\n/g,"<br>"),s}const $1={get_tool_schema:qm,get_tool_state:Pl,set_controls_schema:bp,set_canvas_code:Uf,edit_canvas_code:Bd,set_libraries:Wm,set_custom_css:Bd};function V1(t,s){if(!s)return"";const r=s;if(t==="agent-artDirector"||t==="agent-coder"){const a=r.prompt||r.message||"";return a?`"${a.slice(0,60)}${a.length>60?"…":""}"`:""}if(t==="set_controls_schema")try{return`${(Array.isArray(r.schema)?r.schema:JSON.parse(r.schema||"[]")).length} controls`}catch{return""}if(t==="set_canvas_code"){const a=(r.code||"").length;return a>0?`${a} chars`:""}if(t==="edit_canvas_code")return r.old_string?`"${r.old_string.slice(0,40)}…"`:"";if(t==="set_libraries")try{return`${(Array.isArray(r.libraries)?r.libraries:JSON.parse(r.libraries||"[]")).length} lib(s)`}catch{return""}return t==="set_custom_css"?r.css?`${r.css.length} chars`:"":t==="get_tool_schema"||t==="get_tool_state"?"":JSON.stringify(s).slice(0,80)}function Gc({text:t}){const[s,r]=n.useState(!1);return e.jsx("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(t).then(()=>{r(!0),setTimeout(()=>r(!1),1500)})},className:"flex items-center gap-1 text-[10px] text-[#737373] hover:text-[#525252] transition-colors",title:"Copy to clipboard",children:s?e.jsx(Qo,{className:"w-3 h-3 text-green-600"}):e.jsx(Yi,{className:"w-3 h-3"})})}function H1(t){return t==="agent-artDirector"?"delegate → Art Director":t==="agent-coder"?"delegate → Coder":t}function Yp({tc:t}){const[s,r]=n.useState(!1),a=$1[t.name]||Ah,o=V1(t.name,t.args),i=JSON.stringify(t.args,null,2),l=H1(t.name),c=t.name.startsWith("agent-");return e.jsxs("div",{className:"flex flex-col bg-[#f5f5f5] rounded-[10px] border border-[#e5e5e5] text-[12px] overflow-hidden",children:[e.jsxs("button",{onClick:()=>r(x=>!x),className:"flex items-center gap-1.5 px-2 py-1.5 hover:bg-[#ebebeb] transition-colors text-left",children:[s?e.jsx(vo,{className:"w-3 h-3 text-[#a3a3a3] shrink-0"}):e.jsx(yo,{className:"w-3 h-3 text-[#a3a3a3] shrink-0"}),e.jsx(a,{className:"w-3 h-3 text-[#737373] shrink-0"}),e.jsx("span",{className:`font-mono ${c?"text-[#475569] font-medium":"text-[#525252]"}`,children:l}),!s&&o&&e.jsx("span",{className:"text-[#a3a3a3] truncate max-w-[160px]",children:o}),t.result&&!s&&c&&e.jsx("span",{className:"text-[#a3a3a3] ml-auto shrink-0",children:t.result})]}),s&&e.jsxs("div",{className:"flex flex-col gap-1 px-2 pb-2 border-t border-[#e5e5e5]",children:[e.jsxs("div",{className:"flex items-center justify-between pt-1",children:[e.jsx("div",{className:"text-[10px] text-[#a3a3a3] uppercase tracking-wide",children:"Args"}),e.jsx(Gc,{text:i})]}),e.jsx("pre",{className:"text-[10px] text-[#525252] font-mono whitespace-pre-wrap break-all bg-white border border-[#e5e5e5] rounded-[6px] p-2 max-h-48 overflow-y-auto",children:i}),t.result&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[10px] text-[#a3a3a3] uppercase tracking-wide",children:"Result"}),e.jsx(Gc,{text:t.result})]}),e.jsx("pre",{className:"text-[10px] text-[#737373] font-mono whitespace-pre-wrap break-all bg-white border border-[#e5e5e5] rounded-[6px] p-2 max-h-64 overflow-y-auto",children:t.result})]})]})]})}function z1(t,s){const r=t.split(`
52`),a=s.split(`
53`),o=r.length,i=a.length,l=Array.from({length:o+1},()=>new Array(i+1).fill(0));for(let y=o-1;y>=0;y--)for(let u=i-1;u>=0;u--)l[y][u]=r[y]===a[u]?l[y+1][u+1]+1:Math.max(l[y+1][u],l[y][u+1]);const c=[];let x=0,h=0;for(;x<o&&h<i;)r[x]===a[h]?(c.push({type:"same",text:r[x]}),x++,h++):l[x+1][h]>=l[x][h+1]?(c.push({type:"del",text:r[x]}),x++):(c.push({type:"add",text:a[h]}),h++);for(;x<o;)c.push({type:"del",text:r[x++]});for(;h<i;)c.push({type:"add",text:a[h++]});return c}function U1({previousBrief:t,brief:s}){const r=z1(t,s);return e.jsx("pre",{className:"px-2 pb-2 text-[11px] leading-[15px] border-t border-[#e5e5e5] whitespace-pre-wrap break-words font-mono",children:r.map((a,o)=>e.jsxs("div",{className:a.type==="add"?"bg-green-50 text-green-700":a.type==="del"?"bg-red-50 text-red-700 line-through decoration-red-300":"text-[#a3a3a3]",children:[a.type==="add"?"+ ":a.type==="del"?"- ":"  ",a.text||" "]},o))})}function Zp({artDirector:t}){const[s,r]=n.useState(!1),[a,o]=n.useState(!1),i=Zl();if(!t)return null;const l=!!(t.updated&&t.previousBrief),c=t.reconcile,x=(c==null?void 0:c.decision)==="yes"&&c.raw==="";return e.jsxs("div",{className:"border border-[#e5e5e5] rounded-[10px] bg-[#fafafa] overflow-hidden",children:[e.jsxs("button",{onClick:()=>{t.brief&&(i("debug_thinking_art_director_toggle"),r(h=>!h))},className:"flex items-center gap-1.5 w-full px-2 py-1.5 text-[10px] text-[#525252] hover:bg-[#f0f0f0] transition-colors",children:[e.jsx(gp,{className:"w-3 h-3"}),e.jsx("span",{className:"text-[12px]",children:t.status==="running"?"Art Director is reviewing…":l?"Brief updated":t.status==="skipped"?"Art Director skipped — preset brief":(c==null?void 0:c.decision)==="no"?"Art Director skipped — minor tweak":(c==null?void 0:c.decision)==="yes"?"Brief kept — reviewed, no change":"Art Director"}),c&&e.jsxs("span",{title:c.raw?`gate said "${c.raw}"`:"gate fail-safed (no model answer)",className:`text-[10px] px-1 rounded ${c.decision==="no"?"bg-[#f0f0f0] text-[#737373]":x?"bg-orange-100 text-orange-700":"bg-blue-50 text-blue-600"}`,children:[c.decision==="no"?"AD skipped":"AD ran",x?" (fail-safe)":""]}),t.status==="running"&&e.jsx(In,{className:"w-3 h-3 animate-spin ml-auto"}),t.brief&&(s?e.jsx(yo,{className:"w-3 h-3 ml-auto"}):e.jsx(vo,{className:"w-3 h-3 ml-auto"}))]}),c&&e.jsxs("div",{className:"px-2 py-1 border-t border-[#e5e5e5] text-[10px] font-mono text-[#737373] flex flex-wrap gap-x-2 gap-y-0.5",children:[e.jsxs("span",{children:["Gate A (re-run AD?): ",e.jsx("span",{className:"text-[#525252]",children:c.decision??"—"}),x?" (fail-safe)":""]}),e.jsxs("span",{children:["raw:"," ",e.jsx("span",{className:"text-[#525252]",children:c.raw?`"${c.raw}"`:"∅"})]}),c.model?e.jsxs("span",{children:["model: ",c.model]}):null,typeof c.ms=="number"?e.jsxs("span",{children:[c.ms,"ms"]}):null,c.error?e.jsxs("span",{className:"text-red-600",children:["err: ",c.error]}):null]}),t.brief&&!s&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:a?"":"max-h-[140px] overflow-y-auto",children:l?e.jsx(U1,{previousBrief:t.previousBrief,brief:t.brief}):e.jsx("div",{className:"px-2 pb-2 pt-1 text-[12px] text-[#737373] leading-[14px] border-t border-[#e5e5e5]",dangerouslySetInnerHTML:{__html:F1(t.brief)}})}),e.jsx("button",{type:"button",onClick:()=>o(h=>!h),className:"w-full py-1 text-[10px] text-[#737373] hover:bg-[#f0f0f0] border-t border-[#e5e5e5] transition-colors",children:a?"Show less":"Show more"})]})]})}function G1({skills:t}){return!t||t.length===0?null:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap px-1",children:[e.jsx(Lp,{className:"w-3 h-3 text-[#737373]"}),e.jsx("span",{className:"text-[10px] text-[#737373]",children:"Skills"}),t.map((s,r)=>e.jsx("span",{className:"text-[9px] bg-[#e8f5e9] text-[#2e7d32] border border-[#c8e6c9] rounded px-1.5 py-0.5",children:s},r))]})}function W1({debug:t}){const[s,r]=n.useState(!1),a=t.matches.filter(i=>!i.isWildcard),o=t.matches.filter(i=>i.isWildcard);return e.jsxs("div",{className:"border border-[#e5e5e5] rounded-[10px] bg-[#fafafa] overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1.5 text-[12px] text-[#525252]",children:[e.jsx(Lp,{className:"w-3 h-3"}),e.jsx("span",{children:"Skills"}),e.jsxs("span",{className:"text-[10px] text-[#a3a3a3] ml-auto tabular-nums",children:[t.contextChars," chars · Mastra on-demand"]})]}),e.jsxs("div",{className:"px-2 pb-2 flex flex-col gap-1.5",children:[a.length>0&&e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx("span",{className:"text-[10px] text-[#737373]",children:"Scored"}),a.map((i,l)=>e.jsxs("span",{className:"text-[9px] bg-[#e8f5e9] text-[#2e7d32] border border-[#c8e6c9] rounded px-1.5 py-0.5",title:`score ${i.score}`,children:[i.name," ",e.jsxs("span",{className:"text-[#558b2f]",children:["·",i.score]})]},l))]}),o.length>0&&e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx("span",{className:"text-[10px] text-[#737373]",children:"Wildcard"}),o.map((i,l)=>e.jsx("span",{className:"text-[9px] bg-[#e3f2fd] text-[#1565c0] border border-[#bbdefb] rounded px-1.5 py-0.5",children:i.name},l))]}),t.conceptTags&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-[10px] text-[#737373]",children:"Concept tags fed to matcher"}),e.jsx("pre",{className:"text-[10px] text-[#525252] whitespace-pre-wrap font-mono bg-white border border-[#e5e5e5] rounded-[6px] p-2 max-h-32 overflow-y-auto",children:t.conceptTags})]}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",onClick:()=>r(i=>!i),className:"flex items-center gap-1 text-[10px] text-[#737373] hover:text-[#525252]",children:[s?e.jsx(vo,{className:"w-3 h-3"}):e.jsx(yo,{className:"w-3 h-3"}),e.jsxs("span",{children:["Assembled system prompt (",t.assembledPrompt.length," chars)"]}),e.jsx(Gc,{text:t.assembledPrompt})]}),s&&e.jsx("pre",{className:"mt-1 text-[10px] text-[#525252] whitespace-pre-wrap font-mono bg-white border border-[#e5e5e5] rounded-[6px] p-2 max-h-64 overflow-y-auto",children:t.assembledPrompt})]})]})]})}function Gd({ok:t,label:s}){return t===void 0?e.jsxs("span",{className:"text-[9px] bg-[#f5f5f5] text-[#a3a3a3] border border-[#e5e5e5] rounded px-1.5 py-0.5",children:[s," —"]}):e.jsxs("span",{className:t?"text-[9px] bg-[#e8f5e9] text-[#2e7d32] border border-[#c8e6c9] rounded px-1.5 py-0.5":"text-[9px] bg-[#ffe4e1] text-[#c2185b] border border-[#f8bbd0] rounded px-1.5 py-0.5",children:[s," ",t?"OK":"FAIL"]})}function q1({health:t}){const[s,r]=n.useState(!1),a=t.canvasOk===!1||t.controlsOk===!1;return e.jsxs("div",{className:"border border-[#e5e5e5] rounded-[10px] bg-[#fafafa] overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>r(o=>!o),className:"flex items-center gap-1.5 w-full px-2 py-1.5 text-[12px] text-[#525252] hover:text-[#262626]",children:[s?e.jsx(vo,{className:"w-3 h-3"}):e.jsx(yo,{className:"w-3 h-3"}),e.jsx(Ch,{className:"w-3 h-3"}),e.jsx("span",{children:"Tool health"}),e.jsxs("span",{className:"ml-auto flex items-center gap-1",children:[e.jsx(Gd,{ok:t.canvasOk,label:t.renderKind==="svg"?"svg":"canvas"}),e.jsx(Gd,{ok:t.controlsOk,label:"controls"}),a&&e.jsx("span",{className:"text-[9px] bg-[#ffe4e1] text-[#c2185b] border border-[#f8bbd0] rounded px-1.5 py-0.5",children:"!"})]})]}),s&&e.jsxs("div",{className:"px-2 pb-2 flex flex-col gap-1.5",children:[a&&e.jsxs("div",{className:"flex flex-col gap-0.5 text-[11px] text-[#c2185b]",children:[t.canvasOk===!1&&e.jsxs("span",{children:["⚠ Canvas:"," ",t.canvasReason??"no visible, non-zero render surface (canvas/svg)"]}),t.controlsOk===!1&&e.jsxs("span",{children:["⚠ Controls: only ",t.controlsRendered??0,"/",t.controlsDeclared??0," ","declared controls rendered"]})]}),e.jsx("pre",{className:"text-[10px] text-[#525252] whitespace-pre-wrap font-mono bg-white border border-[#e5e5e5] rounded-[6px] p-2 overflow-x-auto",children:[`renderOk:         ${t.canvasOk??"—"}`,`renderKind:       ${t.renderKind??"—"}`,`canvasReason:     ${t.canvasReason||"—"}`,`canvasWidth:      ${t.canvasWidth??"—"}`,`canvasHeight:     ${t.canvasHeight??"—"}`,`controlsOk:       ${t.controlsOk??"—"}`,`controlsDeclared: ${t.controlsDeclared??"—"}`,`controlsRendered: ${t.controlsRendered??"—"}`,`maybeBlank:       ${t.maybeBlank??"—"}`].join(`
54`)})]})]})}function K1(){return e.jsx("div",{className:"flex items-center gap-3 px-2 pb-1",children:Object.keys(Uc).map(t=>e.jsxs("span",{className:"flex items-center gap-1 text-[9px] text-[#737373]",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full shrink-0",style:{backgroundColor:Kp[t].accent}}),Uc[t]]},t))})}function Y1({turn:t,turnDone:s}){const r=Kp[t.agent],a=!s,o=!!t.artDirector||!!t.reasoning||!!t.reply||!!(t.toolCalls&&t.toolCalls.length>0);return e.jsxs("div",{className:"rounded-[10px] overflow-hidden border",style:{borderColor:`${r.accent}33`,backgroundColor:r.tint,borderLeftWidth:3,borderLeftColor:r.accent},children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1.5",children:[e.jsx("span",{className:"text-[10px] font-medium px-1.5 py-0.5 rounded",style:{color:r.accent,backgroundColor:`${r.accent}14`},children:Uc[t.agent]}
54),a&&e.jsxs("span",{className:"flex items-center gap-1 text-[9px] text-[#737373]",children:[e.jsx(In,{className:"w-2.5 h-2.5 animate-spin"}),"running"]})]}),e.jsxs("div",{className:"px-2 pb-2 flex flex-col gap-1.5",children:[t.artDirector&&e.jsx(Zp,{artDirector:t.artDirector}),t.reasoning&&e.jsxs("div",{className:"bg-white/70 border border-[#e5e5e5] rounded-[10px] p-2 max-h-32 overflow-y-auto",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-wide text-[#a3a3a3] mb-1",children:"Reasoning"}),e.jsx("pre",{className:"text-[10px] text-[#737373] whitespace-pre-wrap font-mono leading-relaxed",children:t.reasoning})]}),(t.toolCalls||[]).map((i,l)=>e.jsx(Yp,{tc:i},l)),t.reply&&e.jsxs("div",{className:"bg-white/70 border border-[#e5e5e5] rounded-[10px] p-2 max-h-32 overflow-y-auto",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-wide text-[#a3a3a3] mb-1",children:"Reply"}),e.jsx("pre",{className:"text-[10px] text-[#525252] whitespace-pre-wrap leading-relaxed",children:t.reply})]}),!o&&e.jsx("span",{className:"text-[10px] text-[#a3a3a3] px-0.5",children:"…"})]})]})}function Z1({block:t}){const[s,r]=n.useState(!1),[a,o]=n.useState(0),i=Zl();n.useEffect(()=>{if(t.done){o(t.elapsed||0);return}const h=t.startTime,y=()=>o(Math.round((Date.now()-h)/1e3));y();const u=setInterval(y,1e3);return()=>clearInterval(u)},[t.done,t.startTime,t.elapsed]);const l=t.done?t.hasReasoning?`Reasoned for ${a}s`:`Thought for ${a}s`:t.hasReasoning?"Reasoning…":"Thinking…",c=t.turns??[],x=c.length>0;return e.jsxs("div",{className:"mx-3 my-1 border border-orange-200 rounded-[10px] bg-orange-50/40",children:[e.jsxs("div",{className:"px-2 pt-1 pb-0 flex items-center justify-between",children:[e.jsx("span",{className:"text-[9px] font-medium text-orange-500 uppercase tracking-wide",children:"Debug view (admin)"}),t.requestId&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[9px] text-gray-500",children:"Request ID:"}),e.jsxs("a",{href:`https://brikapp.grafana.net/d/brik-errors-drilldown/brik-error-drill-down?orgId=1&from=now-7d&to=now&timezone=browser&var-datasource=grafanacloud-logs&var-env=production&var-interval=5m&var-requestId=${t.requestId}&var-function=$__all&refresh=1m`,target:"_blank",rel:"noopener noreferrer",className:"text-[9px] font-mono text-blue-600 hover:text-blue-800 underline",title:"View logs in Grafana",children:[t.requestId.slice(0,8),"..."]}),e.jsx("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(t.requestId)},className:"text-[9px] text-gray-500 hover:text-gray-700",title:"Copy request ID",children:e.jsx(Yi,{className:"w-2.5 h-2.5"})})]})]}),e.jsxs("button",{onClick:()=>{i("debug_thinking_block_toggle"),r(h=>!h)},className:"flex items-center gap-1.5 w-full text-[10px] text-[#737373] hover:text-[#525252] px-2 py-1 transition-colors",children:[s?e.jsx(yo,{className:"w-3 h-3"}):e.jsx(vo,{className:"w-3 h-3"}),t.done?e.jsx(Qo,{className:"w-3 h-3 text-green-600"}):e.jsx(In,{className:"w-3 h-3 animate-spin"}),e.jsx("span",{children:l}),!t.done&&t.currentStep&&e.jsxs("span",{className:"ml-1 text-[#a3a3a3] truncate max-w-[160px]",children:["— ",t.currentStep]}),!t.done&&e.jsxs("span",{className:"ml-auto tabular-nums",children:[a,"s"]})]}),!s&&x&&e.jsx(K1,{}),!s&&e.jsxs("div",{className:"pl-5 pr-2 flex flex-col gap-1.5 pb-2",children:[x?c.map((h,y)=>e.jsx(Y1,{turn:h,turnDone:t.done||y<c.length-1},h.id)):e.jsxs(e.Fragment,{children:[e.jsx(Zp,{artDirector:t.artDirector}),t.reasoning&&e.jsx("div",{className:"bg-[#f5f5f5] border border-[#e5e5e5] rounded-[10px] p-2 max-h-32 overflow-y-auto",children:e.jsx("pre",{className:"text-[10px] text-[#737373] whitespace-pre-wrap font-mono leading-relaxed",children:t.reasoning})}),(t.toolCalls||[]).map((h,y)=>e.jsx(Yp,{tc:h},y))]}),t.skillsDebug?e.jsx(W1,{debug:t.skillsDebug}):e.jsx(G1,{skills:t.skills}),t.health&&e.jsx(q1,{health:t.health})]})]})}const Vn={understanding:{new:["Understanding your vision…","Exploring your idea…","Imagining the possibilities…"],iteration:["Reading your feedback…","Picking up where we left off…"],remix:["Studying the original…"]}
54,designing:{default:["Designing the experience…","Shaping the creative direction…","Planning the visual approach…"],artRunning:"Consulting the art director…",artDone:"Creative direction set — moving to build…",iteration:"Planning the changes…"},building:{default:"Building your tool…",idle:"Thinking through the details…",slow:"Still working — this one is complex…"},done:{new:"Your tool is ready",iteration:"Changes applied",stopped:"Generation stopped",error:"Something went wrong"},plan:["Preparing your plan…","Planning your tool…","Thinking it through…"]},J1={get_tool_state:"Reviewing the current state…",get_tool_schema:"Reviewing the current state…",search_media_assets:"Looking through the media library…",set_controls_schema:"Setting up the controls…",set_canvas_code:"Writing the code…",edit_canvas_code:"Refining the code…",set_libraries:"Adding creative libraries…",set_custom_css:"Styling the details…"};function X1(t,s){return t==="set_canvas_code"&&s?"Still writing…":J1[t]??"Working on it…"}function Jp(t,s){if(t==="remix")return Vn.understanding.remix[0];if(t==="iteration"){const a=Vn.understanding.iteration;return a[s%a.length]}const r=Vn.understanding.new;return r[s%r.length]}function Xp(t,s,r){if(s)return s;if(t==="iteration")return Vn.designing.iteration;const a=Vn.designing.default;return a[r%a.length]}function Wd(t){const s=Vn.plan;return s[t%s.length]}function Wc(t){return t.stopped?Vn.done.stopped:t.error?Vn.done.error:t.mode==="iteration"?Vn.done.iteration:Vn.done.new}const Q1="linear-gradient(100deg, var(--product-grey-05) 20%, var(--product-grey-02) 50%, var(--product-grey-05) 80%)",e0={backgroundImage:Q1,backgroundSize:"300% 100%",WebkitBackgroundClip:"text",backgroundClip:"text",color:"transparent"};function Fl({children:t,className:s=""}){return e.jsx("span",{className:`animate-[chat-shimmer_2.4s_linear_infinite] ${s}`,style:e0,children:t})}function qd({label:t,elapsedSeconds:s,detail:r,mark:a,onToggle:o,expanded:i,children:l}){return e.jsxs("div",{className:"flex w-full flex-col items-start gap-[12px] px-[16px] py-[12px]",children:[e.jsxs("button",{type:"button",onClick:o,"aria-expanded":i,disabled:!o,className:"flex w-full flex-col items-start gap-[12px] text-left disabled:cursor-default",children:[a&&e.jsx("span",{className:"flex h-[22px] w-[23px] shrink-0 items-center",children:a}),e.jsxs("span",{className:"flex w-full flex-col items-start gap-[8px] leading-[1.2]",children:[e.jsxs("span",{className:"flex w-full items-start justify-between whitespace-nowrap text-[12px] tracking-[-0.36px] capitalize",children:[e.jsx(Fl,{children:t}),s!==void 0&&e.jsxs(Fl,{className:"tabular-nums",children:[s,"s"]})]}),r&&e.jsx("span",{className:"w-full truncate text-[10px] tracking-[-0.3px]",style:{color:"var(--product-grey-03)"},children:r})]})]}),l]})}const $l=["understanding","designing","building"];function hc(t){const s=$l.indexOf(t);return s===-1?$l.length:s}function Qp(t,s){const[r,a]=n.useState(0);return n.useEffect(()=>{if(!s){a(0);return}const o=()=>a(Math.round((Date.now()-t)/1e3));o();const i=setInterval(o,1e3);return()=>clearInterval(i)},[s,t]),r}function Kd({phaseKey:t,label:s,subStatus:r,isActive:a,showElapsed:o,startedAt:i=0}){const l=Qp(i,!!(o&&a)),c={understanding:vp,designing:gp,building:bp,done:Qo}[t];return e.jsxs("div",{className:"flex flex-col gap-0.5 text-[11px] transition-opacity duration-300",style:{opacity:a?1:.5},children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(c,{className:`w-3 h-3 shrink-0 ${a?"text-[#737373]":"text-[#a3a3a3]"}`}),e.jsx("span",{className:a?"text-[#525252]":"text-[#a3a3a3]",children:s}),a&&e.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-1.5",children:[e.jsx(In,{className:"h-3 w-3 animate-spin text-[#a3a3a3]"}),o&&e.jsxs("span",{className:"tabular-nums text-[10px] text-[#a3a3a3]",children:[l,"s"]}
54)]})]}),a&&r&&e.jsx("span",{className:"pl-[18px] text-[10px] text-[#a3a3a3] transition-all duration-200 animate-in fade-in",children:r},r)]})}function t0({phase:t}){const s=Wc(t);return t.error?e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[e.jsx(Kl,{className:"w-3 h-3 text-red-500 shrink-0"}),e.jsx("span",{className:"text-red-500",children:s})]}):e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]","data-testid":"tool-editor-ready-state",children:[e.jsx(Qo,{className:"w-3 h-3 text-green-600 shrink-0"}),e.jsx("span",{className:"text-[#525252]",children:s})]})}const gc="flex w-full flex-col gap-[8px] px-[16px] pb-[12px]";function n0(t,s,r){return t==="understanding"?Jp(s.mode,r):t==="designing"?Xp(s.mode,s.designSubStatus,r):Vn.building.default}function Yd({label:t,subStatus:s,isActive:r,showElapsed:a,startedAt:o=0}){const i=Qp(o,!!(a&&r));return e.jsxs("div",{className:"flex w-full flex-col gap-[4px]",children:[e.jsxs("div",{className:"flex w-full items-start gap-[8px] text-[12px] leading-[1.3] tracking-[-0.12px]",children:[r?e.jsx(Fl,{children:t}):e.jsx("span",{style:{color:"var(--product-grey-03)"},children:t}),r&&a&&e.jsxs(Fl,{className:"ml-auto tabular-nums",children:[i,"s"]})]}),r&&s&&e.jsx("span",{className:"text-[10px] leading-[1.3] tracking-[-0.3px]",style:{color:"var(--product-grey-03)"},children:s})]})}function s0({phase:t,copyVariantIndex:s,planMode:r,chrome:a="legacy",showElapsed:o=!1}){const i=hc(t.current),l=t.current==="done";if(a==="new-design"){if(l)return t.error?e.jsx(fp,{tone:"error",message:Wc(t)}):!t.madeChanges&&!t.stopped?null:e.jsx("div",{className:gc,"data-testid":"tool-editor-ready-state",children:e.jsx("span",{className:"text-[12px] leading-[1.3] tracking-[-0.12px]",style:{color:"var(--product-grey-05)"},children:Wc(t)})});if(r)return e.jsx("div",{className:gc,children:e.jsx(Yd,{label:Wd(s),isActive:!0,showElapsed:o,startedAt:t.startedAt})});const h=$l.filter(w=>hc(w)<=i).map(w=>({phase:w,label:n0(w,t,s)})),y=t.current==="building"?t.buildSubStatus:void 0,u=h.some(w=>w.label===y)?void 0:y;return e.jsx("div",{className:gc,children:h.map(w=>e.jsx(Yd,{label:w.label,subStatus:w.phase==="building"?u:void 0,isActive:t.current===w.phase,showElapsed:o,startedAt:t.startedAt},w.phase))})}if(r&&!l)return e.jsx("div",{className:"mx-3 my-2",children:e.jsx(Kd,{phaseKey:"understanding",label:Wd(s),isActive:!0,showElapsed:o,startedAt:t.startedAt})});const c=$l.filter(h=>hc(h)<=i);if(l)return!t.madeChanges&&!t.error&&!t.stopped?null:e.jsx("div",{className:"mx-3 my-2",children:e.jsx(t0,{phase:t})});const x=Xp(t.mode,t.designSubStatus,s);return e.jsx("div",{className:"mx-3 my-2 flex flex-col gap-1.5",children:c.map(h=>{const y=t.current===h;let u="",w;return h==="understanding"?u=Jp(t.mode,s):h==="designing"?u=x:h==="building"&&(u=Vn.building.default,w=y&&t.buildSubStatus!==x?t.buildSubStatus:void 0),e.jsx(Kd,{phaseKey:h,label:u,subStatus:w,isActive:y,showElapsed:o,startedAt:t.startedAt},h)})})}const Oa={root:"reasoning-block",toggle:"reasoning-block-toggle",elapsed:"reasoning-block-elapsed",latest:"reasoning-block-latest",full:"reasoning-block-full"};function r0(t){const s=t.split(`
55`);for(let r=s.length-1;r>=0;r--){const a=s[r].replace(/[*_`#]/g,"").trim();if(a)return a}return""}function a0(t,s){const[r,a]=n.useState(0);return n.useEffect(()=>{if(!s)return;const o=()=>a(Math.round((Date.now()-t)/1e3));o();const i=setInterval(o,1e3);return()=>clearInterval(i)},[s,t]),r}const o0=({reasoning:t,isStreaming:s,startedAt:r,chrome:a="legacy"})=>{const[o,i]=n.useState(!1),l=a0(r,s),c=n.useRef(null);if(n.useEffect(()=>{o&&s&&c.current&&(c.current.scrollTop=c.current.scrollHeight)},[o,s,t]),!t.trim())return a==="new-design"&&s?e.jsx("div",{"data-testid":Oa.root,children:e.jsx(qd,{label:"thinking...",elapsedSeconds:l,mark:e.jsx(Fd,{className:"h-[22px] w-[23px] text-[var(--product-grey-05)]"})})}):null;const x=r0(t);return a==="new-design"?s?e.jsx("div",{"data-testid":Oa.root,children:e.jsx(qd,{label:"thinking...",elapsedSeconds:l,detail:o?void 0:x,mark:e.jsx(Fd,{className:"h-[22px] w-[23px] text-[var(--product-grey-05)]"}),onToggle:()=>i(h=>!h),expanded:o,children:o?e.jsx("div",{ref:c,"data-testid":Oa.full,className:"max-h-[220px] w-full overflow-y-auto border-l pl-2 text-[10px] leading-[1.5] whitespace-pre-wrap",style:{borderColor:"var(--product-grey-02)",color:"var(--product-grey-03)"},children:t}):null})}):null:e.jsxs("div",{"data-testid":Oa.root,className:"mx-3 my-2 flex flex-col gap-0.5",children:[e.jsxs("button",{type:"button","data-testid":Oa.toggle,onClick:()=>i(h=>!h),"aria-expanded":o,className:"flex items-center gap-1.5 text-left text-[11px] text-[#737373] transition-opacity hover:opacity-70",children:[o?e.jsx(vo,{className:"h-3 w-3 shrink-0 text-[#a3a3a3]"}):e.jsx(yo,{className:"h-3 w-3 shrink-0 text-[#a3a3a3]"}),e.jsx(Nh,{className:Wt("h-3 w-3 shrink-0 text-[#a3a3a3]",s&&"animate-pulse")}),e.jsx("span",{className:"text-[#525252]",children:s?"Thinking…":"Thought process"}),s?e.jsxs("span",{"data-testid":Oa.elapsed,className:"ml-auto shrink-0 text-[10px] tabular-nums text-[#a3a3a3]",children:[l,"s"]}
55):null]}),o?e.jsx("div",{ref:c,"data-testid":Oa.full,className:"ml-[18px] max-h-[220px] overflow-y-auto whitespace-pre-wrap border-l border-[#e5e5e5] pl-2 text-[10px] leading-[1.5] text-[#a3a3a3]",children:t}):e.jsx("span",{"data-testid":Oa.latest,className:"truncate pl-[18px] text-[10px] text-[#a3a3a3]",children:x})]})};let i0=0;const Br=()=>`msg-${++i0}-${Date.now()}`;function l0(t){var s,r;return(s=t==null?void 0:t.full_name)!=null&&s.trim()?t.full_name.trim():(r=t==null?void 0:t.name)!=null&&r.trim()?t.name.trim():t!=null&&t.email?t.email.split("@")[0]:null}function c0(t){return!t||typeof t!="object"||!("system_tags"in t)?!1:t.system_tags!=null}function d0(t){return t.hasMetadataHandler&&!!t.text&&!!t.toolId&&!t.alreadyRequestedForTurn}const bc="Please sign in again to keep chatting.",u0=["Create a particle system with rainbow trails that follows the mouse","Build a rotating 3D wireframe icosahedron with Three.js","Make a fullscreen GLSL-style animated plasma wave effect","Generate an SVG animation with text orbiting along a curved path"];function p0(t){return{...t,id:t.id??Br(),images:t.images??t.image_urls??[],isStreaming:t.isStreaming??!1,toolSnapshotId:t.toolSnapshotId??t.tool_snapshot_id,isGenesisMarker:t.isGenesisMarker??t.is_genesis_marker??!1,autoFix:t.autoFix??t.auto_fix??!1}}function Zd(t){return t instanceof Error?t.message:typeof t=="string"?t:"Something went wrong."}function Vl({initialPrompt:t,initialImageUrls:s,initialReferenceFiles:r,presetBrief:a,onBeforeSend:o,onStructuredUpdate:i,onStatusChange:l,onPlanTurnActiveChange:c,onPlanQuestionsReceived:x,onPlanQuestionsPendingChange:h,onPlanPendingKindChange:y,autoFixing:u=!1,onGenerationComplete:w,ensureToolId:_,getToolUuid:v,restoredMessages:j,restoredSessionId:A,restoredModel:I,onMessagesUpdate:O,consoleErrors:L,onGeneratedMetadata:P,isAdmin:V=!1,onRevertToVersion:re,genesisSnapshotId:X,toolHasCode:je=!1,onDesignBriefUpdate:he,currentBrief:me,chatActionsRef:T,hideHeader:ee=!1,mobileBubbles:ae=!1,debugMode:ve,newDesign:ue=!1,messagesHidden:z=!1,planQuestionsHost:$=null,sharedEdges:W,onCollapse:ne,chatOverlay:F,onToggleVersions:te,versionsOpen:Le=!1}){var va,Ds,ya,ys,Cn;const{sessionId:Ke,user:oe,userId:st}=za(),{toast:rt}=df(),{notifyAgentDone:q,notifyAgentNeedsAttention:we,primeNotifications:De}=Qh(),ie=n.useRef(q),pe=n.useRef(we),J=n.useRef(De);ie.current=q,pe.current=we,J.current=De;const Ce=Zl(),se=Qc(),{mutateAsync:Ot}=pm({mutationFn:xm}),{data:U}=ed(oe==null?void 0:oe.id),mt=!!(U!=null&&U.exhausted),le=n.useRef(!1);n.useEffect(()=>{var C,Q;mt&&!le.current&&gs.capture("credits_depleted",{plan_key:U==null?void 0:U.plan_key,monthly_remaining:(C=U==null?void 0:U.credits)==null?void 0:C.monthly_remaining,daily_remaining:(Q=U==null?void 0:U.credits)==null?void 0:Q.daily_remaining,user_id:oe==null?void 0:oe.id}),le.current=mt},[mt,U,oe==null?void 0:oe.id]);const Se=!(oe!=null&&oe.id),gt=n.useMemo(()=>(L??[]).filter(C=>C.level!=="warning"),[L]),[Fe,Te]=n.useState([]),[Dt,Dn]=n.useState(""),[Ct,qt]=n.useState(!1),Jn=Fe.length===0,dn=(()=>{const C=U==null?void 0:U.action_costs;return C?Jn?je?C.remix:C.create:C.iterate:0})(),H=Xc({remaining:((va=U==null?void 0:U.credits)==null?void 0:va.remaining)??null,cost:dn,dailyRemaining:((Ds=U==null?void 0:U.credits)==null?void 0:Ds.daily_remaining)??null,monthlyRemaining:((ya=U==null?void 0:U.credits)==null?void 0:ya.monthly_remaining)??null}),be=H.blocked,xe=!!(U!=null&&U.credits)&&H.variant!==null,[Y,Ue]=n.useState(""),[ut,Ye]=n.useState(""),[bt,Sn]=n.useState(""),[Hn,xa]=n.useState([]),yr=n.useRef(!1),zr=V;n.useEffect(()=>{ip().then(C=>{if(C.length===0)return;xa(C);const Q=lp(C),Z=C.find(xt=>xt.isADDefault)??Q;Z&&Ye(Z.id);const Ae=C.find(xt=>xt.isSupervisorDefault)??Q;Ae&&Sn(Ae.id),!yr.current&&Q&&Ue(Q.id)})},[]);const{sendFileInteraction:cr}=gm(),as=bm({onFileEvent:C=>cr(_m(C))}),zs=n.useRef(as);zs.current=as;const _r=!1,[dr,Me]=n.useState(!1),{debugMode:ei,toggle:Us}=fd(V),Gs=ve??ei,[Ws,Ur]=n.useState(!1),[ur,Ge]=n.useState(""),[qs,fn]=n.useState(null),[Gr,zn]=n.useState(!1),[Ts,wn]=n.useState(null),[Ht,os]=n.useState(null),wr=n.useRef(!1),Ks=n.useRef(null),Xn=n.useRef(null),Un=n.useRef(null),Rs=(v==null?void 0:v())??null,Xt=Rs?`brik:plan-questions:${Rs}`:null,Tn=n.useCallback(C=>{if(os(C),Un.current=C,!!Xt)try{C?localStorage.setItem(Xt,C):localStorage.removeItem(Xt)}catch{}},[Xt]);n.useEffect(()=>{h==null||h(Ht!==null)},[Ht,h]),n.useEffect(()=>{if(!y)return;const C=Ht?ji(Ht):null;y(C?C.summary?"summary":"questions":null)},[Ht,y]),n.useEffect(()=>{if(!Xt){os(null);return}try{const C=localStorage.getItem(Xt),Q=C??Un.current;if(Q&&!C)try{localStorage.setItem(Xt,Q)}catch{}os(Q),localStorage.removeItem(`brik:plan-active:${Rs}`)}catch{os(null)}},[Xt,Rs]);const[fa]=n.useState(()=>{const C=new URLSearchParams(window.location.search);if(!C.has("mockPlanMode"))return null;const Q=C.get("mockPlanMode")||"1";C.delete("mockPlanMode");const Z=C.toString();return window.history.replaceState({},"",`${window.location.pathname}${Z?`?${Z}`:""}`),Q});n.useEffect(()=>{if(!V||!fa)return;const C=fa,Q=[{id:"vibe",question:"What visual vibe are you after?",options:[{label:"Minimal",description:"Clean and spare"},{label:"Playful",description:"Colorful and bouncy"}]},{id:"color",question:"Warm or cool palette?",options:[{label:"Warm"},{label:"Cool"},{label:"Neutral"}]},{id:"features",question:"Which of these should the tool include?",multiSelect:!0,options:[{label:"Upload photo",description:"Users bring their own image"},{label:"Live preview",description:"Result updates as you type"},{label:"Share link",description:"One-tap share of the result"}]},{id:"audience",question:"Who is this mainly for?",options:[{label:"Just me",description:"A personal tool"},{label:"My team",description:"Shared internally"}
55,{label:"My audience",description:"Public-facing"}]}],Z=C==="summary"?{originalRequest:"mock",transcript:"",round:2,summary:"A minimal, warm-toned photo-upload tool with a live preview."}:{originalRequest:"mock",transcript:"",round:1,questions:Q.slice(0,Math.min(Math.max(parseInt(C,10)||1,1),Q.length))};os(JSON.stringify(Z))},[V,Xt,fa]);const ma=n.useRef(0),bs=n.useRef(0),Cr=n.useRef(0),Qn=Fe.length===0,ha=wm(u0,{paused:Dt.length>0||!Qn||dr}),qr=Dt?"":Se?bc:dr?"":Qn?ha:"Describe your vision...",Mt=n.useRef(A||null),Rn=n.useRef(A||null),pr=n.useRef(null),xr=n.useRef(null),_o=n.useRef(!0),is=n.useRef(null),Ys=n.useRef(!1),jr=n.useRef(t),ls=n.useRef(s),fr=n.useRef(r),Ka=n.useRef(!1),rn=n.useRef(null),ga=n.useRef(null),Zs=n.useRef(null);n.useEffect(()=>()=>{var C,Q;(C=rn.current)==null||C.call(rn),(Q=ga.current)==null||Q.abort()},[]);const ba=n.useCallback(async()=>{var At;if(!qs||!re)return;if(Ct){fn(null),rt({title:"Revert unavailable",description:"Wait for the current response to finish, then try again."});return}const C=qs,Q=Gr;fn(null),zn(!1);const Z=Fe.findIndex(Et=>Et.toolSnapshotId===C),Ae=Z===-1&&C===X;if(Z===-1&&!Ae){console.error("[handleRevert] snapshot is not in this conversation:",C),rt({title:"Revert failed",description:"That version is no longer part of this conversation.",variant:"destructive"});return}if(!Rn.current&&v){const Et=v();if(Et)try{const Je=await D.entities.Tool.filter({uuid:Et}),Sr=(At=Je==null?void 0:Je[0])==null?void 0:At.chat_session_id;Sr&&(Rn.current=Sr)}catch{}}if(!Rn.current){console.error("[handleRevert] no chatSessionEntityId — cannot revert safely"),rt({title:"Revert failed",description:"Could not load this tool’s chat session. Please reload and try again.",variant:"destructive"});return}const xt=Ae?[]:Fe.slice(0,Z+1);try{const Et=await re({snapshotId:C,chatSessionEntityId:Rn.current});Et&&(Rn.current=Et),Te(xt),rt({title:Q?"Reverted to previous version":"Version restored",duration:3e3})}catch(Et){console.error("[handleRevert] revert failed:",Et),rt({title:"Revert failed",description:"Could not restore this version. Please try again.",variant:"destructive"})}},[qs,Gr,Fe,re,v,Ct,rt,X]);n.useEffect(()=>{O&&O(Fe)},[Fe,O]);const Js=n.useCallback(()=>{const C=xr.current;C&&(_o.current=C.scrollHeight-C.scrollTop-C.clientHeight<=80)},[]);n.useEffect(()=>{pr.current&&(!Ct||_o.current)&&pr.current.scrollIntoView({behavior:"smooth",block:"end"})},[Fe,Ct,Ht]),n.useEffect(()=>{A&&(Rn.current=A)},[A]),n.useEffect(()=>{yr.current||!I||Hn.length===0||(Hn.some(C=>C.id===I)&&Ue(I),yr.current=!0)},[I,Hn]);const wo=n.useRef(Y);n.useEffect(()=>{wo.current=Y},[Y]);const Es=n.useCallback(C=>{const Q=Rn.current;Q&&D.entities.ChatSession.update(Q,{selected_model:C}).catch(Z=>console.error("[ChatPanel] Failed to persist selected model:",Z))},[]),Co=n.useRef(!1),Is=n.useCallback(C=>{yr.current=!0,Co.current=!0,Ue(C),Es(C)},[Es]);n.useEffect(()=>{if(Ka.current||!j||j.length===0)return;Ka.current=!0;const C=j.map(p0);Te(C)},[j]),n.useEffect(()=>{const C=jr.current;if(!C||Ys.current)return;const Q=()=>{if(Ys.current)return;Ys.current=!0;const Ae=ls.current&&ls.current.length>0?ls.current:void 0,xt=fr.current&&fr.current.length>0?fr.current:void 0;Lt(C,Ae,{referenceFilesOverride:xt})};if(Hn.length>0){const Ae=window.setTimeout(Q,300);return()=>window.clearTimeout(Ae)}const Z=window.setTimeout(Q,1500);return()=>window.clearTimeout(Z)},[Hn.length]);const cs=n.useCallback(C=>{Te(Q=>[...Q,C])},[]),Qt=n.useCallback(C=>{Te(Q=>{const Z=vc(Q,xt=>xt.role==="thinking");if(Z===-1)return Q;const Ae=[...Q];return Ae[Z]={...Ae[Z],phase:C(Ae[Z].phase)},Ae})},[]);n.useEffect(()=>{if(!Ct)return;const C=setInterval(()=>{if(Cr.current===0)return;const Q=Date.now()-Cr.current;Q>3e4?Qt(Z=>Z.current==="building"?{...Z,buildSubStatus:Vn.building.slow}:Z):Q>5e3&&Qt(Z=>Z.current==="building"?{...Z,buildSubStatus:Vn.building.idle}:Z)},2e3);return()=>clearInterval(C)},[Ct,Qt]);const pt=n.useCallback(C=>{Te(Q=>{const Z=vc(Q,At=>At.role==="thinking");if(Z===-1)return Q;const Ae=[...Q],xt=Ae[Z].thinking;return xt?(Ae[Z]={...Ae[Z],thinking:{...xt,...C(xt)}},Ae):Q})},[]),Mn=n.useCallback(C=>{Te(Q=>{const Z=vc(Q,xt=>
55xt.role==="assistant"&&!!xt.isStreaming);if(Z===-1)return Q;const Ae=[...Q];return Ae[Z]={...Ae[Z],...C(Ae[Z])},Ae})},[]),Kr=n.useCallback(()=>{const C=oe==null?void 0:oe.id;if(!C)return;const Q=xf(C);se.resetQueries({queryKey:Q}),se.refetchQueries({queryKey:Q,type:"active"})},[oe==null?void 0:oe.id,se]),kr=n.useCallback(()=>{rn.current&&(rn.current(),rn.current=null,Qt(C=>({...C,current:"done",stopped:!0})))},[Qt]);n.useEffect(()=>()=>{var C;return(C=rn.current)==null?void 0:C.call(rn)},[]);const Gn=n.useRef(null),Lt=n.useCallback(async(C,Q,Z)=>{const Ae=(C||Dt).trim(),xt=(Z==null?void 0:Z.continuationIndex)??0,At=xt>0,Et=!(Z!=null&&Z.isAutoFix)&&!(Z!=null&&Z.isManualFix)&&!At?Ht??Ks.current:null;Et&&(Tn(null),Ks.current=null);const Je=(Z==null?void 0:Z.isAutoFix)??!1,Sr=(Z==null?void 0:Z.isManualFix)??!1,es=Je||Sr||At,Ne=(Z==null?void 0:Z.modelOverride)??Y;let qe=Q??[],qn=(Z==null?void 0:Z.referenceFilesOverride)??[],_s=!1;if(!Q&&!(Z!=null&&Z.referenceFilesOverride)){const _e=await vm(()=>zs.current.ensureUploaded());if(!_e)return;_s=!0,qe=_e.imageUrls,qn=_e.referenceFiles}else Q||(qe=zs.current.imageUrls),Z!=null&&Z.referenceFilesOverride||(qn=zs.current.referenceFiles);const ht={image:qe.length,video:qn.filter(_e=>_e.kind==="video").length,document:qn.filter(_e=>_e.kind==="document").length,text:qn.filter(_e=>_e.kind==="text").length},zt=ht.image+ht.video+ht.document+ht.text;if(!At&&pc({generating:Ct,exhausted:es?mt:be,text:Ae,imageCount:qe.length+qn.length,authenticated:!Se,uploading:_s?!1:zs.current.isUploading})||At&&!Ae&&qe.length+qn.length===0)return;let ws=null,Ya=!1;const Jr=_e=>{if(!d0({hasMetadataHandler:!!P,text:Ae,toolId:ws,alreadyRequestedForTurn:Ya})||!P||!ws)return;Ya=!0;const Kt=ws;(async()=>{try{const St=await D.entities.Tool.get(Kt);if(c0(St))return;const En=await Gf({prompt:Ae,designBrief:_e,imageCount:qe.length});P(En)}catch(St){console.warn("[ChatPanel] Failed to generate tool metadata:",St)}})()},en=Date.now(),ce={},We=!!(a&&!Mt.current&&!es),_a=!es&&!_r&&!a&&!!Et;wr.current=_a&&!(Z!=null&&Z.planBuildNow),c==null||c(wr.current);try{await(o==null?void 0:o())}catch(_e){console.warn("[ChatPanel] Pre-send persistence failed:",_e),c==null||c(!1),rt({variant:"destructive",title:"Could not save your latest changes",description:"Please try sending your message again."});return}const mr=Xn.current;Xn.current=null;const ts=Et?ji(Et):null,Bt={plan_mode:_a,...Z!=null&&Z.planBuildNow?{plan_build_now:!0}
55:{},...ts?{plan_round:ts.round,plan_asked_count:ts.askedCount}:{},...mr?{plan_questions_in_turn:mr.total,plan_answered:mr.answered,plan_skipped:mr.skipped}:{}},ot=typeof window<"u"&&window.matchMedia("(max-width: 1023px)").matches;ma.current=0,Cr.current=0,bs.current=Math.floor(Math.random()*3);const $e=oe,Tr=l0($e);Tr&&!Zs.current&&(Zs.current=Tr),$r({eventName:"user_prompt_submitted",properties:{prompt_length:Ae.length,has_images:ht.image>0,image_count:ht.image,has_attachments:zt>0,attachment_count:zt,video_count:ht.video,document_count:ht.document,text_count:ht.text,user_id:$e==null?void 0:$e.id,user_email:$e==null?void 0:$e.email}}),es||gs.capture("chat_message_sent",{tool_id:ws,prompt_length:Ae.length,has_images:ht.image>0,has_attachments:zt>0,attachment_count:zt,image_count:ht.image,video_count:ht.video,document_count:ht.document,text_count:ht.text,model:Y,is_first_message:!Mt.current&&Fe.length===0,...Bt}),Dn(""),zs.current.clear(),qt(!0),wn(null),l==null||l("loading"),J.current(),At||cs({id:Br(),role:"user",content:Ae,images:qe,reference_files:qn.length>0?qn:void 0,userName:Zs.current??void 0,autoFix:Je});const Qs=!Mt.current&&Fe.length===0&&!A?X?"remix":"new":"iteration",yt=Br(),wa=Date.now();cs({id:yt,role:"thinking",content:"",isDiscuss:_r,autoFix:Je,turnStartedAt:wa,phase:{current:"understanding",startedAt:wa,buildSubStatus:"",designSubStatus:"",mode:Qs},thinking:V?{currentStep:"Starting…",artDirector:null,skills:[],reasoning:"",hasReasoning:!1,toolCalls:[],turns:[],done:!1,startTime:wa,elapsed:0,requestId:Ts??void 0}:void 0});try{if(ws=await(_==null?void 0:_())??null,!ws)throw new Error("Failed to create Tool record");const _e={prompt_data:uf(Ae,ht,Bt),session_id:Ke,tool_id:ws,userId:st??($e==null?void 0:$e.id)??void 0};ir(lr.ITERATION_PROMPT,pf(_e),_e,{has_attachments:zt>0,attachment_count:zt,image_count:ht.image,video_count:ht.video,document_count:ht.document,text_count:ht.text})}catch(_e){const Kt=Sd(_e),St=Kt?bc:Zd(_e);console.error("[ChatPanel] ensureToolId failed:",_e);const En=Date.now()-en;$r({eventName:"content_creation_failed",properties:{error_type:"tool_init_error",error_message:St,prompt_length:Ae.length,has_images:qe.length>0,duration_ms:En,duration_seconds:Math.round(En/1e3),user_id:$e==null?void 0:$e.id,user_email:$e==null?void 0:$e.email}}),Qt(Kn=>({...Kn,current:"done",error:St})),V&&pt(Kn=>({done:!0,currentStep:void 0,elapsed:Math.round((Date.now()-(Kn.startTime||Date.now()))/1e3)})),cs({id:Br(),role:"assistant",content:Kt?St:`Error: Could not initialize tool session. ${St}`,isStreaming:!1}),qt(!1),l==null||l("ready");return}const Xr=(_e=!1,Kt)=>{Qt(St=>({...St,current:"done",madeChanges:_e,...Kt?{error:Kt}:{}})),V&&pt(St=>({done:!0,currentStep:void 0,elapsed:Math.round((Date.now()-(St.startTime||Date.now()))/1e3)}))};let jn=null,kt=!1,Ut=!1,hr=null,Ca=xt+1,Qr=!1,ja=null,On=null,xs=-1,Ms="";const pn=crypto.randomUUID();let Pe=null;const on=c1({clientTurnId:pn,toolUuid:(v==null?void 0:v())??void 0,model:Ne,isAutoFix:Je,isManualFix:Sr,isCompletionPass:At,isPlanMode:_a}),ea=(_e={})=>{var lt;if(kt)return;kt=!0,rn.current=null;const Kt=_e.text||"";if(_e.session_id&&(Mt.current=_e.session_id),_e.chat_session_id){const _t=Rn.current!==_e.chat_session_id;Rn.current=_e.chat_session_id,_t&&Co.current&&Es(wo.current)}const St=Kt||(Ut?"Done! I've updated the code.":"");
55if(!St){Ci({event:"chat_empty_done",requestId:Pe??pn,message:"terminal event carried no text and no code write",fields:on.snapshot({path:"empty_done",terminalType:_e.type??"unknown",structuredUpdate:_e.structured_update,codeWrittenReceived:Ut})}),It("Something interrupted that response and it didn't come through. Please resend — if it keeps happening, switch the model at the bottom of the chat.");return}const En=_e.tool_snapshot_id;if(jn)St?Mn(()=>({content:St,isStreaming:!1,...En?{toolSnapshotId:En}:{}})):Te(_t=>_t.filter(nn=>nn.id!==jn));else if(St){const _t=Br();cs({id:_t,role:"assistant",content:St,isStreaming:!1,autoFix:Je,...En?{toolSnapshotId:En}:{}})}if(_e.requires_approval&&_e.plan_questions||i==null||i(),V){pt(nn=>{var B;return((B=nn.artDirector)==null?void 0:B.status)==="running"?{artDirector:{...nn.artDirector,status:"done"}}:{}}),_e.design_brief&&pt(nn=>{var B;return(B=nn.artDirector)!=null&&B.brief?{}:{artDirector:{status:"done",brief:_e.design_brief??""}}});const _t=_e.skills_used??_e.skills??[];_t.length&&pt(nn=>{var B;return(B=nn.skills)!=null&&B.length?{}:{skills:_t}})}_e.design_brief?(he==null||he(_e.design_brief),Jr(_e.design_brief)):Jr(),Xr(Ut),Ut&&Tn(null),w==null||w({ok:!0,codeWritten:Ut,isAutoFix:Je,model:Ne}),_e.requires_approval&&_e.plan_questions?pe.current():ie.current(),qt(!1),l==null||l("ready"),_e.requires_approval&&_e.plan_questions||(lt=is.current)==null||lt.focus(),Kr();const Kn=Date.now()-en,tn=_t=>_t?_t-en:void 0;$r({eventName:"ai_generation_completed",properties:{duration_ms:Kn,duration_seconds:Math.round(Kn/1e3),prompt_length:Ae.length,has_images:qe.length>0,model:Y,ttfb_ms:tn(ce.firstByte),art_director_ms:tn(ce.artDirectorEnd),first_reasoning_ms:tn(ce.firstReasoning),first_tool_call_ms:tn(ce.firstToolCall),is_mobile:ot,used_preset_brief:We,user_id:$e==null?void 0:$e.id,user_email:$e==null?void 0:$e.email}})},It=(_e,{refreshBilling:Kt=!0}={})=>{var St;kt||(kt=!0,rn.current=null,Xr(!1,_e),i==null||i(),cs({id:Br(),role:"assistant",content:_e,isStreaming:!1}),w==null||w({ok:!1,codeWritten:Ut,isAutoFix:Je,model:Ne}),qt(!1),l==null||l("ready"),(St=is.current)==null||St.focus(),Kt&&Kr())},Ft=new AbortController;ga.current=Ft,rn.current=()=>{var _e;kt||(kt=!0,Ft.abort(),jn&&Mn(()=>({isStreaming:!1})),Xr(),w==null||w({ok:!1,codeWritten:Ut,isAutoFix:Je,model:Ne}),qt(!1),l==null||l("ready"),(_e=is.current)==null||_e.focus(),Kr())};const gr=v==null?void 0:v();if(!gr){console.error("[ChatPanel] tool UUID unavailable — cannot send message"),on.dispose(),qt(!1),l==null||l("ready");return}const Rr=async({midStreamRetries:_e,preHandshakeRetries:Kt})=>{var Kn;const St=_e+Kt,En=a1(Ft,{isCompleted:()=>kt,onTimeout:({idleMs:tn,timeoutMs:lt})=>{Ci({event:"chat_keepalive_timeout",requestId:Pe??pn,message:`no keepalive for ${tn}ms — aborting stalled stream`,fields:on.snapshot({path:"keepalive_timeout",idleMs:tn,keepaliveTimeoutMs:lt,codeWrittenReceived:Ut,serverRequestIdKnown:!!Pe})})}});try{const tn=await Ot({message:Ae,request_id:pn,bi_session_id:Ke,session_id:Mt.current??void 0,tool_uuid:gr,model:Ne||void 0,art_director_model:V&&ut||void 0,supervisor_model:zr&&bt||void 0,discuss_mode:_r||void 0,preset_brief:We?a:void 0,image_urls:qe.length>0?qe:void 0,reference_files:qn.length>0?qn:void 0,is_auto_fix:Je||void 0,is_manual_fix:Sr||void 0,continuation_index:xt||void 0,plan_mode:_a||void 0,pending_plan_questions:Et||void 0,plan_build_now:(Z==null?void 0:Z.planBuildNow)||void 0,last_event_id:xs>=0?xs:void 0,client_request_id:pn,signal:Ft.signal});Ft.signal.throwIfAborted();const lt=await fm(tn,(_t,nn)=>{if(Ft.signal.aborted)return;const B=nn;if(typeof B.seq=="number"&&(xs=B.seq),B.type&&(Ms=B.type),on.recordEvent(B.type??"",B.seq),En.beat(),B.request_id&&typeof B.request_id=="string"&&(Pe=B.request_id,wn(B.request_id),V&&pt(Re=>({...Re,requestId:B.request_id}))),B.type!=="keepalive"){if(ce.firstByte??(ce.firstByte=Date.now()),B.type==="status")Qt(Re=>Re.current==="understanding"?{...Re,startedAt:Date.now()}:Re),V&&pt(()=>({currentStep:B.text??""}));else if(B.type==="art_director_start"){if(Qt(Re=>Re.current==="building"||Re.current==="done"?Re:{...Re,current:"designing",startedAt:Re.current!=="designing"?Date.now():Re.startedAt,designSubStatus:Vn.designing.artRunning}),V){const Re={status:"running",brief:""};pt(et=>({artDirector:Re,turns:Pa(et.turns||[],"artDirector",{artDirector:Re})}))}}else if(B.type==="art_director_delta")V&&pt(Re=>{var $t;const et={status:"running",brief:((($t=Re.artDirector)==null?void 0:$t.brief)||"")+(B.delta||"")};return{artDirector:et,turns:Pa(Re.turns||[],"artDirector",{artDirector:et})}});else if(B.type==="design_brief"){ce.artDirectorEnd??(ce.artDirectorEnd=Date.now());const Re=B.brief??"";if(Qt(et=>et.current==="designing"?{...et,designSubStatus:Vn.designing.artDone}:et),B.unchanged||he==null||he(Re),B.updated&&Ge(B.previous_brief??""),Jr(Re),
55V){const et={status:B.preset?"skipped":"done",brief:Re,...B.updated?{updated:!0,previousBrief:B.previous_brief??""}:{},...B.reconcile?{reconcile:B.reconcile}:{}};pt($t=>{var Yt;return{artDirector:et,turns:Pa($t.turns||[],"artDirector",{artDirector:et}),...(Yt=B.skills)!=null&&Yt.length?{skills:B.skills}:{}}})}}else if(B.type==="skills")ce.artDirectorEnd??(ce.artDirectorEnd=Date.now()),Jr(),V&&pt(()=>({skills:B.skills||[]}));else if(B.type==="skills_debug")V&&pt(()=>({skillsDebug:{matches:B.matches??[],contextChars:B.contextChars??0,conceptTags:B.conceptTags??"",assembledPrompt:B.assembledPrompt??""}}));else if(B.type==="reasoning_start"){ce.firstReasoning??(ce.firstReasoning=Date.now());const Re=Ni(B.agent);pt(et=>({hasReasoning:!0,reasoningStartedAt:et.reasoningStartedAt??Date.now(),...V?{turns:Pa(et.turns||[],Re,{})}:{}}))}else if(B.type==="reasoning"){const Re=Ni(B.agent);pt(et=>({reasoning:(et.reasoning||"")+(B.text||""),reasoningStartedAt:et.reasoningStartedAt??Date.now(),...V?{turns:Pa(et.turns||[],Re,{reasoningDelta:B.text||""})}:{}}))}else if(B.type==="art_director_consulted")Qt(Re=>({...Re,current:"building",startedAt:Re.current!=="building"?Date.now():Re.startedAt,buildSubStatus:Vn.designing.artRunning})),V&&pt(()=>({currentStep:Vn.designing.artRunning}));else if(B.type==="tool_call"){const Re=B.name??"unknown_tool",et=Re.startsWith("agent-");if(!et){ce.firstToolCall??(ce.firstToolCall=Date.now()),Re==="set_canvas_code"&&ma.current++,Cr.current=Date.now();const $t=X1(Re,ma.current>1);Qt(Yt=>({...Yt,current:"building",startedAt:Yt.current!=="building"?Date.now():Yt.startedAt,buildSubStatus:$t}))}if(V){const $t=Ni(B.agent),Yt={name:Re,args:B.args||{},result:""};pt(Zt=>({toolCalls:et?Zt.toolCalls:[...Zt.toolCalls||[],Yt],turns:Pa(Zt.turns||[],$t,{toolCall:Yt}),...et?{currentStep:Re==="agent-artDirector"?"Delegating to Art Director…":Re==="agent-coder"?"Delegating to Coder…":`Delegating (${Re})…`}:{}}))}}else if(B.type==="tool_result"){if(V){const Re=Ni(B.agent),et=(B.name??"").startsWith("agent-");pt($t=>{const Yt=[...$t.toolCalls||[]];return!et&&Yt.length&&(Yt[Yt.length-1]={...Yt[Yt.length-1],result:B.result||""}),{toolCalls:et?$t.toolCalls:Yt,turns:Pa($t.turns||[],Re,{toolResult:B.result||""})}})}}else if(B.type==="text"){if(!B.text)return;if(jn?Mn(()=>({content:B.text})):(jn=Br(),cs({id:jn,role:"assistant",content:B.text,isStreaming:!0,autoFix:Je})),V){const Re=Ni(B.agent);pt(et=>{var Zt;const $t=(Zt=et.turns)==null?void 0:Zt[et.turns.length-1],Yt=typeof B.delta=="string"&&B.delta.length>0?B.delta:($t==null?void 0:$t.agent)===Re&&$t.reply?"":B.text||"";return Yt?{turns:Pa(et.turns||[],Re,{replyDelta:Yt})}:{}})}}else if(B.type==="code_written")Ut=!0;else if(B.type==="needs_completion")hr=typeof B.plan=="string"?B.plan:"",Qr=!!B.is_correction,ja=typeof B.stalled_model=="string"?B.stalled_model:null,typeof B.continuation=="number"&&(Ca=B.continuation),B.session_id&&(Mt.current=B.session_id),B.chat_session_id&&(Rn.current=B.chat_session_id);else if(B.type!=="phase"){if(B.type==="done"||B.type==="result")B.requires_approval&&B.plan_questions&&(On=B.plan_questions),ea({text:B.text||"",session_id:B.session_id,chat_session_id:B.chat_session_id,structured_update:B.structured_update,tool_snapshot_id:B.tool_snapshot_id,design_brief:B.design_brief,skills_used:B.skills_used,requires_approval:B.requires_approval,plan_questions:B.plan_questions});else if(B.type==="error"){const Re=Date.now()-en;$r({eventName:"content_creation_failed",properties:{error_type:"agent_stream_error",error_category:B.category||"unknown",error_phase:B.phase||"unknown",error_message:B.error||"Agent execution failed",model:Y,duration_ms:Re,duration_seconds:Math.round(Re/1e3),user_id:$e==null?void 0:$e.id,user_email:$e==null?void 0:$e.email}});let et="Something interrupted that response and it didn't come through. Please resend — if it keeps happening, switch the model at the bottom of the chat.";B.category==="model_rate_limit"?et="⚠️ The AI is overloaded right now and couldn't respond. Wait a few seconds and resend — or switch the model at the bottom of the chat (Gemini 3 Flash is a reliable fallback).":B.category==="model_context_exceeded"?et="This tool has gotten large enough that the current model ran out of room. Try a smaller, more specific request — or switch to a larger-context model at the bottom of the chat.":B.category==="max_steps_exhausted"||B.category==="empty_no_output"?et="I couldn't quite finish that edit. Try breaking it into a smaller, more specific change.":B.category==="model_timeout"?et="That took too long and timed out. Try again, or make the change smaller.":B.category==="quota_exceeded"&&(et=B.error||"You don't have enough credits left for this generation."),It(et)}}}},{signal:Ft.signal,requestId:pn});if(Ft.signal.throwIfAborted(),On!==null&&(Tn(On),x==null||x()),!kt)if(hr!=null&&hr.trim()&&(Qr||Ca<=mm)){kt=!0,rn.current=null,jn&&Mn(()=>({isStreaming:!1})),Xr(!1);const _t=hr,nn=ja===Ne?hm:void 0;(Kn=Gn.current)==null||Kn.call(Gn,_t,void 0,{continuationIndex:Ca,modelOverride:nn})}else if(Ut)i==null||i(),ea({text:"Generation completed.",structured_update:!0});else if(hr!==null)Ci({event:"chat_empty_done",requestId:Pe??pn,message:"needs_completion plan was blank",fields:on.snapshot({path:"empty_completion_plan"})}),It("Something interrupted that response and it didn't come through. Please resend — if it keeps happening, switch the model at the bottom of the chat.");else{const _t=Date.now()-en;if(console.error("[ChatPanel] connection_lost: stream closed without terminal event",{requestId:Pe??pn,lastEvent:Ms,lastSeq:xs,duration_ms:_t,model:Ne,retryAttempt:St}),Ci({event:"chat_stream_drop",requestId:Pe??pn,message:"SSE closed with 
55no terminal event",fields:on.snapshot({path:"mid_stream_drop",codeWrittenReceived:Ut,serverRequestIdKnown:!!Pe,endReason:lt==null?void 0:lt.endReason,bytesReceived:lt==null?void 0:lt.bytesReceived,chunkCount:lt==null?void 0:lt.chunkCount,parsedEventCount:lt==null?void 0:lt.eventCount,parseErrorCount:lt==null?void 0:lt.parseErrorCount,trailingBufferLen:lt==null?void 0:lt.trailingBufferLen,trailingBufferSample:lt==null?void 0:lt.trailingBufferSample,retryAttempt:St})}),_e<e1&&!Ft.signal.aborted)return jn&&(Te(nn=>nn.filter(B=>B.id!==jn)),jn=null),En.clear(),"retry_mid_stream";$r({eventName:"content_creation_failed",properties:{error_type:"connection_lost",error_message:"Stream closed with no terminal event",prompt_length:Ae.length,has_images:qe.length>0,model:Y,duration_ms:_t,duration_seconds:Math.round(_t/1e3),last_seq:xs,last_event:Ms,user_id:$e==null?void 0:$e.id,user_email:$e==null?void 0:$e.email}}),It("Connection lost. Please try again.")}return En.clear(),on.dispose(),"done"}catch(tn){if(En.clear(),um(tn)||Ft.signal.aborted)return on.dispose(),r1(Ft.signal)&&(console.error("[ChatPanel] connection_lost: keepalive timeout",{requestId:Pe??pn,lastEvent:Ms,lastSeq:xs,duration_ms:Date.now()-en,model:Ne}),It("Connection lost. Please check your internet connection and try again.",{refreshBilling:!0})),"aborted";const lt=Sd(tn),_t=lt?bc:Zd(tn);console.error("[ChatPanel] agentChat error:",_t,tn);const nn=Date.now()-en,B=/load failed|failed to fetch|network/i.test(_t),Re=B?"Connection lost. Please check your internet connection and try again.":_t;return Ci({event:B?"chat_fetch_error":"chat_request_error",requestId:Pe??pn,message:_t.slice(0,200),fields:on.snapshot({path:B?"fetch_error":"agent_error",codeWrittenReceived:Ut,serverRequestIdKnown:!!Pe,errorName:tn instanceof Error?tn.name:typeof tn,errorMessage:_t.slice(0,300),httpStatus:ff(tn),isAuthError:lt})}),B&&!Pe&&!lt&&Kt<t1?"retry_pre_handshake":(on.dispose(),$r({eventName:"content_creation_failed",properties:{error_type:B?"connection_lost":"agent_error",error_message:_t,prompt_length:Ae.length,has_images:qe.length>0,model:Y,duration_ms:nn,duration_seconds:Math.round(nn/1e3),last_seq:xs,last_event:Ms,user_id:$e==null?void 0:$e.id,user_email:$e==null?void 0:$e.email}}),It(Re,{refreshBilling:!lt}),"done")}};try{await o1(Rr,{sseAbort:Ft,onBeforeRetry(){Ms="",Pe=null}})}finally{on.dispose(),ga.current===Ft&&(ga.current=null)}},[Dt,Ct,be,mt,Ot,cs,Qt,pt,Mn,o,i,l,c,x,w,_,v,Y,Es,ut,bt,zr,_r,P,he,Fe.length,A,V,oe,Se,Kr,Ke,st,X,a,Ht,Tn,Ts,rt]);n.useEffect(()=>{Gn.current=Lt},[Lt]),n.useEffect(()=>{if(T)return T.current={sendMessage:(C,Q)=>Lt(C,void 0,Q),attachHealth:C=>pt(()=>({health:C})),setSelectedModel:Is,focusComposer:()=>{var C;return(C=is.current)==null?void 0:C.focus()}},()=>{T.current&&(T.current=null)}},[T,Lt,pt,Is]);const An=C=>{if(C.key==="Enter"&&!C.shiftKey){if(C.preventDefault(),pc({generating:Ct,exhausted:be,text:Dt,imageCount:as.readyCount,authenticated:!Se,uploading:as.isUploading}))return;Lt()}},vs=ue?m1:T1,ds=Fe.length===0?120:96,Wn=n.useCallback(()=>{const C=is.current;C&&(C.style.height="auto",C.style.height=`${Math.min(C.scrollHeight,ds)}px`)},[ds]);n.useLayoutEffect(()=>{Wn()},[Dt,ha,Fe.length,dr,ds,Wn]);const mn=pc({generating:Ct,exhausted:be,text:Dt,imageCount:as.readyCount,authenticated:!Se,uploading:as.isUploading}),Rt=ym({exhausted:be,imageCount:as.readyCount,authenticated:!Se,uploading:as.isUploading}),Xs=`flex flex-col justify-between items-stretch w-full min-w-0 h-full shrink-0 px-[15px] pt-0 pb-[15px] my-0 mx-0 transition-[background-color] duration-300 ${ee?"":"rounded-[10px] border border-[#e1e1e1]"}`,jt=Fe.filter(C=>C.role==="assistant"&&C.toolSnapshotId&&!C.autoFix),Pn=jt[jt.length-1],us=jt[jt.length-2],un=V?e.jsxs(e.Fragment,{children:[e.jsx(go,{content:"Admin: show current design brief",children:e.jsx("button",{type:"button",onClick:()=>{Ce("chat_panel_toggle_brief"),Ur(C=>!C)},className:"flex h-[24px] items-center rounded-[4px] px-[6px] text-[10px] tracking-[-0.2px] transition-colors hover:bg-[var(--product-grey-01)]",style:{color:Ws?"var(--product-black-00)":"var(--product-grey-05)"},children:"Brief"})}),e.jsx(go,{content:"Admin: toggle debug view",children:e.jsx("button",{type:"button",onClick:()=>{Ce(Gs?"chat_panel_disable_debug":"chat_panel_enable_debug"),Us()},className:"flex h-[24px] items-center rounded-[4px] px-[6px] text-[10px] tracking-[-0.2px] transition-colors hover:bg-[var(--product-grey-01)]",style:{color:Gs?"var(--product-black-00)":"var(--product-grey-05)"},children:Gs?"Debug on":"Debug"})})]}):void 0,ps=Ht&&!Ct?ji(Ht):null,an=(ys=[...Fe].reverse().find(C=>C.role==="assistant"&&!C.isGenesisMarker))==null?void 0:ys.id,Nr=ps?e.jsx(fc,{questions:ps.questions,summary:ps.summary,disabled:be,chrome:ue?"new-design":"legacy",onAnswer:(C,Q)=>{Xn.current=Q,Lt(C)},onBuild:()=>
55{Ce("chat_panel_plan_build_it"),Tn(null),Lt("Build it",void 0,{planBuildNow:!0})},onKeepPlanning:()=>{Ce("chat_panel_plan_keep_planning"),Ks.current=Ht,Tn(null),cs({id:Br(),role:"assistant",content:"What else would you like to add or change?",isStreaming:!1})}},Ht):null,hn=C=>{var Q,Z,Ae,xt;if(C.autoFix)return V?C.role==="user"?Gs?e.jsx(S1,{content:C.content},C.id):null:C.role!=="assistant"?null:e.jsxs("div",{className:"flex items-center gap-2 mx-3 my-2 text-[11px] text-[#737373]",children:[C.isStreaming?e.jsx(In,{className:"w-3 h-3 animate-spin"}):e.jsx("span",{"aria-hidden":!0,children:"⟳"}),e.jsxs("span",{children:["Auto-fix",C.isStreaming?"ing":"ed"," console issues"]})]},C.id):null;if(C.role==="user")return ue?e.jsx(qp,{content:C.content,images:C.images,referenceFiles:C.reference_files},C.id):e.jsx(P1,{content:C.content,images:C.images,referenceFiles:C.reference_files,userName:C.userName,mobile:ae},C.id);if(C.role==="thinking"&&C.phase){const At=C.phase.current==="done",Et=((Q=C.thinking)==null?void 0:Q.reasoningStartedAt)??((Z=C.thinking)==null?void 0:Z.startTime)??C.turnStartedAt??C.phase.startedAt,Je=(Ae=C.thinking)!=null&&Ae.reasoning||ue&&!At?e.jsx(o0,{reasoning:((xt=C.thinking)==null?void 0:xt.reasoning)??"",isStreaming:!At,startedAt:Et,chrome:ue?"new-design":"legacy"}):null;return C.isDiscuss?At?null:e.jsxs("div",{children:[Je,ue?null:e.jsxs("div",{className:"flex items-center gap-2 mx-3 my-2 text-[11px] text-[#737373]",children:[e.jsx(In,{className:"w-3 h-3 animate-spin"}),e.jsx("span",{children:"Thinking…"})]})]},C.id):V&&Gs&&C.thinking?e.jsx(Z1,{block:C.thinking},C.id):e.jsxs("div",{children:[Je,e.jsx(s0,{phase:C.phase,copyVariantIndex:bs.current,chrome:ue?"new-design":"legacy",showElapsed:Je==null})]},C.id)}if(C.role==="assistant"){if(C.isGenesisMarker)return null;let At="none",Et;if(re&&!Ct){const Je=C.toolSnapshotId&&C.id===(Pn==null?void 0:Pn.id);Je&&jt.length>=2&&us?(At="undo",Et=()=>{zn(!0),fn(us.toolSnapshotId)}):Je&&jt.length===1&&X?(At="undo",Et=()=>{zn(!0),fn(X)}):C.toolSnapshotId&&!Je&&(At="revert",Et=()=>{zn(!1),fn(C.toolSnapshotId)})}return e.jsxs(mf.Fragment,{children:[ue?e.jsx(Wp,{content:C.content,isStreaming:C.isStreaming,buttonMode:At,onRevert:Et}):e.jsx(N1,{content:C.content,isStreaming:C.isStreaming,buttonMode:At,onRevert:Et,mobile:ae}),V&&Gs&&C.request_id&&e.jsxs("div",{className:"mx-3 -mt-1 mb-2 inline-flex w-fit items-center gap-1.5 rounded bg-gray-50 border border-gray-200 px-1.5 py-0.5 text-[10px]",children:[e.jsx("span",{className:"text-gray-600",children:"Request ID:"}),e.jsxs("a",{href:`https://brikapp.grafana.net/d/brik-errors-drilldown/brik-error-drill-down?orgId=1&from=now-7d&to=now&timezone=browser&var-datasource=grafanacloud-logs&var-env=production&var-interval=5m&var-requestId=${C.request_id}&var-function=$__all&refresh=1m`,target:"_blank",rel:"noopener noreferrer",className:"font-mono text-blue-600 hover:text-blue-800 underline",title:"View logs in Grafana",children:[C.request_id.slice(0,8),"..."]}),e.jsx("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(C.request_id)},className:"text-gray-500 hover:text-gray-700",title:"Copy request ID",children:e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),e.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]})]},C.id)}return null},gn=()=>{Ce("chat_panel_fix_with_ai");const C=gt.map((Q,Z)=>`${Z+1}. ${Q.message}${Q.line?` (line ${Q.line})`:""}`).join(`
56`);Lt(`Fix these console errors from the preview:
57
58${C}`,void 0,{isManualFix:!0})},Yr=gt.length>0&&!Ct&&!u?ue?e.jsx(fp,{tone:"error",message:`${gt.length} console error${gt.length!==1?"s":""} detected in preview`,action:{label:"Fix with AI",onClick:gn,disabled:mt||Se}}):e.jsx(R1,{errors:gt,disabled:mt||Se,onFix:gn}):null,Zr=ue?e.jsx(g1,{open:!!qs,onOpenChange:C=>!C&&fn(null),onConfirm:ba}):e.jsx(Dm,{open:!!qs,onClose:()=>fn(null),onConfirm:ba,title:"Revert to this version?",description:"This will restore the tool code from this point. All messages after this will be permanently deleted. This cannot be undone.",confirmLabel:"Revert & Delete",destructive:!0,confirmClassName:"bg-gradient-to-b from-[#FF4447] to-[#FF59F1] text-white hover:opacity-90 shadow-[inset_0px_1px_4px_#ffd9e8]"});return ue?e.jsxs(C1,{sharedEdges:W,messagesHidden:z,messages:Fe,renderMessage:hn,working:Ct,header:ee?void 0:{title:"Chat",extraActions:un,onToggleHistory:te,historyOpen:Le,onCollapse:ne},scrollRef:xr,onScroll:Js,bottomRef:pr,overlay:e.jsxs(e.Fragment,{children:[(()=>{if(!Ht||Ct)return null;const C=ji(Ht);if(!C)return null;const Q=e.jsx("div",{children:e.jsx(fc,{questions:C.questions,summary:C.summary,disabled:be,chrome:"new-design",onAnswer:(Z,Ae)=>{Xn.current=Ae,Lt(Z)},onBuild:()=>
58{Ce("chat_panel_plan_build_it"),Tn(null),Lt("Build it",void 0,{planBuildNow:!0})},onKeepPlanning:()=>{Ce("chat_panel_plan_keep_planning"),Ks.current=Ht,Tn(null),cs({id:Br(),role:"assistant",content:"What else would you like to add or change?",isStreaming:!1})}},Ht)});return $&&!C.summary?Ko.createPortal(Q,$):e.jsx("div",{className:"absolute inset-x-0 bottom-0 z-10",children:Q})})(),F]}),afterMessages:$&&!(ps!=null&&ps.summary)||ue&&an?null:Nr,belowMessages:e.jsxs(e.Fragment,{children:[(U==null?void 0:U.credits)&&e.jsx(xd,{chrome:"new-design",planKey:U.plan_key,cost:dn,remaining:U.credits.remaining,dailyRemaining:U.credits.daily_remaining,monthlyRemaining:U.credits.monthly_remaining,dailyResetAt:((Cn=U.resets)==null?void 0:Cn.daily_reset_at)??null,dailyLimit:U.credits.daily_limit,monthlyLimit:U.credits.monthly_limit}),Yr]}),composer:e.jsx(vs,{creditBannerVisible:xe,billingSummary:U,nextActionCost:dn,input:Dt,setInput:Dn,handleKeyDown:An,syncTextareaHeight:Wn,setComposerFocused:Me,inputRef:is,displayPlaceholder:qr,messages:Fe,mobileBubbles:ae,composerMaxHeightPx:ds,isCreditExhausted:be,chatAuthBlocked:Se,attach:as,sendFileInteraction:cr,sendToolEditorAction:Ce,availableModels:Hn,selectedModel:Y,setSelectedModel:Ue,isAdmin:V,showSupervisorPicker:zr,selectedSupervisorModel:bt,setSelectedSupervisorModel:Sn,selectedArtDirectorModel:ut,setSelectedArtDirectorModel:Ye,handleModelChange:Is,generating:Ct,stopGeneration:kr,sendBlocked:mn,sendBlockedReason:Rt,sendMessage:Lt}),children:[V&&e.jsx(Hd,{open:Ws,brief:me??"",previousBrief:ur,onClose:()=>Ur(!1)}),Zr]}):e.jsxs("div",{className:Xs,style:{background:"rgba(255, 255, 255, 1)"},children:[V&&e.jsx(Hd,{open:Ws,brief:me??"",previousBrief:ur,onClose:()=>Ur(!1)}),e.jsxs("div",{className:"flex flex-col flex-1 min-h-0 w-full",children:[!ee&&e.jsx(A1,{isAdmin:V,briefWindowOpen:Ws,onToggleBrief:()=>{Ce("chat_panel_toggle_brief"),Ur(C=>!C)},debugMode:Gs,onToggleDebug:()=>{Ce(Gs?"chat_panel_disable_debug":"chat_panel_enable_debug"),Us()},onToggleVersions:te,versionsOpen:Le,onCollapse:ne}),e.jsxs(E1,{scrollContainerRef:xr,onScroll:Js,bottomRef:pr,overlay:F,newDesign:ue,children:[Fe.length===0&&!Ct&&e.jsx(O1,{onSuggestion:C=>{var Q;Dn(C),(Q=is.current)==null||Q.focus()}}),Fe.map(hn),(()=>{if(!Ht||Ct)return null;const C=ji(Ht);return C?e.jsx(fc,{questions:C.questions,summary:C.summary,disabled:be,onAnswer:(Q,Z)=>{Xn.current=Z,Lt(Q)},onBuild:()=>{Ce("chat_panel_plan_build_it"),Tn(null),Lt("Build it",void 0,{planBuildNow:!0})},onKeepPlanning:()=>{Ce("chat_panel_plan_keep_planning"),Ks.current=Ht,Tn(null),cs({id:Br(),role:"assistant",content:"What else would you like to add or change?",isStreaming:!1})}},Ht):null})()]}),Yr,e.jsx(vs,{creditBannerVisible:xe,billingSummary:U,nextActionCost:dn,input:Dt,setInput:Dn,handleKeyDown:An,syncTextareaHeight:Wn,setComposerFocused:Me,inputRef:is,displayPlaceholder:qr,messages:Fe,mobileBubbles:ae,composerMaxHeightPx:ds,isCreditExhausted:be,chatAuthBlocked:Se,attach:as,sendFileInteraction:cr,sendToolEditorAction:Ce,availableModels:Hn,selectedModel:Y,setSelectedModel:Ue,isAdmin:V,showSupervisorPicker:zr,selectedSupervisorModel:bt,setSelectedSupervisorModel:Sn,selectedArtDirectorModel:ut,setSelectedArtDirectorModel:Ye,handleModelChange:Is,generating:Ct,stopGeneration:kr,sendBlocked:mn,sendBlockedReason:Rt,sendMessage:Lt})]}),Zr]})}function vc(t,s){for(let r=t.length-1;r>=0;r--)if(s(t[r]))return r;return-1}function ex({x:t,y:s,onClose:r}){const a=n.useRef(null),[o,i]=n.useState({x:t,y:s});return n.useLayoutEffect(()=>{const l=a.current;if(!l)return;const c=l.getBoundingClientRect(),x=Math.min(t,Math.max(0,window.innerWidth-c.width-4)),h=Math.min(s,Math.max(0,window.innerHeight-c.height-4));i({x,y:h})},[t,s]),n.useEffect(()=>{var l;(l=a.current)==null||l.focus()},[]),n.useEffect(()=>{function l(x){const h=a.current;h&&!h.contains(x.target)&&r()}function c(x){x.key==="Escape"&&(x.stopPropagation(),r())}return document.addEventListener("mousedown",l,!0),document.addEventListener("keydown",c,!0),window.addEventListener("blur",r),()=>{document.removeEventListener("mousedown",l,!0),document.removeEventListener("keydown",c,!0),window.removeEventListener("blur",r)}},[r]),{ref:a,pos:o}}function Si({icon:t,label:s,onClick:r}){return e.jsxs("button",{type:"button",onClick:r,className:"flex w-full items-center gap-[8px] px-[10px] py-[6px] text-left text-[12px] text-black hover:bg-[#f0f0f0] tracking-[-0.24px]",children:[e.jsx("span",{className:"flex h-[14px] w-[14px] items-center justify-center text-[#525252]",children:t}),e.jsx("span",{children:s})]})}const x0=({x:t,y:s,controlKind:r,isHidden:a=!1,disableHideDelete:o=!1,onClose:i,onSelect:l})=>{const{ref:c,pos:x}=ex({x:t,y:s,onClose:i}),h=r==="slider";return Ko.createPortal(e.jsxs("div",{ref:c,role:"menu",tabIndex:-1,style:{position:"fixed",top:x.y,left:x.x,zIndex:9999,outline:"none"},className:"min-w-[180px] rounded-[8px] border border-[#e1e1e1] bg-white py-[4px] shadow-[0_8px_24px_rgba(0,0,0,0.12)]",children:[h&&e.jsx(Si,{icon:e.jsx(Bp,{className:"h-[12px] w-[12px]"}),label:"Edit range",onClick:()=>l("edit-range")}),e.jsx(Si,{icon:e.jsx(vp,{className:"h-[12px] w-[12px]"}),label:"Animate this control…",onClick:()=>l("animate")}),e.jsx(Si,{icon:e.jsx(kl,{className:"h-[12px] w-[12px]"}),label:"Rename",onClick:()=>l("rename")}
58),!o&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"my-[4px] border-t border-[#e1e1e1]"}),e.jsx(Si,{icon:a?e.jsx(Pl,{className:"h-[12px] w-[12px]"}):e.jsx(yp,{className:"h-[12px] w-[12px]"}),label:a?"Show control":"Hide control",onClick:()=>l("hide")}),e.jsx(Si,{icon:e.jsx(_p,{className:"h-[12px] w-[12px] text-red-500"}),label:"Delete control",onClick:()=>l("delete")})]})]}),document.body)};function Ti({icon:t,label:s,onClick:r,destructive:a}){return e.jsxs("button",{type:"button",role:"menuitem",onClick:r,className:Wt(Tm,a&&"text-[var(--product-red-03)]"),children:[e.jsx("span",{className:Sm,children:t}),e.jsx(jp,{className:Dl,children:s})]})}const f0=({x:t,y:s,controlKind:r,isHidden:a=!1,disableHideDelete:o=!1,onClose:i,onSelect:l})=>{const{ref:c,pos:x}=ex({x:t,y:s,onClose:i}),h=y=>()=>l(y);return Ko.createPortal(e.jsxs("div",{ref:c,role:"menu",tabIndex:-1,"aria-label":"Control actions",style:{position:"fixed",top:x.y,left:x.x,zIndex:9999,outline:"none"},className:Wt(ad,"w-[171px]"),children:[r==="slider"&&e.jsx(Ti,{icon:e.jsx(Lm,{className:"size-[12px]"}),label:"Edit range",onClick:h("edit-range")}),e.jsx(Ti,{icon:e.jsx(Bm,{className:"size-[13px]"}),label:"Animate this control…",onClick:h("animate")}),e.jsx(Ti,{icon:e.jsx(Yl,{className:"size-[15px]"}),label:"Rename",onClick:h("rename")}),!o&&e.jsxs(e.Fragment,{children:[e.jsx(Vs,{className:"my-[4px]"}),e.jsx(Ti,{icon:a?e.jsx(wp,{className:"size-[12px]"}):e.jsx(yp,{className:"size-[12px]",strokeWidth:2}),label:a?"Show control":"Hide control",onClick:h("hide")}),e.jsx(Ti,{icon:e.jsx(id,{className:"size-[12px]"}),label:"Delete control",onClick:h("delete"),destructive:!0})]})]}),document.body)};function tx({menu:t,onClose:s,onEditRange:r,onRename:a,onSendMessage:o,onHide:i,onDelete:l,disableHideDelete:c,chrome:x="v1"}){if(!t)return null;const h=x==="v2"?f0:x0;return e.jsx(h,{x:t.x,y:t.y,controlKind:t.kind,isHidden:t.visible===!1,disableHideDelete:c,onClose:s,onSelect:y=>{if(s(),y==="edit-range"&&t.kind==="slider")r(t.key);else if(y==="rename")a(t.key,t.label);else if(y==="hide")i==null||i(t.key);else if(y==="delete")l==null||l(t.key);else if(y==="animate"){const u=t.label||t.key;o([`Add an animation system for the "${u}" control (type: ${t.kind}, key: ${t.key}).`,"","Decide what is appropriate based on the control type and what the control represents:",`- For booleans/toggles: a single "Animate ${u}" toggle may be enough.`,"- For scalar sliders: add controls for the animation range (min + max within the existing range) plus a speed control.","- For position/size or anything with multiple axes (x/y, width/height): consider an axis selector (X / Y / Both), per-axis min/max, and a shared speed.","- For colors/palettes: a cycle/loop toggle plus a speed control may suffice.","",`Keep the original "${u}" control. Add the new controls in addition to it. Wire it so when the animation toggle is on, the original control value is driven by the animation; when off, the user controls it manually.`,"Choose sensible defaults for the new controls and pick reasonable keys/labels."].join(`
59`))}}})}const m0=({open:t,initialLabel:s,onClose:r,onSave:a})=>{const[o,i]=n.useState(s);n.useEffect(()=>{t&&i(s)},[t,s]);const l=o.trim().length>0;function c(){l&&a(o.trim())}return e.jsx(la,{open:t,onOpenChange:x=>x?null:r(),children:e.jsxs(ca,{className:"max-w-[380px]",children:[e.jsx(ju,{children:e.jsxs(da,{className:"flex items-center gap-2 text-[14px]",children:[e.jsx(kl,{className:"h-4 w-4"}),"Rename control"]})}
59),e.jsx("input",{autoFocus:!0,type:"text",value:o,onChange:x=>i(x.target.value),onKeyDown:x=>{x.key==="Enter"&&l&&c()},className:"w-full h-[36px] rounded-[6px] border border-[#d4d4d4] bg-white px-[10px] text-[12px] text-black outline-none focus:border-[#000] tracking-[-0.24px]"}),e.jsxs(ku,{children:[e.jsx("button",{type:"button",onClick:r,className:"h-[32px] rounded-[6px] border border-[#d4d4d4] bg-white px-[12px] text-[12px] font-medium text-black hover:bg-[#f5f5f5]",children:"Cancel"}),e.jsx("button",{type:"button",onClick:c,disabled:!l,className:"h-[32px] rounded-[6px] bg-black px-[12px] text-[12px] font-medium text-white hover:bg-[#262626] disabled:opacity-40 disabled:cursor-not-allowed",children:"Save"})]})]})})},nx={renameControl:{root:"rename-control-dialog-v2",close:"rename-control-dialog-v2-close",input:"rename-control-dialog-v2-input",cancel:"rename-control-dialog-v2-cancel",save:"rename-control-dialog-v2-save"},sliderRange:{root:"slider-range-dialog-v2",close:"slider-range-dialog-v2-close",min:"slider-range-dialog-v2-min",max:"slider-range-dialog-v2-max",error:"slider-range-dialog-v2-error",cancel:"slider-range-dialog-v2-cancel",save:"slider-range-dialog-v2-save"}},Ri=nx.renameControl,h0=({open:t,initialLabel:s,onClose:r,onSave:a})=>{const[o,i]=n.useState(s);n.useEffect(()=>{t&&i(s)},[t,s]);const l=o.trim().length>0,c=()=>{l&&a(o.trim())};return e.jsxs(Ki,{open:t,onOpenChange:x=>!x&&r(),"data-testid":Ri.root,children:[e.jsx(Xo,{title:"Rename control",close:e.jsx(vr,{"data-testid":Ri.close,children:e.jsx(Zn,{className:"size-[15px] shrink-0"})})}),e.jsxs($s,{className:"flex-col gap-[6px]",children:[e.jsx("span",{className:"text-[12px] leading-[1.3] tracking-[-0.12px] text-[var(--product-grey-04)]",children:"Control name"}),e.jsx(ld,{size:"lg",value:o,onChange:i,placeholder:"Control name",autoFocus:!0,"data-testid":Ri.input,"aria-label":"Control name",onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),c())}})]}),e.jsx(Vs,{}),e.jsxs(bo,{children:[e.jsx(vr,{asChild:!0,children:e.jsxs(Nn,{size:"big",skin:"standard",priority:"secondary",className:"min-w-0 flex-1 border-0","data-testid":Ri.cancel,children:[e.jsx(Zn,{className:"size-[15px] shrink-0"}),e.jsx("span",{className:"whitespace-nowrap",children:"Cancel"})]})}),e.jsxs(Nn,{size:"big",skin:"standard",priority:"primary",className:"min-w-0 flex-1 border-0",disabled:!l,"data-testid":Ri.save,onClick:c,children:[e.jsx(hp,{className:"size-[15px] shrink-0"}),e.jsx("span",{className:"whitespace-nowrap",children:"Save"})]})]})]})};function sx({renameTarget:t,schema:s,onClose:r,onSave:a,chrome:o="v1"}){if(!t)return null;const i=s.find(c=>c.key===t.key);if(!i)return null;const l=o==="v2"?h0:m0;return e.jsx(l,{open:!0,initialLabel:i.label||i.key||"",onClose:r,onSave:c=>a(t.key,c)})}const Jd="w-full h-[32px] rounded-[6px] border border-[#d4d4d4] bg-white px-[10px] text-[12px] text-black outline-none focus:border-[#000] tracking-[-0.24px]",g0=({open:t,controlLabel:s,initial:r,onClose:a,onSave:o})=>{const[i,l]=n.useState(String(r.min)),[c,x]=n.useState(String(r.max));n.useEffect(()=>{t&&(l(String(r.min)),x(String(r.max)))},[t,r.min,r.max]);const h=Number(i),y=Number(c),u=Number.isFinite(h)&&Number.isFinite(y)&&y>h;function w(){u&&o({min:h,max:y})}return e.jsx(la,{open:t,onOpenChange:_=>_?null:a(),children:e.jsxs(ca,{className:"max-w-[380px]",children:[e.jsx(ju,{children:e.jsxs(da,{className:"flex items-center gap-2 text-[14px]",children:[e.jsx(Bp,{className:"h-4 w-4"}),"Edit slider range"]})}),e.jsx("div",{className:"text-[11px] text-[#737373] tracking-[-0.22px] -mt-2",children:s}),e.jsxs("div",{className:"grid grid-cols-2 gap-[10px]",children:[e.jsxs("label",{className:"flex flex-col gap-[4px]",children:[e.jsx("span",{className:"text-[11px] text-[#525252] tracking-[-0.22px]",children:"Min"}),e.jsx("input",{type:"number",value:i,onChange:_=>l(_.target.value),className:Jd})]}),e.jsxs("label",{className:"flex flex-col gap-[4px]",children:[e.jsx("span",{className:"text-[11px] text-[#525252] tracking-[-0.22px]",children:"Max"}),e.jsx("input",{type:"number",value:c,onChange:_=>x(_.target.value),className:Jd})]})]}),!u&&e.jsx("div",{className:"text-[11px] text-red-600 tracking-[-0.22px]",children:"Max must be greater than min."}),e.jsxs(ku,{children:[e.jsx("button",{type:"button",onClick:a,className:"h-[32px] rounded-[6px] border border-[#d4d4d4] bg-white px-[12px] text-[12px] font-medium text-black hover:bg-[#f5f5f5]",children:"Cancel"}),e.jsx("button",{type:"button",onClick:w,disabled:!u,className:"h-[32px] rounded-[6px] bg-black px-[12px] text-[12px] font-medium text-white hover:bg-[#262626] disabled:opacity-40 disabled:cursor-not-allowed",children:"Save"})]})]})})},co=nx.sliderRange,b0=({open:t,controlLabel:s,initial:r,onClose:a,onSave:o})=>{const[i,l]=n.useState(String(r.min)),[c,x]=n.useState(String(r.max));n.useEffect(()=>{t&&(l(String(r.min)),x(String(r.max)))},[t,r.min,r.max]);const h=Number(i),y=Number(c),u=i.trim()!==""&&c.trim()!==""&&Number.isFinite(h)&&Number.isFinite(y)&&y>h,w=()=>{u&&o({min:h,max:y})},_=v=>{v.key==="Enter"&&(v.preventDefault(),w())};return e.jsxs(Ki,{open:t,onOpenChange:v=>!v&&a(),"data-testid":co.root,children:[e.jsx(Xo,{title:"Edit slider range",subt
59itle:s,close:e.jsx(vr,{"data-testid":co.close,children:e.jsx(Zn,{className:"size-[15px] shrink-0"})})}),e.jsxs($s,{className:"flex-col gap-[12px]",children:[e.jsx("div",{className:"flex gap-[12px]",children:[["Min",i,l,co.min],["Max",c,x,co.max]].map(([v,j,A,I])=>e.jsxs("label",{className:"flex min-w-0 flex-1 flex-col gap-[6px]",children:[e.jsx("span",{className:"text-[12px] leading-[1.3] tracking-[-0.12px] text-[var(--product-grey-04)]",children:v}),e.jsx(ld,{size:"md",value:j,onChange:A,inputMode:"decimal",placeholder:v,autoFocus:v==="Min","data-testid":I,"aria-label":v,"aria-invalid":!u,onKeyDown:_})]},v))}),e.jsx("span",{"data-testid":co.error,role:u?void 0:"alert",className:"min-h-[14px] text-[11px] leading-[1.2] tracking-[-0.22px] text-[var(--product-red-03)]",children:u?"":"Max must be greater than min."})]}),e.jsx(Vs,{}),e.jsxs(bo,{children:[e.jsx(vr,{asChild:!0,children:e.jsxs(Nn,{size:"big",skin:"standard",priority:"secondary",className:"min-w-0 flex-1 border-0","data-testid":co.cancel,children:[e.jsx(Zn,{className:"size-[15px] shrink-0"}),e.jsx("span",{className:"whitespace-nowrap",children:"Cancel"})]})}),e.jsxs(Nn,{size:"big",skin:"standard",priority:"primary",className:"min-w-0 flex-1 border-0",disabled:!u,"data-testid":co.save,onClick:w,children:[e.jsx(hp,{className:"size-[15px] shrink-0"}),e.jsx("span",{className:"whitespace-nowrap",children:"Save"})]})]})]})};function rx({editingKey:t,schema:s,onClose:r,onSave:a,chrome:o="v1"}){if(!t)return null;const i=s.find(c=>c.key===t);if(!i||i.type!=="slider")return null;const l=o==="v2"?b0:g0;return e.jsx(l,{open:!0,controlLabel:i.label||i.key||"Slider",initial:{min:Number(i.min??0),max:Number(i.max??100)},onClose:r,onSave:c=>a(t,c)})}function v0({toolId:t}){const{isAnonymous:s,loading:r,sessionId:a,userId:o}=za(),i=n.useRef(!1),l=n.useRef(!1),c=!r&&!s,x=n.useCallback(()=>{if(!c||i.current)return;i.current=!0;const u={userId:o,session_id:a,tool_id:t??void 0};ir(lr.ONBOARDING_SURVEY_STARTED,hf(u),u)},[c,o,a,t]),h=n.useCallback((u,w)=>{if(!c)return;const _={userId:o,session_id:a,tool_id:t??void 0,question:u,answer:w}
59;ir(lr.ONBOARDING_SURVEY_ANSWERED,gf(_),_)},[c,o,a,t]),y=n.useCallback((u,w)=>{if(!c||l.current)return;l.current=!0;const _={userId:o,session_id:a,tool_id:t??void 0,onboarding_data:Nu({version:"v1",answers:u}),completion_type:w};ir(lr.ONBOARDING_SURVEY_COMPLETED,bf(_),_);const v=Object.fromEntries(u.map(j=>[j.question,j.answer]));gs.setPersonProperties({survey_role:v.role,survey_intent:v.intent,survey_context:v.context})},[c,o,a,t]);return{logStarted:x,logAnswered:h,logCompleted:y}}function Zi(){const[t,s]=n.useState(0);return n.useEffect(()=>{const r=window.visualViewport;if(!r)return;const a=()=>{const o=Math.max(0,window.innerHeight-r.height-r.offsetTop);s(o),o===0&&window.scrollY!==0&&window.scrollTo(0,0)};return a(),r.addEventListener("resize",a),r.addEventListener("scroll",a),()=>{r.removeEventListener("resize",a),r.removeEventListener("scroll",a)}},[]),t}const Pt={root:"onboarding-survey-root",introTitle:"onboarding-survey-intro-title",introStart:"onboarding-survey-intro-start",introSkip:"onboarding-survey-intro-skip",closingTitle:"onboarding-survey-closing-title",closingDismiss:"onboarding-survey-closing-dismiss",answerChip:t=>`onboarding-survey-answer-chip-${t}`,counter:"onboarding-survey-counter",prevButton:"onboarding-survey-prev-button",nextButton:"onboarding-survey-next-button",questionTitle:"onboarding-survey-question-title",option:(t,s)=>`onboarding-survey-option-${t}-${s}`,freeTextInput:"onboarding-survey-free-text-input",freeTextSubmit:"onboarding-survey-free-text-submit",questionSkip:"onboarding-survey-question-skip",questionNext:"onboarding-survey-question-next"},Xd="var(--product-grey-01)",Ei="var(--product-grey-02)",Lr=[{key:"role",q:"I'm a…",options:[{id:"designer",emo:"🎨",label:"Designer"},{id:"developer",emo:"💻",label:"Developer"},{id:"marketer",emo:"📣",label:"Marketer"},{id:"founder",emo:"🚀",label:"Founder"},{id:"other",emo:"✦",label:"Something else…",escape:!0}]},{key:"intent",q:"I'm here to make…",options:[{id:"social",emo:"📱",label:"Social media content"},{id:"web",emo:"🖥️",label:"Websites and product visuals"},{id:"brand",emo:"✨",label:"Brand and campaign assets"},{id:"motion",emo:"🎬",label:"Motion and animation"},{id:"explore",emo:"🧪",label:"Just exploring",escape:!0},{id:"other",emo:"✦",label:"Something else…",escape:!0}]},{key:"context",q:"I work…",options:[{id:"agency",emo:"🏢",label:"At an agency or studio"},{id:"freelance",emo:"💼",label:"Freelance, with clients"},{id:"inhouse",emo:"🧩",label:"In-house at a company"},{id:"ownbrand",emo:"🌱",label:"On my own brand"},{id:"fun",emo:"🎈",label:"For fun"},{id:"other",emo:"✦",label:"Something else…",escape:!0}]}];function Qd({checked:t}){return e.jsx("span",{className:"flex size-[14px] shrink-0 items-center justify-center rounded-full border border-solid",style:{background:"var(--product-white-00)",borderColor:"var(--product-grey-03)"},children:t&&e.jsx("span",{className:"size-[6px] rounded-full",style:{background:"var(--product-black-00)"}})})}function y0(t){const s=t.filter(a=>!a.escape),r=t.filter(a=>a.escape);for(let a=s.length-1;a>0;a--){const o=Math.floor(Math.random()*(a+1));[s[a],s[o]]=[s[o],s[a]]}return[...s,...r]}const ax=({generationStatus:t,onDismiss:s,toolId:r,standalone:a=!1,bottomBarHeight:o=0,progressRef:i,chrome:l="legacy",planQuestionPending:c=!1})=>{const x=n.useMemo(()=>Lr.map(H=>({...H,options:y0(H.options)})),[]),{logStarted:h,logAnswered:y,logCompleted:u}=v0({toolId:r}),w=Zi(),_=n.useRef(null),v=n.useRef(null),[j,A]=n.useState(0);n.useEffect(()=>{var xe;if(!a)return;const H=(xe=v.current)==null?void 0:xe.offsetParent;if(!H)return;const be=window.innerHeight-H.getBoundingClientRect().bottom;A(w>0?w-be:-(be-o))},[w,a,o]);const I=(i==null?void 0:i.current)??null,[O,L]=n.useState((I==null?void 0:I.introDone)??!1),[P,V]=n.useState((I==null?void 0:I.showClosing)??!1),[re,X]=n.useState(!1),je=n.useRef(null),he=n.useRef(!1),me=n.useRef(t==="loading"),[T,ee]=n.useState((I==null?void 0:I.answers)??{}),[ae,ve]=n.useState((I==null?void 0:I.skips)??{}),ue=n.useRef((I==null?void 0:I.answers)??{}),z=n.useRef((I==null?void 0:I.skips)??{}),[$,W]=n.useState((I==null?void 0:I.activeIndex)??0),[ne,F]=n.useState(""),[te,Le]=n.useState(!1),[Ke,oe]=n.useState(null),[st,rt]=n.useState(null),[q,we]=n.useState(!1),De=n.useRef(null),ie=n.useRef(Date.now());n.useEffect(()=>
59{i&&(i.current={introDone:O,showClosing:P,answers:T,skips:ae,activeIndex:$})},[i,O,P,T,ae,$]),n.useEffect(()=>{var H;!a||!te||w===0||(H=_.current)==null||H.scrollIntoView({block:"nearest"})},[a,te,w,j]);const pe=()=>Lr.map(H=>{var xe;const be=ue.current[H.key];return be?{question:H.key,answer:be.id==="other"?((xe=be.note)==null?void 0:xe.trim())||"other":be.id}:{question:H.key,answer:z.current[H.key]?"skipped":"not_reached"}}),J=n.useCallback(H=>{he.current||(he.current=!0,u(pe(),H),X(!0),je.current=setTimeout(s,300))},[u,s]);n.useEffect(()=>{h()},[h]),n.useEffect(()=>{if(l==="new-design")return;const H=me.current;if(me.current=t==="loading",t==="loading")return;if(P){H&&J("finished");return}const be=window.setTimeout(()=>J("auto_dismissed"),1800);return()=>window.clearTimeout(be)},[l,t,P,J]),n.useEffect(()=>{if(l==="new-design"||!P)return;const H=window.setTimeout(()=>J("recap_timeout"),7e3);return()=>window.clearTimeout(H)},[l,P,J]),n.useEffect(()=>{ie.current=Date.now()},[O,P,$,T,ae,ne,Ke]),n.useEffect(()=>{if(l!=="new-design"||!c)return;const H=15e4;let be;const xe=()=>{const Y=Date.now()-ie.current;if(Y>=H){J("plan_question");return}be=setTimeout(xe,H-Y)};return xe(),()=>clearTimeout(be)},[l,c,J]),n.useEffect(()=>()=>{window.clearTimeout(De.current??void 0),window.clearTimeout(je.current??void 0)},[]);const Ce=()=>J("closed"),se=x[$],Ot=Lr.length,U=$===Ot-1,mt=Ke!==null&&!(Ke==="other"&&ne.trim().length===0);n.useEffect(()=>{var H;oe(((H=ue.current[se==null?void 0:se.key])==null?void 0:H.id)??null)},[se]);const le=Lr.flatMap(H=>{var Y;const be=T[H.key];if(!be)return[];const xe=H.options.find(Ue=>Ue.id===be.id);return xe?[{key:H.key,emo:xe.emo,label:((Y=be.note)==null?void 0:Y.trim())||xe.label}]:[]}),Se=(H,be)=>{ue.current=H,z.current=be,ee(H),ve(be)},gt=(H,be,xe)=>
59{var Ye;const Y=bt=>H[bt]!==void 0||!!be[bt];if(Lr.every(bt=>Y(bt.key))){Lr.some(bt=>H[bt.key]!==void 0)?V(!0):J("finished");return}const ut=Lr.map((bt,Sn)=>(xe+1+Sn)%Ot).find(bt=>!Y(Lr[bt].key));ut!==void 0&&(W(ut),F(((Ye=H[Lr[ut].key])==null?void 0:Ye.note)??""))},Fe=(H,be)=>{Se(H,be),F(""),gt(H,be,$)},Te=H=>{if(st)return;const be={...ae};delete be[se.key];const xe={...T,[se.key]:{id:H.id}},Y=$;y(se.key,H.id),Se(xe,be),rt(H.id),De.current=setTimeout(()=>{rt(null),F(""),gt(xe,be,Y)},750)},Dt=()=>{const H=ne.trim(),be={...ae};delete be[se.key],y(se.key,H||"other"),Fe({...T,[se.key]:{id:"other",...H?{note:H}:{}}},be)},Dn=()=>{if(Ke===null)return;if(Ke==="other"){Dt();return}const H=se.options.find(xe=>xe.id===Ke);if(!H)return;const be={...ae};delete be[se.key],y(se.key,H.id),Fe({...T,[se.key]:{id:H.id}},be)},Ct=()=>{const H={...T};delete H[se.key],y(se.key,"skipped"),Fe(H,{...ae,[se.key]:!0})},qt=()=>{st||q||(we(!0),De.current=setTimeout(()=>{we(!1),Ct()},750))},Jn=H=>{var be;W(H),F(((be=T[Lr[H].key])==null?void 0:be.note)??"")},dn="flex size-[26px] flex-none items-center justify-center rounded-[5px] text-black transition-colors hover:bg-[#fef0fd] disabled:opacity-30 disabled:hover:bg-transparent focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-[#fe71f2]";return e.jsx("div",{ref:v,"data-testid":Pt.root,role:"group","aria-label":"Personalize Brik",className:Wt("absolute inset-x-0 z-20 flex max-h-full flex-col overflow-hidden font-sans transition-[box-shadow] duration-200 ease-out",l==="new-design"?void 0:"rounded-t-[12px]",a?void 0:l==="new-design"?"bottom-0":"bottom-[-18px]",l==="new-design"?void 0:re?"shadow-[0_-8px_24px_rgba(255,234,253,0)]":"shadow-[0_-8px_24px_rgba(255,234,253,0.33)]"),style:a?{bottom:j,maxHeight:`calc(100% - ${Math.max(0,j)}px)`}:void 0,children:e.jsx("div",{className:Wt("flex min-h-0 max-h-full flex-col overflow-auto text-black transition-transform duration-300 ease-in",l==="new-design"?"gap-[20px] px-[12px] pt-[12px]":"gap-[10px] rounded-t-[12px] border-x border-t border-[#e1e1e1] bg-white p-[10px] pb-[20px]",re?"translate-y-full":"animate-in slide-in-from-bottom-4 fade-in duration-300"),style:l==="new-design"?{background:Xd,borderTop:`1px solid ${Ei}`,paddingBottom:P||!O?"28px":"12px"}:void 0,children:l==="new-design"?e.jsx(e.Fragment,{children:P?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("p",{"data-testid":Pt.closingTitle,className:"text-product-title",style:{color:"var(--product-black-00)",fontFamily:"var(--product-font)"},children:"That’s it, thanks!"}),e.jsx("button",{type:"button","data-testid":Pt.closingDismiss,onClick:Ce,"aria-label":"Dismiss",className:"flex size-[24px] flex-none items-center justify-center transition-colors hover:bg-[var(--product-grey-02)]",style:{color:"var(--product-black-00)"},children:e.jsx(Zn,{className:"size-[15px]"})})]}),e.jsx("p",{className:"w-full text-[11px] leading-[1.2] tracking-[-0.22px]",style:{color:"var(--product-black-00)",fontFamily:"var(--product-font)"},children:"Your tool is almost ready."}),e.jsx("div",{className:"flex w-full flex-wrap items-start gap-[6px]",children:le.map(H=>e.jsx("span",{"data-testid":Pt.answerChip(H.key),className:"flex items-center border border-solid px-[6px] py-[3px] text-[11px] tracking-[-0.22px]",style:{borderColor:"var(--product-black-00)",color:"var(--product-black-00)",fontFamily:"var(--product-font)"},children:H.label},H.key))})]}):O?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsx("p",{"data-testid":Pt.questionTitle,className:"text-product-title",style:{color:"var(--product-black-00)",fontFamily:"var(--product-font)"},children:se.q}),e.jsxs("span",{"data-testid":Pt.counter,className:"text-product-tiny",style:{color:"var(--product-grey-05)"},children:[$+1,"/",Ot]})]}),e.jsx("div",{className:"flex w-full flex-col",children:se.options.map(H=>{const be=Ke===H.id;if(H.id==="other"){const xe=ne.trim().length>0;return e.jsxs("div",{className:"flex min-h-[40px] w-full flex-col items-start justify-center gap-[8px] border-t border-solid p-[8px]",style:{borderColor:Ei},children:[e.jsxs("button",{type:"button","data-testid":Pt.option(se.key,H.id),onClick:()=>{oe("other"),window.setTimeout(()=>{var Y;
59return(Y=_.current)==null?void 0:Y.focus()},0)},disabled:q,className:"flex w-full items-center gap-[15px] text-start disabled:cursor-not-allowed",children:[e.jsx(Qd,{checked:be}),e.jsx("span",{className:"min-w-0 flex-1 text-product-text",style:{color:"var(--product-grey-05)"},children:"Something else..."})]}),be&&e.jsx("input",{ref:_,type:"text","data-testid":Pt.freeTextInput,value:ne,onChange:Y=>F(Y.target.value),onFocus:()=>{Le(!0),window.setTimeout(()=>{var Y;return(Y=_.current)==null?void 0:Y.scrollIntoView({block:"center"})},300)},onBlur:()=>Le(!1),onKeyDown:Y=>{Y.key==="Enter"&&xe&&Dt()},placeholder:"Type your own...","aria-label":"Something else — tell us in a few words",className:"w-full min-w-0 border border-solid px-[8px] py-[4px] text-product-text outline-none",style:{fontFamily:"var(--product-font)",borderColor:Ei,background:"var(--product-white-00)",color:"var(--product-black-00)"}})]},H.id)}return e.jsxs("button",{type:"button","data-testid":Pt.option(se.key,H.id),onClick:()=>oe(H.id),disabled:q,className:"flex min-h-[40px] w-full items-center gap-[15px] border-t border-solid p-[8px] text-start disabled:cursor-not-allowed",style:{borderColor:Ei},children:[e.jsx(Qd,{checked:be}),e.jsx("span",{className:"min-w-0 flex-1 text-product-text",style:{color:"var(--product-black-00)"},children:H.label})]},H.id)})}),e.jsxs("div",{className:"flex w-full items-center justify-end gap-[8px]",children:[e.jsx("button",{type:"button","data-testid":Pt.questionSkip,onClick:qt,disabled:q,className:"flex shrink-0 items-center justify-center px-[8px] py-[4px] text-product-text capitalize transition-colors disabled:cursor-not-allowed",style:{background:"var(--product-grey-02)",color:"var(--product-black-00)"},children:"skip"}),e.jsxs("button",{type:"button","data-testid":Pt.questionNext,onClick:Dn,disabled:!mt||q,className:"flex shrink-0 items-center justify-center gap-[8px] px-[8px] py-[4px] transition-colors disabled:cursor-not-allowed",style:mt?{background:"var(--product-black-00)",border:"1px solid var(--product-black-00)",color:"var(--product-white-00)"}:{background:Xd,border:`1px solid ${Ei}`,color:"var(--product-grey-03)"},children:[e.jsx("span",{className:"text-product-text capitalize",children:U?"done":"next"}),e.jsx(Md,{className:"size-[15px] shrink-0"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex w-full flex-col gap-[8px]",children:[e.jsx("p",{"data-testid":Pt.introTitle,className:"text-product-title",style:{color:"var(--product-black-00)",fontFamily:"var(--product-font)"},children:"While Brik builds…"}),e.jsx("p",{className:"w-full text-[11px] leading-[1.2] tracking-[-0.22px]",style:{color:"var(--product-black-00)",fontFamily:"var(--product-font)"},children:"Answer 3 quick questions while your tool is loading to make Brik tailored to you. One tap each, skip anything."})]}),e.jsxs("div",{className:"flex w-full items-start gap-[6px]",children:[e.jsxs("button",{type:"button","data-testid":Pt.introStart,onClick:()=>L(!0),className:"flex flex-1 items-center justify-center gap-[8px] px-[8px] py-[4px] transition-opacity hover:opacity-90",style:{background:"var(--product-black-00)",color:"var(--product-white-00)"},children:[e.jsx("span",{className:"text-product-text capitalize",children:"let’s go"}),e.jsx(Md,{className:"size-[15px]"})]}),e.jsx("button",{type:"button","data-testid":Pt.introSkip,onClick:()=>J("closed"),className:"flex flex-none items-center justify-center px-[8px] py-[4px] transition-colors hover:opacity-80",style:{background:"var(--product-grey-02)",color:"var(--product-black-00)"},children:e.jsx("span",{className:"text-product-text capitalize",children:"skip"})})]})]})}):P?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button","data-testid":Pt.closingDismiss,onClick:Ce,"aria-label":"Dismiss",className:"-mb-[4px] flex size-[26px] flex-none items-center justify-center self-end rounded-[5px] text-black transition-colors hover:bg-[#fef0fd] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-[#fe71f2]",children:e.jsx(Hr,{className:"h-[14px] w-[14px]",strokeWidth:1.5})}),e.jsx("div",{className:"flex w-full items-center justify-center px-[8px]",children:e.jsx("div",{className:"flex min-w-px flex-1 flex-col items-center gap-[4px]",children:e.jsx("div",{className:"flex w-full items-center",children:e.jsx("h2",{"data-testid":Pt.closingTitle,className:"min-w-px flex-1 text-[12px] font-medium tracking-[-0.24px] text-black",children:"That’s it, thanks!"})})})}),e.jsxs("div",{className:"flex w-full flex-col pb-[10px]",children:[e.jsx("div",{className:"flex flex-col pb-[12px] pl-[8px] pr-[14px] text-black",children:e.jsx("p",{className:"text-[12px] leading-[1.4] tracking-[-0.24px]",children:"Your tool is almost ready."})}),e.jsx("div",{className:"flex w-full flex-wrap content-center items-center gap-[8px] p-[8px]",children:le.map(H=>e.jsxs("div",{"data-testid":Pt.answerChip(H.key),className:"flex items-center gap-[6px] rounded-[18px] border border-[#ffeafd] px-[16px] py-[8px] text-[10px] leading-[1.4] tracking-[-0.24px] text-black",children:[e.jsx("span",{"aria-hidden":!0,
59children:H.emo}),e.jsx("span",{children:H.label})]},H.key))})]})]}):O?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex w-full items-center justify-center",children:e.jsxs("div",{className:"flex w-full max-w-full flex-col items-center gap-[4px] lg:w-[275px]",children:[e.jsxs("span",{"data-testid":Pt.counter,className:"text-[8px] tracking-[-0.16px] text-[#888]",children:[$+1,"/",Ot]}),e.jsxs("div",{className:"flex w-full items-center justify-between gap-[12px]",children:[e.jsx("button",{type:"button","data-testid":Pt.prevButton,onClick:()=>Jn(Math.max(0,$-1)),disabled:$===0,"aria-label":"Previous question",className:dn,children:e.jsx(Km,{className:"h-[14px] w-[14px]",strokeWidth:1.5})}),e.jsx("h2",{"data-testid":Pt.questionTitle,className:"flex-1 text-center text-[12px] font-medium tracking-[-0.24px] text-black",children:se.q}),e.jsx("button",{type:"button","data-testid":Pt.nextButton,onClick:()=>Jn(Math.min(Ot-1,$+1)),disabled:$===Ot-1,"aria-label":"Next question",className:dn,children:e.jsx(Ad,{className:"h-[14px] w-[14px]",strokeWidth:1.5})})]})]})}),e.jsx("div",{className:"flex w-full flex-col",children:se.options.map((H,be)=>{var Ue;const xe=be+1,Y=((Ue=T[se.key])==null?void 0:Ue.id)===H.id;if(H.id==="other"){const ut=ne.trim().length>0;return e.jsxs("div",{className:Wt("flex w-full items-center gap-[12px] rounded-[10px] p-[8px] transition-colors",(te||ut)&&"bg-[rgba(255,234,253,0.33)]"),children:[e.jsx("span",{"aria-hidden":!0,className:"flex size-[28px] flex-none items-center justify-center rounded-[8px] border border-[#ffeafd] text-black",children:e.jsx(Ih,{className:"h-[15px] w-[15px]",strokeWidth:1.5})}),e.jsx("input",{ref:_,type:"text","data-testid":Pt.freeTextInput,value:ne,onChange:Ye=>F(Ye.target.value),onFocus:()=>{Le(!0),window.setTimeout(()=>{var Ye;return(Ye=_.current)==null?void 0:Ye.scrollIntoView({block:"center"})},300)},onBlur:()=>Le(!1),onKeyDown:Ye=>{Ye.key==="Enter"&&ut&&Dt()},placeholder:"Something else…","aria-label":"Something else — tell us in a few words",className:"min-w-0 flex-1 border-0 bg-transparent p-0 text-[12px] tracking-[-0.24px] text-black placeholder:text-[#686868] focus-visible:outline-none"}),ut?e.jsx("button",{type:"button","data-testid":Pt.freeTextSubmit,onClick:Dt,"aria-label":"Send",className:"flex flex-none items-center justify-center rounded-[5px] bg-[#ff8ef4] p-[8px] text-white transition-colors hover:bg-[#fe71f2]",children:e.jsx(Ad,{className:"h-[10px] w-[10px]",strokeWidth:2})}):e.jsx("button",{type:"button","data-testid":Pt.freeTextSubmit,onClick:qt,className:Wt("flex flex-none items-center justify-center rounded-[5px] border border-[#ffeafd] px-[16px] py-[8px] text-[10px] font-medium tracking-[-0.24px] transition-colors",q?"bg-[#ffeafd] text-[#454545]":"bg-transparent text-[#6e6e6e] hover:bg-[#ffeafd]"),children:"Skip"})]},H.id)}return e.jsxs("button",{type:"button","data-testid":Pt.option(se.key,H.id),onClick:()=>Te(H),className:Wt("flex w-full items-center gap-[12px] rounded-[10px] pl-[8px] pr-[14px] py-[12px] text-left transition-colors hover:bg-[rgba(255,234,253,0.33)]",Y&&"bg-[#fff5fe] hover:bg-[#fff5fe]"),children:[e.jsx("span",{"aria-hidden":!0,className:Wt("flex size-[28px] flex-none items-center justify-center rounded-[8px] border text-[12px] tracking-[-0.24px] transition-colors",Y?"border-[#ffd6fc] bg-[#ffd6fc] text-black":"border-[#ffeafd] text-black"),children:xe}),e.jsxs("span",{className:"flex items-center gap-[6px] text-[12px] leading-[1.4] tracking-[-0.24px] text-black",children:[e.jsx("span",{"aria-hidden":!0,children:H.emo}),e.jsx("span",{children:H.label})]})]},H.id)})})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex w-full items-center justify-center px-[8px]",children:e.jsxs("div",{className:"flex min-w-px flex-1 flex-col items-center gap-[4px]",children:[e.jsx("div",{"aria-hidden":!0,className:"h-[10px] w-[12px]"}),e.jsx("div",{className:"flex w-full items-center",children:e.jsx("h2",{"data-testid":Pt.introTitle,className:"min-w-px flex-1 text-[12px] font-medium tracking-[-0.24px] text-black",children:"While Brik builds…"})})]})}),e.jsxs("div",{className:"flex w-full flex-col pb-[10px] pt-[10px]",children:[e.jsx("div",{className:"flex flex-col pb-[12px] pl-[8px] pr-[14px] text-black",children:e.jsx("p",{className:"text-[12px] leading-[1.4] tracking-[-0.24px]",children:"Answer 3 quick questions while your tool is loading to make Brik tailored to you. One tap each, skip anything."})}),e.jsxs("div",{className:"flex w-full items-center gap-[12px] p-[8px]",children:[e.jsx("button",{type:"button","data-testid":Pt.introStart,onClick:()=>L(!0),className:"flex h-[32px] flex-1 items-center justify-center rounded-[5px] bg-[linear-gradient(171deg,#ff4447_21%,#ff59f1_79%)] px-[15px] text-[10px] font-medium tracking-[-0.24px] text-white transition-opacity hover:opacity-90",children:"Let’s Go"}),e.jsx("button",{type:"button","data-testid":Pt.introSkip,onClick:()=>J("closed"),className:"flex h-[32px] flex-none items-center justify-center rounded-[5px] border border-[#ffeafd] px-[16px] text-[10px] font-medium tracking-[-0.24px] text-[#6e6e6e] transition-colors hover:bg-[#ffeafd]",children:"Skip"})]})]})]})})})},Vi=200,Va=40,rs={saveChangesButton:"publish-panel-save-changes-button",nameInput:"publish-panel-name-input",descriptionInput:"publish-panel-description-input",tagInput:"publish-panel-tag-input",addTagButton:"publish-panel-add-tag-button",visibilityDescription:"publish-panel-visibility-description",visibilityToggle:"publish-panel-visibility-toggle",screenshotCoverButton:"publish-panel-screenshot-cover-button",recordCoverButton:"publish-panel-record-cover-button",staticCoverInput:"publish-panel-static-cover-input",dynamicCoverInput:"publish-panel-dynamic-cover-input",removeStaticCoverButton:"publish-panel-remove-static-cover-button",removeDynamicCoverButton:"publish-panel-remove-dynamic-cover-button",presetsSection:"publish-panel-presets",presetCard:"publish-panel-preset-card",presetThumbnail:"publish-panel-preset-thumbnail"};function _0({className:t}){return e.jsx("svg",{width:12,height:12,viewBox:"0 0 13.1 13.1",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:e.jsx("path",{d:"M6.55 0.55C8.05077 2.19301 8.90365 4.32522 8.95 6.55C8.90365 8.77478 8.05077 10.907 6.55 12.55M6.55 0.55C5.04923 2.19301 4.19635 4.32522 4.15 6.55C4.19635 8.77478 5.04923 10.907 6.55 12.55M6.55 0.55C3.23629 0.55 0.55 3.23629 0.55 6.55C0.55 9.86371 3.23629 12.55 6.55 12.55M6.55 0.55C9.86371 0.55 12.55 3.23629 12.55 6.55C12.55 9.86371 9.86371 12.55 6.55 12.55M0.850012 4.75H12.25M0.85 8.35H12.25",stroke:"currentColor",strokeWidth:1.1,strokeLinecap:"round",strokeLinejoin:"round"})})}function w0({className:t}){return e.jsx("svg",{width:13,height:13,viewBox:"0 0 13.1 13.1",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":"true",children:e.jsx("path",{d:"M1.02492e-07 9.68789V4.67812C1.02492e-07 4.18634 -0.000236817 3.78427 0.0263673 3.45839C0.
590535219 3.12604 0.11129 2.82419 0.254883 2.54238C0.47915 2.10231 0.837256 1.74415 1.27734 1.51992C1.559 1.3765 1.86025 1.31855 2.19238 1.2914C2.51825 1.26478 2.92033 1.26503 3.41211 1.26503H5.91699C6.22059 1.26503 6.46654 1.5113 6.4668 1.81484C6.4668 2.11859 6.22075 2.36562 5.91699 2.36562H3.41211C2.90226 2.36562 2.55291 2.36597 2.28223 2.38808C2.0179 2.40968 1.87727 2.44897 1.77637 2.50039C1.54322 2.61919 1.35415 2.80923 1.23535 3.04238C1.18401 3.14322 1.14366 3.28331 1.12207 3.54726C1.09995 3.81801 1.09961 4.16804 1.09961 4.67812V9.68789C1.09961 10.1977 1.09996 10.5471 1.12207 10.8178C1.14367 11.0821 1.18394 11.2227 1.23535 11.3236C1.35416 11.5567 1.54328 11.7469 1.77637 11.8656C1.87726 11.917 2.01805 11.9563 2.28223 11.9779C2.5529 12 2.90229 12.0004 3.41211 12.0004H8.42188C8.93196 12.0004 9.28198 12 9.55273 11.9779C9.81634 11.9564 9.9568 11.9169 10.0576 11.8656V11.8646C10.2908 11.7458 10.4808 11.5568 10.5996 11.3236C10.651 11.2227 10.6903 11.0821 10.7119 10.8178C10.734 10.5471 10.7344 10.1977 10.7344 9.68789V7.183C10.7344 6.87925 10.9814 6.6332 11.2852 6.6332C11.5887 6.63345 11.835 6.8794 11.835 7.183V9.68789C11.835 10.1797 11.8352 10.5817 11.8086 10.9076C11.7814 11.2397 11.7235 11.541 11.5801 11.8227C11.3558 12.2627 10.9977 12.6208 10.5576 12.8451C10.2758 12.9887 9.97396 13.0465 9.6416 13.0736C9.31572 13.1002 8.91365 13.1 8.42188 13.1H3.41211C2.92033 13.1 2.51825 13.1003 2.19238 13.0736C1.86019 13.0465 1.55904 12.9886 1.27734 12.8451C0.837206 12.6209 0.479145 12.2628 0.254883 11.8227C0.111399 11.541 0.0535214 11.2398 0.0263673 10.9076C-0.00025674 10.5817 -8.73665e-08 10.1797 1.02492e-07 9.68789ZM10.001 0.531635C10.7098 -0.177211 11.8595 -0.177212 12.5684 0.531635C13.2772 1.24048 13.2772 2.39017 12.5684 3.09902L6.86523 8.80214C6.67755 8.98982 6.52266 9.14937 6.33398 9.26503C6.17805 9.36059 6.0079 9.43133 5.83008 9.47402C5.61484 9.52569 5.39242 9.52187 5.12695 9.52187H4.12793C3.8243 9.52179 3.57822 9.27569 3.57813 8.97206V7.97304C3.57812 7.70758 3.5743 7.48515 3.62598 7.26992C3.66867 7.09209 3.73941 6.92194 3.83496 6.76601C3.95062 6.57734 4.11017 6.42244 4.29785 6.23476L10.001 0.531635ZM4.67773 8.42226H5.12695C5.4447 8.42226 5.514 8.41793 5.57324 8.40371C5.63866 8.38799 5.7014 8.36265 5.75879 8.32753C5.81074 8.2957 5.86219 8.24855 6.08691 8.02382L11.79 2.3207C12.0693 2.04143 12.0693 1.58923 11.79 1.30996C11.5108 1.03068 11.0586 1.03069 10.7793 1.30996L5.07617 7.01308C4.85144 7.23781 4.8043 7.28926 4.77246 7.34121C4.73734 7.3986 4.71201 7.46133 4.69629 7.52675C4.68207 7.58599 4.67774 7.6553 4.67773 7.97304V8.42226Z",fill:"currentColor"})})}const Hl=72,C0=Hl+10,j0=t=>!t.canvasWidth||!t.canvasHeight?Hl:Math.max(1,Math.round(Hl*t.canvasHeight/t.canvasWidth)),k0=({presets:t})=>t.length===0?null:e.jsxs("section",{"data-testid":rs.presetsSection,className:"flex w-full flex-col gap-[12px] px-[10px]",children:[e.jsxs("h3",{className:"text-[12px] font-medium tracking-[-0.24px] text-black",children:["Tool Presets (",t.length,")"]}),e.jsx("div",{className:"flex w-full items-start gap-[6px] overflow-x-auto pb-[4px]",children:t.map(s=>e.jsxs("div",{"data-testid":rs.presetCard,className:"flex shrink-0 flex-col gap-[6px]",style:{width:C0},children:[e.jsx("div",{className:"rounded-[10px] border border-[#e8e8e8] p-[4px]",children:e.jsx("div",{"data-testid":rs.presetThumbnail,className:"overflow-hidden rounded-[6px] bg-[#e8e8e8]",style:{width:Hl,height:j0(s)},children:e.jsx(Fm,{preset:s,className:"block size-full object-cover"})})}),e.jsx("p",{title:s.name,className:"truncate text-[12px] tracking-[-0.24px] text-black",children:s.name})]},s.id))})]}),eu={main:0,edit:1},yc=120,N0=142;function ox({visibility:t,onVisibilityChange:s,listedInGallery:r,shareUrl:a,onRemove:o,toolName:i,onToolNameChange:l,toolDescription:c,onToolDescriptionChange:x,media:h,coverAspectRatio:y=Su,isCoverWorking:u,onCaptureStaticCover:w,onRecordDynamicCover:_,onUploadStaticCover:v,onUploadDynamicCover:j,toolTags:A,onAddTag:I,onRemoveTag:O,publishState:L,onSave:P,isSaving:V=!1,onClose:re,initialPage:X="main",hideBack:je=!1,coverDirty:he=!1,onCoverDirtyReset:me,biOrigin:T,onBiAction:ee,presets:ae=[]}){const ve=Y=>ee(Ym(T,Y)),[ue,z]=n.useState(X==="edit"?"edit":"main"),[$,W]=n.useState(!1),[ne,F]=n.useState("forward"),te=n.useRef(null),Le=n.useRef(null),Ke=n.useRef(null),[oe,st]=n.useState(!1),[rt,q]=n.useState(!1),we=n.useMemo(()=>Yo(y),[y]),De=n.useMemo(()=>Yo(h.thumbnail_aspect_ratio??y),[y,h.thumbnail_aspect_ratio]),ie=n.useMemo(()=>({aspectRatio:String(we)}),[we]),pe=n.useMemo(()=>({width:N0,aspectRatio:String(De)}),[De]),J=Y=>{const Ue=eu[Y]>eu[ue];F(Ue?"forward":"back"),W(!0),setTimeout(()=>{z(Y),W(!1)},220)},[Ce,se]=n.useState(i),[Ot,U]=n.useState(""),[mt]=n.useState(c),[le]=n.useState(A),Se=c.length,gt=Se>yc,Fe=gt&&c!==mt,Te=Ce!==i,Dt=c!==mt,Dn=A.length!==le.length||A.some((Y,Ue)=>Y!==le[Ue]),Ct=Te||Dt||Dn||he,qt=L!=="draft",Jn=()=>{const Y=Ot.trim().toLowerCase().slice(0,Va);Y&&!A.includes(Y)&&I(Y),U("")},dn=po(h),H=(()=>{const Y=Nl(h);return Y&&Sl(Y)?Y:null})(),be=$?ne==="forward"?"opacity-0 translate-x-4":"opacity-0 -translate-x-4":"opacity-100 translate-x-0",xe=(Y,Ue)=>e.jsxs("div",{className:"bg-white border border-[#e1e1e1] shadow-[0px_4px_15px_rgba(0,0,0,0.1)] rounded-[10px] w-full flex flex-col overflow-x-hidden",style:{maxHeight:"calc(100vh - 80px)"},children:[e.jsx("div",{className:"flex-1 overflow-y-auto overflow-x-hidden min-h-0",children:e.jsx("div",{ref:te,className:`flex flex-col gap-[15px] items-start p-[20px] transition-all duration-200 ease-out ${be}`,children:Y})}),Ue?e.jsx("div",{className:"relative shrink-0",children:e.jsx("div",{className:"px-[20px] pb-[20px] bg-white",children:Ue})}):null]});return ue==="edit"?xe(e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col gap-[15px] w-full shrink-0",children:[e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsxs("div",{className:"flex items-center gap-[8px]",children:[je?null:e.jsx("button",{type:"button",onClick:()=>J("main"),className:"p-1 -ml-1 text-black hover:text-[#444] transition-colors","aria-label":"Back",children:e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none","aria-hidden":!0,
59className:"shrink-0",children:e.jsx("path",{d:"M6.5 2L3.5 5L6.5 8",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),e.jsx("p",{className:"text-[14px] font-medium text-black tracking-[-0.28px] leading-[1.4]",children:"Edit Cover"})]}),e.jsx("button",{type:"button",onClick:re,className:"p-1 -mr-1 text-black hover:text-[#444] transition-colors","aria-label":"Close",children:e.jsx(Pd,{className:"text-black"})})]}),e.jsx("div",{className:"h-px w-full bg-[#e1e1e1]"})]}),e.jsxs("div",{className:"flex flex-col gap-[15px] items-center w-full px-[10px]",children:[e.jsxs("div",{className:"flex gap-[10px] items-start w-full",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-[5px]",children:[e.jsx("p",{className:"px-[5px] text-[12px] font-medium tracking-[-0.24px] text-[#686868] leading-[1.4]",children:"Static Cover"}),e.jsxs("div",{className:"flex w-full flex-col overflow-hidden rounded-[10px] border border-[#e8e8e8] p-[4px]",children:[e.jsx("div",{className:"relative w-full overflow-hidden rounded-[6px] bg-[#e8e8e8]",style:ie,children:dn&&!oe?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:dn,alt:"",className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>{ve(lo.coverRemoveStatic),st(!0)},"data-testid":rs.removeStaticCoverButton,disabled:u,className:"absolute right-[6px] top-[6px] flex size-[18px] items-center justify-center rounded-[5px] border border-[#e1e1e1] bg-white text-black disabled:opacity-50","aria-label":"Remove static cover",children:e.jsx(Hr,{className:"size-[10px]",strokeWidth:2.25})})]}):e.jsxs("button",{type:"button",onClick:()=>{var Y;return(Y=Le.current)==null?void 0:Y.click()},disabled:u||!v,className:"flex h-full w-full flex-col items-center justify-center gap-[10px] border border-dashed border-[rgba(104,104,104,0.3)] rounded-[5px] p-[10px] disabled:opacity-50",children:[e.jsx("span",{className:"flex size-[36px] items-center justify-center rounded-[10px] border border-[#e1e1e1] bg-white",children:e.jsx(Bi,{className:"size-[12px] text-[#686868]"})}),e.jsx("span",{className:"max-w-[101px] text-center text-[10px] font-medium tracking-[-0.2px] text-[#686868] leading-[1.4]",children:"Upload Image Cover (5mb Max)"})]})}),e.jsx("button",{type:"button",onClick:()=>{ve(lo.coverScreenshot),st(!1),w()},"data-testid":rs.screenshotCoverButton,disabled:u,className:"flex h-[36px] w-full items-center justify-center bg-white text-[12px] font-medium tracking-[-0.24px] text-black underline disabled:opacity-50",children:u?e.jsx(In,{className:"size-3 animate-spin"}):"Screenshot Cover"}),v?e.jsx("input",{ref:Le,"data-testid":rs.staticCoverInput,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:Y=>{var ut;const Ue=(ut=Y.currentTarget.files)==null?void 0:ut[0];Ue&&(ve(lo.coverUploadImage),v(Ue),st(!1)),Y.currentTarget.value=""}}):null]})]}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-[5px]",children:[e.jsx("p",{className:"px-[5px] text-[12px] font-medium tracking-[-0.24px] text-[#686868] leading-[1.4]",children:"Dynamic Cover"}),e.jsxs("div",{className:"flex w-full flex-col overflow-hidden rounded-[10px] border border-[#e8e8e8] p-[4px]",children:[e.jsx("div",{className:"relative w-full overflow-hidden rounded-[6px] bg-[#e8e8e8]",style:ie,children:H&&!rt?e.jsxs(e.Fragment,{children:[e.jsx(Gi,{tool:h,autoPlay:!0,className:"pointer-events-none absolute inset-0",size:"small"}),e.jsx("button",{type:"button",onClick:()=>{ve(lo.coverRemoveDynamic),q(!0)},"data-testid":rs.removeDynamicCoverButton,disabled:u,className:"absolute right-[6px] top-[6px] z-10 flex size-[18px] items-center justify-center rounded-[5px] border border-[#e1e1e1] bg-white text-black disabled:opacity-50","aria-label":"Remove dynamic cover",children:e.jsx(Hr,{className:"size-[10px]",strokeWidth:2.25})})]}):e.jsxs("button",{type:"button",onClick:()=>{var Y;return(Y=Ke.current)==null?void 0:Y.click()},disabled:u,className:"flex h-full w-full flex-col items-center justify-center gap-[10px] border border-dashed border-[rgba(104,104,104,0.3)] rounded-[5px] p-[10px] disabled:opacity-50",children:[e.jsx("span",{className:"flex size-[36px] items-center justify-center rounded-[10px] border border-[#e1e1e1] bg-white",children:e.jsx(Bi,{className:"size-[12px] text-[#686868]"})}),e.jsx("span",{className:"max-w-[101px] text-center text-[10px] font-medium tracking-[-0.2px] text-[#686868] leading-[1.4]",children:"Upload Video Cover (5mb Max)"})]})}),e.jsx("button",{type:"button",onClick:()=>{ve(lo.coverRecord),q(!1),_()},"data-testid":rs.recordCoverButton,disabled:u,className:"flex h-[36px] w-full items-center justify-center bg-white text-[12px] font-medium tracking-[-0.24px] text-black underline disabled:opacity-50",children:u?e.jsx(In,{className:"size-3 animate-spin"}):"Record Cover"}),e.jsx("input",{ref:Ke,"data-testid":rs.dynamicCoverInput,type:"file",accept:"video/mp4,video/webm",className:"hidden",onChange:Y=>{var ut;const Ue=(ut=Y.currentTarget.files)==null?void 0:ut[0];Ue&&(ve(lo.coverUploadVideo),j(Ue),q(!1)),Y.currentTarget.value=""}})]})]})]}),e.jsx("p",{className:"w-full text-center text-[10px] font-medium tracking-[-0.2px] text-[#686868] leading-[1.4]",children:"Min ratio 16:9 - Max ratio 9:16"}),e.jsx("div",{className:"h-px w-full bg-[#e1e1e1]"}),e.jsxs("div",{className:"flex w-full flex-col gap-[10px]",children:[e.jsx("p",{className:"px-[5px] text-[12px] font-medium tracking-[-0.24px] text-[#686868] leading-[1.4]",children:"Name"}),e.jsx("input",{type:"text","data-testid":rs.nameInput,value:Ce,onChange:Y=>se(Y.target.value),onBlur:()=>{Ce!==i&&l(Ce)},className:"h-[36px] w-full rounded-[10px] bg-[#e8e8e8] px-[15px] text-[12px] tracking-[-0.24px] text-black outline-none transition-colors focus:bg-[#dcdcdc]"})]}),e.jsxs("div",{className:"flex w-full flex-col gap-[10px]",children:[e.jsx("p",{className:"px-[5px] text-[12px] font-medium tracking-[-0.24px] text-[#686868] leading-[1.4]",children:"Description"}),e.jsxs("div",{className:"relative w-full",children:[e.jsx("textarea",{"data-testid":rs.descriptionInput,value:c,onChange:Y=>{x(Y.target.value)},maxLength:yc,rows:3,className:"h-[100px] w-full resize-none rounded-[10px] bg-[#e8e8e8] p-[15px] pb-[28px] text-[12px] tracking-[-0.24px] text-black outline-none transition-colors focus:bg-[#dcdcdc]"}
59),e.jsxs("p",{className:`absolute bottom-[10px] right-[15px] text-[11px] tracking-[-0.24px] leading-[1.4] ${gt?"text-red-500":"text-[#686868]"}`,children:[Se,"/",yc]})]})]}),e.jsxs("div",{className:"flex w-full flex-col gap-[10px]",children:[e.jsx("p",{className:"px-[5px] text-[12px] font-medium tracking-[-0.24px] text-[#686868] leading-[1.4]",children:"Tags"}),e.jsxs("div",{className:"flex h-[36px] items-center rounded-[10px] bg-[#e8e8e8] px-[15px]",children:[e.jsx("input",{type:"text","data-testid":rs.tagInput,value:Ot,maxLength:Va,onChange:Y=>U(Y.target.value.slice(0,Va)),onBlur:Jn,onKeyDown:Y=>{(Y.key==="Enter"||Y.key===",")&&(Y.preventDefault(),Jn())},placeholder:"Add Tags",className:"min-w-0 flex-1 bg-transparent text-[12px] tracking-[-0.24px] text-black outline-none placeholder:text-[#686868]"}),e.jsx("button",{type:"button","data-testid":rs.addTagButton,onClick:Jn,className:"flex size-[20px] items-center justify-center text-black","aria-label":"Add tag",children:e.jsx(Bi,{className:"size-[12px]"})})]}),A.length>0?e.jsx("div",{className:"flex flex-wrap gap-[5px]",children:A.map(Y=>e.jsxs("button",{type:"button",onClick:()=>{O(Y)},className:"flex h-[26px] min-w-0 max-w-full items-center gap-[5px] rounded-[5px] border border-[#e1e1e1] bg-white px-[10px] text-[10px] font-medium tracking-[-0.2px] text-black transition-colors hover:bg-[#f5f5f5]",children:[e.jsx(Hr,{className:"size-[10px] shrink-0"}),e.jsx("span",{className:"min-w-0 truncate",children:Y})]},Y))}):null]})]})]}),e.jsxs("button",{type:"button","data-testid":rs.saveChangesButton,disabled:!Ct,onClick:()=>{ve(lo.saveDetails),Te&&l(Ce),me==null||me(),P()},className:`flex gap-[8px] h-[36px] items-center justify-center px-[15px] rounded-[10px] w-full text-[12px] tracking-[-0.24px] leading-[1.4] transition-colors ${Ct?"bg-black border border-[#e1e1e1] text-white hover:bg-[#262626]":"bg-[#e8e8e8] text-[#686868] cursor-not-allowed"}`,children:[e.jsx(Qm,{className:"size-[12px] shrink-0"}),"Save Changes"]})):xe(e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex w-full shrink-0 flex-col gap-[15px]",children:[e.jsx("div",{className:"flex w-full items-start justify-between",children:e.jsxs("div",{className:"flex min-w-0 flex-col w-full",children:[e.jsxs("div",{className:"flex items-center justify-between gap-[8px]",children:[e.jsx("p",{className:"text-[14px] font-medium tracking-[-0.28px] text-black leading-[1.4]",children:"Publish Preview"}),e.jsxs("div",{className:"flex items-center gap-[8px]",children:[qt&&L==="published_dirty"?e.jsx("span",{className:"flex h-[20px] items-center justify-center rounded-[5px] bg-[#fff3cd] px-[8px] text-[8px] font-medium tracking-[-0.16px] text-[#856404]",children:"Changes pending"}):qt&&r?e.jsx("span",{className:"flex h-[20px] items-center justify-center rounded-[5px] px-[8px] text-[8px] font-medium tracking-[-0.16px] text-white",style:{backgroundImage:"linear-gradient(160deg, #ff4447 21%, #ff59f1 79%)"},children:"Live in Brik"}):null,e.jsx("button",{type:"button",onClick:re,className:"shrink-0 p-0 text-black transition-colors hover:text-[#444]","aria-label":"Close",children:e.jsx(Pd,{className:"text-black"})})]})]}),e.jsx("p",{className:"text-[12px] tracking-[-0.24px] text-[#686868] leading-[1.4]",children:"Make it easy to find and hard to scroll past."})]})}),e.jsx("div",{className:"h-px w-full bg-[#e1e1e1]"})]}),e.jsx("div",{className:"flex w-full flex-col px-[10px]",children:e.jsxs("div",{className:"flex w-full items-start gap-[15px]",children:[e.jsx("div",{className:"shrink-0 rounded-[10px] border border-[#e8e8e8] p-[4px]",children:e.jsx("div",{className:"relative overflow-hidden rounded-[6px] bg-[#e8e8e8]",style:pe,children:dn?e.jsx("img",{src:dn,alt:"Cover",className:"h-full w-full object-cover"}):H?e.jsx(Gi,{tool:h,autoPlay:!0,className:"pointer-events-none absolute inset-0",size:"small"}):e.jsx("div",{className:"flex h-full w-full items-center justify-center text-[10px] font-medium tracking-[-0.2px] text-[#7d7d7d]",children:"No cover"})})}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-[15px]",children:[e.jsxs("div",{className:"flex flex-col gap-[3px] px-[5px]",children:[e.jsx("p",{className:"text-[12px] font-medium tracking-[-0.24px] text-black leading-[1.4]",children:i||"Untitled tool"}),c?e.jsx("p",{className:"line-clamp-4 text-[12px] tracking-[-0.24px] text-[#686868] leading-[1.4]",children:c}):null,Fe?e.jsxs("div",{className:"flex items-center gap-[4px] text-[#ff4447]",children:[e.jsx(eh,{className:"size-[12px] shrink-0"}),e.jsx("span",{className:"text-[10px] tracking-[-0.2px] leading-[1.4]",children:"Description is too long. Edit listing to shorten it to 120 characters."})]}):null]}),e.jsxs("button",{type:"button",onClick:()=>{J("edit")},className:"flex h-[36px] w-full items-center justify-center gap-[8px] rounded-[10px] border border-[#e1e1e1] bg-white text-[12px] font-medium tracking-[-0.24px] text-black transition-colors hover:bg-[#f5f5f5]",children:[e.jsx(w0,{className:"text-black"}),"Edit Listing"]})]})]})}),e.jsx(k0,{presets:ae}),e.jsxs("div",{className:`flex w-full items-center gap-[15px] rounded-[10px] border p-[15p
59x] ${t==="public"?"border-[#ff4447]":"border-[#e8e8e8]"}`,children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col text-[12px] tracking-[-0.24px]",children:[e.jsx("p",{className:"font-medium text-black leading-[1.4]",children:t==="public"?"Listed in Brik gallery":"Unlisted in Brik gallery"}),e.jsx("p",{"data-testid":rs.visibilityDescription,className:"text-[#686868] leading-[1.4]",children:t==="public"?"Brik users will be able to see and freely use your tool":"Anyone with the tool link can see and freely use your tool"})]}),e.jsx("button",{type:"button",role:"switch","data-testid":rs.visibilityToggle,"aria-checked":t==="public","aria-label":"Listed in Brik gallery",onClick:()=>s(t==="public"?"private":"public"),className:`relative flex h-[19px] w-[32px] shrink-0 items-center rounded-[20px] transition-colors ${t==="public"?"":"bg-[#686868]"}`,style:t==="public"?{backgroundImage:"linear-gradient(149deg, #ff4447 21%, #ff59f1 79%)"}:void 0,children:e.jsx("span",{className:`block size-[15px] rounded-full bg-white shadow-sm transition-transform ${t==="public"?"translate-x-[15px]":"translate-x-[2px]"}`})})]}),qt&&a?e.jsxs("div",{className:"flex w-full flex-col gap-[10px]",children:[e.jsx("p",{className:"px-[5px] text-[12px] font-medium tracking-[-0.24px] text-black leading-[1.4]",children:"Share Link"}),e.jsxs("div",{className:"flex w-full items-center gap-[5px]",children:[e.jsx("a",{href:a,target:"_blank",rel:"noreferrer",className:"flex h-[36px] min-w-0 flex-1 items-center truncate rounded-[10px] bg-[#e8e8e8] px-[15px] text-[10px] tracking-[-0.2px] text-black transition-colors hover:bg-[#dcdcdc]",children:a}),e.jsxs("button",{type:"button",onClick:async()=>{a&&(await navigator.clipboard.writeText(a),Ie.success("Link copied"))},className:"flex h-[36px] shrink-0 items-center justify-center gap-[8px] rounded-[10px] border border-[#e1e1e1] bg-white px-[15px] text-[12px] font-medium tracking-[-0.24px] text-black transition-colors hover:bg-[#f5f5f5]",children:[e.jsx(Yi,{className:"size-[12px]"}),"Copy"]})]})]}):null]}),qt?e.jsxs("div",{className:"flex w-full flex-col gap-[8px]",children:[e.jsxs("button",{type:"button",onClick:P,disabled:V||Fe,className:"flex h-[36px] w-full items-center justify-center gap-[8px] rounded-[10px] border border-[#e1e1e1] bg-black px-[15px] text-[12px] tracking-[-0.24px] text-white transition-colors hover:bg-[#262626] disabled:opacity-50",children:[V?e.jsx(In,{className:"size-3 animate-spin"}):null,V?"Updating...":"Update"]}),e.jsx("button",{type:"button",onClick:o,disabled:V,className:"flex h-[36px] w-full items-center justify-center gap-[8px] rounded-[10px] border border-[#ff4447] bg-white px-[15px] text-[12px] font-medium tracking-[-0.24px] text-[#ff4447] transition-colors hover:bg-[#fff5f5] disabled:opacity-50",children:"Unpublish"})]}):e.jsxs("button",{type:"button",onClick:P,disabled:V||Fe,className:"flex h-[36px] w-full items-center justify-center gap-[8px] rounded-[10px] border border-[#e1e1e1] bg-black px-[15px] text-[12px] tracking-[-0.24px] text-white transition-colors hover:bg-[#262626] disabled:opacity-50",children:[V?e.jsx(In,{className:"size-3 animate-spin"}):e.jsx(_0,{className:"text-white"}),V?"Publishing...":"Publish"]}))}const S0={settingsButton:"editor-tool-name-section-settings-button"};function T0({toolName:t,open:s,onOpenChange:r,shareUrl:a,visibility:o,listedInGallery:i,publishState:l,onRemove:c,onVisibilityChange:x,onToolNameChange:h,toolDescription:y,onToolDescriptionChange:u,media:w,coverAspectRatio:_,isCoverWorking:v,onCaptureStaticCover:j,onRecordDynamicCover:A,onUploadStaticCover:I,onUploadDynamicCover:O,toolTags:L,onAddTag:P,onRemoveTag:V,onSave:re,onClose:X,coverDirty:je,onCoverDirtyReset:he,onBiAction:me}){return e.jsxs("div",{"data-testid":xn.toolNameSection.root,className:"flex items-center gap-[10px]",children:[e.jsx("span",{"data-testid":xn.toolNameSection.toolName,className:"text-[12px] font-medium tracking-[-0.24px] text-black whitespace-nowrap",children:t||"Untitled Tool"}),e.jsx("div",{className:"flex items-center gap-[5px]",children:e.jsxs(Ga,{open:s,onOpenChange:r,children:[e.jsx(Wa,{asChild:!0,children:e.jsx("button",{type:"button","data-testid":S0.settingsButton,className:"flex size-[26px] items-center justify-center rounded-[5px] border border-[#e1e1e1] bg-white hover:bg-[#f5f5f5] transition-colors","aria-label":"Edit listing",children:e.jsx(D1,{className:"size-[10px]"})})}),e.jsx(qa,{align:"start",side:"bottom",sideOffset:5,className:"w-[390px] max-w-[calc(100vw-32px)] p-0 border-0 shadow-none bg-transparent",children:e.jsx(ox,{initialPage:"edit",hideBack:!0,shareUrl:a,onRemove:c,visibility:o,listedInGallery:i,onVisibilityChange:x,toolName:t,onToolNameChange:h,toolDescription:y,onToolDescriptionChange:u,media:w,coverAspectRatio:_,isCoverWorking:v,onCaptureStaticCover:j,onRecordDynamicCover:A,onUploadStaticCover:I,onUploadDynamicCover:O,toolTags:L,onAddTag:P,onRemoveTag:V,publishState:l,onSave:re,onClose:X,coverDirty:je,onCoverDirtyReset:he,biOrigin:kp.toolDetails,onBiAction:me})})]})})]})}function ix({open:t,onClose:s}){return e.jsx(la,{open:t,onOpenChange:s,children:e.jsxs(ca,{"data-testid":xn.publishModal.root,className:"sm:max-w-[326px] gap-0 rounded-[10px] border border-[#e1e1e1] bg-white p-[15px] shadow-[0px_4px_15px_rgba(0,0,0,0.1)] [&>button]:hidden","aria-describedby":void 0,children:[e.jsx(da,{className:"sr-only",children:"Publish to share"}),e.jsxs("div",{className:"flex flex-col gap-[15px]",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-[3px]",children:[e.jsx("p",{className:"text-[14px] font-medium leading-[1.4] tracking-[-0.28px] text-black",children:"Publish to share"}),e.jsx("p",{className:"text-[12px] leading-[1.4] tracking-[-0.24px] text-[#7d7d7d]",children:"Publish your tool to get a shareable link."})]}),e.jsx("button",{type:"button","data-testid":xn.publishModal.closeButton,onClick:s,className:"text-black transition-opacity hover:opacity-70",children:e.jsx(Hr,{className:"h-3.5 w-3.5"})})]}),e.jsx("button",{type:"button","data-testid":xn.publishModal.gotItButton,onClick:s,className:"flex h-[36px] w-full items-center justify-center rounded-[10px] border border-[#e1e1e1] bg-black px-[15px] text-[12px] font-medium leading-[1.4] tracking-[-0.24px] text-white transition-colors hover:bg-[#111]",children:"Got it"})]})]})})}const vl=xn.timelinePanel;function lx({timeline:t,controlsSchema:s,iframeRef:r,playbackLocked:a=!1,chromeVariant:o="legacy",className:i}){var V;const[l,c]=n.useState(!1),x=(t==null?void 0:t.tracks)??[],h=(t==null?void 0:t.fps)??30,y=Math.max(1,(t==null?void 0:t.durationFrames)??h*10),u=(t==null?void 0:t.loop)??"loop",{playing:w,togglePlay:_,playFrom:v,playheadFrame:j}=qf({tracks:x,fps:h,durationFrames:y,loopMode:u,controlsSchema:s,iframeRef:r,exportRange:(t==null?void 0:t.exportRange)??void 0}),A=n.useMemo(()=>{var re;return((re=t==null?void 0:t.exportRange)==null?void 0:re.startFrame)??0},[(V=t==null?void 0:t.exportRange)==null?void 0:V.startFrame]),I=()=>
59{if(!a){if(w){_();return}if(j>=y-.5){v(A);return}_()}},O=w?"Pause animation":"Play animation",L=o==="v2"?e.jsx(vf,{"data-testid":vl.mobilePlayButton,size:"medium",skin:"ghost",priority:"primary",onClick:I,disabled:a,title:a?"Playback locked while exporting":void 0,"aria-label":O,icon:e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":!0,children:w?e.jsxs(e.Fragment,{children:[e.jsx("rect",{x:"6.5",y:"5",width:"3.5",height:"14"}),e.jsx("rect",{x:"14",y:"5",width:"3.5",height:"14"})]}):e.jsx("path",{d:"M7 4.5V19.5L19 12L7 4.5Z"})})}):e.jsx("button",{type:"button","data-testid":vl.mobilePlayButton,onClick:I,disabled:a,title:a?"Playback locked while exporting":void 0,"aria-label":O,className:"shrink-0 flex h-[32px] w-[32px] items-center justify-center rounded-full bg-black text-white disabled:bg-[#d6d6d6] disabled:pointer-events-none",children:w?e.jsx(Zm,{className:"h-[14px] w-[14px]",fill:"white",strokeWidth:0}):e.jsx(th,{className:"h-[14px] w-[14px] ml-[1px]",fill:"white",strokeWidth:0})}),P=o==="v2";return l?e.jsx("div",{"data-testid":vl.mobileBanner,className:Wt("lg:hidden shrink-0 flex justify-start mb-[15px]",P?"mx-[16px]":"mx-[20px]",i),children:P?L:e.jsx("div",{className:"flex items-center rounded-[12px] bg-white p-[6px] shadow-[0_1px_6px_rgba(0,0,0,0.1)]",children:L})}):e.jsxs("div",{"data-testid":vl.mobileBanner,role:"status",className:Wt("lg:hidden shrink-0 flex items-center gap-[10px] mb-[15px]",P?"mx-[16px] border border-[var(--product-grey-02-legacy)] bg-[var(--product-white-00)] px-[12px] py-[10px]":"mx-[20px] rounded-[12px] bg-white px-[12px] py-[10px] shadow-[0_1px_6px_rgba(0,0,0,0.1)]",i),children:[L,e.jsx("p",{className:"flex-1 min-w-0 m-0 text-[13px] leading-[1.35] tracking-[-0.26px] text-[#1a1a1a]",children:"To edit and view the timeline, open on desktop."}),e.jsx("button",{type:"button","aria-label":"Minimize",onClick:()=>c(!0),className:"shrink-0 flex h-[20px] w-[20px] items-center justify-center text-[#7d7d7d]",children:e.jsx(Hr,{className:"h-[14px] w-[14px]",strokeWidth:2})})]})}const uo="flex w-full items-center gap-[8px] rounded-[5px] px-[8px] py-[5px] text-[12px] leading-[1.4] tracking-[-0.24px] text-[#7d7d7d] transition-colors hover:bg-[#e8e8e8] hover:text-black",R0=({onCopyUrl:t,onDelete:s,onRemix:r,onMidi:a,onProject:o,viewerUrl:i,disabled:l=!1,disabledReason:c})=>{const{sendPageClicked:x}=Ua(),[h,y]=n.useState(!1);return n.useEffect(()=>{l&&y(!1)},[l]),e.jsxs(e.Fragment,{children:[h&&Ko.createPortal(e.jsx("div",{className:"fixed inset-0 z-40","aria-hidden":!0,onClick:()=>y(!1)}),document.body),e.jsxs(Ga,{open:h,onOpenChange:u=>{l&&u||y(u)},children:[e.jsx(zi,{disabled:l,reason:c,children:e.jsx(Wa,{asChild:!0,children:e.jsx("button",{type:"button","aria-disabled":l||void 0,onClick:()=>{l||x({button_name:"tool_editor_actions"})},className:`flex size-[40px] shrink-0 items-center justify-center rounded-[10px] border border-[#e1e1e1] bg-white text-black transition-colors hover:bg-neutral-50 ${l?"cursor-not-allowed opacity-50":""}`,"aria-label":"More actions",children:e.jsx(Th,{className:"size-4 shrink-0"})})})}),e.jsxs(qa,{align:"end",side:"bottom",sideOffset:5,className:"z-50 flex w-auto min-w-[140px] flex-col gap-[15px] rounded-[10px] border border-[#e1e1e1] bg-white p-[15px] shadow-[0px_4px_15px_0px_rgba(0,0,0,0.1)]",onOpenAutoFocus:u=>u.preventDefault(),children:[e.jsxs("div",{className:"flex flex-col gap-[5px]",children:[i?e.jsxs("a",{href:i,...Tl,onClick:()=>{x({button_name:"tool_actions_view"}),y(!1)},className:uo,children:[e.jsx(Pl,{className:"size-4 shrink-0"}),"View"]}
59):e.jsxs("button",{type:"button",disabled:!0,className:`${uo} cursor-not-allowed opacity-50`,children:[e.jsx(Pl,{className:"size-4 shrink-0"}),"View"]}),e.jsxs("button",{type:"button",onClick:()=>{x({button_name:"tool_actions_share"}),y(!1),t()},className:uo,children:[e.jsx("svg",{width:"11",height:"11",viewBox:"0 0 11.0996 11.0996",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:e.jsx("path",{d:"M9.15655e-07 7.88281V3.2168C9.15655e-07 2.75922 -0.000536313 2.38264 0.024415 2.07715C0.0499009 1.76522 0.104294 1.47868 0.241212 1.20996C0.453724 0.79291 0.79291 0.453724 1.20996 0.241212C1.47868 0.104294 1.76522 0.0499009 2.07715 0.024415C2.38264 -0.000536324 2.75922 9.1571e-07 3.2168 9.1571e-07H4.43848C4.74223 9.1571e-07 4.98828 0.246049 4.98828 0.549806C4.98828 0.853562 4.74223 1.09961 4.43848 1.09961H3.2168C2.74124 1.09961 2.41727 1.10067 2.16699 1.12109C1.92335 1.141 1.79775 1.17701 1.70996 1.22168C1.49985 1.32874 1.32874 1.49985 1.22168 1.70996C1.17701 1.79775 1.141 1.92335 1.12109 2.16699C1.10067 2.41727 1.09961 2.74124 1.09961 3.2168V7.88281C1.09961 8.35837 1.10067 8.68234 1.12109 8.93262C1.141 9.17626 1.17701 9.30186 1.22168 9.38965C1.32874 9.59976 1.49985 9.77087 1.70996 9.87793C1.79775 9.9226 1.92335 9.95861 2.16699 9.97852C2.41727 9.99894 2.74124 10 3.2168 10H7.88281C8.35837 10 8.68234 9.99894 8.93262 9.97852C9.17626 9.95861 9.30186 9.9226 9.38965 9.87793C9.59976 9.77087 9.77087 9.59976 9.87793 9.38965C9.9226 9.30186 9.95861 9.17626 9.97852 8.93262C9.99894 8.68234 10 8.35837 10 7.88281V6.66113C10 6.35738 10.246 6.11133 10.5498 6.11133C10.8536 6.11133 11.0996 6.35738 11.0996 6.66113V7.88281C11.0996 8.34039 11.1001 8.71697 11.0752 9.02246C11.0497 9.33439 10.9953 9.62093 10.8584 9.88965C10.6459 10.3067 10.3067 10.6459 9.88965 10.8584C9.62093 10.9953 9.33439 11.0497 9.02246 11.0752C8.71697 11.1001 8.34039 11.0996 7.88281 11.0996H3.2168C2.75922 11.0996 2.38264 11.1001 2.07715 11.0752C1.76522 11.0497 1.47868 10.9953 1.20996 10.8584C0.792911 10.6459 0.453724 10.3067 0.241212 9.88965C0.104293 9.62093 0.0499009 9.33439 0.024415 9.02246C-0.000536256 8.71697 9.15655e-07 8.34039 9.15655e-07 7.88281ZM11.0996 3.88281C11.0996 4.18657 10.8536 4.43359 10.5498 4.43359C10.246 4.4336 10 4.18657 10 3.88281V1.87695L5.93848 5.93848C5.72369 6.15327 5.37592 6.15327 5.16113 5.93848C4.94635 5.72369 4.94635 5.37592 5.16113 5.16113L9.22266 1.09961H7.2168C6.91304 1.09961 6.66602 0.853562 6.66602 0.549806C6.66602 0.246051 6.91304 9.1571e-07 7.2168 9.1571e-07H10.5498C10.8536 8.13363e-06 11.0996 0.246056 11.0996 0.549806V3.88281Z",fill:"currentColor"})}),"Share"]}),e.jsxs("button",{type:"button",onClick:()=>{x({button_name:"tool_actions_remix"}),y(!1),r()},className:uo,children:[e.jsx("svg",{width:"11",height:"11",viewBox:"0 0 11.0996 11.0996",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"shrink-0",children:e.jsx("path",{d:"M10 5.64942C10 5.36075 9.99962 5.17715 9.98828 5.03809C9.97751 4.9062 9.95965 4.86244 9.95117 4.8457C9.90803 4.76103 9.83858 4.69158 9.75391 4.64844C9.73717 4.63996 9.69341 4.6221 9.56152 4.61133C9.42246 4.59999 9.23886 4.59961 8.9502 4.59961H5.64942C5.36075 4.59961 5.17715 4.59999 5.03809 4.61133C4.9062 4.62211 4.86244 4.63996 4.8457 4.64844C4.76103 4.69158 4.69158 4.76103 4.64844 4.8457C4.63996 4.86244 4.62211 4.9062 4.61133 5.03809C4.59999 5.17715 4.59961 5.36075 4.59961 5.64942V8.9502C4.59961 9.23886 4.59999 9.42246 4.61133 9.56152C4.6221 9.69341 4.63996 9.73717 4.64844 9.75391C4.69158 9.83858 4.76103 9.90803 4.8457 9.95117C4.86244 9.95965 4.9062 9.97751 5.03809 9.98828C5.17715 9.99962 5.36075 10 5.64942 10H8.9502C9.23886 10 9.42246 9.99962 9.56152 9.98828C9.69341 9.97751 9.73717 9.95965 9.75391 9.95117C9.83858 9.90803 9.90803 9.83858 9.95117 9.75391C9.95965 9.73717 9.97751 9.69341 9.98828 9.56152C9.99962 9.42246 10 9.23886 10 8.9502V5.64942ZM6.5 2.04981C6.5 1.80931 6.49915 1.65643 6.49121 1.54004C6.48368 1.42966 6.47157 1.39193 6.46582 1.37793C6.42015 1.26767 6.33194 1.17946 6.22168 1.13379C6.20768 1.12804 6.16996 1.11594 6.05957 1.1084C5.94318 1.10046 5.7903 1.09961 5.54981 1.09961H2.14942C1.86075 1.09961 1.67715 1.09999 1.53809 1.11133C1.4062 1.1221 1.36244 1.13996 1.3457 1.14844C1.26103 1.19158 1.19158 1.26103 1.14844 1.3457C1.13996 1.36244 1.1221 1.4062 1.11133 1.53809C1.09999 1.67715 1.09961 1.86075 1.09961 2.14942V5.54981C1.09961 5.7903 1.10046 5.94318 1.1084 6.05957C1.11594 6.16996 1.12804 6.20768 1.13379 6.22168C1.17946 6.33194 1.26767 6.42015 1.37793 6.46582C1.39193 6.47157 1.42966 6.48368 1.54004 6.49121C1.65643 6.49915 1.80931 6.5 2.04981 6.5C2.35356 6.5 2.59961 6.74605 2.59961 7.04981C2.59961 7.35356 2.35356 7.59961 2.04981 7.59961C1.82436 7.59961 1.62737 7.59996 1.46484 7.58887C1.29757 7.57743 1.12691 7.551
5978 0.957032 7.48145C0.577238 7.32413 0.275481 7.02237 0.118165 6.64258C0.0478339 6.4727 0.0221768 6.30204 0.0107434 6.13477C-0.000345283 5.97225 1.19864e-06 5.77525 1.19864e-06 5.54981V2.14942C7.91562e-07 1.87863 -0.000244668 1.64249 0.0156262 1.44824C0.0320296 1.24748 0.0683606 1.04312 0.168947 0.845704C0.317494 0.554379 0.554379 0.317494 0.845704 0.168947C1.04312 0.0683606 1.24748 0.0320296 1.44824 0.0156262C1.64249 -0.00024467 1.87863 7.91685e-07 2.14942 1.19864e-06H5.54981C5.77525 1.19864e-06 5.97225 -0.000345283 6.13477 0.0107434C6.30204 0.0221768 6.4727 0.0478339 6.64258 0.118165C7.02237 0.275481 7.32413 0.577238 7.48145 0.957032C7.55178 1.12691 7.57743 1.29757 7.58887 1.46484C7.59996 1.62737 7.59961 1.82436 7.59961 2.04981C7.59961 2.35356 7.35356 2.59961 7.04981 2.59961C6.74605 2.59961 6.5 2.35356 6.5 2.04981ZM11.0996 8.9502C11.0996 9.22098 11.0999 9.45712 11.084 9.65137C11.0676 9.85213 11.0313 10.0565 10.9307 10.2539C10.7821 10.5452 10.5452 10.7821 10.2539 10.9307C10.0565 11.0313 9.85213 11.0676 9.65137 11.084C9.45712 11.0999 9.22098 11.0996 8.9502 11.0996H5.64942C5.37863 11.0996 5.14249 11.0999 4.94824 11.084C4.74748 11.0676 4.54312 11.0313 4.3457 10.9307C4.05438 10.7821 3.81749 10.5452 3.66895 10.2539C3.56836 10.0565 3.53203 9.85213 3.51563 9.65137C3.49976 9.45712 3.5 9.22098 3.5 8.9502V5.64942C3.5 5.37863 3.49976 5.14249 3.51563 4.94824C3.53203 4.74748 3.56836 4.54312 3.66895 4.3457C3.81749 4.05438 4.05438 3.81749 4.3457 3.66895C4.54312 3.56836 4.74748 3.53203 4.94824 3.51563C5.14249 3.49976 5.37863 3.5 5.64942 3.5H8.9502C9.22098 3.5 9.45712 3.49976 9.65137 3.51563C9.85213 3.53203 10.0565 3.56836 10.2539 3.66895C10.5452 3.81749 10.7821 4.05438 10.9307 4.3457C11.0313 4.54312 11.0676 4.74748 11.084 4.94824C11.0999 5.14249 11.0996 5.37863 11.0996 5.64942V8.9502Z",fill:"currentColor"})}),"Duplicate"]}),a?e.jsxs("button",{type:"button",onClick:()=>{x({button_name:"tool_actions_midi"}),y(!1),a()},className:uo,children:[e.jsx($m,{className:"size-4 shrink-0"}),"MIDI"]}):null,o?e.jsxs("button",{type:"button",onClick:()=>{x({button_name:"tool_actions_project"}),y(!1),o()},className:uo,children:[e.jsx(Pm,{className:"size-4 shrink-0"}),"Projection"]}):null]}),e.jsx("div",{className:"h-px w-full shrink-0 bg-[#e8e8e8]","aria-hidden":!0}),e.jsxs("button",{type:"button",onClick:()=>{x({button_name:"tool_actions_delete"}),y(!1),s()},className:uo,children:[e.jsx(_p,{className:"size-4 shrink-0"}),"Delete Tool"]})]})]})]})},E0={publish:"tool-publish-button-publish"};function I0({className:t}){return e.jsx("svg",{viewBox:"0 0 13.0996 13.0996",fill:"none",overflow:"visible",preserveAspectRatio:"none",xmlns:"http://www.w3.org/2000/svg",className:t,"aria-hidden":!0,children:e.jsx("path",{d:"M12 6.4502C12 5.98464 11.942 5.53269 11.834 5.10059H9.17773C9.24922 5.54158 9.29038 5.98916 9.2998 6.44043C9.29993 6.44668 9.29993 6.45371 9.2998 6.45996C9.29038 6.91123 9.24922 7.35881 9.17773 7.7998H11.834C11.942 7.3677 12 6.91575 12 6.4502ZM1.37695 8.7002C2.10731 10.3445 3.61239 11.5664 5.42969 11.9043C4.72888 10.9362 4.21542 9.8499 3.91406 8.7002H1.37695ZM8.98633 8.7002C8.68492 9.85008 8.17071 10.9361 7.46973 11.9043C9.28745 11.5666 10.793 10.3448 11.5234 8.7002H8.98633ZM4.84766 8.7002C5.17113 9.81058 5.71419 10.8506 6.4502 11.7578C7.1862 10.8506 7.72926 9.81058 8.05273 8.7002H4.84766ZM4.6377 5.10059C4.55817 5.54399 4.50998 5.99482 4.5 6.4502C4.50998 6.90557 4.55817 7.3564 4.6377 7.7998H8.2627C8.34222 7.35641 8.38944 6.90556 8.39941 6.4502C8.38944 5.99483 8.34222 5.54398 8.2627 5.10059H4.6377ZM7.46973 0.995117C8.17095 1.96347 8.68486 3.05006 8.98633 4.2002H11.5234C10.7929 2.55551 9.28753 1.33272 7.46973 0.995117ZM6.4502 1.1416C5.71394 2.04892 5.1712 3.08957 4.84766 4.2002H8.05273C7.72919 3.08957 7.18645 2.04892 6.4502 1.1416ZM5.42969 0.995117C3.61231 1.33297 2.10734 2.5558 1.37695 4.2002H3.91406C4.21548 3.05024 4.72864 1.96336 5.42969 0.995117ZM0.900391 6.4502C0.900391 6.91575 0.958433 7.3677 1.06641 7.7998H3.72266C3.65117 7.35881 3.61001 6.91123 3.60059 6.45996C3.60046 6.45371 3.60046 6.44668 3.60059 6.44043C3.61001 5.98916 3.65117 5.54158 3.72266 5.10059H1.06641C0.958433 5.53269 0.900391 5.98464 0.900391 6.4502ZM12.9004 6.4502C12.9004 10.0124 10.0124 12.9004 6.4502 12.9004C2.88796 12.9004 0 10.0124 0 6.4502C0 2.88796 2.88796 0 6.4502 0C10.0124 0 12.9004 2.88796 12.9004 6.4502Z",fill:"currentColor"})})}const D0=n.forwardRef(function({isParamOnlyChange:s,isPublishing:r,isRepublishing:a,onPublish:o,onSetPublishVisibility:i,onUpdate:l,publishState:c,visibility:x,stagedVisibility:h,shareUrl:y,onRemoveFromGallery:u,toolName:w,toolDescription:_,media:v,coverAspectRatio:j,isCoverWorking:A,onToolNameChange:I,onToolDescriptionChange:O,onCaptureStaticCover:L,onRecordDynamicCover:P,onUploadStaticCover:V,onUploadDynamicCover:re,toolTags:X,onAddTag:je,onRemoveTag:he,onOpen:me,disabled:T=!1,disabledReason:ee,coverDirty:ae,onCoverDirtyReset:ve,presets:ue},z){const $=Zl(),[W,ne]=n.useState(!1);n.useImperativeHandle(z,()=>({openPanel:()=>ne(!0),closePanel:()=>ne(!1)}),[]);const[F,te]=n.useState(!1);n.useEffect(()=>{if(!W&&!F)return;const q=()=>{te(!1),ne(!1)};return window.addEventListener("blur",q),()=>{window.removeEventListener("blur",q)}},[W,F]),n.useEffect(()=>{T&&(ne(!1),te(!1))},[T]);const Le=c==="draft"?"publish":"update",Ke=Le==="publish"?c==="draft"?r:a:Le==="update"?a:!1,oe=n.useRef(!1);n.useEffect(()=>{Ke?oe.current=!0:oe.current&&(oe.current=!1,ne(!1))},[Ke]);const st=q=>{T&&q||(ne(q),q&&(me==null||me()))},rt=()=>{if(!(T||Ke)){if(te(!1),i(h),c==="draft"){o(h);return}l(h)}};return e.jsxs(Ga,{open:W,onOpenChange:st,children:[e.jsx(zi,{disabled:T,reason:ee,children:e.jsxs("div",{className:`flex h-[40px] w-fit items-center overflow-hidden whitespace-nowrap rounded-[10px] border border-[#e1e1e1] bg-white text-[12px] font-medium tracking-[-0.24px] text-black ${T?"opacity-50":""} ${W?"border-[#d4d4d4]":""}`,children:[e.jsxs("button",{type:"button","data-testid":E0.publish,onClick:()=>
59{if(!(T||Ke)){if($("Publish"),c==="draft"){st(!W);return}i(h),l(h)}},"aria-disabled":T||r||a||void 0,"aria-label":"Publish","aria-haspopup":c==="draft"?"dialog":void 0,"aria-expanded":c==="draft"?W:void 0,className:`flex h-[40px] items-center gap-[8px] px-[15px] transition-colors hover:bg-neutral-50 ${T||Ke?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:[Ke?e.jsx(In,{className:"size-3.5 shrink-0 animate-spin"}):e.jsx(I0,{className:"size-4 shrink-0 text-black"}),e.jsx("span",{children:Ke?"Publishing...":"Publish"})]}),e.jsx("span",{className:"h-[40px] w-px bg-[#e1e1e1]","aria-hidden":!0}),e.jsx(Wa,{asChild:!0,children:e.jsx("button",{type:"button","aria-disabled":T||void 0,onClick:()=>{T||$("Publish")},"aria-label":"Listing options",className:`flex h-[40px] items-center justify-center px-[10px] transition-colors hover:bg-neutral-50 data-[state=open]:bg-[#e8e8e8] ${T?"cursor-not-allowed opacity-50":"cursor-pointer"}`,children:e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none","aria-hidden":!0,className:"shrink-0 text-black/60",children:e.jsx("path",{d:"M2 3.5L5 6.5L8 3.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})})})]})}),e.jsx(qa,{align:"end",side:"bottom",sideOffset:5,onInteractOutside:q=>q.preventDefault(),onFocusOutside:q=>q.preventDefault(),className:`w-[390px] max-w-[calc(100vw-32px)] p-0 border-0 shadow-none bg-transparent transition-opacity ${A?"pointer-events-none opacity-0":"opacity-100"}`,children:e.jsx(ox,{shareUrl:y,onRemove:()=>{ne(!1),u()},visibility:h,listedInGallery:c!=="draft"&&x==="public",onVisibilityChange:q=>{q!=="draft"&&i(q)},toolName:w,onToolNameChange:I,toolDescription:_,onToolDescriptionChange:O,media:v,coverAspectRatio:j,isCoverWorking:A,onCaptureStaticCover:L,onRecordDynamicCover:P,onUploadStaticCover:V,onUploadDynamicCover:re,toolTags:X,onAddTag:je,onRemoveTag:he,publishState:c,onSave:()=>{rt()},isSaving:Ke,onClose:()=>ne(!1),coverDirty:ae,onCoverDirtyReset:ve,biOrigin:kp.publish,onBiAction:$,presets:ue})})]})}),M0=({onSave:t,disabled:s=!1,disabledReason:r})=>{const{sendPageClicked:a}=Ua();return e.jsx(zi,{disabled:s,reason:r,children:e.jsx("button",{type:"button","aria-disabled":s||void 0,onClick:()=>{s||(a({button_name:"tool_actions_save"}),t())},className:`flex size-[40px] shrink-0 items-center justify-center rounded-[10px] border border-[#e1e1e1] bg-white text-black transition-colors hover:bg-neutral-50 ${s?"cursor-not-allowed opacity-50":""}`,"aria-label":"Save",children:e.jsx(I1,{className:"size-[13px] shrink-0"})})})},cx=n.forwardRef(({onCopyUrl:t,onDelete:s,onExport:r,onRemix:a,onMidi:o,onProject:i,onSave:l,viewerUrl:c,showActionButtons:x=!0,isPublishing:h,isRepublishing:y,isParamOnlyChange:u,onPublish:w,onSetPublishVisibility:_,onUpdate:v,publishState:j,visibility:A,stagedVisibility:I,onRemoveFromGallery:O,toolName:L,toolDescription:P,media:V,coverAspectRatio:re,isCoverWorking:X,onToolNameChange:je,onToolDescriptionChange:he,onCaptureStaticCover:me,onRecordDynamicCover:T,onUploadStaticCover:ee,onUploadDynamicCover:ae,toolTags:ve,onAddTag:ue,onRemoveTag:z,onOpen:$,publishExportDisabled:W=!1,publishExportDisabledReason:ne,coverDirty:F,onCoverDirtyReset:te,presets:Le,showActionsButton:Ke=!0},oe)=>e.jsxs("div",{className:"flex items-center gap-[5px]",children:[e.jsx(Jm,{disabled:W,disabledReason:ne,title:"Video Render"}),Ke&&e.jsx(R0,{disabled:W,disabledReason:ne,onCopyUrl:t,onDelete:s,onRemix:a,onMidi:o,onProject:i,viewerUrl:c}),e.jsx(M0,{onSave:l,disabled:W,disabledReason:ne}),e.jsx(D0,{ref:oe,disabled:W,disabledReason:ne,isParamOnlyChange:u,isPublishing:h,isRepublishing:y,onPublish:w,onSetPublishVisibility:_,onUpdate:v,publishState:j,visibility:A,stagedVisibility:I,shareUrl:c,onRemoveFromGallery:O,toolName:L,toolDescription:P,media:V,coverAspectRatio:re,isCoverWorking:X,onToolNameChange:je,onToolDescriptionChange:he,onCaptureStaticCover:me,onRecordDynamicCover:T,onUploadStaticCover:ee,onUploadDynamicCover:ae,toolTags:ve,onAddTag:ue,onRemoveTag:z,onOpen:$,coverDirty:F,onCoverDirtyReset:te,presets:Le}),x?e.jsx(Kf,{onExport:r}):null]}));
59cx.displayName="ToolPublishControls";const dx=({isEditingName:t,isAdmin:s,isWorking:r,media:a,coverAspectRatio:o=Su,onChangeDescription:i,onCaptureStaticCover:l,onClose:c,onCommitName:x,onOpenNameEdit:h,onRecordDynamicCover:y,onRemoveTag:u,onUploadDynamicCover:w,onUploadStaticCover:_,onUpsertTag:v,toolDescription:j,toolName:A,toolSystemTags:I,toolTags:O})=>{const[L,P]=n.useState(A),[V,re]=n.useState(""),X=n.useRef(null),je=n.useRef(null),he=n.useRef(null);n.useEffect(()=>{P(A)},[A,t]),n.useEffect(()=>{const F=he.current;F&&(F.style.height="0px",F.style.height=`${F.scrollHeight}px`)},[j]);const me=n.useMemo(()=>Yo(o),[o]),T=n.useMemo(()=>yf(me),[me]),ee=n.useMemo(()=>({aspectRatio:String(me)}),[me]),ae=n.useMemo(()=>{if(a.thumbnail_poster_url)return a.thumbnail_poster_url;const F=po(a);if(F)return F;const te=Nl(a);return te&&!Sl(te)?te:null},[a]),ve=n.useMemo(()=>{const F=Nl(a);return F&&Sl(F)?F:null},[a]),ue=I?[{key:"visual_behavior",label:"Visual behavior",tags:I.visual_behavior},{key:"use_case",label:"Use case",tags:I.use_case}]:[],z=ue.some(F=>F.tags.length>0),$=()=>{V.trim()&&(v(V),re(""))},W=F=>{if(F.key==="Enter"){x(L);return}F.key==="Escape"&&(P(A),x(A))},ne=F=>{(F.key==="Enter"||F.key===",")&&(F.preventDefault(),$())};return e.jsxs("div",{className:"tool-settings-scroll h-full min-h-0 flex-1 overflow-y-auto rounded-[10px] border border-[#e1e1e1] bg-white p-[15px]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-[10px]",children:[t?e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-[8px] rounded-[5px] bg-[#e8e8e8] px-[10px] h-[26px]",children:[e.jsx(kl,{className:"h-[10px] w-[10px] shrink-0 text-black"}),e.jsx("input",{type:"text",value:L,autoFocus:!0,onChange:F=>P(F.currentTarget.value),onBlur:()=>x(L),onKeyDown:W,className:"min-w-0 flex-1 bg-transparent text-[12px] font-medium tracking-[-0.24px] text-black outline-none"})]}):e.jsxs("button",{type:"button",onClick:h,className:"flex min-w-0 max-w-full items-center gap-[8px] rounded-[5px] bg-[#e8e8e8] px-[10px] h-[26px]",children:[e.jsx(kl,{className:"h-[10px] w-[10px] shrink-0 text-black"}),e.jsx("span",{className:"truncate text-[12px] font-medium tracking-[-0.24px] text-black",children:A||"Tool Name"})]}),e.jsx("button",{type:"button",onClick:c,className:"flex h-[26px] w-[26px] shrink-0 items-center justify-center rounded-[5px] bg-black text-white transition-opacity hover:opacity-85","aria-label":"Close tool settings",children:e.jsx(Qo,{className:"h-[12px] w-[12px]"})})]}),e.jsx("div",{className:"mt-[15px] h-px w-full bg-[#e1e1e1]"}),e.jsxs("div",{className:"mt-[15px] flex flex-col gap-[25px]",children:[e.jsxs("section",{className:"flex flex-col gap-[10px]",children:[e.jsx("h3",{className:"text-[12px] font-normal tracking-[-0.24px] text-black",children:"Tool Description"}),e.jsxs("div",{className:"rounded-[10px] bg-[#e8e8e8] p-[15px]",children:[e.jsx("textarea",{ref:he,value:j,onChange:F=>i(F.currentTarget.value.slice(0,Vi)),rows:1,maxLength:Vi,placeholder:"Describe this tool...",className:"w-full resize-none overflow-hidden bg-transparent text-[12px] leading-[1.4] tracking-[-0.24px] text-black outline-none placeholder:text-[#7d7d7d]","data-testid":xn.toolSettingsPanel.descriptionTextarea}),e.jsxs("div",{className:"mt-[20px] text-right text-[10px] font-medium tracking-[-0.2px] text-[#7d7d7d]","data-testid":xn.toolSettingsPanel.descriptionCounter,children:[j.length,"/",Vi]})]})]}),e.jsxs("section",{className:"flex flex-col gap-[10px]",children:[e.jsx("h3",{className:"text-[12px] font-normal tracking-[-0.24px] text-black",children:"Tags"}),e.jsxs("div",{className:"flex h-[36px] items-center rounded-[10px] bg-[#e8e8e8] px-[15px]",children:[e.jsx("input",{type:"text",value:V,onBlur:$,onChange:F=>re(F.currentTarget.value),onKeyDown:ne,placeholder:"Add Tags",className:"min-w-0 flex-1 bg-transparent text-[12px] tracking-[-0.24px] text-black outline-none placeholder:text-[#7d7d7d]"}),e.jsx("button",{type:"button",onClick:$,className:"flex h-[20px] w-[20px] items-center justify-center text-black","aria-label":"Add tag",children:e.jsx(Bi,{className:"h-[12px] w-[12px]"})})]}),e.jsx("div",{className:"flex flex-wrap gap-[5px]",children:O.map(F=>e.jsxs("button",{type:"button",onClick:()=>u(F),className:"flex h-[26px] items-center gap-[5px] rounded-[5px] border border-[#e1e1e1] bg-white px-[10px] text-[10px] font-medium tracking-[-0.2px] text-black",children:[e.jsx(Hr,{className:"h-[10px] w-[10px]"}),e.jsx("span",{children:F})]},F))}),s&&I?e.jsxs("div",{className:"mt-[5px] flex flex-col gap-[8px] rounded-[10px] border border-[#e1e1e1] bg-[#f8f8f8] p-[10px]",children:[e.jsx("h4",{className:"text-[10px] font-medium tracking-[-0.2px] text-[#7d7d7d]",children:"System Tags"}),z?e.jsx("div",{className:"flex flex-col gap-[8px]",children:ue.map(F=>F.tags.length>0?e.jsxs("div",{className:"flex flex-col gap-[5px]",children:[e.jsx("div",{className:"text-[10px] font-medium tracking-[-0.2px] text-[#7d7d7d]",children:F.label}),e.jsx("div",{className:"flex flex-wrap gap-[5px]",children:F.tags.map(te=>e.jsx("span",{className:"rounded-[5px] border border-[#d8d8d8] bg-white px-[10px] py-[6px] text-[10px] font-medium tracking-[-0.2px] text-[#333]",children:te},`${F.key}-${te}`))})]},F.key):null)}):e.jsx("div",{className:"text-[10px] font-medium tracking-[-0.2px] text-[#7d7d7d]",children:"No system tags"})]}):null]}),e.jsxs("section",{className:"flex flex-col gap-[10px]",children:[e.jsx("h3",{className:"text-[12px] font-normal tracking-[-0.24px] text-black",children:"Static cover"}),e.jsxs("div",{className:"relative overflow-hidden rounded-[10px] bg-[#f3f3f3]",style:ee,children:[ae?e.jsx("img",{src:ae,alt:"",className:"h-full w-full object-cover"}):e.jsx("div",{className:"flex h-full w-full items-center justify-center bg-[#e8e8e8] text-[10px] font-medium tracking-[-0.2px] text-[#7d7d7d]",children:"No static cover"}),e.jsxs("button",{type:"button",onClick:()=>{var F;return(F=X.current)==null?void 0:F.click()}
59,disabled:r,className:"absolute bottom-[10px] left-[10px] flex h-[26px] items-center gap-[5px] rounded-[5px] border border-[#e1e1e1] bg-white px-[10px] text-[10px] font-medium tracking-[-0.2px] text-black disabled:opacity-60",children:[r?e.jsx(In,{className:"h-[10px] w-[10px] animate-spin"}):e.jsx(Fi,{className:"h-[10px] w-[10px]"}),e.jsx("span",{children:"Change"})]}),e.jsx("input",{ref:X,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:F=>{var Le;const te=(Le=F.currentTarget.files)==null?void 0:Le[0];te&&_(te),F.currentTarget.value=""}})]}),e.jsx("div",{className:"text-[10px] font-medium tracking-[-0.2px] text-[#7d7d7d]",children:T}),e.jsxs("button",{type:"button",onClick:l,disabled:r,className:"flex h-[36px] items-center justify-center gap-[8px] rounded-[10px] border border-[#e1e1e1] bg-white px-[15px] text-[12px] font-medium tracking-[-0.24px] text-black disabled:opacity-60",children:[r?e.jsx(In,{className:"h-[12px] w-[12px] animate-spin"}):e.jsx(nh,{className:"h-[12px] w-[12px]"}),e.jsx("span",{children:"Screenshot Cover"})]})]}),e.jsxs("section",{className:"flex flex-col gap-[10px]",children:[e.jsx("h3",{className:"text-[12px] font-normal tracking-[-0.24px] text-black",children:"Dynamic cover"}),e.jsxs("div",{className:"rounded-[10px] border border-dashed border-[#e8e8e8] p-[10px]",children:[e.jsx("div",{className:Wt("relative flex items-center justify-center overflow-hidden rounded-[5px] bg-[#e8e8e8]",ve?"border border-[#e1e1e1]":null),style:ee,children:ve?e.jsxs(e.Fragment,{children:[e.jsx(Gi,{tool:a,autoPlay:!0,className:"pointer-events-none absolute inset-0",size:"small"}),e.jsxs("button",{type:"button",onClick:()=>{var F;return(F=je.current)==null?void 0:F.click()},disabled:r,className:"absolute bottom-[10px] left-[10px] z-10 flex h-[26px] items-center gap-[5px] rounded-[5px] border border-[#e1e1e1] bg-white px-[10px] text-[10px] font-medium tracking-[-0.2px] text-black disabled:opacity-60",children:[r?e.jsx(In,{className:"h-[10px] w-[10px] animate-spin"}):e.jsx(Fi,{className:"h-[10px] w-[10px]"}),e.jsx("span",{children:"Change"})]})]}):e.jsxs("button",{type:"button",onClick:()=>{var F;return(F=je.current)==null?void 0:F.click()},disabled:r,className:"flex h-full w-full items-center justify-center gap-[5px] text-[10px] font-medium tracking-[-0.2px] text-[#7d7d7d] disabled:opacity-60",children:[r?e.jsx(In,{className:"h-[12px] w-[12px] animate-spin"}):e.jsx(Fi,{className:"h-[12px] w-[12px]"}),e.jsx("span",{children:"Upload Video Cover (5mb Max)"})]})}),e.jsx("input",{ref:je,type:"file",accept:"video/mp4,video/webm",className:"hidden",onChange:F=>{var Le;const te=(Le=F.currentTarget.files)==null?void 0:Le[0];te&&w(te),F.currentTarget.value=""}})]}),e.jsx("div",{className:"text-[10px] font-medium tracking-[-0.2px] text-[#7d7d7d]",children:T}),e.jsxs("button",{type:"button",onClick:y,disabled:r,className:"flex h-[36px] items-center justify-center gap-[8px] rounded-[10px] border border-[#e1e1e1] bg-white px-[15px] text-[12px] font-medium tracking-[-0.24px] text-black disabled:opacity-60",children:[r?e.jsx(In,{className:"h-[12px] w-[12px] animate-spin"}):e.jsx(sh,{className:"h-[12px] w-[12px]"}),e.jsx("span",{children:"Record Cover"})]})]})]})]})},kn={root:"tool-versions-panel",loading:"tool-versions-panel-loading",empty:"tool-versions-panel-empty",closeButton:"tool-versions-panel-close",versionRow:"tool-versions-panel-row",optionsButton:"tool-versions-panel-options",optionsMenu:"tool-versions-panel-options-menu",badgeCurrent:"tool-versions-panel-badge-current",badgeLive:"tool-versions-panel-badge-live",dateGroup:"tool-versions-panel-date-group",renameInput:"tool-versions-panel-rename-input"};function A0({testId:t,label:s,onClick:r,children:a}){return e.jsx("button",{type:"button","data-testid":t,onClick:r,"aria-label":s,title:s,className:"flex size-[24px] shrink-0 items-center justify-center transition-colors hover:bg-[var(--product-grey-01)]",style:{color:"var(--product-grey-05)"},children:e.jsx("span",{className:"block size-[15px]",children:a})})}const tu=`${pp} hover:bg-[var(--product-white-00)] focus:bg-[var(--product-white-00)] data-[highlighted]:bg-[var(--product-white-00)]`;function P0({onRename:t,onRestore:s,triggerRef:r}){const a=n.useRef(!1);return e.jsx("div",{className:"shrink-0",onClick:o=>o.stopPropagation(),children:e.jsxs(rh,{children:[e.jsx(ah,{asChild:!0,children:e.jsx("button",{ref:r,type:"button","data-testid":kn.optionsButton,"aria-label":"Version options",title:"Version options",className:Wt("flex size-[24px] shrink-0 items-center justify-center transition-colors","text-[var(--product-grey-05)] hover:bg-[var(--product-grey-01)]","data-[state=open]:bg-[var(--product-grey-02)] data-[state=open]:text-[var(--product-black-00)]"),children:e.jsx("span",{className:"block size-[15px]",children:e.jsx(Bh,{className:"size-full"})})})}),e.jsxs(oh,{side:"right",align:"start",sideOffset:0,onCloseAutoFocus:o=>{a.current&&(a.current=!1,o.preventDefault())},"data-testid":kn.optionsMenu,className:Wt(ad,"max-h-[300px] w-[137px] overflow-y-auto"),children:[e.jsx(Od,{className:tu,onClick:s,children:e.jsx("span",{className:Dl,children:"Restore"})}),e.jsx(Od,{className:tu,onClick:()=>{a.current=!0,t()},children:e.jsx("span",{className:Dl,children:"Rename"})})]})]})})}function O0({row:t,onPreview:s,onRestore:r,onRename:a}){const[o,i]=n.useState(!1),[l,c]=n.useState(t.displayName),x=n.useRef(t.displayName),h=n.useRef(null),y=n.useRef(!1),u=n.useRef(null);function w(j=!1){i(!1),setTimeout(()=>{var A;y.current=!1,j&&((A=u.current)==null||A.focus())},0)}function _(){x.current=t.displayName,c(t.displayName),y.current=!0,i(!0)}n.useEffect(()=>{if(!o)return;const j=setTimeout(()=>{var A,I;(A=h.current)==null||A.focus(),(I=h.current)==null||I.select()},0);return()=>clearTimeout(j)},[o]);function v(j=!1){w(j);const A=l.trim();
59A!==x.current.trim()&&(A===""&&!t.hasStoredName||a(A))}return e.jsxs("div",{"data-testid":kn.versionRow,"data-previewing":t.isPreviewing?"true":void 0,onClick:()=>{y.current||s()},className:Wt("flex w-full gap-[8px] py-[6px] pl-[6px] pr-[6px] transition-colors",o?"cursor-default":"cursor-pointer",t.isPreviewing&&!o?"bg-[var(--product-grey-02)]":"bg-transparent hover:bg-[var(--product-grey-01)]"),children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-start gap-[8px]",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-[6px]",children:[o?e.jsx("div",{className:"w-[165px]",children:e.jsx("input",{ref:h,"data-testid":kn.renameInput,className:"w-full min-w-[24px] rounded-none border-0 bg-[var(--product-grey-02)] p-[3px] text-product-text text-[var(--product-black-00)] outline-none",value:l,onChange:j=>c(j.target.value),onBlur:()=>v(),onKeyDown:j=>{j.key==="Enter"&&v(),j.key==="Escape"&&w(!0)},onClick:j=>j.stopPropagation()})}):e.jsx("p",{className:"max-w-[165px] text-product-text text-[var(--product-black-00)] [word-break:break-word]",children:t.displayName}),e.jsx("p",{className:"whitespace-nowrap text-product-tiny text-[var(--product-grey-05)]",children:t.timestamp})]}),e.jsxs("div",{className:"flex shrink-0 items-start gap-[4px]",children:[t.isLive?e.jsx(Fc,{"data-testid":kn.badgeLive,size:"small",skin:"main",children:"Live"}):null,t.isCurrent?e.jsx(Fc,{"data-testid":kn.badgeCurrent,size:"small",skin:"black",children:"Current"}):null]})]}),e.jsx(P0,{onRename:_,onRestore:r,triggerRef:u})]})}function L0({groups:t,loading:s,onClose:r,onPreview:a,onRestore:o,onRename:i}){return e.jsxs("div",{"data-testid":kn.root,className:"flex h-full w-full flex-col overflow-hidden border border-solid",style:{background:"var(--product-white-00)",borderColor:"var(--product-grey-02)",fontFamily:"var(--product-font)",fontWeight:400},children:[e.jsx("div",{className:"flex shrink-0 flex-col items-start border-b border-solid py-[8px]",style:{borderColor:"var(--product-grey-02)"},children:e.jsxs("div",{className:"flex w-full items-start justify-between overflow-hidden py-[8px] pl-[12px] pr-[8px]",children:[e.jsxs("div",{className:"flex min-w-0 flex-col gap-[6px] py-[3px]",children:[e.jsx("p",{className:"text-product-title text-[var(--product-black-00)]",children:"Versions history"}),e.jsx("p",{className:"text-product-text text-[var(--product-grey-05)]",children:"Click on a version to preview it on the canvas"})]}),e.jsx("div",{className:"flex shrink-0 items-center",children:e.jsx(A0,{testId:kn.closeButton,label:"Close versions panel",onClick:r,children:e.jsx(Zn,{className:"size-full"})})})]})}),e.jsx("div",{className:"chat-scroll min-h-0 flex-1 overflow-y-auto",children:s?e.jsx("p",{"data-testid":kn.loading,className:"px-[16px] py-[12px] text-product-text text-[var(--product-grey-05)]",children:"Loading…"}):t.length===0?e.jsx("p",{"data-testid":kn.empty,className:"px-[16px] py-[12px] text-product-text text-[var(--product-grey-05)]",children:"No versions yet."}):t.map(l=>{var c;return e.jsxs("div",{"data-testid":kn.dateGroup,className:"flex flex-col gap-[12px] px-[16px] py-[12px]",children:[e.jsx("p",{className:"text-product-tiny text-[var(--product-grey-05)]",children:l.label}),l.rows.map(x=>e.jsx(O0,{row:x,onPreview:()=>a(x.id),onRestore:()=>o(x.id),onRename:h=>i(x.id,h)},x.id))]},`${l.label}-${((c=l.rows[0])==null?void 0:c.id)??""}`)})})]})}const _c=new Map;function nu(t){return t.replace(/^["'`]+|["'`]+$/g,"").replace(/[.!,;:]+$/g,"").trim().split(/\s+/).slice(0,5).join(" ")}function su(t,s){return t.getFullYear()===s.getFullYear()&&t.getMonth()===s.getMonth()&&t.getDate()===s.getDate()}function B0(t,s){if(su(t,s))return"Today";const r=new Date(s);return r.setDate(s.getDate()-1),su(t,r)?"Yesterday":t.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function ux(t,s="·"){if(!t)return"";const r=new Date(t),a=r.toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit"}),o=r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return`${a} ${s} ${o}`}function F0({onRename:t,onRestore:s,triggerRef:r}){const[a,o]=n.useState(!1),i=n.useRef(null);n.useEffect(()=>{if(!a)return;function c(x){i.current&&!i.current.contains(x.target)&&o(!1)}return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[a]);const l="w-full text-left px-[8px] py-[5px] rounded-[5px] text-[12px] leading-[1.4] tracking-[-0.24px] text-[#686868] hover:bg-[#e8e8e8] hover:text-black transition-colors";return e.jsxs("div",{className:"relative",ref:i,children:[e.jsx("button",{ref:r,type:"button",onClick:c=>{c.stopPropagation(),o(x=>!x)},className:"flex items-center justify-center rounded-[5px] size-[20px] hover:bg-[#f5f5f5] transition-colors shrink-0","aria-label":"Version options","data-testid":kn.optionsButton,children:e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 2.17393 10",fill:"none","aria-hidden":!0,
59children:[e.jsx("circle",{cx:"1.08696",cy:"1.08696",r:"1.08696",fill:"currentColor"}),e.jsx("circle",{cx:"1.08698",cy:"5",r:"1.08696",fill:"currentColor"}),e.jsx("circle",{cx:"1.08698",cy:"8.91304",r:"1.08696",fill:"currentColor"})]})}),a?e.jsxs("div",{className:"absolute right-0 top-full mt-1 z-50 flex flex-col gap-[5px] rounded-[10px] border border-[#e1e1e1] border-solid bg-white p-[15px] drop-shadow-[0px_4px_15px_rgba(0,0,0,0.1)] min-w-[120px]","data-testid":kn.optionsMenu,children:[e.jsx("button",{type:"button",className:l,onClick:c=>{c.stopPropagation(),o(!1),s()},children:"Restore"}),e.jsx("button",{type:"button",className:l,onClick:c=>{c.stopPropagation(),o(!1),t()},children:"Rename"})]}):null]})}function $0({impl:t,autoLabel:s,summary:r,isLive:a,isPreviewing:o,onPreview:i,onRestore:l,onRename:c,revertedFrom:x}){const[h,y]=n.useState(!1),u=t.custom_name||r||s,[w,_]=n.useState(u),v=n.useRef(u),j=n.useRef(null),A=n.useRef(!1),I=n.useRef(null);function O(T=!1){y(!1),setTimeout(()=>{var ee;A.current=!1,T&&((ee=I.current)==null||ee.focus())},0)}function L(){v.current=u,_(u),A.current=!0,y(!0)}n.useEffect(()=>{if(!h)return;const T=setTimeout(()=>{var ee,ae;(ee=j.current)==null||ee.focus(),(ae=j.current)==null||ae.select()},0);return()=>clearTimeout(T)},[h]);function P(T=!1){O(T);const ee=w.trim();ee!==v.current.trim()&&(ee===""&&!t.custom_name||c(ee))}const V="linear-gradient(147.779deg, rgb(255, 68, 71) 20.72%, rgb(255, 89, 241) 79.339%)",re=a&&!o,X=o?"border-black":re?"border-transparent":"border-[#e8e8e8]",je="#ffffff",he=re?"":"bg-white",me=re?{background:`linear-gradient(${je}, ${je}) padding-box, ${V} border-box`}:void 0;return e.jsxs("div",{className:`border border-solid ${X} ${he} flex gap-[15px] items-center p-[15px] rounded-[10px] w-full cursor-pointer ${re?"":"hover:bg-[#e8e8e8]"} transition-colors`,style:me,onClick:()=>{A.current||i()},"data-testid":kn.versionRow,"data-previewing":o?"true":void 0,children:[e.jsxs("div",{className:`flex flex-1 flex-col items-start min-w-0 ${x?"gap-[10px]":""}`,children:[e.jsxs("div",{className:"flex flex-col items-start w-full min-w-0",children:[h?e.jsx("input",{ref:j,"data-testid":kn.renameInput,className:"text-[12px] font-medium leading-[1.4] text-black tracking-[-0.24px] border border-[#e1e1e1] rounded-[4px] px-[6px] py-[2px] w-full outline-none focus:border-black",value:w,onChange:T=>_(T.target.value),onBlur:()=>P(),onKeyDown:T=>{T.key==="Enter"&&P(!0),T.key==="Escape"&&O(!0)},onClick:T=>T.stopPropagation()}):e.jsx(jp,{productFont:!1,className:"text-[12px] font-medium leading-[1.4] text-black tracking-[-0.24px] w-full",children:u}),e.jsx("p",{className:"text-[12px] leading-[1.4] text-[#686868] tracking-[-0.24px]",children:ux(t.created_date)})]}),x?e.jsxs("span",{className:"bg-[#e8e8e8] text-[#686868] text-[8px] font-medium leading-[1.4] tracking-[-0.16px] px-[8px] py-[5px] rounded-[3px] h-[20px] flex items-center",children:["Reverted from “",x,"”"]}):null]}),e.jsxs("div",{className:"flex items-center gap-[5px] shrink-0",onClick:T=>T.stopPropagation(),children:[a?e.jsx("span",{className:"text-white text-[8px] font-medium leading-[1.4] tracking-[-0.16px] px-[8px] py-[5px] rounded-[5px] h-[20px] flex items-center justify-center","data-testid":kn.badgeLive,style:{backgroundImage:"linear-gradient(147.78deg, rgb(255, 68, 71) 20.72%, rgb(255, 89, 241) 79.34%)"},children:"Live"}):null,e.jsx(F0,{onRename:L,onRestore:l,triggerRef:I})]})]})}function px({toolUuid:t,draftImplId:s,publishedImplId:r,publishedImplUuid:a,previewingId:o=null,activeVersionId:i=null,liveSnapshotId:l=null,onPreview:c,onExitPreview:x,onRestore:h,onClose:y,chatMessages:u,chromeVariant:w="legacy"}){var ue,z;const[_,v]=n.useState([]),[j,A]=n.useState(!0),I=n.useCallback(async()=>{if(!t){A(!1);return}A(!0);try{const W=(await D.entities.ToolImplementation.filter({tool_uuid:t})).filter(ne=>ne.source_message_id).sort((ne,F)=>new Date(F.created_date??0).getTime()-new Date(ne.created_date??0).getTime());v(W)}catch($){console.warn("[ToolVersionsPanel] Failed to load versions:",$)}finally{A(!1)}},[t]);n.useEffect(()=>{I()},[I]);const[O,L]=n.useState({});n.useEffect(()=>{if(!t||_.length===0)return;let $=!1;const W={};for(const F of _){const te=_c.get(F.id);te&&(W[F.id]=te)}Object.keys(W).length>0&&L(F=>({...F,...W}));const ne=_.filter(F=>!_c.has(F.id));if(ne.length!==0)return(async()=>{var F,te;try{let Le=u&&u.length>0?u:[];if(Le.length===0){const pe=await D.entities.Tool.filter({uuid:t}),J=(F=pe==null?void 0:pe[0])==null?void 0:F.chat_session_id;if(J){const Ce=await D.entities.ChatSession.get(J);Le=(Ce==null?void 0:Ce.messages)??[]}}const Ke=pe=>(pe==null?void 0:pe.tool_snapshot_id)??(pe==null?void 0:pe.toolSnapshotId),oe=pe=>(pe==null?void 0:pe.role)==="user"&&!((pe==null?void 0:pe.auto_fix)??(pe==null?void 0:pe.autoFix))&&typeof(pe==null?void 0:pe.content)=="str
59ing"&&pe.content.trim(),st=new Map,rt=new Map;let q="";Le.forEach(pe=>{oe(pe)&&(q=pe.content);const J=Ke(pe);J&&q&&rt.set(String(J),q)});const we=pe=>{const J=Le.findIndex(Ce=>String(Ce==null?void 0:Ce.id)===pe);if(J===-1)return"";for(let Ce=J;Ce>=0;Ce--)if(oe(Le[Ce]))return Le[Ce].content;return""};for(const pe of _){const J=rt.get(String(pe.id))||(pe.source_message_id?we(String(pe.source_message_id)):"");J&&st.set(pe.id,J)}const De={},ie=[];for(const pe of ne){if((te=pe.source_message_id)!=null&&te.startsWith("restore:")){De[pe.id]="Restored earlier version";continue}const J=st.get(pe.id);J&&ie.push({id:pe.id,request:J.slice(0,400)})}if(!$&&(ie.length>0||Object.keys(De).length>0)){const pe={...De};for(const J of ie)pe[J.id]=nu(J.request);L(J=>({...J,...pe}))}if(ie.length>0){const pe=await D.integrations.Core.InvokeLLM({model:"gpt_5_mini",prompt:`You label versions of a web tool in a version-history panel. For each version, write a concise label of AT MOST 5 words describing what the user asked for in that version. Title case, concrete, no quotes, no trailing punctuation.
60
61Versions (JSON): ${JSON.stringify(ie)}
62
63Return JSON: { "summaries": [ { "id": "<id>", "summary": "<label>" } ] } — one per id.`,response_json_schema:{type:"object",properties:{summaries:{type:"array",items:{type:"object",properties:{id:{type:"string"},summary:{type:"string"}},required:["id","summary"]}}},required:["summaries"]}}),J=(pe==null?void 0:pe.summaries)??[];for(const Ce of J)if(Ce!=null&&Ce.id&&typeof Ce.summary=="string"){const se=nu(Ce.summary);se&&(De[Ce.id]=se)}}for(const[pe,J]of Object.entries(De))_c.set(pe,J);!$&&Object.keys(De).length>0&&L(pe=>({...pe,...De}))}catch(Le){console.warn("[ToolVersionsPanel] Failed to summarize versions:",Le)}})(),()=>{$=!0}},[t,_,u]);const P=async($,W)=>{try{await D.entities.ToolImplementation.update($,{custom_name:W||null}),v(ne=>ne.map(F=>F.id===$?{...F,custom_name:W||null}:F)),gs.capture(Fa.VERSION_RENAMED,{impl_id:$,has_custom_name:!!W})}catch(ne){console.warn("[ToolVersionsPanel] Failed to rename version:",ne)}},V=async $=>{await h($),await I()},re=new Date,X=[];for(const $ of _){const W=$.created_date?new Date($.created_date):re,ne=B0(W,re),F=X[X.length-1];F&&F.label===ne?F.items.push($):X.push({label:ne,items:[$]})}const je=_.length,he=new Map;_.forEach(($,W)=>{he.set($.id,`Version ${je-W}`)});const me=(i&&_.some($=>$.id===i)?i:null)??((ue=_.find($=>$.id===s))==null?void 0:ue.id)??((z=_[0])==null?void 0:z.id)??null,T=_.some($=>!!r&&$.id===r||!!a&&!!$.uuid&&$.uuid===a),ee=$=>{if(r&&$.id===r||a&&$.uuid&&$.uuid===a)return!0;if((r||a)&&!T){const W=l??(i?null:me);return W!=null&&$.id===W}return!1},ae=($,W)=>{if($===me){x==null||x();return}gs.capture(Fa.VERSION_PREVIEWED,{impl_id:$}),c($,W)},ve=$=>$.custom_name||O[$.id]||he.get($.id)||"Version";return w==="v2"?e.jsx(L0,{loading:j,groups:X.map($=>({label:$.label,rows:$.items.map(W=>({id:W.id,displayName:ve(W),timestamp:ux(W.created_date,"|"),hasStoredName:!!W.custom_name,isLive:ee(W),isCurrent:W.id===me,isPreviewing:W.id===o}))})),onClose:y,onPreview:$=>{const W=_.find(ne=>ne.id===$);ae($,W?ve(W):"Version")},onRestore:$=>void V($),onRename:($,W)=>void P($,W)}):e.jsxs("div",{className:"flex flex-col rounded-[10px] border border-[#e1e1e1] border-solid bg-white w-full h-full overflow-hidden","data-testid":kn.root,children:[e.jsxs("div",{className:"flex flex-col gap-[15px] p-[15px] pb-0 shrink-0",children:[e.jsxs("div",{className:"flex flex-col items-start w-full",children:[e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("span",{className:"text-[12px] font-medium leading-[1.4] text-black tracking-[-0.24px]",children:"Versions History"}),e.jsx("button",{type:"button",onClick:y,className:"flex items-center justify-center size-[20px] rounded-[5px] hover:bg-[#f5f5f5] transition-colors shrink-0","aria-label":"Close versions panel","data-testid":kn.closeButton,children:e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 8 8",fill:"none","aria-hidden":!0,children:e.jsx("path",{d:"M1 1L7 7M7 1L1 7",stroke:"black",strokeWidth:"1.2",strokeLinecap:"round"})})})]}),e.jsx("p",{className:"text-[12px] leading-[1.4] text-[#686868] tracking-[-0.24px] w-full",children:"Click a version to preview it on the canvas"})]}),e.jsx("div",{className:"h-px bg-[#e1e1e1]"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-[25px] py-[15px] min-h-0",children:j?e.jsx("p",{className:"text-[12px] leading-[1.4] text-[#686868] tracking-[-0.24px]","data-testid":kn.loading,children:"Loading…"}):_.length===0?e.jsx("p",{className:"text-[12px] leading-[1.4] text-[#686868] tracking-[-0.24px]","data-testid":kn.empty,children:"No versions yet."}):e.jsx("div",{className:"flex flex-col gap-[15px]",children:X.map($=>{var W;return e.jsxs("div",{className:"flex flex-col gap-[15px]",children:[e.jsx("p",{className:"text-[12px] leading-[1.4] text-[#686868] tracking-[-0.24px]",children:$.label}),e.jsx("div",{className:"flex flex-col gap-[5px]",children:$.items.map(ne=>e.jsx($0,{impl:ne,autoLabel:he.get(ne.id)??"Version",summary:O[ne.id],isLive:ee(ne),isPreviewing:ne.id===o,onPreview:()=>ae(ne.id,ne.custom_name||O[ne.id]||he.get(ne.id)||"Version"),onRestore:()=>V(ne.id),onRename:F=>P(ne.id,F)},ne.id))})]},`${$.label}-${((W=$.items[0])==null?void 0:W.id)??""}`)})})})]})}const Ii={root:"version-preview-bar",label:"version-preview-bar-label",hint:"version-preview-bar-hint",exitButton:"version-preview-bar-exit",restoreButton:"version-preview-bar-restore"},xx=({versionName:t,onExitPreview:s,onRestore:r,isRestoring:a=!1})=>e.jsxs("div",{"data-testid":Ii.root,className:"flex w-full items-center justify-between gap-[10px] rounded-[10px] border border-[#e1e1e1] border-solid bg-white p-[12px] sm:gap-[15px] sm:p-[15px]",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-[8px]",children:[e.jsxs("p",{"data-testid":Ii.label,className:"min-w-0 truncate text-[12px] leading-[1.4] tracking-[-0.24px] text-black",children:["Previewing “",t,"”"]}
63),e.jsx("span",{"aria-hidden":!0,className:"shrink-0 text-[#d1d1d1]",children:"·"}),e.jsx("span",{"data-testid":Ii.hint,className:"shrink-0 whitespace-nowrap text-[12px] leading-[1.4] tracking-[-0.24px] text-[#7d7d7d]",children:"Changes won’t be saved"})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-[5px]",children:[e.jsx("button",{type:"button","data-testid":Ii.exitButton,onClick:s,disabled:a,className:"flex h-[26px] items-center justify-center whitespace-nowrap rounded-[5px] border border-[#e1e1e1] border-solid bg-white px-[10px] text-[10px] font-medium leading-[1.4] tracking-[-0.2px] text-black transition-colors hover:bg-[#f5f5f5] disabled:cursor-not-allowed disabled:opacity-50",children:"Exit preview"}),e.jsx("button",{type:"button","data-testid":Ii.restoreButton,onClick:r,disabled:a,className:"flex h-[26px] min-w-[62px] items-center justify-center whitespace-nowrap rounded-[5px] px-[10px] text-[10px] font-medium leading-[1.4] tracking-[-0.2px] text-white bg-black transition-opacity hover:opacity-90 disabled:cursor-not-allowed",children:a?e.jsx(In,{className:"size-[12px] animate-spin","aria-hidden":!0}):"Restore"})]})]});function V0({leading:t,center:s}){return e.jsx(Hs.div,{"data-testid":xn.desktopHeader.root,className:"hidden lg:flex lg:px-[20px] relative z-[20]",initial:{opacity:0,y:-10},animate:{opacity:1,y:0},transition:{duration:.5,ease:[.4,0,.2,1]},children:e.jsx("div",{className:"w-full",children:e.jsx(ih,{inverted:!0,buildButtonStyle:"secondary",slimDesktopLeading:t,slimDesktopCenter:s})})})}function fx(t,s){return t?s?{title:"Delete this tool?",description:"This will unpublish and permanently delete this tool. This cannot be undone.",confirmLabel:"Delete"}:{title:"Delete this tool?",description:"This will permanently delete the tool. This cannot be undone.",confirmLabel:"Delete"}:{title:"Discard this tool?",description:"This tool hasn't been saved. It will be lost.",confirmLabel:"Discard"}}const yl="var(--product-grey-02)",$o=`${_f}px`,H0=500,z0=24;function U0({isExiting:t=!1,belowBoxSlot:s}){const r=n.useRef(null),[a,o]=n.useState(null),[i,l]=n.useState(!1);return n.useEffect(()=>{const c=setTimeout(()=>l(!0),H0);return()=>clearTimeout(c)},[]),n.useEffect(()=>{const c=r.current;if(!c)return;const x=new ResizeObserver(()=>{const h=c.getBoundingClientRect();o({width:h.width,height:h.height})});return x.observe(c),()=>x.disconnect()},[i]),e.jsxs(Hs.div,{"data-testid":_n.canvasGuides.root,className:"absolute inset-0 flex items-center justify-center bg-[var(--product-grey-01)]",initial:{opacity:0}
63,animate:{opacity:t?0:1},transition:{duration:t?.6:1.2,ease:[.4,0,.2,1]},children:[a&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute top-0 bottom-0","data-testid":_n.canvasGuides.guideLeft,style:{left:`calc(50% - ${a.width/2}px - ${$o})`,borderColor:yl,borderLeftWidth:$o,borderLeftStyle:"solid"},"aria-hidden":!0}),e.jsx("div",{className:"absolute top-0 bottom-0","data-testid":_n.canvasGuides.guideRight,style:{left:`calc(50% + ${a.width/2}px)`,borderColor:yl,borderLeftWidth:$o,borderLeftStyle:"solid"},"aria-hidden":!0}),e.jsx("div",{className:"absolute left-0 right-0","data-testid":_n.canvasGuides.guideTop,style:{top:`calc(50% - ${a.height/2}px - ${$o})`,borderColor:yl,borderTopWidth:$o,borderTopStyle:"solid"},"aria-hidden":!0}),e.jsx("div",{className:"absolute left-0 right-0","data-testid":_n.canvasGuides.guideBottom,style:{top:`calc(50% + ${a.height/2}px)`,borderColor:yl,borderTopWidth:$o,borderTopStyle:"solid"},"aria-hidden":!0})]}),e.jsx("div",{ref:r,"data-testid":_n.canvasGuides.box,className:`flex items-center justify-center px-[11px] py-[12px] ${i?"":"size-[50px]"}`,children:i?e.jsx(Hs.p,{"data-testid":_n.canvasGuides.sentence,initial:{opacity:0}
63,animate:{opacity:1},transition:{duration:1.2,ease:[.22,1,.36,1]},className:"m-0 max-w-[60vw] text-center text-[20px] tracking-[-0.2px] text-[var(--product-grey-05)] [font-family:var(--product-font-book)]",children:"Write what you imagine and watch your creative vision come to life."}):e.jsx(wf,{className:"size-5",fill:"var(--product-grey-05)"})}),s&&a&&e.jsx(Hs.div,{"data-testid":_n.canvasGuides.belowBoxSlot,className:"absolute left-1/2 -translate-x-1/2",style:{top:`calc(50% + ${a.height/2+z0}px)`},initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2,ease:[.22,1,.36,1],delay:1.1},children:s})]})}const G0="Import source file (dev)",W0="Importing source…",q0="inline-flex items-center gap-[8px] rounded-[10px] border border-white/40 bg-white/10 px-[15px] py-[10px] text-[12px] font-medium tracking-[-0.24px] text-white backdrop-blur-sm transition-colors hover:bg-white/20 disabled:opacity-60",ru=({onImport:t,variant:s,className:r})=>{const{fileInputRef:a,importing:o,openPicker:i,handleFileChange:l}=Yf(t,{successMessage:"Source imported"}),c=o?W0:G0,x={onClick:i,disabled:o,"data-testid":xn.idleOverlay.importSourceButton};return e.jsxs(e.Fragment,{children:[s==="canvas-guides"?e.jsxs(Nn,{size:"small",priority:"secondary",skin:"filled",className:r,...x,children:[e.jsx(Fi,{className:"size-[14px]",strokeWidth:2}),e.jsx("span",{children:c})]}):e.jsxs("button",{type:"button",className:`${q0} ${r??""}`,...x,children:[e.jsx(Fi,{className:"h-[14px] w-[14px]",strokeWidth:2}),e.jsx("span",{children:c})]}),e.jsx("input",{ref:a,type:"file",accept:".html,text/html",className:"hidden","data-testid":xn.idleOverlay.importSourceInput,onChange:l})]})},au=xn.consoleErrorBadge;function K0({count:t,newDesignLayout:s=!1}){if(t<=0)return null;const r=`${t} error${t!==1?"s":""}`;return s?e.jsx(Fc,{"data-testid":au.root,size:"small",skin:"error",priority:"secondary",className:"absolute right-3 top-3 z-10",children:r}):e.jsxs("div",{"data-testid":au.root,className:"absolute top-3 right-3 z-10 flex items-center gap-1.5 bg-red-50 border border-red-200 rounded-full px-2.5 py-1 shadow-sm",children:[e.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500 animate-pulse"}),e.jsx("span",{className:"text-[10px] font-medium text-red-700",children:r})]})}function mx({coverAspectRatio:t,coverCaptureDuration:s=4,coverCaptureMode:r=null,renderCoverCaptureControls:a,coverCaptureVariant:o,onCoverCropAspectRatioChange:i,renderRecordingOverlay:l,coverCaptureWorking:c=!1,consoleErrors:x,isAdmin:h,isGenerating:y,isReverting:u,holdUntilTool:w,onCoverCaptureCancel:_,onCoverCaptureError:v,onDynamicCoverCaptured:j,onError:A,onErrorsChange:I,onNewError:O,onHealth:L,onReady:P,onStaticCoverCaptured:V,onToolAction:re,onExportedFile:X,onControlEditRequest:je,onControlMenuRequest:he,freshControlKeys:me,onControlFreshCleared:T,freshSectionLabels:ee,onSectionFreshCleared:ae,onToggleControlVisibility:ve,onDeleteControl:ue,onRenameControl:z,onReorderControls:$,onReorderSections:W,onBulkSetVisibility:ne,onBulkDeleteControls:F,onMoveControlsToSection:te,previewRef:Le,showIdleOverlay:Ke=!1,idleOverlayExiting:oe=!1,onIdleGenerate:st,newDesignLayout:rt=!1,toolData:q,autosavedControlValuesRef:we,timeline:De,onBeforeRecord:ie,onExportOpenChange:pe,onRecordingChange:J,onImportImplementation:Ce,showSourceImport:se=!1,toolHtml:Ot,toolLoaded:U=!1,toolName:mt,chatCollapsed:le=!1,onOpenProjection:Se,onTimelineToggleClick:gt,timelineToggleTestId:Fe,onPanelWidthChange:Te,getControlsSchema:Dt,onMidiMappingLearned:Dn,onMidiMappingCleared:Ct,controlsSchema:qt,showDesktopControlsPanel:Jn,timelineActive:dn,trackedControlKeys:H,onToggleTrack:be,onMotionTabChange:xe,revealControl:Y,toolLoadKey:Ue,toolId:ut,presetController:Ye}){const bt=se&&!!Ce,Sn=td(),Hn=Sn||le;return e.jsxs("div",{className:`flex-1 min-h-0 flex flex-col relative overflow-hidden ${rt?"":"rounded-[10px]"}`,children:[e.jsx(Zf,{ref:Le,toolHtml:Ot,toolName:mt,toolData:q,autosavedControlValuesRef:we,timeline:De,onBeforeRecord:ie,onExportOpenChange:pe,onRecordingChange:J,onImportImplementation:Ce,coverAspectRatio:t,coverCaptureDuration:s,coverCaptureMode:r,renderCoverCaptureControls:a,coverCaptureVariant:o,onCoverCropAspectRatioChange:i,renderRecordingOverlay:l,coverCaptureWorking:c,isAdmin:h,onCoverCaptureCancel:_,onCoverCaptureError:v,onDynamicCoverCaptured:j,onReady:P,onError:A,onErrorsChange:I,onNewError:O,onHealth:L,onStaticCoverCaptured:V,onToolAction:re,onExportedFile:X,onControlEditRequest:je,onControlMenuRequest:he,freshControlKeys:me,onControlFreshCleared:T,freshSectionLabels:ee,onSectionFreshCleared:ae,onToggleControlVisibility:ve,onDeleteControl:ue,onRenameControl:z,onReorderControls:$,onReorderSections:W,onBulkSetVisibility:ne,onBulkDeleteControls:F,onMoveControlsToSection:te,isGenerating:y,isReverting:u,holdUntilTool:w,toolLoaded:U,chatCollapsed:le,newDesignLayout:rt,onOpenProjection:Se,onTimelineToggleClick:gt,timelineToggleTestId:Fe,onPanelWidthChange:Te,getControlsSchema:Dt,onMidiMappingLearned:Dn,onMidiMappingCleared:Ct,controlsSchema:qt,showDesktopControl
63sPanel:Jn,timelineActive:dn,trackedControlKeys:H,onToggleTrack:be,onMotionTabChange:xe,revealControl:Y,toolLoadKey:Ue,toolId:ut,presetController:Ye}),Ke&&rt&&e.jsx("div",{"data-testid":xn.idleOverlay.canvasGuidesFrame,className:"absolute inset-0 z-10 overflow-hidden pointer-events-none",style:{left:Hn?0:wl},children:e.jsx(U0,{isExiting:oe,belowBoxSlot:bt&&!oe&&!Sn?e.jsx("div",{className:"pointer-events-auto",children:e.jsx(ru,{variant:"canvas-guides",onImport:Ce})}):void 0})}),Ke&&!rt&&e.jsxs("div",{className:`absolute inset-0 z-10 rounded-[10px] overflow-hidden ${le?"":"left-[330px]"}`,children:[e.jsx(lh,{isExiting:oe}),e.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center px-[40px]",children:[e.jsx(Hs.div,{className:"text-center",initial:{opacity:0,y:20},animate:{opacity:oe?0:1,y:oe?-20:0},transition:oe?{duration:.6,ease:[.4,0,.2,1]}:{duration:1.2,ease:[.22,1,.36,1],delay:.5},style:{fontFamily:"'Neue Haas Grotesk Display Pro', system-ui, sans-serif",fontSize:34,fontWeight:500,color:"white",letterSpacing:"-0.68px",lineHeight:1.1},children:e.jsx("p",{className:"m-0",children:"Write what you imagine and watch your creative vision come to life."})}),bt&&!oe&&e.jsx(Hs.div,{className:"mt-[24px]",initial:{opacity:0}
63,animate:{opacity:1},transition:{duration:1.2,ease:[.22,1,.36,1],delay:1.1},children:e.jsx(ru,{variant:"idle-overlay",onImport:Ce})})]})]}),e.jsx(K0,{count:x.filter(xa=>xa.level!=="warning").length,newDesignLayout:rt})]})}function hx({deleteDialogContent:t,embedPreviewHtml:s,isDeleting:r,isPublishing:a,isRepublishing:o,showPublishSuccessDialog:i,setShowPublishSuccessDialog:l,toolSlug:c,newToolName:x,onCloseDeleteDialog:h,onClosePublishAsNewDialog:y,onClosePublishDialog:u,onCloseUnpublishDialog:w,onCloseUpdateDialog:_,onDeleteTool:v,onPublish:j,onRemixAsNew:A,onSetNewToolName:I,onSetToolDescription:O,onSetToolName:L,onSetVisibility:P,onUnpublish:V,onUpdate:re,setShowDeleteDialog:X,setShowPublishAsNewDialog:je,setShowPublishDialog:he,setShowUnpublishDialog:me,setShowUpdateDialog:T,showDeleteDialog:ee,showPublishAsNewDialog:ae,showPublishDialog:ve,showUnpublishDialog:ue,showUpdateDialog:z,toolDescription:$,toolName:W,visibility:ne}){const{sendModalClicked:F}=nd();Fr({open:ve,modalName:"tool_publish_modal",origin:"tool_editor_publish_controls"}),Fr({open:z,modalName:"tool_update_published_modal",origin:"tool_editor_publish_controls"}),Fr({open:ae,modalName:"tool_remix_modal",origin:"tool_editor_publish_controls"}),Fr({open:ue,modalName:"tool_unpublish_modal",origin:"tool_editor_publish_controls"}),Fr({open:ee,modalName:"tool_delete_modal",origin:"tool_editor_publish_controls"}),Fr({open:i,modalName:"tool_publish_success_modal",origin:"tool_editor_publish_controls"});const te=ne==="public"?"It's now visible on your profile and in the gallery.":"Only people with the link can view it.",Le="Your tool is published",Ke=c?Cf(c,jf.appId):"",oe=Ke,st=ne==="public"?"Published (Public)":"Published (Private link)",rt=()=>e.jsxs("div",{className:"flex w-[274px] flex-col gap-[5px] rounded-[10px] border border-[#e1e1e1] bg-white p-[15px] shadow-[0px_4px_15px_rgba(0,0,0,0.1)]",children:[e.jsxs("div",{className:"rounded-[5px] bg-white px-[10px] py-[12px]",children:[e.jsx("p",{className:"text-[12px] leading-[1.4] tracking-[-0.24px] text-black",children:"Draft (Private)"}),e.jsx("p",{className:"mt-[3px] text-[10px] leading-[1.4] tracking-[-0.2px] text-[#7d7d7d]",children:"Only you can view and edit this tool in your workspace. Not shareable yet."})]}),e.jsxs("button",{type:"button",onClick:()=>P("private"),className:`rounded-[10px] border px-[15px] py-[12px] text-left transition-colors ${ne==="private"?"border-[#e8e8e8] bg-[#e8e8e8]":"border-transparent bg-white hover:bg-[#f5f5f5]"}`,children:[e.jsx("p",{className:"text-[12px] leading-[1.4] tracking-[-0.24px] text-black",children:"Published (Private link)"}),e.jsx("p",{className:"mt-[3px] text-[10px] leading-[1.4] tracking-[-0.2px] text-[#7d7d7d]",children:"Only people with the link can view it. Not shown in your profile or gallery. Requires a Brik account to access."})]}),e.jsxs("button",{type:"button",onClick:()=>P("public"),className:`rounded-[5px] border px-[10px] py-[12px] text-left transition-colors ${ne==="public"?"border-[#e8e8e8] bg-[#e8e8e8]":"border-transparent bg-white hover:bg-[#f5f5f5]"}`,children:[e.jsx("p",{className:"text-[12px] leading-[1.4] tracking-[-0.24px] text-black",children:"Published (Public)"}),e.jsx("p",{className:"mt-[3px] text-[10px] leading-[1.4] tracking-[-0.2px] text-[#7d7d7d]",children:"Visible on your profile and in the gallery. Anyone can discover and use it. Best for sharing work with the community."})]})]}),q=()=>e.jsxs(Ga,{children:[e.jsx(Wa,{asChild:!0,children:e.jsxs("button",{type:"button",className:"flex h-[36px] w-full items-center justify-between rounded-[10px] bg-[#e8e8e8] px-[15px] text-[12px] leading-[1.4] tracking-[-0.24px] text-black",children:[e.jsx("span",{children:st}),e.jsx("span",{className:"text-black",children:"⌄"})]})}),e.jsx(qa,{align:"start",side:"bottom",sideOffset:5,className:"w-auto border-0 bg-transparent p-0 shadow-none",children:rt()})]});return e.jsxs(e.Fragment,{children:[e.jsx(la,{open:ve,onOpenChange:he,children:e.jsxs(ca,{className:"sm:max-w-[326px] gap-0 rounded-[10px] border border-[#e1e1e1] bg-white p-[15px] shadow-[0px_4px_15px_rgba(0,0,0,0.1)] [&>button]:hidden","aria-describedby":void 0,children:[e.jsx(da,{className:"sr-only",children:"Publish tool"}),e.jsxs("div",{className:"flex flex-col gap-[15px]",children:[e.jsxs("div",{className:"flex flex-col gap-[3px]",children:[e.jsx("p",{className:"text-[12px] font-medium leading-[1.4] tracking-[-0.24px] text-black",children:"Tool Visibility Options"}),e.jsx("p",{className:"text-[10px] leading-[1.4] tracking-[-0.2px] text-[#7d7d7d]",children:"Your tool is auto-saved. Publishing controls who can see and use it."})]}),e.jsxs("div",{className:"flex flex-col gap-[5px]",children:[q(),e.jsx("button",{onClick:j,disabled:a,className:"flex h-[36px] w-full items-center justify-center gap-[8px] rounded-[10px] border border-[#e1e1e1] bg-black px-[15px] text-[12px] font-medium leading-[1.4] tracking-[-0.24px] text-white transition-colors hover:bg-[#111] disabled:opacity-70",children:a?e.jsxs(e.Fragment,{children:[e.jsx(In,{className:"h-3 w-3 animate-spin"}),"Publishing..."]}
63):e.jsxs(e.Fragment,{children:[e.jsx($c,{className:"h-3 w-3"}),"Publish"]})})]})]})]})}),e.jsx(la,{open:z,onOpenChange:T,children:e.jsxs(ca,{className:"sm:max-w-[326px] gap-0 rounded-[10px] border border-[#e1e1e1] bg-white p-[15px] shadow-[0px_4px_15px_rgba(0,0,0,0.1)] [&>button]:hidden","aria-describedby":void 0,children:[e.jsx(da,{className:"sr-only",children:"Update published version"}),e.jsxs("div",{className:"flex flex-col gap-[15px]",children:[e.jsxs("div",{className:"flex flex-col gap-[3px]",children:[e.jsx("p",{className:"text-[12px] font-medium leading-[1.4] tracking-[-0.24px] text-black",children:"Tool Visibility Options"}),e.jsx("p",{className:"text-[10px] leading-[1.4] tracking-[-0.2px] text-[#7d7d7d]",children:"Your tool is auto-saved. Publishing controls who can see and use it."})]}),e.jsxs("div",{className:"flex flex-col gap-[5px]",children:[q(),e.jsx("button",{onClick:re,disabled:o,className:"flex h-[36px] w-full items-center justify-center gap-[8px] rounded-[10px] border border-[#e1e1e1] bg-black px-[15px] text-[12px] font-medium leading-[1.4] tracking-[-0.24px] text-white transition-colors hover:bg-[#111] disabled:opacity-70",children:o?e.jsxs(e.Fragment,{children:[e.jsx(In,{className:"h-3 w-3 animate-spin"}),"Updating..."]}):e.jsxs(e.Fragment,{children:[e.jsx($c,{className:"h-3 w-3"}),"Publish"]})})]})]})]})}),e.jsx(la,{open:ae,onOpenChange:we=>{je(we),we||I("")},children:e.jsxs(ca,{className:"sm:max-w-[400px] p-0 overflow-hidden rounded-[5px] gap-0 border-0","aria-describedby":void 0,children:[e.jsx(da,{className:"sr-only",children:"Remix"}),e.jsxs("div",{className:"px-5 pt-5 pb-5 flex flex-col gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-medium text-[#111]",children:"Remix"}),e.jsx("p",{className:"text-[12px] text-[#888] mt-1.5 leading-relaxed",children:"Create a remixed version of this tool. Your existing published tool will remain unchanged."})]}),e.jsx("input",{type:"text",value:x,onChange:we=>I(we.target.value),placeholder:`${W} (Remix)`,className:"w-full px-4 py-3 text-sm font-medium border border-[#e5e5e5] rounded-[12px] outline-none focus:border-[#bbb] transition-colors bg-[#fafafa]"}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("button",{onClick:A,className:"w-full h-[44px] rounded-[12px] bg-[#2d2d2d] text-white text-sm font-medium hover:bg-[#444] transition-colors",children:"Remix"}),e.jsx("button",{onClick:y,type:"button",className:"w-full h-[44px] rounded-[12px] bg-[#f4f4f4] text-[#666] text-sm font-medium hover:bg-[#eaeaea] transition-colors",onClickCapture:()=>F({modal_name:"tool_remix_modal",origin:"tool_editor_publish_controls",button_name:"tool_remix_modal_cancel",button_type:"button"}),children:"Cancel"})]})]})]})}),e.jsx(la,{open:ue,onOpenChange:me,children:e.jsxs(ca,{className:"sm:max-w-[400px] p-0 overflow-hidden rounded-[5px] gap-0 border-0","aria-describedby":void 0,children:[e.jsx(da,{className:"sr-only",children:"Unpublish tool"}),e.jsxs("div",{className:"px-5 pt-5 pb-5 flex flex-col gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-medium text-[#111]",children:"Unpublish tool"}),e.jsx("p",{className:"text-[12px] text-[#888] mt-1.5 leading-relaxed",children:"This will make the tool private. Anyone with the link will no longer be able to view it."})]}),e.jsxs("div",{className:"flex flex-col gap-2 mt-1",children:[e.jsx("button",{onClick:V,className:"w-full h-[44px] rounded-[12px] bg-red-600 text-white text-sm font-medium hover:bg-red-700 transition-colors",children:"Unpublish"}),e.jsx("button",{onClick:w,type:"button",className:"w-full h-[44px] rounded-[12px] bg-[#f4f4f4] text-[#666] text-sm font-medium hover:bg-[#eaeaea] transition-colors",onClickCapture:()=>F({modal_name:"tool_unpublish_modal",origin:"tool_editor_publish_controls",button_name:"tool_unpublish_modal_cancel",button_type:"button"}),children:"Cancel"})]})]})]})}),e.jsx(la,{open:ee,onOpenChange:we=>{r||X(we)},children:e.jsxs(ca,{className:"sm:max-w-[400px] p-0 overflow-hidden rounded-[5px] gap-0 border-0","aria-describedby":void 0,children:[e.jsx(da,{className:"sr-only",children:t.title}),e.jsxs("div",{className:"px-5 pt-5 pb-5 flex flex-col gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-base font-medium text-[#111]",children:t.title}),e.jsx("p",{className:"text-[12px] text-[#888] mt-1.5 leading-relaxed",children:t.description})]}),e.jsxs("div",{className:"flex flex-col gap-2 mt-1",children:[e.jsx("button",{onClick:v,disabled:r,className:"w-full h-[44px] rounded-[12px] bg-red-600 text-white text-sm font-medium hover:bg-red-700 transition-colors disabled:opacity-50",children:r?"Deleting...":t.confirmLabel}),e.jsx("button",{onClick:h,disabled:r,type:"button",className:"w-full h-[44px] rounded-[12px] bg-[#f4f4f4] text-[#666] text-sm font-medium hover:bg-[#eaeaea] transition-colors disabled:opacity-50",onClickCapture:()=>F({modal_name:"tool_delete_modal",origin:"tool_editor_publish_controls",button_name:"tool_delete_modal_cancel",button_type:"button"}),children:"Cancel"})]})]})]})}),e.jsx(la,{open:i,onOpenChange:l,children:e.jsxs(ca,{className:"sm:max-w-[650px] gap-0 rounded-[10px] border border-[#e1e1e1] bg-white p-[15px] shadow-[0px_4px_15px_rgba(0,0,0,0.1)] [&>button]:hidden","aria-describedby":void 0,children:[e.jsx(da,{className:"sr-only",children:Le}),e.jsxs("div",{className:"flex min-w-0 max-w-full flex-col gap-[15px]",children:[e.jsxs("div",{className:"flex flex-col gap-[3px]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("p",{className:"text-[12px] leading-[1.4] tracking-[-0.24px] text-black",children:Le}),e.jsx("button",{type:"button",onClick:()=>l(!1),className:"text-black transition-opacity hover:opacity-70",children:e.jsx(Hr,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"text-[10px] leading-[1.4] tracking-[-0.2px] text-[#7d7d7d]",children:te})]}),e.jsxs("div",{className:"flex min-w-0 max-w-full flex-wrap items-center gap-[5px]",children:[e.jsxs("button",{onClick:async()=>{oe&&(await navigator.clipboard.writeText(oe),l(!1))},onClickCapture:()=>F({modal_name:"tool_publish_success_modal",origin:"tool_editor_publish_controls",button_name:"tool_publish_success_modal_copy_link",button_type:"button",button_value:oe||void 0}),type:"button",className:"flex h-[36px] items-center justify-center gap-[8px] rounded-[10px] border border-[#e1e1e1] bg-black px-[15px] text-[12px] font-medium leading-[1.4] tracking-[-0.24px] text-white transition-colors hover:bg-[#111]",children:[e.jsx(Yi,{className:"h-3 w-3"}),"Copy"]}),e.jsxs("div",{className:"flex h-[36px] min-w-0 max-w-full flex-1 basis-0 items-center gap-[8px] overflow-hidden rounded-[10px] bg-[#e8e8e8] px-[15px] text-[12px] leading-[1.4] tracking-[-0.24px] text-black",children:[e.jsx(Vm,{className:"h-2.5 w-2.5 shrink-0"}),e.jsx("span",{className:"block min-w-0 flex-1 truncate",children:Ke})]})]})]})]})})]})}function Y0(){return e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 border-2 border-[#333] border-t-[#888] rounded-full animate-spin"}),e.jsx("span",{className:"text-xs text-[#666]",children:"Restoring session…"})]})})}const Z0="Imported Tool";function gx(t,s){var r;return((r=t.name)==null?void 0:r.trim())||(s==null?void 0:s.trim())||Z0}async function bx(t,{ensureDraftImplId:s,handleStructuredUpdate:r}){const{schema:a}=await xo(t.controlsSchema),o=t.canvasCode?await fo(t.canvasCode):null,i=t.customCss?await mo(t.customCss):null,l=await s();await D.entities.ToolImplementation.update(l,{canvas_code_url:o??"",controls_schema:a,libraries:t.libraries,custom_css_url:i??"",...t.technology!=null&&{technology:t.technology},...typeof t.canvasWidth=="number"&&{canvas_width:t.canvasWidth},...typeof t.canvasHeight=="number"&&{canvas_height:t.canvasHeight}}),await r()}function J0(t){var i,l,c;const{user:s}=za(),{data:r}=ed(s==null?void 0:s.id),a=(()=>{const x=r==null?void 0:r.action_costs;return x?t?x.remix:x.create:0})(),o=Xc({remaining:((i=r==null?void 0:r.credits)==null?void 0:i.remaining)??null,cost:a,dailyRemaining:((l=r==null?void 0:r.credits)==null?void 0:l.daily_remaining)??null,monthlyRemaining:((c=r==null?void 0:r.credits)==null?void 0:c.monthly_remaining)??null});return{billingSummary:r,nextActionCost:a,isCreditExhausted:o.blocked,creditBannerVisible:!!(r!=null&&r.credits)&&o.variant!==null}}const X0=({open:t,isAdmin:s=!1,toolHasCode:r=!1,onClose:a,onSend:o,onModelChange:i})=>{var re;const[l,c]=n.useState(""),[x,h]=n.useState([]),[y,u]=n.useState(""),w=n.useRef(null),_=Zi(),v=cd(a,t),{billingSummary:j,nextActionCost:A,isCreditExhausted:I,creditBannerVisible:O}=J0(r),L=l.trim(),P=L.length>0&&!I,V=()=>{P&&(o(L,y?{model:y}:void 0),c(""))};return n.useEffect(()=>{var X;t?(X=w.current)==null||X.focus():c("")},[t]),n.useEffect(()=>{ip().then(X=>{const je=s?X:X.filter(me=>!me.isAdminOnly);h(je);const he=lp(je);he&&u(he.id)})},[s]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:Wt("lg:hidden fixed inset-0 z-40",t?"":"pointer-events-none"),onClick:a,"aria-hidden":!0}),e.jsxs("div",{className:Wt("lg:hidden fixed bottom-0 left-0 right-0 z-50 flex flex-col items-center overflow-clip rounded-t-[15px] bg-white","shadow-[0px_-15px_15px_0px_rgba(0,0,0,0.05),0px_-4px_8px_0px_rgba(0,0,0,0.06)]",t?"translate-y-0":"translate-y-full pointer-events-none"),style:{bottom:_,paddingBottom:_?0:"env(safe-area-inset-bottom, 0px)",transition:"transform 300ms ease-out",...v.sheetStyle},"aria-hidden":!t,children:[e.jsxs("div",{...v.dragProps,className:"flex w-full flex-col items-center gap-[6px] px-[10px] pb-[16px] pt-[10px]",children:[e.jsx(Wi,{onClose:a,testId:Jt.chatConsole.handle}),e.jsx("div",{className:"flex w-full items-center justify-between px-[10px]",children:e.jsx("p",{className:"text-[14px] font-medium leading-[1.4] tracking-[-0.28px] text-black",children:"Chat 
63Console"})})]}),e.jsx("div",{className:"h-px w-[350px] max-w-[calc(100%-30px)] bg-[#e1e1e1]"}),e.jsxs("div",{className:"flex w-full flex-col gap-[10px] px-[15px] pb-[15px] pt-[15px]",children:[e.jsxs("div",{className:O?"flex flex-col gap-0":void 0,children:[j!=null&&j.credits?e.jsx("div",{"data-testid":O?Jt.chatConsole.creditBanner:void 0,children:e.jsx(xd,{planKey:j.plan_key,cost:A,remaining:j.credits.remaining,dailyRemaining:j.credits.daily_remaining,monthlyRemaining:j.credits.monthly_remaining,dailyResetAt:((re=j.resets)==null?void 0:re.daily_reset_at)??null,dailyLimit:j.credits.daily_limit,monthlyLimit:j.credits.monthly_limit})}):null,e.jsx("div",{className:O?"relative z-10 -mt-[10px]":void 0,children:e.jsxs("div",{"data-testid":Jt.chatConsole.composer,className:Wt("flex h-[122px] w-full flex-col justify-between rounded-[10px] border border-[#e1e1e1] bg-white p-[10px]",O?"border-[#be22b1] rounded-t-[15px]":null),children:[e.jsx("textarea",{ref:w,value:l,onChange:X=>c(X.target.value),onKeyDown:X=>{X.key==="Enter"&&!X.shiftKey&&(X.preventDefault(),V())},placeholder:"Describe your vision...",disabled:I,"data-testid":Jt.chatConsole.composerInput,className:"w-full flex-1 resize-none border-0 bg-transparent p-[5px] text-[14px] leading-[1.4] tracking-[-0.28px] text-black outline-none placeholder:text-[#686868] disabled:opacity-50"}),e.jsxs("div",{className:"flex w-full items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-[8px]",children:[e.jsx("button",{type:"button","aria-label":"Add image",disabled:I,className:"flex size-[30px] items-center justify-center rounded-[5px] text-[#686868] hover:bg-[#f5f5f5] disabled:opacity-40",children:e.jsx(ch,{className:"size-[16px]",strokeWidth:1.6})}),x.length>0?e.jsx(od,{models:x,value:y,onValueChange:X=>{u(X),i==null||i(X)},disabled:I,triggerClassName:"h-[30px] w-auto min-w-0 gap-[4px] bg-transparent border-0 shadow-none px-[8px] py-0 text-[14px] font-medium text-[#686868] tracking-[-0.28px] ring-0 focus:ring-0 hover:bg-[#f5f5f5] rounded-[5px] transition-colors"}):null]}),e.jsx("button",{type:"button","data-testid":Jt.chatConsole.sendButton,onClick:V,disabled:!P,"aria-label":"Send",className:Wt("flex size-[30px] items-center justify-center rounded-[10px] text-white transition-colors",P?"bg-black":"bg-[#a1a1aa]"),children:e.jsx(dh,{className:"size-[14px]",strokeWidth:2})})]})]})})]}),e.jsx("p",{className:"px-[15px] text-center text-[11px] font-medium leading-[1.4] tracking-[-0.22px] text-[#686868]",children:"AI can make mistakes. Always double-check the results."})]})]})]})};function Q0(){const[t,s]=n.useState(0);return n.useEffect(()=>{const r=window.visualViewport;if(!r)return;const a=()=>s(Math.max(0,r.offsetTop));return a(),r.addEventListener("resize",a),r.addEventListener("scroll",a),()=>{r.removeEventListener("resize",a),r.removeEventListener("scroll",a)}},[]),t}const eg="lg:hidden fixed bottom-0 left-[16px] right-[16px] z-50 flex flex-col overflow-hidden border border-[var(--product-grey-02-legacy)] bg-[var(--product-grey-01)]",tg=50,ng="60%",sg=16,rg='input, textarea, select, button, a, label, [contenteditable="true"], [role="button"], [tabindex]';function ag(t){t.target.closest(rg)||t.preventDefault()}const og="grid h-[50px] w-full shrink-0 grid-cols-3 items-center overflow-hidden border-b border-[var(--product-grey-02-legacy)] bg-[var(--product-grey-02)] py-[8px] pr-[8px] pl-[12px]";function qc({open:t,onClose:s,keyboardInset:r,isAdmin:a,debugMode:o,onToggleDebug:i,chromeVariant:l="legacy",size:c="full",onExpand:x,title:h="Chat",dataHooks:y=Jt.chatOverlay,children:u}){const w=l==="v2"&&c!=="full",_=cd(s,t,w?x:void 0),v=l==="v2"&&c==="compact",j=Q0(),A=l==="v2"&&!v&&r>0;return l==="v2"?e.jsxs(e.Fragment,{children:[e.jsx("div",{"data-testid":y.backdrop,className:`lg:hidden fixed inset-0 z-40 ${t?"":"pointer-events-none"}`,onClick:s,"aria-hidden":!0}),e.jsxs("div",{"data-testid":y.root,className:`${eg} ${t?"translate-y-0":"translate-y-full pointer-events-none"}`,onMouseDown:ag,style:{interpolateSize:"allow-keywords",height:A?`calc(100% - ${r+j}px)`:v?"auto":c==="mid"?ng:`calc(100% - ${tg+sg+r}px)`,bottom:r,transition:"transform 300ms ease-out, height 300ms ease-out",..._.sheetStyle},"aria-hidden":!t,children:[e.jsxs("div",{..._.dragProps,className:og,children:[e.jsx("button",{type:"button",onClick:w?x:void 0,disabled:!w||!x,"data-testid":y.expand,className:"col-start-1 justify-self-start text-product-title text-[var(--product-black-00)] disabled:cursor-default",children:h}),e.jsx(Wi,{onClose:s,testId:y.handle,className:"col-start-2 h-[4px] w-[45px] justify-self-center rounded-none bg-[var(--product-grey-03)]"}),a&&e.jsx("button",{type:"button","data-testid":y.debugButton,onClick:i,className:`col-start-3 flex h-[20px] items-center justify-self-end px-[8px] text-product-tiny transition-colors ${o?"bg-[var(--product-black-00)] text-[var(--product-white-00)]":"border border-[var(--product-grey-02)] text-[var(--product-grey-05)]"}`,children:o?"Debug on":"Debug"})]}),e.jsx("div",{className:"flex min-h-0 flex-1 flex-col",children:u})]}),t&&r>0?e.jsx("div",{"data-testid":y.keyboardUnderlay,"aria-hidden":!0,
63className:"lg:hidden fixed inset-x-0 bottom-0 z-50 bg-[var(--product-white-00)]",style:{height:r}}):null]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{"data-testid":y.backdrop,className:`lg:hidden fixed inset-0 z-40 ${t?"":"pointer-events-none"}`,onClick:s,"aria-hidden":!0}),e.jsxs("div",{"data-testid":y.root,className:`lg:hidden fixed bottom-0 left-0 right-0 z-50 flex flex-col bg-white rounded-t-[15px] overflow-hidden shadow-[0px_-15px_15px_0px_rgba(0,0,0,0.05),0px_-4px_8px_0px_rgba(0,0,0,0.06)] ${t?"translate-y-0":"translate-y-full pointer-events-none"}`,style:{height:"85dvh",bottom:r,maxHeight:`calc(100dvh - ${r}px - 56px)`,transition:"transform 300ms ease-out",..._.sheetStyle},"aria-hidden":!t,children:[e.jsxs("div",{..._.dragProps,className:"shrink-0 flex w-full flex-col items-center gap-[6px] px-[10px] pb-[16px] pt-[10px]",children:[e.jsx(Wi,{onClose:s,testId:y.handle}),e.jsxs("div",{className:"flex w-full items-center justify-between px-[10px]",children:[e.jsx("p",{className:"text-[14px] font-medium leading-[1.4] tracking-[-0.28px] text-black",children:"Chat 
63Console"}),e.jsx("div",{className:"flex items-center gap-[10px]",children:a&&e.jsx("button",{type:"button","data-testid":y.debugButton,onClick:i,className:`flex h-[20px] items-center rounded-[5px] border px-[8px] text-[11px] font-medium leading-none transition-colors ${o?"border-black bg-black text-white":"border-[#e1e1e1] text-[#7d7d7d]"}`,children:o?"Debug on":"Debug"})})]})]}),e.jsx("div",{className:"h-px w-[350px] max-w-[calc(100%-30px)] shrink-0 self-center bg-[#e1e1e1]"}),e.jsx("div",{className:"flex-1 min-h-0 flex flex-col",children:u})]})]})}const ig=({open:t,coverUrl:s,name:r,description:a,tags:o,descriptionMax:i=120,onNameChange:l,onDescriptionChange:c,onAddTag:x,onRemoveTag:h,onBack:y})=>{const[u,w]=n.useState("");if(!t)return null;const _=()=>{const v=u.trim();v&&(x(v),w(""))};return e.jsx("div",{className:"lg:hidden fixed inset-0 z-[60] flex flex-col bg-white",children:e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-[20px] pt-[20px]",children:e.jsxs("div",{className:"flex flex-col gap-[20px]",children:[e.jsxs("button",{type:"button",onClick:y,className:"flex items-center gap-[15px] self-start","aria-label":"Back",children:[e.jsx(uh,{className:"size-[18px] text-black",strokeWidth:2}),e.jsx("span",{className:"text-[16px] font-medium leading-[1.4] tracking-[-0.32px] text-black",children:"Edit Listing"})]}),e.jsxs("div",{className:"flex flex-col gap-[5px]",children:[s&&e.jsx("img",{src:s,alt:r||"Untitled tool",className:"h-[190px] w-full rounded-[10px] object-cover"}),e.jsx("p",{className:"text-[12px] font-medium leading-[1.4] tracking-[-0.24px] text-[#686868]",children:"To change the thumbnail image, switch to desktop."})]}),e.jsxs("label",{className:"flex flex-col gap-[8px]",children:[e.jsx("span",{className:"text-[12px] font-medium leading-[1.4] tracking-[-0.24px] text-[#686868]",children:"Name"}),e.jsx("input",{value:r,onChange:v=>l(v.target.value),className:"h-[40px] w-full rounded-[10px] bg-[#e8e8e8] px-[15px] text-[16px] leading-[1.4] tracking-[-0.28px] text-black outline-none"})]}),e.jsxs("label",{className:"flex flex-col gap-[8px]",children:[e.jsx("span",{className:"text-[12px] font-medium leading-[1.4] tracking-[-0.24px] text-[#686868]",children:"Description"}),e.jsxs("div",{className:"flex h-[80px] flex-col rounded-[10px] bg-[#e8e8e8] px-[15px] py-[10px]",children:[e.jsx("textarea",{value:a,onChange:v=>c(v.target.value.slice(0,i)),maxLength:i,className:"w-full flex-1 resize-none bg-transparent text-[16px] leading-[1.4] tracking-[-0.28px] text-black outline-none"}),e.jsxs("span",{className:"self-end text-[12px] leading-[1.4] tracking-[-0.24px] text-[#4b5563]",children:[a.length,"/",i]})]})]}),e.jsxs("div",{className:"flex flex-col gap-[10px]",children:[e.jsx("span",{className:"text-[12px] font-medium leading-[1.4] tracking-[-0.24px] text-[#686868]",children:"Tags"}),e.jsxs("div",{className:"flex h-[36px] items-center justify-between rounded-[10px] bg-[#e8e8e8] px-[15px]",children:[e.jsx("input",{value:u,onChange:v=>w(v.target.value),onKeyDown:v=>{v.key==="Enter"&&(v.preventDefault(),_())},placeholder:"Add Tags",className:"min-w-0 flex-1 bg-transparent text-[16px] leading-[1.4] tracking-[-0.28px] text-black outline-none placeholder:text-[14px] placeholder:text-[#686868]"}),e.jsx("button",{type:"button",onClick:_,"aria-label":"Add tag",className:"flex size-[20px] items-center justify-center text-[#686868]",children:e.jsx(Bi,{className:"size-[12px]",strokeWidth:2})})]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap items-start gap-[8px]",children:o.map(v=>e.jsxs("button",{type:"button",onClick:()=>h(v),className:"flex h-[26px] items-center gap-[5px] rounded-[5px] border border-[#e1e1e1] bg-white px-[10px] py-[5px] text-[12px] font-medium tracking-[-0.24px] text-black",children:[e.jsx(Hr,{className:"size-[10px] text-black",strokeWidth:2}),v]},v))})]})]})})})};function vx(t,s){const{sendPageClicked:r}=Ua(),[a,o]=n.useState(!1);return n.useEffect(()=>{if(!a)return;const l=window.setTimeout(()=>o(!1),1500);return()=>window.clearTimeout(l)},[a]),{copied:a,copyLink:()=>{var l;t&&(r({button_name:s}),(l=navigator.clipboard)==null||l.writeText(t).then(()=>o(!0)).catch(()=>Ie.error("Couldn't copy the link — copy it from the field instead.")))}}}const lg="lg:hidden fixed bottom-0 left-[16px] right-[16px] z-50 flex min-h-[350px] has-[[data-publish-fit]]:min-h-0 flex-col overflow-hidden border border-[var(--product-grey-02-legacy)] bg-[var(--product-grey-01)]",ou="grid h-[50px] w-full shrink-0 grid-cols-3 items-center overflow-hidden border-b border-[var(--product-grey-02-legacy)] bg-[var(--product-grey-02)] py-[8px] pr-[8px] pl-[12px]",Di="text-product-title text-[var(--product-black-00)]",wc="text-product-tiny text-[var(--product-grey-05)]",Cc="flex w-full items-center gap-[12px] border border-[var(--product-grey-02)] bg-[var(--product-white-00)] p-[8px]",jc="min-w-0 flex-1 resize-none bg-transparent text-product-text text-[var(--product-black-00)] outline-none placeholder:text-[var(--product-grey-05)]",cg=({swipe:t,open:s,coverUrl:r,toolName:a,description:o,listed:i,publishing:l,canPublish:c,ctaLabel:x,showShareView:h,isPublished:y,shareUrl:u,listing:w,onToggleListed:_,onEditListing:v,onPublish:j,onUnpublish:A,onClose:I})=>{const{copied:O,copyLink:L}=vx(u,"mobile_publish_copy_link"),[P,V]=n.useState("publish"),[re,X]=n.useState("");n.useEffect(()=>{s&&(V("publish"),X(""))},[s]);const je=()=>{const T=re.trim();T&&w&&(w.onAddTag(T),X(""))},he=e.jsx(Wi,{onClose:I,testId:Jt.publishDrawer.handle,className:"col-start-2 h-[4px] w-[45px] justify-self-center rounded-none bg-[var(--product-grey-03)]"}),me=e.jsxs("div",{...t.dragProps,className:ou,children:[e.jsx("p",{className:`col-start-1 justify-self-start ${Di}`,children:"Publish"}),he]});return P==="listing"&&w?e.jsxs(e.Fragment,{children:[e.jsxs("div",{...t.dragProps,className:ou,children:[e.jsxs("button",{type:"button",onClick:()=>V("publish"),"data-testid":Jt.publishDrawer.editListingBack,className:"col-start-1 flex items-center gap-[8px] justify-self-start text-[var(--product-black-00)]",children:[e.jsx(Tu,{className:"size-[15px] shrink-0"}),e.jsx("span",{className:Di,children:"edit listing"})]}),he]}),e.jsxs("div",{"data-publish-fit":!0,className:"flex min-h-0 flex-1 flex-col overflow-y-auto",children:[e.jsxs("div",{className:"flex w-full shrink-0 flex-col gap-[12px] p-[12px]",children:[e.jsxs("div",{className:"flex w-full flex-col gap-[6px]",children:[e.jsx("label",{className:wc,htmlFor:"mobile-publish-name",children:"Tool Name"}),e.jsx("div",{className:`${Cc} h-[36px]`,children:e.jsx("input",{id:"mobile-publish-name","data-testid":Jt.publishDrawer.nameInput,value:w.name,onChange:T=>w.onNameChange(T.target.value),className:jc})})]}),e.jsxs("div",{className:"flex h-[92px] w-full flex-col gap-[6px]",children:[e.jsx("label",{className:wc,htmlFor:"mobile-publish-description",children:"Description"}),e.jsx("div",{className:`${Cc} min-h-0 flex-1 items-start`,children:e.jsx("textarea",{id:"mobile-publish-description","data-testid":Jt.publishDrawer.descriptionInput,value:w.description,onChange:T=>w.onDescriptionChange(T.target.value),className:`${jc} h-full`})})]}),e.jsxs("div",{className:"flex w-full flex-col gap-[6px]",children:[e.jsx("label",{className:wc,htmlFor:"mobile-publish-tags",children:"Tags"}),e.jsx("div",{className:`${Cc} h-[36px]`,children:e.jsx("input",{id:"mobile-publish-tags","data-testid":Jt.publishDrawer.tagInput,value:re,placeholder:"Add tags",onChange:T=>X(T.target.value),onKeyDown:T=>{T.key==="Enter"&&(T.preventDefault(),je())},className:jc})})]}),w.tags.length>0&&e.jsx("div",{"data-testid":Jt.publishDrawer.tagList,className:"flex flex-wrap items-start gap-[4px]",children:w.tags.map(T=>e.jsxs("span",{className:"flex items-center justify-center gap-[8px] bg-[var(--product-white-00)] px-[6px] py-[3px] text-product-tiny text-[var(--product-black-00)]",children:[e.jsx("button",{type:"button","aria-label":`Remove ${T}`,onClick:()=>w.onRemoveTag(T),className:"flex items-center text-[var(--product-black-00)]",children:e.jsx(Zn,{className:"size-[15px] shrink-0"})}),T]},T))})]}),e.jsx(Vs,{})]})]}):h?e.jsxs(e.Fragment,{children:[me,e.jsxs("div",{"data-publish-fit":!0,className:"flex min-h-0 flex-1 flex-col overflow-y-auto",children:[e.jsxs("div",{className:"flex w-full shrink-0 items-start justify-between p-[12px]",children:[e.jsx("p",{className:Di,children:"Your tool is published"}),e.jsx("span",{className:"shrink-0 bg-[var(--product-blue-03)] px-[6px] py-[3px] text-product-tiny text-[var(--product-white-00)]",children:"Live in Brik"})]}),e.jsx(Vs,{}),e.jsxs("div",{className:"flex w-full shrink-0 flex-col gap-[12px] border border-[var(--product-grey-02)] p-[12px]",children:[e.jsx("p",{className:Di,children:"Tool link"}),e.jsxs("div",{className:"flex h-[36px] w-full items-center gap-[12px] border border-[var(--product-grey-02)] bg-[var(--product-white-00)] p-[8px]",children:[e.jsx("p",{className:"min-w-0 flex-1 truncate text-product-text text-[var(--product-grey-05)]","data-testid":Jt.publishDrawer.shareUrl,children:u}),e.jsx(Nn,{type:"button",size:"small",priority:"primary",skin:"standard","data-testid":Jt.publishDrawer.copyLink,onClick:L,children:"Copy Link"})]})]}),e.jsx("div",{className:"flex w-full shrink-0 items-center justify-center p-[12px]",children:e.jsx("p",{className:"flex-1 text-product-text text-[var(--product-grey-05)]",children:O?"Link copied.":"Made something great? Tag us @brik.space."})})]})]}):e.jsxs(e.Fragment,{children:[me,e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto",children:[e.jsxs("div",{className:"flex w-full shrink-0 flex-col gap-[12px] p-[12px]",children:[r&&e.jsx("img",{src:r,alt:"",className:"h-[200px] w-full shrink-0 object-cover"}),e.jsxs("div",{className:"flex w-full flex-col gap-[20px]",children:[e.jsxs("div",{className:"flex w-full flex-col gap-[8px]",children:[e.jsx("p",{className:Di,children:a||"Untitled tool"}),o&&e.jsx("p",{className:"text-product-text text-[var(--product-grey-05)]",children:o})]}),e.jsxs(Nn,{type:"button",size:"medium",priority:"secondary",skin:"standard",className:"w-full","data-testid":Jt.publishDrawer.editListing,onClick:()=>w?V("listing"):v==null?void 0:v(),children:[e.jsx(Yl,{className:"size-[15px] shrink-0"}),"edit listing"]})]})]}),e.jsx(Vs,{}),e.jsxs("div",{className:"flex w-full shrink-0 flex-col p-[12px]",role:"radiogroup",children:[e.jsx(Rd,{title:"Unlisted",description:"Only people with the tool link can see your tool.",selected:!i,onSelect:()=>_(!1),testId:Jt.publishDrawer.unlisted}),e.jsx(Rd,{title:"In gallery",description:"Anyone can find your tool in the Brik gallery.",selected:i,onSelect:()=>_(!0),testId:Jt.publishDrawer.listed})]})]}),e.jsxs("div",{className:"flex w-full shrink-0 items-stretch",children:[y&&A&&e.jsxs(Nn,{type:"button",size:"big",priority:"secondary",skin:"error",className:"min-w-0 flex-1 border-0","data-testid":Jt.publishDrawer.unpublish,onClick:A,children:[e.jsx(pd,{className:"size-[15px] shrink-0"}),"Unpublish"]}),e.jsxs(Nn,{type:"button",size:"big",priority:"primary",skin:"standard",className:"min-w-0 flex-1",disabled:!c||l,"data-testid":Jt.publishDrawer.cta,onClick:j,children:[e.jsx(Fp,{className:"size-[15px] shrink-0"}),l?"Publishing…":x]})]})]})},yx=({open:t,coverUrl:s,toolName:r,description:a,listed:o,publishing:i=!1,canPublish:l=!0,ctaLabel:c="Publish",published:x=!1,chromeVariant:h="legacy",publishState:y,justPublished:u,shareUrl:w,listing:_,onToggleListed:v,onEditListing:j,onPublish:A,onUnpublish:I,onClose:O})=>{const L=cd(O,t),P=Zi();return h==="v2"?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:Wt("lg:hidden fixed inset-0 z-40 bg-black/30 transition-opacity duration-200",t?"opacity-100":"opacity-0 pointer-events-none"),onClick:O,"aria-hidden":!0}),e.jsx("div",{className:Wt(lg,t?"translate-y-0":"translate-y-full pointer-events-none"),style:{bottom:P,maxHeight:`calc(90dvh - ${P}px)`,transition:"transform 300ms ease-out",...L.sheetStyle},"aria-hidden":!t,children:e.jsx(cg,{swipe:L,open:t,coverUrl:s,toolName:r,description:a,listed:o,publishing:i,canPublish:l,ctaLabel:c,showShareView:!!u,isPublished:y!==void 0&&y!=="draft",shareUrl:w,listing:_,onToggleListed:v,onEditListing:j,onPublish:A,onUnpublish:I,onClose:O})})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:Wt("lg:hidden fixed inset-0 z-40 bg-black/30 transition-opacity duration-200",t?"opacity-100":"opacity-0 pointer-events-none"),onClick:O,"aria-hidden":!0}),e.jsxs("div",{className:Wt("lg:hidden fixed bottom-0 left-0 right-0 z-50 flex flex-col items-center overflow-clip rounded-t-[15px] bg-white","shadow-[0px_-15px_15px_0px_rgba(0,0,0,0.05),0px_-4px_8px_0px_rgba(0,0,0,0.06)]",t?"translate-y-0":"translate-y-full pointer-events-none"),style:{maxHeight:"90dvh",paddingBottom:"env(safe-area-inset-bottom, 0px)",transition:"transform 300ms ease-out",...L.sheetStyle},"aria-hidden":!t,children:[e.jsxs("div",{...L.dragProps,className:"flex w-full flex-col items-center gap-[6px] px-[10px] pb-[16px] pt-[10px]",children:[e.jsx(Wi,{onClose:O,testId:Jt.publishDrawer.handle}),e.jsx("div",{className:"flex w-full items-center justify-between px-[10px]",children:e.jsx("p",{className:"text-[14px] font-medium leading-[1.4] tracking-[-0.28px] text-black",children:"Publish"})})]}),e.jsx("div",{className:"h-px w-[350px] max-w-[calc(100%-30px)] shrink-0 self-center bg-[#e1e1e1]"}),e.jsxs("div",{className:"flex w-full flex-1 min-h-0 flex-col gap-[15px] overflow-y-auto px-[20px] py-[15px]",children:[s&&e.jsx("img",{src:s,alt:"",className:"h-[190px] w-full shrink-0 rounded-[10px] object-cover"}),e.jsxs("div",{className:"flex flex-col gap-[3px]",children:[e.jsx("p",{className:"text-[16px] font-medium leading-[1.4] tracking-[-0.32px] text-black",children:r||"Untitled Tool"}),a&&e.jsx("p",{className:"text-[14px] font-normal leading-[1.4] tracking-[-0.28px] text-[#686868]",children:a})]}),e.jsxs("button",{type:"button",onClick:j,className:"flex h-[48px] w-full shrink-0 items-center justify-center gap-[8px] rounded-[10px] border border-[#e1e1e1] bg-white text-[12px] font-medium tracking-[-0.24px] text-black transition-colors hover:bg-[#f5f5f5]",children:[e.jsx(ph,{className:"size-[12px]",strokeWidth:2}),"Edit Listing"]}),e.jsxs("div",{className:Wt("flex w-full shrink-0 items-center gap-[15px] rounded-[10px] border bg-white p-[15px]",o?"border-[#ff4447]":"border-[#e1e1e1]"),children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col text-[14px] tracking-[-0.28px]",children:[e.jsx("p",{className:"font-medium leading-[1.4] text-black",children:"Listed in Brik gallery"}),e.jsx("p",{"data-testid":Jt.publishDrawer.listedDescription,className:"font-normal leading-[1.4] text-[#686868]",children:"Brik users will be able to see and freely use your tool"})]}),e.jsx("button",{type:"button",role:"switch","aria-checked":o,"aria-label":"Listed in Brik gallery",onClick:()=>v(!o),className:Wt("relative h-[19px] w-[32px] shrink-0 rounded-full transition-colors",o?"bg-[#ff4447]":"bg-[#e1e1e1]"),children:e.jsx("span",{className:Wt("absolute top-[2px] size-[15px] rounded-full bg-white shadow-sm transition-[left]",o?"left-[15px]":"left-[2px]")})})]}),e.jsxs("div",{className:"flex w-full shrink-0 flex-col gap-[6px]",children:[e.jsxs("button",{type:"button",onClick:A,disabled:i||!l,className:"flex h-[48px] w-full shrink-0 items-center justify-center gap-[8px] rounded-[10px] border border-[#e1e1e1] bg-black text-[12px] font-medium tracking-[-0.24px] text-white transition-opacity hover:opacity-90 disabled:opacity-60",children:[e.jsx($c,{
63className:"size-[12px]",strokeWidth:2}),i?"Publishing…":c]}),x&&I&&e.jsx("button",{type:"button",onClick:I,disabled:i,className:"flex h-[48px] w-full shrink-0 items-center justify-center rounded-[10px] border border-[#e1e1e1] bg-white text-[12px] font-medium tracking-[-0.24px] text-[#ff4447] transition-colors hover:bg-[#fff5f5] disabled:opacity-60",children:"Unpublish"})]})]})]})]})};function _x({setControlsSchema:t,draftImplId:s,dropTracks:r,isPreviewingVersion:a}){const o=n.useCallback(_=>{!s||a||D.entities.ToolImplementation.update(s,{controls_schema:_}).catch(v=>{console.error("[useControlsSchemaEditing] Failed to save schema",v)})},[s,a]),i=n.useCallback(_=>{t(v=>{const j=v.map(A=>A.key===_?{...A,visible:A.visible===!1}:A);return o(j),j})},[o,t]),l=n.useCallback(_=>{t(v=>{const j=v.map(A=>A.key===_?{...A,deleted:!0}:A);return o(j),j}),r==null||r([_])},[o,t,r]),c=n.useCallback((_,v)=>{t(j=>{const A=j.map(I=>I.key===_?{...I,label:v}:I);return o(A),A})},[o,t]),x=n.useCallback(_=>{t(v=>{const j=fh(v,_);return o(j),j})},[o,t]),h=n.useCallback(_=>{t(v=>{const j=mh(v,_);return o(j),j})},[o,t]),y=n.useCallback((_,v)=>{t(j=>{const A=new Set(_),I=j.map(O=>O.key&&A.has(O.key)?{...O,visible:v}:O);return o(I),I})},[o,t]),u=n.useCallback(_=>{t(v=>{const j=new Set(_),A=v.map(I=>I.key&&j.has(I.key)?{...I,deleted:!0}:I);return o(A),A}),r==null||r(_)},[o,t,r]),w=n.useCallback((_,v)=>{t(j=>{const A=hh(j,_,v);return o(A),A})},[o,t]);return{persistControlsSchema:o,handleToggleControlVisibility:i,handleDeleteControl:l,handleRenameControl:c,handleReorderControls:x,handleReorderSections:h,handleBulkSetVisibility:y,handleBulkDeleteControls:u,handleMoveControlsToSection:w}}const dg=200,ug=200,pg=50;let iu=0;function wx(t,s){return t.length>s?t.slice(0,s):t}function xg(t){if(!t)return;const s={};for(const[r,a]of Object.entries(t))a!=null&&(s[r]=typeof a=="string"?wx(a,dg):a);return Object.keys(s).length>0?Nu(s):void 0}function Cx(t){var s;return((s=t==null?void 0:t.split(`
64`)[0])==null?void 0:s.trim())||void 0}function jx(){const{anonymousUserId:t,isAnonymous:s,loading:r,sessionId:a,userId:o}=za(),i=kf();return{sendError:n.useCallback(({error_data:c,error_message:x,error_type:h,tool_id:y})=>{if(r||iu>=pg)return;iu+=1;const u={anon_uuid:s?t:void 0,error_data:xg(c),error_message:wx(x,ug),error_type:h,page_name:i,session_id:a,tool_id:y,userId:s?void 0:o};ir(lr.ERROR_SHOWN,Nf(u),u)},[t,s,r,i,a,o])}}function kx({toolId:t}){const{isAnonymous:s,loading:r,sessionId:a,userId:o}=za(),i=Jf(),l=n.useRef(null);return n.useEffect(()=>{if(r||!t||l.current===t)return;l.current=t;const x={referral:i,session_id:a,tool_id:t??void 0,userId:s?void 0:o};ir(lr.TOOL_EDITOR_VIEWED,Sf(x),x)},[s,r,i,a,t,o]),{sendToolEditorAction:n.useCallback(x=>{if(r)return;const h={action_name:x,session_id:a,tool_id:t??void 0,userId:s?void 0:o};ir(lr.TOOL_EDITOR_ACTION,Tf(h),h)},[s,r,a,t,o])}}const fg=3e4,kc=25,mg=20;function hg(t){const{userId:s}=za(),r=n.useRef(null),a=n.useRef(Date.now()),{data:o}=Rf({queryKey:["user-tools",s],queryFn:async()=>{for(let i=0;i<mg;i++){const l=await D.entities.Tool.filter({user_id:s},"created_date",kc,i*kc),c=l.filter(x=>!x.remixed_from);if(c.length>0){if(c.length>1)return!1;const x=c[0].created_date?Date.parse(c[0].created_date):Number.NaN;return Number.isNaN(x)?!1:x>=a.current-fg}if(l.length<kc)return!0}return!1},enabled:t&&!!s&&r.current===null,staleTime:1/0});return r.current===null&&o!==void 0&&(r.current=o),r.current??!1}const lu="brik-onboarding-survey-completed",gg=2,bg=1500;function Nc(t){return t?`${lu}:${t}`:lu}function cu(t){try{return localStorage.getItem(t)==="1"}catch{return!1}}function vg(t){try{localStorage.setItem(t,"1")}catch{}}function yg(){const{profile:t,loading:s,setProfile:r,refreshProfile:a}=gh(),o=t,i=(o==null?void 0:o.user_id)??null,l=s||!o,c=n.useRef(0);n.useEffect(()=>{if(s||o||c.current>=gg)return;const u=c.current+1;c.current=u;const w=window.setTimeout(()=>{a()},bg*u);return()=>window.clearTimeout(w)},[s,o,a]);const x=!!(o!=null&&o.onboarding_survey_seen_at)||cu(Nc(i)),h=n.useRef(!1);n.useEffect(()=>{if(h.current||!(o!=null&&o.id)||!i||o.onboarding_survey_seen_at||!cu(Nc(i))
64)return;h.current=!0;const u=new Date().toISOString(),w=o;r({...o,onboarding_survey_seen_at:u}),D.entities.Profile.update(o.id,{onboarding_survey_seen_at:u}).catch(_=>{r(w),h.current=!1,console.error("[OnboardingSurvey] failed to backfill seen marker",_)})},[o,i,r]);const y=n.useCallback(()=>{if(vg(Nc(i)),!(o!=null&&o.id))return;const u=new Date().toISOString(),w=o;r({...o,onboarding_survey_seen_at:u}),D.entities.Profile.update(o.id,{onboarding_survey_seen_at:u}).catch(_=>{r(w),console.error("[OnboardingSurvey] failed to persist seen marker",_)})},[o,r,i]);return{completed:x,loading:l,markCompleted:y}}function Nx({generating:t,editingBorrowedTool:s=!1,forceSurvey:r}){const[a,o]=n.useState(!1),i=n.useRef(r),{completed:l,loading:c,markCompleted:x}=yg(),h=n.useCallback(()=>{x(),o(!0)},[x]),y=hg(!i.current&&!c&&!l),u=n.useRef(!1),w=!c&&!l&&!s&&y;return w&&t&&(u.current=!0),{show:!a&&(i.current||w&&(t||u.current)),previouslyDone:l,onDismiss:h}}const _g=4,zl=["google/gemini-3.5-flash","anthropic/claude-sonnet-5"],du=t=>t.split("/")[0];function Sx(t,s,r){if(t>=_g)return null;if(t<2)return s;const a=zl.find(o=>du(o)!==du(s)&&!r.has(o));return a||(zl.find(o=>!r.has(o))??null)}function Tx(t,s){const r=new Set,a=new Set;for(const l of t)l.type==="section"?l.label&&a.add(l.label):l.key&&r.add(l.key);if(r.size===0&&a.size===0)return[];const o=new Set(a),i=[];for(const l of s)l.type==="section"&&l.label&&!o.has(l.label)&&(i.push(l.label),o.add(l.label));return i}async function Ul(t,s,r={},a={}){const o=await D.entities.Tool.create(t);try{if(await D.entities.Tool.update(o.id,{...r,creator_id:s.id,creator_name:s.full_name??"",creator_email:s.email??""}),a.creationMode){const i={creation_mode:a.creationMode,tool_description:typeof t.description=="string"?t.description:void 0,tool_id:o.id,tool_name:typeof t.name=="string"?t.name:void 0,userId:s.id};ir(lr.TOOL_CREATED,Ef(i),i)}If.setQueryData([sd,s.id],!0)}catch(i){throw await D.entities.Tool.delete(o.id).catch(()=>{}),i}return o}function uu(t,s){return typeof t=="number"&&t>0?t:s}function Gl(t,s){return{width:uu(t,nt.export.defaultWidth),height:uu(s,nt.export.defaultHeight)}}function Rx({idleOverlayExiting:t,hasPreviewHtml:s,status:r,previewPending:a,hasStarted:o,arrivedWithPrompt:i}){return!i&&(t||!s&&r!=="error"&&!a&&!o)}function wg({isMobile:t,...s}){return!t&&Rx(s)}function Cg(t){return Rx(t)}const jg="clay-draft-";function Ex(){try{const t=Object.keys(localStorage).filter(s=>s.startsWith(jg));for(const s of t)localStorage.removeItem(s);return t.length}catch{return 0}}function Kc(t){const s={};if(!t)return s;for(const r of t)r.key&&r.default!==void 0&&r.type!=="section"&&r.type!=="button"&&(s[r.key]=r.default);return s}function pu(t,s){return!t&&(!s||Object.keys(s).length===0)?null:{...t??{},...s??{}}}function xu(t,s){const r={};for(const a of Object.keys(t))JSON.stringify(t[a])!==JSON.stringify(s[a])&&(r[a]=t[a]);return r}function Ix(t,s){return{...t,...s}}function kg(t,s,r){return t&&Object.keys(t).length>0?t:!s||Object.keys(s).length===0?null:Ix(Kc(r),s)}function Yc(){return{stack:[{}],index:0}}const Dx="clay-control-checkpoints-";function Ng(t){try{const s=localStorage.getItem(`${Dx}${t}`);if(!s)return null;const r=JSON.parse(s);if(!Array.isArray(r.stack)||!r.stack.every(Mx))return null;const a=typeof r.index=="number"&&r.index>=0&&r.index<r.stack.length?r.index:r.stack.length-1;return{stack:r.stack,index:a}}catch{return null}}function Zc(t,s){try{localStorage.setItem(`${Dx}${t}`,JSON.stringify(s))}catch{}}async function Sc(t,s,r,a){await t({control_values:r}),Zc(s,a);try{await t({control_checkpoints:a})}catch{}}function Mx(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function Sg(t,s,r){let a=Yc();const o=t??s;if(o&&typeof o=="object"){const i=o;Array.isArray(i.stack)&&i.stack.every(Mx)&&(a={stack:i.stack,index:typeof i.index=="number"&&i.index>=0&&i.index<i.stack.length?i.index:i.stack.length-1})}return Tg(a,r)}function Tg(t,s){const r=s??{},a=t.stack[t.index]??{};if(JSON.stringify(a)===JSON.stringify(r))return t;const i=[...t.stack.slice(0,t.index+1),r];return{stack:i,index:i.length-1}}function Rg(t,s){const r=t.stack[t.index]??{};if(JSON.stringify(s)!==JSON.stringify(r))return{state:t,targetTweaks:r,changed:!0};if(t.index<=0)return{state:t,targetTweaks:r,changed:!1};const a=t.index-1;return{state:{stack:t.stack,index:a},targetTweaks:t.stack[a]??{},changed:!0}}function Eg(t,s){const r={};if(!t||!s)return r;const a=(o,i)=>
64{if(typeof o=="string"){typeof i=="string"&&i!==o&&(o.startsWith("data:")||o.startsWith("blob:"))&&(r[o]=i);return}if(Array.isArray(o)&&Array.isArray(i)){o.forEach((l,c)=>a(l,i[c]));return}if(o&&typeof o=="object"&&i&&typeof i=="object")for(const l of Object.keys(o))a(o[l],i[l])};for(const o of Object.keys(s))a(t[o],s[o]);return r}function Jc(t,s){if(Object.keys(s).length===0)return t;if(typeof t=="string")return s[t]??t;if(Array.isArray(t))return t.map(r=>Jc(r,s));if(t&&typeof t=="object"){const r={};for(const[a,o]of Object.entries(t))r[a]=Jc(o,s);return r}return t}function Wl(t){return typeof t=="string"?t.startsWith("blob:")||t.startsWith("data:"):Array.isArray(t)?t.some(Wl):t&&typeof t=="object"?Object.values(t).some(Wl):!1}function Ig(t){return Object.values(t).some(Wl)}function Dg(t){const s={},r=[];for(const[a,o]of Object.entries(t))Wl(o)?r.push(a):s[a]=o;return{values:s,droppedKeys:r}}const Tc=600,Mg=150,Ag=3e3,Pg=15e3,_l=[1e3,4e3,1e4];function Ax({draftImplId:t,previewImplId:s=null,persistencePaused:r=!1,canvasCode:a,controlsSchemaRef:o,previewRef:i,setControlValuesChanged:l,ensureDraftImplId:c,onAutosaveSaved:x,onAutosaveError:h}){const y=n.useRef(null),u=n.useRef(null),w=n.useRef(Yc()),_=n.useRef(c);_.current=c;const v=n.useRef(x);v.current=x;const j=n.useRef(h);j.current=h;const A=n.useRef(t);A.current=t;const I=n.useRef(s);I.current=s;const O=n.useRef(r);n.useEffect(()=>{O.current=r},[r]);const L=n.useRef(!1),P=n.useCallback(()=>(L.current=!0,()=>{L.current=!1}),[]),V=n.useCallback(()=>new Promise(T=>{var ue,z,$;const ee=(z=(ue=i.current)==null?void 0:ue.getIframeRefObj)==null?void 0:z.call(ue);if(!(($=ee==null?void 0:ee.current)!=null&&$.contentWindow)){T(null);return}let ae=!1;const ve=$n(W=>{W.type===Df&&!ae&&(ae=!0,ve(),T(W.payload||null))});yn(ee,Mf),setTimeout(()=>{ae||(ae=!0,ve(),T(null))},Ag)}),[i]),re=n.useCallback(async()=>pu(await V(),u.current),[V]),X=n.useCallback(async T=>{const ee=await re(),ae=kg(ee,y.current,T);return ae&&ae!==ee&&console.warn("[useControlAutosave] iframe live values unavailable — baking autosaved control_values"),ae},[re]),je=n.useCallback((T,ee,ae={})=>{y.current=ee,u.current=null;const ve=T==null?void 0:T.id,ue=Sg(T==null?void 0:T.control_checkpoints,ve?Ng(ve):null,ee);return w.current=ue,ve&&(Zc(ve,ue),ae.writeBackIfChanged&&JSON.stringify(T==null?void 0:T.control_checkpoints)!==JSON.stringify(ue)&&D.entities.ToolImplementation.update(ve,{control_checkpoints:ue}).catch(z=>console.warn("[useControlAutosave] control_checkpoints DB write failed",z))),ue},[]),he=n.useCallback(T=>{const ee=Yc();return w.current=ee,T&&Zc(T,ee),ee},[]),me=n.useCallback(()=>{y.current=null,u.current=null},[]);return n.useEffect(()=>{let T=null,ee=!1,ae=!1,ve=Tc,ue=0,z=0,$=null;const W=async()=>{if(I.current)return I.current;if(A.current)return A.current;if(!_.current)return null;try{return await _.current()}catch(oe){return console.warn("[useControlAutosave] Could not resolve a draft implementation",oe),null}},ne=async(oe,st)=>{var q;const rt=we=>D.entities.ToolImplementation.update(oe,we);try{return await Sc(rt,oe,st,w.current),st}catch(we){const{values:De,droppedKeys:ie}=Dg(st);if(ie.length===0)throw we;return await Sc(rt,oe,De,w.current),Ie.error("Couldn't save an uploaded file — your other changes were saved"),(q=j.current)==null||q.call(j),De}},F=()=>{if(T=null,!(!ee||ae)){if(L.current||O.current){T=setTimeout(F,Tc);return}ee=!1,ae=!0,(async()=>{var oe,st,rt,q;try{const we=await re();if(!we||Object.keys(we).length===0)return;const De=$a(o.current,a),ie=await ho(we,De,D),pe=ie??we,J=Kc(De),Ce=xu(pe,J);if(JSON.stringify(Ce)===JSON.stringify(y.current??{}))return;const se=await W();if(!se){z<_l.length&&($=_l[z],z+=1,ee=!0);return}if(L.current||O.current){ee=!0;return}const Ot=await ne(se,Ce);y.current=Ot,z=0,(oe=v.current)==null||oe.call(v);const U=(rt=(st=i.current)==null?void 0:st.getIframeRefObj)==null?void 0:rt.call(st);if(U&&ie){const mt=Eg(we,ie);if(Object.keys(mt).length>0){const le=pu(we,u.current);for(const Se of Object.keys(ie)){const gt=le&&Se in le?le[Se]:we[Se],Fe=Jc(gt,mt);JSON.stringify(Fe)!==JSON.stringify(gt)&&yn(U,Of,{key:Se,value:Fe})}}}}catch(we){if(console.error("[useControlAutosave] Failed to autosave control values",we),z<_l.length){$=_l[z],z+=1,ee=!0;return}(q=j.current)==null||q.call(j);const De=Date.now();De-ue>Pg&&(ue=De,Ie.error("Autosave failed — your latest change may not be saved"))}finally{ae=!1,ee&&(T=setTimeout(F,$??ve),$=null)}})()}},te=oe=>{oe&&(u.current=oe),ve=oe&&Ig(oe)?Mg:Tc,z=0,$=null,ee=!0,T&&clearTimeout(T),T=setTimeout(F,ve)},Le=()=>{T&&(clearTimeout(T),F())},Ke=$n(oe=>{if(oe.type!==rd)return;const st=oe.payload;st!=null&&st.animating||te(st==null?void 0:st.values)});return window.addEventListener("beforeunload",Le),window.addEventListener("pagehide",Le),()=>{window.removeEventListener("beforeunload",Le),window.removeEventListener("pagehide",Le),T&&(clearTimeout(T),T=null,!L.current&&!O.current&&F()),Ke()}},[a,t,s,re,i,o]),n.useEffect(()=>$n(ee=>{var ve,ue;if(ee.type!==Af)return;const ae=(ue=(ve=i.current)==null?void 0:ve.getIframeRefObj)==null?void 0:ue.call(ve);if(!t){ae&&yn(ae,Td);return}(async()=>{try{const z=await re();if(!z||Object.keys(z).length===0){ae&&yn(ae,Td);return}const $=$a(o.current,a),W=Kc($),ne=xu(z,W),F=Rg(w.current,ne);
64if(!F.changed)return;w.current=F.state,y.current=F.targetTweaks;const te=Ix(W,F.targetTweaks);ae&&yn(ae,Pf,te),await Sc(Le=>D.entities.ToolImplementation.update(t,Le),t,F.targetTweaks,F.state),l(Object.keys(F.targetTweaks).length>0)}catch(z){console.error("[useControlAutosave] Failed to revert control checkpoints",z)}})()}),[a,t,re,i,o,l]),{controlValuesRef:y,latestIframeTweakedRef:u,controlCheckpointsRef:w,getIframeLiveValues:V,getMergedIframeLiveValues:re,getControlValuesForBake:X,pauseAutosave:P,hydrateCheckpointsForImpl:je,resetCheckpointsForSave:he,clearDraftTweaks:me}}const Og=12e3,Px=400;async function Lg(t,s={}){try{return await fu(t,s)}catch(r){return console.info("[presets] offscreen capture retrying with a longer settle —",r),await fu(t,{...s,settleMs:(s.settleMs??Px)*4})}}async function fu(t,s={}){const{timeoutMs:r=Og,settleMs:a=Px,flattenColor:o="#ffffff"}=s,i=document.createElement("iframe");return i.setAttribute("aria-hidden","true"),i.setAttribute("sandbox","allow-scripts"),i.style.cssText="position:fixed;left:0;top:0;width:1280px;height:1280px;border:0;pointer-events:none;opacity:0.01;z-index:-1;",await new Promise((l,c)=>{let x=!1,h,y,u;const w=_=>{x||(x=!0,clearTimeout(h),clearTimeout(y),u==null||u(),i.remove(),_())};u=$n(_=>{var j,A;if(_.type===Lf){y=setTimeout(()=>{yn({current:i},Bf,{format:"png",resolution:1,transparentBackground:!1,flattenColor:o,watermark:!1,coverCapture:!0})},a);return}if(_.type===Ff){const I=typeof((j=_.payload)==null?void 0:j.message)=="string"?_.payload.message:"unknown error";w(()=>c(new Error(`The tool could not capture a frame: ${I}`)));return}if(_.type!==$f)return;const v=(A=_.payload)==null?void 0:A.dataURL;if(typeof v!="string"||!v){w(()=>c(new Error("The tool has no canvas to capture")));return}w(()=>l(v))},{source:()=>i.contentWindow}),h=setTimeout(()=>w(()=>c(new Error("The tool did not render in time"))),r),document.body.appendChild(i),i.srcdoc=t})}const mu=800,Rc=(t,s)=>Object.prototype.hasOwnProperty.call(t,s),hu=D.entities.ToolImplementation;function Bg(t){const[s,r]=n.useState({}),a=t?s[t]??null:null,o=n.useRef(s),i=n.useRef(new Map),l=n.useRef(new Map),c=n.useRef(new Map),x=n.useRef(new Map),h=n.useRef(new Map),y=n.useRef(new Map),u=n.useRef(!0),w=n.useCallback(L=>{const P=h.current.get(L);if(P)return P;const V=(async()=>{const re=await hu.get(L),X=Hm(re==null?void 0:re.presets);Rc(o.current,L)||(o.current={...o.current,[L]:X},!c.current.has(L)&&!x.current.has(L)&&i.current.set(L,JSON.stringify(Dd(X))),r(je=>Rc(je,L)?je:{...je,[L]:X}))})().catch(re=>{throw h.current.delete(L),re});return h.current.set(L,V),V},[]);n.useEffect(()=>{t&&w(t).catch(L=>{console.warn("[presets] load failed",{version:t,err:L})})},[t,w]);const _=n.useCallback(async function L(P){const V=l.current.get(P);V&&(clearTimeout(V),l.current.delete(P));const re=c.current.get(P);if(!re){await x.current.get(P);return}c.current.delete(P);const X=JSON.stringify(re),je=x.current.get(P)??Promise.resolve();let he;he=je.catch(()=>{}).then(async()=>{if(i.current.get(P)!==X)try{await hu.update(P,{presets:re}),i.current.set(P,X),y.current.delete(P)}catch(me){c.current.has(P)||c.current.set(P,re);const T=y.current.get(P)??0;throw y.current.set(P,T+1),u.current&&T<3&&!l.current.has(P)&&l.current.set(P,setTimeout(()=>{L(P).catch(ee=>{console.warn("[presets] persist retry failed",{version:P,err:ee})})},mu*2**T)),me}}).finally(()=>{x.current.get(P)===he&&x.current.delete(P)}),x.current.set(P,he),await he},[]),v=n.useCallback((L,P)=>{const V={...o.current,[L]:P};o.current=V,r(V);const re=Dd(P),X=JSON.stringify(re);if(i.current.get(L)===X&&!x.current.has(L)){c.current.delete(L);const he=l.current.get(L);he&&(clearTimeout(he),l.current.delete(L));return}c.current.set(L,re);const je=l.current.get(L);je&&clearTimeout(je),l.current.set(L,setTimeout(()=>{_(L).catch(he=>{console.warn("[presets] persist failed",{version:L,err:he})})},mu))},[_]),j=n.useCallback((L,P)=>{const V=o.current[L],re=Object.keys(P);!V||re.some(X=>!V.some(je=>je.id===X))||v(L,V.map(X=>{const je=P[X.id];return je?{...X,thumbnail:je}:X}))},[v]);n.useEffect(()=>{const L=l.current,P=c.current;return u.current=!0,()=>{u.current=!1;for(const[V]of P)_(V).catch(re=>{console.warn("[presets] final persist failed",{version:V,err:re})});for(const V of L.values())clearTimeout(V);L.clear()}},[_]);const A=n.useCallback(async()=>
64{if(!t)return null;try{return Rc(o.current,t)||await w(t),await _(t),o.current[t]??[]}catch(L){throw console.warn("[presets] publish read failed; blocking publish to preserve presets",{version:t,err:L}),L}},[t,_,w]),I=n.useCallback(async()=>{t&&await _(t)},[t,_]),O=n.useCallback(L=>zm(L,D),[]);return{versionPresets:a,onPersistPresets:v,updatePresetThumbnails:j,getVersionPresets:A,flushPresets:I,uploadPresetThumbnail:O}}const Fg=4;function Ox({activeVersionKey:t,isHistoricalVersion:s,canvasSize:r,canvasSizeTweaked:a,thumbnailRefreshToken:o,setCanvasSize:i,timeline:l,timelineDockRef:c,previewRef:x,toolName:h,controlsSchema:y,canvasCode:u,libraries:w,customCss:_,onPreviewChange:v}){const{versionPresets:j,onPersistPresets:A,updatePresetThumbnails:I,getVersionPresets:O,flushPresets:L,uploadPresetThumbnail:P}=Bg(t),V=n.useCallback(me=>{var T;(T=c.current)==null||T.replaceTimeline(me)},[c]),re=n.useCallback(me=>{var ee,ae;me.width>0&&me.height>0&&i(me);const T=(ae=(ee=x.current)==null?void 0:ee.getIframeRefObj)==null?void 0:ae.call(ee);T&&Xf(T,me)},[x,i]),X=n.useCallback(async(me,T)=>{const ee=pa({name:h,controlsSchema:y,canvasCode:u,libraries:w,customCss:_,controlValues:me,hideControlsOnMobile:!0,canvasConfig:T?{...nt,export:{...nt.export,defaultWidth:T.width,defaultHeight:T.height}}:nt,editorMode:!1,externalControls:!0});return await Um(await Lg(ee))},[u,y,_,w,h]),je=n.useRef(`${t??""}:${o??""}`);return n.useEffect(()=>{const me=`${t??""}:${o??""}`;if(!t||o==null||j==null||me===je.current)return;je.current=me;let T=!1;return(async()=>{const ee={},ae=[...j],ve=async z=>{try{const $=z.canvasWidth&&z.canvasHeight?{width:z.canvasWidth,height:z.canvasHeight}:null,W=await X(z.values,$),ne=await P(W);if(!ne)throw new Error(`Thumbnail upload returned no URL for preset ${z.id}`);ee[z.id]=ne}catch($){console.warn("[presets] automatic thumbnail refresh failed",z.name,$)}};await Promise.all(Array.from({length:Math.min(Fg,ae.length)},async()=>{for(;!T;){const z=ae.shift();if(!z)return;await ve(z)}}));const ue=Object.keys(ee);T||ue.length===0||I(t,ee)})(),()=>{T=!0}},[t,X,o,I,P,j]),{controller:n.useMemo(()=>({versionKey:t,presets:j,canAdd:!s,isHistoricalVersion:s,canvasSize:r,canvasSizeTweaked:a,timeline:l,persist:A,uploadThumbnail:P,renderThumbnail:X,onPreviewChange:v,applyTimeline:V,applyCanvasSize:re}),[t,re,V,r,a,s,A,v,X,l,P,j]),getVersionPresets:O,flushPresets:L}}function Lx({toolIdRef:t}){const[s,r]=n.useState(""),a=n.useRef(""),[o,i]=n.useState([]),l=n.useRef([]),[c,x]=n.useState(null),h=n.useRef(Ld),y=n.useCallback(w=>{const _=w.slice(0,Vi);a.current=_,r(_)},[]),u=n.useCallback((w,_)=>{const v=qi(w);if(l.current=v,i(v),_!==void 0){const j=_?ud(_):null;h.current=j??Ld,x(j)}},[]);return n.useEffect(()=>{a.current=s},[s]),n.useEffect(()=>{const w=t.current;if(!w)return;const _=setTimeout(()=>{D.entities.Tool.update(w,{description:s}).catch(v=>console.error("[ToolEditor] Failed to save description:",v))},1500);return()=>clearTimeout(_)},[s,t]),{toolDescription:s,setToolDescription:r,toolDescriptionRef:a,applyToolDescription:y,toolTags:o,toolTagsRef:l,toolSystemTags:c,setToolSystemTags:x,toolSystemTagsRef:h,applyToolTagsState:u}}function Bx({initialPrompt:t,routeToolId:s}){const r=n.useMemo(()=>!t||s?bh:vh(t),[t,s]),[a,o]=n.useState(()=>{const h=yh(s)||r;return{value:h,manualEdited:!1,lastAutoName:h,hasGeneratedSuggestion:!1}}),i=n.useRef(a),l=n.useCallback((x,h="system")=>{const y=Jo(x);o(u=>{const w={value:y,manualEdited:h==="manual"?!0:u.manualEdited,lastAutoName:h==="generated"?y:u.lastAutoName,hasGeneratedSuggestion:h==="generated"?!0:u.hasGeneratedSuggestion};return i.current=w,w})},[]),c=n.useCallback((x,h={})=>{const y=Jo(x);o(u=>{const w={value:y,manualEdited:h.markManualEdited?!0:u.manualEdited,lastAutoName:y,hasGeneratedSuggestion:h.markGeneratedSuggestion?!0:u.hasGeneratedSuggestion};return i.current=w,w})},[]);return n.useEffect(()=>{i.current=a},[a]),{toolName:a.value,toolNaming:a,setToolNaming:o,toolNamingRef:i,applyToolName:l,hydrateToolName:c}}const Ec=[300,800,1500];function $g(t){return new Promise(s=>setTimeout(s,t))}function Fx({previewRef:t,toolIdRef:s,toolMediaRef:r,setToolMedia:a}){const[o,i]=n.useState(!1),l=n.useRef(!1),c=n.useRef(null),x=n.useCallback(()=>{var _;if(!((_=t.current)!=null&&_.startThumbnailRecording))return Promise.resolve(null);if(l.current)return c.current??Promise.resolve(null);l.current=!0;const w=new Promise(v=>{const j=setTimeout(()=>{var A,I;(I=(A=t.current)==null?void 0:A.stopRecording)==null||I.call(A),v(null)},1e4);t.current.startThumbnailRecording(A=>{clearTimeout(j),v(A)})}).finally(()=>{l.current=!1,c.current=null});return c.current=w,w},[t]),h=n.useCallback(async(w,_,v)=>{let j=null;for(let L=0;L<=Ec.length;L+=1){if(L>0){const V=v==="custom_thumbnail"?r.current.custom_thumbnail:r.current.thumbnail_url;if(s.current!==w||V!==_)return}const P=await Vf(_,{requestPayload:{source_field:v,tool_id:w}});if(P.ok){j=P.stream;break}if(P.status!==409||L===Ec.length){console.warn("[ToolEditor] Thumbnail video stream was not created:",P);return}await $g(Ec[L])}if(!j||s.current!==w||(v==="custom_thumbnail"?r.current.custom_thumbnail:r.current.thumbnail_url)!==_)return;const I=await D.entities.Tool.get(w).catch(()=>null);I&&(v==="custom_thumbnail"?I.custom_thumbnail===_:I.thumbnail_url===_)&&(await D.entities.Tool.update(w,{thumbnail_stream_format:j.stream_format,thumbnail_stream_url:j.stream_url}),a(L=>(v==="custom_thumbnail"?L.custom_thumbnail===_:L.thumbnail_url===_)?{...L,thumbnail_stream_format:j.stream_format,thumbnail_stream_url:j.stream_url}:L))},[s,r,a]),y=n.useCallback(async(w,_)=>{if(!(!w||!_))try{const v=w.type.includes("mp4")?"mp4":"webm",j=new File([w],`thumbnail.${v}`,{type:w.type}),[A,I]=await Promise.all([dd(w),Ui(j).catch(()=>null)]),O=await Hi(j,{awaitStream:!1});if(O.file_url){const L={thumbnail_stream_format:null,thumbnail_stream_url:"",thumbnail_url:O.file_url,...typeof I=="number"?{thumbnail_aspect_ratio:I}:{}};if(A)try{const P=await D.integrations.Core.UploadFile({file:A});P!=null&&P.file_url&&(L.thumbnail_poster_url=P.file_url)}catch{}await D.entities.Tool.update(_,L),a(P=>({...P,thumbnail_stream_format:null,thumbnail_stream_url:null,thumbnail_url:L.thumbnail_url??P.thumbnail_url??null,thumbnail_poster_url:L.thumbnail_poster_url??P.thumbnail_poster_url??null,...typeof I=="number"?{thumbnail_aspect_ratio:I}:{}})),h(_,O.file_url,"thumbnail_url")}}catch(v){console.error("[ToolEditor] Failed to upload thumbnail:",v)}},[h,a]),u=n.useCallback(async()=>{i(!0);try{const w=await x();await y(w,s.current)}finally{i(!1)}},[x,y,s]);
64return{isCapturingThumbnail:o,recordThumbnailBlob:x,uploadThumbnailBlob:y,recordAndUploadThumbnail:u,createToolVideoStreamInBackground:h}}const Vg=800,Hg=4e3,Ic={duration:.24,ease:[.22,1,.36,1]},zg=4;function Dc(t,s){return!s||!t?t??[]:t.map(r=>r.type==="section"||r.type==="button"||!r.key||!(r.key in s)?r:{...r,default:s[r.key]})}async function Ug(t,s){const a=await(await fetch(t)).blob();return new File([a],s,{type:a.type||"image/jpeg"})}function Gg(){var Fo,fs,wi;Eu("ToolEditor");const t=Iu(),{mutateAsync:s}=Ip(),r=Du(),{toolId:a}=ql(),[o,i]=Mu(),[l]=n.useState(()=>a?"":o.get("prompt")||""),c=l,x=((Fo=r.state)==null?void 0:Fo.initialImageUrls)??[],h=((fs=r.state)==null?void 0:fs.initialReferenceFiles)??[],y=a?void 0:((wi=r.state)==null?void 0:wi.presetBrief)??void 0,{toolName:u,setToolNaming:w,toolNamingRef:_,applyToolName:v,hydrateToolName:j}=Bx({initialPrompt:c,routeToolId:a}),[A,I]=n.useState("chat"),[O,L]=n.useState(null),[P,V]=n.useState(null),[re,X]=n.useState(null),[je,he]=n.useState(!1),[me,T]=n.useState(""),[ee,ae]=n.useState(null),[ve,ue]=n.useState(null),[z,$]=n.useState(null),W=n.useRef(null),[ne,F]=n.useState(()=>new Set),te=n.useMemo(()=>[...ne],[ne]),Le=n.useCallback(p=>{F(g=>{if(!g.has(p))return g;const N=new Set(g);return N.delete(p),N})},[]),[Ke,oe]=n.useState(()=>new Set),st=n.useMemo(()=>[...Ke],[Ke]),rt=n.useCallback(p=>{oe(g=>{if(!g.has(p))return g;const N=new Set(g);return N.delete(p),N})},[]),[q,we]=n.useState([{type:"slider",key:"speed",label:"Speed",min:1,max:100,default:30,step:1},{type:"slider",key:"hue",label:"Hue Shift",min:0,max:360,default:180,step:1},{type:"slider",key:"scale",label:"Scale",min:1,max:20,default:5,step:1},{type:"color",key:"accent",label:"Accent Color",default:"#4a9eff"},{type:"toggle",key:"animate",label:"Animate",default:!0}]);Sp();const De=n.useRef(q);n.useEffect(()=>{De.current=q},[q]);const[ie,pe]=n.useState(""),[J,Ce]=n.useState([]),[se,Ot]=n.useState(""),[U,mt]=n.useState(null),[le,Se]=n.useState(null),[gt,Fe]=n.useState(null),[Te,Dt]=n.useState(null),[Dn,Ct]=n.useState({active:!1,tracked:[]}),qt=n.useCallback(p=>{Ct(g=>g.active===p.active&&g.tracked.join("\0")===p.trackedKeys.join("\0")?g:{active:p.active,tracked:p.trackedKeys})},[]),[Jn,dn]=n.useState(null),H=n.useRef(null),be=n.useCallback(p=>{dn(g=>({key:p,nonce:((g==null?void 0:g.nonce)??0)+1})),H.current&&clearTimeout(H.current),H.current=setTimeout(()=>dn(null),2200)},[]);n.useEffect(()=>()=>{H.current&&clearTimeout(H.current)},[]);const[xe,Y]=n.useState(null),[Ue,ut]=n.useState(null),[Ye,bt]=n.useState("idle"),Sn=n.useRef(!!a),Hn=n.useRef(!0);n.useEffect(()=>(Hn.current=!0,()=>{Hn.current=!1}),[]);const xa=n.useRef(!!c),[yr,zr]=n.useState(!1),[cr,as]=n.useState(!1),zs=n.useRef(!1),_r=n.useCallback(p=>{zs.current=p,as(p)},[]),dr=n.useRef(null),{user:Me}=za(),ei=Qc(),[Us,Gs]=n.useState(!1),[Ws,Ur]=n.useState(null),ur=Nx({generating:Ye==="loading"&&!cr,editingBorrowedTool:Us||!!Ws&&Ws!==(Me==null?void 0:Me.id),forceSurvey:o.get("survey")==="1"}),[Ge,qs]=n.useState(!1),[fn,Gr]=n.useState("draft"),[zn,Ts]=n.useState("private"),[wn,Ht]=n.useState(!1),[os,wr]=n.useState(!1),[Ks,Xn]=n.useState(!1),[Un,Rs]=n.useState(!1),[Xt,Tn]=n.useState(null),[fa,ma]=n.useState(null),[bs,Cr]=n.useState(!1),[Qn,ha]=n.useState(!1),[Wr,qr]=n.useState(!1),[Mt,Rn]=n.useState(null),[pr,xr]=n.useState(!1),[_o,is]=n.useState(!1),[Ys,jr]=n.useState(!1),[ls,fr]=n.useState(!1),[Ka,rn]=n.useState(!1),[ga,Zs]=n.useState(!1),[ba,Js]=n.useState(!1),[wo,Es]=n.useState(!1),[Co,Is]=n.useState(!1),[cs,Qt]=n.useState(""),[pt,Mn]=n.useState({custom_thumbnail:null,thumbnail_aspect_ratio:null,thumbnail_poster_url:null,thumbnail_stream_format:null,thumbnail_stream_url:null,thumbnail_url:null}),Kr=n.useRef(pt),[kr,Gn]=n.useState(null),[Lt,An]=n.useState(null),[vs,ds]=n.useState(!1),Wn=n.useRef(!1),mn=n.useRef(!1),[Rt,Xs]=n.useState(nt.export.defaultWidth),[jt,Pn]=n.useState(nt.export.defaultHeight),us=n.useRef({width:nt.export.defaultWidth,height:nt.export.defaultHeight}),[un,ps]=n.useState(!1),[an,Nr]=n.useState(null),hn=n.useMemo(()=>Yo(an??Rt/jt),[jt,Rt,an]),[gn,Yr]=n.useState(null),[Zr,va]=n.useState(0),Ds=n.useCallback(p=>{Yr(p),va(g=>g+1)}
64,[]),[ya,ys]=n.useState(!1),[Cn,C]=n.useState(!!a),[Q,Z]=n.useState(a??null),[Ae,xt]=n.useState(null),[At,Et]=n.useState(null),[Je,Sr]=n.useState(null),es=n.useMemo(()=>({...nt,export:{...nt.export,defaultWidth:Rt,defaultHeight:jt}}),[Rt,jt]),Ne=n.useRef(a||null),{toolDescription:qe,setToolDescription:qn,toolDescriptionRef:_s,applyToolDescription:ht,toolTags:zt,toolTagsRef:ws,toolSystemTags:Ya,setToolSystemTags:Jr,toolSystemTagsRef:en,applyToolTagsState:ce}=Lx({toolIdRef:Ne}),We=n.useRef(null),_a=n.useCallback(()=>We.current,[]);Au(_a);const mr=n.useRef(null),[ts,Bt]=n.useState(!1),{sendToolEditorAction:ot}=kx({toolId:Q}),$e=n.useCallback(()=>{Wn.current&&(Wn.current=!1,ot("tool_editor_settings_close"))},[ot]),{sendError:Tr}=jx(),Nt=n.useRef(null),{isCapturingThumbnail:Qs,recordThumbnailBlob:yt,uploadThumbnailBlob:wa,recordAndUploadThumbnail:Xr,createToolVideoStreamInBackground:jn}=Fx({previewRef:Nt,toolIdRef:Ne,toolMediaRef:Kr,setToolMedia:Mn}),kt=n.useRef(null),Ut=n.useCallback(()=>{const p=kt.current;return p?p():Promise.reject(new Error("[ToolEditor] Draft implementation resolver unavailable"))},[]),[hr,Ca]=n.useState(!1),Qr=n.useRef(!1),ja=n.useCallback(p=>{const g=p!==null;Qr.current=g,Ca(g)},[]),{controlValuesRef:On,getControlValuesForBake:xs,pauseAutosave:Ms,hydrateCheckpointsForImpl:pn,resetCheckpointsForSave:Pe,clearDraftTweaks:on}=Ax({draftImplId:U,previewImplId:(O==null?void 0:O.id)??null,persistencePaused:hr,canvasCode:ie,controlsSchemaRef:De,previewRef:Nt,setControlValuesChanged:xr,ensureDraftImplId:Ut}),ea=n.useCallback((p,g,N)=>{var k,E;we(f=>{const ge=f.map(de=>de.key===p?{...de,midi:g,default:N}:de);return De.current=ge,ge}),(E=(k=Nt.current)==null?void 0:k.patchControl)==null||E.call(k,p,{default:N})},[]),It=n.useCallback(p=>{we(g=>{const N=g.map(k=>{if(k.key!==p)return k;const{midi:E,...f}=k;return f});return De.current=N,N})},[]),Ft=n.useRef(null),gr=n.useRef(0),Rr=n.useRef(0),_e=n.useRef(!1),[Kt,St]=n.useState([]),[En,Kn]=n.useState(!1),[tn,lt]=n.useState(!1),_t=n.useRef(!1),nn=n.useCallback(p=>{_t.current=p,lt(p)},[]),B=n.useRef([]);n.useEffect(()=>{B.current=Kt},[Kt]);const Re=n.useRef(!1),et=n.useRef(null);n.useEffect(()=>{et.current=gn},[gn]);const $t=n.useRef(0),Yt=n.useRef(new Set),Zt=n.useRef(null),ta=n.useRef(null),Za=n.useRef(null),Er=n.useRef(!1);n.useEffect(()=>{Me!=null&&Me.id&&a&&op(Me.id,a)},[Me==null?void 0:Me.id,a]);const na=(Me==null?void 0:Me.role)==="admin",jo=na&&!!Ws&&Ws!==(Me==null?void 0:Me.id),As=jo?Ws:Me==null?void 0:Me.id,er=n.useRef([]),sn=td(),Ji=n.useRef(null),[Ps,sa]=n.useState(0),Ja=n.useRef(null),ko=ur.show?e.jsx(ax,{generationStatus:Ye==="ready"?"ready":Ye==="error"?"error":"loading",onDismiss:ur.onDismiss,toolId:Q,standalone:sn,bottomBarHeight:Ps,progressRef:Ja}):null,Os=ua(Rp)&&!sn,Xa=n.useRef(Os);n.useEffect(()=>{Xa.current=Os},[Os]);const Qa=n.useRef(Os);n.useEffect(()=>{Qa.current!==Os&&(Qa.current=Os,gn&&Ds(pa({name:u,controlsSchema:De.current,canvasCode:ie,libraries:J,customCss:se,controlValues:On.current,hideControlsOnMobile:!0,canvasConfig:es,editorMode:!0,externalControls:Os})))},[Os,gn,u,ie,J,se,es,On,Ds]);const eo=ed(sn?Me==null?void 0:Me.id:void 0),Jl=xh(Me),to=Me!=null&&Me.full_name?Me.full_name.split(" ").map(p=>p[0]).join("").toUpperCase().slice(0,2):void 0,ka=ua(Tp),no=ua(Ep),[ti,Xi]=n.useState(),Ls=n.useCallback(()=>{Xi(p=>(p??0)+1)},[]),So=n.useRef(Promise.resolve()),ns=na||no,To=ua(Xu),tr=n.useRef(null),ra=U??xe??null,Ro=n.useCallback(p=>{Xs(p.width),Pn(p.height),Nr(p.width/p.height)},[]),{controller:ni,getVersionPresets:br,flushPresets:aa}=Ox({activeVersionKey:ra,isHistoricalVersion:!!O,canvasSize:{width:Rt,height:jt},canvasSizeTweaked:un,thumbnailRefreshToken:ti,setCanvasSize:Ro,timeline:Te,timelineDockRef:tr,previewRef:Nt,toolName:u,controlsSchema:q,canvasCode:ie,libraries:J,customCss:se,onPreviewChange:ja}),[ct,Qi]=n.useState(320),[si,ri]=n.useState(!1),Xl=Zi(),[el,ai]=n.useState(!1),[Bs,Na]=n.useState(!1),{debugMode:oi,toggle:tl}=fd(ns),[nr,Eo]=n.useState(!1);n.useEffect(()=>{const p=Ji.current;if(!p){sa(0);return}const g=new ResizeObserver(()=>sa(p.offsetHeight));return g.observe(p),sa(p.offsetHeight),()=>g.disconnect()},[sn,Cn,nr,ur.show]);const[Ql,ec]=n.useState(0),nl=n.useRef(sn),Ir=n.useMemo(()=>({get current(){var p,g,N;return((N=(g=(p=Nt.current)==null?void 0:p.getIframeRefObj)==null?void 0:g.call(p))==null?void 0:N.current)??null}}),[]);n.useEffect(()=>{Kr.current=pt},[pt]),n.useEffect(()=>{const p=document.documentElement,g={overflow:p.style.overflow,scrollbarGutter:p.style.scrollbarGutter};return p.style.overflow="hidden",p.style.scrollbarGutter="auto",()=>{p.style.overflow=g.overflow,p.style.scrollbarGutter=g.scrollbarGutter}},[]);const ii=n.useCallback(()=>{Sn.current||(Sn.current=!0,zr(!0),dr.current&&clearTimeout(dr.current),dr.current=setTimeout(()=>zr(!1),6500))},[]);n.useEffect(()=>{Ye==="loading"&&!cr&&!Sn.current&&ii()},[Ye,cr]);const Dr=n.useCallback(p=>{var N,k,E;const g=(k=(N=Nt.current)==null?void 0:N.getIframeRefObj)==null?void 0:k.call(N);(E=g==null?void 0:g.current)!=null&&E.contentWindow&&yn(g,Pu,{collapsed:p}),Rs(p)},[Nt]),sl=Xt?`${window.location.origin}${Ho("ToolViewer")}?slug=${Xt}`:null,sr=n.useCallback(()=>{Q&&(ot("OpenProjection"),t(Ou({id:Q,slug:Xt??void 0})))},[Q,Xt,ot,t]),rl=n.useMemo(()=>Mt?pr||u!==Mt.toolName||qe!==Mt.toolDescription||JSON.stringify(zt)!==JSON.stringify(Mt.toolTags)||JSON.stringify(q)!==JSON.stringify(Mt.controlsSchema)||ie!==Mt.canvasCode||JSON.stringify(J)!==JSON.stringify(Mt.libraries)||se!==Mt.customCss:!1,[u,qe,zt,q,ie,J,se,Mt,pr]),tc=n.useMemo(()=>!Mt||!pr?!1:u===Mt.toolName&&qe===Mt.toolDescription&&JSON.stringify(zt)===JSON.stringify(Mt.toolTags)&&JSON.stringify(q)===JSON.stringify(Mt.controlsSchema)&&ie===Mt.canvasCode&&JSON.stringify(J)===JSON.stringify(Mt.libraries)&&se===Mt.customCss,[pr,u,qe,zt,q,ie,J,se,Mt]),Io=n.useMemo(()=>Wr?rl?"published_dirty":"published_clean":"draft",[Wr,rl]);n.useEffect(()=>{if(!a)return;X(null);let p=!1;return(async()=>{var g,N,k,E;try{let f=null;try{f=await D.entities.Tool.get(a)}catch{f=null}if(!f){Ie.error("Tool couldn't load due to a technical issue. Try again."),Ne.current=null,Z(null);return}if(p)return;Bl(f.id,f.name),Ap({currentName:_.current.value,persistedName:f.name,manualEdited:_.current.manualEdited,lastAutoName:_.current.lastAutoName,hasGeneratedSuggestion:_.current.hasGeneratedSuggestion})&&j(f.name),ht(f.description??"");const ge=f;ce(Ol(ge),Ll(ge)),Mn({custom_thumbnail:typeof f.custom_thumbnail=="string"?f.custom_thumbnail:null,thumbnail_aspect_ratio:typeof f.thumbnail_aspect_ratio=="number"?f.thumbnail_aspect_ratio:null,thumbnail_poster_url:typeof f.thumbnail_poster_url=="string"?f.thumbnail_poster_url:null,thumbnail_stream_format:typeof f.thumbnail_stream_format=="string"?f.thumbnail_stream_format:null,thumbnail_stream_url:typeof f.thumbnail_stream_url=="string"?f.thumbnail_stream_url:null,thumbnail_url:typeof f.thumbnail_url=="string"?f.thumbnail_url:null}),mn.current=!!(typeof f.custom_thumbnail=="string"&&f.custom_thumbnail);const de=f.visibility||(f.is_public?"public":"draft");qs(de==="public"),Gr(de),Ts(de==="draft"?"private":de),f.slug&&Tn(f.slug),Ur(f.user_id??f.creator_id??null),Gs(!!f.remixed_from),_e.current=!f.is_public&&!(typeof f.custom_thumbnail=="string"&&f.custom_thumbnail.trim())&&!(typeof f.thumbnail_url=="string"&&f.thumbnail_url.trim()),de!=="draft"&&f.slug&&qr(!0);const[G,ke]=await Promise.all([Rl(f).catch(()=>null),f.chat_session_id?D.entities.ChatSession.get(f.chat_session_id).catch(()=>null):Promise.resolve(null)]);if(f.uuid)We.current=f.uuid;else{const Oe=crypto.randomUUID();We.current=Oe,D.entities.Tool.update(f.id,{uuid:Oe}).catch(Gt=>{console.error("[ToolEditor] Failed to backfill tool UUID:",Gt)})}
64G&&G.revision==null?(mt(G.id),Se(G.uuid??null),G.canvas_width&&Xs(G.canvas_width),G.canvas_height&&Pn(G.canvas_height)):f.draft_implementation_uuid&&Se(f.draft_implementation_uuid),us.current=Gl(G==null?void 0:G.canvas_width,G==null?void 0:G.canvas_height),ps(!1),(g=G==null?void 0:G.design_brief)!=null&&g.text&&T(G.design_brief.text);let Be="";try{G?Be=await La(G):Be=await zo(f)}catch(Oe){console.warn("[ToolEditor] resolveCanvasCode failed, using inline canvas fields",Oe),Be=Ss("",f.draft_canvas_code,f.canvas_code)}const Xe=(N=G==null?void 0:G.controls_schema)!=null&&N.length?G.controls_schema:Ss([],f.draft_controls_schema,f.controls_schema),Ve=await Uo(Xe),Qe=(k=G==null?void 0:G.libraries)!=null&&k.length?G.libraries:Ss([],f.draft_libraries,f.libraries),bn=G!=null&&G.custom_css_url?await fetch(G.custom_css_url).then(Oe=>Oe.text()).catch(()=>""):Ss("",f.draft_custom_css,f.custom_css);we(Ve),pe(Be),Ce(Qe),Ot(bn),On.current=(G==null?void 0:G.control_values)??null;const ss=Go(G==null?void 0:G.timeline);Fe(ss),Dt(Ml(ss));const at=(G==null?void 0:G.control_values)??null;if(pn(G,at,{writeBackIfChanged:!0}),Ve.length>0||(Be||"").trim()){const Oe={...es,export:{...es.export,...(G==null?void 0:G.canvas_width)!=null&&{defaultWidth:G.canvas_width},...(G==null?void 0:G.canvas_height)!=null&&{defaultHeight:G.canvas_height}}},Gt=pa({name:f.name||"Untitled Tool",controlsSchema:Ve,canvasCode:Be||"",libraries:Qe,customCss:bn,controlValues:On.current,hideControlsOnMobile:!0,canvasConfig:Oe,editorMode:!0,externalControls:Xa.current});_e.current?(_e.current=!1,Do(Gt)):Ds(Gt)}else Yr(null);if(bt(Oe=>Oe==="loading"?Oe:"ready"),de!=="draft"&&f.slug){const Oe=await Lu(f).catch(()=>null);Oe&&(Y(Oe.id??null),ut(Oe.uuid??null));const Gt=Oe?await La(Oe):await zo({canvas_code_url:f.canvas_code_url,canvas_code:f.canvas_code});Rn({toolName:f.name||"Untitled Tool",toolDescription:_s.current,toolTags:ws.current,controlsSchema:(Oe==null?void 0:Oe.controls_schema)??f.controls_schema??[],canvasCode:Gt,libraries:(Oe==null?void 0:Oe.libraries)??f.libraries??[],customCss:f.custom_css||""})}if(ke!=null&&ke.id&&Et(ke.id),ke!=null&&ke.selected_model&&Sr(ke.selected_model),((E=ke==null?void 0:ke.messages)==null?void 0:E.length)>0)xt(ke.messages);else{const Oe=f.chat_history;let Gt=!1;if(Oe&&typeof Oe=="object"){const Tt=Object.keys(Oe);if(Tt.length>0){const Ze=Tt[Tt.length-1],Fn=Oe[Ze];Fn&&Fn.length>0&&(Et(Ze),xt(Fn),Gt=!0)}}if(!Gt&&a)try{const Tt=localStorage.getItem(`clay-chat-${a}`);if(Tt){const Ze=JSON.parse(Tt);Array.isArray(Ze)&&Ze.length>0&&xt(Ze)}}catch{}}p||gs.capture("tool_opened",{tool_id:f.id,tool_uuid:f.uuid,tool_name:f.name,visibility:f.visibility,is_public:f.is_public})}catch(f){console.error("[ToolEditor] Failed to load existing tool:",f)}finally{p||C(!1)}})(),()=>{p=!0}},[ht,ce,j,a]),n.useEffect(()=>{Ex()},[]),n.useEffect(()=>{const p=nl.current!==sn;p&&er.current.length>0&&xt([...er.current]),p&&Ye==="loading"&&bt("idle"),nl.current=sn},[sn]);const li=n.useRef(!1);n.useEffect(()=>{li.current||!c||(li.current=!0,sn&&!a&&ai(!0),i(p=>{const g=new URLSearchParams(p);return g.delete("prompt"),g.delete("plan"),g},{replace:!0}))},[c]);const ci=n.useCallback(p=>{const g=Ne.current;if(!g)return;const N=Jo(p);Bl(g,N),D.entities.Tool.update(g,{name:N}).catch(k=>console.error("[ToolEditor] Failed to save name:",k))},[]);n.useEffect(()=>{if(Cn||!Ne.current)return;const g=setTimeout(()=>ci(u),1500);return()=>clearTimeout(g)},[ci,Cn,u]);const al=n.useCallback(p=>{const g=_.current,N=p.name??"",k=Jo(N),E=Pp({currentName:g.value,suggestedName:N,manualEdited:g.manualEdited,lastAutoName:g.lastAutoName,alreadySuggested:g.hasGeneratedSuggestion});w(Be=>{const Xe=E?{value:k,manualEdited:Be.manualEdited,lastAutoName:k,hasGeneratedSuggestion:!0}:{...Be,hasGeneratedSuggestion:!0};return _.current=Xe,Xe});const f=(p.description??"").trim(),ge=!!f&&Op({currentDescription:_s.current,previousName:g.value}),de=ud(p.system_tags),G=ws.current,ke={system_tags:de,user_tags:G,tags:Wo(de,G)};E&&(ke.name=k),ge&&(ke.description=f,ht(f)),en.current=de,Jr(de),Ne.current&&D.entities.Tool.update(Ne.current,ke).catch(Be=>console.error("[ToolEditor] Failed to persist generated metadata:",Be))},[ht,w,_,Jr,_s,ws,en]),Mr=n.useCallback(async(p={})=>{var g,N;if(Ne.current)return Ne.current;try{const k=Me;if(!k)throw new Error("User not authenticated");const E=`tool-${Date.now().toString(36)}`,f=crypto.randomUUID(),ge=((g=p.name)==null?void 0:g.trim())||u||"Untitled Tool",de=Ba(ge),G=await Ul({name:ge,slug:E,user_id:k.id,uuid:f,description:de,is_public:!1},{id:k.id,full_name:k.full_name??null,email:k.email??void 0},{},{creationMode:p.creationMode??"prompt"});return Ne.current=G.id,Z(G.id),We.current=f,ht(de),(N=p.name)!=null&&N.trim()&&j(ge),p.deferNavigation||t(`/tooleditor/${G.id}`,{replace:!0}),G.id}catch(k){return console.error("[ToolEditor] Failed to create Tool record:",k),null}},[u,t,Me,ht,j]),Ln=n.useCallback(async p=>{const g=Ne.current??await Mr();if(!g)throw new Error("Tool not available");return await D.entities.Tool.update(g,p),g},[Mr]),ol=n.useCallback(async p=>{const g=qi(p);try{await Ln({user_tags:g,tags:Wo(en.current,g)}),ce(g)}catch(N){console.error("[ToolEditor] Failed to update tags:",N),Ie.error("Tags weren't updated due to a technical issue. Try again.")}},[ce,Ln,en]),so=n.useCallback(async p=>{const g=Mp(p).slice(0,Va);g&&await ol([...zt,g])},[zt,ol]),rr=n.useCallback(async p=>{const g=zt.filter(E=>E!==p),N=en.current,k={visual_behavior:N.visual_behavior.filter(E=>E!==p),use_case:N.use_case.filter(E=>E!==p)};try{await Ln({user_tags:qi(g),system_tags:k,tags:Wo(k,g)}),ce(g,k)}catch(E){console.error("[ToolEditor] Failed to update tags:",E),Ie.error("Tags weren't updated due to a technical issue. Try again.")}},[zt,Ln,ce,en]),Sa=n.useMemo(()=>`<!DOCTYPE html>
65<html>
66<head>
67  <meta charset="UTF-8">
68  <meta name="viewport" content="width=device-width, initial-scale=1.0">
69  <style>
70    body { margin: 0; padding: 0; background: transparent; }
71  </style>
72</head>
73<body></body>
74</html>`,[]),Do=n.useCallback(p=>{gr.current+=1,Rr.current=gr.current,Ds(p)},[Ds]),Bn=n.useCallback(async()=>{var p,g,N;if(Ne.current){ys(!0);try{const k=await D.entities.Tool.get(Ne.current),E=k;ce(Ol(E),Ll(E)),Mn({custom_thumbnail:typeof k.custom_thumbnail=="string"?k.custom_thumbnail:null,thumbnail_aspect_ratio:typeof k.thumbnail_aspect_ratio=="number"?k.thumbnail_aspect_ratio:null,thumbnail_poster_url:typeof k.thumbnail_poster_url=="string"?k.thumbnail_poster_url:null,thumbnail_stream_format:typeof k.thumbnail_stream_format=="string"?k.thumbnail_stream_format:null,thumbnail_stream_url:typeof k.thumbnail_stream_url=="string"?k.thumbnail_stream_url:null,thumbnail_url:typeof k.thumbnail_url=="string"?k.thumbnail_url:null}),mn.current=!!(typeof k.custom_thumbnail=="string"&&k.custom_thumbnail);const f=await Rl(k).catch(()=>null);
74f&&f.revision==null?(mt(f.id),Se(f.uuid??null),f.canvas_width&&Xs(f.canvas_width),f.canvas_height&&Pn(f.canvas_height)):k.draft_implementation_uuid&&Se(k.draft_implementation_uuid),us.current=Gl(f==null?void 0:f.canvas_width,f==null?void 0:f.canvas_height),ps(!1),(p=f==null?void 0:f.design_brief)!=null&&p.text&&T(f.design_brief.text);const ge=(g=f==null?void 0:f.controls_schema)!=null&&g.length?f.controls_schema:Ss([],k.draft_controls_schema,k.controls_schema),de=await Uo(ge),G=f?await La(f):await zo(k),ke=(N=f==null?void 0:f.libraries)!=null&&N.length?f.libraries:Ss([],k.draft_libraries,k.libraries),Be=f!=null&&f.custom_css_url?await fetch(f.custom_css_url).then(at=>at.text()).catch(()=>""):Ss("",k.draft_custom_css,k.custom_css),Xe=new Set;De.current.forEach(at=>{at.key&&Xe.add(at.key)});const Ve=[];de.forEach(at=>{at.key&&!Xe.has(at.key)&&Ve.push(at.key)}),Xe.size>0&&Ve.length>0&&F(at=>{const Oe=new Set(at);return Ve.forEach(Gt=>Oe.add(Gt)),Oe}),F(at=>{let Oe=!1;const Gt=new Set,Tt=new Set(de.map(Ze=>Ze.key).filter(Ze=>!!Ze));return at.forEach(Ze=>{Tt.has(Ze)?Gt.add(Ze):Oe=!0}),Oe?Gt:at});const Qe=Tx(De.current,de);Qe.length>0&&oe(at=>{const Oe=new Set(at);return Qe.forEach(Gt=>Oe.add(Gt)),Oe}),oe(at=>{let Oe=!1;const Gt=new Set,Tt=new Set(de.filter(Ze=>Ze.type==="section"&&Ze.label).map(Ze=>Ze.label));return at.forEach(Ze=>{Tt.has(Ze)?Gt.add(Ze):Oe=!0}),Oe?Gt:at}),we(de),pe(G),Ce(ke),Ot(Be),On.current=(f==null?void 0:f.control_values)??null;const bn=Go(f==null?void 0:f.timeline);Fe(bn),Dt(Ml(bn));const ss=(f==null?void 0:f.control_values)??null;if(pn(f,ss),de.length>0||G){const at={...es,export:{...es.export,...(f==null?void 0:f.canvas_width)!=null&&{defaultWidth:f.canvas_width},...(f==null?void 0:f.canvas_height)!=null&&{defaultHeight:f.canvas_height}}},Oe=pa({name:u,controlsSchema:de,canvasCode:G,libraries:ke,customCss:Be,controlValues:On.current,hideControlsOnMobile:!0,canvasConfig:at,editorMode:!0,externalControls:Xa.current});Do(Oe)}bt("ready")}catch(k){console.warn("[ToolEditor] Failed to rebuild preview from structured update:",k)}finally{ys(!1)}}},[u,Do,es,ce,On,pn]),Mo=n.useCallback(()=>{So.current=Bn()},[Bn]),il=n.useCallback(async(p,g)=>{try{const N=await D.entities.ToolImplementation.get(p),k=(N==null?void 0:N.controls_schema)??[],E=await Uo(k),f=N?await La(N):"",ge=(N==null?void 0:N.libraries)??[],de=N!=null&&N.custom_css_url?await fetch(N.
74custom_css_url).then(Be=>Be.text()).catch(()=>""):"",G=(N==null?void 0:N.control_values)??null,ke=pa({name:u,controlsSchema:E,canvasCode:f,libraries:ge,customCss:de,controlValues:G,hideControlsOnMobile:!0,canvasConfig:es,editorMode:!0,externalControls:Xa.current});Ds(ke),we(E),On.current=G,L({id:p,label:g}),ot("version_preview")}catch(N){console.warn("[ToolEditor] handlePreviewVersion failed:",N)}},[u,es,ot,On,Ds]),oa=n.useCallback(async({snapshotId:p,chatSessionEntityId:g})=>{var N;if(!U)throw new Error("[ToolEditor] No draft implementation loaded — cannot revert");Kn(!0);try{let k=g;if(We.current)try{const Xe=await D.entities.Tool.filter({uuid:We.current}),Ve=(N=Xe==null?void 0:Xe[0])==null?void 0:N.chat_session_id;Ve&&(Ve!==g&&console.warn("[ToolEditor] chatSessionEntityId mismatch on revert — using authoritative ID",{provided:g,authoritative:Ve}),k=Ve)}catch(Xe){console.warn("[ToolEditor] Could not fetch authoritative chat_session_id from Tool — using provided ID",Xe)}const f=(await D.entities.ChatSession.get(k)).messages??[];let ge=-1;for(let Xe=f.length-1;Xe>=0;Xe--)if(f[Xe].tool_snapshot_id===p){ge=Xe;break}const de=await D.entities.ToolImplementation.get(p),G=ge===-1,ke=G?[]:f.slice(0,ge+1);await D.entities.ChatSession.update(k,{messages:ke});try{await D.entities.ToolImplementation.update(U,{controls_schema:de.controls_schema??[],libraries:de.libraries??[],...de.canvas_code_url!=null&&{canvas_code_url:de.canvas_code_url},...de.custom_css_url!=null&&{custom_css_url:de.custom_css_url},...de.technology!=null&&{technology:de.technology},...de.canvas_width!=null&&{canvas_width:de.canvas_width},...de.canvas_height!=null&&{canvas_height:de.canvas_height}})}catch(Xe){throw console.warn("[ToolEditor] Code restore failed — rolling back ChatSession history",Xe),await D.entities.ChatSession.update(k,{messages:f}).catch(Ve=>console.error("[ToolEditor] ChatSession rollback also failed — history may be truncated",Ve)),Xe}(G?f:f.slice(ge+1)).map(Xe=>Xe.tool_snapshot_id).filter(Boolean).forEach(Xe=>D.entities.ToolImplementation.delete(Xe).catch(()=>null));try{await Bn(),Ls()}catch(Xe){console.warn("[ToolEditor] Canvas refresh failed after revert — revert data is saved, UI may need a refresh",Xe)}return k}finally{Kn(!1)}},[U,Bn,Ls]),Ta=n.useCallback(async()=>{if(!We.current||!Ne.current)throw new Error("[ToolEditor] Cannot ensure draft — missing tool");const p=crypto.randomUUID();let g={tool_uuid:We.current,uuid:p,user_id:As,is_public:!1,controls_schema:[],libraries:[]};if(xe){const E=await D.entities.ToolImplementation.get(xe);g={...g,controls_schema:(E==null?void 0:E.controls_schema)??[],libraries:(E==null?void 0:E.libraries)??[],...(E==null?void 0:E.canvas_code_url)!=null&&{canvas_code_url:E.canvas_code_url},...(E==null?void 0:E.custom_css_url)!=null&&{custom_css_url:E.custom_css_url},...(E==null?void 0:E.canvas_width)!=null&&{canvas_width:E.canvas_width},...(E==null?void 0:E.canvas_height)!=null&&{canvas_height:E.canvas_height},...(E==null?void 0:E.control_values)!=null&&{control_values:E.control_values},...(E==null?void 0:E.design_brief)!=null&&{design_brief:E.design_brief},...(E==null?void 0:E.timeline)!=null&&{timeline:E.timeline},...(E==null?void 0:E.presets)!=null&&{presets:E.presets},...(E==null?void 0:E.technology)!=null&&{technology:E.technology}}}else if(Ue){const E=await D.entities.ToolImplementation.filter({uuid:Ue}),f=E==null?void 0:E[0];f&&(g={...g,controls_schema:(f==null?void 0:f.controls_schema)??[],libraries:(f==null?void 0:f.libraries)??[],...(f==null?void 0:f.canvas_code_url)!=null&&{canvas_code_url:f.canvas_code_url},...(f==null?void 0:f.custom_css_url)!=null&&{custom_css_url:f.custom_css_url},...(f==null?void 0:f.canvas_width)!=null&&{canvas_width:f.canvas_width},...(f==null?void 0:f.canvas_height)!=null&&{canvas_height:f.canvas_height},...(f==null?void 0:f.control_values)!=null&&{control_values:f.control_values},...(f==null?void 0:f.design_brief)!=null&&{design_brief:f.design_brief},...(f==null?void 0:f.timeline)!=null&&{timeline:f.timeline},...(f==null?void 0:f.presets)!=null&&{presets:f.presets},...(f==null?void 0:f.technology)!=null&&{technology:f.technology}})}const N=await D.entities.ToolImplementation.create(g),k=N==null?void 0:N.id;if(!k)throw new Error("[ToolEditor] Failed to create draft implementation");return mt(k),Se(p),await D.entities.Tool.update(Ne.current,{draft_implementation_uuid:p}),k},[As,xe,Ue]),ro=n.useRef(null),ia=n.useCallback(async()=>U||(ro.current||(ro.current=Ta().finally(()=>{ro.current=null})),ro.current),[Ta,U]);kt.current=ia;const ll=n.useCallback(async(p,g)=>{if(!Ne.current&&!p.canvasCode.trim())throw new Error("This source file has no tool code to import.");const k={id:null},E=async()=>
74{if(!Ne.current&&(k.id=await Mr({name:gx(p,g),creationMode:"import",deferNavigation:!0}),!k.id))throw new Error("Could not create the tool for this import");return ia()};try{await bx(p,{ensureDraftImplId:E,handleStructuredUpdate:Bn})}finally{k.id&&Hn.current&&t(`/tooleditor/${k.id}`,{replace:!0})}Sn.current=!0},[ia,Mr,Bn,t]),Ra=n.useCallback(async p=>{var g,N;if(!We.current)throw new Error("[ToolEditor] Missing tool — cannot restore");Kn(!0);try{const k=await ia(),E=await D.entities.ToolImplementation.filter({tool_uuid:We.current}).catch(()=>[]);if(xe||Ue){const Be=E.filter(Ve=>Ve.source_message_id).sort((Ve,Qe)=>new Date(Qe.created_date??0).getTime()-new Date(Ve.created_date??0).getTime());if(!Be.some(Ve=>!!xe&&Ve.id===xe||!!Ue&&!!Ve.uuid&&Ve.uuid===Ue)){const Ve=(P&&Be.some(Qe=>Qe.id===P)?P:null)??((g=Be.find(Qe=>Qe.id===U))==null?void 0:g.id)??((N=Be[0])==null?void 0:N.id)??null;Ve&&!P&&X(Qe=>Qe??Ve)}}const f=await D.entities.ToolImplementation.get(p),ge={controls_schema:f.controls_schema??[],libraries:f.libraries??[],...f.canvas_code_url!=null&&{canvas_code_url:f.canvas_code_url},...f.custom_css_url!=null&&{custom_css_url:f.custom_css_url},...f.technology!=null&&{technology:f.technology},...f.canvas_width!=null&&{canvas_width:f.canvas_width},...f.canvas_height!=null&&{canvas_height:f.canvas_height},...f.control_values!=null&&{control_values:f.control_values},...f.design_brief!=null&&{design_brief:f.design_brief},...f.timeline!=null&&{timeline:f.timeline}},de=Math.max(0,...E.filter(Be=>Be.revision!=null).map(Be=>Be.revision)),G=await D.entities.ToolImplementation.create({tool_uuid:We.current,uuid:crypto.randomUUID(),user_id:f.user_id??As,is_public:!1,revision:de+1,source_message_id:`restore:${crypto.randomUUID()}`,...ge}),ke=G==null?void 0:G.id;if(!ke)throw new Error("[ToolEditor] Failed to create restored version snapshot");await D.entities.ToolImplementation.update(k,ge),V(ke),L(null);try{await Bn(),Ls()}catch(Be){console.warn("[ToolEditor] Canvas refresh failed after restore — draft is saved, UI may need a refresh",Be)}return ke}finally{Kn(!1)}},[P,U,ia,As,Bn,xe,Ue,Ls]),di=n.useCallback(()=>{L(null),ot("version_preview_exit"),Bn()},[Bn,ot]),ui=n.useCallback(()=>{if(!O)return;if(Ye==="loading"){console.warn("[ToolEditor] Restore blocked — generation in progress");return}const p=O.id;gs.capture(Fa.VERSION_RESTORED,{tool_id:Ne.current,tool_uuid:We.current,impl_id:p}),ot("version_restore"),Ra(p).then(()=>{I("chat")}).catch(g=>{console.warn("[ToolEditor] Restore from preview bar failed:",g),Ie.error("Version wasn't restored due to a technical issue. Try again.")})},[O,Ye,Ra,ot]),cl=n.useCallback(p=>{bt(p)},[]),pi=n.useCallback(p=>{bt("error"),console.error("[ToolPreview]",p instanceof Error?p.message:p)},[]),Ao=n.useCallback(p=>{p.level!=="warning"&&Tr({error_type:"tool_runtime",error_message:p.message??"",tool_id:Q??void 0,error_data:{attempt_number:$t.current,error_count:B.current.length,is_post_generation:_t.current,line:p.line??void 0,model:Zt.current??void 0,stack_head:Cx(p.stack)}})},[Q,Tr]),Cs=n.useCallback(()=>{ta.current&&(clearTimeout(ta.current),ta.current=null),Za.current&&(clearTimeout(Za.current),Za.current=null)},[]),Ea=n.useCallback(p=>{Cs(),Er.current=!1,$t.current=0,Yt.current=new Set,Zt.current=null,nn(!1),p==="clean"?ot("auto_fix_verified_clean"):p==="exhausted"&&(ot("auto_fix_exhausted"),Ie.info("Couldn't auto-fix this one",{description:"Try refreshing the page, or remix the tool and continue from there."}))},[Cs,nn,ot]),Ia=n.useCallback((p=!1)=>{const g=B.current??[],N=g.filter(ke=>ke.level!=="warning");if(N.length===0){if(!p&&!Re.current)return;Er.current=!1,Ea("clean");return}Er.current=!1;const k=$t.current,E=Zt.current??zl[0],f=Sx(k,E,Yt.current);if(!f||!W.current){Ea("exhausted");return}const ge=N.map((ke,Be)=>`${Be+1}. ${ke.message??""}${ke.line?` (line ${ke.line})`:""}`).join(`
75`),de=g.filter(ke=>ke.level==="warning"),G=de.length?`
76
77Also present (fix only if they indicate a real bug, ignore cosmetic/deprecation noise):
78${de.map((ke,Be)=>`${Be+1}. ${ke.message??""}`).join(`
79`)}`:"";$t.current=k+1,Yt.current.add(f),ot("auto_fix_attempt"),W.current.sendMessage(`The preview produced these issues. Fix them so the tool runs cleanly:
80
81${ge}${G}`,{modelOverride:f,isAutoFix:!0})},[Ea,ot]),nc=n.useCallback(p=>{var N;if(!et.current)return;Re.current=!0,na&&((N=W.current)==null||N.attachHealth(p));const g=[];if(p.canvasOk===!1){const k=p.canvasReason??`no render surface — no sized, visible <canvas> was found (canvas ${p.canvasWidth??0}×${p.canvasHeight??0})`;g.push({biData:{error_type:"tool_health_blank_canvas",error_message:k,error_data:{attempt_number:$t.current,canvas_height:p.canvasHeight??void 0,canvas_width:p.canvasWidth??void 0,model:Zt.current??void 0}},payload:{level:"error",message:`Tool health: ${k}. Nothing is rendering. Brik exports the <canvas>, so every tool MUST render to the provided canvas/ctx (or a framework canvas like Three.js) — ensure it is created, sized, visible, and drawn to. Do NOT render to <svg> or other DOM; that exports blank.`}})}
81if(p.controlsOk===!1&&g.push({biData:{error_type:"tool_health_controls",error_message:`only ${p.controlsRendered??0} of ${p.controlsDeclared??0} declared controls rendered`,error_data:{attempt_number:$t.current,controls_declared:p.controlsDeclared??void 0,controls_rendered:p.controlsRendered??void 0,model:Zt.current??void 0}},payload:{level:"error",message:`Tool health: only ${p.controlsRendered??0} of ${p.controlsDeclared??0} declared controls rendered. The controls panel is not wired up — every control in the schema must be created via the controls API and read by the canvas code.`}}),g.length>0){const k=B.current??[],E=new Set(k.map(ge=>ge.message)),f=g.filter(ge=>!E.has(ge.payload.message));if(f.length>0){const ge=[...k,...f.map(de=>de.payload)];B.current=ge,St(ge),f.forEach(de=>Tr({...de.biData,tool_id:Q??void 0}))}}_t.current&&Er.current&&Ia(!1)},[Q,Ia,na,Tr]),xi=n.useCallback(()=>{Cs(),ta.current=setTimeout(Ia,Vg)},[Cs,Ia]),fi=n.useCallback(p=>{if(!p.ok){_t.current&&Ea("aborted");return}if(!p.codeWritten){_t.current&&Ea("clean");return}V(null),L(null),So.current.then(()=>Ls()).catch(g=>console.warn("[presets] post-chat thumbnail refresh skipped",g)),Zt.current==null&&(Zt.current=p.model),nn(!0),Er.current=!0,Re.current=!1,Cs(),Za.current=setTimeout(()=>{Er.current&&Ia(!0)},Hg)},[Ea,nn,Cs,Ia,Ls]);n.useEffect(()=>Cs,[Cs]);const mi=n.useCallback(async p=>{if(p.size>5*1024*1024){Ie.error("Image cover must be 5MB or smaller");return}Gn("static-upload");try{const g=await Ui(p).catch(()=>hn),{file_url:N}=await D.integrations.Core.UploadFile({file:p});await Ln({thumbnail_aspect_ratio:g,thumbnail_poster_url:N}),Mn(k=>({...k,thumbnail_aspect_ratio:g,thumbnail_poster_url:N})),mn.current=!0,ds(!0)}catch(g){console.error("[ToolEditor] Failed to upload static cover:",g),Ie.error("Cover wasn't updated due to a technical issue. Try again.")}finally{Gn(null)}},[hn,Ln]),ao=n.useCallback(async p=>{if(p.size>5*1024*1024){Ie.error("Video cover must be 5MB or smaller");return}Gn("dynamic-upload");try{const g=await Ui(p).catch(()=>hn),[N,k]=await Promise.all([Hi(p,{awaitStream:!1}),dd(p)]),E={custom_thumbnail:N.file_url,thumbnail_aspect_ratio:g,thumbnail_stream_format:null,thumbnail_stream_url:""};let f=null;if(k){const ge=await D.integrations.Core.UploadFile({file:k});f=ge.file_url,E.thumbnail_poster_url=ge.file_url}await Ln(E),Mn(ge=>({...ge,custom_thumbnail:N.file_url,thumbnail_aspect_ratio:g,thumbnail_stream_format:null,thumbnail_stream_url:null,thumbnail_poster_url:f??ge.thumbnail_poster_url??null})),Ne.current&&jn(Ne.current,N.file_url,"custom_thumbnail"),mn.current=!0,ds(!0)}catch(g){console.error("[ToolEditor] Failed to upload dynamic cover:",g),Ie.error("Cover wasn't updated due to a technical issue. Try again.")}finally{Gn(null)}},[hn,jn,Ln]),Fs=n.useCallback(p=>{var N,k,E;const g=(k=(N=Nt.current)==null?void 0:N.getIframeRefObj)==null?void 0:k.call(N);(E=g==null?void 0:g.current)!=null&&E.contentWindow&&yn(g,Bu,{capturing:p})},[Nt]),Ar=n.useCallback(()=>{An("static"),Fs(!0)},[Fs]),Da=n.useCallback(()=>{An("dynamic"),Fs(!0)},[Fs]),Po=n.useCallback(async p=>{Gn("static-capture");try{const g=await Ug(p,"static-cover.jpg"),{file_url:N}=await D.integrations.Core.UploadFile({file:g});await Ln({thumbnail_aspect_ratio:hn,thumbnail_poster_url:N}),Mn(k=>({...k,thumbnail_aspect_ratio:hn,thumbnail_poster_url:N})),mn.current=!0,ds(!0),An(null),Fs(!1),Wn.current&&(Wn.current=!1,Bt(!0))}catch(g){console.error("[ToolEditor] Failed to capture static cover:",g),Ie.error("Cover wasn't captured due to a technical issue. Try again."),$e()}finally{Gn(null)}},[$e,hn,Ln,Fs]),hi=n.useCallback(async(p,g)=>{Gn("dynamic-record");try{const N=Dp(g),k=new File([p],`dynamic-cover.${N}`,{type:g||p.type}),E=await Hi(k,{awaitStream:!1});await Ln({custom_thumbnail:E.file_url,thumbnail_aspect_ratio:hn,thumbnail_stream_format:null,thumbnail_stream_url:""}),Mn(f=>({...f,custom_thumbnail:E.file_url,thumbnail_aspect_ratio:hn,thumbnail_stream_format:null,thumbnail_stream_url:null})),Ne.current&&jn(Ne.current,E.file_url,"custom_thumbnail"),mn.current=!0,ds(!0),An(null),Fs(!1),Wn.current&&(Wn.current=!1,Bt(!0))}catch(N){console.error("[ToolEditor] Failed to record dynamic cover:",N),Ie.error("Cover wasn't recorded due to a technical issue. Try again."),$e()}finally{Gn(null)}},[$e,hn,jn,Ln,Fs]),Oo=n.useCallback(()=>{An(null),Fs(!1),$e()},[$e,Fs]),sc=n.useCallback(p=>{console.warn("[ToolEditor] Cover capture failed:",p),Ie.error("Cover wasn't captured due to a technical issue. Try again."),Oo()},[Oo]),rc=n.useCallback(()=>
81{if(bt("ready"),Er.current&&xi(),mn.current||Rr.current===0||Rr.current!==gr.current)return;Rr.current=0,Ft.current&&clearTimeout(Ft.current);const p=gr.current;Ft.current=setTimeout(()=>{gr.current===p&&Xr()},2e3)},[Xr,xi]),Lo=n.useCallback(async()=>{var g,N;const p=Ms();try{const k=$a(q,ie),E=await xs(k),f=await ho(E,k,D),ge=Dc(k,f),{schema:de,skippedKeys:G}=await xo(ge),ke=ie?await fo(ie):null,Be=se?await mo(se):null,Xe=Ne.current??await Mr();if(!Xe)throw new Error("Tool not available");let Ve=U,Qe=le;const bn=Pe(Ve);if(Ve)await D.entities.ToolImplementation.update(Ve,{canvas_code_url:ke??"",controls_schema:de,libraries:J,custom_css_url:Be??"",control_values:{},control_checkpoints:bn,timeline:Te});else{const at=crypto.randomUUID();Ve=(await D.entities.ToolImplementation.create({tool_uuid:We.current,uuid:at,user_id:As,is_public:!1,canvas_code_url:ke??"",controls_schema:de,libraries:J,timeline:Te,...Be?{custom_css_url:Be}:{},...Rt!==nt.export.defaultWidth?{canvas_width:Rt}:{},...jt!==nt.export.defaultHeight?{canvas_height:jt}:{}})).id,Qe=at,mt(Ve),Se(Qe),await D.entities.Tool.update(Xe,{draft_implementation_uuid:Qe})}await D.entities.Tool.update(Xe,{name:u,description:qe}),we(ge),xr(!1),on();const ss=(N=(g=Nt.current)==null?void 0:g.getIframeRefObj)==null?void 0:N.call(g);ss&&f&&yn(ss,El,f),G.length?Ie.info("Saved. The canvas drawing was too large to store."):Ie.success("Saved.")}catch(k){console.error("[ToolEditor] Save failed:",k),Ie.error("Tool wasn't saved due to a technical issue. Try again.")}finally{p()}},[ie,jt,Rt,on,q,se,U,le,As,Mr,xs,J,Te,Ms,Pe,qe,u]);n.useEffect(()=>{const p=()=>{Cn||wn||os||Lo()},g=k=>{!(k.metaKey||k.ctrlKey)||k.key!=="s"&&k.key!=="S"||(k.preventDefault(),p())};window.addEventListener("keydown",g);const N=$n(k=>{k.type===Fu&&p()});return()=>{window.removeEventListener("keydown",g),N()}},[Lo,Cn,wn,os]),n.useEffect(()=>Wr?$n(g=>{var N;if(g.type===rd){const k=(N=g.payload)==null?void 0:N.dirty;xr(k===void 0?!0:!!k)}}):void 0,[Wr]),n.useEffect(()=>$n(p=>{var N,k;if(p.type!==$u)return;const g=(N=p.payload)==null?void 0:N.key;g&&((k=tr.current)==null||k.addOrRevealTrack(g))}),[]),n.useEffect(()=>$n(g=>{var k,E;if(g.type!==Vu)return;const N=(E=(k=Nt.current)==null?void 0:k.getIframeRefObj)==null?void 0:E.call(k);N&&(yn(N,Hu),yn(N,zu,{schema:De.current}))}),[Nt]),n.useEffect(()=>$n(g=>{var k,E;if(g.type!==Uu)return;const N=(E=(k=Nt.current)==null?void 0:k.getIframeRefObj)==null?void 0:E.call(k);N&&yn(N,Bc)}),[Nt]),n.useEffect(()=>$n(g=>{var N,k;if(g.type===Gu&&((N=g.payload)!=null&&N.schema)){const E=g.payload.schema,f=De.current;if(JSON.stringify(f)===JSON.stringify(E))return;const ge=ke=>new Set(ke.filter(Be=>!Be.deleted&&Be.key).map(Be=>Be.key)),de=ge(E),G=[...ge(f)].filter(ke=>!de.has(ke));we(E),G.length>0&&((k=tr.current)==null||k.dropTracks(G)),U&&!O&&D.entities.ToolImplementation.update(U,{controls_schema:E}).catch(ke=>{console.error("[ToolEditor] Failed to save schema from edit mode",ke)})}}),[U,O]);const{handleToggleControlVisibility:dl,handleDeleteControl:gi,handleRenameControl:Bo,handleReorderControls:ul,handleBulkSetVisibility:oo,handleBulkDeleteControls:bi,handleMoveControlsToSection:ac}=_x({setControlsSchema:we,draftImplId:U,dropTracks:p=>{var g;return(g=tr.current)==null?void 0:g.dropTracks(p)},isPreviewingVersion:!!O});n.useEffect(()=>$n(g=>{var N,k;if(g.type===Wu){const E=g.payload,f=E==null?void 0:E.w,ge=E==null?void 0:E.h;if(typeof f=="number"&&typeof ge=="number"&&f>0&&ge>0){if(Xs(f),Pn(ge),Nr(f/ge),E!=null&&E.userInitiated&&!O&&!Qr.current){const de=us.current;ps(f!==de.width||ge!==de.height)}U&&!O&&!Qr.current&&D.entities.ToolImplementation.update(U,{canvas_width:f,canvas_height:ge}).catch(de=>{console.error("[ToolEditor] Failed to persist canvas size",de)})}}if(g.type===qu){const E=(N=g.payload)==null?void 0:N.width,f=(k=g.payload)==null?void 0:k.height;typeof E=="number"&&typeof f=="number"&&E>0&&f>0&&Nr(E/f)}}),[U,O]),n.useEffect(()=>()=>{Ft.current&&clearTimeout(Ft.current),Rr.current=0},[]);const pl=n.useMemo(()=>ie?Ku({name:u,controlsSchema:q,canvasCode:ie,libraries:J,customCss:se,timeline:Te}):null,[u,q,ie,J,se,Te]),Ma=n.useMemo(()=>Go(Te)??gt,[Te,gt]),xl=n.useMemo(()=>({id:Ne.current,uuid:We.current,controlsSchema:q,canvasCode:ie,libraries:J,customCss:se,slug:Xt??void 0,visibility:fn,isPublic:Ge}),[q,ie,J,se,Xt,fn,Ge]),io=async p=>{Ht(!0),Ft.current&&(clearTimeout(Ft.current),Ft.current=null);const N=`${u.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"untitled"}-${Date.now().toString(36)}`;let k=Promise.resolve(null);const E=Ms();try{const f=$a(q,ie),ge=await xs(f);k=yt().catch(()=>null);const de=await ho(ge,f,D),G=Dc(f,de),{schema:ke,skippedKeys:Be}=await xo(G),Xe=await fo(ie),Ve=se?await mo(se):null,Qe=p??zn,bn=Qe==="public",ss=Qe==="public",at=Al(await br());if(Ne.current){const Tt=await D.entities.ToolImplementation.filter({tool_uuid:We.current}).catch(()=>[]),Fn=Math.max(0,...Tt.filter(ln=>ln.revision!=null).map(ln=>ln.revision))+1;let ms=U,js=le;if(ms){await D.entities.ToolImplementation.update(ms,{revision:Fn,is_public:bn,canvas_code_url:Xe,controls_schema:ke,libraries:J,custom_css_url:Ve||"",control_values:{},control_checkpoints:Pe(ms),timeline:Te,...Rt!==nt.export.defaultWidth?{canvas_width:Rt}:{},...jt!==nt.export.defaultHeight?{canvas_height:jt}:{},...at!==void 0?{presets:at}:{}});const ln=await D.entities.ToolImplementation.get(ms);js=(ln==null?void 0:ln.uuid)??js}else{const ln=crypto.randomUUID(),Or=await D.entities.ToolImplementation.create({tool_uuid:We.current,uuid:ln,user_id:As,is_public:bn,revision:Fn,canvas_code_url:Xe,controls_schema:ke,libraries:J,timeline:Te,...Ve?{custom_css_url:Ve}:{},...Rt!==nt.export.defaultWidth?{canvas_width:Rt}:{},...jt!==nt.export.defaultHeight?{canvas_height:jt}:{},...at!==void 0?{presets:at}:{}});ms=(Or==null?void 0:Or.id)??void 0,js=ln}await D.entities.Tool.update(Ne.current,{name:u,slug:N,is_public:ss,visibility:Qe,description:qe||Ba(u),published_implementation_uuid:js,draft_implementation_uuid:""}),xe&&xe!==ms&&Tt.some(Or=>Or.id===xe)&&D.entities.ToolImplementation.delete(xe).catch(()=>null),Y(ms),ut(js),V(null),X(null),mt(null),Se(null)}else{const Tt=Me;if(!Tt)throw new Error("Not authenticated");const Ze=crypto.randomUUID(),Fn=await Ul({name:u,slug:N,description:qe||Ba(u),is_public:ss,visibility:Qe,user_id:Tt.id,uuid:Ze},{id:Tt.id,full_name:Tt.full_name??null,email:Tt.email??null},{},{creationMode:"prompt"});Ne.current=Fn.id,Z(Fn.id),We.current=Ze,t(`/tooleditor/${Fn.id}`,{replace:!0});const ms=crypto.randomUUID(),js=await D.entities.ToolImplementation.create({tool_uuid:Ze,uuid:ms,user_id:Tt.id,is_public:bn,revision:1,canvas_code_url:Xe,controls_schema:ke,libraries:J,timeline:Te,...Ve?{custom_css_url:Ve}:{},...Rt!==nt.export.defaultWidth?{canvas_width:Rt}:{},...jt!==nt.export.defaultHeight?{canvas_height:jt}:{},...at!==void 0?{presets:at}:{}});await D.entities.Tool.update(Fn.id,{published_implementation_uuid:js.uuid}),Y(js.id),ut(js.uuid)}Ne.current&&Qu({toolId:Ne.current,designBrief:me}).catch(Tt=>console.warn("[ToolEditor] Metadata refresh failed:",Tt)),we(G),Tn(N),qs(ss),Gr(Qe),Ts(Qe),qr(!0),xr(!1),on(),Rn({toolName:u,toolDescription:qe,toolTags:zt,controlsSchema:G,canvasCode:ie,libraries:J,customCss:se}),is(!1);const Oe=Ne.current;k.then(Tt=>wa(Tt,Oe)),Be.length&&Ie.info("Published. The canvas drawing was too large to store."),Xn(!0);const Gt={tool_id:Ne.current??void 0,userId:Me==null?void 0:Me.id};ir(lr.TOOL_PUBLISHED,Il(Gt),Gt,{tool_uuid:We.current,visibility:Qe,slug:N,tag_count:zt.length,controls_count:ke.length,is_republish:!1}),localStorage.getItem("clay-first-tool-created")||(localStorage.setItem("clay-first-tool-created","1"),gs.capture("first_tool_created",{tool_id:Ne.current,tool_uuid:We.current,visibility:Qe,slug:N}))}catch(f){console.error("Publish failed:",f),$r({eventName:"content_creation_failed",properties:{error_type:"publish_error",error_message:f instanceof Error?f.message:"Update failed",is_public:!0}}),Ie.error("Tool wasn't published due to a technical issue. Try again.")}finally{E(),Ht(!1)}},vi=async p=>{var N,k;if(!Ne.current||!Xt)return;Ft.current&&(clearTimeout(Ft.current),Ft.current=null),wr(!0);const g=Ms();try{const E=$a(q,ie),f=await xs(E),ge=await ho(f,E,D),de=Dc(E,ge),{schema:G,skippedKeys:ke}=await xo(de),Be=await fo(ie),Xe=se?await mo(se):null,Ve=fn,Qe=p??zn,bn=Qe==="public",ss=Qe==="public",at=Al(await br()),Oe=await D.entities.ToolImplementation.filter({tool_uuid:We.current}).catch(()=>[]),Tt=Math.max(0,...Oe.filter(ln=>ln.revision!=null).map(ln=>ln.revision))+1;let Ze=U,Fn=le;if(Ze)await D.entities.ToolImplementation.update(Ze,{revision:Tt,is_public:bn,canvas_code_url:Be,controls_schema:G,libraries:J,custom_css_url:Xe||"",control_values:{},control_checkpoints:Pe(Ze),timeline:Te,...Rt!==nt.export.defaultWidth?{canvas_width:Rt}:{},...jt!==nt.export.defaultHeight?{canvas_height:jt}:{},...at!==void 0?{presets:at}:{}});else{const ln=crypto.randomUUID();Ze=(await D.entities.ToolImplementation.create({tool_uuid:We.current,uuid:ln,user_id:As,is_public:bn,revision:Tt,canvas_code_url:Be,controls_schema:G,libraries:J,timeline:Te,...Xe?{custom_css_url:Xe}:{},...Rt!==nt.export.defaultWidth?{canvas_width:Rt}:{},...jt!==nt.export.defaultHeight?{canvas_height:jt}:{},...at!==void 0?{presets:at}:{}})).id,Fn=ln}await D.entities.Tool.update(Ne.current,{name:u,description:qe||Ba(u),slug:Xt,is_public:ss,visibility:Qe,published_implementation_uuid:Fn,draft_implementation_uuid:""}),xe&&xe!==Ze&&Oe.some(Or=>Or.id===xe)&&D.entities.ToolImplementation.delete(xe).catch(()=>null),Y(Ze),ut(Fn),V(null),X(null),mt(null),Se(null),we(de),xr(!1),on(),qs(ss),Gr(Qe),Ts(Qe),Rn({toolName:u,toolDescription:qe,toolTags:zt,controlsSchema:de,canvasCode:ie,libraries:J,customCss:se}
81),rn(!1),yt().then(ln=>wa(ln,Ne.current));const ms=(k=(N=Nt.current)==null?void 0:N.getIframeRefObj)==null?void 0:k.call(N);ms&&ge&&yn(ms,El,ge),ke.length?Ie.info("Updated. The canvas drawing was too large to store."):Ve!==Qe?Xn(!0):Ie.success("Updated.",{description:"Your latest changes are now live."});const js={tool_id:Ne.current??void 0,userId:Me==null?void 0:Me.id};ir(lr.TOOL_PUBLISHED,Il(js),js,{tool_uuid:We.current,visibility:Qe,visibility_changed:Ve!==Qe,tag_count:zt.length,controls_count:G.length,is_republish:!0})}catch(E){console.error("Update failed:",E),$r({eventName:"content_creation_failed",properties:{error_type:"update_error",error_message:E instanceof Error?E.message:"Update failed",tool_uuid:We.current}}),Ie.error("Tool wasn't updated due to a technical issue. Try again.")}finally{g(),wr(!1)}},Pr=async()=>{const p=cs.trim()||`${u} (Remix)`;if(Ne.current)try{ot("Remix");const{tool:g}=await s({toolId:Ne.current,options:{source:"draft",name:p}});if(!g)return;Zs(!1),Qt(""),window.location.href=`/tooleditor/${g.id}`}catch(g){console.error("Remix failed:",g),Ie.error(g instanceof Error?g.message:"Tool wasn't remixed due to a technical issue. Try again.")}},Yn=async()=>{if(Ne.current)try{const p=await D.entities.Tool.get(Ne.current);if(await D.entities.Tool.update(Ne.current,{is_public:!1,visibility:"draft"}),p!=null&&p.published_implementation_uuid){const g=await D.entities.ToolImplementation.filter({uuid:p.published_implementation_uuid}).catch(()=>[]);g[0]&&await D.entities.ToolImplementation.update(g[0].id,{is_public:!1})}qs(!1),Gr("draft"),Ts("private"),qr(!1),Rn(null),Js(!1),Ie.success("Tool unpublished.")}catch(p){console.error("Unpublish failed:",p),Ie.error("Tool wasn't unpublished due to a technical issue. Try again.")}},fl=async()=>{const p=Ne.current;Is(!0);try{if(p){const g=await D.entities.Tool.get(p).catch(()=>null),N=g==null?void 0:g.uuid;if(N){const k=await D.entities.ToolImplementation.filter({tool_uuid:N}).catch(()=>[]);await Promise.all(k.map(E=>D.entities.ToolImplementation.delete(E.id).catch(()=>null)))}await D.entities.Tool.delete(p),Me!=null&&Me.id&&await ei.invalidateQueries({queryKey:[sd,Me.id]})}window.location.href=Ho("ToolEditor")}catch(g){console.error("Delete failed:",g),Ie.error("Tool wasn't deleted due to a technical issue. Try again."),Is(!1),Es(!1)}},yi=n.useMemo(()=>fx(!!Ne.current,Wr),[Wr]),_i=Cn?null:e.jsx(T0,{onBiAction:ot,toolName:u,open:ts,onOpenChange:p=>{var g;ot(p?"tool_editor_settings_open":"tool_editor_settings_close"),Bt(p),p&&((g=mr.current)==null||g.closePanel())},shareUrl:sl,visibility:fn,listedInGallery:Io!=="draft"&&fn==="public",publishState:Io,onRemove:()=>{Bt(!1),Js(!0)},onVisibilityChange:p=>{p!=="draft"&&Ts(p)},onToolNameChange:p=>v(p,"manual"),toolDescription:qe,onToolDescriptionChange:ht,media:pt,coverAspectRatio:hn,isCoverWorking:kr!==null||Lt!==null,onCaptureStaticCover:()=>{Bt(!1),Wn.current=!0,Ar()},onRecordDynamicCover:()=>{Bt(!1),Wn.current=!0,Da()},onUploadStaticCover:mi,onUploadDynamicCover:ao,toolTags:zt,onAddTag:so,onRemoveTag:rr,coverDirty:vs,onCoverDirtyReset:()=>ds(!1),onSave:()=>{ot("tool_editor_settings_close"),Bt(!1)},onClose:()=>{ot("tool_editor_settings_close"),Bt(!1)}}),oc=!Cn&&gn?e.jsx(Vr,{sendToolEditorAction:ot,children:e.jsx(cx,{ref:mr,publishExportDisabled:!!O,publishExportDisabledReason:O?"Exit or restore to enable":void 0,onCopyUrl:()=>{Io==="draft"?ha(!0):Cr(!0)},onDelete:()=>{ot("Delete Tool"),Es(!0)},onRemix:()=>{ot("Remix"),Qt(`${u} (Remix)`),Zs(!0)},onProject:Q?sr:void 0,onMidi:()=>{var g,N,k,E;const p=(N=(g=Nt.current)==null?void 0:g.getIframeRefObj)==null?void 0:N.call(g);p&&yn(p,Bc),(E=(k=Nt.current)==null?void 0:k.openMidiLearn)==null||E.call(k)},viewerUrl:sl,onSave:Lo,isParamOnlyChange:tc,isPublishing:wn,isRepublishing:os,onPublish:io,onSetPublishVisibility:Ts,onUpdate:vi,publishState:Io,visibility:fn,stagedVisibility:zn,onRemoveFromGallery:()=>{ot("Unpublish"),Js(!0)},toolName:u,toolDescription:qe,media:pt,coverAspectRatio:hn,isCoverWorking:kr!==null||Lt!==null,onToolNameChange:p=>v(p,"manual"),onToolDescriptionChange:ht,onCaptureStaticCover:Ar,onRecordDynamicCover:Da,onUploadStaticCover:mi,onUploadDynamicCover:ao,toolTags:zt,onAddTag:so,onRemoveTag:rr,coverDirty:vs,onCoverDirtyReset:()=>ds(!1),presets:ni.presets??[],onOpen:()=>Bt(!1),onExport:()=>{var p,g;return(g=(p=Nt.current)==null?void 0:p.openExport)==null?void 0:g.call(p)}})}):null;return e.jsxs("div",{className:"h-[100dvh] flex flex-col border-0 bg-white lg:bg-[#E8E8E8] transition-[padding] duration-300 ease-out",style:{color:"rgba(0, 0, 0, 1)",backgroundImage:"none",borderStyle:"none",borderImage:"none",paddingBottom:sn&&nr?Ql:void 0},children:[ts&&e.jsx("div",{className:"fixed inset-0 z-40","aria-hidden":!0,onClick:()=>Bt(!1)}),e.jsx(V0,{leading:_i,center:oc}),!Cn&&e.jsx("div",{className:"lg:hidden shrink-0",children:e.jsx(ep,{toolName:u,creatorName:(Me==null?void 0:Me.full_name)??void 0,publishLabel:"Publish",onBack:()=>{var g;(((g=window.history.state)==null?void 0:g.idx)??0)>0?t(-1):t(Ho("Home"))},onToggleSave:Lo,onShare:()=>{ot("tool_publish_controls_copy_link"),Cr(!0)},onPublish:()=>jr(!0),onExport:()=>{var p,g;return(g=(p=Nt.current)==null?void 0:p.openExport)==null?void 0:g.call(p)},avatarUrl:Jl,avatarInitials:to,userName:(Me==null?void 0:Me.full_name)||void 0,userEmail:(Me==null?void 0:Me.email)||void 0,billingSummary:eo.data,billingLoading:eo.isLoading,billingError:eo.isError})}),Cn?e.jsx(Y0,{}):e.jsx("div",{className:"flex-1 min-h-0 flex flex-col pt-[10px] pb-[20px] relative",style:{backgroundColor:"unset",background:"unset"}
81,children:e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col lg:flex-row px-[20px] relative",children:[!sn&&e.jsx(zp,{collapsed:Un,children:e.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",children:[e.jsx(Hs.div,{initial:{x:-28,opacity:0},animate:{x:0,opacity:A!=="chat"?0:1},transition:Ic,className:`absolute inset-0 flex min-h-0 flex-col gap-[5px] ${A!=="chat"?"pointer-events-none":""}`,children:e.jsx(Vr,{sendToolEditorAction:ot,children:e.jsx(Vl,{chatOverlay:ko,initialPrompt:c,initialImageUrls:x,initialReferenceFiles:h,onBeforeSend:aa,onStructuredUpdate:Mo,onStatusChange:cl,onPlanTurnActiveChange:_r,onGenerationComplete:fi,autoFixing:tn,ensureToolId:Mr,getToolUuid:()=>We.current,restoredMessages:Ae??void 0,restoredSessionId:At??void 0,restoredModel:Je??void 0,onMessagesUpdate:p=>{er.current=p},consoleErrors:Kt,onGeneratedMetadata:al,isAdmin:ns,onRevertToVersion:oa,genesisSnapshotId:Us?U??void 0:void 0,toolHasCode:!!ie||Us,onDesignBriefUpdate:T,currentBrief:me,chatActionsRef:W,onCollapse:Ye!=="idle"?()=>Dr(!0):void 0,onToggleVersions:Q?()=>{if(A==="versions"){I("chat"),L(null),Bn();return}I("versions"),gs.capture(Fa.VERSIONS_PANEL_OPENED,{tool_id:Ne.current,tool_uuid:We.current}),ot("version_panel_open")}:void 0,versionsOpen:A==="versions"})})},"tool-chat-panel"),e.jsx(Yu,{initial:!1,children:A==="versions"?e.jsx(Hs.div,{initial:{x:-28,opacity:0}
81,animate:{x:0,opacity:1},exit:{x:-28,opacity:0},transition:Ic,className:"absolute inset-0 flex min-h-0 flex-col",children:e.jsx(px,{toolUuid:We.current,chatMessages:er.current.length>0?er.current:Ae??void 0,draftImplId:U,publishedImplId:xe,publishedImplUuid:Ue,previewingId:(O==null?void 0:O.id)??null,activeVersionId:P,liveSnapshotId:re,onPreview:il,onExitPreview:di,onRestore:p=>{if(Ye==="loading"){console.warn("[ToolEditor] Restore blocked — generation in progress");return}gs.capture(Fa.VERSION_RESTORED,{tool_id:Ne.current,tool_uuid:We.current,impl_id:p}),ot("version_restore"),Ra(p).then(()=>{I("chat")}).catch(g=>{console.warn("[ToolEditor] Restore from versions panel failed:",g),Ie.error("Version wasn't restored due to a technical issue. Try again.")})},onClose:()=>{I("chat"),L(null),Bn()}})},"tool-versions-panel"):A==="settings"?e.jsx(Hs.div,{initial:{x:-28,opacity:0},animate:{x:0,opacity:1},exit:{x:-28,opacity:0},transition:Ic,className:"absolute inset-0 flex min-h-0 flex-col",children:e.jsx(dx,{isEditingName:je,isAdmin:ns,isWorking:Qs||kr!==null||Lt!==null,media:pt,coverAspectRatio:hn,onChangeDescription:ht,onCaptureStaticCover:Ar,onClose:()=>{he(!1),I("chat")},onCommitName:p=>
81{v(p,"manual"),he(!1)},onOpenNameEdit:()=>{ot("Rename"),he(!0)},onRecordDynamicCover:Da,onRemoveTag:rr,onUploadDynamicCover:ao,onUploadStaticCover:mi,onUpsertTag:so,toolDescription:qe,toolName:u,toolSystemTags:Ya,toolTags:zt})},"tool-settings-panel"):null})]})}),e.jsxs("div",{className:"flex flex-col flex-1 min-h-0 gap-[5px] relative",children:[O?e.jsx("div",{className:"absolute top-0 right-[330px] z-20 flex items-start pointer-events-none",style:{left:Un?"0":"330px",transition:"left 400ms ease-out"},children:e.jsx("div",{className:"w-full pointer-events-auto",children:e.jsx(xx,{versionName:O.label,onExitPreview:di,onRestore:ui,isRestoring:En})})}):null,e.jsx(Vr,{sendToolEditorAction:ot,children:e.jsx(mx,{chatCollapsed:Un,coverAspectRatio:hn,coverCaptureDuration:zg,coverCaptureMode:Lt,coverCaptureWorking:kr!==null,consoleErrors:Kt,isAdmin:ns,isGenerating:(Ye==="loading"||ya)&&!gn||tn,isReverting:En,onCoverCaptureCancel:Oo,onCoverCaptureError:sc,onDynamicCoverCaptured:hi,onError:pi,onErrorsChange:St,onNewError:Ao,onHealth:nc,onReady:rc,onStaticCoverCaptured:Po,onToolAction:ot,onExportedFile:sn?void 0:ma,onControlEditRequest:(p,g)=>{g==="slider"&&ae(p)},onControlMenuRequest:p=>{const g=q.find(N=>N.key===p.key);$({...p,visible:g==null?void 0:g.visible})},freshControlKeys:te,onControlFreshCleared:Le,freshSectionLabels:st,onSectionFreshCleared:rt,onToggleControlVisibility:dl,onDeleteControl:gi,onRenameControl:Bo,onReorderControls:ul,onBulkSetVisibility:oo,onBulkDeleteControls:bi,onMoveControlsToSection:ac,previewRef:Nt,showIdleOverlay:wg({isMobile:sn,idleOverlayExiting:yr,hasPreviewHtml:!!gn,status:Ye,previewPending:ya,hasStarted:Sn.current,arrivedWithPrompt:xa.current}),idleOverlayExiting:yr,onIdleGenerate:(p,g)=>{var N;ii(),(N=W.current)==null||N.sendMessage(p,{modelOverride:g})},toolData:xl,autosavedControlValuesRef:O?null:On,timeline:Te,onBeforeRecord:()=>{var p;return(p=tr.current)==null?void 0:p.playFromStart()},onRecordingChange:ri,onImportImplementation:ll,showSourceImport:To,toolHtml:gn||Sa,toolLoaded:!!gn,toolName:u,onOpenProjection:Q&&!(sn&&!ns)?sr:void 0,getControlsSchema:()=>De.current,onMidiMappingLearned:ea,onMidiMappingCleared:It,onPanelWidthChange:Qi,controlsSchema:q,showDesktopControlsPanel:Os,toolLoadKey:gn?String(Zr):null,toolId:Q,timelineActive:ka&&!!gn&&Dn.active,trackedControlKeys:Dn.tracked,onToggleTrack:p=>{var g;return(g=tr.current)==null?void 0:g.addOrRevealTrack(p)},revealControl:Jn,presetController:ni})}),ka&&!sn&&!!gn&&e.jsx(Vr,{sendToolEditorAction:ot,children:e.jsx(tp,{ref:tr,controlsSchema:q,iframeRef:Ir,toolLoadKey:String(Zr),chatCollapsed:Un,draftImplId:U,initialTimeline:gt,controlsPanelWidth:ct,onTimelineChange:Dt,onTrackKeysChange:qt,onRevealControl:be,playbackLocked:si,persistencePaused:hr})}),sn&&!!gn&&e.jsx(Qf,{controlsSchema:q,iframeRef:Ir,toolLoadKey:String(Zr),toolId:Q,open:nr,onClose:()=>Eo(!1),onHeightChange:ec}),sn?ko:null]}),e.jsx(Hp,{collapsed:Un,onExpand:()=>Dr(!1)})]})}),!Cn&&sn&&!nr&&e.jsxs("div",{className:"lg:hidden shrink-0",ref:Ji,children:[ka&&!!gn&&Zu(Te)&&e.jsx(lx,{timeline:Ma,controlsSchema:q,iframeRef:Ir,playbackLocked:si}),e.jsx(np,{onChat:()=>{er.current.length>0||((Ae==null?void 0:Ae.length)??0)>0?ai(!0):Na(!0)},onControls:()=>Eo(!0),disabled:ur.show})]}),sn&&e.jsx(yx,{open:Ys,coverUrl:pt.custom_thumbnail||pt.thumbnail_poster_url||pt.thumbnail_url,toolName:u,description:qe,listed:zn==="public",publishing:wn,canPublish:!!gn,ctaLabel:"Publish",published:fn!=="draft",onToggleListed:p=>Ts(p?"public":"private"),onEditListing:()=>fr(!0),onPublish:async()=>{gn&&(await io(zn),jr(!1))},onUnpublish:()=>{Yn(),jr(!1)},onClose:()=>jr(!1)}),sn&&e.jsx(ig,{open:ls,coverUrl:pt.custom_thumbnail||pt.thumbnail_poster_url||pt.thumbnail_url,name:u,description:qe,tags:zt,descriptionMax:Vi,onNameChange:p=>v(p,"manual"),onDescriptionChange:ht,onAddTag:p=>void so(p),onRemoveTag:p=>void rr(p),onBack:()=>fr(!1)}),sn&&e.jsx(X0,{open:Bs,isAdmin:ns,toolHasCode:!!ie||Us,onClose:()=>Na(!1),onModelChange:p=>{var g;return(g=W.current)==null?void 0:g.setSelectedModel(p)},onSend:(p,g)=>{var N,k;g!=null&&g.model&&((N=W.current)==null||N.setSelectedModel(g.model)),(k=W.current)==null||k.sendMessage(p,{modelOverride:g==null?void 0:g.model}),Na(!1),ai(!0)}}),sn&&e.jsx(qc,{open:el,onClose:()=>ai(!1),keyboardInset:Xl,isAdmin:ns,debugMode:oi,onToggleDebug:tl,children:e.jsx(Vr,{sendToolEditorAction:ot,children:e.jsx(Vl,{hideHeader:!0,mobileBubbles:!0,initialPrompt:c,initialImageUrls:x,initialReferenceFiles:h,onBeforeSend:aa,onPlanTurnActiveChange:_r,presetBrief:y,restoredMessages:Ae??void 0,restoredSessionId:At??void 0,restoredModel:Je??void 0,onStructuredUpdate:Mo,onStatusChange:cl,onGenerationComplete:fi,autoFixing:tn,ensureToolId:Mr,getToolUuid:()=>We.current,chatActionsRef:W,consoleErrors:Kt,onGeneratedMetadata:al,isAdmin:ns,debugMode:oi,genesisSnapshotId:Us?U??void 0:void 0,toolHasCode:!!ie||Us,onDesignBriefUpdate:T,currentBrief:me,onRevertToVersion:oa,onMessagesUpdate:p=>{if(er.current=p,a&&p.length>0)try{localStorage.setItem(`clay-chat-${a}`,JSON.stringify(p))}catch{}}})})}),e.jsx(Vp,{show:jo}),e.jsx(rx,{editingKey:ee,schema:q,onClose:()=>ae(null),onSave:(p,g)=>{var f,ge,de;const N=q.map(G=>{if(G.key!==p)return G;const ke=Number(G.default??g.min),Be=Math.min(Math.max(ke,g.min),g.max);return{...G,min:g.min,max:g.max,default:Be}});we(N);const k=Number(((f=q.find(G=>G.key===p))==null?void 0:f.default)??g.min),E=Math.min(Math.max(k,g.min),g.max);(de=(ge=Nt.current)==null?void 0:ge.patchControl)==null||de.call(ge,p,{min:g.min,max:g.max,default:E}
81),ae(null)}}),e.jsx(tx,{menu:z,onClose:()=>$(null),onEditRange:p=>ae(p),onRename:(p,g)=>ue({key:p,label:g}),onSendMessage:p=>{var g;return(g=W.current)==null?void 0:g.sendMessage(p)},onHide:dl,onDelete:gi,disableHideDelete:!Os||(z==null?void 0:z.key)===Ju}),e.jsx(sx,{renameTarget:ve,schema:q,onClose:()=>ue(null),onSave:(p,g)=>{var N,k;Bo(p,g),(k=(N=Nt.current)==null?void 0:N.patchControl)==null||k.call(N,p,{label:g}),ue(null)}}),e.jsx(hx,{deleteDialogContent:yi,embedPreviewHtml:pl,isDeleting:Co,isPublishing:wn,isRepublishing:os,newToolName:cs,onCloseDeleteDialog:()=>Es(!1),onClosePublishAsNewDialog:()=>{Zs(!1),Qt("")},onClosePublishDialog:()=>is(!1),onCloseUnpublishDialog:()=>Js(!1),onCloseUpdateDialog:()=>rn(!1),onDeleteTool:fl,onPublish:io,onRemixAsNew:Pr,onSetNewToolName:Qt,onSetToolName:p=>v(p,"manual"),onSetToolDescription:qn,onSetVisibility:Ts,onUnpublish:Yn,onUpdate:vi,setShowDeleteDialog:Es,setShowPublishAsNewDialog:Zs,setShowPublishDialog:is,setShowUnpublishDialog:Js,setShowUpdateDialog:rn,showDeleteDialog:wo,showPublishAsNewDialog:ga,showPublishDialog:_o,showUnpublishDialog:ba,showUpdateDialog:Ka,showPublishSuccessDialog:Ks,setShowPublishSuccessDialog:Xn,toolDescription:qe,toolName:u,toolSlug:Xt,visibility:zn}),e.jsx(sp,{file:fa,toolName:u,toolSlug:Xt,onClose:()=>ma(null)}),e.jsx(rp,{open:bs,autoDismissMs:3e4,toolName:u,toolSlug:Xt,onClose:()=>Cr(!1)}),e.jsx(ix,{open:Qn,onClose:()=>ha(!1)})]})}function Wg(){const{toolId:t}=ql(),s=n.useRef(t??"__new__"),r=n.useRef(t);return t!==r.current&&(r.current===void 0&&t!==void 0||(s.current=t??"__new__"),r.current=t),e.jsx(Np,{children:e.jsx(Ru,{children:e.jsx(Gg,{},s.current)})})}const qg="flex h-[50px] items-center justify-center gap-[8px] whitespace-nowrap bg-[var(--product-black-00)] px-[12px] py-[4px] text-[14px] leading-[1.2] tracking-[-0.14px]";function $x({elapsed:t,duration:s,onStop:r,timerTestId:a,stopButtonTestId:o}){return e.jsxs("div",{className:"flex items-stretch",children:[e.jsxs("div",{className:`${qg} w-[120px] text-[var(--product-white-00)]`,children:[e.jsx($p,{className:"size-[15px] shrink-0 text-[var(--product-red-03)]"}),e.jsxs("span",{"data-testid":a,children:[e.jsxs("span",{className:"text-[var(--product-red-03)]",children:[t.toFixed(1),"s"]}),e.jsx("span",{children:` / ${s.toFixed(1)}s`})]})]}),e.jsx("span",{className:"w-px shrink-0 bg-[var(--product-white-00)]","aria-hidden":!0}),e.jsx("button",{type:"button","data-testid":o,onClick:r,"aria-label":"Stop recording",className:"flex size-[50px] shrink-0 items-center justify-center bg-[var(--product-black-00)] text-[var(--product-white-00)] transition-opacity hover:opacity-90",children:e.jsx(Oh,{className:"size-[22px] shrink-0"})})]})}const Mi=_n.coverCapture,Kg="flex h-[50px] items-center justify-center gap-[8px] whitespace-nowrap bg-[var(--product-black-00)] px-[12px] py-[4px] text-product-title";function Yg({mode:t,isBusy:s,isRecording:r,elapsedSeconds:a,durationSeconds:o,onCapture:i,onCancel:l,onStopRecording:c}){const{sendPageClicked:x}=Ua();return e.jsxs("div",{"data-testid":Mi.root,className:"flex shrink-0 items-start self-stretch",children:[e.jsx("button",{type:"button","data-testid":Mi.cancel,"aria-label":"Cancel cover capture",disabled:s,onClick:()=>{x({button_name:"editor_cover_capture_cancel"}),l()},className:"flex size-[24px] shrink-0 items-center justify-center bg-[var(--product-grey-02)] text-[var(--product-black-00)] transition-colors hover:bg-[var(--product-grey-03)] disabled:cursor-not-allowed disabled:opacity-50",children:e.jsx(Zn,{className:"size-[15px] shrink-0"})}),r?e.jsx($x,{elapsed:a,duration:o,onStop:()=>{x({button_name:"editor_cover_capture_stop"}),c()},timerTestId:Mi.timer,stopButtonTestId:Mi.stop}):e.jsx("button",{type:"button","data-testid":Mi.capture,disabled:s,onClick:()=>{x({button_name:`editor_cover_capture_${t}`}),i()},className:`${Kg} w-[120px] text-[var(--product-white-00)] transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50`,children:s?"Saving...":t==="dynamic"?`Capture (${Math.round(o)}s)`:"Capture"})]})}const Li="flex w-full items-center gap-[8px] px-[8px] py-[6px] min-h-[24px] text-product-text text-[var(--product-black-00)] transition-colors hover:bg-[var(--product-grey-01-legacy)]",Zg=Li.replace("text-[var(--product-black-00)]","text-[var(--product-red-03)]"),Ai="size-[18px] shrink-0",Jg="bg-[var(--product-grey-02)]",Xg="hover:bg-[var(--product-grey-02)]";function Qg({onShare:t,onRemix:s,onEditCover:r,onDelete:a,viewerUrl:o,disabled:i=!1,coverPanel:l,coverPanelOpen:c=!1,onCoverPanelClose:x}){const{sendPageClicked:h}=Ua(),[y,u]=n.useState(!1),w=c&&!!l,_=(v,j)=>()=>{h({button_name:v}),u(!1),j()};return e.jsxs(Ga,{open:w||y,onOpenChange:v=>{if(w){v||x==null||x();return}i&&v||u(v)},children:[e.jsx(Wa,{asChild:!0,children:e.jsx("button",{type:"button","data-testid":_n.topBar.actionsTrigger,"aria-label":"More actions","aria-disabled":i||void 0,onClick:()=>{i||h({button_name:"tool_editor_actions"})},className:`flex size-[50px] shrink-0 items-center justify-center text-[var(--product-grey-05)] transition-colors hover:text-[var(--product-black-00)] ${Xg} ${y?Jg:""} ${i?"cursor-not-allowed opacity-50":""}`,children:e.jsx(Im,{className:"size-[15px] shrink-0"})})}),e.jsx(qa,{align:"start",side:"bottom",sideOffset:0,className:w?"z-50 w-auto rounded-none border-0 bg-transparent p-0 shadow-none":"z-50 flex w-[164px] flex-col p-[4px] rounded-none border border-[var(--product-grey-02-legacy)] bg-[var(--product-white-00)] shadow-none [font-family:var(--product-font)]",onOpenAutoFocus:v=>v.preventDefault(),children:w?l:e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button","data-testid":_n.topBar.actionRemix,onClick:_("tool_actions_remix",s),className:Li,children:[e.jsx(Cp,{className:Ai}),"Remix"]}),e.jsxs("button",{type:"button","data-testid":_n.topBar.actionShare,onClick:_("tool_actions_share",t),className:Li,children:[e.jsx(em,{className:Ai}),"Share"]}),e.jsxs("button",{type:"button","data-testid":_n.topBar.actionEditCover,onClick:_("editor_actions_edit_cover",r),className:Li,children:[e.jsx(Yl,{className:Ai}),"Edit cover"]}),o&&e.jsxs("a",{href:o,...Tl,"data-testid":_n.topBar.actionView,onClick:()=>{h({button_name:"tool_actions_view"}),u(!1)},className:Li,children:[e.jsx(wp,{className:Ai}),"View"]}
81),e.jsx("div",{className:"h-px w-full shrink-0 bg-[var(--product-grey-02-legacy)]","aria-hidden":!0}),e.jsxs("button",{type:"button","data-testid":_n.topBar.actionDelete,onClick:_("tool_actions_delete",a),className:Zg,children:[e.jsx(id,{className:Ai}),"Delete"]})]})})]})}const Pi=_n.topBar,gu="flex h-full items-center justify-center gap-[8px] whitespace-nowrap px-[12px] py-[4px] text-product-title transition-colors",bu="w-[176px]",Mc="bg-[var(--product-grey-01)] text-[var(--product-grey-03)]",Vx="hover:bg-[var(--product-grey-02)]",eb=`${Vx} data-[state=open]:bg-[var(--product-grey-02)]`;function tb({onExport:t,onPublishNow:s,publishOpensPanel:r=!1,publishPanel:a,publishPanelOpen:o=!1,onPublishPanelOpenChange:i,isPublishing:l,publishDisabled:c=!1,publishDisabledReason:x,capturing:h=!1}){const{sendPageClicked:y}=Ua(),u=n.useRef(null),w=r&&!c&&!l&&!h;return e.jsxs("div",{className:"flex h-full items-center",children:[e.jsx(tm,{disabled:c||h}),e.jsxs("div",{ref:u,className:`flex h-full ${bu} shrink-0 items-stretch`,children:[e.jsx(go,{content:x??"Publish",side:"bottom",className:"min-w-0 flex-1",children:e.jsx("button",{type:"button","data-testid":Pi.publish,"aria-label":"Publish","aria-disabled":c||l||h||void 0,"aria-haspopup":w?"dialog":void 0,"aria-expanded":w?o:void 0,onClick:()=>{if(!(c||l||h)){if(w){const _=!o;_&&y({button_name:"editor_top_bar_publish_panel"}),i==null||i(_);return}y({button_name:"editor_top_bar_publish"}),s()}},className:`${gu} h-full w-full min-w-0 overflow-hidden ${h?Mc:`${Vx} bg-[var(--product-white-00)] text-[var(--product-black-00)]`}
81 ${c||l?"cursor-not-allowed opacity-50":""}`,children:e.jsx("span",{className:"whitespace-nowrap",children:l?"Publishing...":"Publish"})})}),e.jsxs(Ga,{open:o,onOpenChange:_=>{c||h||i==null||i(_)},children:[e.jsx(Wa,{asChild:!0,children:e.jsxs("button",{type:"button","data-testid":Pi.publishOptions,"aria-label":"Publish options","aria-disabled":c||h||void 0,className:`flex h-full shrink-0 items-stretch gap-[10px] py-[4px] pr-[12px] transition-colors ${h?Mc:`${eb} bg-[var(--product-white-00)] text-[var(--product-black-00)]`} ${c?"cursor-not-allowed opacity-50":""}`,children:[e.jsx("span",{"data-testid":Pi.publishDivider,className:"w-px shrink-0 bg-[var(--product-grey-02)]","aria-hidden":!0}),e.jsx(up,{className:"size-[24px] shrink-0 self-center"})]})}),a&&e.jsx(qa,{align:"end",side:"bottom",sideOffset:0,"data-testid":Pi.publishPanelAnchor,className:"w-auto rounded-none border-0 bg-transparent p-0 shadow-none",onOpenAutoFocus:_=>_.preventDefault(),onPointerDownOutside:_=>{var j;if(!w)return;const v=_.detail.originalEvent.target;v&&((j=u.current)!=null&&j.contains(v))&&_.preventDefault()},children:a})]})]}),e.jsxs("button",{type:"button","data-testid":Pi.export,"aria-label":"Export","aria-disabled":h||void 0,onClick:()=>{h||(y({button_name:"canvas_toolbar_export"}),t())},className:`${gu} ${bu} shrink-0 ${h?`${Mc} cursor-not-allowed`:"bg-[var(--product-black-00)] text-[var(--product-white-00)] hover:opacity-90"}`,children:[e.jsx(nm,{className:"size-[20px] shrink-0"}),e.jsx("span",{children:"Export"})]})]})}const ft=_n.publishPanel,nb="w-full border border-[var(--product-grey-02)] bg-[var(--product-grey-01)] p-[8px] text-product-text text-[var(--product-black-00)] outline-none placeholder:text-[var(--product-grey-05)]",sb="text-product-title text-[var(--product-black-00)]",rb="text-product-text text-[var(--product-grey-05)]",Ac="text-product-tiny text-[var(--product-grey-05)]",ab=[{key:"linkedin",label:"Share on LinkedIn",Icon:cm},{key:"instagram",label:"Share on Instagram",Icon:sm},{key:"x",label:"Share on X",Icon:Om},{key:"copy",label:"Copy link",Icon:rm}];function ob(t,s){const r=encodeURIComponent(s);switch(t){case"linkedin":return`https://www.linkedin.com/sharing/share-offsite/?url=${r}`;case"x":return`https://twitter.com/intent/tweet?url=${r}`;default:return null}}function ib({publishState:t,justPublished:s,visibility:r,onVisibilityChange:a,toolName:o,toolDescription:i,media:l,shareUrl:c,isPublishing:x=!1,publishError:h,onPublish:y,onUnpublish:u,onClose:w,initialPage:_="preview",listingDraft:v,onListingDraftChange:j,onToolNameChange:A,onToolDescriptionChange:I,toolTags:O,onAddTag:L,onRemoveTag:P,onCaptureStaticCover:V,onRecordDynamicCover:re,onUploadStaticCover:X,onUploadDynamicCover:je,onClearCover:he,isCoverWorking:me=!1}){const{sendPageClicked:T}=Ua(),[ee,ae]=n.useState(_),[ve,ue]=n.useState((v==null?void 0:v.tag)??""),[z,$]=n.useState((v==null?void 0:v.name)??o),W=n.useRef(null),ne=n.useRef(null),F=le=>{const Se=le.name===void 0?z:le.name;j==null||j({name:Se===null||Se===o?null:Se,tag:le.tag===void 0?ve:le.tag})},te=le=>{$(le),F({name:le})},Le=le=>{ue(le),F({tag:le})};n.useEffect(()=>{ee==="cover"&&(v==null?void 0:v.name)==null&&$(o)},[ee]);const Ke=t!=="draft",oe=po(l??void 0),st=Nl(l??void 0),rt=Sl(st),q=!!s&&ee==="preview",{copied:we,copyLink:De}=vx(c,"editor_publish_copy_link");Fr({open:q,modalName:"tool_publish_success_modal",origin:"tool_editor_publish_controls"});const ie=()=>{const le=ve.trim().slice(0,Va);le&&L(le),ue(""),F({tag:""})},pe=()=>{z!==o&&A(z),F({name:null}),ae("preview")},J=(le,Se,gt,Fe)=>e.jsx(Xo,{title:gt?e.jsxs("button",{type:"button","data-testid":ft.back,onClick:gt,className:`flex w-fit items-center gap-[8px] ${sb}`,children:[e.jsx(Tu,{className:"size-[15px] shrink-0"}),le]}):le,subtitle:Fe,trailing:Se,close:e.jsx(vr,{"data-testid":ft.close,onClick:w,children:e.jsx(Zn,{className:"size-[15px] shrink-0"})})}),Ce="inline-flex shrink-0 items-center justify-center whitespace-nowrap px-[6px] py-[3px] text-product-tiny",se=t==="draft"?e.jsx("span",{"data-testid":ft.badge,className:`${Ce} bg-[var(--product-grey-02)] text-[var(--product-grey-05)]`,children:"Draft"}):t==="published_dirty"?e.jsx("span",{"data-testid":ft.badge,className:`${Ce} outline outline-1 -outline-offset-1 outline-[var(--product-blue-03)] text-[var(--product-blue-03)]`,children:"Live - unpublished changes"}):e.jsx("span",{"data-testid":ft.badge,className:`${Ce} bg-[var(--product-blue-03)] text-[var(--product-white-00)]`,children:"Live in Brik"}),Ot=c?e.jsxs("div",{className:"flex h-[36px] w-full items-center justify-between border border-[var(--product-grey-02-legacy)] bg-[var(--product-grey-01-legacy)] p-[8px]",children:[e.jsx("p",{"data-testid":ft.toolLink,className:"min-w-0 truncate text-product-text text-[var(--product-grey-05)]",children:c}),e.jsxs("div",{className:"flex shrink-0 items-center",children:[e.jsx("button",{type:"button","data-testid":ft.copyLink,"aria-label":we?"Link copied":"Copy link",onClick:De,className:"flex size-[24px] items-center justify-center text-[var(--product-grey-05)] transition-colors hover:text-[var(--product-black-00)]",children:e.jsx(am,{className:"size-[15px] shrink-0"})}),e.jsx("a",{href:c,...Tl,"data-testid":ft.openLink,"aria-label":"Open tool",onClick:()=>T({button_name:"editor_publish_open_link"}),className:"flex size-[24px] items-center justify-center text-[var(--product-grey-05)] transition-colors hover:text-[var(--product-black-00)]",children:e.jsx(Xm,{className:"size-[15px] shrink-0"})})]})]}):null,U=(le,Se,gt,Fe)=>{const Te=r===le;return e.jsx("button",{type:"button",role:"radio","aria-checked":Te,"data-testid":Fe,onClick:()=>{T({button_name:`editor_publish_visibility_${le}`}),a(le)},className:"flex min-h-[40px] w-full flex-col items-start justify-center p-[8px] text-left",children:e.jsxs("span",{className:"flex w-full items-center gap-[15px]",children:[e.jsx("span",{className:"flex size-[14px] shrink-0 items-center justify-center rounded-full border border-[var(--product-grey-03)] bg-[var(--product-white-00)]",children:Te&&e.jsx("span",{className:"size-[6px] rounded-full bg-[var(--product-black-00)]","aria-hidden":!0})}),e.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-[2px]",children:[e.jsx("span",{className:"text-product-text text-[var(--product-black-00)]",children:Se}),e.jsx("span",{className:"text-product-text text-[var(--product-grey-05)]",children:gt})]})]})})},mt=({label:le,preview:Se,emptyLabel:gt,uploadRef:Fe,uploadTestId:Te,inputTestId:Dt,uploadAriaLabel:Dn,accept:Ct,onUpload:qt,uploadClick:Jn,actionLabel:dn,ActionIcon:H,actionTestId:be,onAction:xe,actionClick:Y,onClear:Ue})=>e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-[12px]",children:[e.jsx("p",{className:rb,children:le}),e.jsx("div",{className:"flex h-[279px] w-full flex-col px-[6px]",children:e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-[6px]",children:[e.jsxs("div",{className:"relative flex min-h-0 flex-1 items-center justify-center overflow-hidden border border-[var(--product-grey-02)] bg-[var(--product-grey-01)] p-[4px]",children:[Se??e.jsxs("button",{type:"button","data-testid":Te,"aria-label":Dn,disabled:me||!qt,onClick:()=>{var ut;T({button_name:Jn}),(ut=Fe.current)==null||ut.click()},className:"flex size-full flex-col items-center justify-center gap-[10px] border border-dashed border-[rgba(104,104,104,0.3)] transition-colors hover:bg-[var(--product-grey-02)] disabled:cursor-not-allowed disabled:opacity-50",children:[e.jsx("span",{className:"flex size-[24px] shrink-0 items-center justify-center",children:e.jsx(dm,{className:"size-[15px] shrink-0 text-[var(--product-grey-05)]"})}),e.jsx("span",{className:"w-[101px] text-center text-product-tiny text-[var(--product-grey-05)]",children:gt})]}),Se&&Ue&&e.jsx("button",{type:"button","data-testid":ft.clearCover,"aria-label":"Remove c
81over",onClick:Ue,className:"absolute right-0 top-0 flex items-center bg-[var(--product-white-00)] text-[var(--product-black-00)]",children:e.jsx(Zn,{className:"size-[15px] shrink-0"})}),e.jsx("input",{ref:Fe,type:"file",accept:Ct,"data-testid":Dt,className:"hidden",onChange:ut=>{var bt;const Ye=(bt=ut.currentTarget.files)==null?void 0:bt[0];Ye&&(qt==null||qt(Ye)),ut.currentTarget.value=""}})]}),e.jsxs(Nn,{size:"medium",priority:"secondary",className:"w-full","data-testid":be,disabled:me,onClick:()=>{T({button_name:Y}),xe()},children:[e.jsx(H,{className:"size-[15px] shrink-0"}),e.jsx("span",{className:"whitespace-nowrap",children:dn})]})]})})]});return ee==="cover"?e.jsxs(uc,{"data-testid":ft.root,className:"max-h-[calc(100dvh-32px)] min-h-0 w-[455px] max-w-[calc(100vw-32px)] [font-family:var(--product-font)]",children:[e.jsx("div",{className:"w-full shrink-0",children:J("Edit cover",null,()=>ae("preview"))}),e.jsxs("div",{"data-testid":ft.coverBody,className:"flex min-h-0 w-full flex-1 flex-col overflow-y-auto",children:[e.jsxs($s,{className:"items-start gap-[12px]",children:[mt({label:"Static cover",preview:oe?e.jsx("img",{alt:"",src:oe,className:"size-full object-cover"}):null,emptyLabel:"Upload Image Cover (5mb Max)",uploadRef:W,uploadTestId:ft.uploadCover,inputTestId:ft.uploadCoverInput,uploadAriaLabel:"Upload image cover",accept:"image/png,image/jpeg,image/webp,image/gif",onUpload:X,uploadClick:"editor_publish_upload_cover",actionLabel:"Screenshot cover",ActionIcon:Ph,actionTestId:ft.screenshotCover,onAction:V,actionClick:"editor_publish_screenshot_cover"}),mt({label:"Dynamic cover",preview:rt?e.jsx(Gi,{tool:l??{},autoPlay:!0,size:"small",className:"pointer-events-none absolute inset-0"}):null,emptyLabel:"Upload Video Cover (5mb max)",uploadRef:ne,uploadTestId:ft.uploadDynamicCover,inputTestId:ft.uploadDynamicCoverInput,uploadAriaLabel:"Upload video cover",accept:"video/mp4,video/webm",onUpload:je,uploadClick:"editor_publish_upload_dynamic_cover",actionLabel:"Record cover",ActionIcon:$p,actionTestId:ft.recordCover,onAction:re,actionClick:"editor_publish_record_cover",onClear:rt?he:void 0})]}),e.jsx(Vs,{}),e.jsxs($s,{className:"flex-col gap-[15px]",children:[e.jsxs("div",{className:"flex w-full flex-col gap-[6px]",children:[e.jsx("label",{className:Ac,htmlFor:"publish-v2-name",children:"Tool Name"}),e.jsx("input",{id:"publish-v2-name","data-testid":ft.nameInput,value:z,maxLength:_h,onChange:le=>te(le.target.value),className:`${nb} h-[36px]`})]}),e.jsxs("div",{className:"flex w-full flex-col gap-[6px]",children:[e.jsx("label",{className:Ac,htmlFor:"publish-v2-description",children:"Description"}),e.jsx("div",{className:"flex h-[75px] w-full flex-col border border-[var(--product-grey-02)] bg-[var(--product-grey-01)] p-[8px]",children:e.jsx("textarea",{id:"publish-v2-description","data-testid":ft.descriptionInput,value:i,onChange:le=>I(le.target.value),className:"min-h-0 flex-1 resize-none bg-transparent text-[12px] leading-[1.3] tracking-[-0.12px] text-[var(--product-black-00)] outline-none"})})]}),e.jsxs("div",{className:"flex w-full flex-col gap-[12px]",children:[e.jsx("label",{className:Ac,htmlFor:"publish-v2-tags",children:"Tags"}),e.jsx("div",{className:"flex h-[36px] w-full items-center justify-between border border-[var(--product-grey-02)] bg-[var(--product-grey-01)] p-[8px]",children:e.jsx("input",{id:"publish-v2-tags","data-testid":ft.tagInput,value:ve,maxLength:Va,placeholder:"Add tags",onChange:le=>Le(le.target.value.slice(0,Va)),onKeyDown:le=>{le.key==="Enter"&&(le.preventDefault(),ie())},className:"min-w-0 flex-1 bg-transparent text-[12px] leading-[1.3] tracking-[-0.12px] text-[var(--product-black-00)] outline-none placeholder:text-[var(--product-grey-05)]"})}),O.length>0&&e.jsx("div",{"data-testid":ft.tagList,className:"flex flex-wrap items-start gap-[4px]",children:O.map(le=>e.jsxs("span",{title:le,className:"flex min-w-0 max-w-full items-center justify-center gap-[8px] bg-[var(--product-grey-01)] px-[6px] py-[3px] text-[11px] leading-[1.2] tracking-[-0.22px] text-[var(--product-black-00)]",children:[e.jsx("button",{type:"button","aria-label":`Remove ${le}`,onClick:()=>P(le),className:"flex shrink-0 items-center text-[var(--product-black-00)]",children:e.jsx(Zn,{className:"size-[15px] shrink-0"})}),e.jsx("span",{"data-testid":ft.tagLabel,className:"min-w-0 truncate",children:le})]},le))})]})]})]}),e.jsx(bo,{className:"w-full shrink-0",children:e.jsx(Nn,{size:"big",skin:"standard",priority:"primary",className:"w-full border-0","data-testid":ft.saveChanges,onClick:()=>{T({button_name:"editor_publish_save_cover"}),pe()},children:"Save changes"})})]}):q?e.jsxs(uc,{"data-testid":ft.root,className:"w-[455px] max-w-[calc(100vw-32px)] [font-family:var(--product-font)]",children:[J("Your tool is published",se),Ot&&e.jsxs(e.Fragment,{children:[e.jsx($s,{title:"Tool link",children:Ot}),e.jsx(Vs,{})]}),e.jsx($s,{title:"Share options",children:e.jsx("div",{className:"flex w-full items-start gap-[4px]",children:ab.map(({key:le,label:Se,Icon:gt})=>{const Fe=c?ob(le,c):null,Te="flex h-[30px] min-w-0 flex-1 items-center justify-center bg-[var(--product-grey-01-legacy)] px-[8px] py-[4px] text-[var(--product-black-00)] transition-colors hover:bg-[var(--product-grey-02-legacy)]";return Fe?e.jsx("a",{href:Fe,...Tl,"aria-label":Se,"data-testid":`${ft.share}-${le}`,onClick:()=>T({button_name:`editor_publish_share_${le}`}),className:Te,children:e.jsx(gt,{className:"size-[22px] shrink-0"})},le):e.jsx("button",{type:"button","aria-label":Se,"data-testid":`${ft.share}-${le}`,onClick:()=>
81{if(le==="copy"){De();return}De()},className:Te,children:e.jsx(gt,{className:"size-[22px] shrink-0"})},le)})})}),e.jsx(Vs,{}),e.jsx($s,{className:"items-center justify-center",children:e.jsx("p",{className:"flex-1 text-product-text text-[var(--product-grey-05)]",children:we?"Link copied.":"Made something great? Tag us @brik.space."})})]}):e.jsxs(uc,{"data-testid":ft.root,className:"w-[455px] max-w-[calc(100vw-32px)] [font-family:var(--product-font)]",children:[J("Publish preview",se,void 0,"This is what people see before they open your tool."),e.jsxs($s,{className:"items-start gap-[12px] border border-[var(--product-grey-02-legacy)]",children:[e.jsx("div",{"data-testid":ft.previewCover,className:"relative h-[200px] w-[150px] shrink-0 overflow-hidden bg-[var(--product-grey-01-legacy)]",children:oe?e.jsx("img",{alt:"",src:oe,className:"size-full object-cover"}):rt?e.jsx(Gi,{tool:l??{},autoPlay:!0,size:"small",className:"pointer-events-none absolute inset-0"}):null}),e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col items-start justify-between self-stretch",children:[e.jsxs("div",{className:"flex w-full flex-col gap-[8px]",children:[e.jsx("p",{"data-testid":ft.previewName,className:"text-product-text text-[var(--product-black-00)]",children:o}),e.jsx("p",{className:"text-product-text text-[var(--product-grey-05)]",children:i})]}),e.jsxs(Nn,{size:"medium",skin:"filled",priority:"secondary",className:"shrink-0","data-testid":ft.editCover,onClick:()=>{T({button_name:"editor_publish_edit_cover"}),ae("cover")},children:[e.jsx(Yl,{className:"size-[15px] shrink-0"}),"Edit cover"]})]})]}),e.jsx(Vs,{}),e.jsx($s,{title:"Tool visibility",children:e.jsxs("div",{role:"radiogroup","aria-label":"Tool visibility",className:"flex w-full flex-col",children:[U("private","Unlisted","Only people with the tool link can see your tool.",ft.visibilityUnlisted),U("public","In gallery","Anyone can find your tool in the Brik gallery.",ft.visibilityListed)]})}),Ot&&e.jsx($s,{title:"Tool link",className:"border border-[var(--product-grey-02-legacy)]",children:Ot}),h&&e.jsxs("div",{"data-testid":ft.publishError,className:"flex w-full items-start gap-[6px] bg-[var(--product-red-02-legacy)] p-[12px] text-[var(--product-black-00)]",children:[e.jsx(Cm,{className:"mt-[1px] size-[15px] shrink-0"}),e.jsx("p",{className:"min-w-0 flex-1 text-product-text",children:h})]}),e.jsxs(bo,{children:[Ke&&e.jsxs(Nn,{size:"big",skin:"error",priority:"secondary",className:"min-w-0 flex-1 border-0","data-testid":ft.unpublish,onClick:()=>{T({button_name:"editor_publish_unpublish"}),u()},children:[e.jsx(pd,{className:"size-[15px] shrink-0"}),"Unpublish"]}),e.jsx("button",{type:"button","data-testid":ft.publish,"aria-label":x?"Publishing…":"Publish","aria-disabled":x||void 0,onClick:()=>{x||(T({button_name:"editor_publish_confirm"}),y())},className:`group relative flex h-[50px] min-w-0 flex-1 overflow-hidden bg-[var(--product-black-00)] text-[var(--product-white-00)] ${x?"cursor-not-allowed opacity-70":""}`,children:e.jsx("span",{"data-testid":ft.publishRoll,className:`flex w-full flex-col transition-transform duration-[250ms] ease-out motion-reduce:transition-none ${x?"":"group-hover:-translate-y-[50px]"}`,children:[!1,!0].map(le=>e.jsxs("span",{"aria-hidden":le||void 0,className:`flex h-[50px] w-full shrink-0 items-center gap-[8px] whitespace-nowrap p-[12px] text-[14px] leading-[1.2] tracking-[-0.14px] ${Ke?"":"justify-center"}`,children:[e.jsx(Fp,{className:"size-[15px] shrink-0"}),x?"Publishing…":"Publish"]},String(le)))})})]})]})}function lb({elapsed:t,duration:s,onStop:r}){const{sendPageClicked:a}=Ua();return n.useEffect(()=>{Ie.info("Keep this tab open and in the foreground")},[]),e.jsx($x,{elapsed:t,duration:s,onStop:()=>{a({button_name:"recording_overlay_stop"}),r()},stopButtonTestId:_n.topBar.recordingStop})}const Vo=_n.remixDialog,vu="tool_remix_modal",yu="tool_editor_publish_controls";function cb({open:t,onOpenChange:s,toolName:r,newToolName:a,onSetNewToolName:o,onConfirm:i}){const{sendModalClicked:l}=nd();Fr({open:t,modalName:vu,origin:yu});const c=x=>l({modal_name:vu,origin:yu,button_name:x,button_type:"button"});return e.jsxs(Ki,{open:t,onOpenChange:s,"data-testid":Vo.root,gridLineTestId:Vo.gridLine,children:[e.jsx(Xo,{title:"Remix",close:e.jsx(vr,{"data-testid":Vo.close,onClick:()=>c("tool_remix_modal_close"),children:e.jsx(Zn,{className:"size-[15px] shrink-0"})})}),e.jsxs($s,{className:"flex-col gap-[12px]",children:[e.jsx("p",{className:"text-product-text text-[var(--product-grey-05)]",children:"Create a remixed version of this tool. Your existing published tool will remain unchanged."}),e.jsx(ld,{size:"lg",value:a,onChange:o,placeholder:`${r} (Remix)`,"data-testid":Vo.nameInput})]}),e.jsx(Vs,{}),e.jsxs(bo,{children:[e.jsx(vr,{asChild:!0,children:e.jsxs(Nn,{size:"big",skin:"standard",priority:"secondary",className:"min-w-0 flex-1 border-0","data-testid":Vo.cancel,onClick:()=>c("tool_remix_modal_cancel"),children:[e.jsx(Zn,{className:"size-[15px] shrink-0"}),e.jsx("span",{className:"whitespace-nowrap",children:"Cancel"})]})}),e.jsxs(Nn,{size:"big",skin:"standard",priority:"primary",className:"min-w-0 flex-1 border-0","data-testid":Vo.confirm,onClick:()=>{c("tool_remix_modal_confirm"),i()},children:[e.jsx(Cp,{className:"size-[15px] shrink-0"}),e.jsx("span",{className:"whitespace-nowrap",children:"Remix"})]})]})]})}const Oi=_n.unpublishDialog,_u="tool_unpublish_modal",wu="tool_editor_publish_controls";function db({open:t,onOpenChange:s,onConfirm:r}){const{sendModalClicked:a}=nd();Fr({open:t,modalName:_u,origin:wu});const o=i=>a({modal_name:_u,origin:wu,button_name:i,button_type:"button"});return e.jsxs(Ki,{open:t,onOpenChange:s,"data-testid":Oi.root,gridLineTestId:Oi.gridLine,children:[e.jsx(Xo,{title:"Unpublish tool?",close:e.jsx(vr,{"data-testid":Oi.close,onClick:()=>o("tool_unpublish_modal_close"),children:e.jsx(Zn,{className:"size-[15px] shrink-0"})})}),e.jsx($s,{className:"items-center",children:e.jsx("p",{className:"min-w-0 flex-1 text-product-text text-[var(--product-grey-05)]",children:"Anyone with the tool link will lose access, and it will be removed from the Brik gallery. You can republish anytime."})}),e.jsx(Vs,{}),e.jsxs(bo,{children:[e.jsx(vr,{asChild:!0,children:e.jsxs(Nn,{size:"big",skin:"standard",priority:"secondary",className:"min-w-0 flex-1 border-0","data-testid":Oi.cancel,onClick:()=>o("tool_unpublish_modal_cancel"),children:[e.jsx(Zn,{className:"size-[15px] shrink-0"}),e.jsx("span",{className:"whitespace-nowrap",children:"Cancel"})]})}),e.jsxs(Nn,{size:"big",skin:"error",priority:"primary",className:"min-w-0 flex-1 border-0","data-testid":Oi.confirm,onClick:()=>{o("tool_unpublish_modal_confirm"),r()},children:[e.jsx(pd,{className:"size-[15px] shrink-0"}),e.jsx("span",{className:"whitespace-nowrap",children:"Unpublish"})]})]})]})}function ub({hasPreviewHtml:t,lastGenerationFailed:s,buildStarted:r,previewPending:a,arrivedWithPrompt:o}){return t||s?!1:r||a||o}function pb(t){return t?"mid":"compact"}function xb(t){return t==="compact"?"mid":"full"}function Pc(t){return t==="compact"?"mid":t}function fb({isMobile:t,outstanding:s,surveyShowing:r}){return t&&s&&!r}function mb({sheetOpen:t,planQuestionOutstanding:s,finishedUnseen:r}){return t?!1:s||r}function hb({isMobile:t,buildWindowOpen:s,surveyShowing:r}){return t&&s&&!r}function gb({alreadyOpened:t,isMobile:s,restoring:r,emptyCanvasShowing:a,surveyShowing:o}){return t||!s||r||o?!1:a}const bb=800,vb=4e3,Oc={duration:.24,ease:[.22,1,.36,1]},yb=4;function Lc(t,s){return!s||!t?t??[]:t.map(r=>r.type==="section"||r.type==="button"||!r.key||!(r.key in s)?r:{...r,default:s[r.key]})}async function _b(t,s){const a=await(await fetch(t)).blob();return new File([a],s,{type:a.type||"image/jpeg"})}function wb(){var jd,kd,Nd;Eu("ToolEditor");const t=Iu(),{mutateAsync:s}=Ip(),r=Du(),{toolId:a}=ql(),[o,i]=Mu(),[l]=n.useState(()=>a?"":o.get("prompt")||""),c=l,x=((jd=r.state)==null?void 0:jd.initialImageUrls)??[],h=((kd=r.state)==null?void 0:kd.initialReferenceFiles)??[],y=a?void 0:((Nd=r.state)==null?void 0:Nd.presetBrief)??void 0,{toolName:u,setToolNaming:w,toolNamingRef:_,applyToolName:v,hydrateToolName:j}=Bx({initialPrompt:c,routeToolId:a}),[A,I]=n.useState("chat"),[O,L]=n.useState(null),[P,V]=n.useState(null),[re,X]=n.useState(null),[je,he]=n.useState(!1),[me,T]=n.useState(""),[ee,ae]=n.useState(null),[ve,ue]=n.useState(null),[z,$]=n.useState(null),W=n.useRef(null),[ne,F]=n.useState(()=>new Set),te=n.useMemo(()=>[...ne],[ne]),Le=n.useCallback(d=>{F(b=>{if(!b.has(d))return b;const R=new Set(b);
81return R.delete(d),R})},[]),[Ke,oe]=n.useState(()=>new Set),st=n.useMemo(()=>[...Ke],[Ke]),rt=n.useCallback(d=>{oe(b=>{if(!b.has(d))return b;const R=new Set(b);return R.delete(d),R})},[]),[q,we]=n.useState([{type:"slider",key:"speed",label:"Speed",min:1,max:100,default:30,step:1},{type:"slider",key:"hue",label:"Hue Shift",min:0,max:360,default:180,step:1},{type:"slider",key:"scale",label:"Scale",min:1,max:20,default:5,step:1},{type:"color",key:"accent",label:"Accent Color",default:"#4a9eff"},{type:"toggle",key:"animate",label:"Animate",default:!0}]);Sp();const De=n.useRef(q);n.useEffect(()=>{De.current=q},[q]);const[ie,pe]=n.useState(""),[J,Ce]=n.useState([]),[se,Ot]=n.useState(""),[U,mt]=n.useState(null),[le,Se]=n.useState(null),[gt,Fe]=n.useState(null),[Te,Dt]=n.useState(null),[Dn,Ct]=n.useState({active:!1,tracked:[]}),qt=n.useCallback(d=>{Ct(b=>b.active===d.active&&b.tracked.join("\0")===d.trackedKeys.join("\0")?b:{active:d.active,tracked:d.trackedKeys})},[]),[Jn,dn]=n.useState(null),H=n.useRef(null),be=n.useCallback(d=>{dn(b=>({key:d,nonce:((b==null?void 0:b.nonce)??0)+1})),H.current&&clearTimeout(H.current),H.current=setTimeout(()=>dn(null),2200)},[]);n.useEffect(()=>()=>{H.current&&clearTimeout(H.current)},[]);const[xe,Y]=n.useState(null),[Ue,ut]=n.useState(null),[Ye,bt]=n.useState("idle"),Sn=n.useRef(!!a),Hn=n.useRef(!0);n.useEffect(()=>(Hn.current=!0,()=>{Hn.current=!1}),[]);const[xa,yr]=n.useState(!1),[zr,cr]=n.useState(!1),[as,zs]=n.useState(!1),_r=n.useRef(a),[dr,Me]=n.useState(!1),ei=n.useRef(!1),Us=n.useCallback(d=>{ei.current=d,Me(d)},[]),[Gs,Ws]=n.useState(!1),Ur=n.useCallback(()=>Ws(!0),[]),ur=n.useRef(null),{user:Ge}=za(),qs=Qc(),[fn,Gr]=n.useState(!1),[zn,Ts]=n.useState(null),wn=Nx({generating:Ye==="loading"&&!dr,editingBorrowedTool:fn||!!zn&&zn!==(Ge==null?void 0:Ge.id),forceSurvey:o.get("survey")==="1"}),[Ht,os]=n.useState(!1),[wr,Ks]=n.useState("draft"),[Xn,Un]=n.useState("private"),[Rs,Xt]=n.useState(!1),[Tn,fa]=n.useState(!1),[,ma]=n.useState(!1),[bs,Cr]=n.useState(!1),[Qn,ha]=n.useState(null),[Wr,qr]=n.useState(null),[Mt,Rn]=n.useState(!1),[pr,xr]=n.useState(!1),[_o,is]=n.useState(!1),[Ys,jr]=n.useState(!1),[ls,fr]=n.useState(null),[Ka,rn]=n.useState(!1),[ga,Zs]=n.useState(!1),[ba,Js]=n.useState(!1),[wo,Es]=n.useState(!1),[Co,Is]=n.useState(!1),[cs,Qt]=n.useState(!1),[pt,Mn]=n.useState(!1),[Kr,kr]=n.useState(!1),[Gn,Lt]=n.useState(""),[An,vs]=n.useState({custom_thumbnail:null,thumbnail_aspect_ratio:null,thumbnail_poster_url:null,thumbnail_stream_format:null,thumbnail_stream_url:null,thumbnail_url:null}),ds=n.useRef(An),[Wn,mn]=n.useState(null),[Rt,Xs]=n.useState(null),jt=n.useRef(!1),Pn=n.useRef(null),us=n.useRef(!1),[un,ps]=n.useState(nt.export.defaultWidth),[an,Nr]=n.useState(nt.export.defaultHeight),hn=n.useRef({width:nt.export.defaultWidth,height:nt.export.defaultHeight}),[gn,Yr]=n.useState(!1),[Zr,va]=n.useState(null),[Ds,ya]=n.useState(null),ys=n.useMemo(()=>Yo(Zr??un/an),[an,un,Zr]),Cn=n.useMemo(()=>Yo(Ds??ys),[ys,Ds]),[C,Q]=n.useState(null),[Z,Ae]=n.useState(0),xt=n.useCallback(d=>{Q(d),Ae(b=>b+1)},[]),[At,Et]=n.useState(!1),[Je,Sr]=n.useState(!!a),[es,Ne]=n.useState(!!a),[qe,qn]=n.useState(a??null),[_s,ht]=n.useState(null),[zt,ws]=n.useState(null),[Ya,Jr]=n.useState(null),en=n.useMemo(()=>({...nt,export:{...nt.export,defaultWidth:un,defaultHeight:an}}),[un,an]),ce=n.useRef(a||null),{toolDescription:We,setToolDescription:_a,toolDescriptionRef:mr,applyToolDescription:ts,toolTags:Bt,toolTagsRef:ot,toolSystemTags:$e,setToolSystemTags:Tr,toolSystemTagsRef:Nt,applyToolTagsState:Qs}=Lx({toolIdRef:ce}),yt=n.useRef(null),wa=n.useCallback(()=>yt.current,[]);Au(wa);const[Xr,jn]=n.useState(!1),[kt,Ut]=n.useState(null),[hr,Ca]=n.useState({name:null,tag:""});n.useEffect(()=>{const d=_r.current;_r.current=a,Ca({name:null,tag:""}),cr(!1),d!==void 0&&zs(!1)},[a]);const[Qr,ja]=n.useState(!1),On=ba||(kt==null?void 0:kt.anchor)==="publish",xs=n.useRef(!1);n.useEffect(()=>{xs.current&&!On&&ja(!1),xs.current=!!On},[On]);const[Ms,pn]=n.useState(null),{sendToolEditorAction:Pe}=kx({toolId:qe}),on=n.useCallback(()=>{Pn.current=null,jt.current&&(jt.current=!1,Pe("tool_editor_settings_close"))},[Pe]),{sendError:ea}=jx(),It=n.useRef(null),{isCapturingThumbnail:Ft,recordThumbnailBlob:gr,uploadThumbnailBlob:Rr,recordAndUploadThumbnail:_e,createToolVideoStreamInBackgroun
81d:Kt}=Fx({previewRef:It,toolIdRef:ce,toolMediaRef:ds,setToolMedia:vs}),St=n.useRef(null),En=n.useCallback(()=>{const d=St.current;return d?d():Promise.reject(new Error("[ToolEditor] Draft implementation resolver unavailable"))},[]),[Kn,tn]=n.useState(!1),lt=n.useRef(!1),_t=n.useCallback(d=>{const b=d!==null;lt.current=b,tn(b)},[]),[nn,B]=n.useState("saved"),[Re,et]=n.useState(null),[$t,Yt]=n.useState(null),{controlValuesRef:Zt,getControlValuesForBake:ta,getIframeLiveValues:Za,getMergedIframeLiveValues:Er,pauseAutosave:na,hydrateCheckpointsForImpl:jo,resetCheckpointsForSave:As,clearDraftTweaks:er}=Ax({draftImplId:U,previewImplId:(O==null?void 0:O.id)??null,persistencePaused:Kn,canvasCode:ie,controlsSchemaRef:De,previewRef:It,setControlValuesChanged:rn,ensureDraftImplId:En,onAutosaveSaved:()=>B(d=>d==="error"?"saved":d),onAutosaveError:()=>B("error")}),sn=n.useCallback((d,b,R)=>{var S,M;we(m=>{const ye=m.map(fe=>fe.key===d?{...fe,midi:b,default:R}:fe);return De.current=ye,ye}),(M=(S=It.current)==null?void 0:S.patchControl)==null||M.call(S,d,{default:R})},[]),Ji=n.useCallback(d=>{we(b=>{const R=b.map(S=>{if(S.key!==d)return S;const{midi:M,...m}=S;return m});return De.current=R,R})},[]),Ps=n.useRef(null),sa=n.useRef(0),Ja=n.useRef(0),ko=n.useRef(!1),[No,Os]=n.useState([]),[Xa,Qa]=n.useState(!1),[eo,Jl]=n.useState(!1),to=n.useRef(!1),ka=n.useCallback(d=>{to.current=d,Jl(d)},[]),no=n.useRef([]);n.useEffect(()=>{no.current=No},[No]);const ti=n.useRef(!1),Xi=n.useRef(null);n.useEffect(()=>{Xi.current=C},[C]);const Ls=n.useRef(0),So=n.useRef(new Set),ns=n.useRef(null),To=n.useRef(null),tr=n.useRef(null),ra=n.useRef(!1);n.useEffect(()=>{Ge!=null&&Ge.id&&a&&op(Ge.id,a)},[Ge==null?void 0:Ge.id,a]);const Ro=(Ge==null?void 0:Ge.role)==="admin",ni=Ro&&!!zn&&zn!==(Ge==null?void 0:Ge.id),br=ni?zn:Ge==null?void 0:Ge.id,aa=n.useRef([]),ct=td(),Qi=n.useRef(null),[si,ri]=n.useState(0),Xl=n.useRef(null),el=wn.show?e.jsx(ax,{generationStatus:Ye==="ready"?"ready":Ye==="error"?"error":"loading",onDismiss:wn.onDismiss,toolId:qe,standalone:ct,bottomBarHeight:si,progressRef:Xl,chrome:"new-design",planQuestionPending:Gs}):null,Bs=ua(Rp)&&!ct,Na=n.useRef(Bs);n.useEffect(()=>{Na.current=Bs},[Bs]);const oi=n.useRef(Bs),tl=n.useRef(ct);n.useEffect(()=>{const d=oi.current!==Bs,b=tl.current!==ct;if(!d&&!b||(oi.current=Bs,tl.current=ct,!C))return;let R=!1;return(async()=>{const S=O?await Za():await Er();R||xt(pa({name:u,controlsSchema:De.current,canvasCode:ie,libraries:J,customCss:se,controlValues:S??Zt.current,hideControlsOnMobile:!0,canvasConfig:en,editorMode:!0,externalControls:Bs,showCanvasGuides:!0,showToolFrameBar:!ct}))})(),()=>{R=!0}},[Bs,C,u,ie,J,se,en,Zt,Za,Er,xt,ct,O]);const nr=n.useRef(ct);nr.current=ct;const Eo=ua(Tp),Ql=ua(Ep),[ec,nl]=n.useState(),Ir=n.useCallback(()=>{nl(d=>(d??0)+1)},[]),ii=n.useRef(Promise.resolve()),Dr=Ro||Ql,sl=ua(Xu),sr=n.useRef(null),rl=U??xe??null,tc=n.useCallback(d=>{ps(d.width),Nr(d.height),va(d.width/d.height)},[]),{controller:Io,getVersionPresets:li,flushPresets:ci}=Ox({activeVersionKey:rl,isHistoricalVersion:!!O,canvasSize:{width:un,height:an},canvasSizeTweaked:gn,thumbnailRefreshToken:ec,setCanvasSize:tc,timeline:Te,timelineDockRef:sr,previewRef:It,toolName:u,controlsSchema:q,canvasCode:ie,libraries:J,customCss:se,onPreviewChange:_t}),[al,Mr]=n.useState(320),[Ln,ol]=n.useState(!1),so=Zi(),[rr,Sa]=n.useState(!1),[Do,Bn]=n.useState("compact"),Mo=n.useRef(0),il=n.useCallback(()=>Mo.current>0||((_s==null?void 0:_s.length)??0)>0,[_s]),oa=n.useCallback(()=>{Bn(pb(il())),Sa(!0)},[il]),[Ta,ro]=n.useState(!1);n.useEffect(()=>{C&&ro(!1)},[C]);const ia=n.useRef(!1),ll=hb({isMobile:ct,buildWindowOpen:Ta,surveyShowing:wn.show});n.useEffect(()=>{if(!ia.current){if(ll){oa();return}Ta&&ct&&wn.show&&Sa(!1)}},[ll,oa,Ta,ct,wn.show]);const[Ra,di]=n.useState(!1),[ui,cl]=n.useState(null),pi=Ra&&ui==="questions",[Ao,Cs]=n.useState(!1),[Ea,Ia]=n.useState(null);n.useEffect(()=>{if(fb({isMobile:ct,outstanding:Ra,surveyShowing:wn.show})){if(ui==="summary"){Cs(!1),Bn(Pc),Sa(!0);return}Sa(!1),Cs(!0)}},[ct,Ra,ui,wn.show]),n.useEffect(()=>{pi||!Ao||(Cs(!1),Bn(Pc),Sa(!0))},[pi,Ao]);const[nc,xi]=n.useState(!1),fi=n.useRef(rr);n.useEffect(()=>{fi.current=rr,rr&&xi(!1)},[rr]);const mi=mb({sheetOpen:rr,planQuestionOutstanding:Ra,finishedUnseen:nc}),{debugMode:ao,toggle:Fs}=fd(Dr),[Ar,Da]=n.useState(!1),Po=!!C&&q.length>0;n.useEffect(()=>{Ar&&!Po&&Da(!1)},[Ar,Po]);const hi=Cg({idleOverlayExiting:xa,hasPreviewHtml:!!C,status:Ye,previewPending:At,hasStarted:as,arrivedWithPrompt:!!c}),Oo=n.useRef(!1);n.useEffect(()=>{var d;gb({alreadyOpened:Oo.current,isMobile:ct,restoring:Je,emptyCanvasShowing:hi,surveyShowing:wn.show}
81)&&(Oo.current=!0,oa(),(d=W.current)==null||d.focusComposer())},[ct,Je,hi,wn.show,oa]);const sc=rr||Ao||Ar||ba||Mt||pr,rc="transition-[opacity,transform] ease-out motion-reduce:transition-none";n.useEffect(()=>{const d=Qi.current;if(!d){ri(0);return}const b=new ResizeObserver(()=>ri(d.offsetHeight));return b.observe(d),ri(d.offsetHeight),()=>b.disconnect()},[ct,Je,Ar,wn.show]);const[Lo,dl]=n.useState(0),gi=n.useRef(ct),Bo=n.useMemo(()=>({get current(){var d,b,R;return((R=(b=(d=It.current)==null?void 0:d.getIframeRefObj)==null?void 0:b.call(d))==null?void 0:R.current)??null}}),[]);n.useEffect(()=>{ds.current=An},[An]),n.useEffect(()=>{const d=document.documentElement,b={overflow:d.style.overflow,scrollbarGutter:d.style.scrollbarGutter};return d.style.overflow="hidden",d.style.scrollbarGutter="auto",()=>{d.style.overflow=b.overflow,d.style.scrollbarGutter=b.scrollbarGutter}},[]),n.useEffect(()=>{if(Je){Ne(!0);return}const d=setTimeout(()=>Ne(!1),Ed);return()=>clearTimeout(d)},[Je]);const ul=n.useCallback(()=>{Sn.current||(Sn.current=!0,yr(!0),ur.current&&clearTimeout(ur.current),ur.current=setTimeout(()=>yr(!1),6500))},[]);n.useEffect(()=>{Ye!=="loading"||dr||(zs(!0),Sn.current||ul())},[Ye,dr]);const oo=n.useCallback(d=>{var R,S,M;const b=(S=(R=It.current)==null?void 0:R.getIframeRefObj)==null?void 0:S.call(R);(M=b==null?void 0:b.current)!=null&&M.contentWindow&&yn(b,Pu,{collapsed:d}),Cr(d)},[It]),bi=Qn?`${window.location.origin}${Ho("ToolViewer")}?slug=${Qn}`:null,ac=n.useCallback(()=>{qe&&(Pe("OpenProjection"),t(Ou({id:qe,slug:Qn??void 0})))},[qe,Qn,Pe,t]),pl=n.useMemo(()=>ls?Ka||u!==ls.toolName||We!==ls.toolDescription||JSON.stringify(Bt)!==JSON.stringify(ls.toolTags)||JSON.stringify(q)!==JSON.stringify(ls.controlsSchema)||ie!==ls.canvasCode||JSON.stringify(J)!==JSON.stringify(ls.libraries)||se!==ls.customCss:!1,[u,We,Bt,q,ie,J,se,ls,Ka]),Ma=n.useMemo(()=>Ys?pl?"published_dirty":"published_clean":"draft",[Ys,pl]);n.useEffect(()=>{if(!a)return;X(null);let d=!1;return(async()=>{var b,R,S,M;try{let m=null;try{m=await D.entities.Tool.get(a)}catch{m=null}if(!m){Ie.error("Tool couldn't load due to a technical issue. Try again."),ce.current=null,qn(null);return}if(d)return;Bl(m.id,m.name),Ap({currentName:_.current.value,persistedName:m.name,manualEdited:_.current.manualEdited,lastAutoName:_.current.lastAutoName,hasGeneratedSuggestion:_.current.hasGeneratedSuggestion})&&j(m.name),ts(m.description??"");const ye=m;Qs(Ol(ye),Ll(ye)),vs({custom_thumbnail:typeof m.custom_thumbnail=="string"?m.custom_thumbnail:null,thumbnail_aspect_ratio:typeof m.thumbnail_aspect_ratio=="number"?m.thumbnail_aspect_ratio:null,thumbnail_poster_url:typeof m.thumbnail_poster_url=="string"?m.thumbnail_poster_url:null,thumbnail_stream_format:typeof m.thumbnail_stream_format=="string"?m.thumbnail_stream_format:null,thumbnail_stream_url:typeof m.thumbnail_stream_url=="string"?m.thumbnail_stream_url:null,thumbnail_url:typeof m.thumbnail_url=="string"?m.thumbnail_url:null}),us.current=!!(typeof m.custom_thumbnail=="string"&&m.custom_thumbnail);const fe=m.visibility||(m.is_public?"public":"draft");os(fe==="public"),Ks(fe),Un(fe==="draft"?"private":fe),m.slug&&ha(m.slug),Ts(m.user_id??m.creator_id??null),Gr(!!m.remixed_from),ko.current=!m.is_public&&!(typeof m.custom_thumbnail=="string"&&m.custom_thumbnail.trim())&&!(typeof m.thumbnail_url=="string"&&m.thumbnail_url.trim()),fe!=="draft"&&m.slug&&jr(!0);const[K,Ee]=await Promise.all([Rl(m).catch(()=>null),m.chat_session_id?D.entities.ChatSession.get(m.chat_session_id).catch(()=>null):Promise.resolve(null)]);if(m.uuid)yt.current=m.uuid;else{const ze=crypto.randomUUID();yt.current=ze,D.entities.Tool.update(m.id,{uuid:ze}).catch(cn=>{console.error("[ToolEditor] Failed to backfill tool UUID:",cn)})}K&&K.revision==null?(mt(K.id),Se(K.uuid??null),K.canvas_width&&ps(K.canvas_width),K.canvas_height&&Nr(K.canvas_height)):m.draft_implementation_uuid&&Se(m.draft_implementation_uuid),hn.current=Gl(K==null?void 0:K.canvas_width,K==null?void 0:K.canvas_height),Yr(!1),(b=K==null?void 0:K.design_brief)!=null&&b.text&&T(K.design_brief.text);let He="";try{K?He=await La(K):He=await zo(m)}
81catch(ze){console.warn("[ToolEditor] resolveCanvasCode failed, using inline canvas fields",ze),He=Ss("",m.draft_canvas_code,m.canvas_code)}const tt=(R=K==null?void 0:K.controls_schema)!=null&&R.length?K.controls_schema:Ss([],m.draft_controls_schema,m.controls_schema),it=await Uo(tt),vt=(S=K==null?void 0:K.libraries)!=null&&S.length?K.libraries:Ss([],m.draft_libraries,m.libraries),ks=K!=null&&K.custom_css_url?await fetch(K.custom_css_url).then(ze=>ze.text()).catch(()=>""):Ss("",m.draft_custom_css,m.custom_css);we(it),pe(He),Ce(vt),Ot(ks),Zt.current=(K==null?void 0:K.control_values)??null;const Ns=Go(K==null?void 0:K.timeline);Fe(Ns),Dt(Ml(Ns));const dt=(K==null?void 0:K.control_values)??null;if(jo(K,dt,{writeBackIfChanged:!0}),it.length>0||(He||"").trim()){const ze={...en,export:{...en.export,...(K==null?void 0:K.canvas_width)!=null&&{defaultWidth:K.canvas_width},...(K==null?void 0:K.canvas_height)!=null&&{defaultHeight:K.canvas_height}}},cn=pa({name:m.name||"Untitled Tool",controlsSchema:it,canvasCode:He||"",libraries:vt,customCss:ks,controlValues:Zt.current,hideControlsOnMobile:!0,canvasConfig:ze,editorMode:!0,externalControls:Na.current,showCanvasGuides:!0,showToolFrameBar:!nr.current});ko.current?(ko.current=!1,Fo(cn)):xt(cn)}else Q(null);if(bt(ze=>ze==="loading"?ze:"ready"),fe!=="draft"&&m.slug){const ze=await Lu(m).catch(()=>null);ze&&(Y(ze.id??null),ut(ze.uuid??null));const cn=ze?await La(ze):await zo({canvas_code_url:m.canvas_code_url,canvas_code:m.canvas_code});fr({toolName:m.name||"Untitled Tool",toolDescription:mr.current,toolTags:ot.current,controlsSchema:(ze==null?void 0:ze.controls_schema)??m.controls_schema??[],canvasCode:cn,libraries:(ze==null?void 0:ze.libraries)??m.libraries??[],customCss:m.custom_css||""})}if(Ee!=null&&Ee.id&&ws(Ee.id),Ee!=null&&Ee.selected_model&&Jr(Ee.selected_model),((M=Ee==null?void 0:Ee.messages)==null?void 0:M.length)>0)ht(Ee.messages);else{const ze=m.chat_history;let cn=!1;if(ze&&typeof ze=="object"){const Vt=Object.keys(ze);
81if(Vt.length>0){const wt=Vt[Vt.length-1],hs=ze[wt];hs&&hs.length>0&&(ws(wt),ht(hs),cn=!0)}}if(!cn&&a)try{const Vt=localStorage.getItem(`clay-chat-${a}`);if(Vt){const wt=JSON.parse(Vt);Array.isArray(wt)&&wt.length>0&&ht(wt)}}catch{}}d||gs.capture("tool_opened",{tool_id:m.id,tool_uuid:m.uuid,tool_name:m.name,visibility:m.visibility,is_public:m.is_public})}catch(m){console.error("[ToolEditor] Failed to load existing tool:",m)}finally{d||Sr(!1)}})(),()=>{d=!0}},[ts,Qs,j,a]),n.useEffect(()=>{Ex()},[]),n.useEffect(()=>{const d=gi.current!==ct;d&&aa.current.length>0&&ht([...aa.current]),d&&Ye==="loading"&&bt("idle"),gi.current=ct},[ct]);const xl=n.useRef(!1);n.useEffect(()=>{xl.current||!c||(xl.current=!0,ct&&!a&&ro(!0),i(d=>{const b=new URLSearchParams(d);return b.delete("prompt"),b.delete("plan"),b},{replace:!0}))},[c]);const io=n.useCallback(d=>{const b=ce.current;if(!b)return;const R=Jo(d);Bl(b,R),D.entities.Tool.update(b,{name:R}).catch(S=>console.error("[ToolEditor] Failed to save name:",S))},[]);n.useEffect(()=>{if(Je||!ce.current)return;const b=setTimeout(()=>io(u),1500);return()=>clearTimeout(b)},[io,Je,u]);const vi=n.useCallback(d=>{const b=_.current,R=d.name??"",S=Jo(R),M=Pp({currentName:b.value,suggestedName:R,manualEdited:b.manualEdited,lastAutoName:b.lastAutoName,alreadySuggested:b.hasGeneratedSuggestion});w(He=>{const tt=M?{value:S,manualEdited:He.manualEdited,lastAutoName:S,hasGeneratedSuggestion:!0}:{...He,hasGeneratedSuggestion:!0};return _.current=tt,tt});const m=(d.description??"").trim(),ye=!!m&&Op({currentDescription:mr.current,previousName:b.value}),fe=ud(d.system_tags),K=ot.current,Ee={system_tags:fe,user_tags:K,tags:Wo(fe,K)};M&&(Ee.name=S),ye&&(Ee.description=m,ts(m)),Nt.current=fe,Tr(fe),ce.current&&D.entities.Tool.update(ce.current,Ee).catch(He=>console.error("[ToolEditor] Failed to persist generated metadata:",He))},[ts,w,_,Tr,mr,ot,Nt]),Pr=n.useCallback(async(d={})=>{var b,R;if(ce.current)return ce.current;try{const S=Ge;if(!S)throw new Error("User not authenticated");const M=`tool-${Date.now().toString(36)}`,m=crypto.randomUUID(),ye=((b=d.name)==null?void 0:b.trim())||u||"Untitled Tool",fe=Ba(ye),K=await Ul({name:ye,slug:M,user_id:S.id,uuid:m,description:fe,is_public:!1},{id:S.id,full_name:S.full_name??null,email:S.email??void 0},{},{creationMode:d.creationMode??"prompt"});return ce.current=K.id,qn(K.id),yt.current=m,ts(fe),(R=d.name)!=null&&R.trim()&&j(ye),d.deferNavigation||t(`/tooleditor/${K.id}`,{replace:!0}),K.id}catch(S){return console.error("[ToolEditor] Failed to create Tool record:",S
81),null}},[u,t,Ge,ts,j]),Yn=n.useCallback(async d=>{const b=ce.current??await Pr();if(!b)throw new Error("Tool not available");return await D.entities.Tool.update(b,d),b},[Pr]),fl=n.useCallback(async d=>{const b=qi(d);try{await Yn({user_tags:b,tags:Wo(Nt.current,b)}),Qs(b)}catch(R){console.error("[ToolEditor] Failed to update tags:",R),Ie.error("Tags weren't updated due to a technical issue. Try again.")}},[Qs,Yn,Nt]),yi=n.useCallback(async d=>{const b=Mp(d).slice(0,Va);b&&await fl([...Bt,b])},[Bt,fl]),_i=n.useCallback(async d=>{const b=Bt.filter(M=>M!==d),R=Nt.current,S={visual_behavior:R.visual_behavior.filter(M=>M!==d),use_case:R.use_case.filter(M=>M!==d)};try{await Yn({user_tags:qi(b),system_tags:S,tags:Wo(S,b)}),Qs(b,S)}catch(M){console.error("[ToolEditor] Failed to update tags:",M),Ie.error("Tags weren't updated due to a technical issue. Try again.")}},[Bt,Yn,Qs,Nt]),oc=n.useMemo(()=>`<!DOCTYPE html>
82<html>
83<head>
84  <meta charset="UTF-8">
85  <meta name="viewport" content="width=device-width, initial-scale=1.0">
86  <style>
87    body { margin: 0; padding: 0; background: transparent; }
88  </style>
89</head>
90<body></body>
91</html>`,[]),Fo=n.useCallback(d=>{sa.current+=1,Ja.current=sa.current,xt(d)},[xt]),fs=n.useCallback(async()=>{var d,b,R;if(ce.current){Et(!0);try{const S=await D.entities.Tool.get(ce.current),M=S;Qs(Ol(M),Ll(M)),vs({custom_thumbnail:typeof S.custom_thumbnail=="string"?S.custom_thumbnail:null,thumbnail_aspect_ratio:typeof S.thumbnail_aspect_ratio=="number"?S.thumbnail_aspect_ratio:null,thumbnail_poster_url:typeof S.thumbnail_poster_url=="string"?S.thumbnail_poster_url:null,thumbnail_stream_format:typeof S.thumbnail_stream_format=="string"?S.thumbnail_stream_format:null,thumbnail_stream_url:typeof S.thumbnail_stream_url=="string"?S.thumbnail_stream_url:null,thumbnail_url:typeof S.thumbnail_url=="string"?S.thumbnail_url:null}),us.current=!!(typeof S.custom_thumbnail=="string"&&S.custom_thumbnail);const m=await Rl(S).catch(()=>null);m&&m.revision==null?(mt(m.id),Se(m.uuid??null),m.canvas_width&&ps(m.canvas_width),m.canvas_height&&Nr(m.canvas_height)):S.draft_implementation_uuid&&Se(S.draft_implementation_uuid),hn.current=Gl(m==null?void 0:m.canvas_width,m==null?void 0:m.canvas_height),Yr(!1),(d=m==null?void 0:m.design_brief)!=null&&d.text&&T(m.design_brief.text);const ye=(b=m==null?void 0:m.controls_schema)!=null&&b.length?m.controls_schema:Ss([],S.draft_controls_schema,S.controls_schema),fe=await Uo(ye),K=m?await La(m):await zo(S),Ee=(R=m==null?void 0:m.libraries)!=null&&R.length?m.libraries:Ss([],S.draft_libraries,S.libraries),He=m!=null&&m.custom_css_url?await fetch(m.custom_css_url).then(dt=>dt.text()).catch(()=>""):Ss("",S.draft_custom_css,S.custom_css),tt=new Set;De.current.forEach(dt=>{dt.key&&tt.add(dt.key)});const it=[];fe.forEach(dt=>{dt.key&&!tt.has(dt.key)&&it.push(dt.key)}),tt.size>0&&it.length>0&&F(dt=>{const ze=new Set(dt);return it.forEach(cn=>ze.add(cn)),ze}),F(dt=>{let ze=!1;const cn=new Set,Vt=new Set(fe.map(wt=>wt.key).filter(wt=>!!wt));return dt.forEach(wt=>{Vt.has(wt)?cn.add(wt):ze=!0}),ze?cn:dt});const vt=Tx(De.current,fe);vt.length>0&&oe(dt=>{const ze=new Set(dt);return vt.forEach(cn=>ze.add(cn)),ze}),oe(dt=>{let ze=!1;const cn=new Set,Vt=new Set(fe.filter(wt=>wt.type==="section"&&wt.label).map(wt=>wt.label));return dt.forEach(wt=>{Vt.has(wt)?cn.add(wt):ze=!0}),ze?cn:dt}),we(fe),pe(K),Ce(Ee),Ot(He),Zt.current=(m==null?void 0:m.control_values)??null;const ks=Go(m==null?void 0:m.timeline);Fe(ks),Dt(Ml(ks));const Ns=(m==null?void 0:m.control_values)??null;if(jo(m,Ns),fe.length>0||K){const dt={...en,export:{...en.export,...(m==null?void 0:m.canvas_width)!=null&&{defaultWidth:m.canvas_width},...(m==null?void 0:m.canvas_height)!=null&&{defaultHeight:m.canvas_height}}},ze=pa({name:u,controlsSchema:fe,canvasCode:K,libraries:Ee,customCss:He,controlValues:Zt.current,hideControlsOnMobile:!0,canvasConfig:dt,editorMode:!0,externalControls:Na.current,showCanvasGuides:!0,showToolFrameBar:!nr.current});Fo(ze)}bt("ready")}catch(S){console.warn("[ToolEditor] Failed to rebuild preview from structured update:",S)}finally{Et(!1)}}},[u,Fo,en,Qs,Zt,jo]),wi=n.useCallback(()=>{ii.current=fs()},[fs]),p=n.useCallback(async(d,b)=>{try{const R=await D.entities.ToolImplementation.get(d),S=(R==null?void 0:R.controls_schema)??[],M=await Uo(S),m=R?await La(R):"",ye=(R==null?void 0:R.libraries)??[],fe=R!=null&&R.custom_css_url?await fetch(R.custom_css_url).then(He=>He.text()).catch(()=>""):"",K=(R==null?void 0:R.control_values)??null,Ee=pa({name:u,controlsSchema:M,canvasCode:m,libraries:ye,customCss:fe,controlValues:K,hideControlsOnMobile:!0,canvasConfig:en,editorMode:!0,externalControls:Na.current,showCanvasGuides:!0,showToolFrameBar:!nr.current});xt(Ee),we(M),Zt.current=K,L({id:d,label:b}),Pe("version_preview")}catch(R){console.warn("[ToolEditor] handlePreviewVersion failed:",R)}},[u,en,Pe,Zt,xt]),g=n.useCallback(async({snapshotId:d,chatSessionEntityId:b})=>{var R;if(!U)throw new Error("[ToolEditor] No draft implementation loaded — cannot revert");Qa(!0);try{let S=b;if(yt.current)try{const tt=await D.entities.Tool.filter({uuid:yt.current}),it=(R=tt==null?void 0:tt[0])==null?void 0:R.chat_session_id;it&&(it!==b&&console.warn("[ToolEditor] chatSessionEntityId mismatch on revert — using authoritative ID",{provided:b,authoritative:it}),S=it)}catch(tt){console.warn("[ToolEditor] Could not fetch authoritative chat_session_id from Tool — using provided ID",tt)}const m=(await D.entities.ChatSession.get(S)).messages??[];let ye=-1;for(let tt=m.length-1;tt>=0;tt--)if(m[tt].tool_snapshot_id===d){ye=tt;break}const fe=await D.entities.ToolImplementation.get(d),K=ye===-1,Ee=K?[]:m.slice(0,ye+1);await D.entities.ChatSession.update(S,{messages:Ee});try{await D.entities.ToolImplementation.update(U,{controls_schema:fe.controls_schema??[],libraries:fe.libraries??[],...fe.canvas_code_url!=null&&{canvas_code_url:fe.canvas_code_url},...fe.custom_css_url!=null&&{custom_css_url:fe.custom_css_url},...fe.technology!=null&&{technology:fe.technology},...fe.canvas_width!=null&&{canvas_width:fe.canvas_width},...fe.canvas_height!=null&&{canvas_height:fe.canvas_height}})}catch(tt){throw console.warn("[ToolEditor] Code restore failed — rolling back ChatSession history",tt),await D.entities.ChatSession.update(S,{messages:m}).catch(it=>console.error("[ToolEditor] ChatSession rollback also failed — history may be truncated",it)),tt}(K?m:m.slice(ye+1)).map(tt=>
91tt.tool_snapshot_id).filter(Boolean).forEach(tt=>D.entities.ToolImplementation.delete(tt).catch(()=>null));try{await fs(),Ir()}catch(tt){console.warn("[ToolEditor] Canvas refresh failed after revert — revert data is saved, UI may need a refresh",tt)}return S}finally{Qa(!1)}},[U,fs,Ir]),N=n.useCallback(async()=>{if(!yt.current||!ce.current)throw new Error("[ToolEditor] Cannot ensure draft — missing tool");const d=crypto.randomUUID();let b={tool_uuid:yt.current,uuid:d,user_id:br,is_public:!1,controls_schema:[],libraries:[]};if(xe){const M=await D.entities.ToolImplementation.get(xe);b={...b,controls_schema:(M==null?void 0:M.controls_schema)??[],libraries:(M==null?void 0:M.libraries)??[],...(M==null?void 0:M.canvas_code_url)!=null&&{canvas_code_url:M.canvas_code_url},...(M==null?void 0:M.custom_css_url)!=null&&{custom_css_url:M.custom_css_url},...(M==null?void 0:M.canvas_width)!=null&&{canvas_width:M.canvas_width},...(M==null?void 0:M.canvas_height)!=null&&{canvas_height:M.canvas_height},...(M==null?void 0:M.control_values)!=null&&{control_values:M.control_values},...(M==null?void 0:M.design_brief)!=null&&{design_brief:M.design_brief},...(M==null?void 0:M.timeline)!=null&&{timeline:M.timeline},...(M==null?void 0:M.presets)!=null&&{presets:M.presets},...(M==null?void 0:M.technology)!=null&&{technology:M.technology}}}else if(Ue){const M=await D.entities.ToolImplementation.filter({uuid:Ue}),m=M==null?void 0:M[0];m&&(b={...b,controls_schema:(m==null?void 0:m.controls_schema)??[],libraries:(m==null?void 0:m.libraries)??[],...(m==null?void 0:m.canvas_code_url)!=null&&{canvas_code_url:m.canvas_code_url},...(m==null?void 0:m.custom_css_url)!=null&&{custom_css_url:m.custom_css_url},...(m==null?void 0:m.canvas_width)!=null&&{canvas_width:m.canvas_width},...(m==null?void 0:m.canvas_height)!=null&&{canvas_height:m.canvas_height},...(m==null?void 0:m.control_values)!=null&&{control_values:m.control_values},...(m==null?void 0:m.design_brief)!=null&&{design_brief:m.design_brief},...(m==null?void 0:m.timeline)!=null&&{timeline:m.timeline},...(m==null?void 0:m.presets)!=null&&{presets:m.presets},...(m==null?void 0:m.technology)!=null&&{technology:m.technology}})}const R=await D.entities.ToolImplementation.create(b),S=R==null?void 0:R.id;if(!S)throw new Error("[ToolEditor] Failed to create draft implementation");return mt(S),Se(d),await D.entities.Tool.update(ce.current,{draft_implementation_uuid:d}),S},[br,xe,Ue]),k=n.useRef(null),E=n.useCallback(async()=>U||(k.current||(k.current=N().finally(()=>{k.current=null})),k.current),[N,U]);St.current=E;const f=n.useCallback(async(d,b)=>{if(!ce.current&&!d.canvasCode.trim())throw new Error("This source file has no tool code to import.");const S={id:null},M=async()=>{if(!ce.current&&(S.id=await Pr({name:gx(d,b),creationMode:"import",deferNavigation:!0}),!S.id))throw new Error("Could not create the tool for this import");return E()};try{await bx(d,{ensureDraftImplId:M,handleStructuredUpdate:fs})}finally{S.id&&Hn.current&&t(`/tooleditor/${S.id}`,{replace:!0})}Sn.current=!0,zs(!0)},[E,Pr,fs,t]),ge=n.useCallback(async d=>{var b,R;if(!yt.current)throw new Error("[ToolEditor] Missing tool — cannot restore");Qa(!0);try{const S=await E(),M=await D.entities.ToolImplementation.filter({tool_uuid:yt.current}).catch(()=>[]);if(xe||Ue){const He=M.filter(it=>it.source_message_id).sort((it,vt)=>new Date(vt.created_date??0).getTime()-new Date(it.created_date??0).getTime());if(!He.some(it=>!!xe&&it.id===xe||!!Ue&&!!it.uuid&&it.uuid===Ue)){const it=(P&&He.some(vt=>vt.id===P)?P:null)??((b=He.find(vt=>vt.id===U))==null?void 0:b.id)??((R=He[0])==null?void 0:R.id)??null;it&&!P&&X(vt=>vt??it)}}const m=await D.entities.ToolImplementation.get(d),ye={controls_schema:m.controls_schema??[],libraries:m.libraries??[],...m.canvas_code_url!=null&&{canvas_code_url:m.canvas_code_url},...m.custom_css_url!=null&&{custom_css_url:m.custom_css_url},...m.technology!=null&&{technology:m.technology},...m.canvas_width!=null&&{canvas_width:m.canvas_width},...m.canvas_height!=null&&{canvas_height:m.canvas_height},...m.control_values!=null&&{control_values:m.control_values},...m.design_brief!=null&&{design_brief:m.design_brief},...m.timeline!=null&&{timeline:m.timeline},...m.presets!=null&&{presets:m.presets}},fe=Math.max(0,...M.filter(He=>He.revision!=null).map(He=>He.revision)),K=await D.entities.ToolImplementation.create({tool_uuid:yt.current,uuid:crypto.randomUUID(),user_id:m.user_id??br,is_public:!1,revision:fe+1,source_message_id:`restore:${crypto.randomUUID()}`,...ye}),Ee=K==null?void 0:K.id;if(!Ee)throw new Error("[ToolEditor] Failed to create restored version snapshot");await D.entities.ToolImplementation.update(S,ye),V(Ee),L(null);try{await fs(),Ir()}catch(He){console.warn("[ToolEditor] Canvas refresh failed after restore — draft is saved, UI may need a refresh",He)}return Ee}finally{Qa(!1)}},[P,U,E,br,fs,xe,Ue,Ir]),de=n.useCallback(()=>{L(null),Pe("version_preview_exit"),fs()},[fs,Pe]),G=n.useCallback(()=>
91{if(!O)return;if(Ye==="loading"){console.warn("[ToolEditor] Restore blocked — generation in progress");return}const d=O.id;gs.capture(Fa.VERSION_RESTORED,{tool_id:ce.current,tool_uuid:yt.current,impl_id:d}),Pe("version_restore"),ge(d).then(()=>{I("chat")}).catch(b=>{console.warn("[ToolEditor] Restore from preview bar failed:",b),Ie.error("Version wasn't restored due to a technical issue. Try again.")})},[O,Ye,ge,Pe]),ke=n.useCallback(d=>{bt(d)},[]),Be=n.useCallback(d=>{bt("error"),console.error("[ToolPreview]",d instanceof Error?d.message:d)},[]),Xe=n.useCallback(d=>{d.level!=="warning"&&ea({error_type:"tool_runtime",error_message:d.message??"",tool_id:qe??void 0,error_data:{attempt_number:Ls.current,error_count:no.current.length,is_post_generation:to.current,line:d.line??void 0,model:ns.current??void 0,stack_head:Cx(d.stack)}})},[qe,ea]),Ve=n.useCallback(()=>{To.current&&(clearTimeout(To.current),To.current=null),tr.current&&(clearTimeout(tr.current),tr.current=null)},[]),Qe=n.useCallback(d=>{Ve(),ra.current=!1,Ls.current=0,So.current=new Set,ns.current=null,ka(!1),d==="clean"?Pe("auto_fix_verified_clean"):d==="exhausted"&&(Pe("auto_fix_exhausted"),Ie.info("Couldn't auto-fix this one",{description:"Try refreshing the page, or remix the tool and continue from there."}))},[Ve,ka,Pe]),bn=n.useCallback((d=!1)=>{const b=no.current??[],R=b.filter(Ee=>Ee.level!=="warning");if(R.length===0){if(!d&&!ti.current)return;ra.current=!1,Qe("clean");return}ra.current=!1;const S=Ls.current,M=ns.current??zl[0],m=Sx(S,M,So.current);if(!m||!W.current){Qe("exhausted");return}const ye=R.map((Ee,He)=>`${He+1}. ${Ee.message??""}${Ee.line?` (line ${Ee.line})`:""}`).join(`
92`),fe=b.filter(Ee=>Ee.level==="warning"),K=fe.length?`
93
94Also present (fix only if they indicate a real bug, ignore cosmetic/deprecation noise):
95${fe.map((Ee,He)=>`${He+1}. ${Ee.message??""}`).join(`
96`)}`:"";Ls.current=S+1,So.current.add(m),Pe("auto_fix_attempt"),W.current.sendMessage(`The preview produced these issues. Fix them so the tool runs cleanly:
97
98${ye}${K}`,{modelOverride:m,isAutoFix:!0})},[Qe,Pe]),ss=n.useCallback(d=>{var R;if(!Xi.current)return;ti.current=!0,Ro&&((R=W.current)==null||R.attachHealth(d));const b=[];if(d.canvasOk===!1){const S=d.canvasReason??`no render surface — no sized, visible <canvas> was found (canvas ${d.canvasWidth??0}×${d.canvasHeight??0})`;b.push({biData:{error_type:"tool_health_blank_canvas",error_message:S,error_data:{attempt_number:Ls.current,canvas_height:d.canvasHeight??void 0,canvas_width:d.canvasWidth??void 0,model:ns.current??void 0}},payload:{level:"error",message:`Tool health: ${S}. Nothing is rendering. Brik exports the <canvas>, so every tool MUST render to the provided canvas/ctx (or a framework canvas like Three.js) — ensure it is created, sized, visible, and drawn to. Do NOT render to <svg> or other DOM; that exports blank.`}})}if(d.controlsOk===!1&&b.push({biData:{error_type:"tool_health_controls",error_message:`only ${d.controlsRendered??0} of ${d.controlsDeclared??0} declared controls rendered`,error_data:{attempt_number:Ls.current,controls_declared:d.controlsDeclared??void 0,controls_rendered:d.controlsRendered??void 0,model:ns.current??void 0}},payload:{level:"error",message:`Tool health: only ${d.controlsRendered??0} of ${d.controlsDeclared??0} declared controls rendered. The controls panel is not wired up — every control in the schema must be created via the controls API and read by the canvas code.`}}),b.length>0){const S=no.current??[],M=new Set(S.map(ye=>ye.message)),m=b.filter(ye=>!M.has(ye.payload.message));if(m.length>0){const ye=[...S,...m.map(fe=>fe.payload)];no.current=ye,Os(ye),m.forEach(fe=>ea({...fe.biData,tool_id:qe??void 0}))}}to.current&&ra.current&&bn(!1)},[qe,bn,Ro,ea]),at=n.useCallback(()=>{Ve(),To.current=setTimeout(bn,bb)},[Ve,bn]),Oe=n.useCallback(d=>{if(nr.current&&!d.isAutoFix&&!fi.current&&xi(!0),!d.ok){d.isAutoFix||cr(!0),to.current&&Qe("aborted");return}if(cr(!1),!d.codeWritten){to.current&&Qe("clean");return}V(null),L(null),ii.current.then(()=>Ir()).catch(b=>console.warn("[presets] post-chat thumbnail refresh skipped",b)),ns.current==null&&(ns.current=d.model),ka(!0),ra.current=!0,ti.current=!1,Ve(),tr.current=setTimeout(()=>{ra.current&&bn(!0)},vb)},[Qe,ka,Ve,bn,Ir]);n.useEffect(()=>Ve,[Ve]);const Gt=n.useCallback(async d=>{if(d.size>5*1024*1024){Ie.error("Image cover must be 5MB or smaller");return}mn("static-upload");try{const b=await Ui(d).catch(()=>ys),{file_url:R}=await D.integrations.Core.UploadFile({file:d});await Yn({thumbnail_aspect_ratio:b,thumbnail_poster_url:R}),vs(S=>({...S,thumbnail_aspect_ratio:b,thumbnail_poster_url:R})),us.current=!0}catch(b){console.error("[ToolEditor] Failed to upload static cover:",b),Ie.error("Cover wasn't updated due to a technical issue. Try again.")}finally{mn(null)}},[ys,Yn]),Tt=n.useCallback(async d=>{if(d.size>5*1024*1024){Ie.error("Video cover must be 5MB or smaller");return}mn("dynamic-upload");try{const b=await Ui(d).catch(()=>ys),[R,S]=await Promise.all([Hi(d,{awaitStream:!1}),dd(d)]),M={custom_thumbnail:R.file_url,thumbnail_aspect_ratio:b,thumbnail_stream_format:null,thumbnail_stream_url:""};let m=null;if(S){const ye=await D.integrations.Core.UploadFile({file:S});
98m=ye.file_url,M.thumbnail_poster_url=ye.file_url}await Yn(M),vs(ye=>({...ye,custom_thumbnail:R.file_url,thumbnail_aspect_ratio:b,thumbnail_stream_format:null,thumbnail_stream_url:null,thumbnail_poster_url:m??ye.thumbnail_poster_url??null})),ce.current&&Kt(ce.current,R.file_url,"custom_thumbnail"),us.current=!0}catch(b){console.error("[ToolEditor] Failed to upload dynamic cover:",b),Ie.error("Cover wasn't updated due to a technical issue. Try again.")}finally{mn(null)}},[ys,Kt,Yn]),Ze=n.useCallback(d=>{var R,S,M;const b=(S=(R=It.current)==null?void 0:R.getIframeRefObj)==null?void 0:S.call(R);(M=b==null?void 0:b.current)!=null&&M.contentWindow&&yn(b,Bu,{capturing:d})},[It]),Fn=n.useCallback(()=>{Xs("static"),Ze(!0)},[Ze]),ms=n.useCallback(()=>{Xs("dynamic"),Ze(!0)},[Ze]),js=n.useCallback(async d=>{mn("static-capture");try{const b=await _b(d,"static-cover.jpg"),{file_url:R}=await D.integrations.Core.UploadFile({file:b});await Yn({thumbnail_aspect_ratio:Cn,thumbnail_poster_url:R}),vs(S=>({...S,thumbnail_aspect_ratio:Cn,thumbnail_poster_url:R})),us.current=!0,Xs(null),Ze(!1),Pn.current&&(Ut({...Pn.current,page:"cover"}),Pn.current=null),jt.current&&(jt.current=!1,jn(!0))}catch(b){console.error("[ToolEditor] Failed to capture static cover:",b),Ie.error("Cover wasn't captured due to a technical issue. Try again."),on()}finally{mn(null)}},[on,Cn,Yn,Ze]),ln=n.useCallback(async(d,b)=>{mn("dynamic-record");try{const R=Dp(b),S=new File([d],`dynamic-cover.${R}`,{type:b||d.type}),M=await Hi(S,{awaitStream:!1});await Yn({custom_thumbnail:M.file_url,thumbnail_aspect_ratio:Cn,thumbnail_stream_format:null,thumbnail_stream_url:""}),vs(m=>({...m,custom_thumbnail:M.file_url,thumbnail_aspect_ratio:Cn,thumbnail_stream_format:null,thumbnail_stream_url:null})),ce.current&&Kt(ce.current,M.file_url,"custom_thumbnail"),us.current=!0,Xs(null),Ze(!1),Pn.current&&(Ut({...Pn.current,page:"cover"}),Pn.current=null),jt.current&&(jt.current=!1,jn(!0))}catch(R){console.error("[ToolEditor] Failed to record dynamic cover:",R),Ie.error("Cover wasn't recorded due to a technical issue. Try again."),on()}finally{mn(null)}},[on,Cn,Kt,Yn,Ze]);n.useEffect(()=>{Rt||ya(null)},[Rt]);const Or=n.useCallback(async()=>{mn("clear-cover");try{await Yn({custom_thumbnail:null,thumbnail_poster_url:null,thumbnail_stream_format:null,thumbnail_stream_url:""}),vs(d=>({...d,custom_thumbnail:null,thumbnail_poster_url:null,thumbnail_stream_format:null,thumbnail_stream_url:null})),us.current=!1}catch(d){console.error("[ToolEditor] Clearing the cover failed:",d),Ie.error("Cover wasn't removed due to a technical issue. Try again.")}finally{mn(null)}},[Yn]),ic=n.useCallback(()=>{Xs(null),Ze(!1),on()},[on,Ze]),Hx=n.useCallback(d=>{console.warn("[ToolEditor] Cover capture failed:",d),Ie.error("Cover wasn't captured due to a technical issue. Try again."),ic()},[ic]),zx=n.useCallback(()=>{if(bt("ready"),ra.current&&at(),us.current||Ja.current===0||Ja.current!==sa.current)return;Ja.current=0,Ps.current&&clearTimeout(Ps.current);const d=sa.current;Ps.current=setTimeout(()=>{sa.current===d&&_e()},2e3)},[_e,at]),hd=n.useCallback(async()=>{var b,R;const d=na();try{const S=$a(q,ie),M=await ta(S),m=await ho(M,S,D),ye=Lc(S,m),{schema:fe,skippedKeys:K}=await xo(ye),Ee=ie?await fo(ie):null,He=se?await mo(se):null,tt=ce.current??await Pr();if(!tt)throw new Error("Tool not available");let it=U,vt=le;const ks=As(it);if(it)await D.entities.ToolImplementation.update(it,{canvas_code_url:Ee??"",controls_schema:fe,libraries:J,custom_css_url:He??"",control_values:{},control_checkpoints:ks,timeline:Te});else{const dt=crypto.randomUUID();it=(await D.entities.ToolImplementation.create({tool_uuid:yt.current,uuid:dt,user_id:br,is_public:!1,canvas_code_url:Ee??"",controls_schema:fe,libraries:J,timeline:Te,...He?{custom_css_url:He}:{},...un!==nt.export.defaultWidth?{canvas_width:un}:{},...an!==nt.export.defaultHeight?{canvas_height:an}:{}})).id,vt=dt,mt(it),Se(vt),await D.entities.Tool.update(tt,{draft_implementation_uuid:vt})}await D.entities.Tool.update(tt,{name:u,description:We}),we(ye),rn(!1),er();const Ns=(R=(b=It.current)==null?void 0:b.getIframeRefObj)==null?void 0:R.call(b);return Ns&&m&&yn(Ns,El,m),K.length?Ie.info("Saved. The canvas drawing was too large to store."):Ie.success("Saved."),!0}
98catch(S){return console.error("[ToolEditor] Save failed:",S),Ie.error("Tool wasn't saved due to a technical issue. Try again."),!1}finally{d()}},[ie,an,un,er,q,se,U,le,br,Pr,ta,J,Te,na,As,We,u]),lc=n.useCallback(async()=>{B("saving");const d=await hd();B(d?"saved":"error")},[hd]);n.useEffect(()=>{const d=()=>{Je||Rs||Tn||lc()},b=S=>{!(S.metaKey||S.ctrlKey)||S.key!=="s"&&S.key!=="S"||(S.preventDefault(),d())};window.addEventListener("keydown",b);const R=$n(S=>{S.type===Fu&&d()});return()=>{window.removeEventListener("keydown",b),R()}},[lc,Je,Rs,Tn]),n.useEffect(()=>Ys?$n(b=>{var R;if(b.type===rd){const S=(R=b.payload)==null?void 0:R.dirty;rn(S===void 0?!0:!!S)}}):void 0,[Ys]),n.useEffect(()=>$n(d=>{var R,S;if(d.type!==$u)return;const b=(R=d.payload)==null?void 0:R.key;b&&((S=sr.current)==null||S.addOrRevealTrack(b))}),[]),n.useEffect(()=>$n(b=>{var S,M;if(b.type!==Vu)return;const R=(M=(S=It.current)==null?void 0:S.getIframeRefObj)==null?void 0:M.call(S);R&&(yn(R,Hu),yn(R,zu,{schema:De.current}))}),[It]),n.useEffect(()=>$n(b=>{var S,M;if(b.type!==Uu)return;const R=(M=(S=It.current)==null?void 0:S.getIframeRefObj)==null?void 0:M.call(S);R&&yn(R,Bc)}),[It]),n.useEffect(()=>$n(b=>{var R,S;if(b.type===Gu&&((R=b.payload)!=null&&R.schema)){const M=b.payload.schema,m=De.current;if(JSON.stringify(m)===JSON.stringify(M))return;const ye=Ee=>
98new Set(Ee.filter(He=>!He.deleted&&He.key).map(He=>He.key)),fe=ye(M),K=[...ye(m)].filter(Ee=>!fe.has(Ee));we(M),K.length>0&&((S=sr.current)==null||S.dropTracks(K)),U&&!O&&D.entities.ToolImplementation.update(U,{controls_schema:M}).catch(Ee=>{console.error("[ToolEditor] Failed to save schema from edit mode",Ee)})}}),[U,O]);const{handleToggleControlVisibility:gd,handleDeleteControl:bd,handleRenameControl:vd,handleReorderControls:Ux,handleReorderSections:Gx,handleBulkSetVisibility:Wx,handleBulkDeleteControls:qx,handleMoveControlsToSection:Kx}=_x({setControlsSchema:we,draftImplId:U,dropTracks:d=>{var b;return(b=sr.current)==null?void 0:b.dropTracks(d)},isPreviewingVersion:!!O});n.useEffect(()=>$n(b=>{var R,S;if(b.type===Wu){const M=b.payload,m=M==null?void 0:M.w,ye=M==null?void 0:M.h;if(typeof m=="number"&&typeof ye=="number"&&m>0&&ye>0){if(ps(m),Nr(ye),va(m/ye),M!=null&&M.userInitiated&&!O&&!lt.current){const fe=hn.current;Yr(m!==fe.width||ye!==fe.height)}U&&!O&&!lt.current&&D.entities.ToolImplementation.update(U,{canvas_width:m,canvas_height:ye}).catch(fe=>{console.error("[ToolEditor] Failed to persist canvas size",fe)})}}if(b.type===qu){const M=(R=b.payload)==null?void 0:R.width,m=(S=b.payload)==null?void 0:S.height;typeof M=="number"&&typeof m=="number"&&M>0&&m>0&&va(M/m)}b.type===Hf&&oo(!bs)}),[U,O,bs,oo]),n.useEffect(()=>()=>{Ps.current&&clearTimeout(Ps.current),Ja.current=0},[]);const Yx=n.useMemo(()=>ie?Ku({name:u,controlsSchema:q,canvasCode:ie,libraries:J,customCss:se,timeline:Te}):null,[u,q,ie,J,se,Te]),Zx=n.useMemo(()=>Go(Te)??gt,[Te,gt]),Jx=n.useMemo(()=>({id:ce.current,uuid:yt.current,controlsSchema:q,canvasCode:ie,libraries:J,customCss:se,slug:Qn??void 0,visibility:wr,isPublic:Ht}),[q,ie,J,se,Qn,wr,Ht]),yd=async d=>{Xt(!0),Ps.current&&(clearTimeout(Ps.current),Ps.current=null);const R=`${u.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"untitled"}-${Date.now().toString(36)}`;let S=Promise.resolve(null);const M=na();try{const m=$a(q,ie),ye=await ta(m);S=gr().catch(()=>null);const fe=await ho(ye,m,D),K=Lc(m,fe),{schema:Ee,skippedKeys:He}=await xo(K),tt=await fo(ie),it=se?await mo(se):null,vt=d??Xn,ks=vt==="public",Ns=vt==="public",dt=Al(await li());if(ce.current){const Vt=await D.entities.ToolImplementation.filter({tool_uuid:yt.current}).catch(()=>[]),hs=Math.max(0,...Vt.filter(vn=>vn.revision!=null).map(vn=>vn.revision))+1;let ar=U,or=le;if(ar){await D.entities.ToolImplementation.update(ar,{revision:hs,is_public:ks,canvas_code_url:tt,controls_schema:Ee,libraries:J,custom_css_url:it||"",control_values:{},control_checkpoints:As(ar),timeline:Te,...un!==nt.export.defaultWidth?{canvas_width:un}:{},...an!==nt.export.defaultHeight?{canvas_height:an}:{},...dt!==void 0?{presets:dt}:{}});const vn=await D.entities.ToolImplementation.get(ar);or=(vn==null?void 0:vn.uuid)??or}else{const vn=crypto.randomUUID(),Aa=await D.entities.ToolImplementation.create({tool_uuid:yt.current,uuid:vn,user_id:br,is_public:ks,revision:hs,canvas_code_url:tt,controls_schema:Ee,libraries:J,timeline:Te,...it?{custom_css_url:it}:{},...un!==nt.export.defaultWidth?{canvas_width:un}:{},...an!==nt.export.defaultHeight?{canvas_height:an}:{},...dt!==void 0?{presets:dt}:{}});ar=(Aa==null?void 0:Aa.id)??void 0,or=vn}await D.entities.Tool.update(ce.current,{name:u,slug:R,is_public:Ns,visibility:vt,description:We||Ba(u),published_implementation_uuid:or,draft_implementation_uuid:""}),xe&&xe!==ar&&Vt.some(Aa=>Aa.id===xe)&&D.entities.ToolImplementation.delete(xe).catch(()=>null),Y(ar),ut(or),V(null),X(null),mt(null),Se(null)}else{const Vt=Ge;if(!Vt)throw new Error("Not authenticated");const wt=crypto.randomUUID(),hs=await Ul({name:u,slug:R,description:We||Ba(u),is_public:Ns,visibility:vt,user_id:Vt.id,uuid:wt},{id:Vt.id,full_name:Vt.full_name??null,email:Vt.email??null},{},{creationMode:"prompt"});ce.current=hs.id,qn(hs.id),yt.current=wt,t(`/tooleditor/${hs.id}`,{replace:!0});const ar=crypto.randomUUID(),or=await D.entities.ToolImplementation.create({tool_uuid:wt,uuid:ar,user_id:Vt.id,is_public:ks,revision:1,canvas_code_url:tt,controls_schema:Ee,libraries:J,timeline:Te,...it?{custom_css_url:it}:{},...un!==nt.export.defaultWidth?{canvas_width:un}:{},...an!==nt.export.defaultHeight?{canvas_height:an}:{},...dt!==void 0?{presets:dt}:{}});await D.entities.Tool.update(hs.id,{published_implementation_uuid:or.uuid}),Y(or.id),ut(or.uuid)}ce.current&&Qu({toolId:ce.current,designBrief:me}).catch(Vt=>console.warn("[ToolEditor] Metadata refresh failed:",Vt)),we(K),ha(R),os(Ns),Ks(vt),Un(vt),jr(!0),rn(!1),er(),fr({toolName:u,toolDescription:We,toolTags:Bt,controlsSchema:K,canvasCode:ie,libraries:J,customCss:se}),Zs(!1);const ze=ce.current;S.then(Vt=>Rr(Vt,ze)),He.length&&Ie.info("Published. The canvas drawing was too large to store."),ja(!0),nr.current||Ut({page:"preview",anchor:"publish"});const cn={tool_id:ce.current??void 0,userId:Ge==null?void 0:Ge.id};ir(lr.TOOL_PUBLISHED,Il(cn),cn,{tool_uuid:yt.current,visibility:vt,slug:R,tag_count:Bt.length,controls_count:Ee.length,is_republish:!1}),localStorage.getItem("clay-first-tool-created")||(localStorage.setItem("clay-first-tool-created","1"),gs.capture("first_tool_created",{tool_id:ce.current,tool_uuid:yt.current,visibility:vt,slug:R}))}catch(m){console.error("Publish failed:",m),$r({eventName:"content_creation_failed",properties:{error_type:"publish_error",error_message:m instanceof Error?m.message:"Update failed",is_public:!0}}),Ie.error("Tool wasn't published due to a technical issue. Try again."),pn("Couldn't publish. Check your connection and try again.")}finally{M(),Xt(!1)}},_d=async d=>{var R,S;if(!ce.current||!Qn)return;Ps.current&&(clearTimeout(Ps.current),Ps.current=null),fa(!0);const b=na();try{const M=$a(q,ie),m=await ta(M),ye=await ho(m,M,D),fe=Lc(M,ye),{schema:K,skippedKeys:Ee}=await xo(fe),He=await fo(ie),tt=se?await mo(se):null,it=wr,vt=d??Xn,ks=vt==="public",Ns=vt==="public",dt=Al(await li()),ze=await D.entities.ToolImplementation.filter({tool_uuid:yt.current}).catch(()=>[]),Vt=Math.max(0,...ze.filter(vn=>vn.revision!=null).map(vn=>vn.revision))+1;let wt=U,hs=le;if(wt)await D.entities.ToolImplementation.update(wt,{revision:Vt,is_public:ks,canvas_code_url:He,controls_schema:K,libraries:J,custom_css_url:tt||"",control_values:{},control_checkpoints:As(wt),timeline:Te,...un!==nt.export.defaultWidth?{canvas_width:un}:{},...an!==nt.export.defaultHeight?{canvas_height:an}:{},...dt!==void 0?{presets:dt}:{}});else{const vn=crypto.randomUUID();wt=(await D.entities.ToolImplementation.create({tool_uuid:yt.current,uuid:vn,user_id:br,is_public:ks,revision:Vt,canvas_code_url:He,controls_schema:K,libraries:J,timeline:Te,...tt?{custom_css_url:tt}:{},...un!==nt.export.defaultWidth?{canvas_width:un}:{},...an!==nt.export.defaultHeight?{canvas_height:an}:{},...dt!==void 0?{presets:dt}:{}})).id,hs=vn}await D.entities.Tool.update(ce.current,{name:u,description:We||Ba(u),slug:Qn,is_public:Ns,visibility:vt,published_implementation_uuid:hs,draft_implementation_uuid:""}),xe&&xe!==wt&&ze.some(Aa=>Aa.id===xe)&&D.entities.ToolImplementation.delete(xe).catch(()=>null),Y(wt),ut(hs),V(null),X(null),mt(null),Se(null),we(fe),rn(!1),er(),os(Ns),Ks(vt),Un(vt),fr({toolName:u,toolDescription:We,toolTags:Bt,controlsSchema:fe,canvasCode:ie,libraries:J,customCss:se}),Es(!1),gr().then(vn=>Rr(vn,ce.current));const ar=(S=(R=It.current)==null?void 0:R.getIframeRefObj)==null?void 0:S.call(R);ar&&ye&&yn(ar,El,ye),Ee.length&&Ie.info("Updated. The canvas drawing was too large to store."),ja(!0),nr.current||Ut({page:"preview",anchor:"publish"});const or={tool_id:ce.current??void 0,userId:Ge==null?void 0:Ge.id};ir(lr.TOOL_PUBLISHED,Il(or),or,{tool_uuid:yt.current,visibility:vt,visibility_changed:it!==vt,tag_count:Bt.length,controls_count:K.length,is_republish:!0})}catch(M){console.error("Update failed:",M),$r({eventName:"content_creation_failed",properties:{error_type:"update_error",error_message:M instanceof Error?M.message:"Update failed",tool_uuid:yt.current}}),Ie.error("Tool wasn't updated due to a technical issue. Try again."),pn("Couldn't update. Check your connection and try again.")}finally{b(),fa(!1)}},wd=async()=>{const d=Gn.trim()||`${u} (Remix)`;if(ce.current)try{Pe("Remix");const{tool:b}=await s({toolId:ce.current,options:{source:"draft",name:d}});if(!b)return;Is(!1),Lt(""),window.location.href=`/tooleditor/${b.id}`}catch(b){console.error("Remix failed:",b),Ie.error(b instanceof Error?b.message:"Tool wasn't remixed due to a technical issue. Try again.")}},cc=async()=>
98{if(ce.current)try{const d=await D.entities.Tool.get(ce.current);if(await D.entities.Tool.update(ce.current,{is_public:!1,visibility:"draft"}),d!=null&&d.published_implementation_uuid){const b=await D.entities.ToolImplementation.filter({uuid:d.published_implementation_uuid}).catch(()=>[]);b[0]&&await D.entities.ToolImplementation.update(b[0].id,{is_public:!1})}os(!1),Ks("draft"),Un("private"),jr(!1),fr(null),Qt(!1),Ie.success("Tool unpublished.")}catch(d){console.error("Unpublish failed:",d),Ie.error("Tool wasn't unpublished due to a technical issue. Try again.")}},Xx=async()=>{const d=ce.current;kr(!0);try{if(d){const b=await D.entities.Tool.get(d).catch(()=>null),R=b==null?void 0:b.uuid;if(R){const S=await D.entities.ToolImplementation.filter({tool_uuid:R}).catch(()=>[]);await Promise.all(S.map(M=>D.entities.ToolImplementation.delete(M.id).catch(()=>null)))}await D.entities.Tool.delete(d),Ge!=null&&Ge.id&&await qs.invalidateQueries({queryKey:[sd,Ge.id]})}window.location.href=Ho("ToolEditor")}catch(b){console.error("Delete failed:",b),Ie.error("Tool wasn't deleted due to a technical issue. Try again."),kr(!1),Mn(!1)}},Qx=n.useMemo(()=>fx(!!ce.current,Ys),[Ys]),dc=()=>{pn(null);const d=Xn==="public"?"public":"private";Un(d),Ma==="draft"?yd(d):_d(d)},ef=d=>{jn(!1),pn(null),d||Pe("tool_editor_settings_close"),Ut(d?{page:"preview",anchor:"publish"}:null)},Cd=d=>e.jsx(ib,{listingDraft:hr,onListingDraftChange:Ca,publishState:Ma,justPublished:Qr,visibility:Xn,onVisibilityChange:Un,toolName:u,toolDescription:We,media:An,shareUrl:bi,isPublishing:Rs||Tn,initialPage:d,publishError:Ms,onPublish:dc,onUnpublish:()=>{Pe("Unpublish"),Qt(!0),Ut(null)},onClose:()=>{Pe("tool_editor_settings_close"),pn(null),Ut(null)},onToolNameChange:b=>{v(b,"manual"),io(b)},onToolDescriptionChange:ts,toolTags:Bt,onAddTag:yi,onRemoveTag:_i,onCaptureStaticCover:()=>{Pn.current=kt,Ut(null),Fn()},onRecordDynamicCover:()=>{Pn.current=kt,Ut(null),ms()},onUploadStaticCover:Gt,onUploadDynamicCover:Tt,onClearCover:()=>void Or(),isCoverWorking:Wn!==null||Rt!==null||Ln}),tf=!Je&&C?e.jsx(Qg,{viewerUrl:bi,disabled:!!O,onShare:()=>{Ma==="draft"?is(!0):Rn(!0)},onRemix:()=>{Pe("Remix"),Lt(`${u} (Remix)`),Is(!0)},onEditCover:()=>{Pe("tool_editor_settings_open"),Ut({page:"cover",anchor:"actions"})},onDelete:()=>{Pe("Delete Tool"),Mn(!0)},coverPanel:(kt==null?void 0:kt.anchor)==="actions"?Cd(kt.page):null,coverPanelOpen:(kt==null?void 0:kt.anchor)==="actions",onCoverPanelClose:()=>{Pe("tool_editor_settings_close"),pn(null),Ut(null)}}):null,nf=!Je&&C?e.jsx(Vr,{sendToolEditorAction:Pe,children:e.jsx(tb,{publishDisabled:!!O,publishDisabledReason:O?"Exit or restore to enable":void 0,isPublishing:Rs||Tn,onPublishNow:dc,publishOpensPanel:Ma==="draft",publishPanelOpen:(kt==null?void 0:kt.anchor)==="publish",onPublishPanelOpenChange:ef,publishPanel:(kt==null?void 0:kt.anchor)==="publish"?Cd(kt.page):null,capturing:Rt!==null,onExport:()=>{var d,b;return(b=(d=It.current)==null?void 0:d.openExport)==null?void 0:b.call(d)}})}):null;return e.jsxs("div",{className:"font-product h-[100dvh] flex [font-family:var(--product-font)]",children:[!ct&&e.jsx(om,{}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-0 bg-[var(--product-grey-01)] transition-[padding] duration-300 ease-out",style:{color:"rgba(0, 0, 0, 1)",backgroundImage:"none",borderStyle:"none",borderImage:"none",paddingBottom:ct&&Ar?Math.max(0,Lo-si):void 0},children:[Xr&&e.jsx("div",{className:"fixed inset-0 z-40","aria-hidden":!0,onClick:()=>jn(!1)}),e.jsx("div",{className:"hidden lg:block relative z-[20] shrink-0",children:e.jsx(im,{toolName:u,thumbnailUrl:po(An),saveStatus:!Je&&C?nn:null,onRename:O?void 0:d=>v(d,"manual"),actionsMenu:tf,captureControls:Rt?e.jsx("div",{ref:et,className:"flex items-start self-stretch"}):null,recordingControls:Ln&&!ct?e.jsx("div",{ref:Yt,className:"flex items-start self-stretch"}):null,actions:nf})}),!Je&&e.jsx("div",{className:"lg:hidden shrink-0",children:e.jsx(ep,{chromeVariant:"v2",toolName:u,thumbnailUrl:po(An),creatorName:(Ge==null?void 0:Ge.full_name)??void 0,publishLabel:"Publish",onBack:()=>{var b;(((b=window.history.state)==null?void 0:b.idx)??0)>0?t(-1):t(Ho("Home"))},onToggleSave:lc,onShare:()=>{Pe("tool_publish_controls_copy_link"),Rn(!0)},onPublish:()=>Js(!0),onExport:()=>{var d,b;return(b=(d=It.current)==null?void 0:d.openExport)==null?void 0:b.call(d)},userName:(Ge==null?void 0:Ge.full_name)||void 0,userEmail:(Ge==null?void 0:Ge.email)||void 0})}),es&&e.jsx("div",{className:"fixed inset-0 z-[80] bg-[var(--product-grey-01)]",style:{opacity:Je?1:0,pointerEvents:Je?"auto":"none",transition:`opacity ${Ed}ms ease-in-out`},children:e.jsx(lm,{className:"absolute inset-0",background:"var(--product-grey-01)",label:"Restoring session"})}),!Je&&e.jsx("div",{className:"flex-1 min-h-0 flex flex-col relative",style:{backgroundColor:"unset",background:"unset"}
98,children:e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col lg:flex-row relative",children:[!ct&&e.jsx(zp,{collapsed:bs,gutter:0,width:wl,collapseMode:"instant",children:e.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden",children:[e.jsx(Hs.div,{initial:{x:-28,opacity:0},animate:{x:0,opacity:A!=="chat"?0:1},transition:Oc,className:`absolute inset-0 flex min-h-0 flex-col gap-[5px] ${A!=="chat"?"pointer-events-none":""}`,children:e.jsx(Vr,{sendToolEditorAction:Pe,children:e.jsx(Vl,{newDesign:!0,sharedEdges:"top-left",chatOverlay:el,initialPrompt:c,initialImageUrls:x,initialReferenceFiles:h,onBeforeSend:ci,onStructuredUpdate:wi,onStatusChange:ke,onPlanTurnActiveChange:Us,onPlanQuestionsReceived:Ur,onPlanQuestionsPendingChange:di,onGenerationComplete:Oe,autoFixing:eo,ensureToolId:Pr,getToolUuid:()=>yt.current,restoredMessages:_s??void 0,restoredSessionId:zt??void 0,restoredModel:Ya??void 0,onMessagesUpdate:d=>{aa.current=d},consoleErrors:No,onGeneratedMetadata:vi,isAdmin:Dr,onRevertToVersion:g,genesisSnapshotId:fn?U??void 0:void 0,toolHasCode:!!ie||fn,onDesignBriefUpdate:T,currentBrief:me,chatActionsRef:W,onCollapse:Ye!=="idle"?()=>oo(!0):void 0,onToggleVersions:qe?()=>{if(A==="versions"){I("chat"),L(null),fs();return}I("versions"),gs.capture(Fa.VERSIONS_PANEL_OPENED,{tool_id:ce.current,tool_uuid:yt.current}),Pe("version_panel_open")}:void 0,versionsOpen:A==="versions"})})},"tool-chat-panel"),e.jsx(Yu,{initial:!1,children:A==="versions"?e.jsx(Hs.div,{initial:{x:-28,opacity:0}
98,animate:{x:0,opacity:1},exit:{x:-28,opacity:0},transition:Oc,className:"absolute inset-0 flex min-h-0 flex-col",children:e.jsx(px,{chromeVariant:"v2",toolUuid:yt.current,chatMessages:aa.current.length>0?aa.current:_s??void 0,draftImplId:U,publishedImplId:xe,publishedImplUuid:Ue,previewingId:(O==null?void 0:O.id)??null,activeVersionId:P,liveSnapshotId:re,onPreview:p,onExitPreview:de,onRestore:d=>{if(Ye==="loading"){console.warn("[ToolEditor] Restore blocked — generation in progress");return}gs.capture(Fa.VERSION_RESTORED,{tool_id:ce.current,tool_uuid:yt.current,impl_id:d}),Pe("version_restore"),ge(d).then(()=>{I("chat")}).catch(b=>{console.warn("[ToolEditor] Restore from versions panel failed:",b),Ie.error("Version wasn't restored due to a technical issue. Try again.")})},onClose:()=>{I("chat"),L(null),fs()}})},"tool-versions-panel"):A==="settings"?e.jsx(Hs.div,{initial:{x:-28,opacity:0},animate:{x:0,opacity:1},exit:{x:-28,opacity:0},transition:Oc,className:"absolute inset-0 flex min-h-0 flex-col",children:e.jsx(dx,{isEditingName:je,isAdmin:Dr,isWorking:Ft||Wn!==null||Rt!==null||Ln,media:An,coverAspectRatio:ys,onChangeDescription:ts,onCaptureStaticCover:Fn,onClose:()=>{he(!1),I("chat")},onCommitName:d=>{v(d,"manual"),he(!1)},onOpenNameEdit:()=>{Pe("Rename"),he(!0)},onRecordDynamicCover:ms,onRemoveTag:_i,onUploadDynamicCover:Tt,onUploadStaticCover:Gt,onUpsertTag:yi,toolDescription:We,toolName:u,toolSystemTags:$e,toolTags:Bt})},"tool-settings-panel"):null})]})}),e.jsxs("div",{className:"flex flex-col flex-1 min-h-0 gap-[5px] relative",children:[O?e.jsx("div",{className:"absolute top-0 right-[330px] z-20 flex items-start pointer-events-none",style:{left:bs?0:wl},children:e.jsx("div",{className:"w-full pointer-events-auto",children:e.jsx(xx,{versionName:O.label,onExitPreview:de,onRestore:G,isRestoring:Xa})})}):null,e.jsx(Vr,{sendToolEditorAction:Pe,children:e.jsx(mx,{chatCollapsed:bs,coverAspectRatio:ys,coverCaptureDuration:yb,coverCaptureMode:Rt,coverCaptureWorking:Wn!==null,consoleErrors:No,isAdmin:Dr,isGenerating:(Ye==="loading"||At)&&!C||eo,isReverting:Xa,onCoverCaptureCancel:ic,coverCaptureVariant:"product",onCoverCropAspectRatioChange:ya,renderCoverCaptureControls:d=>Re?Ko.createPortal(e.jsx(Yg,{...d}),Re):null,renderRecordingOverlay:d=>$t?Ko.createPortal(e.jsx(lb,{...d}),$t):null,onCoverCaptureError:Hx,onDynamicCoverCaptured:ln,onError:Be,onErrorsChange:Os,onNewError:Xe,onHealth:ss,onReady:zx,onStaticCoverCaptured:js,onToolAction:Pe,onExportedFile:ct?void 0:qr,onControlEditRequest:(d,b)=>{b==="slider"&&ae(d)},onControlMenuRequest:d=>$(d),freshControlKeys:te,onControlFreshCleared:Le,freshSectionLabels:st,onSectionFreshCleared:rt,onToggleControlVisibility:gd,onDeleteControl:bd,onRenameControl:vd,onReorderControls:Ux,onReorderSections:Gx,onBulkSetVisibility:Wx,onBulkDeleteControls:qx,onMoveControlsToSection:Kx,previewRef:It,showIdleOverlay:hi,holdUntilTool:ub({hasPreviewHtml:!!C,lastGenerationFailed:zr,buildStarted:as,previewPending:At,arrivedWithPrompt:!!c}),idleOverlayExiting:xa,newDesignLayout:!0,onIdleGenerate:(d,b)=>{var R;ul(),(R=W.current)==null||R.sendMessage(d,{modelOverride:b})},toolData:Jx,autosavedControlValuesRef:O?null:Zt,timeline:Te,onBeforeRecord:()=>{var d;return(d=sr.current)==null?void 0:d.playFromStart()},onExportOpenChange:xr,onRecordingChange:ol,onImportImplementation:f,showSourceImport:sl,toolHtml:C||oc,toolLoaded:!!C,toolName:u,onOpenProjection:qe&&!(ct&&!Dr)?ac:void 0,getControlsSchema:()=>De.current,onMidiMappingLearned:sn,onMidiMappingCleared:Ji,onPanelWidthChange:Mr,controlsSchema:q,showDesktopControlsPanel:Bs,toolLoadKey:C?String(Z):null,toolId:qe,timelineActive:Eo&&!!C&&Dn.active,trackedControlKeys:Dn.tracked,onToggleTrack:d=>{var b;return(b=sr.current)==null?void 0:b.addOrRevealTrack(d)},onMotionTabChange:d=>{var b,R;return d?(b=sr.current)==null?void 0:b.openDock():(R=sr.current)==null?void 0:R.collapseDock()},revealControl:Jn,presetController:Io})}),Eo&&!ct&&!!C&&e.jsx(Vr,{sendToolEditorAction:Pe,children:e.jsx(tp,{ref:sr,controlsSchema:q,iframeRef:Bo,toolLoadKey:String(Z),chatCollapsed:bs,chatPanelWidth:wl,draftImplId:U,initialTimeline:gt,controlsPanelWidth:al,onTimelineChange:Dt,onTrackKeysChange:qt,onRevealControl:be,playbackLocked:Ln,persistencePaused:Kn,chromeVariant:"v2",hasMotionRail:Bs,fullWidth:bs,onToggleFullWidth:()=>oo(!bs)})}),ct&&Po&&e.jsx(Gm,{mode:"mobile",chromeVariant:"v2",controlsSchema:q,iframeRef:Bo,toolL
98oadKey:String(Z),toolId:qe,open:Ar,onClose:()=>Da(!1),onHeightChange:dl}),ct?el:null]}),e.jsx(Hp,{chrome:"new-design",collapsed:bs,onExpand:()=>oo(!1),gutter:0})]})}),!Je&&ct&&e.jsxs("div",{className:`lg:hidden shrink-0 ${rc} ${sc?"pointer-events-none translate-y-[8px] opacity-0 duration-0":"translate-y-0 opacity-100 delay-300 duration-200"}`,ref:Qi,children:[Eo&&!!C&&Zu(Te)&&e.jsx(lx,{timeline:Zx,controlsSchema:q,iframeRef:Bo,playbackLocked:Ln,chromeVariant:"v2"}),e.jsx(np,{chromeVariant:"v2",onChat:pi?()=>Cs(!0):oa,onControls:()=>Da(!0),cells:[{label:"Chat",onClick:oa,testId:Jt.editorBottomBar.chat,unread:mi,unreadLabel:"unread",unreadTestId:Jt.editorBottomBar.chatUnread},...Po?[{label:"Controls",onClick:()=>Da(!0),testId:Jt.editorBottomBar.controls}]:[]],disabled:wn.show})]}),ct&&e.jsx(yx,{open:ba,coverUrl:po(An),toolName:u,description:We,listed:Xn==="public",publishing:Rs,canPublish:!!C,ctaLabel:Ma==="draft"?"Publish":"Update",published:wr!=="draft",chromeVariant:"v2",publishState:Ma,justPublished:Qr,shareUrl:bi,onToggleListed:d=>Un(d?"public":"private"),listing:{name:u,description:We,tags:Bt,onNameChange:d=>v(d,"manual"),onDescriptionChange:ts,onAddTag:d=>void yi(d),onRemoveTag:d=>void _i(d)},onPublish:()=>{C&&dc()},onUnpublish:()=>{cc(),Js(!1)},onClose:()=>Js(!1)}),ct&&e.jsx(qc,{chromeVariant:"v2",size:Do,onExpand:()=>{Ta&&(ia.current=!0),Bn(xb)},open:rr,onClose:()=>{Ta&&(ia.current=!0),Sa(!1)},keyboardInset:so,isAdmin:Dr,debugMode:ao,onToggleDebug:Fs,children:e.jsx(Vr,{sendToolEditorAction:Pe,children:e.jsx(Vl,{hideHeader:!0,newDesign:!0,messagesHidden:Do==="compact",planQuestionsHost:Ea,initialPrompt:c,initialImageUrls:x,initialReferenceFiles:h,onPlanTurnActiveChange:Us,onPlanQuestionsReceived:Ur,onPlanQuestionsPendingChange:di,onPlanPendingKindChange:cl,presetBrief:y,restoredMessages:_s??void 0,restoredSessionId:zt??void 0,restoredModel:Ya??void 0,onBeforeSend:ci,onStructuredUpdate:wi,onStatusChange:ke,onGenerationComplete:Oe,autoFixing:eo,ensureToolId:Pr,getToolUuid:()=>yt.current,chatActionsRef:W,consoleErrors:No,onGeneratedMetadata:vi,isAdmin:Dr,debugMode:ao,genesisSnapshotId:fn?U??void 0:void 0,toolHasCode:!!ie||fn,onDesignBriefUpdate:T,currentBrief:me,onRevertToVersion:g,onMessagesUpdate:d=>{if(d.length>Mo.current&&Bn(Pc),Mo.current=d.length,aa.current=d,a&&d.length>0)try{localStorage.setItem(`clay-chat-${a}`,JSON.stringify(d))}catch{}}})})}),ct&&e.jsx(qc,{chromeVariant:"v2",title:"Plan",dataHooks:Jt.planSheet,size:"compact",open:Ao,onClose:()=>Cs(!1),keyboardInset:so,isAdmin:!1,debugMode:ao,onToggleDebug:Fs,children:e.jsx("div",{ref:Ia,className:"max-h-[70dvh] min-h-0 overflow-y-auto bg-[var(--product-white-00)]"})}),e.jsx(Vp,{show:ni}),e.jsx(rx,{chrome:"v2",editingKey:ee,schema:q,onClose:()=>ae(null),onSave:(d,b)=>{var m,ye,fe;const R=q.map(K=>{if(K.key!==d)return K;const Ee=Number(K.default??b.min),He=Math.min(Math.max(Ee,b.min),b.max);return{...K,min:b.min,max:b.max,default:He}});we(R);const S=Number(((m=q.find(K=>K.key===d))==null?void 0:m.default)??b.min),M=Math.min(Math.max(S,b.min),b.max);(fe=(ye=It.current)==null?void 0:ye.patchControl)==null||fe.call(ye,d,{min:b.min,max:b.max,default:M}),ae(null)}}),e.jsx(tx,{chrome:"v2",menu:z,onClose:()=>$(null),onEditRange:d=>ae(d),onRename:(d,b)=>ue({key:d,label:b}),onSendMessage:d=>{var b;return(b=W.current)==null?void 0:b.sendMessage(d)},onHide:gd,onDelete:bd,disableHideDelete:!Bs||(z==null?void 0:z.key)===Ju}),e.jsx(sx,{chrome:"v2",renameTarget:ve,schema:q,onClose:()=>ue(null),onSave:(d,b)=>{var R,S;vd(d,b),(S=(R=It.current)==null?void 0:R.patchControl)==null||S.call(R,d,{label:b}),ue(null)}}),e.jsx(hx,{deleteDialogContent:Qx,embedPreviewHtml:Yx,isDeleting:Kr,isPublishing:Rs,isRepublishing:Tn,newToolName:Gn,onCloseDeleteDialog:()=>Mn(!1),onClosePublishAsNewDialog:()=>{Is(!1),Lt("")},onClosePublishDialog:()=>Zs(!1),onCloseUnpublishDialog:()=>Qt(!1),onCloseUpdateDialog:()=>Es(!1),onDeleteTool:Xx,onPublish:yd,onRemixAsNew:wd,onSetNewToolName:Lt,onSetToolName:d=>v(d,"manual"),onSetToolDescription:_a,onSetVisibility:Un,onUnpublish:cc,onUpdate:_d,setShowDeleteDialog:Mn,setShowPublishAsNewDialog:Is,setShowPublishDialog:Zs,setShowUnpublishDialog:Qt,setShowUpdateDialog:Es,showDeleteDialog:pt,showPublishAsNewDialog:!1,showPublishDialog:ga,showUnpublishDialog:!1,showUpdateDialog:wo,showPublishSuccessDialog:!1,setShowPublishSuccessDialog:ma,toolDescription:We,toolName:u,toolSlug:Qn,visibility:Xn}),e.jsx(db,{open:cs,onOpenChange:Qt,onConfirm:()=>void cc()}),e.jsx(cb,{open:Co,onOpenChange:d=>{Is(d),d||Lt("")},toolName:u,newToolName:Gn,onSetNewToolName:Lt,onConfirm:()=>void wd()}),e.jsx(sp,{file:Wr,toolName:u,toolSlug:Qn,onClose:()=>qr(null),chromeVariant:"v2"}),e.jsx(rp,{open:Mt,autoDismissMs:3e4,toolName:u,toolSlug:Qn,coverUrl:po(An),chromeVariant:"v2",onClose:()=>Rn(!1)}),e.jsx(ix,{open:_o,onClose:()=>is(!1)})]})]})}function Cb(){const{toolId:t}=ql(),s=n.useRef(t??"__new__"),r=n.useRef(t);return t!==r.current&&(r.current===void 0&&t!==void 0||(s.current=t??"__new__"),r.current=t),e.jsx(Np,{children:e.jsx(Ru,{children:e.jsx(wb,{},s.current)})})}function jb(){return e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx("div",{className:"w-6 h-6 border-2 border-[#333] border-t-[#888] rounded-full animate-spin"})})}function D2(){const t=zf();return t===void 0?e.jsx(jb,{}):t?e.jsx(Cb,{}):e.jsx(Wg,{})}export{D2 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.