PageSourceSearch

https://snich.ai/assets/ProducerView-edbfbe16.js

js snich.ai collected 2026-10-05 15:08:11 UTC 548,529 bytes, 112 lines download raw bytes

1import{r as d,j as e,R as ht,e as Kr}from"./vendor-react-72e4a099.js";import{g as xt,S as we,e as Pe,B as R,u as Se,d as Ye,M as Cs,f as Ke,F as ke,I as Oe,i as Fn,T as Wr,a as un,E as As,C as Rn,b as mn,P as Gr}from"./Toast-43ee7788.js";import{b as Ve,T as ns,L as fl,a as Zs,P as Qr,c as Yr,K as Ga,A as Xr}from"./Display-48adcc24.js";import{S as Bs,C as yn,u as pl}from"./Controls-5a18fd37.js";import{i as Ss}from"./slotWidgets-57ef49ea.js";import{P as Aa,e as Nn,n as et,u as Jr,h as Zr,i as eo,d as ks,j as so,t as Qa,k as Mi,c as Tt,m as Li,l as jl,A as gl,o as Ls,T as Ds,q as no,r as to,v as Pa,w as vl,x as Ya,y as Dn,z as ao,E as Ea,B as bl,C as io,D as Ai,a as lo}from"./timeline-686c23c4.js";import{a as Ae,e as js,u as za,A as Xa}from"./api-d8a57490.js";import{d as Vs,h as En,g as ro,e as ot,B as yl}from"./StudioRealtime-3ad3f1c0.js";import{M as qt,E as oo,a as co}from"./minus-d93c9c9c.js";import{u as Nl,l as wl,d as uo,K as ft,C as wn,B as mo,f as ho,n as xo}from"./Studio-12de6b79.js";import{u as ts,a as qe,c as fs,q as He,p as Xe,j as _t,i as fo}from"./format-5039f022.js";import{R as ws}from"./radio-dc3b7f8c.js";import{X as ls}from"./x-b9f3d093.js";import{H as Ja,I as kl,b as po,G as Yt,M as jo,N as go,v as Ta,o as vo,C as bo,z as Pi,O as yo,R as Ei,T as zi,U as No,Q as wo}from"./ProgramGraphicsLayer-e1e0e604.js";import{c as is}from"./createLucideIcon-581cd729.js";import{C as Re}from"./check-083433f7.js";import{B as Za}from"./bell-521a1a83.js";import{C as Ks}from"./clock-e6794ea5.js";import{U as cn}from"./upload-34ad8b6a.js";import{M as Es}from"./mic-off-05523af3.js";import{V as kn}from"./video-off-a445220e.js";import{E as zs}from"./ellipsis-bbf71637.js";import{F as Xt}from"./file-text-e7c68864.js";import{P as ps}from"./plus-39793e81.js";import{F as pt}from"./film-0ba9e353.js";import{U as nn}from"./users-a990a1e8.js";import{U as Is}from"./user-plus-d862ebc6.js";import{P as Sl}from"./presentation-e2109ecf.js";import{M as Cl,a as ko,b as $l}from"./mouse-pointer-2-a64daac3.js";import{G as So}from"./globe-e09c7f1b.js";import{C as Gn}from"./chevron-down-888c3b30.js";import{E as gs}from"./eye-5711d0dd.js";import{M as Ts}from"./mic-098d6d5b.js";import{V as Sn}from"./video-a08888e9.js";import{M as Hs}from"./message-square-87bea34a.js";import{S as Un}from"./shield-check-111738a3.js";import{U as en}from"./user-round-31d3de96.js";import{U as ct}from"./user-minus-edd1ae61.js";import{C as tt}from"./clapperboard-fdb77651.js";import{P as fn}from"./play-3580deb4.js";import{P as Jt}from"./pause-2cb080c5.js";import{P as ei}from"./pencil-line-6bfa5da3.js";import{T as Zt}from"./triangle-alert-cdc85d96.js";import{C as si}from"./circle-check-63b159d4.js";import{E as Co}from"./ellipsis-vertical-09d18e39.js";import{T as Bn}from"./type-c9e8ec6d.js";import{T as hn}from"./trash-2-7a739e24.js";import{A as Xs}from"./arrow-right-eda8f931.js";import{C as jt}from"./chevron-left-39dc0897.js";import{C as xn}from"./chart-column-b727cf56.js";import{f as ni,O as ti,F as $o}from"./RoomFeaturesUi-d9f0cc70.js";import{C as Ps}from"./chevron-right-b4336544.js";import{L as Io}from"./list-checks-f8235a5c.js";import{L as Hn}from"./layers-e08031b9.js";import{I as gt}from"./image-aefc8036.js";import{P as ai}from"./palette-a7aa7952.js";import{V as Cn}from"./volume-2-a1e941cc.js";import{L as Il}from"./list-ordered-28cc4cb1.js";import{S as Vn}from"./sparkles-e0558c3e.js";import{C as vt}from"./copy-34f4069e.js";import{U as Mo,F as Ml,k as Ll,u as Lo}from"./usePollsControl-16f8b1fc.js";import{S as ii}from"./shield-b21f8aed.js";import{a as Ao}from"./LayoutEditorModal-5c2cbcf2.js";import{M as Ti}from"./move-720276b6.js";import{A as li}from"./arrow-up-955249b3.js";import{A as ri}from"./arrow-down-5480e148.js";import{L as Po}from"./lock-73755c1f.js";import{L as Al}from"./layout-grid-63073c93.js";import{S as jn}from"./square-abcd1e2a.js";import{C as Pl}from"./captions-4aebb0bb.js";import{s as El}from"./sceneTemplates-a017d524.js";import{L as Ut}from"./layout-template-dfe5c440.js";import{P as Eo}from"./pen-line-729408c9.js";import{L as zo}from"./languages-9836601a.js";import{R as zl}
1from"./refresh-cw-98362cea.js";import{c as Tl,r as Ln}from"./buildLifecycle-a44b0e05.js";import{T as To}from"./MaterialsPanels-db2600fc.js";import{S as ea}from"./search-01fb0df0.js";import{A as Ol}from"./arrow-left-6a250fbc.js";import{R as zn}from"./rotate-ccw-738260f2.js";import{M as Oo}from"./minimize-2-7f4bb98d.js";import{I as Fo}from"./image-plus-0ae423f0.js";import{M as Ro}from"./mail-c07c6c62.js";import{D as Oa}from"./download-3e69fd6b.js";import{L as Do}from"./link-2-36909ef8.js";import{C as qo}from"./calendar-plus-0f511f3c.js";import{R as _o}from"./repeat-a9c26444.js";import{C as Yn}from"./circle-alert-67975319.js";import{S as oi}from"./sliders-horizontal-41aa44a5.js";import{U as la}from"./user-2d8f405f.js";import{E as Bt}from"./external-link-63c5a0ce.js";import{T as Uo}from"./timer-dd0230bd.js";import{C as Bo}from"./check-check-9685683e.js";import{H as Fl}from"./headphones-a3105568.js";import{V as Rl}from"./volume-x-8aea9e1c.js";import{p as Ho}from"./publicApi-16230aa9.js";import{P as Dl}from"./pin-70ee9bd9.js";import{S as sa}from"./send-ef7332d3.js";import{M as ql}from"./maximize-edcb58d4.js";import{P as Vo}from"./pin-off-03798f51.js";import{s as Ko,a as Wo,C as Go,e as Oi}from"./embed-cb9596d8.js";import{C as _l}from"./crown-fdf36aa5.js";import{C as Qo}from"./chevron-up-f536cc4c.js";import{S as gn}from"./star-f57b9032.js";import{G as Ul}from"./grip-vertical-b48ba28a.js";import{S as Yo}from"./settings-2-0eb2aee0.js";import{S as Xo}from"./smartphone-d9ded3c9.js";import{C as Jo}from"./circle-119050f3.js";import"./Lobby-cd4ae718.js";import"./BackgroundModal-371a8f77.js";import"./deviceDetection-9fe14a8f.js";import"./chromaKey-9ef66bf0.js";import"./mediaPrefs-a1582108.js";/* empty css              */import"./EntryChrome-3815c94b.js";import"./file-play-96922e92.js";import"./logo-snich-dialogue-bd9a9926.js";import"./monitor-ac1ab9e6.js";import"./loader-circle-f10bdd75.js";import"./plug-1e9df63e.js";import"./pencil-c32e7d9a.js";import"./thumbs-up-f55ea202.js";import"./paperclip-3819f2af.js";import"./music-0f60f4f1.js";import"./sticky-note-012253c0.js";import"./audioQuality-b8c9f17c.js";import"./snichDenoiseRuntime-273d9ce6.js";import"./mediaSettingsStore-1783edcc.js";import"./camera-8e9c5806.js";import"./MicCheckModal-3c0b1b56.js";import"./micDiagnostics-fa65b80f.js";import"./zap-a08e50de.js";import"./WaitingRoom-fe3d8748.js";import"./EventPreview-a5c61118.js";import"./eventDuration-e09aabf0.js";import"./log-out-e38723a8.js";import"./circle-x-d5c7be80.js";import"./calendar-days-6829c81b.js";import"./index-d9998155.js";import"./guestAccess-28c96151.js";import"./roomAccess-6d61bdfc.js";import"./EndedScreen-b2678b64.js";import"./list-13d531b4.js";import"./share-2-50cd044b.js";/**
2 * @license lucide-react v0.554.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 Zo=[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M12 9v4l2 2",key:"1c63tq"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}]],ec=is("alarm-clock",Zo);/**
7 * @license lucide-react v0.554.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 sc=[["path",{d:"m15.477 12.89 1.515 8.526a.5.5 0 0 1-.81.47l-3.58-2.687a1 1 0 0 0-1.197 0l-3.586 2.686a.5.5 0 0 1-.81-.469l1.514-8.526",key:"1yiouv"}],["circle",{cx:"12",cy:"8",r:"6",key:"1vp47v"}]],Fa=is("award",sc);/**
12 * @license lucide-react v0.554.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 nc=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],ci=is("circle-stop",nc);/**
17 * @license lucide-react v0.554.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 tc=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-
215-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],Ht=is("flag",tc);/**
22 * @license lucide-react v0.554.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 ac=[["path",{d:"M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1",key:"fm4g5t"}],["path",{d:"M2 13h10",key:"pgb2dq"}],["path",{d:"m9 16 3-3-3-3",key:"6m91ic"}]],ic=is("folder-input",ac);/**
27 * @license lucide-react v0.554.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 lc=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],di=is("folder-open",lc);/**
32 * @license lucide-react v0.554.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 rc=[["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],Bl=is("folder-plus",rc);/**
37 * @license lucide-react v0.554.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 oc=[["rect",{width:"18",height:"7",x:"3",y:"3",rx:"1",key:"f1a2em"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}
41]],Hl=is("layout-panel-top",oc);/**
42 * @license lucide-react v0.554.0 - ISC
43 *
44 * This source code is licensed under the ISC license.
45 * See the LICENSE file in the root directory of this source tree.
46 */const cc=[["path",{d:"m12 15 4 4",key:"lnac28"}],["path",{d:"M2.352 10.648a1.205 1.205 0 0 0 0 1.704l2.296 2.296a1.205 1.205 0 0 0 1.704 0l6.029-6.029a1 1 0 1 1 3 3l-6.029 6.029a1.205 1.205 0 0 0 0 1.704l2.296 2.296a1.205 1.205 0 0 0 1.704 0l6.365-6.367A1 1 0 0 0 8.716 4.282z",key:"nlhkjb"}],["path",{d:"m5 8 4 4",key:"j6kj7e"}]],dc=is("magnet",cc);/**
47 * @license lucide-react v0.554.0 - ISC
48 *
49 * This source code is licensed under the ISC license.
50 * See the LICENSE file in the root directory of this source tree.
51 */const uc=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],mc=is("menu",uc);/**
52 * @license lucide-react v0.554.0 - ISC
53 *
54 * This source code is licensed under the ISC license.
55 * See the LICENSE file in the root directory of this source tree.
56 */const hc=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"m10 8-3 3 3 3",key:"fp6dz7"}],["path",{d:"M17 14v-1a2 2 0 0 0-2-2H7",key:"1tkjnz"}]],Vl=is("message-square-reply",hc);/**
57 * @license lucide-react v0.554.0 - ISC
58 *
59 * This source code is licensed under the ISC license.
60 * See the LICENSE file in the root directory of this source tree.
61 */const xc=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M7 11h10",key:"1twpyw"}],["path",{d:"M7 15h6",key:"d9of3u"}],["path",{d:"M7 7h8",key:"af5zfr"}]],fc=is("message-square-text",xc);/**
62 * @license lucide-react v0.554.0 - ISC
63 *
64 * This source code is licensed under the ISC license.
65 * See the LICENSE file in the root directory of this source tree.
66 */const pc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 15h18",key:"5xshup"}]],jc=is("panel-bottom",pc);/**
67 * @license lucide-react v0.554.0 - ISC
68 *
69 * This source code is licensed under the ISC license.
70 * See the LICENSE file in the root directory of this source tree.
71 */const gc=[["path",{d:"M13 7 8.7 2.7a2.41 2.41 0 0 0-3.4 0L2.7 5.3a2.41 2.41 0 0 0 0 3.4L7 13",key:"orapub"}],["path",{d:"m8 6 2-2",key:"115y1s"}],["path",{d:"m18 16 2-2",key:"ee94s4"}],["path",{d:"m17 11 4.3 4.3c.94.94.94 2.46 0 3.4l-2.6 2.6c-.94.94-2.46.94-3.4 0L11 17",key:"cfq27r"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],vc=is("pencil-ruler",gc);/**
72 * @license lucide-react v0.554.0 - ISC
73 *
74 * This source code is licensed under the ISC license.
75 * See the LICENSE file in the root directory of this source tree.
76 */const bc=[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13",key:"6uklza"}]],yc=is("redo-2",bc);/**
77 * @license lucide-react v0.554.0 - ISC
78 *
79 * This source code is licensed under the ISC license.
80 * See the LICENSE file in the root directory of this source tree.
81 */const Nc=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M14 15H9v-5",key:"pi4jk9"}],["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M21 3 9 15",key:"15kdhq"}]],wc=is("scaling",Nc);/**
82 * @license lucide-react v0.554.0 - ISC
83 *
84 * This source code is licensed under the ISC license.
85 * See the LICENSE file in the root directory of this source tree.
86 */const kc=[["path",{d:"M21 4v16",key:"7j8fe9"}],["path",{d:"M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z",key:"zs4d6"}]],Sc=is("skip-forward",kc);/**
87 * @license lucide-react v0.554.0 - ISC
88 *
89 * This source code is licensed under the ISC license.
90 * See the LICENSE file in the root directory of this source tree.
91 */const Cc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 21v-2a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2",key:"1m6ac2"}]],$c=is("square-user",Cc);/**
92 * @license lucide-react v0.554.0 - ISC
93 *
94 * This source code is licensed under the ISC license.
95 * See the LICENSE file in the root directory of this source tree.
96 */const Ic=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],Kl=is("tag",Ic);/**
97 * @license lucide-react v0.554.0 - ISC
98 *
99 * This source code is licensed under the ISC license.
100 * See the LICENSE file in the root directory of this source tree.
101 */const Mc=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 19H5",key:"vjpgq2"}]],ra=is("text-align-center",Mc);/**
102 * @license lucide-react v0.554.0 - ISC
103 *
104 * This source code is licensed under the ISC license.
105 * See the LICENSE file in the root directory of this source tree.
106 */const Lc=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M21 19H7",key:"4cu937"}]],Ac=is("text-align-end",Lc);/**
107 * @license lucide-react v0.554.0 - ISC
108 *
109 * This source code is licensed under the ISC license.
110 * See the LICENSE file in the root directory of this source tree.
111 */const Pc=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 19H3",key:"z6ezky"}]],Ec=is("text-align-start",Pc);function on(s,n){const t=()=>{try{const m=window.sessionStorage.getItem(s);return m===null?n:JSON.parse(m)}catch{return n}},[a,i]=d.useState(t),l=d.useRef(s);d.useEffect(()=>{l.current!==s&&(l.current=s,i(t()))},[s]);const r=d.useCallback(m=>{i(o=>{const c=typeof m=="function"?m(o):m;try{window.sessionStorage.setItem(l.current,JSON.stringify(c))}catch{}return c})},[]);return[a,r]}function ui(s){const n=s;if(!n)return!1;if(n.isContentEditable)return!0;const t=n.tagName;if(t==="TEXTAREA"||t==="SELECT")return!0;if(t==="INPUT"){const a=n.type;return!["checkbox","radio","button","range","submit","reset","color"].includes(a)}return!1}function mi(){return!!document.querySelector('.sn-overlay, .sn-popover, [role="dialog"][aria-modal="true"]')}const hi={owner:"Организатор",streamer:"Продюсер",host:"Ведущий",co_host:"Модератор",speaker:"Спикер",guest:"Гость",viewer:"Зритель",guest_viewer:"Зритель"};function Os(s){return String(s.role||"").toLowerCase()}function Rs(s){return hi[Os(s)]||"Участник"}function bt(s){return s==="viewer"||s==="guest_viewer"||s==="attendee"}function zc(s){const n=Os(s);return n==="co_host"?!0:(n==="streamer"||n==="owner")&&s.isCameraOff}function Tc(s,n){const t={live:[],preview:[],backstage:[],team:[],viewers:[]},a=new Map(n.programIds.map((l,r)=>[l,r]));
111s.participants.forEach(l=>{if(l.type!=="user"||l.isAI)return;if(a.has(l.id)){t.live.push(l);return}if(n.previewIds.has(l.id)){t.preview.push(l);return}if(l.isLocal)return;const r=Os(l);bt(r)?t.viewers.push(l):zc(l)?t.team.push(l):t.backstage.push(l)}),t.live.sort((l,r)=>(a.get(l.id)??0)-(a.get(r.id)??0));const i=(l,r)=>l.name.localeCompare(r.name,"ru");return t.backstage.sort(i),t.team.sort(i),t.viewers.sort(i),t}function Ys(s,n){return n&&s.participants.find(t=>s.stageIdOf(t)===n||t.peerId===n||t.id===n)||null}function Ot(s,n){const t=typeof s=="string"?Date.parse(s):Number(s||0);if(!t||!Number.isFinite(t))return"только что";const a=Math.floor(Math.max(0,n-t)/6e4);return a<1?"только что":a<60?`${a} мин`:`${Math.floor(a/60)} ч ${a%60} мин`}function Oc(s,n){const t=typeof s=="string"?Date.parse(s):Number(s||0),a=t&&Number.isFinite(t)?Math.max(0,Math.floor((n-t)/1e3)):0,i=Math.floor(a/60),l=a%60;return`${i}:${String(l).padStart(2,"0")}`}function Js(s){if(!s)return"";const n=s instanceof Date?s:new Date(s);return Number.isNaN(n.getTime())?"":`${String(n.getHours()).padStart(2,"0")}:${String(n.getMinutes()).padStart(2,"0")}`}function Fc(s){return String(s||"").trim().split(/\s+/)[0]||s}const Wl=["5","10","15","30"],Gl="sn-crew:call";function Rc(){try{const s=JSON.parse(window.localStorage.getItem(Gl)||"null");return{inSec:Wl.includes(String(s==null?void 0:s.inSec))?Number(s.inSec):5,auto:(s==null?void 0:s.auto)!==!1}}catch{return{inSec:5,auto:!0}}}function Dc(s){try{window.localStorage.setItem(Gl,JSON.stringify(s))}catch{}}function qc({target:s,onClose:n,onCall:t}){const[a,i]=d.useState("5"),[l,r]=d.useState(!0),[m,o]=d.useState(!1),c=(s==null?void 0:s.participant)||null;d.useEffect(()=>{if(!s)return;const f=Rc();i(String(f.inSec)),r(f.auto),o(!1)},[s]);const u=s!=null&&s.anchor&&s.anchor.isConnected?s.anchor:typeof document<"u"?document.querySelector('.sn-prod-sec[aria-label="Кулисы"]'):null,x=async()=>{if(!(!c||m)){o(!0);try{await t(c,Number(a),l)}finally{o(!1)}}};return e.jsx(xt,{open:!!s&&!!u,onClose:n,anchor:u,placement:"bottom-end",width:330,children:c&&e.jsxs("div",{className:"sn-crew-call",role:"dialog","aria-label":`Вызвать на сцену: ${c.name}`,children:[e.jsxs("div",{className:"sn-crew-call-head",children:[e.jsx("span",{className:"sn-crew-call-ico",children:e.jsx(qt,{className:"sn-i sn-i-16"})}),e.jsx("b",{children:"Вызвать на сцену"})]}),e.jsxs("div",{className:"sn-crew-call-person",children:[e.jsx(Ve,{name:c.name,src:c.avatarUrl,size:36}),e.jsxs("span",{className:"sn-crew-call-text",children:[e.jsx("span",{className:"sn-crew-call-name",children:c.name}),e.jsxs("span",{className:"sn-hint",style:{fontSize:12.5},children:[Rs(c)," · увидит отсчёт и ответит «Готов(а)» или «Нужна минута»"]})]})]}),e.jsxs("div",{className:"sn-crew-call-row",children:[e.jsx("span",{className:"sn-crew-call-label",children:"Выход через"}),e.jsx(we,{className:"sn-seg-tight",ariaLabel:"Отсчёт до выхода",value:a,onChange:i,options:Wl.map(f=>({value:f,label:`${f} с`}))})]}),e.jsxs("div",{className:"sn-crew-call-row is-switch",children:[e.jsxs("span",{className:"sn-crew-call-text",children:[e.jsx("span",{style:{fontSize:13.5,fontWeight:600},children:"Сразу в эфир после «Готов(а)»"}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:l?"В подготовленный кадр, если человек в нём, иначе — в сцену в эфире":"Вы выведете сами — кнопкой «В эфир» на карточке"})]}),e.jsx(Pe,{checked:l,onChange:r,label:"Сразу в эфир после ответа «Готов(а)»"})]}),e.jsxs("div",{className:"sn-crew-call-foot",children:[e.jsx(R,{size:"sm",variant:"text",onClick:n,children:"Отмена"}),e.jsxs(R,{size:"sm",variant:"primary",icon:e.jsx(qt,{className:"sn-i sn-i-16"}),loading:m,onClick:()=>void x(),"data-autofocus":!0,children:["Вызвать через ",a," с"]})]})]})})}const Ql=d.createContext(null),_c=Ql.Provider;function Qn(){return d.useContext(Ql)}const Uc=["pending","ready","need_minute","problem"],Bc=["speaker","host","guest"],Hc=3*6e4,Vc=10*6e4,qn=s=>String(s||"").trim().toLowerCase().replace(/ё/g,"е").replace(/\s+/g," "),kt=s=>String(s||"").trim().split(/\s+/)[0]||s,Xn=(s,n=90)=>s.length>n?`${s.slice(0,n-1).trimEnd()}…`:s;function Fi(s){const n=qn(s);
111return/проблем|не слыш|не вижу|звук|камер|сломал/.test(n)?"problem":/минут|подожд|сейчас|секунд/.test(n)?"wait":"ok"}function Ri(s,n){const t=Ys(s,n.fromPeerId),a=s.participants.filter(i=>i.type==="screen");return a.find(i=>i.ownerSocketId===n.fromPeerId)||(t?a.find(i=>i.ownerSocketId&&s.stageIdOf(t)===i.ownerSocketId):null)||a.find(i=>qn(i.headline)===qn(n.fromName))||null}function Kc(s){const{api:n,producer:t,openPanel:a,actions:i}=s,l=Vs(),r=Se(),m=n.studioSocket,o=n.joined,c=n.room.id,u=n.perms.manageStage,x=d.useRef({api:n,producer:t,actions:i,rt:l});x.current={api:n,producer:t,actions:i,rt:l};const[f,g]=d.useState([]),[h,p]=d.useState(!1),[N,k]=d.useState(0),[b,y]=d.useState({}),[w,T]=d.useState({});d.useEffect(()=>{if(!u||!c)return;let D=!1;return Ae.get(`rooms/${encodeURIComponent(c)}/team`).then(V=>{D||(g(Array.isArray(V)?V:[]),p(!0))}).catch(()=>{D||p(!0)}),()=>{D=!0}},[c,u,N]),d.useEffect(()=>{const D=window.setInterval(()=>k(V=>V+1),45e3);return()=>window.clearInterval(D)},[]);const q=n.participants.filter(D=>D.type==="user"&&!D.isLocal).map(D=>D.id).sort().join("|"),C=d.useRef(!0);d.useEffect(()=>{if(C.current){C.current=!1;return}const D=window.setTimeout(()=>k(V=>V+1),2500);return()=>window.clearTimeout(D)},[q]);const _=d.useMemo(()=>{const D=n.participants.filter(Q=>Q.type==="user"&&!Q.isAI),V=Q=>D.some(Z=>{const fe=Z.isLocal?Z.userId??n.me.userId:Z.userId;return Q.userId!==null&&Q.userId!==void 0&&fe!==null&&fe!==void 0&&String(fe)===String(Q.userId)?!0:!!qn(Q.name)&&qn(Z.name)===qn(Q.name)});return f.filter(Q=>Bc.includes(Q.role)&&!Q.isMe&&!Q.isOwner&&Q.status!=="declined"&&Q.status!=="cancelled"&&!V(Q))},[f,n.participants,n.me.userId]),K=d.useCallback(async D=>{T(V=>({...V,[D.id]:!0}));try{const V=await Ae.post(`rooms/${encodeURIComponent(c)}/team/${encodeURIComponent(D.id)}/remind`,{kind:"studio"});V!=null&&V.reminded?(y(Z=>({...Z,[D.id]:Date.now()})),r.success(`Напоминание отправлено — ${kt(D.name)} получит письмо и уведомление`)):r.error("Напоминание не отправлено — у этого человека нет почты");const Q=Array.isArray(V==null?void 0:V.members)?V.members:[];Q.length&&g(Z=>Z.map(fe=>Q.find(ve=>ve.id===fe.id)||fe))}catch(V){r.error(js(V,"Не удалось отправить напоминание")),k(Q=>Q+1)}finally{T(V=>{const Q={...V};return delete Q[D.id],Q})}},[c,r]),L=d.useCallback(D=>{const V=D.lastRemindedAt?Date.parse(D.lastRemindedAt):0;return Math.max(b[D.id]||0,Number.isFinite(V)?V:0)||null},[b]),[F,S]=d.useState({}),O=d.useRef(F);O.current=F;const[z,M]=d.useState(null),[U,$]=d.useState(null),v=d.useRef(new Set),B=d.useCallback((D,V)=>{D!=null&&D.id&&S(Q=>{const Z=Q[D.id];return{...Q,[D.id]:{...D,localDeadline:Z?Z.localDeadline:V}}})},[]),se=d.useCallback(async D=>{const{api:V,producer:Q}=x.current;if(!V.perms.manageStage)return r.error("Выводить в эфир может продюсер"),!1;if(Q.programIds.includes(D.id))return!0;$(`air:${D.id}`);try{return Q.previewIds.has(D.id)?await Q.takePreview():await Q.putOnAir(D)}finally{$(null)}},[r]),A=d.useCallback(async(D,V,Q)=>{const Z=x.current.api,fe=await En(Z.studioSocket,"studio:call",{peerId:Z.stageIdOf(D),inSec:V,auto:Q});return fe.success?(fe.call&&B(fe.call,Date.now()+V*1e3),r.success(`${D.name} видит отсчёт — выход через ${V} с`),!0):(r.error(fe.error||"Не удалось вызвать на сцену"),!1)},[r,B]),X=d.useCallback((D,V)=>{if(D.status===V)return;const{api:Q}=x.current,Z=Ys(Q,D.peerId),fe=(Z==null?void 0:Z.name)||D.name,ve=D.byPeerId===Q.me.peerId;if(D.status==="ready"){if(ve&&D.auto&&Z&&Q.perms.manageStage){v.current.add(D.id),r.success(`${fe} готов(а) — выводим в эфир`),se(Z);return}r.success(`${fe} готов(а) к выходу`,Z&&Q.perms.manageStage?{duration:12e3,action:{label:"В эфир",onClick:()=>void se(Z)}}:void 0);return}if(D.status==="need_minute"){r.show(`${fe}: нужна минута`,{duration:1e4,action:{label:"Вызвать снова",onClick:()=>{Z&&A(Z,D.inSec,D.auto)}}});return}D.status==="problem"&&r.error(`${fe}: проблема — выход откладывается`,{action:{label:"Написать",onClick:()=>{Z&&x.current.actions.messagePerson(Z)}}})},[se,A,r]);d.useEffect(()=>{if(!m||!o||!u)return;let D=!1;return En(m,"studio:calls").then(V=>{if(D||!V.success||!Array.isArray(V.calls))return;const Q=typeof V.now=="number"?V.now-Date.now():0;S(Z=>{const fe={...Z};
111return V.calls.forEach(ve=>{var Be;fe[ve.id]={...ve,localDeadline:((Be=Z[ve.id])==null?void 0:Be.localDeadline)??ve.deadline-Q}}),fe})}),()=>{D=!0}},[m,o,u]),d.useEffect(()=>{if(!m)return;const D=V=>{const Q=V==null?void 0:V.call;if(!(Q!=null&&Q.id))return;const Z=O.current[Q.id],fe=Z?Z.localDeadline:Date.now()+Math.max(0,Q.deadline-Q.at);B(Q,fe),Z&&X({...Q,localDeadline:fe},Z.status)};return m.on("studio:call-updated",D),()=>{m.off("studio:call-updated",D)}},[m,B,X]);const ce=Object.values(F).filter(D=>D.status==="pending"&&D.auto&&D.byPeerId===n.me.peerId&&!v.current.has(D.id)).reduce((D,V)=>Math.min(D,V.localDeadline),1/0),[xe,ye]=d.useState(0);d.useEffect(()=>{if(!Number.isFinite(ce))return;const D=window.setTimeout(()=>ye(V=>V+1),Math.max(0,ce-Date.now())+50);return()=>window.clearTimeout(D)},[ce]),d.useEffect(()=>{const{api:D}=x.current,V=Date.now();Object.values(O.current).forEach(Q=>{if(Q.status!=="pending"||!Q.auto||Q.byPeerId!==D.me.peerId||v.current.has(Q.id)||V<Q.localDeadline||!D.readyPeers[Q.peerId])return;const Z=Ys(D,Q.peerId);!Z||!D.perms.manageStage||(v.current.add(Q.id),r.success(`${Z.name} на месте — выводим в эфир`),se(Z))})},[xe,n.readyPeers]);const be=d.useCallback(D=>{const V=n.stageIdOf(D);let Q=null;Object.values(F).forEach(fe=>{fe.peerId!==V||!Uc.includes(fe.status)||(!Q||fe.at>Q.at)&&(Q=fe)});const Z=Q;return!Z||Date.now()-Z.updatedAt>Vc?null:Z},[F,n]),ge=d.useCallback(async D=>{$(`cancel:${D.id}`);try{const V=await En(x.current.api.studioSocket,"studio:call-cancel",{callId:D.id});if(!V.success){r.error(V.error||"Не удалось отменить вызов");return}V.call&&B(V.call,D.localDeadline),r.show(`Вызов отменён — ${kt(D.name)} остаётся за кулисами`)}finally{$(null)}},[r,B]),rs=d.useCallback(async D=>{const V=Ys(x.current.api,D.peerId);if(!V){r.error(`${D.name} уже не в студии`);return}$(`call:${V.id}`);try{await A(V,D.inSec,D.auto)}finally{$(null)}},[A,r]),Ie=d.useCallback(D=>!u||D.type!=="user"||D.isLocal||D.isAI||bt(Os(D))?!1:!t.programIds.includes(D.id),[u,t.programIds]),[De,We]=d.useState([]),W=d.useRef(De);W.current=De;const oe=d.useRef(!1),le=d.useCallback(D=>{We(V=>{const Q=V.filter(Z=>Z.id!==D.id);return Q.push(D),Q.sort((Z,fe)=>Z.at-fe.at),Q.slice(-100)})},[]),ie=d.useCallback(D=>{const V=D.questionId?x.current.rt.qna.questions.find(Z=>Z.id===D.questionId):null,Q=Xn((V==null?void 0:V.text)||D.text||"вопрос");switch(D.kind){case"leave_stage":return"просит увести за кулисы";case"join_stage":return"просит вывести на сцену";case"show_question":return D.questionId?`просит вывести на экран вопрос «${Q}»`:"просит убрать вопрос с экрана";case"answer_on_air":return`ответит в эфире на вопрос «${Xn((V==null?void 0:V.text)||"из зала")}»${D.text?` — ${D.text}`:""}`;case"show_screen":return`показывает экран${D.text&&!/^(?:window|screen|tab):\d+:\d+$/i.test(D.text)?` «${Xn(D.text,60)}»`:""} — просит вывести в эфир`;case"poll_done":return`опрос можно убирать${D.text?`: «${Xn(D.text,70)}»`:""}`;default:return"просьба продюсеру"}},[]),as=d.useCallback(D=>{var Be,Y;const{api:V,producer:Q,rt:Z}=x.current,fe=Ys(V,D.fromPeerId),ve=!!fe&&Q.programIds.includes(fe.id);switch(D.kind){case"leave_stage":return ve?"Увести за кулисы":null;case"join_stage":return fe&&!ve?"Вывести в эфир":null;case"show_question":return D.questionId?((Be=Z.qna.onAir)==null?void 0:Be.id)===D.questionId?null:"Вывести вопрос":Z.qna.onAir?"Убрать вопрос":null;case"answer_on_air":return D.questionId&&((Y=Z.qna.onAir)==null?void 0:Y.id)!==D.questionId?"Вывести вопрос":null;case"show_screen":{const Le=Ri(V,D);return Le&&!Q.programIds.includes(Le.id)?"Вывести экран":null}case"poll_done":return D.questionId?"Убрать опрос":null;default:return null}},[]),Ze=d.useCallback(async(D,V,Q=!1)=>{$(`${V}:${D.id}`);try{const Z=await En(x.current.api.studioSocket,"studio:team-request-resolve",{id:D.id,status:V});if(!Z.success){r.error(Z.error||"Не удалось ответить на просьбу");return}Z.request&&le(Z.request),Q||r.show(V==="done"?`Готово — ${kt(D.fromName)}
111 видит, что просьба выполнена`:`${kt(D.fromName)} увидит, что просьба отклонена`)}finally{$(null)}},[r,le]),cs=d.useCallback(async D=>{const{api:V,producer:Q,actions:Z}=x.current,fe=Ys(V,D.fromPeerId);$(`act:${D.id}`);try{switch(D.kind){case"leave_stage":fe&&Q.programIds.includes(fe.id)?await Q.removeFromProgram(fe):await Ze(D,"done",!0);return;case"join_stage":if(!fe){r.error(`${D.fromName} уже не в студии`);return}await se(fe);return;case"show_question":case"answer_on_air":{await Z.showQuestion(D.questionId||null)&&await Ze(D,"done",!0);return}case"show_screen":{const ve=Ri(V,D);if(!ve){r.error("Экран ещё не дошёл до студии — подождите пару секунд");return}await se(ve)&&await Ze(D,"done",!0);return}case"poll_done":{if(!D.questionId)return;await Z.hidePoll(D.questionId)&&await Ze(D,"done",!0);return}default:await Ze(D,"done")}}finally{$(ve=>ve===`act:${D.id}`?null:ve)}},[se,Ze,r]);d.useEffect(()=>{if(!m||!o||!u)return;let D=!1;return En(m,"studio:team-requests").then(V=>{oe.current=!0,!(D||!V.success||!Array.isArray(V.requests))&&V.requests.forEach(le)}),()=>{D=!0}},[m,o,u,le]),d.useEffect(()=>{if(!m)return;const D=Q=>{const Z=Q==null?void 0:Q.request;if(!(Z!=null&&Z.id))return;const fe=W.current.find(Be=>Be.id===Z.id);if(le(Z),fe||Z.status!=="pending")return;const ve=as(Z);r.show(`${Z.fromName} ${ie(Z)}`,{duration:1e4,action:ve?{label:ve,onClick:()=>void cs(Z)}:{label:"Открыть",onClick:()=>a("people")}})},V=Q=>{var Z;(Z=Q==null?void 0:Q.request)!=null&&Z.id&&le(Q.request)};return m.on("studio:team-request",D),m.on("studio:team-request-updated",V),()=>{m.off("studio:team-request",D),m.off("studio:team-request-updated",V)}},[m,le,as,ie,cs,r,a]);const Fe=d.useMemo(()=>De.filter(D=>D.status==="pending").sort((D,V)=>V.at-D.at),[De]),ne=d.useCallback(D=>{const V=n.stageIdOf(D);return Fe.find(Q=>Q.fromPeerId===V||D.peerId&&Q.fromPeerId===D.peerId)||null},[Fe,n]),je=l.cues.log,Ee=d.useCallback(D=>{const V=n.stageIdOf(D);for(let Q=je.length-1;Q>=0;Q-=1){const Z=je[Q];if(!(Z.toPeerId!==V||!Z.reply||!Z.repliedAt))return Date.now()-Z.repliedAt>Hc?null:{text:Z.reply,at:Z.repliedAt,tone:Fi(Z.reply)}}return null},[je,n]),ze=d.useRef(null);d.useEffect(()=>{const D=je.filter(V=>V.reply&&V.repliedAt);if(!ze.current){ze.current=new Set(D.map(V=>`${V.id}:${V.repliedAt}`));return}D.forEach(V=>{const Q=`${V.id}:${V.repliedAt}`;if(ze.current.has(Q))return;ze.current.add(Q);const{api:Z}=x.current,fe=V.toPeerId?Ys(Z,V.toPeerId):null,ve=(fe==null?void 0:fe.name)||V.toName||"Команда",Be=Fi(V.reply||""),Y=V.toPeerId?`${ve} — «${V.reply}»`:`Ответ на сигнал «${Xn(V.text,40)}»: «${V.reply}»`;Be==="problem"?r.error(Y,fe?{action:{label:"Написать",onClick:()=>x.current.actions.messagePerson(fe)}}:void 0):Be==="ok"?r.success(Y):r.show(Y)})},[je,r]);const os=d.useCallback((D,V)=>{M({participant:D,anchor:V})},[]);return{state:{missing:_,rosterLoaded:h,remind:K,reminding:w,remindedAt:L,callOf:be,openCall:os,cancelCall:ge,callAgain:rs,goOnAir:se,canCall:Ie,requests:Fe,requestOf:ne,describe:ie,actionLabel:as,act:cs,resolve:(D,V)=>Ze(D,V),busy:U,replyOf:Ee,openPeople:()=>a("people")},modals:e.jsx(qc,{target:z,onClose:()=>M(null),onCall:async(D,V,Q)=>{Dc({inSec:V,auto:Q}),await A(D,V,Q)&&M(null)}}),pendingRequests:Fe.length}}const st=new Set(["owner","streamer","co_host","producer","moderator","admin"]),St=/^(модератор|продюсер|режисс[её]р|организатор|админ|администратор|оператор|техник|звукорежисс[её]р|ведущий эфира|producer|moderator|admin|operator)(\s|$)/i,Yl=/(вич|вна|ична|инична|ьич)$/,vs=s=>String(s||"").trim().toLowerCase().replace(/ё/g,"е").replace(/\s+/g," "),at=s=>vs(s).split(/[^a-zа-я0-9]+/i).filter(Boolean);function Gs(s){const n=at(s).filter(a=>!/^\d+$/.test(a)),t=n.filter(a=>!(a.length>5&&Yl.test(a)));return(t.length?t:n).sort().join(" ")}function Wc(s){return at(s).filter(n=>n.length>=5&&!Yl.test(n)&&!/\d/.test(n)).map(n=>n.slice(0,n.length>=7?n.length-2:n.length-1))}function Gc(s,n){const t=new Map;s.people.forEach(h=>{const p=vs(h.name);p&&!t.has(p)&&t.set(p,h)});const a=h=>{const p=h.mediaOwnerName||(h.isLocal?s.meName:null),N=h.mediaOwnerUserId??(h.isLocal?s.meUserId:null);if(h.isLocal&&s.meIsProduction||N!=null&&s.meUserId!==null&&String(N)===String(s.meUserId)&&s.meIsProduction)return!0;
111if(N!=null){const b=s.people.find(y=>y.userId!==null&&y.userId!==void 0&&String(y.userId)===String(N));if(b)return st.has(String(b.role||"").toLowerCase())}if(!p)return!1;if(St.test(vs(p)))return!0;const k=t.get(vs(p));return!!k&&st.has(String(k.role||"").toLowerCase())},i=new Map,l=h=>{const p=String(h||"").trim().replace(/\s+/g," "),N=Gs(p);!N||St.test(vs(p))||i.has(N)||i.set(N,p)};s.knownSpeakers.forEach(l),s.people.forEach(h=>{const p=String(h.role||"").toLowerCase();!st.has(p)&&p!=="viewer"&&p!=="guest_viewer"&&l(h.name)}),n.forEach(h=>{h.mediaSpeaker?l(h.mediaSpeaker):h.mediaOwnerName&&!a(h)&&l(h.mediaOwnerName)});const r=[...i.entries()].map(([h,p])=>({key:h,name:p,stems:Wc(p)})),m=h=>{var k,b;const p=[...at(h.name),...at((k=h.presentation)==null?void 0:k.sourceFileName),...at((b=h.videoFile)==null?void 0:b.sourceFileName)];if(!p.length)return null;const N=r.filter(y=>y.stems.some(w=>p.some(T=>T.startsWith(w))));return N.length===1?{key:N[0].key,name:N[0].name,source:"filename"}:null},o=new Map,c=h=>{var N;if(o.has(h))return o.get(h)??null;let p=null;if(h.mediaSpeaker&&h.mediaSpeaker.trim()){const k=h.mediaSpeaker.trim();p={key:Gs(k),name:i.get(Gs(k))||k,source:"assigned"}}else if(h.type!=="screen"&&h.type!=="whiteboard"&&h.type!=="cobrowsing"){const k=((N=s.cabinetOwnerOf)==null?void 0:N.call(s,h))||null;if(h.mediaOwnerName&&!a(h)){const b=Gs(h.mediaOwnerName);p={key:b,name:i.get(b)||h.mediaOwnerName,source:"uploader"}}else if(k){const b=Gs(k);p={key:b,name:i.get(b)||k,source:"cabinet"}}else p=m(h)}else{const k=h.mediaOwnerName||h.headline||null;k&&!St.test(vs(k))&&(p={key:Gs(k),name:k,source:"uploader"})}return o.set(h,p),p},u=h=>{const p=h.mediaOwnerName||(h.isLocal?s.meName:null);if(!p)return null;const N=c(h);return N&&N.key===Gs(p)?null:p},x=[],f=new Set,g=h=>{const p=Gs(h);!p||f.has(p)||(f.add(p),x.push({key:p,name:h}))};return s.people.forEach(h=>{const p=String(h.role||"").toLowerCase();!st.has(p)&&p!=="viewer"&&p!=="guest_viewer"&&!St.test(vs(h.name))&&g(h.name)}),i.forEach(h=>g(h)),{speakerOf:c,addedBy:u,keyOfPerson:h=>Gs(h.name),choices:x}}function Di(s,n){const t=new Map,a=[];s.forEach(l=>{const r=n.speakerOf(l.participant);if(!r){a.push(l);return}const m=t.get(r.key);m?m.items.push(l):t.set(r.key,{key:r.key,name:r.name,items:[l]})});const i=[...t.values()];return a.length&&i.push({key:null,name:"Общие",items:a}),i}function xi(s){const n=Nl(s.room.id,s.joined),t=s.participants,a=s.perms.manageStage,i=s.me.userId,l=s.me.name;return d.useMemo(()=>{var c;const r=t.filter(u=>u.type==="user"&&!u.isAI),m=t.filter(u=>Ss(u.type)),o=(((c=n.data)==null?void 0:c.members)||[]).filter(u=>!st.has(String(u.role||"").toLowerCase()));return Gc({people:r.map(u=>({name:u.name,role:u.role,userId:u.userId??null,isMe:u.isLocal})),knownSpeakers:o.map(u=>u.name),meIsProduction:a,meUserId:i??null,meName:l||null,cabinetOwnerOf:u=>{var x;return((x=wl(n.data,u))==null?void 0:x.name)||null}},m)},[t,n.data,a,i,l])}function fi(s,n,t){if(n.status==="ready")return"ready";const a=s.readyPeers[n.peerId]||0;return(n.status==="need_minute"||n.status==="problem")&&n.repliedAt&&a>n.repliedAt?"ready":n.status==="need_minute"?"need_minute":n.status==="problem"?"problem":t<n.localDeadline?"counting":"waiting"}const Qc={speaker:"Спикер",host:"Ведущий",guest:"Гость",moderator:"Модератор",producer:"Продюсер"};function Xl(s){return Qc[s.role]||"Участник"}function Jl(s){var t,a;const n=String(s||"").trim().split(/\s+/).filter(Boolean);return((((t=n[0])==null?void 0:t[0])||"")+(((a=n[1])==null?void 0:a[0])||"")).toUpperCase()||"?"}function Zl({api:s,call:n,className:t="sn-bs-state"}){const a=ts(250),i=fi(s,n,a),l=Math.max(0,Math.ceil((n.localDeadline-a)/1e3));return i==="counting"?e.jsxs("span",{className:`${t} sn-crew-state is-call`,role:"status",title:"Вызов на сцену: человек видит отсчёт",children:["выход через ",e.jsxs("span",{className:"sn-mono",children:[l," с"]})]}):i==="waiting"?e.jsx("span",{className:`${t} sn-crew-state is-wait`,role:"status",title:"Отсчёт закончился — ждём ответа «Готов(а)» или «Нужна минута»",children:"ждём ответа"}):i==="ready"?e.jsx("span",{className:`${t} sn-crew-state is-ready`,role:"status",title:"Ответ на вызов: готов(а) к выходу",children:"готов(а) к выходу"}):i==="need_minute"?e.jsx("span",{className:`${t} sn-crew-state is-wait`,role:"status",title:"Ответ на вызов: нужна минута",children:"нужна минута"}):e.jsx("span",{className:`${t} sn-crew-state is-problem`,role:"status",title:"Ответ на вызов: проблема",children:"проблема с выходом"})}function er({api:s,crew:n,call:t,participant:a,className:i}){const l=ts(1e3),r=fi(s,t,l);return r==="ready"?e.jsx(R,{size:"sm",variant:"primary",className:i,icon:e.jsx(ws,{className:"sn-i sn-i-16"}),loading:n.busy===`air:${a.id}`,onClick:()=>void n.goOnAir(a),children:"В эфир"}):r==="need_minute"||r==="problem"?e.jsx(R,{size:"sm",variant:"quiet",className:i,icon:e.jsx(qt,{className:"sn-i sn-i-16"}),loading:n.busy===`call:${a.id}`,onClick:()=>void n.callAgain(t),title:`Вызвать ещё раз — отсчёт ${t.inSec} с`,children:"Ещё раз"}):e.jsx(R,{size:"sm",variant:"quiet",className:i,icon:e.jsx(ls,{className:"sn-i sn-i-16"}),loading:n.busy===`cancel:${t.id}`,onClick:()=>void n.cancelCall(t),title:"Отменить вызов на сцену","aria-label":`Отменить вызов: ${a.name}`,children:"Отменить"})}function sr(s,n,t){if(!s||!n||!s.canCall(n))return[];const a=s.callOf(n);return a?[{label:"Отменить вызов на сцену",icon:e.jsx(ls,{className:"sn-i sn-i-16"}),onSelect:()=>void s.cancelCall(a)}]:[{label:"Вызвать на сцену",description:"Отсчёт у человека и ответ «Готов(а)»",icon:e.jsx(qt,{className:"sn-i sn-i-16"}),onSelect:()=>s.openCall(n,t)}]}const Yc={leave_stage:"за кулисы",join_stage:"на сцену",show_question:"вопрос на экран",answer_on_air:"ответит в эфире",show_screen:"экран в эфир",poll_done:"убрать опрос"};function Xc({crew:s,participant:n}){const t=s.requestOf(n);if(t)return e.jsxs("button",{type:"button",className:"sn-crew-flag is-request",onClick:s.openPeople,title:`${t.fromName} ${s.describe(t)}`,children:[e.jsx(Ja,{className:"sn-i",style:{width:12,height:12}}),e.jsx("span",{children:t.kind==="show_question"&&!t.questionId?"убрать вопрос":Yc[t.kind]||"просьба"})]});const a=s.replyOf(n);return a?e.jsxs("span",{className:`sn-crew-flag is-reply is-${a.tone}`,title:`Ответ на сигнал в ${qe(a.at)}`,children:[e.jsx(Vl,{className:"sn-i",style:{width:12,height:12}}),e.jsxs("span",{children:["«",a.text,"»"]})]}):null}function nr({crew:s,member:n,className:t,withIcon:a=!0,size:i="sm"}){const l=ts(5e3),r=s.remindedAt(n),m=!!r&&l-r<6e4;return n.isGuest?e.jsx("span",{className:"sn-crew-guest-note",title:"Гость пришёл по ссылке для роли — почты у него нет",children:"без почты"}):e.jsx(R,{size:i,variant:"quiet",className:t,icon:a?m?e.jsx(Re,{className:"sn-i sn-i-16"}):e.jsx(Za,{className:"sn-i sn-i-16"}):void 0,loading:!!s.reminding[n.id],disabled:m,title:r?`Последнее напоминание в ${qe(r)}`:"Письмо и уведомление: «Вас ждут в студии»",onClick:()=>void s.remind(n),children:m?"Напомнили":"Напомнить"})}
111function Jc({crew:s,member:n}){const t=s.remindedAt(n);return e.jsxs("div",{className:"sn-bs sn-crew-missing","data-member":n.id,children:[e.jsx("div",{className:"sn-crew-missing-art",children:n.avatarUrl?e.jsx(Ve,{name:n.name,src:n.avatarUrl,size:40}):e.jsx("span",{className:"sn-crew-initials","aria-hidden":"true",children:Jl(n.name)})}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:1,padding:"0 2px",minWidth:0},children:[e.jsx("span",{className:"sn-bs-name",title:`${n.name} · ${Xl(n)}`,children:n.name}),e.jsx("span",{className:"sn-bs-state is-warn",title:t?`Не подключился · напомнили в ${qe(t)}`:"Ещё не вошёл в студию",children:t?e.jsxs(e.Fragment,{children:["напомнили · ",e.jsx("span",{className:"sn-mono",children:qe(t)})]}):"не подключился"})]}),e.jsx(nr,{crew:s,member:n,className:"sn-bs-btn"})]})}function tr({crew:s,member:n,size:t=28,withRole:a=!1}){const i=s.remindedAt(n);return e.jsxs("div",{className:"sn-crew-missing-row","data-member":n.id,children:[n.avatarUrl?e.jsx(Ve,{name:n.name,src:n.avatarUrl,size:t}):e.jsx("span",{className:"sn-crew-initials is-sm",style:{width:t,height:t},"aria-hidden":"true",children:Jl(n.name)}),e.jsxs("span",{className:"sn-crew-missing-text",children:[e.jsx("span",{className:"sn-crew-missing-name",children:n.name}),e.jsxs("span",{className:"sn-crew-missing-sub",title:i?`Напомнили в ${qe(i)}`:void 0,children:[a?`${Xl(n)} · `:"",i?e.jsxs(e.Fragment,{children:["напомнили ",e.jsx("span",{className:"sn-mono",children:qe(i)})]}):"ещё не подключился"]})]}),e.jsx(nr,{crew:s,member:n,withIcon:!1})]})}function Zc({crew:s}){const n=s.requests.length;return n?e.jsxs("button",{type:"button",className:"sn-crew-pill",onClick:s.openPeople,children:[e.jsx(Ja,{className:"sn-i",style:{width:14,height:14}}),"Просьбы команды · ",e.jsx("span",{className:"sn-mono",children:n})]}):null}function ed({crew:s,request:n,now:t}){const a=s.actionLabel(n),i=s.busy===`act:${n.id}`;return e.jsxs("div",{className:"sn-h-hand sn-crew-req","data-request":n.id,children:[e.jsxs("div",{className:"sn-h-hand-top",children:[e.jsx(Ve,{name:n.fromName,size:32}),e.jsxs("span",{className:"sn-h-row-text",children:[e.jsx("span",{className:"sn-h-name",children:n.fromN
111ame}),e.jsx("span",{className:"sn-h-sub",style:{whiteSpace:"normal"},children:s.describe(n)})]}),e.jsxs("span",{className:"sn-h-hand-when",children:[e.jsx(Ks,{className:"sn-i sn-i-16"})," ",Ot(n.at,t)]})]}),e.jsxs("div",{className:"sn-h-hand-acts",children:[a&&e.jsx(R,{size:"sm",variant:"quiet",className:"sn-h-small",loading:i,disabled:!!s.busy&&!i,onClick:()=>void s.act(n),children:a}),a?e.jsx(Ye,{label:"Готово — отметить просьбу выполненной",size:"sm",variant:"quiet",className:"sn-crew-req-done",title:"Готово — отметить выполненной",disabled:s.busy===`done:${n.id}`,onClick:()=>void s.resolve(n,"done"),children:e.jsx(Re,{className:"sn-i sn-i-16"})}):e.jsx(R,{size:"sm",variant:"quiet",className:"sn-h-small",icon:e.jsx(Re,{className:"sn-i sn-i-16"}),loading:s.busy===`done:${n.id}`,onClick:()=>void s.resolve(n,"done"),children:"Готово"}),e.jsx(R,{size:"sm",variant:"text",className:"sn-h-small",loading:s.busy===`declined:${n.id}`,onClick:()=>void s.resolve(n,"declined"),children:"Отклонить"})]})]})}function sd({crew:s}){const n=ts(15e3);return s.requests.length?e.jsxs("section",{className:"sn-h-sec","aria-label":"Просьбы команды",children:[e.jsx("div",{className:"sn-h-sec-head",children:e.jsxs("span",{className:"sn-eyebrow sn-h-eb-amber",children:["Просьбы команды · ",s.requests.length]})}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:s.requests.map(t=>e.jsx(ed,{crew:s,request:t,now:n},t.id))})]}):null}function nd({crew:s}){return s.missing.length?e.jsxs("section",{className:"sn-h-sec","aria-label":"Не подключились",children:[e.jsx("div",{className:"sn-h-sec-head",children:e.jsxs("span",{className:"sn-eyebrow sn-h-eb-amber",children:["Не подключились · ",s.missing.length]})}),s.missing.map(n=>e.jsx(tr,{crew:s,member:n,size:36,withRole:!0},n.id))]}):null}function na(s,n,t){if(n.programIds.includes(t.id))return"live";if(n.previewIds.has(t.id))return"preview";const a=s.stageIdOf(t);return s.readyPeers[a]?"ready":t.isCameraOff?"nocam":"idle"}const ta={live:"в эфире",preview:"в подготовке",ready:"ждёт выхода",idle:"за кулисами",nocam:"камера выключена"},td={live:"is-live",preview:"is-preview",ready:"is-ready",idle:"is-idle",nocam:"is-warn"};function $s(s){return s.participants.filter(n=>{if(n.type!=="user"||n.isAI)return!1;if(n.isLocal)return!n.isCameraOff||s.stageParticipants.some(a=>a.id===n.id);const t=String(n.role||"").toLowerCase();return t!=="viewer"&&t!=="guest_viewer"})}const ad={presentation:e.jsx(Sl,{className:"sn-i"}),video_file:e.jsx(pt,{className:"sn-i"}),screen:e.jsx(Cl,{className:"sn-i"}),whiteboard:e.jsx(uo,{className:"sn-i"}),cobrowsing:e.jsx(So,{className:"sn-i"})};function qi(s){var n,t;if(s.type==="presentation"){const a=((n=s.presentation)==null?void 0:n.slides.length)||0;return`PDF · ${a} ${a%10===1&&a%100!==11?"слайд":a%10>=2&&a%10<=4&&(a%100<10||a%100>=20)?"слайда":"слайдов"}`}if(s.type==="video_file"){const a=Math.round(((t=s.videoFile)==null?void 0:t.duration)||0);return a?`Видео · ${Math.floor(a/60)}:${String(a%60).padStart(2,"0")}`:"Видео"}return s.type==="screen"?"Демонстрация экрана":s.type==="whiteboard"?"Доска":s.type==="cobrowsing"?"Совместный браузер":""}function id(s,n){const t=s.slideControl(n.id),a=s.participants.filter(l=>l.type==="user"&&!l.isLocal);if(t==="producer")return{name:null,person:null,away:!1};if(t){const l=a.find(r=>s.stageIdOf(r)===t.peerId)||null;return{name:t.name,person:l,away:!l}}const i=n.ownerSocketId&&a.find(l=>s.stageIdOf(l)===n.ownerSocketId)||null;return i?{name:i.name,person:i,away:!1}:{name:null,person:null,away:!1}}function ld({api:s,deck:n}){const[t,a]=d.useState(null),i=id(s,n),l=c=>c.split(/\s+/)[0],r=i.name?`${l(i.name)}${i.away?" (вышел)":""}`:"продюсер",m=$s(s).filter(c=>!c.isLocal),o=[{label:"Продюсер",description:"Листаете вы и другие продюсеры",checked:!i.name,onSelect:()=>s.setSlideControl(n.id,"producer")},{type:"separator"},{type:"label",label:"Дать листать спикеру"},...m.length?m.map(c=>({label:c.name,description:"Стрелками у себя — за кулисами и Ð
111½Ð° сцене",checked:!!i.person&&i.person.id===c.id,onSelect:()=>s.setSlideControl(n.id,{peerId:s.stageIdOf(c),name:c.name})})):[{label:"В студии нет спикеров",disabled:!0}]];return e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"sn-bs-flipper","aria-label":`Кто листает «${n.name}»: ${r}`,title:"Кто листает слайды",onClick:c=>a(c.currentTarget),children:[e.jsx(nn,{className:"sn-i sn-i-16"}),e.jsxs("span",{children:["Листает: ",e.jsx("b",{children:r})]}),e.jsx(Gn,{className:"sn-i sn-i-16"})]}),e.jsx(Cs,{open:!!t,onClose:()=>a(null),anchor:t,placement:"bottom-start",width:280,items:o})]})}const rd=6;function od({api:s,producer:n,onPersonMenu:t,onMedia:a,onUpload:i,onInvite:l,onOpenMedia:r}){const m=$s(s),o=s.participants.filter(y=>Ss(y.type)),c=xi(s),u=new Map;o.forEach(y=>{var T;const w=y.type==="screen"?null:(T=c.speakerOf(y))==null?void 0:T.key;w&&u.set(w,(u.get(w)||0)+1)});const x=new Set(m.filter(y=>n.programIds.includes(y.id)||n.previewIds.has(y.id)||n.cast.includes(y.id)).map(y=>c.keyOfPerson(y))),f=o.length<=rd||!r?o:o.filter(y=>{var w;return y.type==="screen"||n.programIds.includes(y.id)||n.previewIds.has(y.id)||n.cast.includes(y.id)||typeof y.uploadProgress=="number"&&y.uploadProgress<100||x.has(((w=c.speakerOf(y))==null?void 0:w.key)||"")}),g=o.length-f.length,h=s.perms.manageStage,p=Qn(),[N,k]=on(`sn-studio:${s.room.id}:backstage-missing`,!1),b=h&&p?p.missing:[];return e.jsxs("section",{className:"sn-prod-sec","aria-label":"Кулисы",style:{flexGrow:1},children:[e.jsxs("div",{className:"sn-prod-sec-head",children:[e.jsx("span",{className:"sn-t",children:"Кулисы"}),e.jsx("span",{className:"sn-s",children:"кто и что готово к выходу — зрители их не видят"}),e.jsx("div",{className:"sn-st-grow"}),p&&e.jsx(Zc,{crew:p}),s.perms.mediaTools&&e.jsx(R,{size:"sm",variant:"text",icon:e.jsx(cn,{className:"sn-i sn-i-16"}),onClick:i,style:{height:28,fontSize:13},children:"Загрузить файл"})]}),e.jsxs("div",{className:"sn-prod-grid7",children:[m.map(y=>{var K;const w=na(s,n,y),T=w==="preview"&&n.standInIds.has(y.id),q=((K=s.audioLevels[y.id])==null?void 0:K.level)??0,C=p&&w!=="live"?p.callOf(y):null,_=C?fi(s,C,Date.now())==="ready"?" is-called-ready":" is-called":"";return e.jsxs("div",{className:`sn-bs${_}`,"data-person":y.name,children:[e.jsxs("div",{className:"sn-bs-tile",children:[e.jsx(Aa,{participant:y,mode:"live",width:260}),e.jsxs("div",{className:"sn-bs-icons",children:[y.isMuted&&e.jsx("span",{className:"is-off",title:"Микрофон выключен",children:e.jsx(Es,{size:12})}),y.isCameraOff&&e.jsx("span",{className:"is-off",title:"Камера выключена",children:e.jsx(kn,{size:12})})]}),!y.isMuted&&q>2&&e.jsx("span",{className:"sn-bs-meter",style:{transform:`scaleX(${Math.min(1,q/100)})`}}),p&&e.jsx(Xc,{crew:p,participant:y})]}),h&&e.jsx("button",{type:"button",className:"sn-ibtn sn-scene-menu",style:{right:10,top:10},"aria-label":`Действия: ${y.name}`,onClick:L=>t(y,L.currentTarget),children:e.jsx(zs,{className:"sn-i sn-i-16"})}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:1,padding:"0 2px",minWidth:0},children:[e.jsxs("span",{className:"sn-bs-name",title:y.name,children:[y.name,y.isLocal?" (вы)":""]}),C?e.jsx(Zl,{api:s,call:C}):e.jsx("span",{className:`sn-bs-state ${td[w]}`,children:T?"в подготовке · авто":ta[w]}),r&&(u.get(c.keyOfPerson(y))||0)>0&&e.jsxs("button",{type:"button",className:"sn-bs-files",onClick:()=>r(c.keyOfPerson(y)),title:`Файлы: ${y.name}`,children:[e.jsx(Xt,{className:"sn-i","aria-hidden":"true"}),"Файлы · ",u.get(c.keyOfPerson(y))]})]}),h&&p&&C?e.jsx(er,{api:s,crew:p,call:C,participant:y,className:"sn-bs-btn"}):h&&(w==="live"?e.jsx(R,{size:"sm",variant:"quiet",className:"sn-bs-btn",onClick:()=>void n.removeFromProgram(y),children:"Убрать"}):T?e.jsx(R,{size:"sm",variant:"quiet",className:"sn-bs-btn",icon:e.jsx(ps,{className:"sn-i sn-i-16"}),onClick:()=>n.addToPreview(y),title:"Сцена поставила сама, пока никого не выбрали — нажмите, чтобы выбрать",children:"В кадр"}):w==="preview"?e.jsx(R,{size:"sm",variant:"soft",className:"sn-bs-btn",icon:e.jsx(Re,{className:"sn-i sn-i-16"}),onClick:()=>n.toggleCast(y),title:"Убрать из подготовки",children:"В кадре"}):e.jsx(R,{size:"sm",variant:"quiet",className:"sn-bs-btn",icon:e.jsx(ps,{className:"sn-i sn-i-16"}),onClick:()=>n.addToPreview(y),children:"В кадр"}))]},y.id)}),N&&p&&b.map(y=>e.jsx(Jc,{crew:p,member:y},`m:${y.id}`)),f.map(y=>{var _,K;const w=n.programIds.includes(y.id),T=n.previewIds.has(y.id),q=y.type==="screen"?null:c.speakerOf(y),C=q?`${q.name} · ${qi(y)}`:qi(y);return e.jsxs("div",{className:"sn-bs",children:[e.jsxs("div",{className:"sn-bs-tile",style:{background:"#F4F3EF"},children:[y.type==="presentation"||y.type==="screen"?e.jsx(Aa,{participant:y,mode:y.type==="screen"?"live":"thumb",width:260}):e.jsx("div",{className:"sn-bs-media-art",style:{alignItems:"center",color:"var(--sn-ink-2)"},children:ad[y.type]||e.jsx(pt,{className:"sn-i"})}),typeof y.uploadProgress=="number"&&y.uploadProgress<100&&e.jsx("span",{className:"sn-bs-meter",style:{transform:`scaleX(${y.uploadProgress/100})`,background:"var(--sn-blue)"}})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:1,padding:"0 2px",minWidth:0},children:[e.jsx("span",{className:"sn-bs-name",title:y.name,children:y.name}),w?e.jsxs("span",{className:"sn-bs-state is-live",children:["в эфире",q?` · ${q.name}`:""]}):T?e.jsxs("span",{className:"sn-bs-state is-preview",children:["в подготовке",q?` · ${q.name}`:""]}):e.jsx("span",{className:"sn-bs-sub",title:C,children:C})]}),h&&y.type==="presentation"&&!!((K=(_=y.presentation)==null?void 0:_.slides)!=null&&K.length)&&e.jsx(ld,{api:s,deck:y}),e.jsx(R,{size:"sm",variant:"quiet",className:"sn-bs-btn",onClick:()=>a(y),children:w?"Управлять":"Показать"})]},y.id)}),g>0&&r&&e.jsxs("button",{type:"button",className:"sn-bs-invite",onClick:()=>r(null),children:[e.jsx("span",{children:e.jsx(di,{className:"sn-i"})}),"Все файлы · ",o.length,e.jsx("small",{children:"по спикерам — в «Медиа»"})]}),b.length>0&&e.jsxs("button",{type:"button",className:"sn-bs-invite sn-bs-missing-toggle",onClick:()=>k(!N),"aria-expanded":N,children:[e.jsx("span",{children:e.jsx(nn,{className:"sn-i"})}),N?"Свернуть":e.jsxs(e.Fragment,{children:["Не в студии · ",b.length]}),e.jsx("small",{children:N?"тех, кого нет":"не подключились или вышли"})]}),s.perms.invites&&e.jsxs("button",{type:"button",className:"sn-bs-invite",onClick:l,children:[e.jsx("span",{children:e.jsx(Is,{className:"sn-i"})}),"Позвать гостя"]})]})]})}function cd({scene:s,onClose:n,producer:t}
111){const[a,i]=d.useState(""),[l,r]=d.useState(!1);d.useEffect(()=>{s&&i(s.name)},[s]);const m=async()=>{if(!s)return;const o=a.trim();if(!o)return;r(!0);const c=await t.upsertScene({...s,name:o.slice(0,60)});r(!1),c&&n()};return e.jsx(Ke,{open:!!s,onClose:n,width:440,title:"Переименовать сцену",footer:e.jsxs(e.Fragment,{children:[e.jsx("div",{style:{flex:1}}),e.jsx(R,{variant:"quiet",onClick:n,children:"Отмена"}),e.jsx(R,{variant:"primary",onClick:m,loading:l,disabled:!a.trim(),children:"Сохранить"})]}),children:e.jsx("form",{onSubmit:o=>{o.preventDefault(),m()},children:e.jsx(ke,{label:"Название",children:e.jsx(Oe,{value:a,onChange:o=>i(o.target.value.slice(0,60)),"data-autofocus":!0})})})})}function dd({scene:s,onClose:n,producer:t}){const a=new Map;t.scenes.forEach(l=>{l.hotkey&&a.set(l.hotkey,l)});const i=async l=>{s&&(await t.setSceneHotkey(s,l),n())};return d.useEffect(()=>{if(!s)return;const l=r=>{/^[1-9]$/.test(r.key)&&(r.preventDefault(),r.stopPropagation(),i(Number(r.key)))};return window.addEventListener("keydown",l,!0),()=>window.removeEventListener("keydown",l,!0)}),e.jsxs(Ke,{open:!!s,onClose:n,width:460,title:"Назначить клавишу",subtitle:s?`Сцена «${s.name}» — нажмите цифру на клавиатуре или выберите`:void 0,children:[e.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(3, minmax(0, 1fr))",gap:8},children:Array.from({length:9},(l,r)=>r+1).map(l=>{const r=a.get(l),m=(r==null?void 0:r.id)===(s==null?void 0:s.id);return e.jsxs("button",{type:"button",className:"sn-tpl","aria-pressed":m,onClick:()=>void i(l),style:{alignItems:"center",padding:"12px 8px",gap:4},children:[e.jsx("span",{className:"sn-mono",style:{fontSize:20,fontWeight:600},children:l}),e.jsx("span",{className:"sn-hint",style:{fontSize:12,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r?m?"эта сцена":r.name:"свободна"})]},l)})}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",marginTop:14,alignItems:"center",gap:8},children:[e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Занятая клавиша перейдёт к этой сцене"}),s!=null&&s.hotkey?e.jsx(R,{size:"sm",variant:"text",onClick:()=>void i(null),children:"Снять клавишу"}):null]})]})}const ud=[{value:"streamer",label:"Продюсер",description:"Эфир, сцены, площадки и все права в комнате"},{value:"host",label:"Ведущий",description:"В эфире, видит сценарий и вопросы, просит вывести вопрос"},{value:"co_host",label:"Модератор",description:"Зал ожидания, вопросы и чат — в кадр не выходит"},{value:"speaker",label:"Спикер",description:"Выступает, видит свои заметки, вопросы и сигналы продюсера"},{value:"guest",label:"Гость",description:"Выходит на сцену по приглашению, на одно выступление"},{value:"viewer",label:"Зритель",description:"Только смотрит эфир — без доступа к студии"}],Ra={owner:"Организатор",streamer:"Продюсер",host:"Ведущий",co_host:"Модератор",speaker:"Спикер",guest:"Гость",viewer:"Зритель"};function md({api:s,participant:n,onClose:t}){const[a,i]=d.useState("speaker");if(d.useEffect(()=>{n&&i(String(n.role||"speaker"))},[n]),!n)return null;const l=new Set(s.assignableRoles(n)),r=String(n.role||""),m=n.name.split(/\s+/)[0];return e.jsx(Ke,{open:!!n,onClose:t,width:580,icon:e.jsx(Ve,{name:n.name,src:n.avatarUrl,size:44}),title:e.jsxs("span",{className:"sn-display",children:["Роль: ",n.name]}),subtitle:[n.headline,Ra[r]?`сейчас ${Ra[r].toLowerCase()}`:null].filter(Boolean).join(" · "),footer:e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"sn-hint",style:{flex:1},children:[m," получит новую роль сразу — переподключаться не нужно"]}),e.jsx(R,{variant:"quiet",onClick:t,children:"Отмена"}),e.jsx(R,{variant:"primary",disabled:a===r,onClick:()=>{s.setRole(n.id,a),t()},children:"Сохранить роль"})]}),children:e.jsx("div",{role:"radiogroup","aria-label":"Роль в комнате",style:{display:"flex",flexDirection:"column",gap:8},children:ud.map(o=>{const c=!l.has(o.value)&&o.value!==r;return e.jsxs("button",{type:"button",role:"radio","aria-checked":a===o.value,disabled:c,
111className:"sn-tpl",onClick:()=>i(o.value),style:{flexDirection:"row",alignItems:"center",padding:"12px 14px",gap:12,opacity:c?.45:1},title:c?"Эту роль вы назначить не можете":void 0,children:[e.jsxs("span",{style:{flex:1,minWidth:0},children:[e.jsxs("span",{style:{display:"block",fontWeight:600,fontSize:15},children:[o.label,o.value===r&&e.jsx("span",{className:"sn-hint",style:{fontWeight:500,marginLeft:8},children:"сейчас"})]}),e.jsx("span",{className:"sn-hint",style:{fontSize:13},children:o.description})]}),e.jsx("span",{className:"sn-radio","aria-hidden":"true","data-checked":a===o.value?"true":void 0})]},o.value)})})})}function hd({api:s,producer:n,target:t,onClose:a,onRole:i,onCue:l,onLowerThirds:r,onMessage:m,onKick:o,onFiles:c}){const u=(t==null?void 0:t.participant)||null,x=u?na(s,n,u):"idle",f=u?Ra[String(u.role||"")]||"Участник":"",g=Qn(),h=xi(s),p=u?h.keyOfPerson(u):"",N=u?s.participants.filter(k=>{var b;return Ss(k.type)&&k.type!=="screen"&&((b=h.speakerOf(k))==null?void 0:b.key)===p}).length:0;return e.jsx(Cs,{open:!!t,onClose:a,anchor:(t==null?void 0:t.anchor)||null,placement:"bottom-start",width:290,header:u?e.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center",padding:"8px 10px 12px",borderBottom:"1px solid var(--sn-line)",marginBottom:4},children:[e.jsx(Ve,{name:u.name,src:u.avatarUrl,size:40}),e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:{fontWeight:600,fontSize:14,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:u.name}),e.jsxs("div",{className:"sn-hint",style:{fontSize:12.5},children:[f," · ",ta[x]]})]})]}):null,items:u?[x==="live"?{label:"Убрать из эфира",icon:e.jsx(gs,{className:"sn-i sn-i-16"}),onSelect:()=>void n.removeFromProgram(u)}:{label:x==="preview"?"Убрать из подготовки":"В кадр (в подготовку)",icon:e.jsx(gs,{className:"sn-i sn-i-16"}),onSelect:()=>x==="preview"?n.toggleCast(u):n.addToPreview(u)},...x!=="live"?[{label:"Сразу в эфир",icon:e.jsx(ws,{className:"sn-i sn-i-16"}),onSelect:()=>void n.putOnAir(u)}]:[],...c&&N>0?[{label:`Файлы спикера · ${N}`,description:"презентации и ролики в «Медиа»",icon:e.jsx(Xt,{className:"sn-i sn-i-16"}),onSelect:()=>c(p)}]:[],...sr(g,u,(t==null?void 0:t.anchor)||null),u.isMuted?{label:"Попросить включить микрофон",icon:e.jsx(Ts,{className:"sn-i sn-i-16"}),onSelect:()=>s.requestUnmute(u.id),disabled:u.isLocal}:{label:"Выключить микрофон",icon:e.jsx(Es,{className:"sn-i sn-i-16"}),onSelect:()=>u.isLocal?s.toggleMic():s.forceMute(u.id)},u.isLocal?{label:u.isCameraOff?"Включить камеру":"Выключить камеру",icon:u.isCameraOff?e.jsx(Sn,{className:"sn-i sn-i-16"}):e.jsx(kn,{className:"sn-i sn-i-16"}),onSelect:()=>s.toggleCamera()}:{label:"Выключить камеру",icon:e.jsx(kn,{className:"sn-i sn-i-16"}),onSelect:()=>s.forceCameraOff(u.id),disabled:u.isCameraOff},{type:"separator"},{label:"Написать лично",icon:e.jsx(Hs,{className:"sn-i sn-i-16"}),onSelect:()=>m(u),disabled:u.isLocal},{label:"Сигнал «Осталось 5 минут»",icon:e.jsx(Za,{className:"sn-i sn-i-16"}),onSelect:()=>l(u),disabled:u.isLocal},{label:"Изменить роль",icon:e.jsx(Un,{className:"sn-i sn-i-16"}),onSelect:()=>i(u),disabled:u.isLocal},{label:"Плашка с именем",icon:e.jsx(Kl,{className:"sn-i sn-i-16"}),onSelect:()=>r(u)},{type:"separator"},{label:"Отправить в зрители",icon:e.jsx(en,{className:"sn-i sn-i-16"}),onSelect:()=>s.setRole(u.id,"viewer"),disabled:u.isLocal||!s.assignableRoles(u).includes("viewer")},{label:"Удалить из комнаты",icon:e.jsx(ct,{className:"sn-i sn-i-16"}),danger:!0,onSelect:()=>o(u),disabled:u.isLocal}]:[]})}
111function xd({api:s,anchor:n,onClose:t}){const a=s.recording;return e.jsx(xt,{open:!!n,onClose:t,anchor:n,placement:"bottom-end",width:332,children:e.jsxs("div",{style:{padding:"10px 12px 12px",display:"flex",flexDirection:"column",gap:12},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[e.jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:a.active?"var(--sn-red)":"var(--sn-ink-3)",animation:a.active&&!a.paused?"sn-pulse 1.6s ease-in-out infinite":void 0}}),e.jsxs("div",{style:{flex:1},children:[e.jsx("div",{style:{fontWeight:600,fontSize:15},children:a.active?a.paused?"Запись на паузе":"Идёт запись":"Запись выключена"}),a.active&&e.jsx("div",{className:"sn-hint sn-mono",children:fs(a.elapsedSec,!0)})]}),e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":"Закрыть",onClick:t,children:e.jsx(ls,{className:"sn-i sn-i-16"})})]}),e.jsx("span",{className:"sn-eyebrow",children:"Что записываем"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,fontSize:13.5},children:[e.jsxs("span",{style:{display:"flex",gap:10,alignItems:"center"},children:[e.jsx(tt,{className:"sn-i sn-i-16"})," ",e.jsxs("span",{children:[e.jsx("b",{children:"Горизонтальная 16:9"}),e.jsx("br",{}),e.jsx("span",{className:"sn-hint",children:"1080p · как видят зрители"})]})]}),s.recordingVertical&&e.jsxs("span",{style:{display:"flex",gap:10,alignItems:"center"},children:[e.jsx(tt,{className:"sn-i sn-i-16",style:{transform:"rotate(90deg)"}})," ",e.jsxs("span",{children:[e.jsx("b",{children:"Вертикальная 9:16"}),e.jsx("br",{}),e.jsx("span",{className:"sn-hint",children:"для VK Клипов и соцсетей"})]})]}),s.recordingTracks&&e.jsxs("span",{style:{display:"flex",gap:10,alignItems:"center"},children:[e.jsx(tt,{className:"sn-i sn-i-16"})," ",e.jsxs("span",{children:[e.jsx("b",{children:"Отдельные дорожки спикеров"}),e.jsx("br",{}),e.jsx("span",{className:"sn-hint",children:"видео и звук каждого — для монтажа"})]})]})]}),e.jsx("div",{style:{display:"flex",gap:8},children:a.active?e.jsxs(e.Fragment,{children:[s.pauseRecording&&e.jsx(R,{variant:"quiet",icon:a.paused?e.jsx(fn,{className:"sn-i sn-i-16"}):e.jsx(Jt,{className:"sn-i sn-i-16"}),onClick:()=>{var i;return(i=s.pauseRecording)==null?void 0:i.call(s,!a.paused)},children:a.paused?"Продолжить":"Пауза"}),e.jsx(R,{variant:"quiet",icon:e.jsx(ci,{className:"sn-i sn-i-16"}),onClick:()=>{s.stopRecording(),t()},style:{flex:1},children:"Остановить запись"})]}):e.jsx(R,{variant:"live",block:!0,icon:e.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:"#fff"}}),onClick:()=>{s.startRecording(),t()},children:"Начать запись"})}),e.jsxs("span",{className:"sn-hint",style:{fontSize:12.5},children:["Запись попадёт в ",e.jsx("a",{href:"/recordings",target:"_blank",rel:"noreferrer",children:"«Записи и итоги»"})]})]})})}function fd({open:s,onClose:n,api:t,producer:a,finalScene:i}
111){const l=ts(1e3),[r,m]=d.useState(!0),[o,c]=d.useState(!1),[u,x]=d.useState(null);d.useEffect(()=>{s&&(m(!!i),c(!1),x(null))},[s,i]);const f=t.live,g=f.isLive&&f.startedAt?Math.floor((l-f.startedAt)/1e3):0,h=f.destinations.filter(N=>N.status==="live"),p=async()=>{c(!0);try{if(r&&i&&i.id!==t.program.sourceSceneId){await a.takeScene(i);for(let N=10;N>0;N--)x(N),await new Promise(k=>window.setTimeout(k,1e3))}await t.endForAll()}finally{c(!1),x(null)}};return e.jsx(Ke,{open:s,onClose:()=>o?void 0:n(),width:580,title:e.jsx("span",{className:"sn-display",children:"Завершить эфир?"}),subtitle:f.isLive?e.jsxs(e.Fragment,{children:["Идёт ",e.jsx("span",{className:"sn-mono",children:fs(g,!0)}),t.viewerCount!==null?e.jsxs(e.Fragment,{children:[" · смотрят ",e.jsx("span",{className:"sn-mono",children:He(t.viewerCount)})]}):null]}):"Эфир ещё не начинался — комната закроется для всех",footer:e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"quiet",size:"lg",onClick:n,disabled:o,style:{flex:1},children:"Продолжить эфир"}),e.jsx(R,{variant:"live",size:"lg",onClick:p,loading:o,style:{flex:1},children:u!==null?`Финал… ${u}`:"Завершить эфир"})]}),children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:18},children:[e.jsxs("section",{style:{display:"flex",flexDirection:"column",gap:10},children:[e.jsx("span",{className:"sn-eyebrow",children:"Что произойдёт"}),e.jsxs("ul",{style:{margin:0,padding:0,listStyle:"none",display:"flex",flexDirection:"column",gap:10,fontSize:14},children:[e.jsxs("li",{children:[e.jsx("b",{children:h.length?`Эфир остановится на ${h.length} ${h.length===1?"площадке":"площадках"}`:"Трансляция на странице остановится"}),h.length?e.jsx("div",{className:"sn-hint",children:h.map(N=>N.name).join(", ")}):null]}),e.jsxs("li",{children:[e.jsx("b",{children:t.recording.active?"Запись сохранится":"Запись не велась"}),t.recording.active&&e.jsx("div",{className:"sn-hint",children:"и попадёт в «Записи и итоги»"})]}),e.jsxs("li",{children:[e.jsx("b",{children:"Все участники увидят экран завершения"}),e.jsx("div",{className:"sn-hint",children:"Студия закроется, новые подключения будут недоступны"})]})]})]}),i&&f.isLive&&e.jsx("section",{"aria-label":"Параметры завершения",style:{display:"flex",flexDirection:"column",gap:12},children:e.jsxs("div",{className:"sn-ovl-row",style:{minHeight:0},children:[e.jsxs("span",{className:"sn-ovl-text",children:[e.jsxs("span",{className:"sn-t",children:["Показать «",i.name,"» 10 секунд перед завершением"]}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Потом трансляция остановится сама"})]}),e.jsx(Pe,{checked:r,onChange:m,label:"Показать финал"})]})})]})})}function ar(s){return po(s.banners,s.activeBannerId,s.activeTickerId)}function pi(s,n){return{...s.brand,showNames:n.prefs.names,showHeadlines:n.prefs.names,showLogo:n.prefs.logo}}function yt(s,n){const t=s.activeBannerId?s.banners.find(i=>i.id===s.activeBannerId):null;if(t!=null&&t.text)return{text:t.text,kind:"banner",color:t.color||null,position:t.position||"bottom"};const a=n.wantedTicker;return a?{text:a.text,kind:"ticker",color:a.color||null,position:a.position||"bottom"}:ar(s)}function pd(s,n,t){const a=n.compiledPreview,[i,l]=d.useState(null),r=x=>Ss(x.type)?"media":"person",m=ht.useMemo(()=>{var f;const x=[];return a==null||a.slots.forEach(g=>{g.kind==="participant"&&x.push(g.participant)}
111),(f=a==null?void 0:a.grid)==null||f.participants.forEach(g=>x.push(g)),x},[a]),o=i&&m.find(x=>x.id===i)?r(m.find(x=>x.id===i)):null;if(d.useEffect(()=>{i&&!m.some(x=>x.id===i)&&l(null)},[i,m]),d.useEffect(()=>{if(!i)return;const x=f=>{f.key==="Escape"&&l(null)};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[i]),!s.perms.manageStage||!a)return{from:null,cancel:()=>l(null),overlay:void 0};const c=(x,f)=>{n.swapInPreview(x,f),l(null)};return{from:i,cancel:()=>l(null),overlay:x=>{const f=r(x),g=m.filter(b=>r(b)===f).length>=2,h=f==="person"&&!!t;if(!g&&!h)return null;const p=i===x.id,N=!!i&&!p&&o===f,k=x.name||"участник";return e.jsx("div",{className:`sn-pv-tile${p?" is-picked":""}${N?" is-target":""}`,onClick:N?()=>c(i,x.id):void 0,"data-testid":"pv-tile","data-person":k,children:e.jsxs("div",{className:"sn-tile-tools",children:[g&&e.jsx("button",{type:"button",className:`sn-tile-tool${p?" is-active":""}`,"aria-pressed":p,"aria-label":p?`Отменить: ${k}`:N?`Поменять местами с «${k}»`:`Поменять местами: ${k}`,title:p?"Отменить":N?"Поменять местами":"Поменять местами с другим",onClick:b=>{b.stopPropagation(),p?l(null):N?c(i,x.id):l(x.id)},children:e.jsx(kl,{className:"sn-i"})}),h&&e.jsx("button",{type:"button",className:"sn-tile-tool","aria-label":`Ещё: ${k}`,title:"Ещё",onClick:b=>{b.stopPropagation(),l(null),t==null||t(x,b.currentTarget)},children:e.jsx(Co,{className:"sn-i"})})]})})}}}function _i({api:s,producer:n,onEdit:t,onPersonMenu:a}){const i=n.compiledPreview,l=s.aspect==="9:16",r=pd(s,n,a);return e.jsxs("section",{className:"sn-prod-mon","aria-label":"Подготовка",children:[e.jsxs("div",{className:"sn-prod-mon-head",children:[e.jsx("span",{className:"sn-kicker",children:"ПОДГОТОВКА"}),e.jsx("span",{className:"sn-name",children:(i==null?void 0:i.scene.name)||"Сцена не выбрана"}),e.jsx("span",{className:"sn-note",children:"видите только вы"}),e.jsx("div",{className:"sn-st-grow"}),i&&e.jsx(R,{size:"sm",variant:"text",icon:e.jsx(ei,{className:"sn-i sn-i-16"}),onClick:t,style:{height:26},children:"Изменить"})]}),e.jsxs("div",{className:`sn-prod-screen is-preview${l?" is-vertical":""}`,children:[l&&e.jsx("span",{className:"sn-prod-safe","aria-hidden":"true"}),i?e.jsx(Nn,{compiled:i,brand:pi(s,n),bar:yt(s,n),vertical:l,className:"sn-prod-screen-fill",participantOverlay:r.overlay}):e.jsxs("div",{className:"sn-prod-empty",children:[e.jsx("b",{children:"Нет сцены в подготовке"}),e.jsx("span",{children:"Выберите сцену внизу — клик по карточке"})]}),r.from&&e.jsxs("div",{className:"sn-prod-swaphint",role:"status",children:[e.jsx(kl,{className:"sn-i sn-i-16",style:{flex:"none"}}),e.jsx("span",{children:"Выберите, с кем поменять местами"}),e.jsx("button",{type:"button",onClick:r.cancel,children:"Отмена"})]}),i&&i.warnings.length>0&&e.jsxs("div",{className:"sn-prod-warn",role:"status",children:[e.jsx(Zt,{className:"sn-i sn-i-16",style:{flex:"none"}}),e.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i.warnings[0]})]})]})]})}function jd({api:s,onFixFrame:n,canFix:t,fixNote:a=null,verticalLive:i}){var u,x,f;const l=s.live.isLive,r=!!((u=s.verticalLive)!=null&&u.busy)||((x=s.verticalLive)==null?void 0:x.state)==="preparing"||((f=s.verticalLive)==null?void 0:f.state)==="reconnecting",m=s.programFormat==="both"||s.programFormat==="9:16"||l&&!!(i!=null&&i.checked),o=s.recording.active?!!s.recordingVerticalActive:!!s.recordingVertical,c=r?"Подключаем вертикальный эфир…":m?o?"Вертикаль идёт в эфир и в запись":"Вертикаль идёт в эфир":!l&&(i!=null&&i.checked)?o?"Вертикаль пойдёт в эфир с его началом и в запись":"Вертикаль пойдёт в эфир с его началом":o?"Сейчас вертикаль идёт только в запись":i?"Сейчас вертикаль не идёт ни в эфир, ни в запись":"Сейчас вертикаль не идёт ни в эфир, ни в запись — включите «Вертикальная 9:16» в меню записи";return e.jsxs("section",{className:"sn-prod-format","aria-label":"Формат",children:[e.jsxs("div",{className:"sn-prod-format-head",children:[e.jsx("span",{className:"sn-eyebrow",children:"Формат"}),e.jsx(we,{size:"sm",ariaLabel:"Формат",value:s.aspect,onChange:s.setAspect,options:[{value:"16:9",label:"16:9"},{value:"9:16",label:"9:16"}]})]}),e.jsx("h3",{children:"Вертикальная версия"}),e.jsx("p",{children:"Вертикальная версия для Shorts, Клипов и Reels собирается автоматически из той же сцены — поправьте кадр, если нужно."}),e.jsxs("div",{className:"sn-prod-format-safe",children:[e.jsx("span",{className:"sn-prod-safe-ico","aria-hidden":"true"}),e.jsx("span",{children:"Безопасная зона: за пунктиром площадки рисуют свои кнопки и подписи"})]}),e.jsx(R,{variant:"quiet",icon:e.jsx(Hl,{className:"sn-i sn-i-16"}),onClick:n,disabled:!t,style:{alignSelf:"flex-start"},children:"Поправить кадр"}),a&&e.jsx("span",{className:"sn-hint",style:{fontSize:12.5,marginTop:-4},children:a}),i?e.jsx("div",{className:"sn-prod-format-foot",children:e.jsx(Fn,{title:i.title,de
111scription:e.jsx("span",{role:"status",children:i.note||c}),checked:i.checked,onChange:i.onChange,disabled:i.disabled})}):e.jsx("div",{className:"sn-prod-format-foot",role:"status",children:c})]})}function gd(s,n){return s==="both"?"в эфире 16:9 и 9:16 · 30 к/с":s==="9:16"?n?"1080×1920 · 30 к/с":"в эфире 9:16 · 1080×1920":s==="16:9"?n?"вид 9:16 · в эфире 16:9":"1080p · 30 к/с":`${n?"1080×1920":"1080p"} · 30 к/с`}function oa({api:s,producer:n,onPersonMenu:t}){const a=s.live.isLive,i=s.aspect==="9:16",[l,r]=d.useState(!1),m=d.useRef(s.program.revision);return d.useEffect(()=>{if(s.program.revision===m.current||(m.current=s.program.revision,n.transition!=="fade"))return;r(!0);const o=window.setTimeout(()=>r(!1),520);return()=>window.clearTimeout(o)},[s.program.revision,n.transition]),e.jsxs("section",{className:"sn-prod-mon","aria-label":"Эфир",children:[e.jsxs("div",{className:"sn-prod-mon-head",children:[a?e.jsx(ns,{tone:"live",style:{height:22,fontSize:11},children:"ЭФИР"}):e.jsx(ns,{tone:"gray",style:{height:22,fontSize:11},children:"ЭФИР НЕ ИДЁТ"}),e.jsx("span",{className:"sn-name",children:s.program.name||"Пусто"}),e.jsx("span",{className:"sn-note",children:a?"видят зрители":"появится первой"}),e.jsx("div",{className:"sn-st-grow"}),e.jsx("span",{className:"sn-meta",children:gd(s.programFormat||null,i)})]}),e.jsx("div",{className:`sn-prod-screen${a?" is-program":""}${i?" is-vertical":""}`,style:a?void 0:{outline:"2px solid #2C3036"},children:e.jsx("div",{className:`sn-prod-stagehost${l?" sn-program-dip":""}`,children:s.renderProgramStage({interactive:!1,onTileMenu:t})})})]})}function vd({notice:s,onUndo:n,onClose:t}){return d.useEffect(()=>{const a=window.setTimeout(t,9e3);return()=>window.clearTimeout(a)},[s.id,t]),e.jsxs("div",{role:"status",style:{position:"absolute",left:24,top:16,zIndex:50,width:400,maxWidth:"calc(100% - 48px)",display:"flex",gap:12,padding:"14px 16px",borderRadius:14,background:"var(--sn-surface)",boxShadow:"var(--sn-shadow-pop)",animation:"sn-pop .18s ease-out"},children:[e.jsx(si,{className:"sn-i",style:{color:"var(--sn-green)",flex:"none",marginTop:1}}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0,flex:1},children:[e.jsxs("span",{style:{fontSize:14,fontWeight:600},children:["Сцена «",s.name,"» в эфире"]}),s.detail&&e.jsx("span",{style:{fontSize:13,color:"var(--sn-ink-3)"},children:s.detail}),n&&e.jsx("button",{type:"button",onClick:()=>{n(),t()},style:{alignSelf:"flex-start",background:"none",border:0,padding:0,color:"var(--sn-blue)",fontSize:13,fontWeight:600,cursor:"pointer"},children:"Вернуть предыдущую"})]}),e.jsx("button",{type:"button","aria-label":"Закрыть",onClick:t,style:{background:"none",border:0,padding:2,color:"var(--sn-ink-3)",cursor:"pointer",alignSelf:"flex-start"},children:e.jsx(ls,{className:"sn-i sn-i-16"})})]})}const Ct=80;function bd({open:s,onClose:n,api:t,producer:a,initial:i,kind:l,onShown:r}){const m=t.brand.color||"#0A72C6",[o,c]=d.useState(""),[u,x]=d.useState(""),[f,g]=d.useState("banner"),[h,p]=d.useState(null),[N,k]=d.useState("bottom"),[b,y]=d.useState("none"),[w,T]=d.useState(null),[q,C]=d.useState(null);d.useEffect(()=>{s&&(c((i==null?void 0:i.text)||""),x((i==null?void 0:i.sub)||""),g((i==null?void 0:i.kind)||l),p((i==null?void 0:i.color)||null),k((i==null?void 0:i.position)==="top"?"top":"bottom"),y((i==null?void 0:i.durationSec)===30?"30":(i==null?void 0:i.durationSec)===60?"60":"none"),C(null),T(null))},[s,i,l]);const _=[{value:null,label:"цвет бренда",swatch:m},{value:"#141619",label:"чёрный",swatch:"#141619"},{value:"#D52F3A",label:"красный",swatch:"#D52F3A"},{value:"#FFFFFF",label:"белый",swatch:"#FFFFFF"}],K=_.find(B=>B.value===h)||_[0],L=d.useMemo(()=>({id:(i==null?void 0:i.id)||et(),text:o.trim(),sub:u.trim(),kind:f,color:h,position:N,durationSec:b==="none"?null:Number(b)}),[i==null?void 0:i.id,o,u,f,h,N,b]),F=a.programScene||a.previewScene,S=d.useMemo(()=>F?a.compileFor(F):null,[F,a]),O=ar(t),z=()=>L.text?L.text.length>Ct?(C(`Не длиннее ${Ct} символов — зрители не успеют прочитать`),!1):!0:(C("Напишите текст баннера"),!1),M=async()=>{const se=a.banners.some(A=>A.id===L.id)?a.banners.map(A=>A.id===L.id?L:A):[...a.banners,L];return a.saveBanners(se)},U=async()=>
111{if(!z())return;T("save");const B=await M();B&&(t.activeBannerId===L.id||t.activeTickerId===L.id)&&await t.ensureBanner(L).catch(()=>{}),T(null),B&&n()},$=async()=>{if(!z())return;if(T("show"),await M())try{L.kind==="ticker"?await a.showTicker(L):await t.showBanner(L),r==null||r(L),n()}catch(se){C((se==null?void 0:se.message)||"Не удалось показать в эфире")}T(null)},v=async()=>{if(!i)return;T("delete"),t.activeBannerId===i.id&&t.hideBanner("banner"),(t.activeTickerId===i.id||a.prefs.tickerId===i.id)&&a.hideTicker();const B=await a.saveBanners(a.banners.filter(se=>se.id!==i.id));T(null),B&&n()};return e.jsx(Ke,{open:s,onClose:n,width:940,icon:e.jsx(Bn,{className:"sn-i"}),title:i?"Баннер":f==="ticker"?"Бегущая строка":"Баннер",subtitle:"Текст поверх эфира: акции, ссылки, объявления",footer:e.jsxs(e.Fragment,{children:[i&&e.jsx(R,{variant:"text",icon:e.jsx(hn,{className:"sn-i sn-i-16"}),onClick:v,loading:w==="delete",style:{color:"var(--sn-red-ink)"},children:"Удалить"}),e.jsx("div",{style:{flex:1}}),e.jsx(R,{variant:"quiet",onClick:U,loading:w==="save",disabled:!!w,children:"Сохранить в список"}),t.perms.manageStage&&e.jsx(R,{variant:"primary",icon:e.jsx(ws,{className:"sn-i sn-i-16"}),onClick:$,loading:w==="show",disabled:!!w,children:"Показать в эфире"})]}),children:e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 336px) minmax(0, 1fr)",gap:28},className:"sn-banner-grid",children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx(ke,{label:"Текст",aside:e.jsxs("span",{className:"sn-mono",children:[o.length," / ",Ct]}),error:q,children:e.jsx(Wr,{value:o,onChange:B=>{c(B.target.value.slice(0,Ct+20)),C(null)},rows:2,placeholder:"Скидка 20% для участников эфира — промокод LAUNCH3","data-autofocus":!0})}),e.jsx(ke,{label:"Подпись в списке",hint:"Видите только вы — чтобы не перепутать баннеры",children:e.jsx("input",{className:"sn-input",value:u,onChange:B=>x(B.target.value.slice(0,120)),placeholder:"до пятницы · промокод LAUNCH3"})}),e.jsx(ke,{label:"Тип",children:e.jsx(we,{value:f,onChange:g,options:[{value:"banner",label:"Плашка"},{value:"ticker",label:"Бегущая строка"}]})}),e.jsx(ke,{label:"Цвет",children:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[_.map(B=>e.jsx("button",{type:"button",className:"sn-sed-color","aria-pressed":B.value===h,"aria-label":B.label,title:B.label,onClick:()=>p(B.value),style:{width:40,height:40,background:B.swatch}},B.label)),e.jsx("span",{className:"sn-hint",children:K.label})]})}),e.jsx(ke,{label:"Позиция",children:e.jsx(we,{value:N,onChange:k,options:[{value:"bottom",label:"Снизу"},{value:"top",label:"Сверху"}]})}),e.jsx(ke,{label:"Показывать",children:e.jsx(we,{value:b,onChange:y,options:[{value:"none",label:"Пока не скрою"},{value:"30",label:"30 сек"},{value:"60",label:"1 мин"}]})})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12,minWidth:0},children:[e.jsxs("div",{style:{fontSize:13,fontWeight:600},children:["Так увидят зрители ",e.jsxs("span",{className:"sn-hint",style:{fontWeight:400},children:["· поверх сцены «",(F==null?void 0:F.name)||"Эфир","»"]})]}),e.jsx("div",{style:{borderRadius:14,overflow:"hidden",padding:12,background:"#15171A"},children:e.jsx(Nn,{compiled:S,brand:t.brand,bar:L.text?{text:L.text,kind:L.kind,color:L.color,position:L.position}:O,style:{borderRadius:8}})}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"12px 14px",borderRadius:12,background:"var(--sn-surface-2)",border:"1px solid var(--sn-line)",fontSize:13,color:"var(--sn-ink-2)"},children:[O&&e.jsxs("span",{style:{display:"flex",gap:8},children:[e.jsx(un,{className:"sn-i sn-i-16",style:{flex:"none",marginTop:1}}),"Заменит строку «",O.text.length>40?`${O.text.slice(0,39)}…`:O.text,"» — вернуть её можно в «Графике»."]}),e.jsxs("span",{style:{display:"flex",gap:8,alignItems:"center"},children:[e.jsx(ft,{className:"sn-i sn-i-16",style:{flex:"none"}}),e.jsx("span",{className:"sn-kbd",children:"B"})," — показать или скрыть последний баннер"]})]})]})]})})}const yd=(s,n)=>s.length===n.length&&s.every((t,a)=>t===n[a]),Nd=[];
111function wd(s){if(s.template==="auto")return gl;const n=s.slots.filter((a,i)=>a.kind!=="question"&&a.kind!=="media"&&Ls(s,i)==="camera").length,t=(s.elements||[]).find(a=>a.kind==="grid"&&!a.hidden);return n+(t?t.count&&t.count>1?t.count:9:0)}const Ui=s=>typeof s.uploadProgress=="number"&&s.uploadProgress<100,Tn=60,$t=20;function kd(s,n){var Ne,es;const t=Se(),a=s.room.id,i=Jr({socket:s.studioSocket,roomId:a,enabled:s.perms.seeBackstage}),l=d.useMemo(()=>{var E;return((E=i.config)==null?void 0:E.scenes)??[]},[i.config]),r=d.useMemo(()=>{var E;return((E=i.config)==null?void 0:E.banners)??[]},[i.config]),[m,o]=on(`sn-studio:${a}:preview`,null),c=d.useCallback(E=>{if(E.type!=="user")return`id:${E.id}`;const H=s.personKeyOf(E);return s.participants.some(ee=>ee.id!==E.id&&ee.type==="user"&&s.personKeyOf(ee)===H)?`c:${s.stageIdOf(E)}|${H}`:H},[s.personKeyOf,s.stageIdOf,s.participants]),u=d.useCallback(E=>{var J;if(E.startsWith("id:")){const ee=E.slice(3);return s.participants.some(de=>de.id===ee)?ee:null}let H=E;if(E.startsWith("c:")){const ee=E.indexOf("|"),de=ee>0?E.slice(2,ee):E.slice(2),Ce=s.participants.find(_e=>_e.type==="user"&&s.stageIdOf(_e)===de);if(Ce)return Ce.id;H=ee>0?E.slice(ee+1):""}return H?((J=Zr(s.participants.filter(ee=>ee.type==="user"&&s.personKeyOf(ee)===H)))==null?void 0:J.id)??null:null},[s.participants,s.personKeyOf,s.stageIdOf]),[x,f]=on(`sn-studio:${a}:cast-keys`,[]),[g,h]=on(`sn-studio:${a}:excluded-keys`,[]),p=d.useCallback(E=>{if(!E.length)return Nd;const H=[];return E.forEach(J=>{const ee=u(J);ee&&!H.includes(ee)&&H.push(ee)}),H},[u]),N=d.useMemo(()=>p(x),[p,x]),k=d.useMemo(()=>p(g),[p,g]),[b,y]=on(`sn-studio:${a}:graphics`,{names:s.brand.showNames!==!1,logo:s.brand.showLogo!==!1,tickerId:s.activeTickerId}),[w,T]=on(`sn-studio:${a}:media-speaker`,null),[q,C]=d.useState("fade"),[_,K]=d.useState(!1),[L,F]=d.useState(null),S=d.useRef(!1);d.useEffect(()=>{!S.current&&i.config&&(S.current=!0,C(i.config.transition))},[i.config]);const O=d.useMemo(()=>s.stageParticipants.map(E=>E.id),[s.stageParticipants]),z=d.useMemo(()=>s.stageParticipants.map(E=>s.stageIdOf(E)),[s.stageParticipants,s.stageIdOf]),M=eo(s.program.sceneId),U=d.useCallback(E=>{var J,ee,de,Ce;const H={participants:s.participants,personKeyOf:s.personKeyOf,stageIdOf:s.stageIdOf,previewCast:N,programIds:O,question:n,logoUrl:s.brand.logo,fields:{title:s.room.title,block:((ee=(J=s.rundown)==null?void 0:J.current)==null?void 0:ee.title)||null,next:((Ce=(de=s.rundown)==null?void 0:de.next)==null?void 0:Ce.title)||null},...E};return M&&!H.previewCast.includes(M)&&(H.exclude=[...H.exclude||[],M]),H},[s.participants,s.personKeyOf,s.stageIdOf,N,O,n,s.brand.logo,s.room.title,s.rundown,M]),$=d.useMemo(()=>l.find(E=>E.id===s.program.sourceSceneId)||null,[l,s.program.sourceSceneId]),v=d.useMemo(()=>{const E=l.find(H=>H.id===m);return E||l.find(H=>H.id!==s.program.sourceSceneId)||l[0]||null},[l,m,s.program.sourceSceneId]),[B,se]=d.useState(null),A=d.useMemo(()=>{if(!v)return null;const E=ks(v,U({exclude:k}));return B&&B.sceneId===v.id?so(E,B.pairs):E},[v,U,k,B]),X=d.useCallback((E,H)=>{!v||E===H||se(J=>({sceneId:v.id,pairs:[...J&&J.sceneId===v.id?J.pairs:[],[E,H]]}))},[v]),ae=!!A&&A.scene.id===s.program.sourceSceneId&&yd(A.stageIds,z)&&!N.length&&!k.length,ce=d.useMemo(()=>new Set((A==null?void 0:A.participantIds)??[]),[A]),xe=d.useMemo(()=>{const E=new Set([...N,...O]);return new Set(((A==null?void 0:A.participantIds)??[]).filter(H=>!E.has(H)))},[A,N,O]);d.useEffect(()=>{s.activeTickerId&&s.activeTickerId!==b.tickerId&&y(E=>({...E,tickerId:s.activeTickerId}))},[s.activeTickerId,b.tickerId,y]);const ye=d.useCallback(()=>{const E=b.tickerId||s.activeTickerId;return E&&r.find(H=>H.id===E&&H.kind==="ticker")||null},[b.tickerId,s.activeTickerId,r]),be=d.useCallback(async(E,H)=>{var ee;if(_)return!1;const J=E.slots.flatMap(de=>de.kind==="participant"&&Ui(de.participant)?[de.participant]:[]);if(J.length)return t.error(`«${J[0].name}» ещё загружается — выведите, когда загрузится`),!1;K(!0);try{const de=ye();de&&await s.ensureBanner(de);const Ce=s.program.name,_e=s.stageParticipants.filter(us=>us.type==="user"&&!E.participantIds.includes(us.id)),ss=Qa(E,(H==null?void 0:H.transition)||q,(de==null?void 0:de.id)??null);
111H&&H.sourceSceneId!==void 0&&(ss.sourceSceneId=H.sourceSceneId),ss.brandPatch={showNames:E.brandPatch.showNames!==!1&&b.names,showHeadlines:E.brandPatch.showHeadlines!==!1&&b.names,showLogo:E.brandPatch.showLogo!==!1&&b.logo};const Ms=await s.take(ss);if(!Ms.success)return t.error(Ms.error||"Не удалось вывести сцену в эфир"),!1;if(Ms.dropped&&Ms.dropped.length){const us=new Map;E.slots.forEach(ms=>{ms.kind==="participant"&&us.set(s.stageIdOf(ms.participant),ms.participant)}),(ee=E.grid)==null||ee.participants.forEach(ms=>us.set(s.stageIdOf(ms),ms));const Ws=Ms.dropped.map(ms=>us.get(ms)).filter(ms=>!!ms).map(ms=>ms.type==="user"?ms.name:`«${ms.name}»`);t.error(Ws.length?`Не вышли в эфир: ${Ws.join(", ")} — нет в студии или переподключается, место пустое`:"Кого-то из сцены нет в студии — его место в эфире пустое")}if(E.slots.forEach(us=>{us.kind==="participant"&&us.participant.type==="video_file"&&!O.includes(us.participant.id)&&s.setVideoPlayback(us.participant.id,{isPlaying:!0})}),!(H!=null&&H.quiet)){const us=[];H!=null&&H.detail?us.push(H.detail):(Ce&&s.program.sourceSceneId!==E.scene.id&&us.push(`«${Ce}» ушло из эфира`),_e.length&&us.push(`${_e.map(Ws=>Ws.name).join(", ")} — за кулисами`)),F({id:Date.now(),name:E.scene.name,detail:us.join(" — "),previous:Ms.previous??null})}return!0}finally{K(!1)}},[_,ye,s,q,t,O,b.names,b.logo]),ge=d.useCallback(async()=>{if(!A)return t.show("Сначала выберите сцену для подготовки"),!1;if(!await be(A))return!1;if(f([]),h([]),se(null),A.scene.template==="auto")return o(A.scene.id),!0;const H=l.findIndex(ee=>ee.id===A.scene.id),J=H>=0?l[H+1]:null;return J&&o(J.id),!0},[A,be,f,h,l,o,t]),rs=d.useCallback(async E=>{const H=E.id===(v==null?void 0:v.id)&&A?A:ks(E,U({previewCast:[]}));await be(H)&&E.id===(v==null?void 0:v.id)&&(f([]),h([]),se(null))},[U,v,A,be,f,h]),Ie=d.useCallback(async E=>{if(!E)return;const H=await s.take({...E,transition:q});H.success?t.success("Предыдущая сцена снова в эфире"):t.error(H.error||"Не удалось вернуть предыдущую сцену")},[s,q,t]),De=d.useCallback((E=[])=>s.stageParticipants.filter(H=>Ss(H.type)&&H.id!==M&&!E.includes(H.id)).map(H=>H.id),[s.stageParticipants,M]),We=d.useCallback(async E=>{const H=M&&s.participants.find(ee=>ee.id===M)||null;if(H&&E.id!==M){const ee=s.stageParticipants.filter(de=>de.id!==H.id&&de.id!==E.id);await be(Mi(H,ee,s.stageIdOf),{quiet:!0,sourceSceneId:($==null?void 0:$.id)??null}),t.show(`${E.name} — за кулисами`);return}if(M&&E.id===M){await W(E.id);return}if(!$){s.toggleStageLegacy(E.id);return}const J=ks($,U({previewCast:De([E.id]),exclude:[E.id]}));await be(J,{quiet:!0}),t.show(`${E.name} — за кулисами`)},[$,U,be,s,t,M,De]);async function W(E,H,J){const ee=H||$||Tt("auto","Авто",l),de=ks(ee,U({previewCast:H?[]:De([E]),exclude:[E]}));
111return be(de,{quiet:!0,transition:J})}const oe=d.useCallback(async E=>{const H=s.stageParticipants.filter(J=>J.id!==E.id&&J.id!==M);return be(Mi(E,H,s.stageIdOf),{sourceSceneId:($==null?void 0:$.id)??null,detail:H.some(J=>J.type==="user")?"Спикеры остаются на сцене — вернутся в кадр, когда уберёте файл из эфира":"Файл закрывает весь кадр"})},[s.stageParticipants,s.stageIdOf,M,be,$]),le=d.useCallback((E,H)=>{if(E&&E.template!=="title"&&Li(E)>0)return E;const J=l.filter(de=>de.template!=="title"&&Li(de)>0),ee=de=>wd(de)>=H;return($&&J.includes($)&&ee($)?$:null)||(E?J.find(de=>de.folderId&&de.folderId===E.folderId&&de.template!=="auto"&&ee(de)):null)||J.find(de=>de.template!=="auto"&&ee(de))||J.find(de=>de.template==="auto")||J[0]||null},[l,$]),ie=d.useCallback(async E=>{if(Ss(E.type)){const de=s.stageParticipants.filter(ss=>ss.type==="user").map(ss=>ss.id),Ce=le($,de.length)||Tt("screen_speaker","Экран + спикер",l),_e=ks(Ce,U({previewCast:[...de,...De([E.id]),E.id],exclude:[]}));return be(_e)}const J=$&&$.template!=="title"?$:Tt("solo",E.name,l),ee=ks(J,U({previewCast:[E.id,...O.filter(de=>de!==M||de===E.id)]}));return be(ee)},[$,l,U,O,be,M,s.stageParticipants,le,De]),as=d.useCallback(E=>{const H=ee=>u(ee)===E.id;if(N.includes(E.id)){f(ee=>ee.filter(de=>!H(de)));return}const J=c(E);h(ee=>ee.some(H)?ee.filter(de=>!H(de)):[...ee,J])},[N,c,u,f,h]),Ze=d.useCallback(E=>{if(!v)return;const H=c(E),J=Ce=>u(Ce)===E.id,ee=Ss(E.type);if(h(Ce=>Ce.filter(_e=>!J(_e))),f(Ce=>ee?[...Ce.filter(_e=>!J(_e)),H]:Ce.some(J)?Ce:[...Ce,H]),ee){Ui(E)&&t.show(`«${E.name}» ещё загружается — в эфир можно будет вывести после загрузки`);const Ce=((A==null?void 0:A.participantIds)||[]).filter(ss=>s.participants.some(Ms=>Ms.id===ss&&Ms.type==="user")).length,_e=le(v,Ce);if(_e&&_e.id!==v.id){const ss=v;o(_e.id),se(null),t.show(`В «${ss.name}» нет места для файла — в подготовке «${_e.name}»`,{action:{label:`Вернуть «${ss.name}»`,onClick:()=>
111o(ss.id)}})}else _e||t.show("Ни в одной сцене нет места для файла — создайте сцену «Экран + спикер» или «Авто»");return}if(!ks(v,U({previewCast:[...N.filter(Ce=>Ce!==E.id),E.id],exclude:k.filter(Ce=>Ce!==E.id)})).participantIds.includes(E.id)){const Ce=l.find(_e=>_e.template==="auto"&&_e.id!==v.id)||null;Ce?t.show(`В сцене «${v.name}» мест меньше, чем людей в кадре`,{action:{label:`Взять «${Ce.name}»`,onClick:()=>o(Ce.id)}}):t.show(`В сцене «${v.name}» нет свободного места — создайте сцену «Авто»: она разложит всех, кого вы вывели`)}},[v,c,u,f,h,U,N,k,t,l,o,A,s.participants,le]),cs=d.useRef([]),Fe=d.useRef(new Map);d.useEffect(()=>{const E=Date.now();cs.current.filter(H=>!O.includes(H)).forEach(H=>Fe.current.set(H,E)),cs.current=O,Fe.current.forEach((H,J)=>{E-H>6e4&&Fe.current.delete(J)})},[O]);const ne=d.useRef(()=>{});ne.current=E=>{if(E===M&&s.perms.manageStage){window.setTimeout(()=>void W(E,null,"cut"),300);return}if(!$||$.template!=="auto"||!s.perms.manageStage||!O.includes(E)&&Date.now()-(Fe.current.get(E)||0)>15e3)return;const H=O.filter(J=>J!==E);window.setTimeout(()=>{be(ks($,U({previewCast:[],programIds:H,exclude:[E]})),{quiet:!0,transition:"cut"})},300)},d.useEffect(()=>{const E=s.studioSocket;if(!E)return;const H=({mediaId:J})=>{typeof J=="string"&&J&&ne.current(J)};return E.on("shared-media-removed",H),()=>{E.off("shared-media-removed",H)}},[s.studioSocket]);const je=d.useCallback(E=>{y(J=>({...J,names:E}));const H=!$||$.overlays.lowerThirds;s.updateBrand({showNames:E&&H,showHeadlines:E&&H})},[s,$,y]),Ee=d.useCallback(E=>{y(H=>({...H,logo:E})),s.updateBrand({showLogo:E&&(!$||$.overlays.logo)})},[s,$,y]),ze=d.useCallback(async E=>{if(y(H=>({...H,tickerId:E.id})),$&&!$.overlays.ticker){await s.ensureBanner(E),t.show(`Строка появится со следующей сценой — в «${$.name}» она скрыта`);return}try{await s.showBanner(E)}catch(H){t.error((H==null?void 0:H.message)||"Не удалось показать строку")}},[s,$,y,t]),os=d.useCallback(async E=>{if(E.kind==="ticker"){await ze(E);return}try{await s.showBanner(E)}catch(H){t.error((H==null?void 0:H.message)||"Не удалось показать баннер")}},[s,ze,t]),re=d.useCallback(()=>{y(E=>({...E,tickerId:null})),s.activeTickerId&&s.hideBanner("ticker")},[s,y]),he=d.useRef(!1),D=d.useRef({api:s,scenes:l,runTake:be,baseCtx:U});D.current={api:s,scenes:l,runTake:be,baseCtx:U},d.useEffect(()=>{if(he.current||!i.ready||!l.length||!s.perms.manageStage)return;let E=0;const H=window.setInterval(()=>{var de;const J=D.current;if(E+=1,he.current||E>30){window.clearInterval(H);return}if(!((de=J.api.studioSocket)!=null&&de.connected)||(he.current=!0,window.clearInterval(H),J.api.live.isLive||J.api.program.revision>0||J.api.stageParticipants.length>0))return;const ee=J.scenes.find(Ce=>Ce.template==="title")||J.scenes[0];J.runTake(ks(ee,J.baseCtx({previewCast:[]})),{quiet:!0,transition:"cut"})},1e3);return()=>window.clearInterval(H)},[i.ready,l.length,s.perms.manageStage]);const V=d.useCallback(async(E,H)=>{const J=await i.save({scenes:E});return J.ok?H&&t.success(H):t.error(J.error||"Не удалось сохранить сцены"),J.ok},[i,t]),Q=d.useCallback(async(E,H)=>{const ee=l.some(de=>de.id===E.id)?l.map(de=>de.id===E.id?E:de):[...l,E];return V(ee,H)},[l,V]),Z=d.useCallback(async E=>{if(l.length>=Tn){t.error(`Больше ${Tn} сцен в одной студии не поместится`);return}const H={...E,id:et(),name:`${E.name} — копия`.slice(0,60),hotkey:jl(l)},J=l.findIndex(de=>de.id===E.id),ee=[...l];ee.splice(J+1,0,H),await V(ee,`Сцена «${H.name}» создана`)},[l,V,t]),fe=d.useCallback(async E=>{if(E.id===s.program.sourceSceneId)return t.error("Эта сцена сейчас в эфире — сначала выведите другую"),!1;const H=await V(l.filter(J=>J.id!==E.id),`Сцена «${E.name}» удалена`);return H&&m===E.id&&o(null),H}
111,[s.program.sourceSceneId,V,l,m,o,t]),ve=((Ne=i.config)==null?void 0:Ne.sceneFolders)||[],Be=Array.isArray((es=i.config)==null?void 0:es.sceneFolders),Y=d.useCallback(async(E,H,J)=>{const ee=await i.save(H?{sceneFolders:E,scenes:H}:{sceneFolders:E});return ee.ok?J&&t.success(J):t.error(ee.error||"Не удалось сохранить папки"),ee.ok},[i,t]),Le=d.useCallback(async(E,H=[])=>{const J=E.trim().slice(0,40);if(!J)return null;if(ve.length>=$t)return t.error(`Больше ${$t} папок не поместится`),null;const ee={id:et(),name:J},de=H.length?l.map(_e=>H.includes(_e.id)?{..._e,folderId:ee.id}:_e):void 0;return await Y([...ve,ee],de,`Папка «${J}» создана`)?ee.id:null},[ve,l,Y,t]),Ge=d.useCallback(async(E,H)=>{const J=H.trim().slice(0,40);return J?Y(ve.map(ee=>ee.id===E?{...ee,name:J}:ee)):!1},[ve,Y]),Je=d.useCallback(async E=>{const H=ve.find(J=>J.id===E);return Y(ve.filter(J=>J.id!==E),l.map(J=>J.folderId===E?{...J,folderId:null}:J),H?`Папка «${H.name}» удалена — сцены остались`:void 0)},[ve,l,Y]),ds=d.useCallback(async E=>{if(!E.scenes.length)return t.error("В шаблоне нет сцен"),null;if(l.length+E.scenes.length>Tn)return t.error(`Не поместится: в студии ${l.length} из ${Tn} сцен, в шаблоне ${E.scenes.length} — удалите лишние сцены`),null;if(ve.length>=$t)return t.error(`Больше ${$t} папок не поместится`),null;const H=(E.folderName||E.name||"Шаблон").trim().slice(0,36)||"Шаблон",J=new Set(ve.map(ss=>ss.name));let ee=H;for(let ss=2;J.has(ee);ss+=1)ee=`${H} ${ss}`;const de={id:et(),name:ee},Ce=E.scenes.map(ss=>({...ss,id:et(),folderId:de.id,hotkey:null}));return await Y([...ve,de],[...l,...Ce],`Шаблон «${E.name}» добавлен — папка «${ee}», ${Ce.length} ${Xe(Ce.length,"сцена","сцены","сцен")}`)?de.id:null},[ve,l,Y,t]),pn=d.useCallback(async(E,H)=>{const J=H?ve.find(ee=>ee.id===H):null;return V(l.map(ee=>ee.id===E.id?{...ee,folderId:J?J.id:null}:ee),J?`«${E.name}» — в папке «${J.name}»`:`«${E.name}» — без папки`)},[ve,l,V]),$n=d.useCallback(async(E,H)=>{const J=l.map(ee=>ee.id===E.id?{...ee,hotkey:H}:H!==null&&ee.hotkey===H?{...ee,hotkey:null}:ee);await V(J,H?`Клавиша ${H} — «${E.name}»`:"Клавиша снята")},[l,V]),In=d.useCallback(async(E,H)=>{const J=l.findIndex(Ce=>Ce.id===E);if(J<0||H===J)return;const ee=[...l],[de]=ee.splice(J,1);ee.splice(Math.max(0,Math.min(ee.length,H)),0,de),await V(ee)},[l,V]),Mn=d.useCallback(async E=>{const H=await i.save({banners:E});return H.ok||t.error(H.error||"Не удалось сохранить баннеры"),H.ok},[i,t]),G=d.useCallback(E=>{C(E),i.save({transition:E})},[i]);return{cfg:i,scenes:l,banners:r,previewScene:v,compiledPreview:A,previewIds:ce,standInIds:xe,previewMatchesProgram:ae,programScene:$,programIds:O,cast:N,setPreviewId:o,transition:q,setTransition:G,taking:_,notice:L,dismissNotice:()=>F(null),takePreview:ge,takeScene:rs,undoTake:Ie,removeFromProgram:We,putOnAir:ie,coverWithMedia:oe,coverId:M,uncover:W,toggleCast:as,addToPreview:Ze,upsertScene:Q,saveScenes:V,folders:ve,foldersSupported:Be,createFolder:Le,renameFolder:Ge,deleteFolder:Je,addTemplate:ds,moveSceneToFolder:pn,duplicateScene:Z,deleteScene:fe,setSceneHotkey:$n,moveScene:In,saveBanners:Mn,clearPreview:()=>{f([]),h([]),se(null)},swapInPreview:X,excluded:k,mediaSpeaker:w,setMediaSpeaker:T,prefs:b,setNames:je,setLogo:Ee,showTicker:ze,hideTicker:re,showBanner:os,wantedTicker:ye(),compileFor:E=>ks(E,U(E.id===(v==null?void 0:v.id)?{exclude:k}:{previewCast:[]}))}}const Sd=["custom","auto","solo","duo","trio","screen_speaker","slides_speaker","pip","question","title"];function ji({template:s,count:n}){const t=s==="auto"?to(3,!1).people:null,a=t?Pa(t,3):vl(s,n),i=Ds[s].roles;return e.jsxs("span",{className:"sn-tpl-art","aria-hidden":"true",children:[s==="title"?e.jsxs(e.Fragment,{children:[e.jsx("i",{style:{left:"22%",top:"38%",width:"56%",height:"11%",background:"#fff"}}
111),e.jsx("i",{style:{left:"34%",top:"55%",width:"32%",height:"6%",background:"#56718F"}})]}):a.map((l,r)=>e.jsx("i",{className:i[r]==="media"?"is-media":i[r]==="question"?"is-q":void 0,style:{left:`${l.x}%`,top:`${l.y}%`,width:`${l.w}%`,height:`${l.h}%`}},r)),s==="auto"&&e.jsx("b",{className:"sn-tpl-auto",children:"А"}),s==="custom"&&e.jsx("span",{className:"sn-tpl-blank",children:e.jsx(ps,{size:16})})]})}const ca=s=>s.trim().split(/\s+/)[0]||s;function Cd({open:s,onClose:n,api:t,producer:a,onCreated:i,folderId:l}){const[r,m]=d.useState(""),[o,c]=d.useState("none"),[u,x]=d.useState(""),[f,g]=d.useState("custom"),[h,p]=d.useState([]),[N,k]=d.useState(null),[b,y]=d.useState(!1);d.useEffect(()=>{s&&(m(""),c(l&&a.folders.some(S=>S.id===l)?l:"none"),x(""),g("custom"),p([]),k(null),y(!1))},[s]);const w=$s(t),T=t.participants.filter(S=>Ss(S.type)),q=Ds[f].roles.includes("media")?[...T,...w]:w,C=jl(a.scenes),_=Ds[f].roles.length,K=d.useMemo(()=>{const S=h.map(O=>t.participants.find(z=>z.id===O)).filter(O=>!!O);return S.length?S.length===1?`${ca(S[0].name)} — ${f==="solo"?"соло":Ds[f].label.toLowerCase()}`:S.map(O=>ca(O.name)).join(" и "):f==="custom"?"Своя сцена":Ds[f].label},[h,f,t.participants]),L=S=>{p(O=>O.includes(S.id)?O.filter(z=>z!==S.id):_>0&&O.length>=_?[...O.slice(1),S.id]:[...O,S.id])},F=async()=>{if(a.scenes.length>=Tn){k(`В студии уже ${Tn} сцен — удалите ненужные`);return}const S=(r.trim()||K).slice(0,60),O=h.map(U=>t.participants.find($=>$.id===U)).filter(U=>!!U).map(U=>Ss(U.type)?{kind:"media",id:U.id}:{kind:"person",key:t.personKeyOf(U)}),z=Tt(f,S,a.scenes,Ya(f,O),t.room.title);if(y(!0),o==="new"){const U=u.trim()?await a.createFolder(u):null;if(!U){y(!1),k("Назовите новую папку");return}z.folderId=U}else o!=="none"&&(z.folderId=o);const M=await a.upsertScene(z,`Сцена «${z.name}» создана`);y(!1),M&&(n(),i(z))};return e.jsx(Ke,{open:s,onClose:n,width:720,title:e.jsx("span",{className:"sn-display",children:"Новая сцена"}),subtitle:"С чистого листа или по готовому макету — в редакторе всё двигается и меняется",footer:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sn-hint",style:{flex:1},children:C?e.jsxs(e.Fragment,{children:["Сцена получит клавишу ",e.jsx("span",{className:"sn-kbd",children:C})]}):"Свободных клавиш нет — назначите потом"}),e.jsx(R,{variant:"quiet",onClick:n,children:"Отмена"}),e.jsx(R,{variant:"primary",iconRight:e.jsx(Xs,{className:"sn-i sn-i-16"}),onClick:F,loading:b,children:"Создать и настроить"})]}),children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:18},children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:a.foldersSupported?"minmax(0, 1fr) minmax(0, 240px)":"minmax(0, 1fr)",gap:12,alignItems:"start"},children:[e.jsx(ke,{label:"Название",error:N,children:e.jsx(Oe,{value:r,onChange:S=>m(S.target.value.slice(0,60)),placeholder:K,"data-autofocus":!0})}),a.foldersSupported&&e.jsx(ke,{label:"Папка",children:e.jsx(Bs,{ariaLabel:"Папка",value:o,onChange:c,options:[{value:"none",label:"Без папки"},...a.folders.map(S=>({value:S.id,label:S.name})),{value:"new",label:"+ Новая папка…"}]})})]}),o==="new"&&e.jsx(ke,{label:"Название новой папки",children:e.jsx(Oe,{value:u,onChange:S=>x(S.target.value.slice(0,40)),placeholder:"Например, «Панель спикеров»",autoFocus:!0})}),e.jsxs("section",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsx("span",{className:"sn-label",children:"Макет"}),e.jsx("div",{className:"sn-tpl-grid",role:"group","aria-label":"Макет",children:Sd.map(S=>{var O;return e.jsxs("button",{type:"button",className:"sn-tpl","aria-pressed":f===S,onClick:()=>{g(S);const z=Ds[S].roles.length;p(M=>z?M.slice(0,z):[])},title:(O=no.find(z=>z.id===S))==null?void 0:O.hint,children:[e.jsx(ji,{template:S}),e.jsx("span",{className:"sn-tpl-name",children:Ds[S].label})]},S)})})]}),f==="custom"&&e.jsx("span",{className:"sn-hint",children:"Пустой кадр: в редакторе добавьте камеры, медиа, вопрос, текст, картинки, часы — и расставьте их мышкой как нужно. Бегущая строка и баннер места не занимают: когда они в эфире, сцена сама приподнимется."}),f==="auto"&&e.jsx("span",{className:"sn-hint",children:"Людей выбирать не нужно: сцена сама разложит всех, кого вы выведете «В кадр» в кулисах, — одного, двоих, троих и больше, а экран или слайды поставит рядом со спикерами."}),f!=="title"&&f!=="auto"&&f!=="custom"&&e.jsxs("section",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("span",{children:[e.jsx("span",{className:"sn-label",style:{display:"inline"},children:"Кого поставить"}),e.jsx("span",{className:"sn-hint",children:" · встанут в слоты по порядку выбора, пустые слоты заполнятся сами"})]}),q.length===0?e.jsx("span",{className:"sn-hint",children:"В студии пока никого — слоты заполнятся теми, кто придёт"}):e.jsx("div",{role:"group","aria-label":"Кого поставить",
111style:{display:"flex",flexWrap:"wrap",gap:8},children:q.map(S=>{const O=h.indexOf(S.id);return e.jsxs("button",{type:"button",className:"sn-chip-pick","aria-pressed":O>=0,onClick:()=>L(S),children:[e.jsx(Ve,{name:S.name,src:S.avatarUrl,size:28}),Ss(S.type)?S.name:ca(S.name),O>=0&&e.jsx("span",{className:"sn-order",children:O+1})]},S.id)})})]})]})})}function $d({api:s,backstageReady:n,backstageTotal:t,onOpenPanel:a,onOpenRecording:i,onGoLive:l,onEnd:r,onLeave:m,rundownLabel:o}){const c=ts(1e3),u=s.live,x=u.isLive&&u.startedAt?Math.max(0,Math.floor((c-u.startedAt)/1e3)):0,f=u.destinations.filter(k=>k.status==="live").length,g=u.destinations.some(k=>k.status==="error"),h=s.room.scheduledAt?new Date(s.room.scheduledAt).getTime():null,p=h?Math.floor((h-c)/1e3):null,N=s.me.roleLabel?`Вы ${s.me.roleLabel.toLowerCase()}`:null;return e.jsxs("header",{className:"sn-st-header",children:[e.jsx(Ye,{label:"В кабинет",size:"sm",onClick:m,style:{color:"var(--sn-ink-2)"},children:e.jsx(jt,{className:"sn-i"})}),e.jsx("span",{className:"sn-st-title",title:s.room.title,children:s.room.title}),N&&e.jsx(ns,{tone:"blue",className:"sn-st-hide-sm",children:N}),e.jsx("div",{className:"sn-st-grow"}),e.jsxs("div",{className:"sn-st-status",children:[u.isLive?e.jsx(fl,{time:fs(x,!0),className:"sn-st-livetag"}):e.jsxs(ns,{tone:"gray",className:"sn-st-livetag",style:{height:30},children:[e.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:"var(--sn-ink-3)"}}),u.starting?"Запускаем…":"Не в эфире"]}),u.isLive&&s.viewerCount!==null&&e.jsxs("span",{className:"sn-st-viewers sn-st-hide-sm",title:typeof s.realViewerCount=="number"?`Видят все: ${He(s.viewerCount)} — с зрителями других площадок. В комнате на самом деле: ${He(s.realViewerCount)}`:"Зрители сейчас",children:[e.jsx(gs,{className:"sn-i sn-i-16"}),e.jsx("b",{children:He(s.viewerCount)}),typeof s.realViewerCount=="number"&&e.jsxs("span",{className:"sn-st-viewers-real",children:["реально ",He(s.realViewerCount)]})]}),!u.isLive&&h&&p!==null&&p>-3600&&e.jsxs("span",{className:"sn-st-hide-md",style:{fontSize:14,color:"var(--sn-ink-2)"},children:["Начало в ",e.jsx("span",{className:"sn-mono",style:{color:"var(--sn-ink)",fontWeight:600},children:qe(h)}),p>0?e.jsxs(e.Fragment,{children:[" · через ",e.jsx("span",{className:"sn-mono",style:{color:"var(--sn-ink)",fontWeight:600},children:fs(p)})]}):null]}),o&&e.jsxs("button",{type:"button",className:"sn-st-pill sn-st-hide-md",onClick:()=>a("rundown"),children:[e.jsx(Ks,{className:"sn-i sn-i-16"}),o]}),!u.isLive&&t>0&&e.jsxs("button",{type:"button",className:"sn-st-pill sn-st-hide-sm",style:n<t?{background:"var(--sn-amber-soft)",borderColor:"#EFD3A1",color:"var(--sn-amber)"}:void 0,onClick:()=>a("prelive"),children:[e.jsx(nn,{className:"sn-i sn-i-16"}),"За кулисами ",n," из ",t]}),s.perms.recording&&e.jsxs("button",{type:"button",className:"sn-st-pill sn-st-hide-sm",onClick:k=>i(k.currentTarget),children:[e.jsx("span",{className:`sn-st-dot${s.recording.active?" is-red":""}`}),s.recording.active?e.jsxs(e.Fragment,{children:["Запись ",e.jsx("span",{className:"sn-mono",children:fs(s.recording.elapsedSec)})]}):"Запись"]}),u.isLive&&e.jsxs("button",{type:"button",className:"sn-st-pill sn-st-hide-sm",onClick:()=>a("outputs"),children:[e.jsx("span",{className:`sn-st-dot${g?" is-amber":f?" is-green":""}`}),f?`${f} ${f===1?"площадка":f<5?"площадки":"площадок"}`:"Только страница"]})]}),e.jsx("div",{className:"sn-st-grow"}),e.jsxs("div",{className:"sn-st-actions",children:[e.jsx(Ye,{label:s.me.isMuted?"Включить микрофон":"Выключить микрофон",size:"sm",variant:s.me.isMuted?"off-light":"quiet",onClick:s.toggleMic,children:s.me.isMuted?e.jsx(Es,{className:"sn-i"}):e.jsx(Ts,{className:"sn-i"})}),e.jsx(Ye,{label:s.me.isCameraOff?"Включить камеру":"Выключить камеру",size:"sm",variant:s.me.isCameraOff?"off-light":"quiet",onClick:s.toggleCamera,children:s.me.isCameraOff?e.jsx(kn,{className:"sn-i"}):e.jsx(Sn,{className:"sn-i"})}),e.jsx(Ye,{label:"Настройки студии",size:"sm",variant:"quiet",onClick:s.openDeviceSettings,className:"sn-st-hide-sm",children:e.jsx(Yt,{className:"sn-i"})}),e.jsx("span",{className:"sn-st-sep sn-st-hide-sm"}),s.perms.invites&&e.jsx(R,{size:"sm",variant:"quiet",icon:e.jsx(Is,{className:"sn-i sn-i-16"}),onClick:s.openInvite,className:"sn-st-hide-sm",children:"Пригласить"}),u.isLive?s.perms.endMeeting&&e.jsx(R,{size:"sm",variant:"quiet",style:{color:"var(--sn-red-ink)"},onClick:r,children:"Завершить"}):s.perms.broadcastLive&&e.jsx(R,{size:"sm",variant:"live",icon:e.jsx(ws,{className:"sn-i sn-i-16"}),onClick:l,loading:u.starting,children:"Выйти в эфир"})]})]})}function Id(s,n=28){const t=s.trim();return t.length>n?`${t.slice(0,n-1)}…`:t}function Md({api:s,producer:n,onNewBanner:t,onEditBanner:a,onLowerThirds:i,onBrand:l,quickQuestion:r,onQuestionOnAir:m,quickPoll:o,onRunPoll:c,lowerThirdCount:u}){const x=n.banners.filter(y=>y.kind==="ticker"),f=n.banners.filter(y=>y.kind==="banner"),g=n.wantedTicker||x[0]||null,h=!!n.prefs.tickerId,p=n.prefs.names,N=n.prefs.logo,k=s.perms.manageStage,b=y=>{if(!y){n.hideTicker();return}if(!g){t("ticker");return}n.showTicker(g)};return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"sn-panel-sec",style:{gap:2},children:[e.jsx("span",{className:"sn-eyebrow",style:{paddingBottom:6},children:"Сейчас поверх эфира"}),e.jsxs("div",{className:"sn-ovl-row",children:[e.jsx("span",{className:"sn-ovl-ico",children:e.jsx(Bn,{className:"sn-i"})}),e.jsxs("span",{className:"sn-ovl-text",children:[e.jsx("span",{className:"sn-t",children:"Бегущая строка"}),e.jsx("button",{type:"button",className:"sn-l",onClick:()=>g?a(g):t("ticker"),children:g?`«${Id(g.text)}» · изменить`:"добавить текст строки"})]}),e.jsx(Pe,{checked:h,onChange:b,label:"Бегущая строка",disabled:!k})]}),e.jsxs("div",{className:"sn-ovl-row",children:[e.jsx("span",{className:"sn-ovl-ico",children:e.jsx(en,{className:"sn-i"})}),e.jsxs("span",{className:"sn-ovl-text",children:[e.jsx("span",{className:"sn-t",children:"Имена и должности"}),e.jsxs("button",{type:"button",className:"sn-l",onClick:i,children:[u," ",u%10===1&&u%100!==11?"плашка":u%10>=2&&u%10<=4&&(u%100<10||u%100>=20)?"плашки":"плашек"," · настроить"]})]}),e.jsx(Pe,{checked:p,onChange:n.setNames,label:"Имена и должности",disabled:!k})]}),e.jsxs("div",{className:"sn-ovl-row",children:[e.jsx("span",{className:"sn-ovl-ico",style:{background:"var(--sn-sunk)"},children:e.jsx(jo,{logoUrl:s.brand.logo,size:20,dark:!0,markOnly:!0})}),e.jsxs("span",{className:"sn-ovl-text",children:[e.jsx("span",{className:"sn-t",children:"Логотип"}),e.jsx("button",{type:"button",className:"sn-l",onClick:l,children:"в правом углу строки · бренд"})]}),e.jsx(Pe,{checked:N,onChange:n.setLogo,label:"Логотип",disabled:!k})]})]}),e.jsxs("section",{className:"sn-panel-sec",children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsx("span",{className:"sn-eyebrow",children:"Баннеры"}),e.jsx("span",{className:"sn-s",children:"показываются сразу поверх эфира"})]}),f.length===0&&e.jsxs("div",{style:{padding:"14px 12px",borderRadius:14,border:"1px dashed var(--sn-line-2)",fontSize:13,color:"var(--sn-ink-3)",display:"flex",flexDirection:"column",gap:8,alignItems:"flex-start"},children:["Промокоды, ссылки и объявления — заготовьте заранее и показывайте одним нажатием.",k&&e.jsx(R,{size:"sm",variant:"quiet",icon:e.jsx(ps,{className:"sn-i sn-i-16"}),onClick:()=>t("banner"),children:"Новый баннер"})]}),f.map(y=>{const w=s.activeBannerId===y.id;return e.jsxs("div",{className:`sn-gfx-card${w?" is-on":""}`,children:[e.jsxs("button",{type:"button",className:"sn-txt",onClick:()=>a(y),style:{background:"none",border:0,padding:0,textAlign:"left",cursor:"pointer",color:"inherit",font:"inherit"},title:"Изменить баннер",children:[e.jsx("span",{className:"sn-t",children:y.text}),y.sub&&e.jsx("span",{className:"sn-s",children:y.sub}),w&&e.jsx("span",{className:"sn-k",style:{color:"var(--sn-blue-ink)",fontWeight:600},children:"в эфире"})]}),k&&e.jsx(R,{size:"sm",variant:w?"soft":"quiet",onClick:()=>w?s.hideBanner("banner"):void n.showBanner(y),children:w?"Скрыть":"Показать"})]},y.id)})]}),(r||o)&&e.jsxs("section",{className:"sn-panel-sec",children:[e.jsx("span",{className:"sn-eyebrow",children:"Вывести одним нажатием"}),r&&e.jsxs("div",{className:"sn-gfx-card",children:[e.jsxs("span",{className:"sn-txt",children:[e.jsxs("span",{className:"sn-k",children:[r.note," · ",e.jsxs("span",{className:"sn-mono",style:{color:"var(--sn-blue)"},children:["▲ ",r.votes]})]}),e.jsx("span",{className:"sn-t",children:r.text})]}),e.jsx(R,{size:"sm",variant:"quiet",onClick:()=>m(r.id),children:"На экран"})]}),o&&e.jsxs("div",{className:"sn-gfx-card",children:[e.jsx("span",{className:"sn-ovl-ico",style:{background:"var(--sn-sunk)",color:"var(--sn-ink-2)"},children:e.jsx(xn,{className:"sn-i"})}),e.jsxs("span",{className:"sn-txt",children:[e.jsxs("span",{className:"sn-k",children:["Опрос · ",o.optionsCount," варианта"]}),e.jsx("span",{className:"sn-t",children:o.question})]}),e.jsx(R,{size:"sm",variant:"quiet",onClick:()=>c(o.id),children:o.running?"Итоги":"Запустить"})]})]})]})}const Ld={snich:"SNICH Live",youtube:"YouTube",vk:"VK Видео",vk_video:"VK Видео",rutube:"RUTUBE",twitch:"Twitch",telegram:"Telegram",rtmp:"RTMP"},Ad=s=>Ld[s]||s;function ir(s,n){return!!s.readyPeers[s.stageIdOf(n)]||!n.isCameraOff&&!n.isMuted}function Pd(s){return s.isCameraOff&&s.isMuted?"камера и микрофон выключены":s.isCameraOff?"камера выключена":s.isMuted?"микрофон выключен":"ждём готовности"}function lr(s){const n=$s(s).filter(r=>!r.isLocal),t=n.filter(r=>ir(s,r)),a=s.network.online&&s.network.studioConnected&&(s.network.downlinkMbps===null||s.network.downlinkMbps>=5),i=s.plannedDestinations.length>0,l=!s.perms.recording||s.autoRecord||s.recording.active;return{people:n,readyPeople:t,networkOk:a,destinationsOk:i,recordingOk:l}}function Ed(s,n=0){const t=lr(s),a=[t.people.length+n>0&&t.readyPeople.length===t.people.length+n,t.networkOk,t.destinationsOk,t.recordingOk];
111return{ready:a.filter(Boolean).length,total:a.length}}function Bi({api:s,producer:n,onOpenPanel:t,phone:a=!1}){var q,C;const i=Se(),[l,r]=d.useState({}),{people:m,readyPeople:o,networkOk:c,destinationsOk:u}=lr(s),x=Qn(),f=x&&s.perms.manageStage?x.missing:[],g=m.length+f.length,h=g>0&&o.length===g,p=s.program.name||((q=n.programScene)==null?void 0:q.name)||"Заставка",N=n.previewScene&&n.previewScene.id!==((C=n.programScene)==null?void 0:C.id)?n.previewScene.name:null,k=s.room.scheduledAt?new Date(s.room.scheduledAt):null,b=async _=>{const K=await s.sendCue(s.stageIdOf(_),"Скоро эфир — включите камеру и микрофон, пожалуйста","text");if(!K.success){i.error(K.error||"Не удалось отправить напоминание");return}r(L=>({...L,[_.id]:!0})),i.success(`${_.name} получит напоминание`)},y=s.network.downlinkMbps,w=s.network.online?s.network.studioConnected?y!==null&&y<5?`Слабая сеть — ${y} Мбит/с`:y!==null?`Сеть ${y>=10?"от 10":y} Мбит/с`:"Связь со студией в порядке":"Нет связи со студией":"Нет интернета",T=!s.network.online||!s.network.studioConnected?"Проверьте подключение — зрители не увидят эфир":y!==null&&y<5?"Для 1080p нужно от 6 Мбит/с — закройте загрузки и видео":"Хватит на 1080p и несколько площадок";return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"sn-panel-sec",children:[e.jsx("span",{className:"sn-eyebrow",children:"Готовность"}),e.jsxs("div",{className:`sn-pl-people${g&&!h?" is-warn":""}`,children:[e.jsxs("div",{className:"sn-pl-people-head",children:[e.jsx("span",{className:"sn-pl-ico",children:e.jsx(nn,{className:"sn-i sn-i-16"})}),e.jsx("b",{children:"Спикеры за кулисами"}),g>0&&e.jsxs("span",{className:h?"sn-pl-count is-ok":"sn-pl-count",children:[o.length," из ",g]})]}),g===0?e.jsxs("div",{className:"sn-pl-empty",children:[e.jsx("span",{children:"В студии пока никого — пригласите спикеров по ссылке"}),s.perms.invites&&e.jsx(R,{size:"sm",variant:"quiet",icon:e.jsx(Is,{className:"sn-i sn-i-16"}),onClick:s.openInvite,children:"Позвать гостя"})]}):m.map(_=>{const K=ir(s,_);return e.jsxs("div",{className:"sn-pl-person",children:[e.jsx(Ve,{name:_.name,src:_.avatarUrl,size:28}),e.jsxs("span",{className:"sn-pl-person-text",children:[e.jsx("span",{className:"sn-pl-name",children:_.name}),!K&&e.jsx("span",{className:"sn-pl-sub",children:Pd(_)})]}),K?e.jsxs("span",{className:"sn-pl-ok",children:[e.jsx(Re,{className:"sn-i sn-i-16"})," на месте"]}):s.perms.manageStage?e.jsx(R,{size:"sm",variant:"quiet",onClick:()=>void b(_),disabled:l[_.id],children:l[_.id]?"Напомнили":"Напомнить"}):null]},_.id)}),x&&f.map(_=>e.jsx(tr,{crew:x,member:_},_.id))]}),e.jsxs("div",{className:`sn-pl-card${c?"":" is-warn"}`,children:[e.jsx("span",{className:`sn-pl-check${c?"":" is-warn"}`,children:c?e.jsx(Re,{className:"sn-i sn-i-16"}):"!"}),e.jsxs("span",{className:"sn-pl-text",children:[e.jsx("b",{children:w}),e.jsx("span",{children:T})]})]}),e.jsxs("button",{type:"button",className:`sn-pl-card is-link${u?"":" is-idle"}`,onClick:()=>t("outputs"),children:[e.jsx("span",{className:`sn-pl-check${u?"":" is-idle"}`,children:u?e.jsx(Re,{className:"sn-i sn-i-16"}):e.jsx(Ps,{className:"sn-i sn-i-16"})}),e.jsxs("span",{className:"sn-pl-text",children:[e.jsx("b",{children:u?"Площадки подключены":"Площадки не выбраны"}),e.jsx("span",{children:u?s.plannedDestinations.map(Ad).join(" · "):"Выберите при выходе в эфир — SNICH Live, YouTube, VK Видео"})]}),e.jsx(Ps,{className:"sn-i sn-i-16",style:{color:"var(--sn-ink-3)"}})]}),!s.perms.recording&&s.perms.manageStage&&!ni(s,"recording")&&e.jsxs("div",{className:"sn-pl-card","data-testid":"prelive-recording-off",children:[e.jsx("span",{className:"sn-pl-check is-idle",children:"—"}),e.jsxs("span",{className:"sn-pl-text",children:[e.jsx("b",{children:ti.recording}),e.jsx("span",{children:"Эфир не попадёт в «Записи и итоги» — включите запись в настройках эфира, если она нужна"})]})]}),s.perms.recording&&e.jsxs("div",{className:"sn-pl-card",children:[e.jsx("span",{className:`sn-pl-check${s.autoRecord||s.recording.active?"":" is-idle"}`,children:s.autoRecord||s.recording.active?e.jsx(Re,{className:"sn-i sn-i-16"}):"—"}),e.jsxs("span",{className:"sn-pl-text",children:[e.jsx("b",{children:s.recording.active?"Запись уже идёт":s.autoRecord?"Запись начнётся вместе с эфиром":"Запись выключена"}),e.jsx("span",{children:s.autoRecord||s.recording.active?"Попадёт в «Записи и итоги»":"Включите — эфир попадёт в «Записи и итоги»"})]}),!s.recording.active&&e.jsx(Pe,{checked:s.autoRecord,onChange:s.setAutoRecord,label:"Записывать вместе с эфиром"})]}),e.jsxs("button",{type:"button",className:"sn-pl-card is-info is-link",onClick:()=>t("chat"),children:[e.jsx("span",{className:"sn-pl-check is-info",children:e.jsx(gs,{className:"sn-i sn-i-16"})}),e.jsxs("span",{className:"sn-pl-text",children:[e.jsx("b",{children:s.viewerCount?`${s.viewerCount} ${s.viewerCount%10===1&&s.viewerCount%100!==11?"зритель ждёт":"зрителей ждут"} начала`:"Зрители ждут начала"}),e.jsxs("span",{children:["Видят «",p,"» и пишут в чат"]})]}),e.jsx(Ps,{className:"sn-i sn-i-16",style:{color:"var(--sn-blue)"}})]})]}),e.jsxs("section",{className:"sn-panel-sec",children:[e.jsx("span",{className:"sn-eyebrow",children:"Как начать"}),e.jsxs("ol",{className:"sn-pl-steps",children:[e.jsxs("li",{children:[e.jsx("b",{children:"Проверьте кадр в «Эфир»"}),e.jsxs("span",{children:["Там «",p,"» — её увидят первой"]})]}),e.jsxs("li",{children:[e.jsx("b",{children:"Нажмите «Выйти в эфир»"}),e.jsxs("span",{children:[a?"Кнопка под эфиром":"Вверху справа"," · отсчёт 5 секунд"]})]}),e.jsxs("li",{children:[e.jsx("b",{children:N?`После заставки выведите «${N}»`:"Выведите следующую сцену"}),e.jsx("span",{children:"Кнопка «Вывести в эфир» или Пробел"})]})]})]}),k&&!Number.isNaN(k.getTime())&&e.jsxs("div",{className:"sn-pl-foot",children:[e.jsx(un,{className:"sn-i sn-i-16"}),e.jsxs("span",{children:["В ",e.jsx("span",{className:"sn-mono",children:qe(k)})," эфир сам не начнётся — только по кнопке «Выйти в эфир»"]})]})]})}const Vt={prelive:"Перед эфиром",graphics:"Графика",peo
111ple:"Люди",questions:"Вопросы",chat:"Чат",polls:"Опросы",media:"Медиа",brand:"Бренд",sound:"Звук",rundown:"Программа",outputs:"Эфир",ai:"AI"},Hi=[{id:"graphics",icon:e.jsx(Hn,{className:"sn-i"})},{id:"people",icon:e.jsx(nn,{className:"sn-i"})},{id:"questions",icon:e.jsx(wn,{className:"sn-i"})},{id:"chat",icon:e.jsx(Hs,{className:"sn-i"})},{id:"polls",icon:e.jsx(xn,{className:"sn-i"})},{id:"media",icon:e.jsx(gt,{className:"sn-i"})},{id:"brand",icon:e.jsx(ai,{className:"sn-i"})},{id:"sound",icon:e.jsx(Cn,{className:"sn-i"})},{id:"rundown",icon:e.jsx(Il,{className:"sn-i"})},{id:"outputs",icon:e.jsx(ws,{className:"sn-i"})},{id:"ai",icon:e.jsx(Vn,{className:"sn-i"})}];function zd({active:s,onSelect:n,counts:t,dots:a,showPrelive:i}){const l=i?[{id:"prelive",icon:e.jsx(Io,{className:"sn-i"}),label:"Старт"},...Hi]:Hi;return e.jsx("nav",{className:"sn-prod-rail","aria-label":"Разделы студии",children:l.map(r=>{const m=t[r.id]||0;return e.jsxs("button",{type:"button",className:"sn-rail-item","aria-current":s===r.id?"true":void 0,onClick:()=>n(r.id),title:Vt[r.id],children:[r.icon,r.label||Vt[r.id],m>0?e.jsx("span",{className:"sn-rail-count",children:m>99?"99+":m}):a[r.id]?e.jsx("span",{className:"sn-rail-dot"}):null]},r.id)})})}const da={"#0B1220":"Тёмно-синий","#141619":"Графит","#0A72C6":"Фирменный синий","#1E7F48":"Зелёный","#D52F3A":"Красный","#F4F3EF":"Светлый"},Td=["#FFFFFF","#141619","#0A72C6","#4DAEF5","#F6C66B","#D52F3A"],Ns=5,Od=1.2,an=2.5,It=24,Ft=9,Fd=[{value:"frame",label:"Кадр"},{value:"rounded",label:"Скругл.",title:"Скруглённые углы"},{value:"square",label:"Прямой"},{value:"squircle",label:"iOS",title:"Плавные углы, как у иконок iPhone"},{value:"circle",label:"Круг"}
111],Vi=[...bl,"#FFFFFF"],Rd=/^#?([0-9a-f]{6}|[0-9a-f]{3})$/i;function ua(s){const n=Rd.exec(s.trim());return n?`#${(n[1].length===3?n[1].split("").map(a=>a+a).join(""):n[1]).toUpperCase()}`:null}function Dd({value:s,preset:n,onChange:t,label:a}){const i=!n.some(m=>m.toLowerCase()===s.toLowerCase()),[l,r]=d.useState(i?s.toUpperCase():"");return d.useEffect(()=>{r(i?s.toUpperCase():"")},[i,s]),e.jsxs(e.Fragment,{children:[e.jsx("label",{className:"sn-sed-color sn-sed-color-pick","data-on":i||void 0,style:i?{background:s}:void 0,title:"Свой цвет",children:e.jsx("input",{type:"color",value:ua(s)||"#0B1220",onChange:m=>t(m.target.value.toUpperCase()),"aria-label":a})}),e.jsx("input",{className:"sn-sed-hex",value:l,placeholder:"#HEX",maxLength:7,spellCheck:!1,"aria-label":`${a}, HEX`,onChange:m=>{r(m.target.value);const o=ua(m.target.value);o&&m.target.value.replace("#","").length===6&&t(o)},onBlur:()=>{const m=ua(l);m?t(m):r(i?s.toUpperCase():"")}})]})}function Ki({value:s,onChange:n,label:t}){const a={frame:"4px",rounded:"8px",square:"0",squircle:"11px",circle:"50%"};return e.jsx("div",{className:"sn-sed-shapes",role:"group","aria-label":t,children:Fd.map(i=>e.jsxs("button",{type:"button","aria-pressed":s===i.value,title:i.title,onClick:()=>n(i.value),children:[e.jsx("i",{"aria-hidden":"true",className:i.value==="circle"?"is-circle":void 0,style:{borderRadius:a[i.value]}}),e.jsx("span",{children:i.label})]},i.value))})}const ln={text:"Текст",image:"Картинка",shape:"Подложка",timer:"Таймер",clock:"Часы",grid:"Сетка камер",poll:"Опрос"};function qd(s,n){if(!s)return"весь кадр";const t=s.x+s.w/2,a=s.y+s.h/2;if(s.w>70&&s.h>60)return"на весь кадр";const i=t<40?"слева":t>60?"справа":"в центре";return s.h<45?`${i} ${a<45?"сверху":"снизу"}`:i}function On(s){switch(s.kind){case"person":return`person:${s.key}`;case"media":return`media:${s.id}`;case"question":return"question";case"empty":return"empty";default:return"auto"}}function rr(s){return s.startsWith("person:")?{kind:"person",key:s.slice(7)}:s.startsWith("media:")?{kind:"media",id:s.slice(6)}:s==="question"?{kind:"question"}:s==="empty"?{kind:"empty"}:{kind:"auto"}}function or(s,n,t){const a=Ls(n,t),i=[{value:"auto",label:a==="question"?"Вопрос из очереди (авто)":a==="media"?"Экран или файл (авто)":"По очереди из кулис (авто)",icon:e.jsx(wn,{className:"sn-i sn-i-16"})}];$s(s).forEach(r=>i.push({value:`person:${s.personKeyOf(r)}`,label:r.name,icon:e.jsx(Ve,{name:r.name,src:r.avatarUrl,size:22})}));const l=n.slots[t];return(l==null?void 0:l.kind)==="person"&&!i.some(r=>r.value===On(l))&&i.push({value:On(l),label:`${l.key.replace(/^[a-z]:/,"")} — не в студии`,icon:e.jsx(en,{className:"sn-i sn-i-16"})}),s.participants.filter(r=>Ss(r.type)).forEach(r=>i.push({value:`media:${r.id}`,label:r.name,description:"файл комнаты"})),(l==null?void 0:l.kind)==="media"&&!i.some(r=>r.value===On(l))&&i.push({value:On(l),label:"Файл удалён",disabled:!0}),a!=="question"&&i.push({value:"question",label:"Вопрос из очереди (авто)",icon:e.jsx(wn,{className:"sn-i sn-i-16"})}),i.push({value:"empty",label:"Пусто",icon:e.jsx(As,{className:"sn-i sn-i-16"})}),i}function cr(s,n,t){const a=Ya(n,s.slots,n==="grid"?Math.max(4,s.slots.length):void 0);return{...s,template:n,slots:a,elements:n==="auto"&&s.elements?s.elements.filter(i=>i.kind!=="grid"):s.elements,frames:null,framesVertical:null,roles:null,slotStyles:null,title:n==="title"?s.title||{heading:t,sub:""}:s.title,overlays:n==="title"?{...s.overlays,lowerThirds:!1,ticker:!1}:s.overlays}}function Rt(s,n,t={}){if(s.template!=="auto"){const g=s.template==="title"&&s.title?[{id:it(),kind:"text",frame:{x:10,y:34,w:80,h:16},text:s.title.heading||"{{title}}",textStyle:"heading",color:"#FFFFFF",align:"center"},...s.title.sub?[{id:it(),kind:"text",frame:{x:15,y:53,w:70,h:9},text:s.title.sub,textStyle:"subheading",color:"#FFFFFF",align:"center"}]:[]]:[];return{...s,template:"custom",elements:g.length?[...s.elements||[],...g]:s.elements,roles:s.slots.map((h,p)=>Ls(s,p)),frames:Dn(s).map(h=>({...h})),framesVertical:s.slots.map((h,p)=>({...n.verticalFrames[p]||Dn(s)[p]})),slotStyles:s.slots.map((h,p)=>s.slotStyles&&s.slotStyles[p]||null)}}const a=n.scene,i=[],l=[],r=[],m=[],o=[],c=(s.elements||[]).filter(g=>g.kind!=="grid"),u=a.slots.length&&a.frames?a.frames[0]:null;u&&(i.push({kind:"auto"}),l.push("media"),r.push({fit:"contain"}),m.push({...u}),o.push({...a.framesVertical&&a.framesVertical[0]||u}));const x=n.grid,f=x?x.participants.length:0;
111if(x&&f)if(t.peopleAsGrid||i.length+f>Ft)c.push({id:it(),kind:"grid",frame:{...x.frame},frameVertical:{...x.verticalFrame},count:null,gap:x.element.gap??16,shape:"rounded",fit:"cover"});else{const g=x.element.gap??16,h=Pa(x.frame,f,!1,g),p=Pa(x.verticalFrame,f,!0,g);h.forEach((N,k)=>{i.push({kind:"auto"}),l.push("camera"),r.push(null),m.push(N),o.push(p[k]||N)})}return!i.length&&!c.some(g=>g.kind==="grid")&&(i.push({kind:"auto"}),l.push("camera"),r.push(null),m.push(vl("solo")[0]),o.push(io("solo")[0])),{...s,template:"custom",slots:i,roles:l,slotStyles:r,frames:m.length?m:null,framesVertical:o.length?o:null,elements:c}}function _d(s){return{...s,template:"custom",slots:[],roles:[],slotStyles:[],frames:null,framesVertical:null,elements:[],title:null}}const hs=(s,n,t)=>Math.min(t,Math.max(n,s)),xs=s=>Math.round(s*100)/100,it=()=>`el-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,7)}`;function Wi(s,n,t,a){const i=[0,Ns,50,100-Ns,100,...n.flatMap(c=>[c.x,c.x+c.w/2,c.x+c.w])],l=[0,Ns,50,100-Ns,100,...n.flatMap(c=>[c.y,c.y+c.h/2,c.y+c.h])],r={x:[],y:[]},m=(c,u)=>{let x=null;for(const f of c)for(const g of u){const h=g-f;Math.abs(h)<=Od&&(!x||Math.abs(h)<Math.abs(x.delta))&&(x={delta:h,line:g})}return x},o={...s};if(t==="move"){const c=m([o.x,o.x+o.w/2,o.x+o.w],i);c?(o.x+=c.delta,r.x.push(c.line)):a&&(o.x=Math.round(o.x/an)*an);const u=m([o.y,o.y+o.h/2,o.y+o.h],l);u?(o.y+=u.delta,r.y.push(u.line)):a&&(o.y=Math.round(o.y/an)*an)}else{const c=m([o.x+o.w],i);c?(o.w+=c.delta,r.x.push(c.line)):a&&(o.w=Math.round((o.x+o.w)/an)*an-o.x);const u=m([o.y+o.h],l);u?(o.h+=u.delta,r.y.push(u.line)):a&&(o.h=Math.round((o.y+o.h)/an)*an-o.y)}return o.x=xs(hs(o.x,0,100-o.w)),o.y=xs(hs(o.y,0,100-o.h)),o.w=xs(hs(o.w,3,100-o.x)),o.h=xs(hs(o.h,3,100-o.y)),{frame:o,guides:r}}function Ud(s){return s.x>=Ns-.01&&s.y>=Ns-.01&&s.x+s.w<=100-Ns+.01&&s.y+s.h<=100-Ns+.01}function Bd(s){const n=Math.min(s.w,100-Ns*2),t=Math.min(s.h,100-Ns*2);return{x:xs(hs(s.x,Ns,100-Ns-n)),y:xs(hs(s.y,Ns,100-Ns-t)),w:n,h:t}}const Hd=(s,n)=>s.x<n.x+n.w&&n.x<s.x+s.w&&s.y<n.y+n.h&&n.y<s.y+s.h;function Vd(s){const n=["Анна Белова","Игорь Власов","Мария Соколова","Павел Гринёв","Ольга Ким","Дмитрий Орлов","Елена Шарова","Артём Лебедев","Нина Гусева"];return Array.from({length:s},(t,a)=>({id:`check-${a}`,name:n[a%n.length],headline:"Спикер",type:"user",isLocal:!1,isMuted:!0,isCameraOff:!0,isScreenSharing:!1,stream:null}))}function Kd(s,n){const t=it();switch(s){case"text":return{id:t,kind:s,frame:{x:6,y:8,w:60,h:11},text:"{{block}}",textStyle:"subheading",color:"#FFFFFF",align:"left",plate:!0};case"image":return{id:t,kind:s,frame:{x:82,y:7,w:12,h:12},src:"brand:logo",fit:"contain"};case"shape":return{id:t,kind:s,frame:{x:0,y:72,w:100,h:28},fill:"#0B1220",opacity:80,above:!1};case"timer":return{id:t,kind:s,frame:{x:80,y:80,w:14,h:9},minutes:10,direction:"down",textStyle:"subheading",plate:!0};case"clock":return{id:t,kind:s,frame:{x:80,y:7,w:14,h:9},clockFormat:"HH:mm",textStyle:"subheading",plate:!0};case"grid":return{id:t,kind:s,frame:{x:5,y:12,w:90,h:72},count:null,gap:16,shape:"rounded",fit:"cover"};default:return{id:t,kind:"text",frame:{x:6,y:8,w:60,h:11},text:n,textStyle:"heading"}}}function Wd({api:s,producer:n,scene:t,onClose:a,onHotkey:i,orientation:l="16:9",saved:r}){var ki,Si;
111const m=Se(),[o,c]=d.useState(t),[u,x]=d.useState([]),[f,g]=d.useState([]),[h,p]=d.useState(t.slots.length?{type:"slot",index:0}:null),[N,k]=d.useState(!1),[b,y]=d.useState(null),[w,T]=d.useState(!1),[q,C]=d.useState(!1),[_,K]=d.useState(!0),[L,F]=d.useState("edit"),[S,O]=d.useState(3),[z,M]=d.useState(!0),[U,$]=d.useState(!0),[v,B]=d.useState(!1),[se,A]=d.useState("bottom"),[X,ae]=d.useState({x:[],y:[]}),ce=d.useRef(null),xe=d.useRef(null),ye=d.useRef(null),[be,ge]=d.useState(l),rs=s.verticalFormat?be:"16:9",Ie=rs==="9:16",De=JSON.stringify(o)!==JSON.stringify(r??t),We=!n.scenes.some(j=>j.id===t.id),W=d.useRef(t),oe=d.useCallback(j=>{const I=typeof j=="function"?j(W.current):j;W.current=I,c(I)},[]),le=d.useCallback(j=>{const I=W.current,P=typeof j=="function"?j(I):j;P!==I&&(x(te=>[...te.slice(-59),I]),g([]),oe(P))},[oe]),ie=j=>le(I=>({...I,...j})),as=()=>{if(!u.length)return;const j=W.current;g(I=>[j,...I]),oe(u[u.length-1]),x(I=>I.slice(0,-1))},Ze=()=>{if(!f.length)return;const j=W.current;x(I=>[...I,j]),oe(f[0]),g(I=>I.slice(1))};d.useEffect(()=>{const j=n.scenes.find(I=>I.id===t.id);j&&j.hotkey!==o.hotkey&&oe(I=>({...I,hotkey:j.hotkey}))},[n.scenes]);const cs=d.useMemo(()=>L==="check"?Vd(S):[],[L,S]),Fe=d.useMemo(()=>{var j,I,P,te,ue,pe,Te;return ks(o,{participants:L==="check"?[...s.participants.filter($e=>$e.type!=="user"),...cs]:s.participants,personKeyOf:s.personKeyOf,stageIdOf:s.stageIdOf,previewCast:L==="check"?cs.map($e=>$e.id):o.id===((j=n.previewScene)==null?void 0:j.id)?n.cast:[],programIds:L==="check"?[]:n.programIds,question:((I=n.compiledPreview)==null?void 0:I.question)??(L==="check"?{id:"check",text:"Как вы считаете, что будет с рынком в следующем году?",authorName:"Зритель",votes:12}:null),exclude:L==="check"?[]:o.id===((P=n.previewScene)==null?void 0:P.id)?n.excluded:[],logoUrl:s.brand.logo,fields:{title:s.room.title,block:((ue=(te=s.rundown)==null?void 0:te.current)==null?void 0:ue.title)||"Открытие",next:((Te=(pe=s.rundown)==null?void 0:pe.next)==null?void 0:Te.title)||"Следующий блок"}})},[o,s,n,L,cs]),ne=o.template==="auto",je=ne?[]:Ie?Fe.verticalFrames:Dn(o),Ee=Ie?"framesVertical":"frames",ze=j=>{const I=j[Ee];return I&&I.length>=j.slots.length?I:null},os=j=>Ie?{framesVertical:j}:{frames:j};$s(s),s.participants.filter(j=>Ss(j.type));const re=o.elements||[],he=(h==null?void 0:h.type)==="el"&&re.find(j=>j.id===h.id)||null,D=(h==null?void 0:h.type)==="slot"?h.index:null,V=j=>j.slots.map((I,P)=>Ls(j,P)),Q=j=>j.slots.map((I,P)=>j.slotStyles&&j.slotStyles[P]||null),Z=j=>{if(j===o.template)return;const I=j==="custom"?Rt(o,Fe):cr(o,j,s.room.title);le(I),p(I.slots.length?{type:"slot",index:0}:null)},fe=(j={})=>{W.current.template==="auto"&&(le(Rt(W.current,Fe,j)),m.show("Сцена теперь расставлена вручную: места больше не перестраиваются сами. Ctrl+Z — вернуть «Авто»"))},ve=()=>{le(j=>_d(j)),p(null),m.show("Кадр пуст — добавьте камеры, медиа и текст сверху. Ctrl+Z вернёт как было")},Be=j=>le(I=>({...I,elements:j(I.elements||[])})),Y=(j,I)=>{le(P=>({...P,slots:P.slots.map((te,ue)=>ue===j?I:te)}))},Le=(j,I)=>{const P=je;le(te=>{const ue=Q(te);ue[j]={...ue[j]||{},...I};let pe={...te,slotStyles:ue};if(I.shape==="circle"){const Te=(ze(te)||P).map(Me=>({...Me})),$e=Te[j];if($e){const Me=Ie?9:16,Ue=Ie?16:9,me=Math.min($e.w*Me,$e.h*Ue),Qe=xs(me/Me),bs=xs(me/Ue);Te[j]={x:xs($e.x+($e.w-Qe)/2),y:xs($e.y+($e.h-bs)/2),w:Qe,h:bs},pe={...pe,...os(Te)}}}return pe})},Ge=j=>{if(fe(),W.current.slots.length>=Ft){m.show(`В сцене уже ${Ft} мест — для большего числа людей добавьте «Сетку камер»`);return}const I=j==="question"?{x:55,y:20,w:40,h:40}:j==="media"?{x:5,y:12,w:62,h:62}:{x:64,y:30,w:30,h:30};le(P=>{if(P.slots.length>=Ft)return P;const te=(P.frames&&P.frames.length>=P.slots.length?P.frames:Dn(P)).map(pe=>({...pe})),ue=P.framesVertical&&P.framesVertical.length>=P.slots.length?[...P.framesVertical,{x:8,y:30,w:84,h:26}]:null;return{...P,slots:[...P.slots,j==="question"?{kind:"question"}:{kind:"auto"}],roles:[...V(P),j],slotStyles:[...Q(P),null],frames:[...te.slice(0,P.slots.length),I],framesVertical:ue}}),p({type:"slot",index:W.current.slots.length-1})},Je=j=>{const I=P=>P?P.filter((te,ue)=>ue!==j):null;le(P=>{if(j<0||j>=P.slots.length)return P;const te=P.frames&&P.frames.length>=P.slots.length?P.frames:Dn(P);return{...P,slots:P.slots.filter((ue,pe)=>pe!==j),roles:V(P).filter((ue,pe)=>pe!==j),slotStyles:I(Q(P)),frames:te.filter((ue,pe)=>pe!==j),framesVertical:P.framesVertical&&P.framesVertical.length>=P.slots.length?I(P.framesVertical):null}}),p(null)},ds=j=>
111{if(j==="grid"&&W.current.template==="auto"){fe({peopleAsGrid:!0});const P=(W.current.elements||[]).find(te=>te.kind==="grid");if(P){p({type:"el",id:P.id});return}}if(re.length>=It){m.show(`В сцене уже ${It} элементов`);return}if(j==="grid"&&(W.current.elements||[]).some(P=>P.kind==="grid")){m.show("Сетка камер уже есть в сцене — её можно растянуть или поменять число людей");return}const I=Kd(j,s.room.title);j==="grid"&&W.current.slots.some(P=>P.kind!=="empty")&&(I.frame={x:52,y:12,w:43,h:70}),Be(P=>P.length>=It||j==="grid"&&P.some(te=>te.kind==="grid")?P:I.kind==="shape"?[I,...P]:[...P,I]),p({type:"el",id:I.id}),j==="image"&&window.setTimeout(()=>{var P;return(P=ye.current)==null?void 0:P.click()},50)},pn=(j,I)=>{Be(P=>P.map(te=>te.id===j?{...te,...I}:te))},$n=j=>{Be(I=>I.filter(P=>P.id!==j)),p(null)},In=j=>{const I=re.find(te=>te.id===j);if(!I||re.length>=It||I.kind==="grid")return;const P={...I,id:it(),frame:{...I.frame,x:hs(I.frame.x+2,0,100-I.frame.w),y:hs(I.frame.y+2,0,100-I.frame.h)}};Be(te=>{const ue=te.findIndex(pe=>pe.id===j);return ue<0?te:[...te.slice(0,ue+1),P,...te.slice(ue+1)]}),p({type:"el",id:P.id})},Mn=(j,I)=>{Be(P=>{const te=P.findIndex(Te=>Te.id===j),ue=te+I;if(te<0||ue<0||ue>=P.length)return P;const pe=[...P];return[pe[te],pe[ue]]=[pe[ue],pe[te]],pe})},G=j=>Ai(j,Ie),Ne=(j,I)=>Ie?{...j,frameVertical:I}:{...j,frame:I},es=()=>(ze(o)||je).map(j=>({...j})),E=d.useRef(null),H=j=>{const I=[];return je.forEach((P,te)=>{j.type==="slot"&&j.index===te||I.push(P)}),re.forEach(P=>{!P.hidden&&!(j.type==="el"&&j.id===P.id)&&I.push(G(P))}),I},J=(j,I)=>P=>{var pe,Te,$e;if(P.button!==0||L==="check")return;const te=(pe=ce.current)==null?void 0:pe.getBoundingClientRect();if(!te)return;P.stopPropagation(),P.preventDefault(),p(j);let ue=null;if(j.type==="slot"){const Me=es();ze(o)||oe(Ue=>({...Ue,...os(Me)})),ue=Me[j.index]}else{const Me=re.find(Ue=>Ue.id===j.id);if(!Me||Me.locked)return;ue=G(Me)}ue&&(E.current={target:j,mode:I,startX:P.clientX,startY:P.clientY,frame:ue,rect:te,before:o,others:H(j)},($e=(Te=P.currentTarget).setPointerCapture)==null||$e.call(Te,P.pointerId))},ee=d.useMemo(()=>ne?Rt(o,Fe):null,[ne,o,Fe]),de=ee?(Ie?ee.framesVertical:ee.frames)||[]:je,Ce=j=>I=>{var $e,Me,Ue;if(I.button!==0||L==="check"||!ee)return;const P=($e=ce.current)==null?void 0:$e.getBoundingClientRect();if(!P)return;I.stopPropagation(),I.preventDefault();const te=ee,ue=(Ie?te.framesVertical:te.frames)||[],pe=ue[j];if(le(te),m.show("Сцена теперь расставлена вручную: места больше не перестраиваются сами. Ctrl+Z — вернуть «Авто»"),p({type:"slot",index:j}),!pe)return;const Te=[...ue.filter((me,Qe)=>Qe!==j),...(te.elements||[]).filter(me=>!me.hidden).map(me=>Ai(me,Ie))];E.current={target:{type:"slot",index:j},mode:"move",startX:I.clientX,startY:I.clientY,frame:pe,rect:P,before:te,others:Te},(Ue=(Me=I.currentTarget).setPointerCapture)==null||Ue.call(Me,I.pointerId)},_e=j=>{const I=E.current;if(!I)return;const P=(j.clientX-I.startX)/I.rect.width*100,te=(j.clientY-I.startY)/I.rect.height*100,ue={...I.frame};I.mode==="move"?(ue.x=I.frame.x+P,ue.y=I.frame.y+te):(ue.w=I.frame.w+P,ue.h=I.frame.h+te);const pe=z&&!j.altKey?Wi(ue,I.others,I.mode,v):{frame:Wi(ue,[],I.mode,!1).frame,guides:{x:[],y:[]}};ae(pe.guides);const Te=pe.frame;oe($e=>{if(I.target.type==="slot"){const Ue=(ze($e)||je).map(me=>({...me}));return Ue[I.target.index]=Te,{...$e,...os(Ue)}}const Me=I.target.id;return{...$e,elements:($e.elements||[]).map(Ue=>Ue.id===Me?Ne(Ue,Te):Ue)}})},ss=()=>{const j=E.current;E.current=null,ae({x:[],y:[]}),j&&JSON.stringify(j.before)!==JSON.stringify(W.current)&&(x(I=>[...I.slice(-59),j.before]),g([]))};d.useEffect(()=>{const j=I=>{const P=I.target;if(P&&(P.tagName==="INPUT"||P.tagName==="TEXTAREA"||P.isContentEditable)||document.querySelector(".sn-overlay"))return;const te=I.ctrlKey||I.metaKey;if(te&&(I.key==="z"||I.key==="я")){I.preventDefault(),I.shiftKey?Ze():as();return}if(te&&(I.key==="y"||I.key==="н")){I.preventDefault(),Ze();return}if(!h)return;if(te&&(I.key==="d"||I.key==="в")&&h.type==="el"){I.preventDefault(),In(h.id);return}if(I.key==="Delete"||I.key==="Backspace"){I.preventDefault(),h.type==="slot"?Je(h.index):$n(h.id);return}
111const ue=I.shiftKey?5:1,Te={ArrowLeft:[-ue,0],ArrowRight:[ue,0],ArrowUp:[0,-ue],ArrowDown:[0,ue]}[I.key];if(Te)if(I.preventDefault(),h.type==="slot"){const $e=es(),Me=$e[h.index];if(!Me)return;Me.x=xs(hs(Me.x+Te[0],0,100-Me.w)),Me.y=xs(hs(Me.y+Te[1],0,100-Me.h)),ie(os($e))}else{const $e=re.find(Ue=>Ue.id===h.id);if(!$e||$e.locked)return;const Me={...G($e)};Me.x=xs(hs(Me.x+Te[0],0,100-Me.w)),Me.y=xs(hs(Me.y+Te[1],0,100-Me.h)),ie({elements:re.map(Ue=>Ue.id===$e.id?Ne(Ue,Me):Ue)})}};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)});const Ms=j=>or(s,o,j),us=async(j,I)=>{if(!j.type.startsWith("image/")){m.error("Нужна картинка: JPG, PNG, WebP или SVG");return}if(j.size>10*1024*1024){m.error("Картинка больше 10 МБ — уменьшите её");return}y(I);try{const P=await za(j);if(I==="bg")ie({background:{kind:"image",value:P.url}});else if(he&&he.kind==="shape")ie({elements:re.map(te=>te.id===he.id?{...te,src:P.url,fit:te.fit||"cover"}:te)});else if(he&&he.kind==="image"){const te=await new Promise(Te=>{const $e=new Image;$e.onload=()=>Te({w:$e.naturalWidth,h:$e.naturalHeight}),$e.onerror=()=>Te(null),$e.src=URL.createObjectURL(j)}),ue=G(he);let pe=ue;if(te&&te.w>0&&te.h>0){const Te=Ie?9:16,$e=Ie?16:9,Me=xs(hs(ue.w*Te*te.h/te.w/$e,3,100-ue.y));pe={...ue,h:Me}}ie({elements:re.map(Te=>Te.id===he.id?{...Ne(Te,pe),src:P.url}:Te)})}}catch(P){m.error(js(P,"Не удалось загрузить картинку"))}finally{y(null)}},Ws=d.useMemo(()=>{const j=[],I=Fe.warnings.filter(me=>!/Сетка камер/.test(me));j.push({ok:I.length===0,text:I.length?I[0]:"Все места заняты"});const P=[...je.map((me,Qe)=>({f:me,name:`Место ${Qe+1}`})).filter((me,Qe)=>Ls(o,Qe)!=="question"),...re.filter(me=>me.kind==="grid"&&!me.hidden).map(me=>({f:G(me),name:"Сетка камер"}))];let te=null;for(let me=0;me<P.length&&!te;me+=1)for(let Qe=me+1;Qe<P.length&&!te;Qe+=1){const bs=P[me].f,Fs=P[Qe].f,Ci=Math.min(bs.x+bs.w,Fs.x+Fs.w)-Math.max(bs.x,Fs.x),$i=Math.min(bs.y+bs.h,Fs.y+Fs.h)-Math.max(bs.y,Fs.y);if(Ci<=0||$i<=0)continue;const Ii=Ci*$i/Math.min(bs.w*bs.h,Fs.w*Fs.h);Ii>.08&&Ii<.95&&(te=`${P[me].name} и ${P[Qe].name} перекрываются — один закроет другого`)}j.push({ok:!te,text:te||"Камеры не перекрывают друг друга"});const ue=re.filter(me=>!me.hidden&&(me.kind==="text"||me.kind==="timer"||me.kind==="clock")),pe=ue.filter(me=>!Ud(G(me)));j.push({ok:pe.length===0,text:pe.length?`Текст у края кадра: ${pe.length} — площадки могут его обрезать`:"Текст внутри безопасной зоны",fix:pe.length?()=>ie({elements:re.map(me=>pe.includes(me)?Ne(me,Bd(G(me))):me)}):void 0});const $e=je.filter((me,Qe)=>Ls(o,Qe)==="camera").map(me=>({x:me.x+me.w*.2,y:me.y+me.h*.08,w:me.w*.6,h:me.h*.55})),Me=ue.filter(me=>(me.above??!0)&&$e.some(Qe=>Hd(G(me),Qe)));j.push({ok:Me.length===0,text:Me.length?"Текст может закрыть лицо спикера":"Подписи не закрывают лица",fix:Me.length?()=>ie({elements:re.map(me=>{if(!Me.includes(me))return me;const Qe=G(me);return Ne(me,{...Qe,y:xs(hs(100-Ns-Qe.h,0,100-Qe.h))})})}):void 0});const Ue=ue.filter(me=>{const bs=G(me).h/100*(Ie?1920:1080),Fs=me.textStyle==="heading"?76:me.textStyle==="caption"?32:46;return bs<Fs*(Ie?.62:1)*1.15});return j.push({ok:Ue.length===0,text:Ue.length?"Текст не помещается по высоте":"Текст читается (от 20 px на 1080p)",fix:Ue.length?()=>ie({elements:re.map(me=>{if(!Ue.includes(me))return me;const Qe=G(me),bs=(me.textStyle==="heading"?76:me.textStyle==="caption"?32:46)*(Ie?.62:1)*1.3/(Ie?1920:1080)*100;return Ne(me,{...Qe,h:xs(Math.min(100-Qe.y,bs))})})}):void 0}),j},[Fe,re,je,Ie,o]),ms=async(j=!0,I=_)=>{const P=o.name.trim();if(!P)return m.error("Назовите сцену"),!1;k(!0);const te=await n.upsertScene({...o,name:P},`Сцена «${P}» сохранена${I?" — она уже в Подготовке":""}`);return k(!1),te&&I&&n.setPreviewId(o.id),te&&j&&a(),te},_r=d.useCallback(()=>{De?T(!0):a()}
111,[De,a]),bi=t.id===s.program.sourceSceneId,Ur=Array.from({length:9},(j,I)=>I+1).filter(j=>j===o.hotkey||!n.scenes.some(I=>I.id!==o.id&&I.hotkey===j)),Br=j=>{const I=Fe.slots[j],P=(I==null?void 0:I.kind)==="participant"?I.participant.name:(I==null?void 0:I.kind)==="question"?"Карточка вопроса":"Пусто",te=D===j;return e.jsxs("span",{style:{position:"absolute",left:14,top:14,zIndex:30,display:"inline-flex",alignItems:"center",gap:8,height:34,padding:"0 12px",borderRadius:9,fontSize:17,fontWeight:600,whiteSpace:"nowrap",background:te?"#0A72C6":"rgba(13,14,16,.74)",color:"#fff",pointerEvents:"none"},children:["Место ",j+1," · ",P]})},Hr=[{key:"camera",label:"Камера",icon:e.jsx(Sn,{className:"sn-i sn-i-16"}),onClick:()=>Ge("camera"),hint:"Место для одного человека"},{key:"grid",label:"Сетка камер",icon:e.jsx(Al,{className:"sn-i sn-i-16"}),onClick:()=>ds("grid"),hint:"Все, кто в очереди, — сами встают в сетку"},{key:"media",label:"Медиа",icon:e.jsx($l,{className:"sn-i sn-i-16"}),onClick:()=>Ge("media"),hint:"Презентация, ролик или экран"},{key:"question",label:"Вопрос",icon:e.jsx(wn,{className:"sn-i sn-i-16"}),onClick:()=>Ge("question"),hint:"Вопрос из зала на экране"},{key:"text",label:"Текст",icon:e.jsx(Bn,{className:"sn-i sn-i-16"}),onClick:()=>ds("text"),hint:"Заголовок, подпись, название блока"},{key:"image",label:"Картинка",icon:e.jsx(gt,{className:"sn-i sn-i-16"}),onClick:()=>ds("image"),hint:"Логотип или картинка"},{key:"shape",label:"Подложка",icon:e.jsx(jn,{className:"sn-i sn-i-16"}),onClick:()=>ds("shape"),hint:"Цветная плашка под людьми"},{key:"timer",label:"Таймер",icon:e.jsx(ec,{className:"sn-i sn-i-16"}),onClick:()=>ds("timer"),hint:"Обратный отсчёт или секундомер"},{key:"clock",label:"Часы",icon:e.jsx(Ks,{className:"sn-i sn-i-16"}),onClick:()=>ds("clock"),hint:"Текущее время"}],yi=j=>j.kind!=="grid"&&(j.above??j.kind!=="shape"),tn=re.find(j=>j.kind==="grid")||null,Ni=[...[...re].reverse().filter(yi).map(j=>({key:j.id,label:j.name||ln[j.kind],sub:j.kind==="text"?(j.text||"").slice(0,26):"над людьми",sel:{type:"el",id:j.id},el:j})),...tn?[{key:tn.id,label:tn.name||ln.grid,sub:tn.count&&tn.count>1?`до ${tn.count} чел. из очереди`:"все из очереди, до 9",sel:{type:"el",id:tn.id},el:tn}]:[],...o.slots.map((j,I)=>({key:`slot-${I}`,label:`Место ${I+1}`,sub:Ls(o,I)==="media"?"медиа":Ls(o,I)==="question"?"вопрос":j.kind==="person"?"закреплён человек":"по очереди",sel:{type:"slot",index:I}})),...[...re].reverse().filter(j=>j.kind!=="grid"&&!yi(j)).map(j=>({key:j.id,label:j.name||ln[j.kind],sub:"под людьми",sel:{type:"el",id:j.id},el:j}))],Vr=j=>(h==null?void 0:h.type)==="slot"&&j.type==="slot"&&h.index===j.index||(h==null?void 0:h.type)==="el"&&j.type==="el"&&h.id===j.id,wi=(j,I)=>e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(4, minmax(0, 1fr))",gap:6},children:[["x","y","w","h"].map(P=>e.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:3,fontSize:12,color:"var(--sn-ink-3)"},children:[P==="x"?"X":P==="y"?"Y":P==="w"?"Ш":"В",", %",e.jsx("input",{className:"sn-input sn-mono",style:{height:32,padding:"0 8px",fontSize:13},type:"number",min:P==="w"||P==="h"?3:0,max:100,step:.5,value:Math.round(j[P]*10)/10,"aria-label":`${P==="x"?"Отступ слева":P==="y"?"Отступ сверху":P==="w"?"Ширина":"Высота"}, %`,onChange:te=>{const ue=Number(te.target.value);if(!Number.isFinite(ue))return;const pe={...j,[P]:ue};pe.w=hs(pe.w,3,100),pe.h=hs(pe.h,3,100),pe.x=hs(pe.x,0,100-pe.w),pe.y=hs(pe.y,0,100-pe.h),I(pe)}})]},P)),e.jsxs("div",{style:{gridColumn:"1 / -1",display:"flex",gap:6},children:[e.jsx(R,{size:"sm",variant:"quiet",icon:e.jsx(ra,{className:"sn-i sn-i-16"}),onClick:()=>I({...j,x:xs((100-j.w)/2)}),style:{flex:1},children:"По центру ↔"}),e.jsx(R,{size:"sm",variant:"quiet",icon:e.jsx(ra,{className:"sn-i sn-i-16",style:{transform:"rotate(90deg)"}}),onClick:()=>I({...j,y:xs((100-j.h)/2)}),style:{flex:1},children:"По центру ↕"})]})]});let ia=null;if(D!==null&&o.slots[D]){const j=D,I=o.slots[j],P=Ls(o,j),te=ao(o,j);ia=e.jsxs("section",{className:"sn-panel-sec","aria-label":`Место ${j+1}`,children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsxs("span",{className:"sn-eyebrow",children:["Место ",j+1," · ",qd(je[j],o.slots.length)]}),e.jsx(Ye,{label:"Удалить место",size:"sm",variant:"ghost",onClick:()=>Je(j),children:e.jsx(hn,{className:"sn-i sn-i-16"})})]}),e.jsx(ke,{label:P==="media"?"Что показывать":P==="question"?"Вопрос":"Кто в этом месте",children:e.jsx(Bs,{value:On(I),onChange:ue=>Y(j,rr(ue)),options:Ms(j),ariaLabel:`Место ${j+1}`})}),I.kind==="person"&&e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Если человека нет в студии, место займёт следующий из очереди."}),P!=="question"&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{label:"Форма",children:e.jsx(Ki,{label:"Форма места",value:te.shape||"frame",onChange:ue=>Le(j,{shape:ue})})}),e.jsx(ke,{label:"Кадрирование",children:e.jsx(we,{size:"sm",ariaLabel:"Кадрирование",value:te.fit||(P==="media"?"contain":"cover"),onChange:ue=>Le(j,{fit:ue}),options:[{value:"cover",label:"Заполнить"},{value:"contain",label:"Вписать"}]})})]}),je[j]&&wi(je[j],ue=>{const pe=es();pe[j]=ue,ie(os(pe))})]})}else if(he){const j=he,I=P=>pn(j.id,P);ia=e.jsxs("section",{className:"sn-panel-sec","aria-label":ln[j.kind],children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsx("span",{className:"sn-eyebrow",children:ln[j.kind]}),e.jsxs("span",{style:{display:"inline-flex",gap:2},children:[j.kind!=="grid"&&e.jsx(Ye,{label:"Дублировать",size:"sm",variant:"ghost",onClick:()=>In(j.id),children:e.jsx(vt,{className:"sn-i sn-i-16"})}),e.jsx(Ye,{label:"Удалить элемент",size:"sm",variant:"ghost",onClick:()=>$n(j.id),children:e.jsx(hn,{className:"sn-i sn-i-16"})})]})]}),j.kind==="text"&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{label:"Текст",children:e.jsx(Oe,{value:j.text||"",onChange:P=>I({text:P.target.value.slice(0,300)}),placeholder:"Например, {{block}}"})}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},role:"group","aria-label":"Подставить",children:[["{{title}}","Название эфира"],["{{block}}","Блок программы"],["{{next}}","Следующий блок"],["{{speaker}}","Кто говорит"]].map(([P,te])=>e.jsx("button",{type:"button",className:"sn-chip",onClick:()=>I({text:`${(j.text||"").trim()} ${P}`.trim()}),children:te},P))}),e.jsx(ke,{label:"Стиль",children:e.jsx(we,{size:"sm",ariaLabel:"Стиль текста",value:j.textStyle||"subheading",onCh
111ange:P=>I({textStyle:P}),options:[{value:"heading",label:"Заголовок"},{value:"subheading",label:"Подзаголовок"},{value:"caption",label:"Подпись"}]})}),e.jsx(ke,{label:"Выравнивание",children:e.jsx(we,{size:"sm",ariaLabel:"Выравнивание",value:j.align||"left",onChange:P=>I({align:P}),options:[{value:"left",icon:e.jsx(Ec,{className:"sn-i sn-i-16"}),label:"Слева"},{value:"center",icon:e.jsx(ra,{className:"sn-i sn-i-16"}),label:"Центр"},{value:"right",icon:e.jsx(Ac,{className:"sn-i sn-i-16"}),label:"Справа"}]})})]}),(j.kind==="text"||j.kind==="timer"||j.kind==="clock")&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sn-label",style:{marginBottom:-4},children:"Цвет"}),e.jsx("div",{className:"sn-sed-colors",role:"group","aria-label":"Цвет текста",children:Td.map(P=>e.jsx("button",{type:"button",className:"sn-sed-color",style:{background:P},"aria-label":`Цвет ${P}`,"aria-pressed":(j.color||"#FFFFFF").toLowerCase()===P.toLowerCase(),onClick:()=>I({color:P})},P))}),e.jsx(Fn,{title:"Плашка под текстом",description:"Полупрозрачная — текст читается на любом фоне",checked:j.kind==="text"?!!j.plate:j.plate!==!1,onChange:P=>I({plate:P})})]}),j.kind==="timer"&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{label:"Минут",children:e.jsx(Oe,{type:"number",min:1,max:600,value:String(j.minutes||10),onChange:P=>I({minutes:hs(Math.round(Number(P.target.value)||10),1,600)})})}),e.jsx(we,{size:"sm",ariaLabel:"Направление",value:j.direction||"down",onChange:P=>I({direction:P}),options:[{value:"down",label:"Обратный отсчёт"},{value:"up",label:"Секундомер"}]}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Отсчёт начинается, когда сцена выходит в эфир."})]}),j.kind==="clock"&&e.jsx(we,{size:"sm",ariaLabel:"Формат",value:j.clockFormat||"HH:mm",onChange:P=>I({clockFormat:P}),options:[{value:"HH:mm",label:"ЧЧ:ММ"},{value:"HH:mm:ss",label:"ЧЧ:ММ:СС"}]}),j.kind==="image"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[e.jsx(R,{size:"sm",variant:j.src==="brand:logo"?"primary":"quiet",onClick:()=>I({src:"brand:logo"}),children:"Логотип из бренда"}),e.jsx(R,{size:"sm",variant:"quiet",icon:e.jsx(cn,{className:"sn-i sn-i-16"}),loading:b==="img",onClick:()=>{var P;return(P=ye.current)==null?void 0:P.click()},children:"Своя картинка"})]}),e.jsx(we,{size:"sm",ariaLabel:"Кадрирование",value:j.fit||"contain",onChange:P=>I({fit:P}),options:[{value:"contain",label:"Вписать"},{value:"cover",label:"Заполнить"}]})]}),j.kind==="shape"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sn-sed-colors",role:"group","aria-label":"Цвет подложки",children:[Vi.map(P=>e.jsx("button",{type:"button",className:"sn-sed-color",style:{background:P},"aria-label":da[P]||P,"aria-pressed":(j.fill||"#0B1220").toLowerCase()===P.toLowerCase(),onClick:()=>I({fill:P})},P)),e.jsx(Dd,{value:j.fill||"#0B1220",preset:Vi,onChange:P=>I({fill:P}),label:"Свой цвет подложки"})]}),e.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap",alignItems:"center"},children:[e.jsx(R,{size:"sm",variant:"quiet",icon:e.jsx(cn,{className:"sn-i sn-i-16"}),loading:b==="img",onClick:()=>{var P;return(P=ye.current)==null?void 0:P.click()},children:j.src?"Другая картинка":"Картинка на подложку"}),j.src&&e.jsx(R,{size:"sm",variant:"text",onClick:()=>I({src:void 0}),children:"Убрать картинку"})]}),j.src&&e.jsxs(e.Fragment,{children:[e.jsx(we,{size:"sm",ariaLabel:"Кадрирование картинки",value:j.fit||"cover",onChange:P=>I({fit:P}),options:[{value:"cover",label:"Заполнить"},{value:"contain",label:"Вписать"}]}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Цвет подложки виден по краям и сквозь прозрачные места картинки."})]}),e.jsx(ke,{label:`Прозрачность · ${100-(j.opacity??100)}%`,children:e.jsx("input",{type:"range",min:10,max:100,step:5,value:j.opacity??100,onChange:P=>I({opacity:Number(P.target.value)}),"aria-label":"Непрозрачность подложки"})})]}),(j.kind==="shape"||j.kind==="image")&&e.jsx(ke,{label:`Скругление · ${j.radius||0}%`,children:e.jsx("input",{type:"range",min:0,max:100,step:5,value:j.radius||0,onChange:P=>I({radius:Number(P.target.value)}),"aria-label":"Скругление"})}),j.kind==="grid"&&e.jsxs(e.Fragment,{children:[e.jsx(ke,{label:"Сколько людей",children:e.jsx(we,{size:"sm",ariaLabel:"Сколько людей в сетке",value:j.count&&j.count>1?String(j.count):"auto",onChange:P=>I({count:P==="auto"?null:Number(P)}),options:["auto","2","3","4","6","9"].map(P=>({value:P,label:P==="auto"?"Авто":P}))})}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"В сетку встают те, кого вы вывели «В кадр», и кто уже в эфире. Пока никого не выбрали — все с камерой. «Авто» — до 9."}),e.jsx(ke,{label:"Расстановка",children:e.jsx(we,{size:"sm",ariaLabel:"Расстановка",value:j.arrange||"auto",onChange:P=>I({arrange:P}),options:[{value:"auto",label:"Плитка"},{value:"column",label:"Столбик"},{value:"row",label:"Ряд"}]})}),e.jsx(ke,{label:"Форма",children:e.jsx(Ki,{label:"Форма в сетке",value:j.shape||"rounded",onChange:P=>I({shape:P})})}),e.jsx(ke,{label:`Отступ · ${j.gap??16} px`,children:e.jsx("input",{type:"range",min:0,max:60,step:2,value:j.gap??16,onChange:P=>I({gap:Number(P.target.value)}),"aria-label":"Отступ между камерами"})}),e.jsx(we,{size:"sm",ariaLabel:"Видео в сетке",value:j.fit||"cover",onChange:P=>I({fit:P}),options:[{value:"cover",label:"Заполнить"},{value:"contain",label:"Вписать"}]})]}),j.kind!=="grid"&&e.jsx(Fn,{title:"Поверх людей",description:j.above??j.kind!=="shape"?"Лежит над камерами и медиа":"Лежит под камерами — как фон",checked:j.above??j.kind!=="shape",onChange:P=>I({above:P})}),e.jsx(Oe,{value:j.name||"",onChange:P=>I({name:P.target.value.slice(0,60)||void 0}),placeholder:`Название слоя: ${ln[j.kind]}
111`,"aria-label":"Название слоя"}),wi(G(j),P=>ie({elements:re.map(te=>te.id===j.id?Ne(te,P):te)}))]})}return e.jsxs(e.Fragment,{children:[e.jsxs("main",{className:"sn-prod-main",onPointerMove:_e,onPointerUp:ss,onPointerCancel:ss,children:[e.jsxs("div",{className:"sn-sed-head",style:{display:"flex",alignItems:"center",gap:10,minHeight:40,flexWrap:"wrap"},children:[e.jsx("input",{className:"sn-sed-name",style:{width:`calc(${Math.max(8,o.name.length+2)}ch + 20px)`},value:o.name,onChange:j=>oe(I=>({...I,name:j.target.value.slice(0,60)})),"aria-label":"Название сцены",placeholder:"Название сцены"}),e.jsxs("span",{className:bi?"sn-tag sn-tag-red":"sn-tag sn-tag-blue",children:[e.jsx(As,{size:14}),bi?"сцена в эфире — правки увидят после «Сохранить» и нового вывода":"Конструктор · черновик, зрители не видят"]}),e.jsx("div",{className:"sn-st-grow"}),e.jsx(we,{size:"sm",ariaLabel:"Режим",value:L,onChange:j=>{F(j),E.current=null},options:[{value:"edit",label:"Редактор"},{value:"check",label:"Проверка"}]}),e.jsx(Ye,{label:"Отменить (Ctrl+Z)",size:"sm",variant:"ghost",onClick:as,disabled:!u.length,children:e.jsx(Mo,{className:"sn-i sn-i-16"})}),e.jsx(Ye,{label:"Повторить (Ctrl+Shift+Z)",size:"sm",variant:"ghost",onClick:Ze,disabled:!f.length,children:e.jsx(yc,{className:"sn-i sn-i-16"})}),e.jsx(R,{size:"sm",variant:"quiet",onClick:_r,children:"Отмена"}),e.jsx(R,{size:"sm",variant:"primary",icon:e.jsx(Re,{className:"sn-i sn-i-16"}),onClick:()=>We?C(!0):void ms(!0,!1),loading:N,"aria-label":"Сохранить сцену","data-testid":"sed-save",children:"Сохранить"})]}),L==="edit"&&e.jsxs("div",{className:"sn-sed-tools",role:"toolbar","aria-label":"Добавить на сцену",children:[e.jsx("span",{className:"sn-sed-tools-label",children:"Добавить"}),Hr.map(j=>e.jsxs("button",{type:"button",className:"sn-sed-tool",onClick:j.onClick,title:j.hint,"data-testid":`sed-add-${j.key}`,children:[j.icon,e.jsx("span",{children:j.label})]},j.key))]}),e.jsxs("section",{"aria-label":"Холст сцены",style:{padding:20,borderRadius:18,background:"var(--sn-sunk)",display:"flex",flexDirection:"column",gap:14},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",minHeight:36},children:[s.verticalFormat&&e.jsx(we,{size:"sm",ariaLabel:"Кадр",value:rs,onChange:j=>{ge(j),E.current=null},options:[{value:"16:9",label:"Кадр 16:9"},{value:"9:16",label:"Кадр 9:16 · Shorts и Клипы"}]}),e.jsx("span",{className:"sn-st-grow"}),L==="edit"&&e.jsxs("div",{className:"sn-sed-toggles",role:"group","aria-label":"Помощь при расстановке",children:[e.jsxs("button",{type:"button","aria-pressed":z,onClick:()=>M(j=>!j),title:"Прилипать к краям, центру, безопасной зоне и соседям (Alt при перетаскивании — без привязки)",children:[e.jsx(dc,{className:"sn-i sn-i-16"}),"Привязка"]}),e.jsxs("button",{type:"button","aria-pressed":U,onClick:()=>$(j=>!j),title:"Рамка 5% от краёв: площадки и телефоны могут обрезать то, что за ней",children:[e.jsx(ii,{className:"sn-i sn-i-16"}),"Безопасная зона"]}),e.jsxs("button",{type:"button","aria-pressed":v,onClick:()=>B(j=>!j),title:"Сетка с шагом 10%, при перетаскивании — шаг 2,5%",children:[e.jsx(Ao,{className:"sn-i sn-i-16"}),"Сетка"]})]})]}),e.jsxs("div",{ref:ce,className:`sn-sed-canvas${Ie?" is-vertical":""}`,onPointerDown:()=>p(null),"data-testid":"sed-canvas",children:[e.jsx(Nn,{vertical:Ie,compiled:Fe,brand:s.brand,bar:L==="check"&&se!=="none"?{...yt(s,n)||{text:"Бегущая строка или баннер — сцена приподнимется над ними",kind:"banner"},position:se}:null,highlightSlot:D,onSlotClick:ne?void 0:(j,I)=>{I.stopPropagation(),p({type:"slot",index:j})},renderSlotOverlay:L==="edit"&&!ne?Br:void 0}),v&&L==="edit"&&e.jsx("div",{className:"sn-sed-gridlines","aria-hidden":"true"}),U&&L==="edit"&&e.jsx("div",{className:"sn-sed-safe","aria-hidden":"true",children:e.jsx("span",{children:"безопасная зона"})}),X.x.map(j=>e.jsx("div",{className:"sn-sed-guide is-x",style:{left:`${j}%`},"aria-hidden":"true"},`gx-${j}`)),X.y.map(j=>
111e.jsx("div",{className:"sn-sed-guide is-y",style:{top:`${j}%`},"aria-hidden":"true"},`gy-${j}`)),L==="edit"&&de.map((j,I)=>e.jsx("div",{onPointerDown:ne?Ce(I):J({type:"slot",index:I},"move"),className:"sn-sed-hit",style:{left:`${j.x}%`,top:`${j.y}%`,width:`${j.w}%`,height:`${j.h}%`,cursor:ne?"grab":D===I?"move":"pointer",zIndex:D===I?7:5},"aria-label":`Место ${I+1}`,title:ne?"Потяните — сцена станет ручной, и место можно двигать":void 0,"data-testid":`sed-slot-${I}`,children:D===I&&e.jsx("span",{onPointerDown:J({type:"slot",index:I},"resize"),"aria-label":"Изменить размер",className:"sn-sed-handle"})},`slot-${I}`)),L==="edit"&&re.map(j=>{if(j.hidden)return null;const I=G(j),P=(h==null?void 0:h.type)==="el"&&h.id===j.id;return e.jsxs("div",{onPointerDown:J({type:"el",id:j.id},"move"),className:`sn-sed-hit is-el${P?" is-selected":""}${j.locked?" is-locked":""}`,style:{left:`${I.x}%`,top:`${I.y}%`,width:`${I.w}%`,height:`${I.h}%`,zIndex:P?8:j.kind==="grid"?5:j.above??j.kind!=="shape"?6:4},"aria-label":j.name||ln[j.kind],"data-testid":`sed-el-${j.kind}`,children:[P&&e.jsxs("span",{className:"sn-sed-eltag",children:[j.name||ln[j.kind],j.locked?" · закреплён":""]}),P&&!j.locked&&e.jsx("span",{onPointerDown:J({type:"el",id:j.id},"resize"),"aria-label":"Изменить размер",className:"sn-sed-handle"})]},j.id)})]}),L==="edit"?e.jsxs("p",{className:"sn-sed-hints",style:{margin:0},children:[e.jsxs("span",{children:[e.jsx(ko,{size:14})," Клик — выбрать"]}),e.jsxs("span",{children:[e.jsx(Ti,{size:14})," Перетащите — переставить (Alt — без привязки)"]}),e.jsxs("span",{children:[e.jsx(wc,{size:14})," Угол — размер"]}),e.jsxs("span",{children:[e.jsx("span",{className:"sn-kbd",children:"Del"})," убрать"]}),e.jsxs("span",{children:[e.jsx("span",{className:"sn-kbd",children:"Ctrl"}),"+",e.jsx("span",{className:"sn-kbd",children:"Z"})," отменить"]}),e.jsx("span",{children:"Бегущая строка и баннер места не занимают — в эфире сцена сама приподнимется над ними"})]}):e.jsxs("div",{className:"sn-sed-check","data-testid":"sed-check",children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[e.jsx("b",{style:{fontSize:15},children:"Проверка сцены"}),e.jsxs("span",{className:"sn-hint",children:[Ws.filter(j=>j.ok).length," из ",Ws.length," в порядке"]}),e.jsx("span",{className:"sn-st-grow"}),Ws.every(j=>j.ok)&&e.jsx(R,{size:"sm",variant:"primary",icon:e.jsx(Re,{className:"sn-i sn-i-16"}),onClick:()=>We?C(!0):void ms(!0,!1),children:"Всё хорошо — сохранить"})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[e.jsx(nn,{className:"sn-i sn-i-16"}),e.jsx("b",{style:{fontSize:14},children:"Сколько людей в кулисах"}),e.jsx(we,{size:"sm",ariaLabel:"Сколько людей подставить",value:String(S),onChange:j=>O(Number(j)),options:["1","2","3","4","6","9"].map(j=>({value:j,label:j}))}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"на холсте — условные люди вместо настоящих"})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[e.jsx("b",{style:{fontSize:14},children:"Баннер или бегущая строка"}),e.jsx(we,{size:"sm",ariaLabel:"Баннер в проверке",value:se,onChange:A,options:[{value:"none",label:"Нет"},{value:"bottom",label:"Снизу"},{value:"top",label:"Сверху"}]}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"сцена уступает им место, как в эфире"})]}),e.jsx("ul",{className:"sn-sed-checklist",children:Ws.map(j=>e.jsxs("li",{className:j.ok?"is-ok":"is-warn",children:[e.jsx("span",{"aria-hidden":"true",children:j.ok?"✓":"!"}),e.jsx("span",{children:j.text}),!j.ok&&j.fix&&e.jsx(R,{size:"sm",variant:"quiet",onClick:j.fix,children:"Исправить"})]},j.text))})]}),Ie&&e.jsx("p",{className:"sn-sed-hints",style:{margin:0},children:e.jsx("span",{children:"Вертикальная версия для Shorts и Клипов: расстановка здесь не меняет кадр 16:9."})})]}),L==="edit"&&e.jsxs("section",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{className:"sn-prod-sec-head",children:[e.jsx("h2",{style:{margin:0,fontSize:14,fontWeight:600},children:"Готовые раскладки"}),e.jsx("span",{className:"sn-s",children:"меняет места — люди, медиа и элементы останутся"}),e.jsx("div",{className:"sn-st-grow"}),ze(o)&&o.template!=="custom"&&e.jsx(R,{size:"sm",variant:"text",onClick:()=>ie(os(null)),style:{height:28,fontSize:13},children:Ie?"Сбросить кадр 9:16":"Сбросить расстановку"}),e.jsx(R,{size:"sm",variant:"text",icon:e.jsx(oo,{className:"sn-i sn-i-16"}),onClick:ve,style:{height:28,fontSize:13},disabled:!o.slots.length&&!re.length,children:"Пустой кадр"})]}),e.jsx("div",{role:"group","aria-label":"Готовые раскладки",style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(140px, 1fr))",gap:10},children:[...Ea,...Ea.includes(o.template)?[]:[o.template]].map(j=>e.jsxs("button",{type:"button",className:"sn-tpl","aria-pressed":o.template===j,onClick:()=>Z(j),children:[e.jsx(ji,{template:j}),e.jsx("span",{className:"sn-tpl-name",style:{textAlign:"center"},children:Ds[j].short})]},j))})]})]}),e.jsxs("aside",{className:"sn-prod-panel is-open","aria-label":"Свойства сцены",children:[e.jsx("div",{className:"sn-panel-head",children:e.jsx("h2",{children:h?"Свойства":"Сцена"})}),e.jsxs("div",{className:"sn-panel-body",children:[ia,!h&&e.jsxs(e.Fragment,{children:[ne&&e.jsxs("section",{className:"sn-panel-sec","aria-label":"Сцена «Авто»",children:[e.jsx("span",{className:"sn-eyebrow",children:"Сцена «Авто»"}),e.jsxs("span",{className:"sn-hint",style:{fontSize:13},children:["Раскладывает сама всех, кого вы вывели «В кадр» (и кто уже в эфире): один человек — на весь кадр, двое — рядом, трое — в ряд, четверо — 2×2, дальше — плиткой до ",gl,". Экран, слайды или ролик встают слева, люди — справа. Кто отвалился и вернулся — встаёт на место сам."]}),e.jsx("span",{className:"sn-hint",style:{fontSize:13},children:"Сверху можно добавить текст, логотип, подложку, таймер и часы."}),e.jsx(R,{size:"sm",variant:"quiet",icon:e.jsx(Ti,{className:"sn-i sn-i-16"}),onClick:()=>{fe(),p(W.current.slots.length?{type:"slot",index:0}:null)},children:"Расставить вручную"}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Или просто потяните любое место на холсте: сцена станет ручной, места можно двигать и менять."})]}),o.template==="title"&&e.jsxs("section",{className:"sn-panel-sec",children:[e.jsx("span",{className:"sn-eyebrow",children:"Текст заставки"}),e.jsx(ke,{label:"Заголовок",children:e.jsx(Oe,{value:((ki=o.title)==null?void 0:ki.heading)||"",onChange:j=>{var I;return ie({title:{heading:j.target.value.slice(0,120),sub:((I=o.title)==null?void 0:I.sub)||""}})},placeholder:s.room.title})}),e.jsx(ke,{label:"Подзаголовок",children:e.jsx(Oe,{value:((Si=o.title)==null?void 0:Si.sub)||"",onChange:j=>{var I;return ie({title:{heading:((I=o.title)==null?void 0:I.heading)||"",sub:j.target.value.slice(0,200)}})},placeholder:"Скоро начинаем"})})]}),e.jsxs("section",{className:"sn-panel-sec",children:[e.jsx("span",{className:"sn-eyebrow",children:"Фон"}),e.jsxs("div",{className:"sn-sed-colors",role:"group","aria-label":"Фон",children:[bl.map(j=>e.jsx("button",{type:"button",className:"sn-sed-color",style:{background:j,borderRadius:10,width:40,height:40},"aria-label":da[j]||j,title:da[j]||j,"aria-pressed":o.background.kind==="color"&&o.background.value.toLowerCase()===j.toLowerCase(),onClick:()=>ie({background:{kind:"color",value:j}})},j)),o.background.kind==="image"&&e.jsx("span",{className:"sn-sed-color","aria-pressed":"true",title:"Своя картинка",style:{width:40,height:40,borderRadius:10,backgroundImage:`url(${o.background.value})`,backgroundSize:"cover"}}),e.jsx(R,{size:"sm",variant:"quiet",icon:e.jsx(cn,{className:"sn-i sn-i-16"}),loading:b==="bg",onClick:()=>{var j;return(j=xe.current)==null?void 0:j.click()},style:{height:40},children:"Картинка"})]})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Поверх сцены",style:{gap:14},children:[e.jsx("span",{className:"sn-eyebrow",children:"Поверх сцены"}),e.jsxs("div",{className:"sn-ovl-row",style:{minHeight:0},children:[e.jsxs("span",{className:"sn-ovl-text",children:[e.jsx("span",{className:"sn-t",children:"Подписи имён"}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Имя и должность под человеком"})]}),e.jsx(Pe,{checked:o.overlays.lowerThirds,onChange:j=>ie({overlays:{...o.overlays,lowerThirds:j}}),label:"Подписи"})]}),e.jsxs("div",{className:"sn-ovl-row",style:{minHeight:0},children:[e.jsxs("span",{className:"sn-ovl-text",children:[e.jsx("span",{className:"sn-t",children:"Бегущая строка"}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Баннеры из «Графики»"})]}),e.jsx(Pe,{checked:o.overlays.ticker,onChange:j=>ie({overlays:{...o.overlays,ticker:j}}),label:"Баннер"})]}),e.jsxs("div",{className:"sn-ovl-row",style:{minHeight:0},children:[e.jsxs("span",{className:"sn-ovl-text",children:[e.jsx("span",{className:"sn-t",children:"Логотип из бренда"}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"в углу строки"})]}),e.jsx(Pe,{checked:o.overlays.logo,onChange:j=>ie({overlays:{...o.overlays,logo:j}}),label:"Логотип"})]})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"10px 12px",borderRadius:14,border:"1px solid var(--sn-line)",background:"var(--sn-surface-2)"},children:[e.jsx(ft,{className:"sn-i sn-i-16",style:{color:"var(--sn-ink-3)"}}),e.jsx("span",{style:{fontSize:14,fontWeight:600},children:"Горячая клавиша:"}),o.hotkey?e.jsx("span",{className:"sn-kbd",style:{fontSize:13},children:o.hotkey}):e.jsx("span",{className:"sn-hint",children:"нет"}),e.jsx("div",{className:"sn-st-grow"}),e.jsx(R,{size:"sm",variant:"text",onClick:()=>i(o),disabled:We,title:We?"Выберите в окне «Сохранить»":void 0,children:"Изменить"})]})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Слои",children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsx("span",{className:"sn-eyebrow",children:"Слои"}),e.jsx("span",{className:"sn-hint",style:{fontSize:12},children:"сверху — ближе к зрителю"})]}),e.jsxs("ul",{className:"sn-sed-layers",children:[Ni.map(j=>{const I=j.el;return e.jsxs("li",{className:Vr(j.sel)?"is-selected":void 0,children:[e.jsxs("button",{type:"button",className:"sn-sed-layer-main",onClick:()=>p(j.sel),children:[e.jsx("b",{children:j.label}),e.jsx("span",{children:j.sub})]}),I&&e.jsxs("span",{className:"sn-sed-layer-tools",children:[I.kind!=="grid"&&e.jsx(Ye,{label:"Выше",size:"sm",variant:"ghost",onClick:()=>Mn(I.id,1),children:e.jsx(li,{className:"sn-i sn-i-14"})}),I.kind!=="grid"&&e.jsx(Ye,{label:"Ниже",size:"sm",variant:"ghost",onClick:()=>Mn(I.id,-1),children:e.jsx(ri,{className:"sn-i sn-i-14"})}),e.jsx(Ye,{label:I.hidden?"Показать":"Скрыть",size:"sm",variant:"ghost",onClick:()=>pn(I.id,{hidden:!I.hidden}),children:I.hidden?e.jsx(As,{className:"sn-i sn-i-14"}):e.jsx(gs,{className:"sn-i sn-i-14"})}),e.jsx(Ye,{label:I.locked?"Открепить":"Закрепить",size:"sm",variant:"ghost",onClick:()=>pn(I.id,{locked:!I.locked}),children:I.locked?e.jsx(Po,{className:"sn-i sn-i-14"}):e.jsx(go,{className:"sn-i sn-i-14"})})]})]},j.key)}),!Ni.length&&e.jsx("li",{className:"sn-hint",style:{padding:8},children:"Добавьте камеру, медиа или текст сверху холста"})]})]})]})]}),e.jsx("input",{ref:xe,type:"file",accept:"image/png,image/jpeg,image/webp",hidden:!0,onChange:j=>{var P;const I=(P=j.target.files)==null?void 0:P[0];j.target.value="",I&&us(I,"bg")}}),e.jsx("input",{ref:ye,type:"file",accept:"image/png,image/jpeg,image/webp,image/svg+xml",hidden:!0,onChange:j=>{var P;const I=(P=j.target.files)==null?void 0:P[0];j.target.value="",I&&us(I,"img")}}),e.jsx(Ke,{open:q,onClose:()=>C(!1),width:560,icon:e.jsx(Re,{className:"sn-i sn-i-24"}),title:"Сохранить сцену",subtitle:"Сцена сохранится в этой комнате — её можно подготовить заранее, она будет на месте в день эфира",footer:e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"quiet",onClick:()=>C(!1),children:"Назад"}),e.jsx(R,{variant:"primary",loading:N,onClick:()=>void ms(!0),"data-testid":"sed-save-confirm",children:"Сохранить"})]}),children:e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"220px minmax(0, 1fr)",gap:16,alignItems:"start"},children:[e.jsx("div",{style:{borderRadius:10,overflow:"hidden",pointerEvents:"none"},children:e.jsx(Nn,{compiled:Fe,brand:s.brand,mode:"thumb",vertical:!1})}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsx(ke,{label:"Название",children:e.jsx(Oe,{value:o.name,onChange:j=>oe(I=>({...I,name:j.target.value.slice(0,60)})),autoFocus:!0})}),e.jsx(ke,{label:"Горячая клавиша",children:e.jsx(Bs,{value:o.hotkey?String(o.hotkey):"none",onChange:j=>oe(I=>({...I,hotkey:j==="none"?null:Number(j)})),options:[{value:"none",label:"Без клавиши"},...Ur.map(j=>({value:String(j),label:`Клавиша ${j}`}))],ariaLabel:"Горячая клавиша"})}),e.jsx(Rn,{checked:_,onChange:K,label:"Сразу поставить в Подготовку"})]})]})}),e.jsx(Ke,{open:w,onClose:()=>T(!1),width:480,icon:e.jsx(As,{className:"sn-i sn-i-24"}),iconTone:"amber",title:"Выйти из конструктора?",subtitle:"В сцене есть несохранённые изменения",footer
111:e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"text",onClick:()=>{T(!1),a()},"data-testid":"sed-exit-discard",children:"Выйти без сохранения"}),e.jsx(R,{variant:"quiet",onClick:()=>T(!1),children:"Продолжить"}),e.jsx(R,{variant:"primary",loading:N,onClick:()=>{T(!1),We?C(!0):ms(!0,!1)},children:"Сохранить и выйти"})]}),children:e.jsx("p",{className:"sn-hint",style:{margin:0},children:"Правки не видны зрителям, пока сцену не сохранят и не выведут в эфир."})})]})}const Gd=[{key:"lowerThirds",label:"Подписи",icon:e.jsx(Pl,{className:"sn-i sn-i-16","aria-hidden":"true"})},{key:"ticker",label:"Баннер",icon:e.jsx(jc,{className:"sn-i sn-i-16","aria-hidden":"true"})},{key:"logo",label:"Логотип",icon:e.jsx(gt,{className:"sn-i sn-i-16","aria-hidden":"true"})}],Qd=s=>s.trim().split(/\s+/)[0]||s;function Yd({api:s,producer:n,scene:t,onClose:a,onFull:i}){var _,K,L,F,S,O;const[l,r]=d.useState(t),[m,o]=d.useState(!1),[c,u]=d.useState(!1),x=n.scenes.find(z=>z.id===t.id)||null,f=JSON.stringify(l)!==JSON.stringify(x||t),g=t.id===s.program.sourceSceneId,h=t.id===((_=n.previewScene)==null?void 0:_.id),p=d.useMemo(()=>n.compileFor(l),[n,l]),N=Dn(l),k=!!((K=l.elements)!=null&&K.length||(L=l.roles)!=null&&L.length||l.frames),b=!!((F=Ds[l.template])!=null&&F.flexible),y=z=>{z!==l.template&&r(M=>z==="custom"?Rt(M,p):cr(M,z,s.room.title))},w=z=>r(M=>({...M,slots:Ya(M.template,M.slots,z),frames:null,framesVertical:null})),T=z=>{const M=p.slots[z];return(M==null?void 0:M.kind)==="participant"?Qd(M.participant.name):(M==null?void 0:M.kind)==="question"||Ls(l,z)==="question"?"Вопрос":Ls(l,z)==="media"?"Экран":"Пусто"},q=async()=>{const z=l.name.trim()||t.name;o(!0);const M=await n.upsertScene({...l,name:z},g?`Сцена «${z}» сохранена — выведите её в эфир ещё раз, чтобы зрители увидели правки`:`Сцена «${z}» сохранена — она в Подготовке`);o(!1),M&&(g||n.setPreviewId(l.id),a())},C=()=>{f?u(!0):a()};return e.jsxs("div",{className:"sn-psed",role:"dialog","aria-modal":"true","aria-label":"Изменить сцену",children:[e.jsxs("header",{className:"sn-psed-head",children:[e.jsx(Ye,{label:"Назад",variant:"ghost",onClick:C,children:e.jsx(jt,{className:"sn-i sn-i-20"})}),e.jsxs("span",{className:"sn-psed-titles",children:[e.jsx("b",{children:"Изменить сцену"}),e.jsxs("span",{children:[l.name," · ",g?"в эфире":h?"в подготовке":"черновик"]})]})]}),e.jsxs("main",{className:"sn-psed-body",children:[e.jsxs("section",{"aria-label":"Превью сцены",className:"sn-psed-sec",children:[e.jsxs("div",{className:`sn-psed-canvas${g?" is-live":""}`,children:[e.jsx(Nn,{compiled:p,brand:s.brand,bar:yt(s,n),mode:"thumb",className:"sn-scene-thumb"}),l.slots.map((z,M)=>N[M]&&e.jsxs("span",{className:"sn-psed-slot",style:{left:`calc(${N[M].x}% + 6px)`,top:N[M].y<20?6:`calc(${N[M].y}% + 6px)`},children:[M+1," · ",T(M)]},M))]}),e.jsxs("span",{className:`sn-psed-note${g?" is-live":""}`,children:[g?e.jsx(ws,{className:"sn-i sn-i-14","aria-hidden":"true"}):e.jsx(As,{className:"sn-i sn-i-14","aria-hidden":"true"}),g?"Сцена в эфире — правки увидят после сохранения и нового вывода":"Сцена не в эфире — зрители не видят правки"]})]}),e.jsxs("section",{"aria-labelledby":"psed-layout",className:"sn-psed-sec",children:[e.jsx("h2",{id:"psed-layout",children:"Макет"}),e.jsx("div",{className:"sn-psed-layouts",role:"group","aria-labelledby":"psed-layout",children:Ea.map(z=>e.jsxs("button",{type:"button","aria-pressed":l.template===z,onClick:()=>y(z),children:[e.jsx(ji,{template:z}),e.jsx("span",{children:Ds[z].short})]},z))}),k&&e.jsx("span",{className:"sn-hint sn-psed-hint",children:"Сцена собрана в конструкторе: другой макет заново расставит места, текст и картинки останутся."})]}),l.template==="title"?e.jsxs("section",{"aria-labelledby":"psed-title",className:"sn-psed-sec",children:[e.jsx("h2",{id:"psed-title",children:"Заставка"}),e.jsx(ke,{label:"Заголовок",children:e.jsx(Oe,{value:((S=l.title)==null?void 0:S.heading)||"",onChange:z=>r(M=>{var U;return{...M,title:{heading:z.target.value.slice(0,120),sub:((U=M.title)==null?void 0:U.sub)||""}}})})}),e.jsx(ke,{label:"Подзаголовок",children:e.jsx(Oe,{value:((O=l.title)==null?void 0:O.sub)||"",onChange:z=>r(M=>{var U;return{...M,title:{heading:((U=M.title)==null?void 0:U.heading)||"",sub:z.target.value.slice(0,160)}}})})})]}):l.template==="auto"?e.jsxs("section",{"aria-labelledby":"psed-who",className:"sn-psed-sec",children:[e.jsx("h2",{id:"psed-who",children:"Кто в кадре"}),e.jsx("span",{className:"sn-hint",children:"Сцена «Авто» сама раскладывает всех, кого вы вывели «В кадр» в «Людях», и экран или слайды рядом."})]}):e.jsxs("section",{"aria-labelledby":"psed-who",className:"sn-psed-sec",children:[e.jsxs("div",{className:"sn-psed-sechead",children:[e.jsx("h2",{id:"psed-who",children:"Кто в слотах"}),b&&e.jsxs("span",{className:"sn-psed-count",role:"group","aria-label":"Мест в сетке",children:[e.jsx(Ye,{label:"Меньше мест",size:"sm",variant:"quiet",disabled:l.slots.length<=2,onClick:()=>w(l.slots.length-1),children:e.jsx(co,{className:"sn-i sn-i-16"})}),e.jsx("b",{children:l.slots.length}),e.jsx(Ye,{label:"Больше мест",size:"sm",variant:"quiet",disabled:l.slots.length>=9,onClick:()=>w(l.slots.length+1),children:e.jsx(ps,{className:"sn-i sn-i-16"})})]})]}),e.jsx("div",{className:"sn-psed-slots",children:l.slots.map((z,M)=>e.jsxs(ht.Fragment,{children:[e.jsx("span",{className:`sn-psed-num${z.kind==="person"||z.kind==="media"?" is-set":""}`,children:M+1}),e.jsx(Bs,{value:On(z),onChange:U=>r($=>({...$,slots:$.slots.map((v,B)=>B===M?rr(U):v)})),options:or(s,l,M),ariaLabel:`Слот ${M+1}`})]},M))})]}),e.jsxs("section",{"aria-labelledby":"psed-over",className:"sn-psed-sec",children:[e.jsx("h2",{id:"psed-over",children:"Поверх сцены"}),e.jsx("div",{className:"sn-psed-over",role:"group","aria-labelledby":"psed-over",children:Gd.map(z=>e.jsxs("button",{type:"button","aria-pressed":l.overlays[z.key],onClick:()=>r(M=>({...M,overlays:{...M.overlays,[z.key]:!M.overlays[z.key]}})),children:[z.icon,z.label]},z.key))})]})]}),e.jsxs("footer",{className:"sn-psed-foot",children:[e.jsx(R,{variant:"quiet",size:"lg",icon:e.jsx(vc,{className:"sn-i sn-i-18"}),onClick:()=>i(l),children:"В конструкторе"}),e.jsx(R,{variant:"primary",size:"lg",icon:e.jsx(Re,{className:"sn-i sn-i-18"}),loading:m,onClick:()=>void q(),style:{flex:1},children:"Сохранить"})]}),e.jsx(Ke,{open:c,onClose:()=>u(!1),width:480,icon:e.jsx(As,{className:"sn-i sn-i-24"}),iconTone:"amber",title:"Выйти без сохранения?",subtitle:"В сцене есть несохранённые изменения",footer
111:e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"text",onClick:()=>{u(!1),a()},children:"Выйти без сохранения"}),e.jsx(R,{variant:"primary",loading:m,onClick:()=>{u(!1),q()},children:"Сохранить и выйти"})]}),children:e.jsx("p",{className:"sn-hint",style:{margin:0},children:"Правки не видны зрителям, пока сцену не сохранят и не выведут в эфир."})})]})}function Xd({roomId:s,folder:n,sceneCount:t,onClose:a}){const i=Se(),[l,r]=d.useState(""),[m,o]=d.useState(!1);d.useEffect(()=>{n&&r(n.name)},[n]);const c=async()=>{if(!(!n||!l.trim()||m)){o(!0);try{const u=await El.saveFolder(s,n.id,l.trim());i.success(`Шаблон «${u.name}» сохранён — ${u.sceneCount} ${Xe(u.sceneCount,"сцена","сцены","сцен")}. Добавить в другой студии: «Сцены» → «Шаблоны»`),a()}catch(u){i.error(js(u,"Не удалось сохранить шаблон"))}finally{o(!1)}}};return e.jsx(Ke,{open:!!n,onClose:a,width:460,icon:e.jsx(Ut,{className:"sn-i"}),title:"Сохранить папку как шаблон",subtitle:`${t} ${Xe(t,"сцена","сцены","сцен")} с макетами, формой мест, фоном и графикой. Люди и файлы этой комнаты в шаблон не попадут — в другой студии места заполнятся «Авто»`,footer:e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"quiet",onClick:a,children:"Отмена"}),e.jsx(R,{variant:"primary",onClick:()=>void c(),loading:m,disabled:!l.trim()||t===0,children:"Сохранить шаблон"})]}),children:e.jsx(ke,{label:"Название шаблона",hint:"Шаблоны видны в кабинете («Настройки» → «Шаблоны сцен») и в студиях вашего пространства",children:e.jsx(Oe,{value:l,onChange:u=>r(u.target.value.slice(0,60)),onKeyDown:u=>{u.key==="Enter"&&c()},placeholder:"Конгресс — стандартные сцены","aria-label":"Название шаблона","data-autofocus":!0})})})}function Jd(s){try{return new Date(s).toLocaleDateString("ru-RU",{day:"numeric",month:"long"})}catch{return""}}function Zd({open:s,roomId:n,onClose:t,onAdd:a}){const[i,l]=d.useState(null),[r,m]=d.useState(null),[o,c]=d.use
111State(null);d.useEffect(()=>{if(!s)return;let x=!1;return l(null),m(null),El.list(n).then(f=>{x||l(Array.isArray(f==null?void 0:f.items)?f.items:[])}).catch(f=>{x||m(js(f,"Не удалось загрузить шаблоны"))}),()=>{x=!0}},[s,n]);const u=async x=>{c(x.id);const f=await a(x);c(null),f&&t()};return e.jsx(Ke,{open:s,onClose:t,width:560,icon:e.jsx(Ut,{className:"sn-i"}),title:"Шаблоны сцен",subtitle:"Папки сцен, сохранённые в других студиях. Шаблон добавится отдельной папкой — сцены этой студии не изменятся",footer:e.jsx(R,{variant:"quiet",onClick:t,children:"Закрыть"}),children:e.jsx("div",{className:"sn-scn-tpl-list","data-testid":"scene-templates",children:r?e.jsx("p",{className:"sn-error",role:"alert",children:r}):i===null?e.jsxs(e.Fragment,{children:[e.jsx(Zs,{height:64}),e.jsx(Zs,{height:64})]}):i.length===0?e.jsxs("div",{className:"sn-scn-tpl-empty",children:[e.jsx("b",{children:"Шаблонов пока нет"}),e.jsx("span",{children:"Настройте папку сцен и сохраните её: «…» у папки → «Сохранить как шаблон»."})]}):i.map(x=>e.jsxs("div",{className:"sn-scn-tpl","data-template":x.name,children:[e.jsxs("div",{className:"sn-scn-tpl-main",children:[e.jsx("b",{children:x.name}),e.jsxs("span",{className:"sn-hint",children:[x.sceneCount," ",Xe(x.sceneCount,"сцена","сцены","сцен")," · папка «",x.folderName,"»",x.ownerName&&!x.mine?` · ${x.ownerName}`:""," · ",Jd(x.updatedAt)]}),e.jsxs("span",{className:"sn-scn-tpl-scenes",children:[x.scenes.slice(0,6).map(f=>f.name).join(" · "),x.scenes.length>6?" …":""]})]}),e.jsx(R,{size:"sm",variant:"soft",loading:o===x.id,disabled:!!o&&o!==x.id,onClick:()=>void u(x),children:"Добавить"})]},x.id))})})}function Kt({api:s,producer:n,scene:t}){const a=d.useMemo(()=>n.compileFor(t),[n,t]);return e.jsx(Nn,{compiled:a,brand:pi(s,n),bar:yt(s,n),mode:"thumb",className:"sn-scene-thumb"})}function eu({api:s,producer:n,onNew:t,onEdit:a,onRename:i,onHotkey:l,onDelete:r,touch:m=!1}){var se;const o=mn(),c=d.useRef(null),u=mn(),x=d.useRef(null),[f,g]=on(`sn-studio:${s.room.id}:open-folders`,[]),[h,p]=d.useState(null),[N,k]=d.useState(null),[b,y]=d.useState(null),[w,T]=d.useState(null),[q,C]=d.useState(!1),_=n.scenes,K=n.folders,L=s.perms.changeLayouts,F=L&&n.foldersSupported,S=_.filter(A=>!A.folderId||!K.some(X=>X.id===A.folderId)),O=A=>g(X=>X.includes(A)?X.filter(ae=>ae!==A):[...X,A]),z=_.map(A=>A.hotkey).filter(A=>typeof A=="number").sort((A,X)=>A-X),M=z.length?`клавиши ${z[0]}–${z[z.length-1]}`:"назначьте клавиши в меню сцены",U=c.current,$=x.current,v=A=>{var ce;const X=A.id===s.program.sourceSceneId,ae=!X&&A.id===((ce=n.previewScene)==null?void 0:ce.id);return e.jsxs("div",{className:`sn-scene${X?" is-program":ae?" is-preview":""}`,children:[e.jsxs("button",{type:"button",className:"sn-scene-hit","aria-label":`Сцена «${A.name}» в подготовку`,title:"Клик — в подготовку, двойной клик — сразу в эфир",onClick:()=>n.setPreviewId(A.id),onDoubleClick:()=>void n.takeScene(A),children:[e.jsx(Kt,{api:s,producer:n,scene:A}),e.jsxs("span",{className:"sn-scene-label",children:[e.jsx("span",{className:"sn-n",children:A.name}),X?e.jsx(ns,{tone:"live",className:"sn-scene-badge",children:"ЭФИР"}):ae?e.jsx(ns,{className:"sn-scene-badge",style:{background:"var(--sn-blue)",color:"#fff"},children:"ГОТОВА"}):A.hotkey?e.jsx("span",{className:"sn-k",children:A.hotkey}):null]})]}),e.jsx("button",{type:"button",className:"sn-ibtn sn-scene-menu","aria-label":`Действия со сценой «${A.name}»`,onClick:xe=>{c.current=A,o.toggle(xe)},children:e.jsx(zs,{className:"sn-i sn-i-16"})})]},A.id)},B=A=>{const X=_.filter(ye=>ye.folderId===A.id),ae=f.includes(A.id),ce=X.some(ye=>ye.id===s.program.sourceSceneId),xe=!ce&&X.some(ye=>{var be;return ye.id===((be=n.previewScene)==null?void 0:be.id)});return e.jsxs("div",{className:`sn-scn-folder${ae?" is-open":""}`,"data-folder":A.name,children:[e.jsxs("div",{className:"sn-scn-folder-bar",children:[e.jsxs("button",{type:"button",className:"sn-scn-folder-hit","aria-expanded":ae,onClick:()=>O(A.id),title:ae?"Свернуть папку":"Открыть папку",children:[e.jsx(Ps,{className:"sn-i sn-i-16 sn-scn-folder-chev","aria-hidden":"true"}),ae?e.jsx(di,{className:"sn-i sn-i-16","aria-hidden":"true"}):e.jsx(Ml,{className:"sn-i sn-i-16","aria-hidden":"true"}),e.jsx("b",{children:A.name}),e.jsxs("span",{className:"sn-s",children:[X.length," ",Xe(X.length,"сцена","сцены","сцен")]}),ce&&e.jsx(ns,{tone:"live",className:"sn-scene-badge",children:"ЭФИР"}),xe&&e.jsx(ns,{className:"sn-scene-badge",style:{background:"var(--sn-blue)",color:"#fff"},children:"ГОТОВА"})]}),L&&e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":`Новая сцена в папке «${A.name}»`,title:"Новая сцена в эту папку",onClick:()=>t(A.id),children:e.jsx(ps,{className:"sn-i sn-i-16"})}),L&&e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":`Действия с папкой «${A.name}»`,onClick:ye=>{x.current=A,u.toggle(ye)},children:e.jsx(zs,{className:"sn-i sn-i-16"})})]}),ae&&(X.length?e.jsx("div",{className:"sn-prod-grid7 sn-scn-folder-grid",children:X.map(v)}):e.jsx("div",{className:"sn-scn-folder-empty",children:"Папка пуста — «+» создаст сцену здесь, а готовую перенесёт «…» у сцены → «В папку»"}))]},A.id)};return e.jsxs("section",{className:"sn-prod-sec","aria-label":"Сцены",children:[e.jsxs("div",{className:"sn-prod-sec-head",children:[e.jsx("span",{className:"sn-t",children:"Сцены"}),e.jsx("span",{className:"sn-s",children:m?"касание — в подготовку · «…» — сразу в эфир":e.jsxs(e.Fragment,{children:["клик — в подготовку · двойной клик — сразу в эфир · ",M]})}),e.jsx("div",{className:"sn-st-grow"}),F&&e.jsx(R,{size:"sm",variant:"text",icon:e.jsx(Ut,{className:"sn-i sn-i-16"}),onClick:()=>C(!0),style:{height:28,fontSize:13},title:"Добавить папку сцен из шаблона",children:"Шаблоны"}),F&&e.jsx(R,{size:"sm",variant:"text",icon:e.jsx(Bl,{className:"sn-i sn-i-16"}),onClick:()=>k({folder:null}),style:{height:28,fontSize:13},children:"Папка"}),L&&e.jsx(R,{size:"sm",variant:"text",icon:e.jsx(ps,{className:"sn-i sn-i-16"}),onClick:()=>t(null),style:{height:28,fontSize:13},children:"Сцена"})]}),n.cfg.ready?e.jsxs(e.Fragment,{children:[(S.length>0||_.length===0)&&e.jsxs("div",{className:"sn-prod-grid7",children:[S.map(v),L&&_.length===0&&e.jsxs("button",{type:"button",className:"sn-scene-add",onClick:()=>t(null),children:[e.jsx(ps,{className:"sn-i"}),"Первая сцена"]})]}),K.length>0&&e.jsx("div",{className:"sn-scn-folders",children:K.map(B)})]}):e.jsxs("div",{className:"sn-prod-grid7",children:[Array.from({length:5},(A,X)=>e.jsx("div",{className:"sn-scene",style:{height:100},children:e.jsx("div",{className:"sn-skeleton",style:{height:"70%",borderRadius:8}})},X)),n.cfg.error&&e.jsxs("div",{style:{gridColumn:"1 / -1",fontSize:13,color:"var(--sn-red-ink)"},children:[n.cfg.error," ",e.jsx("button",{type:"button",onClick:n.cfg.reload,style:{background:"none",border:0,color:"var(--sn-blue)",fontWeight:600,cursor:"pointer"},children:"Повторить"})]})]}),e.jsx(Cs,{open:o.open&&!!U,onClose:o.close,anchor:o.anchor,placement:"bottom-end",width:260,header:U?e.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center",padding:"6px 8px 10px",borderBottom:"1px solid var(--sn-line)",marginBottom:4},children:[e.jsx("div",{style:{width:72,flex:"none"},children:e.jsx(Kt,{api:s,producer:n,scene:U})}),e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:{fontWeight:600,fontSize:14,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:U.name}),e.jsx("div",{className:"sn-hint",style:{fontSize:12},children:U.hotkey?e.jsxs(e.Fragment,{children:["клавиша ",e.jsx("span",{className:"sn-mono",children:U.hotkey})]}):"без клавиши"})]})]}):null,items:U?[{label:"В подготовку",icon:e.jsx(gs,{className:"sn-i sn-i-16"}),hint:"клик",onSelect:()=>n.setPreviewId(U.id)},{label:"Сразу в эфир",icon:e.jsx(ws,{className:"sn-i sn-i-16"}),hint:"2× клик",onSelect:()=>void n.takeScene(U),disabled:!s.perms.manageStage},{label:"Изменить сцену",icon:e.jsx(ei,{className:"sn-i sn-i-16"}),onSelect:()=>a(U),disabled:!s.perms.changeLayouts},{label:"Дублировать",icon:e.jsx(vt,{className:"sn-i sn-i-16"}),onSelect:()=>void n.duplicateScene(U),disabled:!s.perms.changeLayouts},{label:"Переименовать",icon:e.jsx(Bn,{className:"sn-i sn-i-16"}),onSelect:()=>i(U),disabled:!s.perms.changeLayouts},{label:"Назначить клавишу",icon:e.jsx(ft,{className:"sn-i sn-i-16"}),hint:U.hotkey?String(U.hotkey):void 0,onSelect:()=>l(U),disabled:!s.perms.changeLayouts},...n.foldersSupported?[{label:"В папку…",icon:e.jsx(ic,{className:"sn-i sn-i-16"}),hint:(se=K.find(A=>A.id===U.folderId))==null?void 0:se.name,onSelect:()=>p(U),disabled:!s.perms.changeLayouts}]:[],{type:"separator"},{label:"Удалить сцену",icon:e.jsx(hn,{className:"sn-i sn-i-16"}),danger:!0,onSelect:()=>r(U),disabled:!s.perms.changeLayouts}]:[]}),e.jsx(Cs,{open:u.open&&!!$,onClose:u.close,anchor:u.anchor,placement:"bottom-end",width:240,items:$?[{label:"Новая сцена в папке",icon:e.jsx(ps,{className:"sn-i sn-i-16"}),onSelect:()=>t($.id)},{label:"Переименовать папку",icon:e.jsx(Bn,{className:"sn-i sn-i-16"}),onSelect:()=>k({folder:$})},{label:"Сохранить как шаблон",description:"для других студий, в кабинете",icon:e.jsx(Ut,{className:"sn-i sn-i-16"}),onSelect:()=>T($)},{type:"separator"},{label:"Удалить папку",description:"сцены останутся, без папки",icon:e.jsx(hn,{className:"sn-i sn-i-16"}),danger:!0,onSelect:()=>y($)}]:[]}),e.jsx(Xd,{roomId:s.room.id,folder:w,sceneCount:w?_.filter(A=>A.folderId===w.id).length:0,onClose:()=>T(null)}),e.jsx(Zd,{open:q,roomId:s.room.id,onClose:()=>C(!1),onAdd:async A=>{const X=await n.addTemplate(A);return X&&g(ae=>ae.includes(X)?ae:[...ae,X]),!!X}}),e.jsx(su,{open:!!N,folder:(N==null?void 0:N.folder)||null,onClose:()=>k(null),onSave:async A=>
111{if(N!=null&&N.folder)return n.renameFolder(N.folder.id,A);const X=await n.createFolder(A);return X&&g(ae=>[...ae,X]),!!X}}),e.jsx(nu,{scene:h,folders:K,onClose:()=>p(null),onMove:async(A,X,ae)=>{if(ae){const xe=await n.createFolder(ae,[A.id]);return xe&&g(ye=>[...ye,xe]),!!xe}const ce=await n.moveSceneToFolder(A,X);return ce&&X&&g(xe=>xe.includes(X)?xe:[...xe,X]),ce}}),e.jsx(yn,{open:!!b,onClose:()=>y(null),onConfirm:()=>{b&&n.deleteFolder(b.id),y(null)},title:b?`Удалить папку «${b.name}»?`:"",description:"Сцены из неё останутся — просто без папки",confirmLabel:"Удалить папку"})]})}function su({open:s,folder:n,onClose:t,onSave:a}){const[i,l]=d.useState(""),[r,m]=d.useState(!1);d.useEffect(()=>{s&&l((n==null?void 0:n.name)||"")},[s,n]);const o=async()=>{if(!i.trim())return;m(!0);const c=await a(i);m(!1),c&&t()};return e.jsx(Ke,{open:s,onClose:t,width:440,title:n?"Переименовать папку":"Новая папка сцен",subtitle:n?void 0:"Например, «Стандартные», «Панель спикеров», «Финал». Сцены переносятся в неё через «…» → «В папку»",footer:e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"quiet",onClick:t,children:"Отмена"}),e.jsx(R,{variant:"primary",onClick:()=>void o(),loading:r,disabled:!i.trim(),children:n?"Сохранить":"Создать папку"})]}),children:e.jsx(ke,{label:"Название папки",children:e.jsx(Oe,{value:i,onChange:c=>l(c.target.value.slice(0,40)),onKeyDown:c=>{c.key==="Enter"&&o()},placeholder:"Стандартные","data-autofocus":!0})})})}function nu({scene:s,folders:n,onClose:t,onMove:a}){const[i,l]=d.useState("none"),[r,m]=d.useState(""),[o,c]=d.use
111State(!1);d.useEffect(()=>{s&&(l(s.folderId&&n.some(f=>f.id===s.folderId)?s.folderId:"none"),m(""))},[s]);const u=async()=>{if(!s||i==="new"&&!r.trim())return;c(!0);const f=await a(s,i==="none"||i==="new"?null:i,i==="new"?r:void 0);c(!1),f&&t()},x=[{id:"none",label:"Без папки"},...n.map(f=>({id:f.id,label:f.name})),{id:"new",label:"Новая папка…"}];return e.jsxs(Ke,{open:!!s,onClose:t,width:440,title:s?`«${s.name}» — в папку`:"",footer:e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"quiet",onClick:t,children:"Отмена"}),e.jsx(R,{variant:"primary",onClick:()=>void u(),loading:o,disabled:i==="new"&&!r.trim(),children:"Перенести"})]}),children:[e.jsx("div",{className:"sn-scn-folder-pick",role:"radiogroup","aria-label":"Папка",children:x.map(f=>e.jsxs("button",{type:"button",role:"radio","aria-checked":i===f.id,className:"sn-scn-folder-opt",onClick:()=>l(f.id),children:[f.id==="new"?e.jsx(Bl,{className:"sn-i sn-i-16"}):f.id==="none"?e.jsx("span",{className:"sn-scn-folder-dot"}):e.jsx(Ml,{className:"sn-i sn-i-16"}),e.jsx("span",{children:f.label})]},f.id))}),i==="new"&&e.jsx(ke,{label:"Название новой папки",children:e.jsx(Oe,{value:r,onChange:f=>m(f.target.value.slice(0,40)),onKeyDown:f=>{f.key==="Enter"&&u()},placeholder:"Например, «Панель спикеров»",autoFocus:!0})})]})}const tu=3e4,au=2*6e4,iu=3,lu=5,ru=10*6e4;function ou(s){const{qna:n}=Vs(),t=s.aiCoHost.on&&s.aiCoHost.by===s.me.peerId&&s.live.isLive,a=d.useRef({lastAt:0,hinted:new Set,queueAt:0,monologueBy:""}),i=d.useRef(s);i.current=s;const l=d.useRef(n.questions);l.current=n.questions,d.useEffect(()=>{if(!t)return;const r=()=>{const o=i.current,c=a.current,u=Date.now();if(u-c.lastAt<au)return;const x=cu(o,l.current,c,u);if(!x)return;c.lastAt=u;const f=o.participants.filter(h=>{var p;return Os(h)==="host"&&h.id!==((p=o.me.participant)==null?void 0:p.id)}),g=`AI-соведущий: ${x}`.slice(0,200);f.length?f.forEach(h=>void o.sendCue(o.stageIdOf(h),g,"text")):o.sendCue(null,g,"text")},m=window.setInterval(r,tu);return()=>window.clearInterval(m)},[t])}function cu(s,n,t,a){var o;const i=n.filter(c=>c.status==="new"||c.status==="selected"),l=i.filter(c=>c.votes>=iu&&!t.hinted.has(c.id)).sort((c,u)=>u.votes-c.votes)[0];if(l){t.hinted.add(l.id);const c=l.text.length>110?`${l.text.slice(0,107)}…`:l.text;return`зал поддержал вопрос (${l.votes}): «${c}»`}if(i.length>=lu&&a-t.queueAt>10*6e4)return t.queueAt=a,`в очереди ${i.length} вопросов без ответа — самое время ответить`;const r=((o=s.transcriptInfo)==null?void 0:o.lines)||[],m=r[r.length-1];if(m!=null&&m.speakerName&&typeof m.startOffsetMs=="number"){let c=m.startOffsetMs;for(let x=r.length-1;x>=0;x-=1){const f=r[x];if(f.speakerName!==m.speakerName||typeof f.startOffsetMs!="number")break;c=f.startOffsetMs}const u=`${m.speakerName}:${c}`;if(m.startOffsetMs-c>=ru&&t.monologueBy!==u)return t.monologueBy=u,`${m.speakerName} говорит уже ${Math.round((m.startOffsetMs-c)/6e4)} мин — можно предложить вопросы из зала`}return null}function Gi(s,n){var i;const t=((i=s.sourceRef)==null?void 0:i.displayTime)||s.sourceTimestamp||null;if(n==="decision")return{time:t,text:String(s.title||s.text||s.details||"").trim()};const a=s.assignee?`${s.assignee} — `:"";return{time:t,text:`${a}${String(s.title||s.text||"").trim()}`}}function ma({title:s,items:n,empty:t}){const[a,i]=d.useState(!1),l=a?n:n.slice(0,2);return e.jsxs("div",{className:"sn-shw-notes",children:[e.jsxs("div",{className:"sn-shw-notes-head",children:[e.jsx("b",{children:s}),e.jsx("span",{className:"sn-shw-count sn-mono",children:n.length}),n.length>2&&e.jsx("button",{type:"button",className:"sn-shw-link",onClick:()=>i(r=>!r),children:a?"свернуть":`ещё ${n.length-2}`})]}),l.length?l.map((r,m)=>e.jsxs("div",{className:"sn-shw-note-line",children:[e.jsx("span",{className:"sn-mono",children:r.time||"—"}),e.jsx("span",{children:r.text})]},m)):e.jsx("span",{className:"sn-hint",style:{fontSize:13},children:t})]})}function du({api:s,workspaceId:n}){const t=Se(),a=ts(15e3),{qna:i}=Vs(),l=s.transcriptInfo,r=s.transcriptEnabled,m=l!=null&&l.startedAt?Math.max(0,Math.floor((a-l.startedAt)/6e4)):null,o=(l==null?void 0:l.lines)||[],c=ni(s,"aiSummary"),[u,x]=d.useState(null),[f,g]=d.useState(!1),[h,p]=d.useState(null),N=o.length>0;d.useEffect(()=>{if(!N||!c)return;let S=!1;return Ae.get(`ai/summarize/${encodeURIComponent(s.room.id)}/latest`).then(O=>{S||x(O)}).catch(()=>{}),()=>{S=!0}},[s.room.id,N,c]);const k=d.useRef(o);k.current=o;const b=d.useRef(!1),y=d.useRef({at:Date.now(),lines:0}),w=d.useRef(async()=>{});d.useEffect(()=>{if(!r||!c)return;const S=window.setInterval(()=>{const O=y.current;b.current||k.current.length-O.lines<15||Date.now()-O.at<4*6e4||w.current(!0)},3e4);return()=>window.clearInterval(S)},[r,c]);const T=async(S=!1)=>
111{if(!(!o.length||!c)){b.current=!0,y.current={at:Date.now(),lines:o.length},g(!0),p(null);try{const O=await Ae.post(`ai/summarize/${encodeURIComponent(s.room.id)}`,{transcript:o.slice(-600).map((z,M)=>({speakerName:z.speakerName||"Спикер",text:z.text,startTime:typeof z.startOffsetMs=="number"?z.startOffsetMs:M,timestamp:z.timestamp})),config:{title:s.room.title,...n?{workspaceId:n}:{}}});x(O),S||t.success("Заметки обновлены")}catch(O){p(O instanceof Xa&&O.status>=500?"AI сейчас недоступен — попробуйте через минуту":js(O,"Не удалось обновить заметки"))}finally{b.current=!1,g(!1)}}};w.current=T;const q=s.perms.manageStage,C=s.aiCoHost.on&&s.aiCoHost.by===s.me.peerId,_=((u==null?void 0:u.keyDecisions)||[]).map(S=>Gi(S,"decision")).filter(S=>S.text),K=((u==null?void 0:u.actionItems)||[]).map(S=>Gi(S,"task")).filter(S=>S.text),F=i.questions.filter(S=>S.status!=="answered"&&S.status!=="hidden").slice(0,20).map(S=>{const O=Date.parse(S.createdAt),z=s.liveSince&&Number.isFinite(O)?Math.max(0,Math.floor((O-s.liveSince)/1e3)):null;return{time:z!==null?`${String(Math.floor(z/60)).padStart(2,"0")}:${String(z%60).padStart(2,"0")}`:null,text:S.text}});return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"sn-panel-sec","aria-label":"Помощники",children:[e.jsxs("div",{className:"sn-shw-ai",children:[e.jsx("span",{className:"sn-shw-mix-ico is-blue",children:e.jsx(Eo,{className:"sn-i sn-i-16"})}),e.jsxs("div",{children:[e.jsx("b",{children:"Стенографист"}),e.jsx("span",{className:r?"sn-shw-status is-live":"sn-hint",children:r?e.jsxs(e.Fragment,{children:[e.jsx("i",{}),(l==null?void 0:l.connected)===!1?"подключаемся…":`идёт расшифровка${m!==null?` · ${m} мин`:""}`]}):"выключен — расшифровки и итогов не будет"})]}),e.jsx(Pe,{checked:r,onChange:()=>s.toggleTranscript(),label:"Стенографист",disabled:!s.perms.manageStage&&!s.perms.recording})]}),e.jsxs("div",{className:s.captionsOnAir?"sn-shw-ai":"sn-shw-ai is-off",children:[e.jsx("span",{className:s.captionsOnAir?"sn-shw-mix-ico is-blue":"sn-shw-mix-ico",children:e.jsx(Pl,{className:"sn-i sn-i-16"})}),e.jsxs("div",{children:[e.jsx("b",{children:"Субтитры в эфире"}),e.jsx("span",{className:s.captionsOnAir?"sn-shw-status is-live":"sn-hint",children:s.captionsOnAir?e.jsxs(e.Fragment,{children:[e.jsx("i",{}),"речь идёт строкой поверх картинки"]}):"строка стенографиста поверх картинки — на SNICH и всех площадках"})]}),e.jsx(Pe,{checked:s.captionsOnAir,onChange:S=>{s.setCaptionsOnAir(S),S&&!r&&t.success("Стенографист включён — субтитры появятся с первой репликой")},label:"Субтитры в эфире",disabled:!q})]}),e.jsxs("div",{className:s.viewerTranslation?"sn-shw-ai":"sn-shw-ai is-off",children:[e.jsx("span",{className:s.viewerTranslation?"sn-shw-mix-ico is-blue":"sn-shw-mix-ico",children:e.jsx(zo,{className:"sn-i sn-i-16"})}),e.jsxs("div",{children:[e.jsx("b",{children:"Перевод для зрителей"}),e.jsx("span",{className:"sn-hint",children:s.viewerTranslation?"зрители выбирают English или 中文 в меню субтитров":"зрителям доступны только русские субтитры"})]}),e.jsx(Pe,{checked:s.viewerTranslation,onChange:S=>s.setViewerTranslation(S),label:"Перевод для зрителей",disabled:!q})]}),e.jsxs("div",{className:s.aiCoHost.on?"sn-shw-ai":"sn-shw-ai is-off",children:[e.jsx("span",{className:s.aiCoHost.on?"sn-shw-mix-ico is-blue":"sn-shw-mix-ico",children:e.jsx(mo,{className:"sn-i sn-i-16"})}),e.jsxs("div",{children:[e.jsx("b",{children:"AI-соведущий"}),e.jsx("span",{className:"sn-hint",children:s.aiCoHost.on?C?"подсказывает ведущей сигналами: вопросы зала, очередь, долгий монолог":"включён другим продюсером — подсказки идут с его студии":"подсказки ведущей по ходу эфира: вопросы зала, очередь, долгий монолог"})]}),e.jsx(Pe,{checked:s.aiCoHost.on,onChange:S=>s.setAICoHost(S),label:"AI-соведущий",disabled:!q})]})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Живые заметки",children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsx("span",{className:"sn-eyebrow",children:"Живые заметки"}),e.jsx(R,{size:"xs",variant:"text",icon:e.jsx(zl,{className:"sn-i",style:{width:14,height:14}}),onClick:()=>void T(),loading:f,disabled:!o.length||!c,title:"Заметки обновляются сами каждые несколько минут",children:"Обновить"})]}),!c&&e.jsxs("div",{className:"sn-shw-note",children:[ti.aiSummary," — решения и задачи не собираются."]}),c&&!o.length&&e.jsx("span",{className:"sn-hint",style:{fontSize:13},children:r?"Решения и задачи появятся, когда стенографист услышит первые реплики.":"Включите стенографиста — по расшифровке AI соберёт решения и задачи."}),h&&e.jsx("div",{className:"sn-shw-note is-warn",children:h}),c&&e.jsx(ma,{title:"Решения",items:_,empty:o.length?"Соберутся из расшифровки через пару минут — или нажмите «Обновить»":"Пока нет"}),e.jsx(ma,{title:"Вопросы без ответа",items:F,empty:"Все вопросы зала разобраны"}),c&&e.jsx(ma,{title:"Задачи",items:K,empty:o.length?"Появятся со следующим обновлением заметок":"Пока нет"})]}),e.jsx("div",{className:"sn-shw-panel-foot",children:e.jsxs("span",{className:"sn-hint",style:{fontSize:13,display:"flex",gap:8,alignItems:"flex-start"},children:[e.jsx(Vn,{className:"sn-i sn-i-16",style:{color:"var(--sn-blue)",flex:"none",marginTop:2}}),c?"Итоги появятся после эфира в «Записях и итогах» — запись, расшифровка и задачи.":"После эфира в «Записях и итогах» будут запись и расшифровка."]})})]})}const ha=s=>Array.isArray(s)?s:[];
111function uu(s,n,t){const[a,i]=d.useState(null),[l,r]=d.useState(null),[m,o]=d.useState([]),[c,u]=d.useState([]),[x,f]=d.useState([]),[g,h]=d.useState(null),[p,N]=d.useState(!0),[k,b]=d.useState(null),[y,w]=d.useState(0),T=d.useRef(t||null),q=d.useCallback(async K=>{try{const L=await Ae.get("/api/v1/streams/destinations",{query:{workspaceId:K||void 0}});f(ha(L).filter(F=>F.provider!=="snich_live")),h(null)}catch(L){h(js(L,"Не удалось загрузить площадки"))}},[]);d.useEffect(()=>{if(!n||!s)return;let K=!1;return N(!0),(async()=>{var z,M;const[L,F,S,O]=await Promise.allSettled([Ae.get(`events/${encodeURIComponent(s)}`),Ae.get(`rooms/${encodeURIComponent(s)}/settings`),Ae.get(`rooms/${encodeURIComponent(s)}/program`),Ae.get(`rooms/${encodeURIComponent(s)}/team`)]);K||(L.status==="fulfilled"&&(i(L.value),(z=L.value)!=null&&z.workspaceId&&(T.current=L.value.workspaceId)),F.status==="fulfilled"&&r(F.value),S.status==="fulfilled"&&o(ha((M=S.value)==null?void 0:M.items)),O.status==="fulfilled"&&u(ha(O.value)),b(L.status==="rejected"?js(L.reason,"Не удалось загрузить данные эфира"):null),await q(T.current),K||N(!1))})(),()=>{K=!0}},[s,n,y,q]);const C=d.useCallback(()=>w(K=>K+1),[]),_=d.useCallback(()=>q(T.current),[q]);return d.useMemo(()=>({event:a,settings:l,program:m,team:c,destinations:x,destinationsError:g,loading:p,error:k,reload:C,reloadDestinations:_}),[a,l,m,c,x,g,p,k,C,_])}function mu(s,n){const[t,a]=d.useState(void 0);return d.useEffect(()=>{if(!s)return;const i=l=>a((l==null?void 0:l.rundown)??null);return s.on("studio:rundown-changed",i),()=>{s.off("studio:rundown-changed",i)}},[s]),[t!==void 0?t:n??null,a]}function hu(s,n){try{const t=window.localStorage.getItem(s);if(!t)return n;const a=JSON.parse(t);return n&&typeof n=="object"&&!Array.isArray(n)&&a&&typeof a=="object"&&!Array.isArray(a)?{...n,...a}:a}catch{return n}}function xu(s,n){try{window.localStorage.setItem(s,JSON.stringify(n))}catch{}}const xa="sn-local-state";function sn(s,n){const[t,a]=d.useState(()=>hu(s,n)),i=d.useRef(t);d.useEffect(()=>{const r=m=>{const o=m.detail;!o||o.key!==s||Object.is(o.value,i.current)||(i.current=o.value,a(o.value))};return window.addEventListener(xa,r),()=>window.removeEventListener(xa,r)},[s]);const l=d.useCallback(r=>{const m=typeof r=="function"?r(i.current):r;i.current=m,xu(s,m),a(m),window.dispatchEvent(new CustomEvent(xa,{detail:{key:s,value:m}}))},[s]);return[t,l]}function ys(s){return s.kind==="video_file"?"video":s.kind==="presentation"?s.id.startsWith("img-")?"image":"slides":s.kind==="image"?"image":"screen"}function fa(s){const n=/\.([a-z0-9]{2,5})$/i.exec(s||"");return n?n[1].toUpperCase():""}function qs(s){const n=Math.max(0,Math.round(s));return`${Math.floor(n/60)}:${String(n%60).padStart(2,"0")}`}function dr(s,n){const t=s.videoFile;if(!t)return 0;const a=t.currentTime||0,i=t.isPlaying&&t.lastSyncedAt?(n-t.lastSyncedAt)/1e3:0;return Math.max(0,Math.min(t.duration||1/0,a+i))}function Da(s){var a,i,l,r,m;const n=s.participant,t=ys(s);if(t==="slides"){const o=((a=n.presentation)==null?void 0:a.slides.length)||0,c=fa(((i=n.presentation)==null?void 0:i.sourceFileName)||n.name)||"PDF";return o?`${c} · ${o} ${Xe(o,"слайд","слайда","слайдов")}`:`${c} · готовим слайды`}if(t==="video"){const o=((l=n.videoFile)==null?void 0:l.duration)||0;return`${fa(((r=n.videoFile)==null?void 0:r.sourceFileName)||n.name)||"Видео"}${o?` · ${qs(o)}`:""} · со звуком`}return t==="image"?`${fa(((m=n.presentation)==null?void 0:m.sourceFileName)||n.name)||"Картинка"} · картинка`:s.subtitle}async function gi(s,n,t,a){const i=n.compileFor(t),l=n.wantedTicker;l&&await s.ensureBanner(l);const r=Qa(i,a,(l==null?void 0:l.id)??null);return r.brandPatch={showNames:i.brandPatch.showNames!==!1&&n.prefs.names,showHeadlines:i.brandPatch.showHeadlines!==!1&&n.prefs.names,showLogo:i.brandPatch.showLogo!==!1&&n.prefs.logo},(await s.take(r)).success}function ur({api:s,producer:n,participant:t,onAir:a}){if(a){const l=n.coverId===t.id;return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e.jsx(R,{variant:"quiet",block:!0,icon:e.jsx(ls,{className:"sn-i sn-i-16"}),onClick:()=>void n.removeFromProgram(t),disabled:!s.perms.manageStage,children:"Убрать из эфира"}),l&&e.jsx("span",{className:"sn-hint",style:{fontSize:12.5,textAlign:"center"},children:"Файл на весь кадр — спикеры вернутся в кадр, когда уберёте его"})]})}return t.type==="presentation"&&!t.id.startsWith("img-")?e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e.jsx(R,{variant:"primary",block:!0,onClick:()=>void n.putOnAir(t),disabled:!s.perms.manageStage,children:"Показать в эфире"}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5,textAlign:"center"},children:"В место для презентации — спикеры остаются в кадре"}),e.jsx(R,{variant:"text",size:"sm",onClick:()=>void n.coverWithMedia(t),disabled:!s.perms.manageStage,style:{alignSelf:"center"},children:"На весь кадр, поверх спикеров"})]}):e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[e.jsx(R,{variant:"primary",block:!0,onClick:()=>void n.coverWithMedia(t),disabled:!s.perms.manageStage,children:"Показать в эфире"}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5,textAlign:"center"},children:"На весь кадр, поверх всего — спикеры останутся на сцене"}),e.jsx(R,{variant:"text",size:"sm",onClick:()=>void n.putOnAir(t),disabled:!s.perms.manageStage,style:{alignSelf:"center"},children:"В текущую сцену, рядом со спикерами"})]})}function mr({item:s}){var l,r,m,o,c,u,x;const n=s.participant,t=ys(s),a=((r=(l=n.presentation)==null?void 0:l.slidesLow)==null?void 0:r[n.presentation.currentSlide])||((c=(m=n.presentation)==null?void 0:m.slides)==null?void 0:c[((o=n.presentation)==null?void 0:o.currentSlide)??0]),i=typeof n.uploadProgress=="number"&&n.uploadProgress<100;return e.jsxs("span",{className:`sn-shw-mthumb is-${t}`,"aria-hidden":"true",children:[(t==="slides"||t==="image")&&a?e.jsx("img",{src:a,alt:"",loading:"lazy"}):null,t==="video"&&((u=n.videoFile)!=null&&u.url)?e.jsx("video",{src:`${n.videoFile.url}#t=1`,muted:!0,preload:"metadata"}):null,!a&&t!=="video"&&(t==="screen"?e.jsx(Cl,{className:"sn-i"}):e.jsx(Xt,{className:"sn-i"})),t==="video"&&((x=n.videoFile)!=null&&x.duration)?e.jsx("span",{className:"sn-shw-mthumb-dur sn-mono",children:qs(n.videoFile.duration)}):null,i&&e.jsx("span",{className:"sn-shw-mthumb-meter",style:{transform:`scaleX(${(n.uploadProgress||0)/100})`}})]})}function fu({api:s,producer:n,openId:t,setOpenId:a,onUpload:i,video:l,data:r=null}
111){const m=Se(),[o,c]=d.useState(null),[u,x]=d.useState(!1),[f,g]=d.useState(""),[h,p]=d.useState(null),N=xi(s),[k,b]=on(`sn-studio:${s.room.id}:media-folders`,{}),y=n.mediaSpeaker,w=d.useRef(y);d.useEffect(()=>{y&&y!==w.current&&a(null),w.current=y},[y,a]);const T=t&&s.media.find(A=>A.id===t)||null;if(T){const A=ys(T);if(A==="slides"||A==="image")return e.jsx(yu,{api:s,producer:n,item:T,onBack:()=>a(null),data:r});if(A==="video")return e.jsx(Nu,{api:s,producer:n,item:T,onBack:()=>a(null),onOpen:a,video:l})}const q=[{key:"slides",title:"Презентации",count:A=>`${A} ${Xe(A,"файл","файла","файлов")}`},{key:"video",title:"Видео",count:A=>`${A} ${Xe(A,"ролик","ролика","роликов")}`},{key:"image",title:"Изображения",count:A=>`${A} ${Xe(A,"файл","файла","файлов")}`},{key:"screen",title:"Экран и доска",count:A=>`${A}`}],C=async A=>{if(!n.programIds.includes(A.id)){if(!s.perms.manageStage){m.show("Выводить в эфир может продюсер");return}const ae=ys(A);ae==="screen"||ae==="slides"?await n.putOnAir(A.participant):await n.coverWithMedia(A.participant)}ys(A)!=="screen"&&a(A.id)},_=(A,X)=>{const ae=n.programIds.includes(X.id),ce=ys(X),xe=[{label:"В подготовку",description:"соберите кадр и выведите кнопкой",icon:e.jsx(Hn,{className:"sn-i sn-i-16"}),onSelect:()=>n.addToPreview(X.participant),disabled:!n.previewScene}];if(!ae&&ce==="slides"&&xe.push({label:"На весь кадр",description:"поверх всех, спикеры останутся на сцене",icon:e.jsx(Oo,{className:"sn-i sn-i-16"}),onSelect:()=>void n.coverWithMedia(X.participant),disabled:!s.perms.manageStage}),ae&&xe.push({label:"Убрать из эфира",icon:e.jsx(ls,{className:"sn-i sn-i-16"}),onSelect:()=>void n.removeFromProgram(X.participant)}),ce!=="screen"&&xe.push({label:"Управлять",icon:e.jsx(Xs,{className:"sn-i sn-i-16"}),onSelect:()=>a(X.id)}),ce!=="screen"){const ye=N.speakerOf(X.participant);xe.push({label:"Чей файл…",description:ye?ye.name:"не указан — общий",icon:e.jsx(en,{className:"sn-i sn-i-16"}),onSelect:()=>p(X),disabled:!s.perms.manageStage&&!s.perms.mediaTools})}xe.push({type:"separator"}),xe.push({label:"Удалить из студии",icon:e.jsx(ls,{className:"sn-i sn-i-16"}),danger:!0,onSelect:()=>s.removeMedia(X.id),disabled:!s.perms.mediaTools&&!X.participant.isLocal}),c({anchor:A,items:xe})},K=A=>{A.preventDefault(),x(!1);const X=Array.from(A.dataTransfer.files||[]);X.length&&i(X)},L=s.media.filter(A=>ys(A)!=="screen"),S=Di(L,N).map(A=>({key:A.key??rn,name:A.name,count:A.items.length})),O=S.some(A=>A.key!==rn)&&L.length>=3,z=y&&S.find(A=>A.key===y)||null,M=vs(f),U=A=>{var ae;if(!M)return!0;const X=N.speakerOf(A.participant);return[A.title,X==null?void 0:X.name,N.addedBy(A.participant),(ae=A.participant.presentation)==null?void 0:ae.sourceFileName].some(ce=>vs(ce).includes(M))},$=A=>{if(!z)return!0;const X=N.speakerOf(A.participant);return z.key===rn?!X&&ys(A)!=="screen":(X==null?void 0:X.key)===z.key},v=s.media.filter(A=>$(A)&&U(A)),B=A=>n.programIds.includes(A.id)||n.previewIds.has(A.id),se=(A,X)=>e.jsx(ju,{api:s,producer:n,item:A,speaker:X?N.speakerOf(A.participant):null,addedBy:N.addedBy(A.participant),onShow:()=>void C(A),onMenu:ae=>_(ae,A)},A.id);return e.jsxs(e.Fragment,{children:[!s.media.length&&e.jsx("div",{className:"sn-shw-note",children:"Здесь будут презентации, ролики и картинки для эфира. Загрузите файл — он появится и в кулисах."}),(O||L.length>6)&&e.jsxs("section",{className:"sn-panel-sec sn-shw-spk","aria-label":"Файлы по спикерам",children:[L.length>6&&e.jsx(Oe,{inputSize:"sm",icon:e.jsx(ea,{className:"sn-i sn-i-16"}),placeholder:"Файл или спикер",value:f,onChange:A=>g(A.target.value),"aria-label":"Найти файл или спикера"}),O&&e.jsxs("div",{className:"sn-shw-spk-chips",role:"group","aria-label":"Спикеры",children:[e.jsxs("button",{type:"button",className:"sn-chip","aria-pressed":!z,onClick:()=>n.setMediaSpeaker(null),children:["Все ",e.jsx("span",{className:"sn-mono",children:L.length})]}),S.map(A=>e.jsxs("button",{type:"button",className:"sn-chip","aria-pressed":(z==null?void 0:z.key)===A.key,title:A.key===rn?"Файлы без спикера — загружены командой":`Файлы спикера: ${A.name}`,onClick:()=>n.setMediaSpeaker((z==null?void 0:z.key)===A.key?null:A.key),children:[A.key===rn?A.name:pu(A.name)," ",e.jsx("span",{className:"sn-mono",children:A.count})]},A.key))]})]}),z?e.jsxs("section",{className:"sn-panel-sec","aria-label":`Файлы: ${z.name}`,children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsx("span",{className:"sn-eyebrow",children:z.key===rn?"Общие файлы":"Файлы спикера"}),e.jsx("button",{type:"button",className:"sn-shw-link",onClick:()=>n.setMediaSpeaker(null),children:"Все файлы"})]}),z.key!==rn&&e.jsx("b",{style:{fontSize:15},children:z.name}),v.length?v.map(A=>se(A,!1)):e.jsx("span",{className:"sn-hint",children:"Ничего не нашлось"})]}):q.map(A=>{const X=v.filter(ce=>ys(ce)===A.key);if(!X.length)return null;const ae=A.key==="slides"&&X.length>6&&!M;return e.jsxs("section",{className:"sn-panel-sec",children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsx("span",{className:"sn-eyebrow",children:A.title}),e.jsx("span",{className:"sn-s",children:A.count(X.length)})]}),ae?Di(X,N).map(ce=>{const xe=ce.key??rn,ye=ce.items.some(B),be=k[xe]??ye;return e.jsxs("div",{className:`sn-shw-folder${be?" is-open":""}`,children:[e.jsxs("button",{type:"button",className:"sn-shw-folder-head","aria-expanded":be,onClick:()=>b(ge=>({...ge,[xe]:!be})),children:[be?e.jsx(Gn,{className:"sn-i sn-i-16"}):e.jsx(Ps,{className:"sn-i sn-i-16"}),ce.key?e.jsx(en,{className:"sn-i sn-i-16"}):e.jsx(di,{className:"sn-i sn-i-16"}),e.jsx("b",{children:ce.name}),e.jsx("span",{className:"sn-mono",children:ce.items.length}),ce.items.some(ge=>n.programIds.includes(ge.id))?e.jsx("span",{className:"sn-shw-media-state is-live",children:"в эфире"}):ce.items.some(ge=>n.previewIds.has(ge.id))?e.jsx("span",{className:"sn-shw-media-state",children:"в подготовке"}):null]}),be&&e.jsx("div",{className:"sn-shw-folder-body",children:ce.items.map(ge=>se(ge,!1))})]},xe)}):X.map(ce=>se(ce,A.key!=="screen"))]},A.key)}),e.jsx(To,{api:s}),e.jsxs("button",{type:"button",className:`sn-shw-drop${u?" is-over":""}`,onClick:()=>i(),onDragOver:A=>{A.preventDefault(),x(!0)},onDragLeave:()=>x(!1),onDrop:K,children:[e.jsxs("b",{children:[e.jsx(cn,{className:"sn-i sn-i-16"})," Перетащите файл"]}),e.jsx("span",{children:"PDF, PPTX, MP4, PNG, JPG — или нажмите, чтобы выбрать"})]}),e.jsx(Cs,{open:!!o,onClose:()=>c(null),anchor:(o==null?void 0:o.anchor)||null,items:(o==null?void 0:o.items)||[],width:260}),h&&e.jsx(gu,{api:s,item:h,speakers:N,onClose:()=>p(null)})]})}const rn="__common";function pu(s){const n=s.trim().split(/\s+/);return n.length<=2&&s.length<=22?s:`${n[0]} ${n.slice(1).map(t=>`${t[0]}.`).join("")}`.slice(0,26)}
111function ju({api:s,producer:n,item:t,speaker:a,addedBy:i,onShow:l,onMenu:r}){const m=n.programIds.includes(t.id),o=n.previewIds.has(t.id),c=typeof t.participant.uploadProgress=="number"&&t.participant.uploadProgress<100,u=ys(t),x=c?`загружаем… ${Math.round(t.participant.uploadProgress||0)}%`:`${Da(t)}${i?` · добавил(а) ${i}`:""}`;return e.jsxs("div",{className:"sn-shw-media",children:[e.jsx(mr,{item:t}),e.jsxs("div",{className:"sn-shw-media-text",children:[e.jsx("b",{title:t.title,children:t.title}),a&&e.jsxs("span",{className:"sn-shw-media-spk",title:a.source==="filename"?"Спикер по названию файла — поправьте в «⋯ → Чей файл», если не так":void 0,children:[e.jsx(en,{className:"sn-i","aria-hidden":"true"}),a.name,a.source==="filename"?" ?":""]}),e.jsx("span",{title:x,children:x}),e.jsxs("div",{className:"sn-shw-media-actions",children:[e.jsx(R,{size:"sm",variant:m?"soft":"quiet",icon:m?void 0:e.jsx(fn,{className:"sn-i sn-i-16"}),onClick:l,disabled:c,children:m?"Управлять":"Показать"}),!m&&u!=="screen"&&e.jsx(R,{size:"sm",variant:o?"soft":"text",onClick:()=>n.addToPreview(t.participant),disabled:!n.previewScene||o||!s.perms.manageStage,title:"Собрать кадр в подготовке и вывести кнопкой «В эфир»",children:o?"В подготовке":"В подготовку"}),e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":`Ещё: ${t.title}`,onClick:f=>r(f.currentTarget),children:e.jsx(zs,{className:"sn-i sn-i-16"})}),m&&e.jsx("span",{className:"sn-shw-media-state is-live",children:"в эфире"})]})]})]})}function gu({api:s,item:n,speakers:t,onClose:a}){const i=Se(),l=t.speakerOf(n.participant),[r,m]=d.useState(""),[o,c]=d.use
111State(!1),u=vs(r),x=t.choices.filter(h=>!u||vs(h.name).includes(u)),f=async h=>{c(!0);const p=await s.setMediaSpeaker(n.id,h);if(c(!1),!p.ok){i.error(p.error||"Не удалось сохранить");return}i.success(h?`«${n.title}» — файл спикера ${h}`:`«${n.title}» — общий файл`),a()},g=r.trim();return e.jsx(Ke,{open:!0,onClose:a,title:"Чей файл",subtitle:n.title,icon:e.jsx(en,{className:"sn-i"}),width:440,footer:e.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end",width:"100%"},children:[e.jsx(R,{variant:"quiet",onClick:()=>void f(null),disabled:o||!l||l.source!=="assigned",children:"Общий файл"}),e.jsx(R,{variant:"primary",onClick:()=>void f(g),disabled:o||!g,children:"Сохранить имя"})]}),children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[e.jsxs("p",{className:"sn-hint",style:{margin:0,fontSize:13},children:[l?`Сейчас: ${l.name}${l.source==="filename"?" (по названию файла)":l.source==="uploader"?" (загрузил сам)":l.source==="cabinet"?" (из кабинета спикера)":""}.`:"Спикер не указан — файл в «Общих»."," ","Файл окажется в папке спикера, а в «Кулисах» — у его плитки."]}),e.jsx(Oe,{inputSize:"sm",icon:e.jsx(ea,{className:"sn-i sn-i-16"}),placeholder:"Имя спикера",value:r,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key==="Enter"&&g&&f(x.length===1?x[0].name:g)},"data-autofocus":!0}),e.jsxs("div",{className:"sn-shw-whose",role:"listbox","aria-label":"Спикеры",children:[x.slice(0,60).map(h=>e.jsxs("button",{type:"button",role:"option","aria-selected":(l==null?void 0:l.key)===h.key,className:"sn-menu-item",onClick:()=>void f(h.name),disabled:o,children:[e.jsx(en,{className:"sn-i sn-i-16"}),e.jsx("span",{style:{flex:1,minWidth:0},children:h.name}),(l==null?void 0:l.key)===h.key&&e.jsx(Re,{className:"sn-i sn-i-16",style:{color:"var(--sn-blue)"}})]},h.key)),!x.length&&e.jsx("span",{className:"sn-hint",style:{fontSize:13},children:"Такого спикера нет в списке — «Сохранить имя» запишет как есть."})]})]})})}const An=12,vu=new Set(["speaker","host","guest"]);function bu(s,n,t){var N,k;const a=Nl(s.room.id,s.joined),i=s.slideControl(n.id),l=s.participants.filter(b=>b.type==="user"&&!b.isLocal&&vu.has(Os(b))),r=wl(a.data,n),m=i&&i!=="producer"&&l.find(b=>s.stageIdOf(b)===i.peerId)||null,o=n.mediaSpeaker&&l.find(b=>vs(b.name)===vs(n.mediaSpeaker))||null,c=n.ownerSocketId&&l.find(b=>s.stageIdOf(b)===n.ownerSocketId)||null,u=r&&l.find(b=>vs(b.name)===vs(r.name))||null,x=l.find(b=>s.stageParticipants.some(y=>y.id===b.id))||null,f=m||o||c||u||x||l.find(b=>
111Os(b)==="speaker")||null,g=i==="producer"?"producer":i||c?"speaker":"producer",h=(i&&i!=="producer"?i.name:null)||(f==null?void 0:f.name)||n.mediaSpeaker||(r==null?void 0:r.name)||null,p=d.useMemo(()=>{var q;if(!t)return{note:null,by:h};const b=h&&t.team.find(C=>vs(C.name)===vs(h))||null,y=b?t.program.find(C=>C.speakerIds.includes(b.id)&&C.note):null,w=(q=s.rundown)!=null&&q.current?t.program.find(C=>{var _,K;return C.id===((K=(_=s.rundown)==null?void 0:_.current)==null?void 0:K.id)}):null,T=y||(w!=null&&w.note?w:null);return{note:(T==null?void 0:T.note)||null,by:(b==null?void 0:b.name)||h}},[t,h,(k=(N=s.rundown)==null?void 0:N.current)==null?void 0:k.id]);return{control:i,mode:g,speaker:f,speakerName:h,handedAway:!!i&&i!=="producer"&&!m,notes:lo(p.note),notesBy:p.by}}function yu({api:s,producer:n,item:t,onBack:a,data:i=null}){var y,w;const l=Se(),r=t.participant,m=bu(s,r,i),o=((y=r.presentation)==null?void 0:y.slides)||[],c=((w=r.presentation)==null?void 0:w.currentSlide)??0,u=n.programIds.includes(t.id),[x,f]=d.useState(()=>Math.floor(c/An));d.useEffect(()=>{f(Math.floor(c/An))},[c]);const g=T=>{const q=Math.max(0,Math.min(o.length-1,T));q!==c&&s.changeSlide(t.id,q-c)},h=d.useRef(g);h.current=g,d.useEffect(()=>{const T=q=>{const C=q.target;C&&(C.tagName==="INPUT"||C.tagName==="TEXTAREA"||C.isContentEditable)||(q.key==="ArrowRight"?(q.preventDefault(),h.current(c+1)):q.key==="ArrowLeft"&&(q.preventDefault(),h.current(c-1)))};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[c]);const p=Math.max(1,Math.ceil(o.length/An)),N=x*An,k=o.slice(N,N+An),b=ys(t)==="image";return e.jsxs("div",{className:"sn-shw-detail",children:[e.jsxs("div",{className:"sn-shw-detail-head",children:[e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":"Назад к медиа",onClick:a,children:e.jsx(jt,{className:"sn-i sn-i-16"})}),e.jsx("b",{title:t.title,children:b?t.title:"Презентация"}),u?e.jsx("span",{className:"sn-tag sn-tag-live",children:"В ЭФИРЕ"}):e.jsx("span",{className:"sn-tag sn-tag-gray",children:"в кулисах"})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Текущий слайд",children:[e.jsx("div",{className:`sn-shw-slide${u?" is-live":""}`,children:o[c]?e.jsx("img",{src:o[c],alt:`Слайд ${c+1}`}):e.jsx("span",{className:"sn-hint",children:"Слайды ещё готовятся…"})}),!b&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsxs("b",{style:{fontSize:15},children:["Слайд ",c+1," из ",o.length||1]}),e.jsx("span",{className:"sn-s",children:"листать можно стрелками ← →"})]}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx(R,{size:"lg",variant:"quiet",icon:e.jsx(Ol,{className:"sn-i"}),onClick:()=>g(c-1),disabled:c<=0,children:"Назад"}),e.jsx(R,{size:"lg",variant:"soft",iconRight:e.jsx(Xs,{className:"sn-i"}),onClick:()=>g(c+1),disabled:c>=o.length-1,style:{flex:1},children:"Далее"})]})]}),e.jsx(ur,{api:s,producer:n,participant:r,onAir:u})]}),!b&&o.length>1&&e.jsxs("section",{className:"sn-panel-sec","aria-label":"Все слайды",children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsx("span",{className:"sn-eyebrow",children:"Слайды"}),e.jsxs("span",{className:"sn-s",children:[p>1&&e.jsx("button",{type:"button",className:"sn-shw-link is-muted",onClick:()=>f(T=>(T-1+p)%p),"aria-label":"Предыдущие слайды",children:"‹"})," ",N+1,"–",Math.min(o.length,N+An)," из ",o.length," ",p>1&&e.jsx("button",{type:"button",className:"sn-shw-link is-muted",onClick:()=>f(T=>(T+1)%p),"aria-label":"Следующие слайды",children:"›"})]})]}),e.jsx("div",{className:"sn-shw-slides",children:k.map((T,q)=>{var K,L;const C=N+q,_=((L=(K=r.presentation)==null?void 0:K.slidesLow)==null?void 0:L[C])||T;return e.jsxs("button",{type:"button","aria-label":`Слайд ${C+1}`,"aria-pressed":C===c,onClick:()=>g(C),children:[e.jsx("img",{src:_,alt:"",loading:"lazy"}),e.jsx("span",{className:"sn-mono",children:C+1})]},C)})})]}),!b&&(()=>{var q;const T=(q=m.notes.bySlide[c+1])!=null&&q.length?m.notes.bySlide[c+1]:m.notes.general;return e.jsxs("section",{className:"sn-panel-sec","aria-label":"Заметки спикера",children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsx("span",{className:"sn-eyebrow",children:"Заметки спикера"}),m.notesBy&&T.length>0&&e.jsxs("span",{className:"sn-s",children:["от ",ho(m.notesBy)]})]}),T.length?e.jsx("div",{className:"sn-shw-deck-notes",children:T.map((C,_)=>e.jsx("p",{children:C},_))}):e.jsxs("span",{className:"sn-hint",style:{fontSize:13},children:["К слайду ",c+1," заметок нет. Их пишут в программе события, в блоке спикера: «Слайд ",c+1,": …»."]})]})})(),!b&&e.jsxs("section",{className:"sn-panel-sec","aria-label":"Кто листает",children:[e.jsx("span",{className:"sn-eyebrow",children:"Листает"}),e.jsx(we,{ariaLabel:"Кто листает слайды",value:m.mode,onCh
111ange:T=>{if(T==="producer"){s.setSlideControl(t.id,"producer");return}if(!m.speaker){l.show("Спикера нет в студии — слайды листает продюсер");return}s.setSlideControl(t.id,{peerId:s.stageIdOf(m.speaker),name:m.speaker.name})},options:[{value:"producer",label:"Продюсер",disabled:!s.perms.manageStage},{value:"speaker",label:m.speakerName?`Спикер (${m.speakerName.split(/\s+/)[0]})`:"Спикер",disabled:!s.perms.manageStage||!m.speaker&&m.mode!=="speaker",title:m.speaker?void 0:"Спикера нет в студии"}]}),e.jsx("p",{className:"sn-hint",style:{margin:0,fontSize:13},children:m.mode==="producer"?"Листаете вы и другие продюсеры — спикер видит слайды, но не переключает.":m.handedAway?`${m.speakerName||"Спикер"} вышел из студии — выберите «Продюсер» или передайте слайды снова, когда он вернётся.`:`Листает ${m.speakerName||"спикер"} — стрелками у себя за кулисами или на сцене; вы тоже можете переключить.`})]}),e.jsx("div",{className:"sn-shw-detail-foot",children:e.jsx(R,{variant:"quiet",block:!0,icon:e.jsx(ls,{className:"sn-i sn-i-16"}),onClick:()=>{u&&n.removeFromProgram(r),a()},children:u?b?"Убрать картинку":"Убрать презентацию":"Закрыть"})})]})}function Nu({api:s,producer:n,item:t,onBack:a,onOpen:i,video:l}){const r=ts(250),m=t.participant,o=m.videoFile,[c,u]=d.useState(0),x=(o==null?void 0:o.duration)||c,f=dr(m,r),g=!!(o!=null&&o.isPlaying),h=n.programIds.includes(t.id),{prefs:p,setPrefs:N}=l,k=typeof m.volume=="number"?m.volume:100,b=p.afterSceneId||l.previousSceneId||"",y=n.scenes.find(C=>C.id===b)||null,w=s.media.filter(C=>C.id!==t.id&&ys(C)==="video"),T=p.queue.map(C=>w.find(_=>_.id===C)).filter(C=>!!C),q=T[0]||null;return e.jsxs("div",{className:"sn-shw-detail",children:[e.jsxs("div",{className:"sn-shw-detail-head",children:[e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":"Назад к медиа",onClick:a,children:e.jsx(jt,{className:"sn-i sn-i-16"})}),e.jsx("b",{title:t.title,children:t.title}),h?e.jsx("span",{className:"sn-tag sn-tag-live",children:"В ЭФИРЕ"}):e.jsx("span",{className:"sn-tag sn-tag-gray",children:"в кулисах"})]}),!(o!=null&&o.duration)&&(o==null?void 0:o.url)&&e.jsx("video",{src:o.url,preload:"metadata",muted:!0,hidden:!0,onLoadedMetadata:C=>u(Number.isFinite(C.currentTarget.duration)?C.currentTarget.duration:0)}),e.jsxs("section",{className:"sn-shw-player","aria-label":"Воспроизведение",children:[e.jsxs("div",{className:"sn-shw-player-top",children:[e.jsx("button",{type:"button",className:"sn-shw-play","aria-label":g?"Пауза":"Играть",onClick:()=>s.setVideoPlayback(t.id,{isPlaying:!g,currentTime:f}),children:g?e.jsx(Jt,{className:"sn-i"}):e.jsx(fn,{className:"sn-i"})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("b",{children:g?"Играет":f>0&&f<x?"На паузе":"Готов к показу"}),e.jsx("span",{className:"sn-hint",style:{display:"block",fontSize:12.5},children:Da(t).replace(" · со звуком","")})]}),e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-quiet sn-ibtn-sm","aria-label":"С начала",onClick:()=>s.setVideoPlayback(t.id,{currentTime:0}),children:e.jsx(zn,{className:"sn-i sn-i-16"})}),e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-quiet sn-ibtn-sm","aria-label":"Вперёд на 10 секунд",onClick:()=>s.setVideoPlayback(t.id,{currentTime:Math.min(x,f+10)}),children:e.jsx(Sc,{className:"sn-i sn-i-16"})})]}),e.jsx("input",{type:"range",className:"sn-shw-range is-red","aria-label":"Позиция в ролике",min:0,max:Math.max(1,Math.round(x)),step:1,value:Math.round(f),onChange:C=>s.setVideoPlayback(t.id,{currentTime:Number(C.target.value)}),style:{"--sn-fill":`${x?f/x*100:0}%`}}),e.jsxs("div",{className:"sn-shw-player-time sn-mono",children:[e.jsx("span",{children:qs(f)}),e.jsxs("span",{className:"sn-hint",children:["осталось ",e.jsx("span",{className:"sn-mono",children:qs(x-f)})]}),e.jsx("span",{children:qs(x)})]}),e.jsx(ur,{api:s,producer:n,participant:m,onAir:h})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Звук ролика",children:[e.jsx("span",{className:"sn-eyebrow",children:"Звук"}),e.jsxs("div",{className:"sn-shw-volrow",children:[e.jsx(Cn,{className:"sn-i sn-i-16"}),e.jsx("input",{type:"range",className:"sn-shw-range","aria-label":"Громкость ролика",min:0,max:100,value:Math.min(100,k),onChange:C=>{var _;return(_=s.setSourceVolume)==null?void 0:_.call(s,t.id,Number(C.target.value))},style:{"--sn-fill":`${Math.min(100,k)}%`},disabled:!s.setSourceVolume}),e.jsxs("span",{className:"sn-mono",children:[Math.min(100,k),"%"]})]}),e.jsxs("div",{className:"sn-shw-switchrow",children:[e.jsxs("div",{children:[e.jsx("b",{children:"Приглушать микрофоны"}),e.jsx("span",{children:"пока идёт ролик, спикеров слышно тише — звук ролика не перебивают"})]}),e.jsx(Pe,{checked:p.duck,onChange:C=>N(_=>({..._,duck:C})),label:"Приглушать микрофоны, пока идёт ролик"})]})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"После окончания",children:[e.jsx("span",{className:"sn-eyebrow",children:"После окончания"}),e.jsx(Bs,{ariaLabel:"После окончания",value:b||"none",onChange:C=>N(_=>({..._,afterSceneId:C==="none"?"none":C})),options:[{value:"none",label:"Оставить последний кадр"},...n.scenes.map(C=>({value:C.id,label:`Вернуться к сцене «${C.name}»`}))]}),y&&p.afterSceneId!=="none"&&e.jsx("p",{className:"sn-hint",style:{margin:0,fontSize:13},children:q?e.jsxs(e.Fragment,{children:["Через ",e.jsx("span",{className:"sn-mono",children:qs(x-f)})," начнётся «",q.title,"», а после очереди — сцена «",y.name,"»."]}):e.jsxs(e.Fragment,{children:["Через ",e.jsx("span",{className:"sn-mono",children:qs(x-f)})," зрители снова увидят сцену «",y.name,"»."]})}),e.jsxs("div",{className:"sn-shw-switchrow",children:[e.jsxs("div",{children:[e.jsx("b",{children:"Плавный переход"}),e.jsx("span",{children:"затемнение в конце ролика"})]}
111),e.jsx(Pe,{checked:p.fade,onChange:C=>N(_=>({..._,fade:C})),label:"Плавный переход"})]})]}),w.length>0&&e.jsxs("section",{className:"sn-panel-sec","aria-label":"Следующий ролик",children:[e.jsx("span",{className:"sn-eyebrow",children:"Следом можно показать"}),w.slice(0,4).map(C=>{const _=p.queue.includes(C.id);return e.jsxs("div",{className:"sn-shw-media is-compact",children:[e.jsx(mr,{item:C}),e.jsxs("div",{className:"sn-shw-media-text",children:[e.jsx("b",{children:C.title}),e.jsx("span",{children:Da(C)})]}),e.jsx(R,{size:"sm",variant:_?"soft":"quiet",onClick:()=>N(K=>({...K,queue:_?K.queue.filter(L=>L!==C.id):[...K.queue,C.id]})),children:_?`В очереди · ${p.queue.indexOf(C.id)+1}`:"В очередь"})]},C.id)}),T.length>0&&e.jsx("button",{type:"button",className:"sn-shw-link is-muted",onClick:()=>i(T[0].id),children:"Открыть следующий ролик"})]}),e.jsx("div",{className:"sn-shw-detail-foot",children:e.jsx(R,{variant:"quiet",block:!0,icon:e.jsx(jn,{className:"sn-i sn-i-16"}),onClick:()=>{s.setVideoPlayback(t.id,{isPlaying:!1,currentTime:0}),h&&n.removeFromProgram(m),a()},children:"Остановить ролик"})})]})}function wu(s,n){var x;const t=ts(500),[a,i]=sn(`sn-show:${s.room.id}:video`,{afterSceneId:"",fade:!0,duck:!0,queue:[]}),l=d.useRef(null),r=d.useRef(null),m=d.useRef({}),o=s.media.find(f=>ys(f)==="video"&&n.programIds.includes(f.id))||null;d.useEffect(()=>{n.programScene&&!o&&(l.current=n.programScene.id)},[n.programScene,o]);const u=!!((x=o==null?void 0:o.participant.videoFile)!=null&&x.isPlaying)&&a.duck&&!!s.setSourceVolume;return d.useEffect(()=>{if(!s.setSourceVolume)return;const f=s.stageParticipants.filter(g=>g.type==="user"&&!g.isAI);if(u){f.forEach(g=>{var h;m.current[g.id]===void 0&&(m.current[g.id]=typeof g.volume=="number"?g.volume:100,(h=s.setSourceVolume)==null||h.call(s,g.id,Math.round((m.current[g.id]||100)*.35)))});return}Object.entries(m.current).forEach(([g,h])=>{var p;return(p=s.setSourceVolume)==null?void 0:p.call(s,g,h)}),m.current={}},[u,s.stageParticipants.length]),d.useEffect(()=>{if(!o||!s.perms.manageStage)return;const f=o.participant.videoFile;if(!(f!=null&&f.isPlaying)||!f.duration)return;const g=dr(o.participant,t),h=`${o.id}:${f.lastSyncedAt||0}`;if(g<f.duration-.6||r.current===h)return;r.current=h;const N=a.queue.filter(y=>y!==o.id&&s.media.some(w=>w.id===y))[0];if(N){const y=s.media.find(w=>w.id===N);i(w=>({...w,queue:w.queue.filter(T=>T!==N)})),y&&(s.setVideoPlayback(y.id,{currentTime:0}),n.coverId===o.id?n.coverWithMedia(y.participant):n.putOnAir(y.participant));return}const k=a.afterSceneId==="none"?null:a.afterSceneId||l.current,b=k?n.scenes.find(y=>y.id===k):null;s.setVideoPlayback(o.id,{isPlaying:!1,currentTime:0}),n.coverId===o.id?a.afterSceneId!=="none"&&n.uncover(o.id,b,a.fade?"fade":"cut"):b&&gi(s,n,b,a.fade?"fade":"cut")},[t]),{prefs:a,setPrefs:i,previousSceneId:l.current}}function ku(s){const n=s.name.toLowerCase();return s.type.startsWith("video/")||/\.(mp4|webm|mov)$/.test(n)?"video":s.type.startsWith("image/")?"image":"slides"}const Su="application/pdf,application/vnd.openxmlformats-officedocument.presentationml.presentation,.pptx,video/mp4,video/webm,video/quicktime,image/*",Cu=1024*1024*1024;function $u(s){const n=Se(),[t,a]=d.useState([]),i=d.useRef(s);return i.current=s,{jobs:t,add:r=>{const m=i.current,o=r.filter(u=>u.size>Cu?(n.error(`«${u.name}» больше 1 ГБ`),!1):!0);if(!o.length)return;if(!m.uploadMediaFiles){m.uploadMedia();return}const c=m.media.map(u=>u.id);a(u=>[...u,...o.map((x,f)=>({key:`${Date.now()}-${f}-${x.name}`,name:x.name,size:x.size,kind:ku(x),startedAt:Date.now(),knownIds:c}))]),m.uploadMediaFiles(o)},remove:r=>a(m=>m.filter(o=>o.key!==r))}}function Iu({open:s,onClose:n,api:t,onOpenMedia:a,uploads:i}){const l=ts(1e3),r=d.useRef(null),[m,o]=d.useState(!1),{jobs:c,add:u}=i,x=d.useMemo(()=>c.map(g=>{var y;const h=g.name.replace(/\.[^.]+$/,"").toLowerCase(),p=t.media.find(w=>{var T,q;return!g.knownIds.includes(w.id)&&(w.title.toLowerCase()===g.name.toLowerCase()||w.title.toLowerCase()===h||(((T=w.participant.presentation)==null?void 0:T.sourceFileName)||((q=w.participant.videoFile)==null?void 0:q.sourceFileName)||"").toLowerCase()===g.name.toLowerCase())}),N=p?p.participant.uploadProgress:void 0,k=!!p&&(N===void 0||N>=100)&&(g.kind!=="slides"||(((y=p.participant.presentation)==null?void 0:y.slides.length)||0)>0),b=!p&&l-g.startedAt>2e4;return{job:g,match:p,progress:k?100:N??(p?100:0),done:k,stale:b}}),[c,t.media,l]),f=x.some(g=>!g.done&&!g.stale);return e.jsx(Ke,{open:s,onClose:n,title:"Загрузка файлов",subtitle:"Файлы появятся во вкладке «Медиа» и в кулисах",icon:e.jsx(cn,{className:"sn-i"}),width:560,footer:e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,width:"100%"},children:[e.jsxs("span",{className:"sn-hint",style:{fontSize:13,display:"flex",alignItems:"center",gap:8,flex:1},children:[e.jsx(un,{className:"sn-i sn-i-16"})," ",f?"Можно закрыть окно — загрузка продолжится":"Файлы видны только команде, пока вы их не покажете"]}),e.jsx(R,{variant:"primary",onClick:n,children:"Готово"})]}),children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[e.jsxs("div",{className:`sn-shw-dropzone${m?" is-over":""}`,onDragOver:g=>{g.preventDefault(),o(!0)},onDragLeave:()=>o(!1),onDrop:g=>{g.preventDefault(),o(!1),u(Array.from(g.dataTransfer.files||[]))},children:[e.jsx("span",{className:"sn-shw-dropzone-ico",children:e.jsx(cn,{className:"sn-i"})}),e.jsx("b",{children:"Перетащите файлы сюда"}),e.jsxs("span",{className:"sn-hint",children:["PDF, PPTX, MP4, PNG, JPG — до 1 ГБ"," ",e.jsx("button",{type:"button",className:"sn-shw-link",onClick:()=>{var g;return(g=r.current)==null?void 0:g.click()},children:"Выбрать на компьютере"})]}),e.jsx("input",{ref:r,type:"file",multiple:!0,accept:Su,hidden:!0,onChange:g=>{u(Array.from(g.target.files||[])),g.target.value=""}})]}),x.map(({job:g,match:h,progress:p,done:N,stale:k})=>e.jsxs("div",{className:"sn-shw-upjob",children:[e.jsx("span",{className:`sn-shw-upjob-ico is-${g.kind}${N?" is-done":""}`,children:g.kind==="video"?e.jsx(pt,{className:"sn-i sn-i-16"}):g.kind==="image"?e.jsx(gt,{className:"sn-i sn-i-16"}):e.jsx(Xt,{className:"sn-i sn-i-16"})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{className:"sn-shw-upjob-top",children:[e.jsx("b",{title:g.name,children:g.name}),!N&&!k&&e.jsxs("span",{className:"sn-mono",children:[Math.round(p||0),"%"]}),N&&e.jsx("span",{className:"sn-tag sn-tag-green",children:"Готово"})]}),!N&&!k&&e.jsx(Qr,{value:Math.max(3,p||0)}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:N?`${_t(g.size)} · в кулисах`:k?"Файл не появился — проверьте формат и попробуйте ещё раз":g.kind==="slides"&&(p||0)>=45?"Превращаем в слайды — покажем, как только закончим":`${_t(g.size)} · загружаем`})]}),N&&h&&ys(h)!=="screen"&&e.jsx(R,{size:"sm",variant:"text",onClick:()=>{a(h.id),n()},children:"Открыть"}),(N||k)&&e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":`Убрать из списка: ${g.name}`,onClick:()=>i.remove(g.key),children:e.jsx(ls,{className:"sn-i sn-i-16"})})]},g.key))]})})}const Mu=[{value:"onest",label:"Onest"},{value:"unbounded",label:"Unbounded"},{value:"mono",label:"Mono"}],Lu=[{key:"light",label:"Светлая",value:"classic",style:"classic"},{key:"dark",label:"Тёмная",value:"minimal",style:"minimal"},{key:"brand",label:"Бренд",value:"block",style:"block"}],Au="/studio-show/bg-grid.svg",pa=[{key:"graphite",label:"Графит",kind:"color",value:"#0F1720",preset:"graphite"},{key:"night",label:"Ночь",kind:"color",value:"#0B2440",preset:"night"},{key:"grid",label:"Сетка",kind:"image",value:Au,preset:null}],hr=/^#[0-9a-f]{6}$/i;function Mt(s){if(!s)return"";try{const n=new URL(s,window.location.origin).pathname;return decodeURIComponent(n.split("/").pop()||"")}catch{return""}}async function Pu(s){const n=document.createElement("canvas");n.width=1920,n.height=1080;const t=n.getContext("2d");if(!t)throw new Error("Браузер не смог нарисовать рамку");t.strokeStyle=s,t.lineWidth=20,t.strokeRect(10,10,1900,1060);const a=await new Promise(i=>n.toBlob(i,"image/png"));if(!a)throw new Error("Браузер не смог нарисовать рамку");return new File([a],`frame-${s.slice(1)}.png`,{type:"image/png"})}async function Eu(s,n,t){const a=n.scenes.map(r=>r.template==="title"&&r.background.kind==="image"?r:{...r,background:t});if(!await n.saveScenes(a))return!1;const l=n.programScene?a.find(r=>{var m;return r.id===((m=n.programScene)==null?void 0:m.id)}):null;
111return l&&s.perms.manageStage&&await gi(s,n,l,"cut"),!0}function Qi({label:s,color:n,onPick:t,disabled:a,hint:i}){const l=d.useRef(null);return e.jsxs("button",{type:"button",className:"sn-shw-swatch","aria-label":`${s} цвет ${n.toUpperCase()}${a?"":" — изменить"}`,title:i,disabled:a,onClick:()=>{var r;return(r=l.current)==null?void 0:r.click()},children:[e.jsx("span",{className:"sn-shw-swatch-chip",style:{background:n}}),e.jsx("b",{children:s}),e.jsx("span",{className:"sn-mono",children:n.toUpperCase()}),t&&e.jsx("input",{ref:l,type:"color",value:hr.test(n)?n:"#0A72C6",onChange:r=>t(r.target.value),tabIndex:-1,"aria-hidden":"true"})]})}function zu({api:s,producer:n,data:t}){var M,U;const a=Se(),i=s.brand,l=Ta(i.theme),r=hr.test(i.color||"")?i.color:"#0A72C6",m=s.perms.branding,[o,c]=d.useState(null),[u,x]=sn(`sn-show:${s.room.id}:frame`,null),[f,g]=d.useState(null),[h,p]=d.useState(null),N=d.useRef(null),k=d.useRef(null),b=((M=t.event)==null?void 0:M.workspaceId)||null,y=n.programScene||n.scenes[0]||null,w=(y==null?void 0:y.background)||{kind:"color",value:"#0F1720"},T=((U=pa.find($=>$.kind===w.kind&&$.value.toLowerCase()===String(w.value).toLowerCase()))==null?void 0:U.key)||(w.kind==="image"?"custom":"color"),q=!!i.overlay&&!!u&&i.overlay===u.url,C=i.logo&&!vo(i.logo)?i.logo:null;d.useEffect(()=>{if(g(null),!C)return;const $=new Image;$.onload=()=>g({w:$.naturalWidth,h:$.naturalHeight}),$.src=C},[C]),d.useEffect(()=>{if(!b)return;let $=!1;return Ae.get(`workspaces/${encodeURIComponent(b)}/brand`).then(v=>{$||p(v)}).catch(()=>{$||p(null)}),()=>{$=!0}},[b]);const _=$=>{var B;s.updateBrand({theme:$.value});const v=(B=n.cfg.config)==null?void 0:B.lowerThirds;v&&n.cfg.save({lowerThirds:{...v,style:$.style}})},K=$=>{s.updateBrand({color:$})},L=d.useRef(r);d.useEffect(()=>{if(!q||L.current===r)return;L.current=r;const $=window.setTimeout(()=>void F(!0),600);return()=>window.clearTimeout($)},[r,q]);const F=async $=>{if(!$){s.updateBrand({overlay:null});return}c("frame");try{const v=await za(await Pu(r));s.updateBrand({overlay:v.url}),x({url:v.url,color:r}),L.current=r}catch(v){a.error(js(v,"Не удалось включить рамку"))}finally{c(null)}},S=async($,v)=>{c(`bg:${v}`);try{await Eu(s,n,$)&&a.success(s.live.isLive?"Фон сцен обновлён — зрители уже видят его":"Фон сцен обновлён")}finally{c(null)}},O=async($,v)=>{if(!$.type.startsWith("image/")){a.error("Нужна картинка: PNG, JPG или SVG");return}c(v);try{const B=await za($);v==="logo"?(s.updateBrand({logo:B.url,showLogo:!0}),a.success("Логотип заменён")):await S({kind:"image",value:B.url},"custom")}catch(B){a.error(js(B,"Не удалось загрузить файл"))}finally{c(null)}},z=async()=>{var v;if(!b)return;c("default");const $=((v=pa.find(B=>B.key===T))==null?void 0:v.preset)||null;try{await Ae.put(`workspaces/${encodeURIComponent(b)}/brand`,{logoUrl:C,logoName:C?Mt(C).slice(0,255):null,accentColor:r,plateColor:r,plateStyle:l==="brand"?"color":l,studioBackground:w.kind==="image"?{preset:null,imageUrl:/^(https?:\/\/|\/)\S+$/.test(w.value)?w.value:null}:{preset:$||"graphite",imageUrl:null}}),a.success("Тема сохранена — она применится к новым эфирам")}catch(B){a.error(js(B,"Не удалось сохранить тему"))}finally{c(null)}};return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"sn-panel-sec","aria-label":"Тема",children:[e.jsx("span",{className:"sn-eyebrow",children:"Тема плашек"}),e.jsx("div",{className:"sn-shw-themes",children:Lu.map($=>e.jsxs("button",{type:"button","aria-pressed":l===$.key,onClick:()=>_($),disabled:!m,children:[e.jsxs("span",{className:`sn-shw-theme-art is-${$.key}`,style:$.key==="brand"?{"--sn-bc":r}:void 0,children:[e.jsx("i",{}),e.jsx("i",{}),e.jsx("em",{})]}),e.jsx("b",{children:$.label}),l===$.key&&e.jsx("span",{className:"sn-shw-theme-check",children:e.jsx(Re,{className:"sn-i",style:{width:12,height:12}})})]},$.key))})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Цвета",children:[e.jsx("span",{className:"sn-eyebrow",children:"Цвета"}),e.jsxs("div",{className:"sn-shw-swatches",children:[e.jsx(Qi,{label:"Основной",color:r,onPick:m?K:void 0,disabled:!m,hint:"Плашки темы «Бренд», рамка и акценты эфира"}),e.jsx(Qi,{label:"Фон",color:w.kind==="color"?w.value:"#0F1720",onPick:m?$=>
111void S({kind:"color",value:$},"color"):void 0,disabled:!m||(o==null?void 0:o.startsWith("bg:")),hint:"Фон всех сцен"})]})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Логотип",children:[e.jsx("span",{className:"sn-eyebrow",children:"Логотип"}),e.jsxs("div",{className:"sn-shw-logo",children:[e.jsx("span",{className:"sn-shw-logo-img",children:C?e.jsx("img",{src:C,alt:"Логотип эфира"}):e.jsx("img",{src:Tl,alt:"Логотип SNICH"})}),e.jsxs("div",{className:"sn-shw-out-text",children:[e.jsx("b",{title:C?Mt(C):void 0,children:C?Mt(C)||"Ваш логотип":"Логотип SNICH"}),e.jsx("span",{children:C?`${(Mt(C).split(".").pop()||"PNG").toUpperCase()}${f?` · ${f.w}×${f.h}`:""}`:"стоит по умолчанию"})]}),e.jsx(R,{size:"sm",variant:"quiet",onClick:()=>{var $;return($=N.current)==null?void 0:$.click()},loading:o==="logo",disabled:!m,children:C?"Заменить":"Загрузить"}),e.jsx("input",{ref:N,type:"file",accept:"image/png,image/jpeg,image/svg+xml,image/webp",hidden:!0,onChange:$=>{var B;const v=(B=$.target.files)==null?void 0:B[0];$.target.value="",v&&O(v,"logo")}})]}),e.jsxs("div",{className:"sn-shw-switchrow",children:[e.jsxs("div",{children:[e.jsx("b",{children:"Логотип в кадре"}),e.jsx("span",{children:"внизу кадра или на плашке — сцены с выключенным логотипом его не покажут"})]}),e.jsx(Pe,{checked:n.prefs.logo,onChange:n.setLogo,label:"Логотип в кадре",disabled:!m})]}),e.jsxs("div",{className:"sn-shw-fontrow",children:[e.jsx("b",{children:"Положение в кадре"}),e.jsx(we,{size:"sm",ariaLabel:"Положение логотипа в кадре",value:bo(i),onChange:$=>s.updateBrand({logoPosition:$}),options:[{value:"left",label:"Слева",disabled:!m},{value:"right",label:"Справа",disabled:!m}]}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"на плашке — с этой стороны; без плашки слева логотип встаёт вверх, над подписями спикеров"})]})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Фон сцены",children:[e.jsx("span",{className:"sn-eyebrow",children:"Фон сцены"}),e.jsxs("div",{className:"sn-shw-bgs",children:[pa.map($=>e.jsxs("button",{type:"button","aria-label":`Фон: ${$.label}`,"aria-pressed":T===$.key,disabled:!m||!!o,onClick:()=>void S({kind:$.kind,value:$.value},$.key),children:[e.jsxs("span",{className:"sn-shw-bg-art",style:$.kind==="color"?{background:$.value}:{backgroundImage:`url(${$.value})`},children:[T===$.key&&e.jsx("span",{className:"sn-shw-theme-check",children:e.jsx(Re,{className:"sn-i",style:{width:12,height:12}})}),o===`bg:${$.key}`&&e.jsx("span",{className:"sn-spinner",style:{width:16,height:16}})]}),$.label]},$.key)),e.jsxs("button",{type:"button","aria-label":"Фон: Свой","aria-pressed":T==="custom",disabled:!m||!!o,onClick:()=>{var $;return($=k.current)==null?void 0:$.click()},children:[e.jsx("span",{className:"sn-shw-bg-art is-add",style:T==="custom"?{backgroundImage:`url(${w.value})`}:void 0,children:T==="custom"?e.jsx("span",{className:"sn-shw-theme-check",children:e.jsx(Re,{className:"sn-i",style:{width:12,height:12}})}):o==="bg"?e.jsx("span",{className:"sn-spinner",style:{width:16,height:16}}):e.jsx(ps,{className:"sn-i sn-i-16"})}),"Свой"]}),e.jsx("input",{ref:k,type:"file",accept:"image/png,image/jpeg,image/webp",hidden:!0,onChange:$=>{var B;const v=(B=$.target.files)==null?void 0:B[0];$.target.value="",v&&O(v,"bg")}})]}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Меняет фон всех сцен, кроме заставок с картинкой. Сцена в эфире обновится сразу."})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Оверлей и плашки",children:[e.jsx("span",{className:"sn-eyebrow",children:"Оверлей и плашки"}),e.jsxs("div",{className:"sn-shw-switchrow",children:[e.jsxs("div",{children:[e.jsx("b",{children:"Рамка"}),e.jsx("span",{children:"тонкая рамка цвета бренда вокруг кадра"})]}
111),e.jsx(Pe,{checked:q,onChange:$=>void F($),label:"Рамка",disabled:!m||o==="frame"})]}),i.overlay&&!q&&e.jsxs("div",{className:"sn-shw-switchrow",children:[e.jsxs("div",{children:[e.jsx("b",{children:"Оверлей поверх кадра"}),e.jsx("span",{children:"картинка из прежней студии"})]}),e.jsx(R,{size:"sm",variant:"text",onClick:()=>s.updateBrand({overlay:null}),disabled:!m,children:"Убрать"})]}),e.jsxs("div",{className:"sn-shw-fontrow",children:[e.jsx("b",{children:"Шрифт плашек с именами"}),e.jsx(we,{size:"sm",ariaLabel:"Шрифт плашек с именами",value:i.nameFont||"onest",onChange:$=>{const v=Pi($);Promise.all([`700 24px ${v}`,`400 17px ${v}`].map(B=>{var se;return(se=document.fonts)==null?void 0:se.load(B).catch(()=>{})})).finally(()=>s.updateBrand({nameFont:$}))},options:Mu.map($=>({value:$.value,label:e.jsx("span",{style:{fontFamily:Pi($.value)},children:$.label}),disabled:!m}))})]})]}),b&&(h==null?void 0:h.canEdit)&&e.jsxs("div",{className:"sn-shw-panel-foot",children:[e.jsxs("button",{type:"button",className:"sn-shw-link",onClick:()=>void z(),disabled:o==="default",children:[e.jsx(ai,{className:"sn-i sn-i-16"})," ",o==="default"?"Сохраняем…":"Сохранить как тему по умолчанию"]}),e.jsxs("span",{className:"sn-hint",style:{fontSize:12.5},children:["тема применится ко всем новым эфирам · ",e.jsx("a",{href:"/settings/brand",target:"_blank",rel:"noreferrer",children:"бренд пространства"})]})]})]})}function Tu({live:s}){return s?e.jsxs("span",{className:"sn-tag sn-tag-amber",style:{gap:6},children:[e.jsx(gs,{className:"sn-i",style:{width:13,height:13}}),"зрители видят сразу"]}):e.jsxs("span",{className:"sn-tag sn-tag-gray",style:{gap:6},children:[e.jsx(Fo,{className:"sn-i",style:{width:13,height:13}}),"до эфира"]})}const xr={snich_live:{label:"SNICH Live",abbr:"SN"},youtube:{label:"YouTube",abbr:"YT"},vk_video:{label:"VK Видео",abbr:"VK"},vk_play:{label:"VK Play Live",abbr:"VK"},rutube:{label:"RUTUBE",abbr:"RT"},twitch:{label:"Twitch",abbr:"TW"},facebook:{label:"Facebook",abbr:"FB"},linkedin:{label:"LinkedIn",abbr:"IN"},x:{label:"X",abbr:"X"},instagram_live:{label:"Instagram",abbr:"IG"},kick:{label:"Kick",abbr:"KK"},vimeo:{label:"Vimeo",abbr:"VM"},custom_rtmp:{label:"RTMP",abbr:"RT"}};function aa(s,n,t){return t&&t.platform==="telegram"?!0:/telegram|телеграм|t\.me/i.test(`${s||""} ${n||""}`)}function dn(s,n){const t=xr[s];return s==="custom_rtmp"&&aa(n)?"Telegram":s==="custom_rtmp"?(n==null?void 0:n.trim())||"Своя площадка (RTMP)":(t==null?void 0:t.label)||n||s}function Ou(s,n){if(s==="custom_rtmp")return null;const t=dn(s),a=String(n||"").trim(),i=a.toLowerCase().startsWith(t.toLowerCase())?a.slice(t.length).replace(/^\s*[·:—-]\s*/,"").trim():a;return!i||/^(vk video|vk видео|youtube|rutube|telegram)$/i.test(i)||i.toLowerCase()===t.toLowerCase()?null:i}function Fu(s,n,t,a){var i;return s==="custom_rtmp"&&aa(n,t,a)?"TG":s==="custom_rtmp"?String(n||"").replace(/[^A-Za-zА-Яа-яЁё0-9]/g,"").slice(0,2).toUpperCase()||"RT":((i=xr[s])==null?void 0:i.abbr)||s.slice(0,2).toUpperCase()}function Ru(s){const n=s.providerConfig||{},t=typeof n.channelTitle=="string"?n.channelTitle:typeof n.channelName=="string"?n.channelName:typeof n.accountName=="string"?n.accountName:null;return t?s.provider==="vk_video"?`сообщество ${t}`:`канал ${t}`:s.provider==="custom_rtmp"&&aa(s.displayName,s.endpointMasked,n)?s.displayName&&!/^telegram$/i.test(s.displayName.trim())?s.displayName:"трансляция в канал или группу":s.provider==="custom_rtmp"?s.endpointMasked||"свой RTMP-сервер":s.displayName&&s.displayName!==dn(s.provider)?s.displayName:s.endpointMasked||"RTMP"}function _s(s){const n=String(s||"").toLowerCase();return n==="live"||n==="active"||n==="degraded"?"live":n==="failed"||n==="error"?"error":n==="reconnecting"||n==="connecting"||n==="pending"||n==="starting"?"connecting":n==="paused"?"paused":"off"}function Du(s){const n=String(s||"").toLowerCase();return n==="live"||n==="active"?"в эфире":n==="degraded"?"в эфире · нестабильно":n==="reconnecting"?"переподключаемся…":n==="connecting"||n==="starting"?"подключаемся…":n==="pending"?"ждём картинку эфира…":n==="failed"||n==="error"?"сбой":n==="paused"?"на паузе":n==="stopped"?"остановлено":"выключено"}const Yi={horizontal_1080p30:"16:9 · 1080p",horizontal_720p30:"16:9 · 720p",horizontal_1440p60:"16:9 · 2K 60",vertical_1080p30:"9:16 · 1080×1920"};function Nt(s){const n=Math.max(0,Math.floor(s)),t=Math.floor(n/3600),a=Math.floor(n%3600/60);return`${String(t).padStart(2,"0")}
111:${String(a).padStart(2,"0")}:${String(n%60).padStart(2,"0")}`}function dt(s){var n;return Math.max(0,s.recording.elapsedSec-(((n=s.recordingPause)==null?void 0:n.pausedSec)||0))}function wt(s){var t;return(((t=s.streamSession)==null?void 0:t.runtimeDestinations)||[]).filter(a=>{const i=String(a.status||"").toLowerCase();return i==="failed"||i==="error"||i==="reconnecting"}).map(a=>({id:a.id,name:dn(String(a.provider),a.displayName??null),status:String(a.status),error:a.lastError??null}))}function fr(s){const n=String(s.me.role||"");return(!n||n==="viewer"||n==="guest")&&s.perms.manageStage?"продюсер":(s.me.roleLabel||"продюсер").toLowerCase()}function pr(s){var n;return(((n=s.streamSession)==null?void 0:n.runtimeDestinations)||[]).filter(t=>_s(t.status)==="live").length}function qu({api:s,rundown:n,onOpenPanel:t,onOpenRecording:a,onGoLive:i,onEnd:l,onSettings:r,onInvite:m}){var C;const o=ts(1e3),c=s.live,u=s.liveSince??c.startedAt,x=c.isLive&&u?Math.max(0,Math.floor((o-u)/1e3)):0,f=s.room.scheduledAt?new Date(s.room.scheduledAt).getTime():null,g=f?Math.floor((f-o)/1e3):null,h=`Вы ${fr(s)}`,p=$s(s).filter(_=>!_.isLocal),N=p.filter(_=>s.readyPeers[s.stageIdOf(_)]||!_.isCameraOff&&!_.isMuted).length,k=Qn(),b=p.length+(k&&s.perms.manageStage?k.missing.length:0),y=wt(s),w=pr(s),T=!!s.streamSession&&(s.streamSession.runtimeDestinations||[]).length>0,q=!!((C=s.recordingPause)!=null&&C.paused);return e.jsxs("header",{className:"sn-st-header",children:[e.jsx(Ye,{label:"В кабинет",size:"sm",onClick:s.leave,style:{color:"var(--sn-ink-2)"},children:e.jsx(jt,{className:"sn-i"})}),e.jsxs("span",{className:"sn-st-titlebox",children:[e.jsx("span",{className:"sn-st-title",title:s.room.title,children:s.room.title}),e.jsx("span",{className:"sn-st-subtitle",children:"Пульт продюсера"})]}),h&&e.jsx(ns,{tone:"blue",className:"sn-st-hide-sm",children:h}),e.jsx("div",{className:"sn-st-grow"}),e.jsxs("div",{className:"sn-st-status",children:[c.isLive?e.jsx(fl,{time:Nt(x),className:"sn-st-livetag"}):e.jsxs(ns,{tone:"gray",className:"sn-st-livetag",style:{height:30},children:[e.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:"var(--sn-ink-3)"}}),c.starting?"Запускаем…":"Не в эфире"]}),c.isLive&&s.viewerCount!==null&&e.jsxs("span",{className:"sn-st-viewers sn-st-hide-sm",title:"Зрители на странице эфира сейчас",children:[e.jsx(gs,{className:"sn-i sn-i-16"}),e.jsx("b",{children:He(s.viewerCount)})]}),!c.isLive&&f&&g!==null&&g>-3600&&e.jsxs("span",{className:"sn-st-hide-md",style:{fontSize:14,color:"var(--sn-ink-2)"},children:["Начало в ",e.jsx("span",{className:"sn-mono",style:{color:"var(--sn-ink)",fontWeight:600},children:qe(f)}),g>0?e.jsxs(e.Fragment,{children:[" · через ",e.jsx("span",{className:"sn-mono",style:{color:"var(--sn-ink)",fontWeight:600},children:fs(g)})]}):null]}),c.isLive&&n.current&&e.jsxs("button",{type:"button",className:`sn-st-pill sn-st-hide-md${n.remainingSec<0?" sn-shw-pill-warn":""}`,onClick:()=>t("rundown"),title:"Программа эфира",children:[e.jsx(Ks,{className:"sn-i sn-i-16"}),e.jsx("span",{className:"sn-shw-pill-text",children:n.current.title}),e.jsxs("span",{className:"sn-mono",children:["· ",n.remainingSec<0?`+${fs(-n.remainingSec)}`:fs(n.remainingSec)]})]}),!c.isLive&&b>0&&e.jsxs("button",{type:"button",className:`sn-st-pill sn-st-hide-sm${N<b?" sn-shw-pill-warn":""}`,onClick:()=>t("prelive"),children:[e.jsx(nn,{className:"sn-i sn-i-16"}),"За кулисами ",N," из ",b]}),s.perms.recording&&(c.isLive||s.recording.active)&&e.jsxs("button",{type:"button",className:"sn-st-pill sn-st-hide-sm",onClick:_=>a(_.currentTarget),"aria-label":"Запись эфира",children:[e.jsx("span",{className:`sn-st-dot${s.recording.active?q?" is-amber":" is-red":""}`}),s.recording.active?q?"Запись на паузе":"Запись":"Не записываем"]}),c.isLive&&(y.length?e.jsxs("button",{type:"button",className:"sn-st-pill sn-shw-pill-warn",onClick:()=>t("outputs"),children:[e.jsx("span",{className:"sn-st-dot is-amber"}
111),"Сбой: ",y[0].name,y.length>1?` и ещё ${y.length-1}`:""]}):e.jsxs("button",{type:"button",className:"sn-st-pill sn-st-hide-sm",onClick:()=>t("outputs"),children:[e.jsx("span",{className:`sn-st-dot${T&&!w?" is-amber":" is-green"}`}),T?`${w+1} ${Xe(w+1,"площадка","площадки","площадок")}`:"Страница эфира"]}))]}),e.jsx("div",{className:"sn-st-grow"}),e.jsxs("div",{className:"sn-st-actions",children:[e.jsx(Ye,{label:s.me.isMuted?"Включить микрофон":"Выключить микрофон",size:"sm",variant:s.me.isMuted?"off-light":"quiet",onClick:s.toggleMic,children:s.me.isMuted?e.jsx(Es,{className:"sn-i"}):e.jsx(Ts,{className:"sn-i"})}),e.jsx(Ye,{label:s.me.isCameraOff?"Включить камеру":"Выключить камеру",size:"sm",variant:s.me.isCameraOff?"off-light":"quiet",onClick:s.toggleCamera,className:"sn-st-hide-sm",children:s.me.isCameraOff?e.jsx(kn,{className:"sn-i"}):e.jsx(Sn,{className:"sn-i"})}),e.jsx(Ye,{label:"Настройки студии",size:"sm",variant:"quiet",onClick:r,className:"sn-st-hide-sm",children:e.jsx(Yt,{className:"sn-i"})}),e.jsx("span",{className:"sn-st-sep sn-st-hide-sm"}),s.perms.invites&&e.jsx(R,{size:"sm",variant:"quiet",icon:e.jsx(Is,{className:"sn-i sn-i-16"}),onClick:m,className:"sn-st-hide-sm",children:"Пригласить"}),c.isLive?s.perms.endMeeting&&e.jsxs(e.Fragment,{children:[e.jsx(R,{size:"sm",variant:"quiet",style:{color:"var(--sn-red-ink)"},onClick:l,className:"sn-st-hide-sm",children:"Завершить"}),e.jsx(Ye,{label:"Завершить эфир",size:"sm",variant:"quiet",onClick:l,className:"sn-st-show-sm",style:{color:"var(--sn-red)"},children:e.jsx(ci,{className:"sn-i"})})]}):s.perms.broadcastLive&&e.jsx(R,{size:"sm",variant:"live",icon:e.jsx(ws,{className:"sn-i sn-i-16"}),onClick:i,loading:c.starting,className:"sn-st-hide-sm",children:"Выйти в эфир"})]})]})}function _u({api:s,anchor:n,onClose:t}){var o,c,u,x;ts(1e3);const a=s.recording,i=!!((o=s.recordingPause)!=null&&o.paused),l=((c=s.recordingUpload)==null?void 0:c.uploadedBytes)||0,r=((u=s.recordingUpload)==null?void 0:u.lastError)||null,m=((x=s.recordingUpload)==null?void 0:x.pendingChunks)||0;return e.jsx(xt,{open:!!n,onClose:t,anchor:n,placement:"bottom-end",width:332,children:e.jsxs("div",{className:"sn-shw-recmenu",role:"menu","aria-label":"Запись эфира",children:[e.jsxs("div",{className:"sn-shw-recmenu-head",children:[e.jsx("span",{className:`sn-shw-recdot${a.active?i?" is-paused":" is-on":""}`,"aria-hidden":"true",children:e.jsx("i",{})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{className:"sn-shw-recmenu-title",children:a.active?i?"Запись на паузе":"Идёт запись":"Запись выключена"}),e.jsx("div",{className:"sn-hint sn-mono",style:{fontSize:13},children:a.active?e.jsxs(e.Fragment,{children:[Nt(dt(s)),l>0?` · ${_t(l)}`:""]}):s.autoRecord?"начнётся вместе с эфиром":"эфир не записывается"})]}),e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":"Закрыть",onClick:t,children:e.jsx(ls,{className:"sn-i sn-i-16"})})]}),e.jsx("span",{className:"sn-eyebrow",children:"Что записываем"}),e.jsxs("div",{className:"sn-shw-recmenu-list",children:[e.jsx(Rn,{checked:!0,onChange:()=>{},disabled:!0,label:"Горизонтальная 16:9",description:"1080p · как видят зрители"}),s.verticalFormat&&e.jsx(Rn,{checked:!!s.recordingVertical,onChange:f=>{var g;return(g=s.setRecordingVertical)==null?void 0:g.call(s,f)},disabled:!s.setRecordingVertical,label:"Вертикальная 9:16",description:a.active&&s.recordingVertical?s.recordingVerticalActive?"для VK Клипов и соцсетей · пишется":"для VK Клипов и соцсетей · запускаем…":"для VK Клипов и соцсетей"}),e.jsx(Rn,{checked:!!s.recordingTracks,onChange:f=>{var g;return(g=s.setRecordingTracks)==null?void 0:g.call(s,f)},disabled:!s.setRecordingTracks,label:"Отдельные дорожки спикеров",description:a.active&&s.recordingTracks?s.recordingTracksActive?"видео и звук каждого — для монтажа · пишутся у спикеров":"видео и звук каждого — для монтажа · запускаем…":"видео и звук каждого — для монтажа"})]}),r&&e.jsxs("div",{className:"sn-shw-note is-warn",style:{fontSize:12.5},children:["Запись сохраняется с задержкой: ",r]}),!r&&m>3&&e.jsxs("div",{className:"sn-hint",style:{fontSize:12.5},children:["Догружаем запись на сервер: ",m," ",Xe(m,"фрагмент","фрагмента","фрагментов")," в очереди"]}),e.jsx("div",{style:{display:"flex",gap:8},children:a.active?e.jsxs(e.Fragment,{children:[s.pauseRecording&&e.jsx(R,{variant:"quiet",icon:i?e.jsx(fn,{className:"sn-i sn-i-16"}):e.jsx(Jt,{className:"sn-i sn-i-16"}),onClick:()=>{var f;return(f=s.pauseRecording)==null?void 0:f.call(s,!i)},children:i?"Продолжить":"Пауза"}),e.jsx(R,{variant:"quiet",icon:e.jsx(ci,{className:"sn-i sn-i-16"}),onClick:()=>{s.stopRecording(),t()},style:{flex:1,color:"var(--sn-red-ink)"},children:"Остановить запись"})]}):e.jsx(R,{variant:"live",block:!0,icon:e.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:"#fff"}}),onClick:()=>{s.startRecording(),t()},children:"Начать запись"})}),e.jsxs("span",{className:"sn-hint",style:{fontSize:12.5,display:"flex",alignItems:"center",gap:8},children:[e.jsx(tt,{className:"sn-i sn-i-16"}),e.jsxs("span",{children:["Запись попадёт в ",e.jsx("a",{href:"/recordings",target:"_blank",rel:"noreferrer",children:"«Записи и итоги»"})]})]})]})})}const Lt=10;function jr(s){const n=s.find(a=>/финал|спасибо/i.test(a.name));if(n)return n;const t=s.filter(a=>a.template==="title");return t.length>1?t[t.length-1]:null}function qa(s){var t;const n=["SNICH Live"];return(((t=s.streamSession)==null?void 0:t.runtimeDestinations)||[]).forEac
111h(a=>{_s(a.status)!=="off"&&n.push(dn(String(a.provider),a.displayName??null))}),n}function gr(s){return s.length<=1?s[0]||"":`${s.slice(0,-1).join(", ")} и ${s[s.length-1]}`}function Uu(s){const[n,t]=d.useState(!1);return d.useEffect(()=>{s.recording.active&&t(!0)},[s.recording.active]),n||s.recording.active}function Bu(s,n,t,a=!1){var m;const{qna:i,audience:l}=Vs(),r=d.useRef(null);return s.live.isLive&&(r.current={since:s.liveSince??s.live.startedAt??((m=r.current)==null?void 0:m.since)??null,platforms:qa(s)}),(o,c)=>{var f,g,h,p;const u=Object.values(l.reactionTotals||{}).reduce((N,k)=>N+(Number(k)||0),0),x=s.live.isLive?{since:s.liveSince??s.live.startedAt??null,platforms:qa(s)}:r.current;return{endedAt:c??Date.now(),endedByMe:o,liveSince:(x==null?void 0:x.since)??null,wasLive:!!x,platforms:(x==null?void 0:x.platforms)||[],recorded:s.recording.active||a||dt(s)>0,recordedSec:dt(s),peak:Math.max(l.peak||0,l.viewers||0,s.viewerCount||0),questions:i.questions.length,answered:i.questions.filter(N=>N.status==="answered").length,reactions:u,chat:s.chat.filter(N=>N.visibility==="public").length,transcript:(((f=s.transcriptInfo)==null?void 0:f.lines)||[]).map(N=>({speakerName:N.speakerName,text:N.text,timestamp:N.timestamp,startOffsetMs:N.startOffsetMs})),finalHeading:((g=t==null?void 0:t.title)==null?void 0:g.heading)||null,finalSub:((h=t==null?void 0:t.title)==null?void 0:h.sub)||null,workspaceId:((p=n.event)==null?void 0:p.workspaceId)||null}}}async function Hu(s){var i;const n=await ot(s.commsSocket,"poll:create",{roomId:s.room.id,mode:"poll",question:"Оцените эфир",options:["5 — отлично","4 — хорошо","3 — нормально","2 — так себе","1 — плохо"],settings:{isAnonymous:!0,showLiveResults:!1,resultsVisibility:"after_close"}}),t=n.ok?(i=n.poll)==null?void 0:i.id:null,a=s.commsSocket;return!t||!(a!=null&&a.connected)?!1:new Promise(l=>{const r=u=>{window.clearTimeout(c),a.off("poll:published",m),a.off("poll:error",o),l(u)},m=u=>{var x;((x=u==null?void 0:u.poll)==null?void 0:x.id)===t&&r(!0)},o=u=>{(u==null?void 0:u.code)==="PUBLISH_FAILED"&&r(!1)},c=window.setTimeout(()=>r(!1),8e3);a.on("poll:published",m),a.on("poll:error",o),a.emit("poll:publish",{roomId:s.room.id,pollId:t,showOnStage:!1,showInChat:!0})})}function Vu({open:s,onClose:n,api:t,producer:a,data:i,plannedEnd:l,finalScene:r,snapshot:m,onEnded:o,recordedBefore:c=!1}){var A,X;const u=Se(),{ended:x}=Vs(),f=t.live.isLive,g=f&&!!r&&t.perms.manageStage,h=g&&!!t.commsSocket,[p,N]=d.useState(!0),[k,b]=d.useState(!0),[y,w]=d.useState("confirm"),[T,q]=d.useState(Lt),[C,_]=d.useState(null),[K,L]=d.useState(Date.now()),F=d.useRef(!1);d.useEffect(()=>{if(!s)return;N(!0),b(!0),w("confirm"),q(Lt),_(null),F.current=!1;const ae=window.setInterval(()=>L(Date.now()),1e3);return()=>window.clearInterval(ae)},[s]);const S=async()=>{w("ending"),_(null);const ae=m(!0),ce=t.endShow?await t.endShow():await x.endForAll().then(xe=>({ok:xe.ok,error:xe.error}));if(!ce.ok){w("confirm"),_(ce.error||"Не удалось завершить эфир — попробуйте ещё раз");return}o({...ae,endedAt:Date.now()})};d.useEffect(()=>{if(y!=="final")return;if(T<=0){S();return}const ae=window.setTimeout(()=>q(ce=>ce-1),1e3);return()=>window.clearTimeout(ae)},[y,T]);const O=async()=>{if(g&&p&&r){w("ending");const ae=r.id===t.program.sourceSceneId||await gi(t,a,r,"fade");if(ae||u.error("Не удалось показать финал — завершаем без него"),ae&&h&&k&&Hu(t).then(ce=>{ce||u.show("Опрос «Оцените эфир» не запустился")}),ae&&!F.current){q(Lt),w("final");return}}await S()},z=t.liveSince??t.live.startedAt,M=f&&z?Math.max(0,Math.floor((K-z)/1e3)):0,U=f?qa(t):[],$=t.recording.active,v=((A=i.event)==null?void 0:A.counts.registrations)||0,B=y!=="confirm",se=f?e.jsxs(e.Fragment,{children:["Идёт ",e.jsx("span",{className:"sn-mono",children:fs(M,!0)}),t.viewerCount!==null?e.jsxs(e.Fragment,{children:[" · смотрят ",e.jsx("span",{className:"sn-mono",children:He(t.viewerCount)})]}):null,l?e.jsxs(e.Fragment,{children:[" · по программе до ",e.jsx("span",{className:"sn-mono",children:qe(l)})]}):null]}):"Эфир ещё не начинался — студия закроется для всех";return e.jsx(Ke,{open:s,onClose:()=>{y!=="ending"&&(F.current=!0,n())},width:580,className:"sn-shw-end",icon:e.jsx(jn,{className:"sn-i"}),iconTone:"red",title:e.jsx("span",{className:"sn-display",children:"Завершить эфир?"}),subtitle:se,footer:y==="final"?e.jsxs("div",{className:"sn-shw-end-foot",children:[e.jsx(R,{variant:"quiet",size:"lg",onClick:()=>{F.current=!0,w("confirm"),n(),u.show("Эфир продолжается — финал остался в эфире")},children:"Не завершать"}),e.jsx(R,{variant:"live",size:"lg",icon:e.jsx(jn,{className:"sn-i sn-i-16"}),onClick:()=>q(0),children:"Завершить сейчас"})]}):e.jsxs("div",{className:"sn-shw-end-foot",children:[e.jsx(R,{variant:"quiet",size:"lg",onClick:n,disabled:B,children:"Продолжить эфир"}),e.jsx(R,{variant:"live",size:"lg",icon:e.jsx(jn,{className:"sn-i sn-i-16"}),onClick:()=>void O(),loading:B,disabled:!t.perms.endMeeting&&!t.perms.manageStage,children:"Завершить эфир"})]}),children:y==="final"?e.jsxs("div",{className:"sn-shw-end-final",role:"status","aria-live":"polite",children:[e.jsx("span",{className:"sn-shw-end-count sn-display",children:T}),e.jsxs("div",{children:[e.jsxs("b",{children:["В эфире «",r==null?void 0:r.name,"»"]}),e.jsxs("span",{children:["Трансляция остановится через ",T," ",Xe(T,"секунду","секунды","секунд")]})]})]}):e.jsxs("div",{className:"sn-shw-end-body",children:[e.jsxs("section",{children:[e.jsx("h3",{className:"sn-eyebrow",children:"Что произойдёт"}),e.jsxs("ul",{className:"sn-shw-end-list",children:[e.jsxs("li",{children:[e.jsx("span",{className:"sn-shw-end-ico",children:e.jsx(ws,{className:"sn-i sn-i-16"})}),e.jsxs("div",{children:[e.jsx("b",{children:f?`Эфир остановится на ${U.length} ${Xe(U.length,"площадке","площадках","площадках")}`:"Студия закроется"}),e.jsx("span",{children:f?gr(U):"Команда и гости увидят экран завершения"})]})]}),e.jsxs("li",{children:[e.jsx("span",{className:"sn-shw-end-ico",children:e.jsx(pt,{className:"sn-i sn-i-16"})}),e.jsxs("div",{children:[e.jsx("b",{children:$?"Запись сохранится":c?"Запись уже остановлена":"Запись не ведётся"}),e.jsx("span",{children:$?"и попадёт в «Записи и итоги» — горизонтальная 16:9":c?"Записанная часть эфира — в «Записях и итогах»":"Этот эфир не попадёт в «Записи и итоги» видеофайлом"})]})]}),g&&r&&e.jsxs("li",{children:[e.jsx("span",{className:"sn-shw-end-ico",children:e.jsx($l,{className:"sn-i sn-i-16"})}),e.jsxs("div",{children:[e.jsxs("b",{children:["Зрители увидят сцену «",r.name,"»"]}),e.jsx("span",{children:(X=r.title)!=null&&X.heading?`«${r.title.heading}»`:"перед тем, как трансляция остановится"})]})]})]})]}),e.jsxs("section",{"aria-label":"Параметры завершения",className:"sn-shw-end-opts",children:[g&&r?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sn-shw-switchrow",children:[e.jsxs("div",{children:[e.jsxs("b",{children:["Показать «",r.name,"» ",Lt," секунд перед завершением"]}),e.jsx("span",{children:"Потом трансляция остановится сама"})]}),e.jsx(Pe,{checked:p,onChange:N,label:`Показать «${r.name}» перед завершением`})]}),e.jsxs("div",{className:"sn-shw-switchrow",children:[e.jsxs("div",{children:[e.jsx("b",{children:"Открыть опрос «Оцените эфир»"}),e.jsx("span",{children:h?"Появится у зрителей в чате вместе с финалом":"Ð
111ÑƒÐ¶Ð½Ð¾ соединение с чатом комнаты"})]}),e.jsx(Pe,{checked:h&&p&&k,onChange:b,label:"Открыть опрос «Оцените эфир»",disabled:!h||!p})]})]}):f?e.jsx("div",{className:"sn-shw-switchrow",children:e.jsxs("div",{children:[e.jsx("b",{children:"Финальной сцены нет"}),e.jsx("span",{children:"Назовите сцену «Финал» — её можно будет показать перед завершением"})]})}):null,i.event&&e.jsxs("div",{className:"sn-shw-switchrow",children:[e.jsx("span",{className:"sn-shw-mix-ico is-blue",children:e.jsx(Ro,{className:"sn-i sn-i-16"})}),e.jsxs("div",{children:[e.jsx("b",{children:"Письмо зрителям со ссылкой на запись"}),e.jsx("span",{children:v?`${He(v)} ${Xe(v,"зарегистрированному","зарегистрированным","зарегистрированным")} — уходит само через 2 часа после начала`:"Уходит само всем, кто зарегистрируется, через 2 часа после начала"})]}),e.jsx(Re,{className:"sn-i sn-i-16",style:{color:"var(--sn-green)"},"aria-label":"включено"})]})]}),C&&e.jsx("div",{className:"sn-shw-note is-warn",role:"alert",children:C})]})})}function Ku(s,n,t){const[a,i]=d.useState(null);return d.useEffect(()=>{if(!t)return;let l=!1,r=null;const m=Date.now(),o=async()=>{try{const c=await Ae.get(`rooms/${encodeURIComponent(s)}/recordings`);if(l)return;const u=(c.recordings||[]).filter(f=>!n||Date.parse(f.createdAt)>=n-10*6e4);i(u),u.some(f=>f.status!=="ready"&&f.status!=="error")&&Date.now()-m<15*6e4&&(r=window.setTimeout(o,5e3))}catch{!l&&Date.now()-m<2*6e4&&(r=window.setTimeout(o,8e3))}};return o(),()=>{l=!0,r!==null&&window.clearTimeout(r)}},[s,n,t]),a}function Wu(s,n,t,a=!0){const[i,l]=d.useState(a?n.transcript.length?"waiting":"none":"off"),[r,m]=d.useState(null),[o,c]=d.use
111State(null),u=d.useRef(!1),x=async()=>{l("writing"),c(null);try{const f=await Ae.post(`ai/summarize/${encodeURIComponent(s)}`,{transcript:n.transcript.slice(-1500).map((g,h)=>({speakerName:g.speakerName||"Спикер",text:g.text,startTime:typeof g.startOffsetMs=="number"?g.startOffsetMs:h,timestamp:g.timestamp})),config:{title:t,...n.workspaceId?{workspaceId:n.workspaceId}:{}}});m(f),l("ready")}catch(f){c(js(f,"AI сейчас недоступен")),l("failed")}};return d.useEffect(()=>{if(u.current||(u.current=!0,!a)||!n.transcript.length)return;if(n.endedByMe){x();return}let f=!1,g=null,h=0;const p=async()=>{const N=await Ae.get(`ai/summarize/${encodeURIComponent(s)}/latest`).catch(()=>null);if(!f){if(N&&((N.keyDecisions||[]).length||(N.actionItems||[]).length||N.summary)){m(N),l("ready");return}h+=1,h<18&&(g=window.setTimeout(p,1e4))}};return g=window.setTimeout(p,8e3),()=>{f=!0,g!==null&&window.clearTimeout(g)}},[s]),{state:i,summary:r,error:o,retry:x}}function At({icon:s,label:n,value:t,sub:a}){return e.jsxs("div",{className:"sn-shw-ended-stat",children:[e.jsxs("span",{className:"sn-shw-ended-stat-l",children:[s,n]}),e.jsx("b",{className:"sn-display",children:t}),e.jsx("span",{className:"sn-hint",children:a})]})}function Gu({api:s,snapshot:n,data:t}){var p,N,k,b;const a=((p=t.event)==null?void 0:p.title)||s.room.title||"Эфир",i=n.liveSince?Math.max(0,Math.floor((n.endedAt-n.liveSince)/1e3)):0,l=Ku(s.room.id,n.liveSince,n.recorded),r=Wu(s.room.id,n,a,((N=s.roomFeatures)==null?void 0:N.aiSummary)!==!1),m=s.room.id,o=(l==null?void 0:l[0])||null,c=n.recorded?!l||!o||l.some(y=>y.status!=="ready"&&y.status!=="error")?"processing":o.status==="error"?"error":"ready":"none",u=l!=null&&l.length?l.reduce((y,w)=>y+(w.durationSeconds||0),0):n.recordedSec,x=(((k=r.summary)==null?void 0:k.keyDecisions)||[]).length,f=(((b=r.summary)==null?void 0:b.actionItems)||[]).length,g=y=>`${new Date(y).toDateString()===new Date().toDateString()?"Сегодня, ":""}${fo(y)}`,h=n.liveSince?`${g(n.liveSince)} · ${qe(n.liveSince)}–${qe(n.endedAt)}`:`${g(n.endedAt)} · ${qe(n.endedAt)}`;return e.jsxs("div",{className:"sn sn-shw-ended",role:"dialog","aria-modal":"true","aria-label":"Эфир завершён",children:[e.jsxs("header",{className:"sn-shw-ended-head",children:[e.jsx("a",{href:Ln.dashboard(),"aria-label":"SNICH — в кабинет",children:e.jsx(Yr,{size:26,textSize:18})}),e.jsx("span",{className:"sn-shw-ended-sep"}),e.jsx("b",{className:"sn-ellipsis",children:a}),e.jsxs(ns,{tone:"gray",children:[e.jsx("span",{"aria-hidden":"true",style:{width:7,height:7,borderRadius:"50%",background:"var(--sn-ink-3)"}}),"Эфир завершён"]}),e.jsx("span",{style:{flex:1}}),e.jsxs("span",{className:"sn-hint",style:{fontSize:13},children:["Вы ",fr(s)]}),e.jsx(Ve,{name:s.me.name,src:s.me.avatarUrl||void 0,size:36})]}),e.jsxs("main",{className:"sn-shw-ended-main",children:[e.jsxs("div",{className:"sn-shw-ended-top",children:[e.jsxs("div",{children:[e.jsx("span",{className:"sn-eyebrow",children:h}),e.jsx("h1",{className:"sn-display",children:n.wasLive||n.liveSince?"Эфир завершён":"Студия закрыта"}),e.jsxs("p",{children:[i?e.jsxs(e.Fragment,{children:["Длительность ",e.jsx("b",{className:"sn-mono",children:Nt(i)})]}):"Эфир не выходил к зрителям",n.platforms.length?` · ${gr(n.platforms)}`:""," · спасибо команде!"]})]}),e.jsxs("div",{className:"sn-shw-ended-actions",children:[e.jsx(R,{variant:"quiet",size:"lg",href:Ln.dashboard(),children:"В кабинет"}),e.jsx(R,{variant:"primary",size:"lg",icon:e.jsx(Vn,{className:"sn-i sn-i-16"}),href:Ln.recording(m),children:"Открыть итоги"})]})]}),e.jsxs("section",{className:"sn-shw-ended-stats","aria-label":"Цифры эфира",children:[e.jsx(At,{icon:e.jsx(gs,{className:"sn-i sn-i-16"}),label:"Пик зрителей",value:He(n.peak),sub:"одновременно на странице эфира"}),e.jsx(At,{icon:e.jsx(wn,{className:"sn-i sn-i-16"}),label:"Вопросов",value:He(n.questions),sub:`отвечено ${He(n.answered)}`}),e.jsx(At,{icon:e.jsx(ro,{className:"sn-i sn-i-16"}),label:"Реакций",value:He(n.reactions),sub:"за весь эфир"}),e.jsx(At,{icon:e.jsx(Hs,{className:"sn-i sn-i-16"}),label:"Сообщений в чате",value:He(n.chat),sub:"в общем чате"})]}),e.jsxs("div",{className:"sn-shw-ended-cards",children:[e.jsxs("section",{className:"sn-shw-ended-card is-rec","aria-label":"Запись",children:[e.jsxs("div",{className:"sn-shw-ended-poster",children:[e.jsx("img",{src:Tl,alt:"",width:22,height:22}),e.jsx("b",{className:"sn-display",children:n.finalHeading||a}),n.finalSub&&e.jsx("span",{children:n.finalSub}),u>0&&e.jsx("i",{className:"sn-mono",children:fs(u)})]}),e.jsxs("div",{className:"sn-shw-ended-rec",children:[e.jsxs("div",{className:"sn-shw-ended-card-h",children:[e.jsx("h2",{children:"Запись"}),c==="processing"&&e.jsx(ns,{tone:"amber",children:"обработка"}),c==="ready"&&e.jsx(ns,{tone:"green",children:"готова"}),c==="error"&&e.jsx(ns,{tone:"red",children:"ошибка"}),c==="none"&&e.jsx(ns,{tone:"gray",children:"не велась"})]}),e.jsx("p",{children:c==="none"?"Запись не включаÐ
111»Ð¸ — в «Записях и итогах» будут расшифровка и итоги, если стенографист работал.":"Сохранится в «Записи и итоги». Главы — по блокам программы."}),c==="processing"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"sn-shw-indet",role:"progressbar","aria-label":"Обработка записи"}),e.jsx("span",{className:"sn-hint",style:{fontSize:13},children:"Собираем запись 16:9 из частей — обычно пара минут"})]}),c==="error"&&e.jsx("span",{className:"sn-hint",style:{fontSize:13},children:"Часть записи не собралась — загляните в «Записи и итоги»."}),c!=="none"&&(o!=null&&o.downloadUrl?e.jsx(R,{size:"sm",variant:"quiet",icon:e.jsx(Oa,{className:"sn-i sn-i-16"}),href:o.downloadUrl,download:!0,style:{alignSelf:"flex-start"},children:"Скачать запись"}):e.jsx(R,{size:"sm",variant:"quiet",icon:e.jsx(Oa,{className:"sn-i sn-i-16"}),disabled:!0,style:{alignSelf:"flex-start"},children:"Скачать запись"}))]})]}),e.jsxs("section",{className:"sn-shw-ended-card","aria-label":"AI-итоги",children:[e.jsxs("div",{className:"sn-shw-ended-card-h",children:[e.jsx("span",{className:"sn-shw-mix-ico is-blue",children:e.jsx(Vn,{className:"sn-i sn-i-16"})}),e.jsx("h2",{children:"AI-итоги"}),r.state==="writing"||r.state==="waiting"?e.jsx(ns,{tone:"blue",children:"готовим"}):r.state==="ready"?e.jsx(ns,{tone:"green",children:"готовы"}):r.state==="failed"?e.jsx(ns,{tone:"red",children:"не получилось"}):r.state==="off"?e.jsx(ns,{tone:"gray",children:"выключены"}):e.jsx(ns,{tone:"gray",children:"нет расшифровки"})]}),e.jsx("p",{children:r.state==="off"?"AI-итоги выключены в настройках эфира — конспект и задачи не готовим.":r.state==="none"?"Стенографист был выключен — без расшифровки конспекта и задач не будет.":"Конспект, решения и задачи — в «Записях и итогах» этого эфира."}),e.jsxs("ul",{className:"sn-shw-ended-steps",children:[e.jsxs("li",{className:n.transcript.length?"is-done":"is-off",children:[e.jsx("i",{}),"Расшифровка",e.jsx("span",{children:n.transcript.length?`${He(n.transcript.length)} ${Xe(n.transcript.length,"реплика","реплики","реплик")}`:"не велась"})]}),e.jsxs("li",{className:r.state==="ready"?"is-done":r.state==="writing"?"is-busy":r.state==="failed"?"is-fail":"is-off",children:[e.jsx("i",{}),"Конспект и решения",e.jsx("span",{children:r.state==="ready"?`${x} ${Xe(x,"решение","решения","решений")}`:r.state==="writing"?"пишем":r.state==="failed"?"ошибка":r.state==="waiting"?"в очереди":"—"})]}),e.jsxs("li",{className:r.state==="ready"?"is-done":r.state==="failed"?"is-fail":"is-off",children:[e.jsx("i",{}),"Задачи с ответственными",e.jsx("span",{children:r.state==="ready"?`${f} ${Xe(f,"задача","задачи","задач")}`:r.state==="writing"||r.state==="waiting"?"в очереди":"—"})]})]}),r.state==="failed"&&e.jsxs("div",{className:"sn-shw-note is-warn",style:{alignItems:"center"},children:[e.jsx("span",{style:{flex:1},children:r.error}),e.jsx(R,{size:"xs",variant:"quiet",onClick:()=>void r.retry(),children:"Ещё раз"})]})]})]}),e.jsxs("section",{className:"sn-shw-ended-next","aria-label":"Что дальше",children:[e.jsx("h2",{className:"sn-eyebrow",children:"Что дальше"}),e.jsxs("div",{children:[e.jsxs("a",{className:"sn-shw-ended-link",href:Ln.recording(m),children:[e.jsx("span",{className:"sn-shw-end-ico",children:e.jsx(Do,{className:"sn-i sn-i-16"})}),e.jsxs("span",{children:[e.jsx("b",{children:"Поделиться записью"}),e.jsx("span",{children:"Ссылка, доступ, встраивание"})]}),e.jsx(Ps,{className:"sn-i sn-i-16"})]}),e.jsxs("a",{className:"sn-shw-ended-link",href:Ln.recordings(),children:[e.jsx("span",{className:"sn-shw-end-ico",children:e.jsx(tt,{className:"sn-i sn-i-16"})}),e.jsxs("span",{children:[e.jsx("b",{children:"Все записи и итоги"}),e.jsx("span",{children:"Этот эфир будет первым в списке"})]}),e.jsx(Ps,{className:"sn-i sn-i-16"})]}),e.jsxs("a",{className:"sn-shw-ended-link",href:Ln.createBroadcast(),children:[e.jsx("span",{className:"sn-shw-end-ico",children:e.jsx(qo,{className:"sn-i sn-i-16"})}),e.jsxs("span",{children:[e.jsx("b",{children:"Запланировать новый эфир"}),e.jsx("span",{children:"Площадки и бренд сохранятся в пространстве"})]}),e.jsx(Ps,{className:"sn-i sn-i-16"})]})]})]})]})]})}const vr="sn-show:quality",_a=[{value:"stable",label:"1080p · стабильное",hint:"~9 Мбит/с — чёткая картинка, умеренная нагрузка"},{value:"max",label:"1080p · максимум",hint:"12 Мбит/с — нужен быстрый интернет и мощный компьютер"},{value:"economy",label:"720p · экономное",hint:"4,5 Мбит/с — для слабого интернета"}],Wt=[{value:"low",label:"Низкая",hint:"YouTube 2–5 с — живой разговор с чатом; VK и RUTUBE задают задержку сами"},{value:"normal",label:"Обычная",hint:"YouTube 5–10 с — подходит большинству эфиров"},{value:"stable",label:"Стабильная",hint:"YouTube 15–30 с — больше запас у зрителей со слабым интернетом"}];function Kn(){try{const s=JSON.parse(window.localStorage.getItem(vr)||"{}
111"),n=["stable","max","economy"].includes(s.quality)?s.quality:"stable",t=["low","normal","stable"].includes(s.latency)?s.latency:"normal",a=["public","unlisted","private"].includes(s.privacy)?s.privacy:"public";return{quality:n,latency:t,privacy:a}}catch{return{quality:"stable",latency:"normal",privacy:"public"}}}function br(s){try{window.localStorage.setItem(vr,JSON.stringify(s))}catch{}}function yr(s,n){return s==="9:16"?"vertical_1080p30":xo(n,"horizontal_1080p30")}function ut(s,n){const t=js(s,n);return/egress capacity/i.test(t)?"Серверы трансляции на площадки сейчас заняты. Эфир на странице SNICH идёт — подключите площадку через пару минут.":/private network|local publish/i.test(t)?"Адрес сервера ведёт в локальную сеть — укажите публичный RTMP-адрес площадки.":/cannot be resolved/i.test(t)?"Сервер площадки не найден — проверьте RTMP-адрес.":/only rtmp/i.test(t)?"Адрес сервера начинается с rtmp:// или rtmps://":t}async function Xi(s){try{await Ae.post(`rooms/${encodeURIComponent(s)}/show/live`,{})}catch{}}async function vi(s,n){var c;s.setAutoRecord(n.record);const t=s.room.id;if(!n.destinations.length){if(!s.startPageLive)return{ok:!1,error:"Студия устарела — обновите страницу"};const u=await s.startPageLive();return u.ok&&Xi(t),u}if(!s.startEgressLive)return{ok:!1,error:"Студия устарела — обновите страницу"};const a={};n.destinations.forEach(u=>{a[u.id]=yr(u.picture,n.quality)});const i=Array.from(new Set(Object.values(a))),l=i.find(u=>u!=="vertical_1080p30")||i[0],r={title:n.title.trim()||s.room.title||"SNICH Live",description:n.description.trim(),privacyStatus:n.privacy,startedFrom:"studio-v2-go-live",outputProfile:l,captionsMode:"none",destinationOutputProfiles:a,programSourceMode:"browser_whip",streamLatencyPreset:n.latency,browserVideoQuality:n.quality,browserDualIngest:i.length>1,browserAudioSafeMode:!0,browserDenoiseModel:"browser-native"};let m;try{const u=await Ae.post("/api/v1/streams/sessions/draft",{roomId:t,workspaceId:n.workspaceId,outputProfile:l,destinationIds:n.destinations.map(x=>x.id),destinationOutputProfiles:a,programSourceMode:"browser_whip",streamLatencyPreset:n.latency,metadata:r});m=await Ae.post(`/api/v1/streams/sessions/${encodeURIComponent(u.id)}/start`,{destinationOutputProfiles:a,programSourceMode:"browser_whip",streamLatencyPreset:n.latency,metadata:{...r,selectedDestinationIds:n.destinations.map(x=>x.id)}})}catch(u){return u instanceof Xa&&(u.status===409||((c=u.data)==null?void 0:c.code)==="active_stream_session_exists")?{ok:!1,error:"В этой комнате уже идёт трансляция — обновите страницу, чтобы управлять ею"}:{ok:!1,error:ut(u,"Не удалось подготовить трансляцию на площадки")}}const o=await s.startEgressLive(m);return o.ok&&Xi(t),o}async function Qu(s,n,t,a){return Ae.post(`/api/v1/streams/sessions/${encodeURIComponent(s)}/destinations`,{destinationId:n,outputProfile:yr(t,a)})}async function Yu(s){const n=s.url.trim(),t=s.provider||"custom_rtmp",a=await Ae.post("/api/v1/streams/destinations",{workspaceId:s.workspaceId,provider:t,displayName:s.name.trim().slice(0,80)||"Своя площадка",endpointUrl:n,streamKey:s.key.trim(),protocol:/^rtmps:/i.test(n)?"rtmps":"rtmp",...s.providerConfig?{providerConfig:s.providerConfig}:{}});return{...a,provider:a.provider||t}}const Gt=5,Ua=s=>`sn-backups:${s}`;function Nr(s){try{const n=JSON.parse(window.sessionStorage.getItem(Ua(s))||"[]");return Array.isArray(n)?n.map(Number).filter(t=>Number.isInteger(t)&&t>0):[]}catch{return[]}}function wr(s,n){try{n.length?window.sessionStorage.setItem(Ua(s),JSON.stringify(n)):window.sessionStorage.removeItem(Ua(s))}catch{}}function nt(s,n){var t;return n===null?"—":n===s.selfUserId?"Вы":((t=s.candidates.find(a=>a.userId===n))==null?void 0:t.name)||`Участник #${n}`}const ja=(s,n)=>n===s.selfUserId||!!s.candidates.find(t=>t.userId===n&&t.online);function Xu(s){return s.failover&&s.status!=="publishing"?{text:"переключение на резерв",tone
111:"amber"}:s.status==="publishing"?{text:"в эфире",tone:"green"}:s.status==="preparing"?{text:"подключается",tone:"amber"}:s.status==="disconnected"?{text:"потерян",tone:"red"}:{text:s.status==="idle"?"остановлен":"—",tone:"gray"}}function Ju(s){const n=s.encoders,t=d.useRef(null),a=!!n&&n.session&&n.canManage&&n.status==="publishing"&&n.publisherUserId!==null&&n.publisherUserId===n.selfUserId&&n.backupUserIds.length===0;d.useEffect(()=>{if(!a||!n)return;const i=`${s.room.id}:${n.publisherUserId}`;if(t.current===i)return;const l=Nr(s.room.id).filter(r=>r!==n.selfUserId).slice(0,Gt);l.length&&(t.current=i,n.savePlan({primaryUserId:n.selfUserId,backupUserIds:l}).then(()=>wr(s.room.id,[])).catch(()=>{}))},[a,n,s.room.id])}function Zu(s){const n=Se(),t=s.encoders,a=t!=null&&t.session?t.publisherUserId:null,i=d.useRef(a);d.useEffect(()=>{const l=i.current;i.current=a,!(!t||a===null||l===null||l===a||!s.live.isLive)&&(a===t.selfUserId?n.success("Эфир теперь идёт из вашего браузера — не закрывайте вкладку",{duration:1e4}):l===t.selfUserId&&n.show(`Эфир ведёт ${nt(t,a)}: ваш браузер в резерве`,{duration:8e3}))},[a,t,s.live.isLive,n])}function em({api:s}){const n=s.encoders,[t,a]=d.useState(()=>Nr(s.room.id));if(!n||!n.canManage)return null;const i=n.candidates.filter(r=>r.userId!==n.selfUserId),l=r=>{const m=t.includes(r)?t.filter(o=>o!==r):[...t,r].slice(0,Gt);a(m),wr(s.room.id,m)};return e.jsxs("div",{className:"sn-shw-box sn-enc-pick",children:[e.jsxs("div",{style:{minWidth:0},children:[e.jsx("b",{style:{fontSize:15},children:"Резервный кодировщик"}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5,display:"block",marginTop:4},children:i.length?"Если ваш браузер пропадёт, эфир подхватит резервный — по порядку выбора. Назначится сразу после старта.":"Нет других продюсеров в студии. Резервный входит в студию со своим аккаунтом по ссылке «Продюсер» — тогда его можно выбрать здесь или в панели «Эфир»."})]}),i.length>0&&e.jsx("div",{className:"sn-enc-chips",role:"group","aria-label":"Резервный кодировщик",children:i.map(r=>{const m=t.indexOf(r.userId);return e.jsxs("button",{type:"button",className:"sn-enc-chip","aria-pressed":m>=0,onClick:()=>l(r.userId),children:[m>=0?e.jsx("span",{className:"sn-enc-rank",children:m+1}):e.jsx(Is,{className:"sn-i sn-i-14","aria-hidden":"true"}),r.name]},r.userId)})})]})}function sm({api:s}){const n=Se(),t=s.encoders,[a,i]=d.useState(!1);if(!t||!t.session)return null;const l=Xu(t),r=t.selfUserId!==null&&t.publisherUserId===t.selfUserId,m=t.canManage||r,o=t.primaryUserId??t.publisherUserId,c=async(h,p)=>{i(!0);try{await h(),p&&n.success(p)}catch(N){const k=(N==null?void 0:N.message)||"";n.error(/publisher_role_required|role/i.test(k)?"У этого человека нет роли продюсера или ведущего в эфире":k||"Не удалось сохранить")}finally{i(!1)}},u=h=>c(()=>t.savePlan({primaryUserId:o,backupUserIds:h.filter(p=>p!==o).slice(0,Gt)})),x=(h,p)=>{const N=[...t.backupUserIds],k=h+p;k<0||k>=N.length||([N[h],N[k]]=[N[k],N[h]],u(N))},f=t.candidates.filter(h=>h.userId!==o&&h.userId!==t.publisherUserId&&!t.backupUserIds.includes(h.userId)),g=t.candidates.filter(h=>h.userId!==t.publisherUserId&&h.online);return e.jsxs("section",{className:"sn-shw-box sn-enc","aria-label":"Кто ведёт эфир",children:[e.jsxs("div",{className:"sn-enc-head",children:[e.jsx("span",{className:"sn-eyebrow",children:"Кто кодирует эфир"}),e.jsx(ns,{tone:l.tone==="gray"?"gray":l.tone,style:{height:22,fontSize:11.5},children:l.text})]}),e.jsxs("div",{className:"sn-enc-now",children:[e.jsx(ws,{className:"sn-i sn-i-16","aria-hidden":"true",style:{color:"var(--sn-red)"}}),e.jsx("b",{children:nt(t,t.publisherUserId)}),e.jsx("span",{className:"sn-hint",children:"браузер отдаёт эфир на площадки"})]}),t.handoverToUserId!==null&&e.jsxs("div",{className:"sn-enc-handover",role:"status",children:[e.jsxs("span",{children:["Передаём эфир → ",e.jsx("b",{children:nt(t,t.handoverToUserId)}),"…"]}),m&&e.jsx("button",{type:"button",className:"sn-enc-link",disabled:a,onClick:()=>void c(()=>t.handover(null)),children:"Отменить"})]}),e.jsx("span",{className:"sn-enc-sub",children:"Резерв по порядку"}),t.backupUserIds.length===0?e.jsx("p",{className:"sn-hint sn-enc-empty",children:"Резерв не назначен: при сбое эфир подхватит любой продюсер, который сейчас в студии."}):e.jsx("ol",{className:"sn-enc-list",children:t.backupUserIds.map((h,p)=>e.jsxs("li",{children:[e.jsx("span",{className:"sn-enc-rank",children:p+1}),e.jsx("span",{className:`sn-enc-dot${ja(t,h)?" is-on":""}`,title:ja(t,h)?"в студии":"не в студии"}),e.jsxs("span",{className:"sn-enc-name",children:[nt(t,h),!ja(t,h)&&e.jsx("span",{className:"sn-hint",children:" · не в студии"})]}),t.canManage&&e.jsxs("span",{className:"sn-enc-tools",children:[e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-xs","aria-label":"Выше",disabled:a||p===0,onClick:()=>x(p,-1),children:e.jsx(li,{className:"sn-i sn-i-14"})}),e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-xs","aria-label":"Ниже",disabled:a||p===t.backupUserIds.length-1,onClick:()=>x(p,1),children:e.jsx(ri,{className:"sn-i sn-i-14"})}),e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-xs","aria-label":`Убрать из резерва: ${nt(t,h)}`,disabled:a,onClick:()=>void u(t.backupUserIds.filter(N=>N!==h)),children:e.jsx(ct,{className:"sn-i sn-i-14"})})]})]},h))}),t.canManage&&f.length>0&&t.backupUserIds.length<Gt&&e.jsx("div",{className:"sn-enc-chips",role:"group","aria-label":"Добавить в резерв",children:f.map(h=>e.jsxs("button",{type:"button",className:"sn-enc-chip",disabled:a,onClick:()=>void u([...t.backupUserIds,h.userId]),children:[e.jsx(Is,{className:"sn-i sn-i-14","aria-hidden":"true"}),h.name]},h.userId))}),m&&g.length>0&&t.handoverToUserId===null&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sn-enc-sub",children:"Передать эфир"}),e.jsx("p",{className:"sn-hint sn-enc-empty",children:"Ваш браузер ведёт эфир, пока новый не подключится; площадки заметят паузу около секунды."}),e.jsx("div",{className:"sn-enc-chips",role:"group","aria-label":"Передать эфир",children:g.map(h=>e.jsxs("button",{type:"button",className:"sn-enc-chip",disabled:a,onClick:()=>void c(()=>t.handover(h.userId),`Передаём эфир: ${h.name}`),children:[e.jsx(_o,{className:"sn-i sn-i-14","aria-hidden":"true"}),h.name]},h.userId))})]})]})}const Pt=5,nm=new Set(["host","speaker","guest"]),ga=s=>String(s||"").trim().toLowerCase();function tm(s,n){const t=s.participants.filter(a=>!a.isLocal&&a.type==="user");return n.filter(a=>!nm.has(a.role)||a.isMe||a.status==="declined"||a.status==="cancelled"?!1:!t.some(i=>a.userId!==null&&String(i.userId??"")===String(a.userId)||ga(i.name)&&ga(i.name)===ga(a.name)))}function kr(s){var t;const n=(t=s.event)==null?void 0:t.slug;return n?`${window.location.origin}/e/${n}`:null}function am(s){return s.status==="ready"&&s.hasStreamKeySecret?{label:"подключено",tone:"green"}:s.status==="failed"?{label:"ошибка ключа",tone:"amber"}:s.hasStreamKeySecret?{label:"не проверено",tone:"gray"}:{label:"нет ключа",tone:"amber"}}function im({state:s}){return e.jsxs("span",{className:`sn-tag sn-tag-${s.tone} sn-shw-dest-state`,children:[s.tone==="green"?e.jsx(Re,{className:"sn-i",style:{width:13,height:13}}
111):null,s.label]})}function Ba({item:s}){return e.jsx("span",{className:"sn-shw-mark sn-mono","aria-hidden":"true",children:Fu(s.provider,s.displayName,s.endpointMasked??null,s.providerConfig??null)})}function Us(s){return s.provider==="custom_rtmp"&&aa(s.displayName,s.endpointMasked,s.providerConfig)?"Telegram":dn(s.provider,s.displayName)}const Jn={vk:{label:"VK Видео",provider:"vk_video",server:"rtmp://ovsu.okcdn.ru/input/",name:"VK Видео",help:"VK Видео → Студия → Трансляция → «Настроить программу для трансляции»: там URL и ключ."},youtube:{label:"YouTube",provider:"youtube",server:"rtmp://a.rtmp.youtube.com/live2",name:"YouTube",help:"YouTube Studio → Создать → Начать трансляцию → «Ключ трансляции»."},telegram:{label:"Telegram",provider:"custom_rtmp",server:"rtmps://dc4-1.rtmp.t.me/s/",name:"Telegram",help:"Канал → Трансляция → «Начать с помощью…»: там URL сервера и ключ."},other:{label:"Другая",provider:"custom_rtmp",server:"",name:"",help:"Адрес сервера и ключ потока есть в настройках трансляции на площадке."}};function Sr({open:s,onClose:n,workspaceId:t,onCreated:a,roomTitle:i}
111){const l=Se(),[r,m]=d.useState("vk"),[o,c]=d.useState(""),[u,x]=d.useState(""),[f,g]=d.useState(""),[h,p]=d.useState(!1),[N,k]=d.useState(null),b=T=>{const q=Jn[T];m(T),x(q.server),c(q.name&&(i!=null&&i.trim())?`${q.name} · ${i.trim()}`.slice(0,80):q.name),k(null)};d.useEffect(()=>{s&&(b("vk"),g(""))},[s]);const y=/^rtmps?:\/\/[^\s/]+/i.test(u.trim()),w=async()=>{if(!y){k("Адрес сервера начинается с rtmp:// или rtmps://");return}if(!f.trim()){k("Вставьте ключ потока из настроек площадки");return}p(!0),k(null);try{const T=Jn[r],q=await Yu({workspaceId:t,name:o,url:u,key:f,provider:T.provider,providerConfig:r==="telegram"?{platform:"telegram"}:void 0});l.success(`Площадка «${q.displayName}» добавлена`),a(q),n()}catch(T){k(ut(T,"Не удалось добавить площадку"))}finally{p(!1)}};return e.jsx(Ke,{open:s,onClose:n,title:"Площадка или ключ",subtitle:"Новый ключ включится в этом эфире; ключ хранится зашифрованным",icon:e.jsx(ps,{className:"sn-i"}),width:500,footer:e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"quiet",onClick:n,children:"Отмена"}),e.jsx(R,{variant:"primary",onClick:()=>void w(),loading:h,children:"Добавить"})]}),children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[e.jsx(we,{size:"sm",ariaLabel:"Площадка",value:r,onChange:b,options:Object.keys(Jn).map(T=>({value:T,label:Jn[T].label}))}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5,marginTop:-6},children:Jn[r].help}),e.jsx(ke,{label:"Название",hint:"Так ключ увидит команда — например, «VK Видео · конгресс»",children:e.jsx(Oe,{value:o,onChange:T=>c(T.target.value),placeholder:"Своя площадка",maxLength:80,"data-autofocus":!0})}),e.jsx(ke,{label:"Адрес сервера (RTMP URL)",children:e.jsx(Oe,{value:u,onChange:T=>x(T.target.value),placeholder:"rtmps://…",className:"sn-mono"})}),e.jsx(ke,{label:"Ключ потока",error:N,children:e.jsx(Gr,{value:f,onChange:T=>g(T.target.value),placeholder:"Ключ из настроек площадки",autoComplete:"off"})}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Ключ хранится зашифрованным и виден только в настройках пространства."})]})})}function lm(s){return sn(`sn-show:${s}:platforms`,{})}function mt(s,n,t){var a;return n[s.id]!==void 0?n[s.id]:(((a=t.settings)==null?void 0:a.restream)||[]).some(i=>i.destinationId===s.id&&i.enabled)}function rm({open:s,onClose:n,api:t,producer:a,data:i,choice:l}){var le,ie,as,Ze,cs,Fe;
111const r=Se(),m=ts(1e3),[o,c]=d.useState("setup"),[u,x]=d.useState(null),[f,g]=sn(`sn-show:${t.room.id}:format`,"16:9"),h=t.verticalFormat!==!1,p=h?f:"16:9",[N,k]=l,[b,y]=sn(`sn-show:${t.room.id}:pictures`,{}),[w,T]=d.useState(()=>Kn()),[q,C]=d.useState(!1),[_,K]=d.useState(""),[L,F]=d.useState(!1),[S,O]=d.useState(Pt),z=d.useRef(null);d.useEffect(()=>{s&&(c("setup"),x(null),T(Kn()),K(ne=>ne||t.room.title||""),i.reloadDestinations())},[s]);const M=t.perms.externalBroadcast,U=d.useMemo(()=>i.destinations.filter(ne=>ne.enabled&&ne.status!=="disabled"),[i.destinations]),$=ne=>M&&mt(ne,N,i),v=U.filter($),B=ne=>p==="both"?b[ne.id]||"16:9":p==="9:16"?"9:16":"16:9",se=tm(t,i.team),A=t.program.sceneId?((le=a.programScene)==null?void 0:le.name)||t.program.name:null,X=t.network.downlinkMbps,ae=t.network.online&&t.network.studioConnected&&(X===null||X>=5),ce=t.room.scheduledAt?Date.parse(t.room.scheduledAt):NaN,xe=ne=>i.program.find(je=>je.speakerIds.includes(ne.id))||null,ye=se.length?(()=>{const ne=se[0],je=xe(ne),Ee=je&&Number.isFinite(ce)?` выступает в ${qe(ce+je.startOffsetMin*6e4)}`:" ещё не подключился",ze=se.length>1?` (и ещё ${se.length-1})`:"";return`${ne.name.split(" ")[0]}${ze}${Ee} — начать можно без него, при старте мы ещё раз отправим напоминание.`})():null,be=["SNICH Live",...v.map(Us)],ge=be.length>1?`${be.slice(0,-1).join(", ")} и ${be[be.length-1]}`:be[0],rs=()=>{var ne;return{destinations:v.map(je=>({id:je.id,picture:B(je)})),format:p,record:t.autoRecord,latency:w.latency,quality:w.quality,privacy:w.privacy,title:_||t.room.title,description:"",workspaceId:((ne=i.event)==null?void 0:ne.workspaceId)??null}},Ie=async()=>{const ne=z.current||rs();c("launching"),ne.format==="9:16"&&t.aspect!=="9:16"&&t.setAspect("9:16"),ne.format!=="9:16"&&t.aspect!=="16:9"&&t.setAspect("16:9");const je=await vi(t,ne);if(!je.ok){x(je.error||"Не удалось начать эфир"),c("setup");return}se.length&&Ae.post(`rooms/${encodeURIComponent(t.room.id)}/team/remind`,{memberIds:se.map(Ee=>Ee.id)}).catch(()=>{}),r.success(ne.destinations.length?"Вы в эфире — площадки подключаются":"Вы в эфире"),n()},De=()=>{v.length&&!M||(br(w),z.current=rs(),x(null),O(Pt),c("countdown"))};if(d.useEffect(()=>{if(!s||o!=="countdown")return;if(S<=0){Ie();return}const ne=window.setTimeout(()=>O(je=>je-1),1e3);return()=>window.clearTimeout(ne)},[s,o,S]),d.useEffect(()=>{if(!s||o!=="countdown")return;const ne=je=>{je.key==="Escape"&&(je.preventDefault(),je.stopPropagation(),c("setup"))};return window.addEventListener("keydown",ne,!0),()=>window.removeEventListener("keydown",ne,!0)},[s,o]),!s)return null;const We=kr(i),W=((as=(ie=i.event)==null?void 0:ie.counts)==null?void 0:as.registrations)??null,oe=Number.isFinite(ce)?` · начало в ${qe(ce)}`:"";return e.jsxs(e.Fragment,{children:[e.jsx(Ke,{open:o==="setup",onClose:n,title:"Выход в эфир",subtitle:`${t.room.title}${oe} · сейчас ${qe(m)}`,icon:e.jsx(ws,{className:"sn-i"}),width:620,className:"sn-shw-golive",footer:e.jsxs("div",{className:"sn-shw-golive-foot",children:[e.jsxs("div",{style:{display:"flex",gap:12,width:"100%"},children:[e.jsx(R,{variant:"quiet",size:"lg",onClick:n,children:"Отмена"}),e.jsx(R,{variant:"live",size:"lg",icon:e.jsx(ws,{className:"sn-i"}),style:{flex:1},onClick:De,disabled:!t.perms.broadcastLive||!t.joined,children:"Выйти в эфир"})]}),e.jsxs("span",{className:"sn-hint",style:{fontSize:13},children:["После нажатия — отсчёт ",Pt," секунд, его можно отменить"]})]}),children:e.jsxs("div",{className:"sn-shw-golive-body",children:[u&&e.jsxs("div",{className:"sn-shw-note is-error",role:"alert",children:[e.jsx(Yn,{className:"sn-i sn-i-16"}),e.jsx("span",{children:u})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsx("h3",{className:"sn-eyebrow",children:"Где показываем"}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"включите нужные площадки"})]}),e.jsxs("ul",{className:"sn-shw-dests",children:[e.jsxs("li",{children:[e.jsx("span",{className:"sn-shw-mark sn-mono","aria-hidden":"true",children:"SN"}),e.jsxs("div",{className:"sn-shw-dest-text",children:[e.jsx("b",{children:"Страница эфира SNICH"}),e.jsxs("span",{children:[We?e.jsx("span",{className:"sn-mono",children:We.replace(/^https?:\/\//,"")}):"страница события",W!==null?` · ${W} зарегистрировались`:""]})]}),e.jsx(Pe,{checked:!0,onChange:()=>{},disabled:!0,label:"Страница эфира SNICH — всегда включена"})]}),U.map(ne=>{const je=$(ne);return e.jsxs("li",{children:[e.jsx(Ba,{item:ne}),e.jsxs("div",{className:"sn-shw-dest-text",children:[e.jsx("b",{children:Us(ne)}),e.jsxs("span",{children:[Ru(ne),!je&&M?" — не показываем":""]})]}),je&&p==="both"&&e.jsx(we,{size:"sm",ariaLabel:`Кадр для ${Us(ne)}`,value:B(ne),onChange:Ee=>y(ze=>({...ze,[ne.id]:Ee})),options:[{value:"16:9",label:"16:9"},{value:"9:16",label:"9:16"}]}),je&&e.jsx(im,{state:am(ne)}),e.jsx(Pe,{checked:je,disabled:!M,onChange:Ee=>k(ze=>({...ze,[ne.id]:Ee})),label:`Показывать на площадке ${Us(ne)}`})]},ne.id)})]}),!M&&e.jsx("p",{className:"sn-hint",style:{fontSize:12.5,margin:"6px 0 0"},children:"Трансляцию на внешние площадки запускают создатель эфира и продюсер."}),i.destinationsError&&M&&e.jsxs("p",{className:"sn-hint",style:{fontSize:12.5,margin:"6px 0 0"},children:["Площадки не загрузились: ",i.destinationsError]}),M&&e.jsx(R,{variant:"text",size:"sm",icon:e.jsx(ps,{className:"sn-i sn-i-16"}),onClick:()=>F(!0),style:{marginTop:4},children:"Добавить площадку или ключ"})]}),e.jsxs("div",{className:"sn-shw-golive-grid",children:[h&&e.jsxs("div",{className:"sn-shw-box",children:[e.jsxs("div",{style:{display:"flex",alignItems:"baseline",gap:10,flexWrap:"wrap"},children:[e.jsx("b",{style:{fontSize:15},children:"Формат"}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:p==="16:9"?"16:9 — для страницы, YouTube и VK":p==="9:16"?"9:16 — для Shorts и Клипов":"для каждой площадки свой кадр"})]}),e.jsx(we,{ariaLabel:"Формат эфира",value:p,onChange:ne=>g(ne),options:[{value:"16:9",label:"16:9"},{value:"9:16",label:"9:16"},{value:"both",label:"Оба",disabled:!v.length,title:v.length?void 0:"Включите хотя бы одну площадку"}],style:{width:"100%"}})]}),e.jsxs("div",{className:"sn-shw-box sn-shw-box-row",children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("b",{style:{fontSize:15,display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{className:"sn-shw-reddot"}),"Запись эфира"]}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5,display:"block",marginTop:4}
111,children:t.roomFeatures&&!t.roomFeatures.recording&&!t.recording.active?"Запись выключена в настройках эфира":"Попадёт в «Записи и итоги» вместе с AI-итогами"})]}),e.jsx(Pe,{checked:t.autoRecord,onChange:t.setAutoRecord,label:"Записывать эфир",disabled:!t.perms.recording})]}),e.jsx(em,{api:t})]}),e.jsxs("section",{children:[e.jsx("h3",{className:"sn-eyebrow",children:"Проверка"}),e.jsxs("ul",{className:"sn-shw-checks",children:[e.jsxs("li",{className:A?"is-ok":"is-warn",children:[A?e.jsx(Re,{className:"sn-i sn-i-16"}):e.jsx(Yn,{className:"sn-i sn-i-16"}),A?`Сцена: ${A}`:"В эфире пусто — выведите заставку"]}),e.jsxs("li",{className:se.length?"is-warn":"is-ok",children:[se.length?e.jsx(Yn,{className:"sn-i sn-i-16"}):e.jsx(Re,{className:"sn-i sn-i-16"}),se.length?`${se[0].name.split(" ")[0]} ещё не за кулисами`:"Спикеры за кулисами"]}),e.jsxs("li",{className:ae?"is-ok":"is-warn",children:[ae?e.jsx(Re,{className:"sn-i sn-i-16"}):e.jsx(Yn,{className:"sn-i sn-i-16"}),t.network.online?t.network.studioConnected?X!==null?e.jsxs(e.Fragment,{children:["Сеть ",e.jsx("span",{className:"sn-mono",children:X>=10?"от 10":String(X).replace(".",",")})," Мбит/с"]}):"Сеть в порядке":"Нет связи со студией":"Нет интернета"]})]}),ye&&e.jsx("p",{className:"sn-hint",style:{fontSize:13,margin:"8px 0 0"},children:ye})]}),e.jsxs("div",{className:`sn-shw-adv${q?" is-open":""}`,children:[e.jsxs("button",{type:"button",className:"sn-shw-adv-head","aria-expanded":q,onClick:()=>C(ne=>!ne),children:[e.jsx(oi,{className:"sn-i sn-i-16"}),e.jsxs("span",{children:[e.jsx("b",{children:"Дополнительно:"})," задержка, качество, ключи потока"]}),e.jsx(Gn,{className:"sn-i sn-i-16",style:{marginLeft:"auto",transform:q?"rotate(180deg)":void 0}})]}),q&&e.jsxs("div",{className:"sn-shw-adv-body",children:[e.jsx(ke,{label:"Название трансляции на площадках",children:e.jsx(Oe,{value:_,onChange:ne=>K(ne.target.value),maxLength:100})}),e.jsx(ke,{label:"Задержка",hint:(Ze=Wt.find(ne=>ne.value===w.latency))==null?void 0:Ze.hint,children:e.jsx(we,{ariaLabel:"Задержка",value:w.latency,onChange:ne=>T(je=>({...je,latency:ne})),options:Wt.map(ne=>({value:ne.value,label:ne.label}))})}),e.jsx(ke,{label:"Качество",hint:(cs=_a.find(ne=>ne.value===w.quality))==null?void 0:cs.hint,children:e.jsx(Bs,{ariaLabel:"Качество",value:w.quality,onChange:ne=>T(je=>({...je,quality:ne})),options:_a.map(ne=>({value:ne.value,label:ne.label}))})}),e.jsx(ke,{label:"Доступ на YouTube",hint:"Для трансляций, созданных через подключённый канал",children:e.jsx(we,{ariaLabel:"Доступ на YouTube",value:w.privacy,onChange:ne=>T(je=>({...je,privacy:ne})),options:[{value:"public",label:"Всем"},{value:"unlisted",label:"По ссылке"},{value:"private",label:"Закрыто"}]})}),e.jsxs("span",{className:"sn-hint",style:{fontSize:13},children:["Ключи потока и подключённые каналы — в ",e.jsx("a",{href:"/settings/integrations",target:"_blank",rel:"noreferrer",children:"настройках интеграций"}),"."]})]})]})]})}),(o==="countdown"||o==="launching")&&Kr.createPortal(e.jsx("div",{className:"sn-portal sn-overlay sn-shw-cd-overlay",children:e.jsxs("div",{className:"sn-shw-cd",role:"dialog","aria-modal":"true","aria-label":"Отсчёт до эфира",children:[e.jsxs("span",{className:"sn-tag sn-tag-live sn-shw-cd-tag",children:[e.jsx("i",{"aria-hidden":"true"}),"ВЫХОД В ЭФИР"]}),e.jsx(om,{value:o==="launching"?0:S,total:Pt,launching:o==="launching"}),e.jsx("h2",{className:"sn-shw-cd-title","aria-live":"assertive",children:o==="launching"?"Запускаем эфир…":`Эфир начнётся через ${S} ${S===1?"секунду":S<5?"секунды":"секунд"}`}),e.jsxs("p",{className:"sn-hint",style:{margin:0,fontSize:14,textAlign:"center"},children:[ge," · ",t.autoRecord?"запись включится сама":"без записи"]}),a.programScene?e.jsxs("div",{className:"sn-shw-cd-scene",children:[e.jsx("div",{className:"sn-shw-cd-thumb",children:e.jsx(Kt,{api:t,producer:a,scene:a.programScene})}),e.jsxs("div",{style:{minWidth:0},children:[e.jsxs("b",{children:["Первой в эфир выйдет сцена «",a.programScene.name,"»"]}),e.jsx("span",{className:"sn-hint",children:a.previewScene&&a.previewScene.id!==a.programScene.id?`Потом выведите «${a.previewScene.name}
111» из «Подготовки»`:"Следующую сцену выберите в «Подготовке»"})]})]}):e.jsxs("div",{className:"sn-shw-cd-scene is-warn",children:[e.jsx(Yn,{className:"sn-i"}),e.jsxs("div",{children:[e.jsx("b",{children:"В эфире пока пусто"}),e.jsx("span",{className:"sn-hint",children:"Зрители увидят пустой кадр — выведите сцену сразу после старта"})]})]}),e.jsxs(R,{variant:"quiet",size:"lg",block:!0,onClick:()=>c("setup"),disabled:o==="launching",children:["Отменить ",e.jsx(Ga,{children:"Esc"})]}),e.jsx(R,{variant:"text",className:"sn-shw-cd-skip",onClick:()=>O(0),disabled:o==="launching",iconRight:e.jsx(Xs,{className:"sn-i sn-i-16"}),children:"Сразу в эфир"})]})}),document.body),e.jsx(Sr,{open:L,onClose:()=>F(!1),workspaceId:((Fe=i.event)==null?void 0:Fe.workspaceId)??null,roomTitle:t.room.title,onCreated:ne=>{const je=ne.provider==="custom_rtmp"?[]:i.destinations.filter(Ee=>Ee.provider===ne.provider).map(Ee=>Ee.id);k(Ee=>({...Ee,...Object.fromEntries(je.map(ze=>[ze,!1])),[ne.id]:!0})),i.reloadDestinations()}})]})}function om({value:s,total:n,launching:t}){const i=2*Math.PI*104,l=t?1:Math.max(0,Math.min(1,s/n));return e.jsxs("div",{className:"sn-shw-cd-ring",children:[e.jsxs("svg",{viewBox:"0 0 232 232",width:"232",height:"232","aria-hidden":"true",children:[e.jsx("circle",{cx:"116",cy:"116",r:104,fill:"none",stroke:"var(--sn-sunk)",strokeWidth:"8"}),e.jsx("circle",{cx:"116",cy:"116",r:104,fill:"none",stroke:"var(--sn-red)",strokeWidth:"8",strokeLinecap:"round",strokeDasharray:i,strokeDashoffset:i*(1-l),transform:"rotate(-90 116 116)",style:{transition:"stroke-dashoffset 1s linear"}})]}),e.jsx("span",{className:"sn-shw-cd-num",children:t?e.jsx("span",{className:"sn-spinner",style:{width:48,height:48}}):s})]})}const va=[{key:"light",label:"Светлая",theme:"classic",style:"classic"},{key:"dark",label:"Тёмная",theme:"minimal",style:"minimal"},{key:"brand",label:"Бренд",theme:"block",style:"block"}],ba=8;function Ji({theme:s,color:n,name:t,title:a,small:i}){const l=yo(s,n);return e.jsxs("span",{className:`sn-shw-plate${i?" is-small":""}`,style:{background:l.bg},children:[e.jsx("b",{style:{color:l.name},children:t||"Имя"}),!i&&a?e.jsx("span",{style:{color:l.title},children:a}):null,i&&e.jsx("i",{style:{background:s==="brand"?"rgba(255,255,255,.7)":n}})]})}function cm({open:s,onClose:n,api:t,producer:a,focusId:i}){var _,K;const l=Se(),r=((_=a.cfg.config)==null?void 0:_.lowerThirds)||null,m=/^#[0-9a-f]{6}$/i.test(t.brand.color||"")?t.brand.color:"#0A72C6",[o,c]=d.useState([]),[u,x]=d.useState(null),[f,g]=d.useState("light"),[h,p]=d.useState(!1),[N,k]=d.useState(!1);d.useEffect(()=>{var z,M;if(!s)return;const L=$s(t),F=(r==null?void 0:r.items)||{},S=L.map(U=>{var v,B;const $=t.personKeyOf(U);return{key:$,participant:U,name:U.name||((v=F[$])==null?void 0:v.name)||"",title:U.headline||((B=F[$])==null?void 0:B.title)||""}});Object.entries(F).forEach(([U,$])=>{S.some(v=>v.key===U)||U.startsWith("g:")&&S.push({key:U,participant:null,name:$.name,title:$.title})}),c(S);const O=i?S.find(U=>{var $;return(($=U.participant)==null?void 0:$.id)===i}):null;x((O==null?void 0:O.key)||((z=S.find(U=>t.stageParticipants.some($=>{var v;return $.id===((v=U.participant)==null?void 0:v.id)})))==null?void 0:z.key)||((M=S[0])==null?void 0:M.key)||null),g(Ta(t.brand.theme)),p(!!(r!=null&&r.autoHideSec))},[s,i]);const b=o.find(L=>L.key===u)||o[0]||null,y=(L,F)=>c(S=>S.map(O=>O.key===L?{...O,...F}:O)),w=async()=>{var L;k(!0);try{const F={...(r==null?void 0:r.items)||{}};let S=0;for(const M of o){const U=M.name.trim().slice(0,60),$=M.title.trim().slice(0,120);if(U)if(M.participant)(U!==(M.participant.name||"")||$!==(M.participant.headline||""))&&((L=t.setLowerThird)==null||L.call(t,M.participant.id,U,$),S+=1),F[M.key]={name:U,title:$};else{const v=`g:${U.toLowerCase()}`;M.key!==v&&delete F[M.key],F[v]={name:U,title:$}}}o.filter(M=>!M.participant&&!M.name.trim()).forEach(M=>delete F[M.key]);const O=va.find(M=>M.key===f)||va[0];Ta(t.brand.theme)!==f&&t.updateBrand({theme:O.theme});const z=await a.cfg.save({lowerThirds:{style:O.style,autoHideSec:h?ba:null,items:F}});if(!z.ok){l.error(z.error||"Не удалось сохранить плашки");return}l.success(S?"Плашки обновлены — зрители видят новые имена":"Плашки сохранены"),n()}finally{k(!1)}},T=(b==null?void 0:b.name)||((K=b==null?void 0:b.participant)==null?void 0:K.name)||"",q=(b==null?void 0:b.title)||"",C=t.perms.branding||t.perms.manageStage;return e.jsx(Ke,{open:s,onClose:n,title:"Плашки с именами",subtitle:"Имя и должность под человеком в кадре — зрители сразу понимают, кто говорит",icon:e.jsx(la,{className:"sn-i"}),width:1e3,className:"sn-shw-lt",footer:e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"quiet",onClick:n,children:"Отмена"}),e.jsx(R,{variant:"primary",onClick:()=>void w(),loading:N,disabled:!C,children:"Сохранить"})]}),children:e.jsxs("div",{className:"sn-shw-lt-grid",children:[e.jsxs("section",{"aria-label":"Люди",children:[e.jsxs("div",{className:"sn-shw-lt-cols",children:[e.jsx("span",{}),e.jsx("span",{children:"Имя"}),e.jsx("span",{children:"Должность"})]}),!o.length&&e.jsx("span",{className:"sn-hint",style:{fontSize:13},children:"Пока в студии никого нет — добавьте плашку для гостя заранее."}),o.map(L=>e.jsxs("div",{className:`sn-shw-lt-row${L.key===(b==null?void 0:b.key)?" is-on":""}`,onFocus:()=>x(L.key),onClick:()=>x(L.key),children:[L.participant?e.jsx(Ve,{name:L.participant.name,src:L.participant.avatarUrl||void 0,size:44}):e.jsx("span",{className:"sn-shw-lt-guest",title:"Гость ещё не в студии",children:e.jsx(la,{className:"sn-i sn-i-16"})}),e.jsx(Oe,{"aria-label":`Имя: ${L.name||"гость"}`,value:L.name,onChange:F=>y(L.key,{name:F.target.value}),maxLength:60,disabled:!C,placeholder:"Имя"}),e.jsx(Oe,{"aria-label":`Должность: ${L.name||"гость"}`,value:L.title,onChange:F=>y(L.key,{title:F.target.value}),maxLength:120,disabled:!C,placeholder:"Должность или компания"}),!L.participant&&e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":"Убрать плашку гостя",onClick:()=>c(F=>F.filter(S=>S.key!==L.key)),children:e.jsx(ls,{className:"sn-i sn-i-16"})})]},L.key)),C&&e.jsx(R,{size:"sm",variant:"text",icon:e.jsx(ps,{className:"sn-i sn-i-16"}),onClick:()=>{const L=`new:${Date.now()}`;c(F=>[...F,{key:L,participant:null,name:"",title:""}]),x(L)},children:"Плашка для гостя"}),e.jsxs("p",{className:"sn-hint",style:{fontSize:13,margin:0,display:"flex",gap:6,alignItems:"flex-start"},children:[e.jsx(un,{className:"sn-i sn-i-16",style:{flex:"none",marginTop:1}}),"Гостям со сцены плашка создаётся из имени, которое они ввели при входе. Плашка гостя подставится, когда он зайдёт с тем же именем."]})]}),e.jsxs("section",{"aria-label":"Вид плашки",className:"sn-shw-lt-side",children:[e.jsxs("span",{className:"sn-shw-label",children:["Превью",T?` · ${T}`:""]}),e.jsxs("div",{className:"sn-shw-lt-preview",children:[b!=null&&b.participant?e.jsx(Aa,{participant:b.participant,width:420}):e.jsx("div",{className:"sn-shw-lt-empty",children:e.jsx(la,{className:"sn-i"})}),e.jsx("div",{className:"sn-shw-lt-plate",children:e.jsx(Ji,{theme:f,color:m,name:T,title:q})})]}),e.jsx("span",{className:"sn-shw-label",children:"Стиль"}),e.jsx("div",{className:"sn-shw-lt-styles",role:"group","aria-label":"Стиль плашек",children:va.map(L=>e.jsxs("button",{type:"button","aria-pressed":f===L.key,onClick:()=>g(L.key),disabled:!C,children:[e.jsx("span",{className:"sn-shw-lt-style-art",children:e.jsx(Ji,{theme:L.key,color:m,name:T||"Имя",title:"",small:!0})}),L.label]},L.key))}),e.jsxs("div",{className:"sn-shw-switchrow is-box",children:[e.jsxs("div",{children:[e.jsxs("b",{children:["Показывать ",ba," секунд после выхода в кадр"]}),e.jsx("span",{children:"Потом плашка скроется, чтобы не закрывать кадр"})]}),e.jsx(Pe,{checked:h,onChange:p,label:`Показывать ${ba} секунд, когда человек выходит в кадр`,disabled:!C})]})]})]})})}function dm(s,n){var o,c,u,x;const t=ht.useRef({}),a=(c=(o=n.cfg.config)==null?void 0:o.lowerThirds)==null?void 0:c.items,i=((x=(u=n.cfg.config)==null?void 0:u.lowerThirds)==null?void 0:x.autoHideSec)||null,l=$s(s),r=l.map(f=>`${f.id}:${f.name}:${f.headline||""}`).join("|");d.useEffect(()=>{!a||!s.setLowerThird||!s.perms.manageStage||l.forEach(f=>{var p;const g=s.personKeyOf(f),h=a[g];!h||t.current[f.id]||(t.current[f.id]=!0,(h.name&&h.name!==f.name||(h.title||"")!==(f.headline||""))&&((p=s.setLowerThird)==null||p.call(s,f.id,h.name||f.name,h.title||"")))})},[r,a]);const m=s.lastProgramChange;d.useEffect(()=>{if(!i||!(m!=null&&m.takenByMe)||!n.prefs.names)return;const f=window.setTimeout(()=>{s.updateBrand({showNames:!1,showHeadlines:!1})},i*1e3);return()=>window.clearTimeout(f)},[m==null?void 0:m.revision,i])}const um=5e3,Ha=60;function mm(s){var r;const n=d.useRef(null);n.current=((r=s.streamPublisher)==null?void 0:r.stats)??null;
111const t=s.live.isLive&&!!s.streamSession,[a,i]=d.useState([]),l=d.useRef(null);return d.useEffect(()=>{if(!t){l.current=null;return}const m=()=>{const c=n.current;if(!c)return;const u=Number(c.videoBitrateKbps||0)+Number(c.audioBitrateKbps||0),x=Number(c.framesEncoded??NaN),f=Number(c.framesDropped??NaN);let g=null;if(Number.isFinite(x)&&Number.isFinite(f)){const h=l.current;if(h){const p=x-h.encoded,N=f-h.dropped;g=p+N>0?Math.max(0,N/(p+N)*100):0}l.current={encoded:x,dropped:f}}i(h=>[...h.slice(-(Ha-1)),{t:Date.now(),kbps:u,dropPct:g}])};m();const o=window.setInterval(m,um);return()=>window.clearInterval(o)},[t]),a}function Cr(s){const n=s/1e3;return n>=10?String(Math.round(n)):n.toFixed(1).replace(".",",")}function hm({samples:s}){const n=Math.max(8e3,...s.map(i=>i.kbps)),t=Math.ceil(n/4e3)*4,a=s.length?s.reduce((i,l)=>i+l.kbps,0)/s.length:0;return e.jsxs("div",{className:"sn-shw-chart",role:"img","aria-label":s.length?`Битрейт за последние 5 минут: в среднем ${Cr(a)} Мбит/с`:"Битрейт появится через несколько секунд",children:[e.jsxs("div",{className:"sn-shw-chart-axis sn-mono",children:[e.jsx("span",{children:t}),e.jsx("span",{children:t/2}),e.jsx("span",{children:"0"})]}),e.jsx("div",{className:"sn-shw-chart-bars",children:Array.from({length:Ha}).map((i,l)=>{const r=s[s.length-Ha+l],m=r?Math.max(2,Math.round(r.kbps/1e3/t*100)):0,o=r?r.kbps<1500:!1;return e.jsx("span",{className:o?"is-low":void 0,style:{height:`${m}%`}},l)})}),e.jsxs("div",{className:"sn-shw-chart-foot",children:[e.jsx("span",{children:"−5 мин"}),e.jsx("span",{children:"Мбит/с"}),e.jsx("span",{children:"сейчас"})]})]})}function xm(s){const[n,t]=d.useState(null),a=ts(2e3);return[n&&a-n.at<8e3?n.session:s.streamSession??null,l=>t({session:l,at:Date.now()})]}function fm(s,n){const[t,a]=d.useState({});return d.useEffect(()=>{if(!s||!n){a({});return}let i=!1;const l=()=>Ae.get(`/api/v1/streams/sessions/${encodeURIComponent(s)}/platform-viewers`).then(m=>{i||a(Object.fromEntries(((m==null?void 0:m.items)||[]).map(o=>[o.runtimeDestinationId,typeof o.viewers=="number"?o.viewers:null])))}).catch(()=>{});l();const r=window.setInterval(()=>void l(),3e4);return()=>{i=!0,window.clearInterval(r)}},[s,n]),t}const Zi=15e3,Va=new Map;function $r(){const[,s]=d.useState(0);return d.useEffect(()=>{const n=window.setInterval(()=>{[...Va.values()].some(t=>Date.now()-t<Zi+1e3)&&s(t=>t+1)},1e3);return()=>window.clearInterval(n)},[]),n=>Date.now()-(Va.get(n)||0)<Zi}async function Ir(s,n,t){const a=await Ae.post(`/api/v1/streams/sessions/${encodeURIComponent(s)}/destinations/${encodeURIComponent(n)}/${t}`,{});return t==="restart"&&Va.set(n,Date.now()),a}function pm({api:s,data:n,choice:t,samples:a,onOpenRecording:i,onOpenGoLive:l}){var rs,Ie,De,We;const r=Se(),m=$r();ts(1e3);const[o,c]=xm(s),[u,x]=t,[f,g]=d.useState(null),[h,p]=d.useState(null),[N,k]=d.useState(!1),b=s.live.isLive,y=(o==null?void 0:o.runtimeDestinations)||[],w=s.perms.externalBroadcast,T=kr(n)||s.room.viewerUrl||null,q=s.viewerCount,C=n.destinations.filter(W=>W.enabled&&W.status!=="disabled"),_=W=>y.find(oe=>oe.destinationId===W.id)||null,K=C.filter(W=>!_(W));y.filter(W=>_s(W.status)==="live").length;const L=wt({...s,streamSession:o}),F=1+(b?y.filter(W=>_s(W.status)!=="off").length:C.filter(W=>mt(W,u,n)).length),S=1+(b?y.length+K.length:C.length),O=b&&y.some(W=>String(W.provider)==="youtube"&&_s(W.status)!=="off"),z=fm(b?(o==null?void 0:o.id)??null:null,O),M=async(W,oe)=>{if(o&&!(oe==="restart"&&m(W.id))){p(`${W.id}:${oe}`);try{const le=await Ir(o.id,W.id,oe);c(le);const ie=dn(String(W.provider),W.displayName??null);r.show(oe==="restart"?`${ie}: переподключаемся`:oe==="pause"?`${ie}: на паузе`:oe==="resume"?`${ie}: продолжаем`:`${ie}: трансляция остановлена`)}catch(le){r.error(ut(le,"Площадка не ответила — попробуйте ещё раз"))}finally{p(null)}}},U=async W=>{var le;const oe=Kn();p(`add:${W.id}`);try{if(o){const ie=await Qu(o.id,W.id,"16:9",oe.quality);c(ie),r.success(`${Us(W)}: подключаем к эфиру`)}else{const ie=await vi(s,{destinations:[{id:W.id,picture:"16:9"}],format:"16:9",record:s.autoRecord,latency:oe.latency,quality:oe.quality,privacy:oe.privacy,title:s.room.title,de
111scription:"",workspaceId:((le=n.event)==null?void 0:le.workspaceId)??null});if(!ie.ok)throw new Error(ie.error||"Не удалось подключить площадку");r.success(`${Us(W)}: подключаем к эфиру`)}x(ie=>({...ie,[W.id]:!0}))}catch(ie){r.error(ut(ie,"Не удалось подключить площадку"))}finally{p(null)}},$=(W,oe)=>{const le=_s(oe.status),ie=[{label:m(oe.id)?"Переподключаем…":"Переподключить",icon:e.jsx(zn,{className:"sn-i sn-i-16"}),onSelect:()=>void M(oe,"restart"),disabled:le==="off"||m(oe.id)},le==="paused"?{label:"Продолжить трансляцию",icon:e.jsx(fn,{className:"sn-i sn-i-16"}),onSelect:()=>void M(oe,"resume")}:{label:"Пауза на этой площадке",description:"зрители площадки увидят паузу",icon:e.jsx(Jt,{className:"sn-i sn-i-16"}),onSelect:()=>void M(oe,"pause"),disabled:le==="off"}];typeof oe.publicUrl=="string"&&oe.publicUrl&&ie.push({label:"Открыть трансляцию",icon:e.jsx(Bt,{className:"sn-i sn-i-16"}),href:oe.publicUrl}),ie.push({type:"separator"}),ie.push({label:"Остановить на площадке",icon:e.jsx(jn,{className:"sn-i sn-i-16"}),danger:!0,onSelect:()=>void M(oe,"stop"),disabled:le==="off"}),g({anchor:W,items:ie})},v=W=>{const oe=[];T&&(oe.push({label:"Открыть страницу эфира",icon:e.jsx(Bt,{className:"sn-i sn-i-16"}),href:T}),oe.push({label:"Скопировать ссылку",icon:e.jsx(vt,{className:"sn-i sn-i-16"}),onSelect:()=>{navigator.clipboard.writeText(T).then(()=>r.success("Ссылка скопирована"),()=>r.error("Не удалось скопировать"))}})),oe.push({label:"Страница включена всегда",description:"зарегистрированные зрители смотрят эфир на ней",disabled:!0}),g({anchor:W,items:oe})},B=a[a.length-1],se=a.filter(W=>W.dropPct!==null).slice(-6),A=se.length?se.reduce((W,oe)=>W+(oe.dropPct||0),0)/se.length:null,X=s.network.downlinkMbps,ae=y.some(W=>W.outputProfile==="vertical_1080p30"),ce=y.filter(W=>W.outputProfile==="vertical_1080p30").map(W=>dn(String(W.provider),W.displayName??null)),xe=o!=null&&o.outputProfile?Yi[String(o.outputProfile)]:null,ye=s.recording,be=!!((rs=s.recordingPause)!=null&&rs.paused),ge=((Ie=s.recordingUpload)==null?void 0:Ie.uploadedBytes)||0;return e.jsxs(e.Fragment,{children:[e.jsx(sm,{api:s}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Площадки",children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsx("span",{className:"sn-eyebrow",children:"Площадки"}),e.jsx("span",{className:"sn-s",children:b&&L.length?`${S-L.length} из ${S} в порядке`:`${F} из ${S} ${Xe(F,"включена","включены","включены")}`})]}),e.jsxs("ul",{className:"sn-shw-out",children:[e.jsxs("li",{children:[e.jsx("span",{className:"sn-shw-mark is-brand sn-mono","aria-hidden":"true",children:"SN"}),e.jsxs("div",{className:"sn-shw-out-text",children:[e.jsx("b",{children:"SNICH Live"}),e.jsxs("span",{className:`sn-shw-status is-${b?"live":"off"}`,children:[e.jsx("i",{}),b?"страница эфира":"откроется со стартом"]})]}),b&&q!==null&&e.jsxs("div",{className:"sn-shw-out-num",title:"Зрители на странице эфира",children:[e.jsxs("span",{children:[e.jsx(gs,{className:"sn-i",style:{width:14,height:14}})," ",e.jsx("b",{className:"sn-mono",children:He(q)})]}),e.jsx("span",{children:"зрителей"})]}),e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":"Настройки: SNICH Live",onClick:W=>v(W.currentTarget),children:e.jsx(zs,{className:"sn-i sn-i-16"})})]}),y.map(W=>{const oe=_s(W.status),le=dn(String(W.provider),W.displayName??null),ie=oe==="error"||String(W.status).toLowerCase()==="reconnecting";return e.jsxs("li",{className:ie?"is-problem":void 0,children:[e.jsx(Ba,{item:{provider:String(W.provider),displayName:W.displayName??null}}),e.jsxs("div",{className:"sn-shw-out-text",children:[e.jsxs("b",{children:[le,e.jsx(el,{provider:String(W.provider),displayName:W.displayName??null})]}),e.jsxs("span",{className:`sn-shw-status is-${oe}`,children:[e.jsx("i",{}),Du(W.status)]}),ie&&W.lastError&&e.jsx("span",{className:"sn-shw-out-err",children:String(W.lastError).slice(0,120)})]}),ie?e.jsx(R,{size:"sm",variant:"quiet",loading:h===`${W.id}:restart`,disabled:m(W.id),onClick:()=>void M(W,"restart"),children:m(W.id)?"Переподключаем…":"Переподключить"}):e.jsxs("div",{className:"sn-shw-out-num",title:typeof z[W.id]=="number"?`Зрители на ${le} — по данным площадки`:void 0,children:[typeof z[W.id]=="number"&&e.jsxs("span",{children:[e.jsx(gs,{className:"sn-i",style:{width:14,height:14}})," ",e.jsx("b",{className:"sn-mono",children:He(z[W.id])})]}),e.jsx("span",{className:"sn-mono",children:Yi[String(W.outputProfile)]||""})]}),e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":`Настройки: ${le}`,onClick:as=>$(as.currentTarget,W),disabled:!w,children:e.jsx(zs,{className:"sn-i sn-i-16"})})]},W.id)}),(b?K:C).map(W=>{const oe=!b&&mt(W,u,n);return e.jsxs("li",{children:[e.jsx(Ba,{item:W}),e.jsxs("div",{className:"sn-shw-out-text",children:[e.jsxs("b",{children:[Us(W),e.jsx(el,{provider:W.provider,displayName:W.displayName})]}),e.jsxs("span",{className:`sn-shw-status is-${oe?"connecting":"off"}`,children:[e.jsx("i",{}),b?"выключено":oe?"включится со стартом":"выключено"]})]}),e.jsx(Pe,{checked:oe||h===`add:${W.id}`,disabled:!w||h===`add:${W.id}`,label:`Вести эфир в ${Us(W)}`,onChange:le=>{if(b){le&&U(W);return}x(ie=>({...ie,[W.id]:le}))}})]},W.id)})]}),w&&e.jsxs("button",{type:"button",className:"sn-shw-dashed",onClick:()=>k(!0),children:[e.jsx(ps,{className:"sn-i sn-i-16"})," Добавить площадку или ключ"]}),!b&&e.jsx(R,{variant:"live",block:!0,icon:e.jsx("span",{className:"sn-shw-reddot is-white"}),onClick:l,disabled:!s.perms.broadcastLive,children:"Выйти в эфир…"}),n.destinationsError&&e.jsxs("span",{className:"sn-hint",style:{fontSize:12.5},children:["Площадки пространства не загрузились: ",n.destinationsError]}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:O?"Зрители YouTube — по данным YouTube, раз в 30 секунд. VK и RUTUBE число зрителей не передают.":"Зрителей считают страница эфира и YouTube (канал подключён через Google);
111 VK и RUTUBE число не передают."})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Качество потока",children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsx("span",{className:"sn-eyebrow",children:"Качество потока"}),e.jsx("span",{className:"sn-s",children:"последние 5 мин"})]}),b&&o?e.jsxs(e.Fragment,{children:[e.jsx(hm,{samples:a}),e.jsxs("div",{className:"sn-shw-kpis",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Битрейт"}),e.jsx("b",{className:"sn-mono",children:B?`${Cr(B.kbps)} Мбит/с`:"—"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Потеря кадров"}),e.jsx("b",{className:"sn-mono",children:A!==null?`${A.toFixed(1).replace(".",",")} %`:"—"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Сеть"}),e.jsx("b",{className:"sn-mono",children:X!==null?`${X>=10?"10+":String(X).replace(".",",")} Мбит/с`:s.network.online?"в сети":"нет"})]})]}),((De=s.streamPublisher)==null?void 0:De.state)==="degraded"&&e.jsx("div",{className:"sn-shw-note is-warn",children:"Компьютер или сеть не успевают — закройте лишние вкладки и программы."})]}):e.jsx("div",{className:"sn-shw-note",children:b?"Эфир идёт только на странице SNICH — зрители смотрят его прямо из студии.":"График появится, когда эфир пойдёт на площадки."})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Запись",children:[e.jsx("span",{className:"sn-eyebrow",children:"Запись"}),e.jsxs("button",{type:"button",className:"sn-pl-card is-link",onClick:W=>i(W.currentTarget),disabled:!s.perms.recording,children:[e.jsx("span",{className:`sn-shw-recdot${ye.active?be?" is-paused":" is-on":""}`,"aria-hidden":"true",children:e.jsx("i",{})}),e.jsxs("span",{className:"sn-pl-text",children:[e.jsx("b",{children:ye.active?e.jsxs(e.Fragment,{children:[be?"На паузе":"Идёт"," · ",e.jsx("span",{className:"sn-mono",children:Nt(dt(s))})]}):!b&&s.autoRecord?"Начнётся вместе с эфиром":"Не записываем"}),e.jsx("span",{children:ye.active?`${s.recordingVerticalActive?"16:9 и 9:16":"16:9"}${s.recordingTracksActive?" · дорожки спикеров":""}${ge?` · ${_t(ge)}`:""}`:b?"Нажмите, чтобы начать запись":"Попадёт в «Записи и итоги»"})]}),e.jsx(Ps,{className:"sn-i sn-i-16",style:{color:"var(--sn-ink-3)"}})]})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Форматы",children:[e.jsx("span",{className:"sn-eyebrow",children:"Форматы"}),e.jsxs("div",{className:"sn-shw-format",children:[e.jsx("span",{className:"sn-shw-format-ico","aria-hidden":"true"}),e.jsxs("div",{className:"sn-shw-out-text",children:[e.jsx("b",{children:"16:9 · горизонтальный"}),e.jsx("span",{children:xe?`${xe.replace("16:9 · ","")} · все площадки`:"1080p · страница и площадки"})]}),e.jsx("span",{className:"sn-tag sn-tag-gray",children:s.aspect==="16:9"?"в студии":"основной"})]}),s.verticalFormat&&e.jsxs("div",{className:"sn-shw-format",children:[e.jsx("span",{className:"sn-shw-format-ico is-v","aria-hidden":"true"}),e.jsxs("div",{className:"sn-shw-out-text",children:[e.jsx("b",{children:"9:16 · вертикальный"}),e.jsx("span",{children:ae?`${ce.join(", ")} · 1080×1920`:s.recordingVertical?"в запись · 1080×1920":"Shorts и Клипы · 1080×1920"})]}),e.jsx(R,{size:"sm",variant:"text",onClick:()=>s.setAspect(s.aspect==="9:16"?"16:9":"9:16"),children:s.aspect==="9:16"?"Вид 16:9":"Вид 9:16"})]})]}),e.jsx(Cs,{open:!!f,onClose:()=>g(null),anchor:(f==null?void 0:f.anchor)||null,items:(f==null?void 0:f.items)||[],width:270}),e.jsx(Sr,{open:N,onClose:()=>k(!1),workspaceId:((We=n.event)==null?void 0:We.workspaceId)??null,roomTitle:s.room.title,onCreated:W=>{if(n.reloadDestinations(),b)return;const oe=W.provider==="custom_rtmp"?[]:n.destinations.filter(le=>le.provider===W.provider).map(le=>le.id);x(le=>({...le,...Object.fromEntries(oe.map(ie=>[ie,!1])),[W.id]:!0}))}})]})}function el({provider:s,displayName:n}){const t=Ou(s,n);return t?e.jsxs("span",{className:"sn-shw-out-key",title:`Ключ «${t}»`,children:[" · ",t]}):null}function jm({api:s,onOpenOutputs:n}){var h,p;const t=Se(),a=wt(s),[i,l]=d.useState({}),[r,m]=d.useState(!1),o=$r(),c=d.useMemo(()=>a.find(N=>i[N.id]!==N.status)||null,[a,i]),u=((h=s.streamSession)==null?void 0:h.id)||null;if(!s.live.isLive||!c||!u)return null;const x=c.status.toLowerCase()!=="reconnecting",f=(((p=s.streamSession)==null?void 0:p.runtimeDestinations)||[]).filter(N=>N.id!==c.id&&_s(N.status)==="live").length,g=async()=>
111{if(!o(c.id)){m(!0);try{await Ir(u,c.id,"restart"),t.show(`${c.name}: переподключаемся`),l(N=>({...N,[c.id]:c.status}))}catch(N){t.error(ut(N,"Не удалось переподключить"))}finally{m(!1)}}};return e.jsxs("div",{className:"sn-shw-alert",role:"status",children:[e.jsx(Zt,{className:"sn-i",style:{color:"var(--sn-amber)",flex:"none"}}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("b",{children:[c.name,": ",x?"потеря соединения":"переподключаемся"]}),e.jsxs("p",{children:[x?`Зрители ${c.name} видят паузу.`:"Поток восстанавливается сам.",f?" Остальные площадки в порядке.":" Страница эфира SNICH работает."]}),e.jsxs("div",{style:{display:"flex",gap:14},children:[e.jsx("button",{type:"button",className:"sn-shw-link",onClick:()=>void g(),disabled:r||o(c.id),children:r||o(c.id)?"Переподключаем…":"Переподключить"}),e.jsx("button",{type:"button",className:"sn-shw-link is-muted",onClick:n,children:"Все площадки"})]})]}),e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":"Скрыть",onClick:()=>l(N=>({...N,[c.id]:c.status})),children:e.jsx(ls,{className:"sn-i sn-i-16"})})]})}function _n(s,n){return s===null?null:s+n.startOffsetMin*6e4}function gm(s){const{program:n,live:t,liveSince:a,now:i}=s,l=s.scheduledAt?Date.parse(s.scheduledAt):NaN,r=Number.isFinite(l)?l:a,m=n.reduce((k,b)=>k+b.durationMin,0),o={base:r,currentIndex:-1,current:null,next:n[0]||null,currentStartedAt:null,currentPlannedEnd:null,elapsedSec:0,remainingSec:0,behindSec:0,plannedEnd:r!==null?r+m*6e4:null,totalMin:m};if(!n.length)return{...o,next:null};let c=t!=null&&t.itemId?n.findIndex(k=>k.id===t.itemId):-1,u=c>=0?(t==null?void 0:t.startedAt)??null:null;if(c<0&&a){const k=(i-a)/6e4;c=n.findIndex(y=>k>=y.startOffsetMin&&k<y.startOffsetMin+y.durationMin),c<0&&(c=k>=m?n.length-1:0);const b=[...s.history].reverse().find(y=>y.itemId===n[c].id);u=(b==null?void 0:b.startedAt)??(c===0?a:a+n[c].startOffsetMin*6e4)}if(c<0)return o;const x=n[c],f=n[c+1]||null,g=_n(r,x),h=r!==null?r+(x.startOffsetMin+x.durationMin)*6e4:null,p=u??g??i,N=h??p+x.durationMin*6e4;return{base:r,currentIndex:c,current:x,next:f,currentStartedAt:p,currentPlannedEnd:N,elapsedSec:Math.max(0,Math.floor((i-p)/1e3)),remainingSec:Math.floor((N-i)/1e3),behindSec:g!==null?Math.round((p-g)/1e3):0,plannedEnd:r!==null?r+m*6e4:null,totalMin:m}}function vm(s){const n={};for(let t=0;t<s.length-1;t+=1){const a=s[t],i=s[t+1],l=Math.max(0,Math.round((i.startedAt-a.startedAt)/1e3));n[a.itemId]=(n[a.itemId]||0)+l}return n}const lt=s=>String(s||"").trim().toLowerCase();function Wn(s,n){if(!s)return null;if(s.sceneId){const a=n.find(i=>i.id===s.sceneId);if(a)return a}const t=lt(s.sceneName)||lt(s.sceneId);return t&&n.find(a=>lt(a.name)===t)||null}function rt(s,n,t){return s?s.speakerIds.map(a=>n.find(i=>i.id===a)).filter(a=>!!a).map(a=>({member:a,participant:t.find(i=>!i.isLocal&&(a.userId!==null&&String(i.userId??"")===String(a.userId)||lt(i.name)===lt(a.name)))||t.find(i=>i.isLocal&&a.isMe)||null})):[]}function bm(s){const n=s<0?"−":"+",t=Math.abs(Math.round(s));return`${n}${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function ym(s){const n=Math.abs(Math.round(s)),t=Math.floor(n/60),a=n%60;return t?a?`${t} мин ${a} с`:`${t} мин`:`${a} с`}function vn(s){return s.trim().split(/\s+/)[0]||s}function Nm(s,n){const t=[],a=(r,m,o)=>{const c=s.stageIdOf(r);t.some(u=>u.peerId===c)||t.push({key:c,label:m,peerId:c,live:o})},i=s.stageParticipants.filter(r=>r.type==="user"&&!r.isLocal&&!r.isAI);n&&!n.isLocal&&a(n,`${vn(n.name)}${i.some(r=>r.id===n.id)?" — в эфире":""}`,i.some(r=>r.id===n.id)),i.slice(0,2).forEach(r=>
111a(r,`${vn(r.name)} — в эфире`,!0));const l=s.participants.find(r=>!r.isLocal&&r.type==="user"&&(r.role==="host"||r.role==="co_host"));return l&&a(l,`${vn(l.name)} — ведущ.`,!1),t.push({key:"all",label:"Все спикеры",peerId:null}),t.slice(0,4)}const wm=[{key:"5min",text:"Осталось 5 минут",kind:"time",icon:e.jsx(Ks,{className:"sn-i sn-i-16"})},{key:"1min",text:"Осталось 1 минута",kind:"time",icon:e.jsx(Uo,{className:"sn-i sn-i-16"})},{key:"wrap",text:"Закругляйтесь",kind:"wrap_up",icon:e.jsx(Ht,{className:"sn-i sn-i-16"})},{key:"louder",text:"Говорите громче",kind:"text",icon:e.jsx(Cn,{className:"sn-i sn-i-16"})},{key:"next",text:"Следующий — вопросы",kind:"text",icon:e.jsx(wn,{className:"sn-i sn-i-16"})},{key:"pause",text:"Пауза: техническая проблема",kind:"text",icon:e.jsx(Zt,{className:"sn-i sn-i-16"}),tone:"warn"}];function km({open:s,anchor:n,onClose:t,api:a,target:i,nextTitle:l}){var k;const r=Se(),{cues:m}=Vs(),o=d.useMemo(()=>Nm(a,i),[a,i]),[c,u]=d.useState(((k=o[0])==null?void 0:k.key)||"all"),[x,f]=d.useState(""),[g,h]=d.useState(null);d.useEffect(()=>{var b;s&&(u(((b=o[0])==null?void 0:b.key)||"all"),f(""))},[s,i==null?void 0:i.id]);const p=async(b,y,w)=>{const T=b.trim().slice(0,200);if(!T)return;const q=o.find(_=>_.key===c)||o[o.length-1];h(w);const C=await m.send(q.peerId,T,y);if(h(null),!C.ok){r.error(C.error||"Сигнал не отправлен");return}r.success(q.peerId?`Сигнал отправлен: ${q.label.split(" — ")[0]}`:"Сигнал отправлен всем спикерам"),t()},N=e.jsxs("div",{className:"sn-shw-cue",children:[e.jsxs("div",{className:"sn-shw-cue-head",children:[e.jsx("span",{className:"sn-shw-mix-ico is-blue",children:e.jsx(Ht,{className:"sn-i sn-i-16"})}),e.jsx("b",{children:"Сигнал спикеру"}),e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":"Закрыть",onClick:t,children:e.jsx(ls,{className:"sn-i sn-i-16"})})]}),e.jsx("span",{className:"sn-shw-label",children:"Кому"}),e.jsx(we,{ariaLabel:"Кому отправить сигнал",value:c,onChange:u,options:o.map(b=>({value:b.key,label:e.jsxs(e.Fragment,{children:[b.live?e.jsx("span",{className:"sn-shw-reddot"}):null,b.label]})})),style:{width:"100%"}}),e.jsx("div",{className:"sn-shw-cue-grid",children:wm.map(b=>{const y=b.key==="next"&&l?`Следующий — ${l}`:b.text;return e.jsxs("button",{type:"button",className:b.tone==="warn"?"is-warn":void 0,onClick:()=>void p(y,b.kind,b.key),disabled:!!g,children:[g===b.key?e.jsx("span",{className:"sn-spinner",style:{width:16,height:16}}):b.icon,e.jsx("span",{children:y})]},b.key)})}),e.jsx("span",{className:"sn-shw-label",children:"Свой текст"}),e.jsxs("form",{className:"sn-shw-cue-own",onSubmit:b=>{b.preventDefault(),p(x,"text","own")},children:[e.jsx(Oe,{value:x,onChange:b=>f(b.target.value),placeholder:"Например: покажите тарифы",maxLength:200,"data-autofocus":!0}),e.jsx(R,{type:"submit",variant:"primary",loading:g==="own",disabled:!x.trim(),children:"Отправить"})]}),e.jsxs("span",{className:"sn-hint",style:{fontSize:12.5,display:"flex",gap:6,alignItems:"center"},children:[e.jsx(un,{className:"sn-i sn-i-16"})," Спикер увидит сигнал крупно и сможет ответить"]})]});return n?e.jsx(xt,{open:s,onClose:t,anchor:n,placement:"top-end",width:404,className:"sn-shw-cue-pop",children:N}):e.jsx(Ke,{open:s,onClose:t,width:440,hideClose:!0,bodyStyle:{padding:0},children:N})}function sl({cue:s,api:n}){const t=s.toPeerId?n.participants.find(i=>n.stageIdOf(i)===s.toPeerId):null,a=s.reply?e.jsxs("span",{className:"sn-shw-cue-reply",children:[e.jsx(Vl,{className:"sn-i",style:{width:13,height:13}}),s.reply]}):e.jsxs("span",{className:"sn-shw-cue-sent",children:[e.jsx(Re,{className:"sn-i",style:{width:13,height:13}}),"отправлен"]});return e.jsxs("li",{className:"sn-shw-cuelog",children:[e.jsx("span",{className:"sn-mono sn-hint",children:qe(s.at)}),t?e.jsx(Ve,{name:t.name,src:t.avatarUrl||void 0,size:22}):e.jsx("span",{className:"sn-shw-cuelog-all",title:"Всем",children:"все"}),e.jsxs("span",{className:"sn-shw-cuelog-text",title:`${s.toName||"Всем"}: ${s.text}`,children:["«",s.text,"»"]}),a]})}function ya({list:s}){return s.length?e.jsxs("span",{className:"sn-shw-rd-people",children:[e.jsx("span",{className:"sn-shw-rd-avatars",children:s.slice(0,4).map(({member:n,participant:t})=>e.jsx(Ve,{name:n.name,src:(t==null?void 0:t.avatarUrl)||n.avatarUrl||void 0,size:20},n.name))}),s.length===1?s[0].member.name:s.length===2?`${vn(s[0].member.name)} и ${vn(s[1].member.name)}`:`${vn(s[0].member.name)} и ещё ${s.length-1}`]}):null}
111function Sm({api:s,producer:n,data:t,view:a,history:i,onNextBlock:l,onCue:r,busy:m}){var K;const o=ts(1e3),{cues:c}=Vs(),u=t.program,x=s.live.isLive,f=vm(i),g=a.base,h=a.plannedEnd,p=n.scenes.find(L=>/финал|спасибо/i.test(L.name))||null,N=[...c.log].sort((L,F)=>F.at-L.at).slice(0,6),k=a.current,b=a.next,y=Wn(b,n.scenes),w=rt(b,t.team,s.participants),T=!!y&&((K=n.previewScene)==null?void 0:K.id)===y.id,q=b&&g!==null?Math.floor((_n(g,b)-o)/1e3):null;if(!u.length)return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sn-shw-note",children:[e.jsx(un,{className:"sn-i sn-i-16",style:{flex:"none",marginTop:2}}),e.jsxs("span",{children:["Программа эфира не заполнена. Добавьте блоки со временем, спикерами и сценами — здесь появится план с отсчётом."," ",e.jsx("a",{href:`/events/${encodeURIComponent(s.room.id)}/program`,target:"_blank",rel:"noreferrer",children:"Открыть программу"})]})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Отправленные сигналы",children:[e.jsx("span",{className:"sn-eyebrow",children:"Сигналы спикерам"}),N.length?e.jsx("ul",{className:"sn-shw-cuelogs",children:N.map(L=>e.jsx(sl,{cue:L,api:s},L.id))}):e.jsx("span",{className:"sn-hint",style:{fontSize:13},children:"Пока не отправляли"})]}),e.jsx("div",{className:"sn-shw-panel-foot is-actions",children:e.jsx(R,{variant:"quiet",icon:e.jsx(Ht,{className:"sn-i sn-i-16"}),onClick:L=>r(L.currentTarget),block:!0,children:"Сигнал спикеру"})})]});const C=x&&k&&a.behindSec>=30?a.behindSec:0,_=rt(k,t.team,s.participants);return e.jsxs(e.Fragment,{children:[C>0&&k&&e.jsxs("div",{className:"sn-shw-note is-warn",role:"note",children:[e.jsx(Zt,{className:"sn-i sn-i-16",style:{flex:"none",marginTop:2}}),e.jsxs("span",{children:[e.jsxs("b",{children:["Отставание от плана: ",e.jsx("span",{className:"sn-mono",children:ym(C)})]}),e.jsx("br",{}),k.title," началось в ",e.jsx("span",{className:"sn-mono",children:qe(a.currentStartedAt)}),".",b&&g!==null?e.jsxs(e.Fragment,{children:[" Чтобы «",b.title,"» началось в ",e.jsx("span",{className:"sn-mono",children:qe(_n(g,b))}),", ",_[0]?`у ${vn(_[0].member.name)}`:"на блок"," ",e.jsx("span",{className:"sn-mono",children:fs(Math.max(0,a.remainingSec))}),"."]}):null]})]}),e.jsxs("ol",{className:"sn-shw-rd","aria-label":"Блоки эфира",children:[u.map((L,F)=>{const S=_n(g,L),O=Wn(L,n.scenes),z=rt(L,t.team,s.participants),M=x&&F===a.currentIndex,U=(b==null?void 0:b.id)===L.id&&(x||F===0),$=x&&a.currentIndex>=0&&F<a.currentIndex;if(M){const B=Math.max(1,a.elapsedSec+Math.max(0,a.remainingSec));return e.jsxs("li",{className:"is-current",children:[e.jsx("span",{className:"sn-shw-rd-time sn-mono",children:S!==null?qe(S):""}),e.jsx("span",{className:"sn-shw-rd-dot is-live"}),e.jsxs("div",{className:"sn-shw-rd-card is-live",children:[e.jsxs("div",{className:"sn-shw-rd-top",children:[e.jsx("span",{className:"sn-tag sn-tag-live",children:"СЕЙЧАС"}),a.currentPlannedEnd&&e.jsxs("span",{className:"sn-hint",children:["до ",e.jsx("span",{className:"sn-mono",children:qe(a.currentPlannedEnd)})]}),O&&e.jsxs("span",{className:"sn-shw-rd-scene",children:[e.jsx(Hn,{className:"sn-i",style:{width:13,height:13}}),O.name]})]}),e.jsx("b",{className:"sn-shw-rd-title",children:L.title}),e.jsx(ya,{list:z}),L.note&&e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:L.note}),e.jsx("span",{className:"sn-shw-rd-bar",role:"progressbar","aria-label":"Прошло времени блока","aria-valuenow":Math.round(a.elapsedSec/B*100),children:e.jsx("i",{style:{width:`${Math.min(100,a.elapsedSec/B*100)}%`}})}),e.jsxs("div",{className:"sn-shw-rd-times",children:[e.jsxs("span",{children:["идёт ",e.jsx("span",{className:"sn-mono",children:fs(a.elapsedSec)})]}),e.jsx("b",{className:a.remainingSec<0?"is-over":void 0,children:a.remainingSec<0?e.jsxs(e.Fragment,{children:["сверх плана ",e.jsx("span",{className:"sn-mono",children:fs(-a.remainingSec)})]}):e.jsxs(e.Fragment,{children:["осталось ",e.jsx("span",{className:"sn-mono",children:fs(a.remainingSec)})]})})]})]})]},L.id)}if(U)return e.jsxs("li",{className:"is-next",children:[e.jsx("span",{className:"sn-shw-rd-time sn-mono",children:S!==null?qe(S):""}),e.jsx("span",{className:"sn-shw-rd-dot is-next"}),e.jsxs("div",{className:"sn-shw-rd-card",children:[e.jsxs("div",{className:"sn-shw-rd-top",children:[e.jsx("span",{className:"sn-tag sn-tag-blue",children:x?"ДАЛЕЕ":"ПЕРВЫЙ БЛОК"}),q!==null&&q>0&&e.jsxs("span",{className:"sn-hint",children:["через ",e.jsx("span",{className:"sn-mono",children:fs(q)})]})]}),e.jsx("b",{className:"sn-shw-rd-title",children:L.title}),e.jsx(ya,{list:w}),O?e.jsxs("div",{className:"sn-shw-rd-prep",children:[e.jsxs("span",{className:"sn-shw-rd-scene is-blue",children:[e.jsx(Hn,{className:"sn-i",style:{width:13,height:13}}),O.name]}),T?e.jsxs("span",{className:"sn-shw-rd-ok",children:["в подготовке ",e.jsx(Re,{className:"sn-i",style:{width:13,height:13}})]}):e.jsx("button",{type:"button",className:"sn-shw-link",onClick:()=>n.setPreviewId(O.id),children:"В подготовку"})]}):L.sceneName?e.jsxs("span",{className:"sn-hint",style:{fontSize:12.5},children:["Сцена «",L.sceneName,"» не найдена в студии"]}):null]})]},L.id);const v=$?f[L.id]:void 0;return e.jsxs("li",{className:$?"is-past":void 0,children:[e.jsx("span",{className:"sn-shw-rd-time sn-mono",children:S!==null?qe(S):""}),e.jsx("span",{className:`sn-shw-rd-dot${$?" is-done":""}`,children:$?e.jsx(Re,{className:"sn-i",style:{width:10,height:10}}):null}),e.jsxs("div",{className:"sn-shw-rd-row",children:[e.jsxs("div",{className:"sn-shw-rd-row-top",children:[e.jsx("b",{children:L.title}),v!==void 0?e.jsxs("span",{className:"sn-mono sn-shw-rd-actual",children:[fs(v)," ",e.jsx("em",{className:v-L.durationMin*60>0?"is-over":"is-under",children:bm(v-L.durationMin*60)})]}):e.jsxs("span",{className:"sn-mono sn-hint",children:[L.durationMin," мин"]})]}),e.jsxs("span",{className:"sn-shw-rd-sub",children:[e.jsx(ya,{list:z}),O?e.jsxs("span",{children:[z.length?" · ":"",O.name]}):null]})]})]},L.id)}
111),h!==null&&e.jsxs("li",{className:"is-end",children:[e.jsx("span",{className:"sn-shw-rd-time sn-mono",children:qe(h)}),e.jsx("span",{className:"sn-shw-rd-dot is-end"}),e.jsxs("span",{className:"sn-hint",style:{fontSize:13},children:["Конец эфира",p?` · сцена «${p.name}»`:""]})]})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Отправленные сигналы",children:[e.jsx("span",{className:"sn-eyebrow",children:"Сигналы спикерам"}),N.length?e.jsx("ul",{className:"sn-shw-cuelogs",children:N.map(L=>e.jsx(sl,{cue:L,api:s},L.id))}):e.jsx("span",{className:"sn-hint",style:{fontSize:13},children:"Пока не отправляли. Ответы спикеров появятся здесь."})]}),e.jsxs("div",{className:"sn-shw-panel-foot",children:[e.jsxs("div",{className:"sn-shw-foot-row",children:[e.jsx(R,{variant:"quiet",icon:e.jsx(Ht,{className:"sn-i sn-i-16"}),onClick:L=>r(L.currentTarget),children:"Сигнал спикеру"}),e.jsx(R,{variant:"primary",onClick:l,loading:m,disabled:!s.perms.manageStage||!x||!b,title:x?b?void 0:"Это последний блок":"Блоки переключаются во время эфира",children:"Следующий блок"})]}),!x&&e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Первый блок начнётся вместе с эфиром."}),x&&c.log.some(L=>L.reply)&&e.jsxs("span",{className:"sn-hint",style:{fontSize:12.5,display:"flex",alignItems:"center",gap:6},children:[e.jsx(Bo,{className:"sn-i sn-i-16"}),"Ответы приходят сразу — спикер отвечает одним нажатием."]})]})]})}const Cm=[{key:"devices",label:"Камера и звук",icon:e.jsx(Ts,{className:"sn-i sn-i-16"})},{key:"quality",label:"Качество эфира",icon:e.jsx(xn,{className:"sn-i sn-i-16"})},{key:"keys",label:"Горячие клавиши",icon:e.jsx(ft,{className:"sn-i sn-i-16"})},{key:"studio",label:"Студия",icon:e.jsx(Al,{className:"sn-i sn-i-16"})}];function $m(s){const[n,t]=d.useState([]);return d.useEffect(()=>{var l,r,m;if(!s||!((l=navigator.mediaDevices)!=null&&l.enumerateDevices))return;let a=!1;const i=()=>navigator.mediaDevices.enumerateDevices().then(o=>{a||t(o)}).catch(()=>{});return i(),(m=(r=navigator.mediaDevices).addEventListener)==null||m.call(r,"devicechange",i),()=>{var o,c;a=!0,(c=(o=navigator.mediaDevices).removeEventListener)==null||c.call(o,"devicechange",i)}},[s]),n}function Na(s,n,t,a){return s.filter(l=>l.kind===n&&l.deviceId).map((l,r)=>({value:l.deviceId,label:l.label||(l.deviceId==="default"?`${t} по умолчанию`:`${t} ${r+1}`),icon:a}))}function Im({stream:s}){const n=d.useRef(null);return d.useEffect(()=>{const t=n.current;t&&(t.srcObject=s||null,s&&t.play().catch(()=>{}))},[s]),e.jsx("video",{ref:n,muted:!0,playsInline:!0,autoPlay:!0,className:"sn-shw-set-cam"})}const nl=[{keys:["1–9"],label:"Сцена в подготовку"},{keys:["Shift","1–9"],label:"Сцена сразу в эфир"},{keys:["Пробел"],label:"Вывести в эфир"},{keys:["B"],label:"Показать или скрыть баннер"},{keys:["Q"],label:"Вопрос на экран"},{keys:["M"],label:"Микрофон вкл/выкл"},{keys:["←","→"],label:"Слайды, когда открыта презентация"}];function tl({compact:s}){const n=s?nl.filter(t=>t.keys[0]!=="Shift"&&t.keys[0]!=="←"):nl;return e.jsx("div",{className:`sn-shw-keys${s?" is-compact":""}`,children:n.map(t=>e.jsxs("div",{children:[e.jsx("span",{className:"sn-shw-keys-k",children:t.keys.map(a=>e.jsx(Ga,{children:a},a))}),e.jsx("span",{children:t.label})]},t.label))})}function Mm({api:s}){const n=Se(),[t,a]=d.useState(!1);if(!s.perms.manageStage)return null;const i=s.live.isLive,l=async r=>{a(!0);try{await Ae.patch(`rooms/${encodeURIComponent(s.room.id)}/settings`,{verticalFormat:r}),n.success(r?"Вертикальный формат 9:16 включён":"Вертикальный формат выключен — эфир и запись только 16:9")}catch(m){n.error(js(m,"Не удалось сохранить"))}finally{a(!1)}};return e.jsxs("div",{className:"sn-shw-set-switchrow",children:[e.jsxs("div",{children:[e.jsx("b",{children:"Вертикальный формат 9:16"}),e.jsx("span",{children:i?"меняется до начала эфира":"вертикальная версия для Shorts и Клипов: кадр, запись, эфир"})]}),e.jsx(Pe,{checked:s.verticalFormat,disabled:t||i,onChange:r=>{l(r)},label:"Вертикальный формат 9:16"})]})}function Lm({open:s,onClose:n,api:t,producer:a,tab:i,setTab:l}){var q,C,_,K,L;const r=Se(),m=$m(s),o=t.deviceSettings,[c,u]=d.useState(()=>Kn()),[x,f]=d.useState(!1);d.useEffect(()=>{s&&u(Kn())},[s]);const g=async F=>
111{if(t.applyDeviceSettings)try{await t.applyDeviceSettings(F)}catch{r.error("Не удалось применить настройку устройства")}},h=o!=null&&o.noiseSuppression?(o.denoiseStrength||60)>=90?"strong":"normal":"off",p=t.me.participant,N=p&&((q=t.audioLevels[p.id])==null?void 0:q.level)||0,k=Na(m,"videoinput","Камера",e.jsx(Sn,{className:"sn-i sn-i-16",style:{color:"var(--sn-ink-3)"}})),b=Na(m,"audioinput","Микрофон",e.jsx(Ts,{className:"sn-i sn-i-16",style:{color:"var(--sn-ink-3)"}})),y=Na(m,"audiooutput","Динамики",e.jsx(Fl,{className:"sn-i sn-i-16",style:{color:"var(--sn-ink-3)"}})),w=async()=>{f(!0);try{const F=window.AudioContext||window.webkitAudioContext,S=new F,O=S.createMediaStreamDestination(),z=S.createOscillator(),M=S.createGain();z.frequency.value=660,M.gain.setValueAtTime(1e-4,S.currentTime),M.gain.exponentialRampToValueAtTime(.2,S.currentTime+.05),M.gain.exponentialRampToValueAtTime(1e-4,S.currentTime+.9),z.connect(M).connect(O);const U=new Audio;U.srcObject=O.stream;const $=o==null?void 0:o.speakerDeviceId;$&&typeof U.setSinkId=="function"&&await U.setSinkId($).catch(()=>{}),await U.play(),z.start(),z.stop(S.currentTime+1),window.setTimeout(()=>{U.pause(),S.close(),f(!1)},1100)}catch{f(!1),r.error("Браузер не дал проиграть звук")}},T=F=>{u(F),br(F)};return e.jsx(Ke,{open:s,onClose:n,title:"Настройки студии",subtitle:"Только для вас — зрители и команда их не видят",icon:e.jsx(Yt,{className:"sn-i"}),width:780,className:"sn-shw-set",footer:e.jsxs("div",{style:{display:"flex",alignItems:"center",width:"100%"},children:[e.jsx("span",{className:"sn-hint",style:{fontSize:13,flex:1},children:"Изменения применяются сразу"}),e.jsx(R,{variant:"primary",onClick:n,children:"Готово"})]}),children:e.jsxs("div",{className:"sn-shw-set-grid",children:[e.jsx("nav",{"aria-label":"Разделы настроек",className:"sn-shw-set-nav",children:Cm.map(F=>e.jsxs("button",{type:"button","aria-current":i===F.key?"page":void 0,onClick:()=>l(F.key),children:[F.icon,F.label]},F.key))}),e.jsxs("div",{className:"sn-shw-set-body",children:[i==="devices"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sn-shw-set-row",children:[e.jsxs("div",{children:[e.jsx("span",{className:"sn-shw-label",children:"Камера"}),e.jsx(Bs,{ariaLabel:"Камера",value:(o==null?void 0:o.cameraDeviceId)||((C=k[0])==null?void 0:C.value)||"",onChange:F=>void g({cameraDeviceId:F}),options:k.length?k:[{value:"",label:"Камера не найдена"}],disabled:!k.length||!t.applyDeviceSettings}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5,display:"block",marginTop:6},children:"Камера продюсера не попадает в эфир, пока вы не выведете себя в кадр"})]}),e.jsxs("div",{className:"sn-shw-set-cam-wrap",children:[p!=null&&p.stream&&!t.me.isCameraOff?e.jsx(Im,{stream:p.stream}):e.jsxs("span",{className:"sn-hint",children:[e.jsx(Sn,{className:"sn-i sn-i-16"})," камера выключена"]}),e.jsx("span",{className:"sn-shw-set-cam-tag",children:"Вы · превью"})]})]}),e.jsxs("div",{className:"sn-shw-set-row",children:[e.jsxs("div",{children:[e.jsx("span",{className:"sn-shw-label",children:"Микрофон"}),e.jsx(Bs,{ariaLabel:"Микрофон",value:(o==null?void 0:o.audioDeviceId)||((_=b[0])==null?void 0:_.value)||"",onChange:F=>void g({audioDeviceId:F}),options:b.length?b:[{value:"",label:"Микрофон не найден"}],disabled:!b.length||!t.applyDeviceSettings})]}),e.jsxs("div",{className:"sn-shw-set-level","aria-label":"Уровень микрофона",children:[e.jsx("span",{className:"sn-shw-bars",children:Array.from({length:10}).map((F,S)=>e.jsx("i",{className:S<Math.round(N/10)?"is-on":void 0},S))}),e.jsx("b",{className:t.me.isMuted?"is-off":N>8?"is-ok":void 0,children:t.me.isMuted?"выключен":N>8?"слышно":"тихо"})]})]}),e.jsxs("div",{className:"sn-shw-set-row",children:[e.jsxs("div",{children:[e.jsx("span",{className:"sn-shw-label",children:"Динамики"}),e.jsx(Bs,{ariaLabel:"Динамики",value:(o==null?void 0:o.speakerDeviceId)||((K=y[0])==null?void 0:K.value)||"",onChange:F=>void g({speakerDeviceId:F}),options:y.length?y:[{value:"",label:"Системные динамики"}],disabled:!y.length||!t.applyDeviceSettings})]}),e.jsx(R,{variant:"quiet",icon:e.jsx(Cn,{className:"sn-i sn-i-16"}),onClick:()=>void w(),loading:x,children:"Проверить звук"})]}),e.jsxs("div",{className:"sn-shw-set-row",children:[e.jsxs("div",{children:[e.jsx("span",{className:"sn-shw-label",children:"Шумоподавление"}),e.jsx(we,{ariaLabel:"Шумоподавление",value:h,onChange:F=>void g(F==="off"?{noiseSuppression:!1}:{noiseSuppression:!0,denoiseStrength:F==="strong"?100:60}),options:[{value:"off",label:"Выкл"},{value:"normal",label:"Обычное"},{value:"strong",label:"Сильное"}],style:{width:"100%"}})]}),e.jsxs("div",{className:"sn-shw-set-switch",children:[e.jsx("b",{children:"Эхоподавление"}),e.jsx(Pe,{checked:!!(o!=null&&o.echoCancellation),onChange:F=>void g({echoCancellation:F}),label:"Эхоподавление",disabled:!t.applyDeviceSettings})]})]}),e.jsxs("div",{className:"sn-shw-box",children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsxs("b",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx(ft,{className:"sn-i sn-i-16"}),"Горячие клавиши"]}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"работают, когда фокус в студии"})]}),e.jsx(tl,{compact:!0})]}),t.openMicCheck&&e.jsx(R,{variant:"text",size:"sm",onClick:()=>{var F;n(),(F=t.openMicCheck)==null||F.call(t)},style:{alignSelf:"flex-start"},children:"Подробная проверка микрофона"})]}),i==="quality"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("span",{className:"sn-shw-label",children:"Качество трансляции на площадки"}),e.jsx("div",{className:"sn-shw-radios",children:_a.map(F=>e.jsxs("button",{type:"button","aria-pressed":c.quality===F.value,onClick:()=>T({...c,quality:F.value}),children:[e.jsx("b",{children:F.label}),e.jsx("span",{children:F.hint})]},F.value))})]}),e.jsxs("div",{children:[e.jsx("span",{className:"sn-shw-label",children:"Задержка"}),e.jsx(we,{ariaLabel:"Задержка",value:c.latency,onChange:F=>T({...c,latency:F}),options:Wt.map(F=>({value:F.value,label:F.label}))}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5,display:"block",marginTop:6},children:(L=Wt.find(F=>F.value===c.latency))==null?void 0:L.hint})]}),e.jsx("p",{className:"sn-hint",style:{margin:0,fontSize:13},children:t.live.isLive&&t.streamSession?"Эфир уже идёт: новые настройки применятся к следующему запуску.":"Применяются при следующем выходе в эфир. Их же можно поменять в окне «Выход в эфир»."})]}),i==="keys"&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sn-hint",style:{margin:0,fontSize:13},children:"Работают, когда фокус в студии, а не в поле ввода."}),e.jsx(tl,{})]}),i==="studio"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sn-shw-set-switchrow",children:[e.jsxs("div",{children:[e.jsx("b",{children:"Переход между сценами"}),e.jsx("span",{children:"как сцена сменяет сцену в эфире"})]}),e.jsx(we,{ariaLabel:"Переход",value:a.transition,onChange:a.setTransition,options:[{value:"cut",label:"Сразу"},{value:"fade",label:"Плавно"}]})]}),e.jsx(Mm,{api:t}),t.verticalFormat&&e.jsxs("div",{className:"sn-shw-set-switchrow",children:[e.jsxs("div",{children:[e.jsx("b",{children:"Кадр в студии"}),e.jsx("span",{children:"9:16 — чтобы настроить вертикальный кадр"})]}),e.jsx(we,{ariaLabel:"Кадр",value:t.aspect,onChange:t.setAspect,options:[{value:"16:9",label:"16:9"},{value:"9:16",label:"9:16"}]})]}),e.jsxs("div",{className:"sn-shw-set-switchrow",children:[e.jsxs("div",{children:[e.jsx("b",{children:"Запись вместе с эфиром"}),e.jsx("span",{children:"запись начнётся сама, когда эфир стартует"})]}),e.jsx(Pe,{checked:t.autoRecord,onChange:t.setAutoRecord,label:"Запись вместе с эфиром",disabled:!t.perms.recording})]}),e.jsxs("div",{className:"sn-shw-set-switchrow",children:[e.jsxs("div",{children:[e.jsx("b",{children:"Зеркалить мою камеру"}),e.jsx("span",{children:"только в вашем превью — зрители видят кадр как есть"})]}),e.jsx(Pe,{checked:!!(o!=null&&o.mirrorVideo),onChange:F=>void g({mirrorVideo:F}),label:"Зеркалить мою камеру",disabled:!t.applyDeviceSettings})]}),e.jsxs("div",{className:"sn-shw-set-switchrow",children:[e.jsxs("div",{children:[e.jsx("b",{children:"Прежняя студия"}),e.jsx("span",{children:"старый интерфейс — если чего-то не хватает"})]}),e.jsx(R,{size:"sm",variant:"quiet",onClick:()=>{n(),t.openLegacyStudio()},children:"Открыть"})]})]})]})]})})}function Mr(s){var l;const n=(l=s.programAudioStream)==null?void 0:l.call(s);if(!n||!n.getAudioTracks().length)return null;const t=window.AudioContext||window.webkitAudioContext;if(!t)return null;const a=new t,i=a.createMediaStreamSource(n);return a.state==="suspended"&&a.resume().catch(()=>{}),{ctx:a,source:i}}
111function Lr(s){try{s.source.disconnect()}catch{}s.ctx.close().catch(()=>{})}function Am(s,n){const t=d.useRef(s);t.current=s,d.useEffect(()=>{if(!n)return;const a=Mr(t.current);if(a)return a.source.connect(a.ctx.destination),()=>Lr(a)},[n])}function Pm(s){const[n,t]=d.useState({l:0,r:0,db:null}),a=d.useRef(s);a.current=s;const i=!!s.programAudioStream;return d.useEffect(()=>{if(!i)return;const l=Mr(a.current);if(!l)return;const{ctx:r,source:m}=l,o=r.createChannelSplitter(2),c=r.createAnalyser(),u=r.createAnalyser();c.fftSize=1024,u.fftSize=1024,m.connect(o),o.connect(c,0),o.connect(u,1);const x=new Float32Array(c.fftSize),f=new Float32Array(u.fftSize),g=(N,k)=>{N.getFloatTimeDomainData(k);let b=0;for(let y=0;y<k.length;y+=1)b+=k[y]*k[y];return Math.sqrt(b/k.length)},h=N=>N<=1e-4?0:Math.max(0,Math.min(1,(20*Math.log10(N)+60)/60)),p=window.setInterval(()=>{const N=g(c,x),k=g(u,f),b=k>0?k:N,y=Math.max(N,b);t({l:h(N),r:h(b),db:y>1e-4?20*Math.log10(y):null})},100);return()=>{window.clearInterval(p),Lr(l)}},[i]),n}function wa({value:s,count:n=24,className:t}){const a=Math.round(Math.max(0,Math.min(1,s))*n);return e.jsx("span",{className:`sn-shw-bars ${t||""}`,"aria-hidden":"true",children:Array.from({length:n}).map((i,l)=>e.jsx("i",{className:l<a?l>=n-2?"is-hot":l>=n-5?"is-warm":"is-on":void 0},l))})}function al(s,n){const[t,a]=d.useState(s),i=d.useRef(0),l=d.useRef(!1);return d.useEffect(()=>{l.current||a(s)},[s]),d.useEffect(()=>()=>window.clearTimeout(i.current),[]),[t,m=>{a(m),l.current=!0,window.clearTimeout(i.current),i.current=window.setTimeout(()=>{l.current=!1,n(m)},150)}]}function il({label:s,value:n,onChange:t,disabled:a}){return e.jsxs("div",{className:"sn-shw-level",children:[e.jsx(Cn,{className:"sn-i sn-i-16","aria-hidden":"true"}),e.jsx("input",{type:"range",className:"sn-shw-range","aria-label":s,min:0,max:100,value:n,disabled:a,onChange:i=>t(Number(i.target.value)),style:{"--sn-fill":`${n}%`}}),e.jsxs("span",{className:"sn-mono",children:[n,"%"]})]})}function Em({api:s}){const n=ts(500),t=s.programSound,a=s.perms.manageStage,[i,l]=al(t.musicVolume,s.setProgramMusicVolume),[r,m]=al(t.sfxVolume,s.setProgramSfxVolume),o=t.music&&Ei.find(x=>{var f;return x.id===((f=t.music)==null?void 0:f.track)})||null,c=t.sfx&&zi.find(x=>{var f;return x.id===((f=t.sfx)==null?void 0:f.effect)})||null,u=c&&t.sfx&&n-t.sfx.at<c.duration*1e3?c.id:null;return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"sn-panel-sec","aria-label":"Фоновая музыка",children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsx("span",{className:"sn-eyebrow",children:"Фоновая музыка"}),e.jsx("span",{className:"sn-s","aria-live":"polite",children:o?`играет «${o.name}»`:"сейчас не играет"})]}),e.jsx("div",{className:"sn-shw-tracks",children:Ei.map(x=>{const f=(o==null?void 0:o.id)===x.id;return e.jsxs("div",{className:`sn-shw-track${f?" is-on":""}`,children:[e.jsx(Ye,{label:f?`Остановить: ${x.name}`:`Играть: ${x.name}`,size:"sm",variant:f?"active":"quiet","aria-pressed":f,disabled:!a,onClick:()=>s.playProgramMusic(f?null:x.id),children:f?e.jsx(jn,{className:"sn-i sn-i-16"}):e.jsx(fn,{className:"sn-i sn-i-16"})}),e.jsx("b",{children:x.name}),e.jsxs("span",{className:"sn-mono",children:[f&&t.music?`${qs(No(t.music,n))} / `:"",qs(x.duration)]})]},x.id)})}),e.jsx(il,{label:"Громкость музыки в эфире",value:i,onChange:l,disabled:!a}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Играет по кругу у зрителей, в записи и на площадках. Спикеры её не слышат — чтобы музыка не вернулась в эфир через их микрофоны."})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Звуковые эффекты",children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsx("span",{className:"sn-eyebrow",children:"Звуковые эффекты"}),e.jsx("span",{className:"sn-s",children:"звучат в эфире сразу"})]}),e.jsx("div",{className:"sn-shw-sfx",children:zi.map(x=>e.jsx(R,{size:"sm",variant:u===x.id?"soft":"quiet",icon:u===x.id?e.jsx(Vn,{className:"sn-i sn-i-16"}):void 0,disabled:!a,onClick:()=>s.playProgramSfx(x.id),children:x.name},x.id))}),e.jsx(il,{label:"Громкость эффектов в эфире",value:r,onChange:m,disabled:!a})]})]})}function zm({api:s,producer:n,listen:t,setListen:a}){const i=Se(),l=Pm(s),[r,m]=d.useState({}),o=new Set(s.stageParticipants.map(w=>w.id)),c=$s(s),u=s.participants.find(w=>w.isLocal&&w.type==="user")||null,x=c.filter(w=>o.has(w.id)&&!w.isLocal),f=c.filter(w=>!o.has(w.id)&&n.previewIds.has(w.id)&&!w.isLocal),g=c.filter(w=>!o.has(w.id)&&!n.previewIds.has(w.id)&&!w.isLocal),h=s.media.filter(w=>ys(w)==="video"),p=!!s.setSourceVolume,N=w=>typeof w.volume=="number"?w.volume:100,k=(w,T)=>{var q;return(q=s.setSourceVolume)==null?void 0:q.call(s,w.id,T)},b=w=>{const T=N(w);T>0?(m(q=>({...q,[w.id]:T})),k(w,0),i.show(`${w.name}: звук убран из эфира`)):k(w,r[w.id]||100)},y=(w,T,q,C="person")=>{var F;const _=((F=s.audioLevels[w.id])==null?void 0:F.level)||0,K=N(w),L=C==="me"?w.isMuted:K===0;return e.jsxs("div",{className:"sn-shw-mix",children:[C==="video"?e.jsx("span",{className:"sn-shw-mix-ico",children:e.jsx(pt,{className:"sn-i sn-i-16"})}):e.jsx(Ve,{name:w.name,src:w.avatarUrl||void 0,size:30}),e.jsxs("div",{className:"sn-shw-mix-text",children:[e.jsx("b",{title:w.name,children:C==="me"?"Продюсер (вы)":w.name}),e.jsx("span",{children:T}),q&&e.jsx("span",{className:"sn-hint",children:q})]}),e.jsxs("div",{className:"sn-shw-mix-ctl",children:[e.jsx(wa,{value:_/100,count:18}),e.jsx("input",{type:"range",className:"sn-shw-range is-sm","aria-label":`Громкость: ${C==="me"?"Продюсер (вы)":w.name}`,min:0,max:150,value:Math.min(150,K),disabled:!p,onChange:S=>k(w,Number(S.target.value)),style:{"--sn-fill":`${Math.min(150,K)/150*100}%`}})]}),C==="me"?e.jsx("button",{type:"button",className:`sn-ibtn sn-ibtn-sm ${L?"sn-ibtn-off-lt":"sn-ibtn-quiet"}`,"aria-label":L?"Включить микрофон":"Выключить микрофон","aria-pressed":L,onClick:s.toggleMic,children:L?e.jsx(Es,{className:"sn-i sn-i-16"}):e.jsx(Ts,{className:"sn-i sn-i-16"})}):e.jsx("button",{type:"button",className:`sn-ibtn sn-ibtn-sm ${L?"sn-ibtn-off-lt":"sn-ibtn-quiet"}`,"aria-label":L?`Вернуть звук: ${w.name}`:`Выключить звук: ${w.name}`,"aria-pressed":L,onClick:()=>b(w),disabled:!p,children:C==="video"?L?e.jsx(Rl,{className:"sn-i sn-i-16"}):e.jsx(Cn,{className:"sn-i sn-i-16"}):L?e.jsx(Es,{className:"sn-i sn-i-16"}):e.jsx(Ts,{className:"sn-i sn-i-16"})})]},w.id)};return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"sn-panel-sec","aria-label":"Микшер",children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsx("span",{className:"sn-eyebrow",children:"Микшер"}),e.jsx("span",{className:"sn-s",children:"уровень · громкость"})]}),x.map(w=>y(w,e.jsxs("span",{className:"sn-shw-status is-live",children:[e.jsx("i",{}),"в эфире"]}))),f.map(w=>y(w,e.jsxs("span",{className:"sn-shw-status is-connecting",children:[e.jsx("i",{}),"в подготовке"]}),"не слышно зрителям")),u&&y(u,u.isMuted?"микрофон выкл":o.has(u.id)?"в эфире":"слышит команда",void 0,"me"),h.map(w=>{var T,q;return y(w.participant,n.programIds.includes(w.id)?(T=w.participant.videoFile)!=null&&T.isPlaying?"в эфире · играет":"в эфире · пауза":`готов${(q=w.participant.videoFile)!=null&&q.duration?` · ${qs(w.participant.videoFile.duration)}`:""}`,void 0,"video")}),!x.length&&!f.length&&!h.length&&e.jsx("span",{className:"sn-hint",style:{fontSize:13},children:"Когда спикеры выйдут в кадр, их громкость можно будет подстроить здесь."}),g.length>0&&e.jsxs("span",{className:"sn-hint",style:{fontSize:12.5},children:[g.slice(0,3).map(w=>w.name.split(" ")[0]).join(", "),g.length>3?` и ещё ${g.length-3}`:""," за кулисами — не в эфире"]}),!p&&e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Громкость меняется в звуке эфира этого компьютера — обновите студию, если ползунки не двигаются."})]}),e.jsxs("section",{className:"sn-panel-sec","aria-label":"Общий уровень эфира",children:[e.jsxs("div",{className:"sn-panel-sec-head",children:[e.jsx("span",{className:"sn-eyebrow",children:"Общий уровень эфира"}),e.jsx("span",{className:"sn-s sn-mono",children:l.db!==null?`${Math.round(l.db)} дБ`:"тишина"})]}),e.jsxs("div",{className:"sn-shw-master",children:[e.jsx("span",{className:"sn-mono",children:"L"}),e.jsx(wa,{value:l.l,count:36,className:"is-wide"}),e.jsx("span",{className:"sn-mono",children:"R"}),e.jsx(wa,{value:l.r,count:36,className:"is-wide"})]}),e.jsxs("div",{className:"sn-shw-switchrow",children:[e.jsx("span",{className:"sn-shw-mix-ico is-blue",children:e.jsx(Fl,{className:"sn-i sn-i-16"})}),e.jsxs("div",{children:[e.jsx("b",{children:"Слушать эфир в наушниках"}),e.jsx("span",{children:"звук, который уходит зрителям и в запись"})]}),e.jsx(Pe,{checked:t,onChange:a,label:"Слушать эфир в наушниках",disabled:!s.programAudioStream})]}),t&&e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Только в наушниках — иначе микрофон подхватит звук эфира."})]}),e.jsx(Em,{api:s})]})}const ll=/клип|clips|shorts|reels|вертикал|vertical/i,Ar="vertical_1080p30",ka=s=>typeof s.destinationId=="string"?s.destinationId:null,rl=s=>s.outputProfile===Ar&&_s(s.status)!=="off";function Tm(s,n,t){const a=Om(s,n,t);return s.verticalFormat?a:null}
111function Om(s,n,t){var U;const a=Se(),i=s.room.id,[l,r]=sn(`sn-show:${i}:format`,"16:9"),[m,o]=sn(`sn-show:${i}:pictures`,{}),[c,u]=t,[x,f]=d.useState(!1),g=s.live.isLive,h=s.streamSession||null,p=(h==null?void 0:h.runtimeDestinations)||[],N=n.destinations.filter($=>$.enabled&&$.status!=="disabled"),k=$=>p.some(v=>ka(v)===$.id&&v.outputProfile!==Ar&&_s(v.status)!=="off"),b=N.filter($=>ll.test($.displayName||"")),y=[...b.filter($=>$.provider==="vk_video"||/клип/i.test($.displayName||"")),...b,...N.filter($=>$.provider==="vk_video")],w=N.find($=>p.some(v=>ka(v)===$.id&&rl(v)))||y.find($=>!(g&&h&&k($)))||null,T=!w&&y.length>0;if(!N.length&&!n.destinations.length&&n.destinationsError)return null;const q=!w||w.provider==="vk_video"||/клип/i.test(w.displayName||"")?"Вести вертикальный эфир на VK Клипы":`Вести вертикальный эфир на ${Us(w)}`,C=$=>l==="both"?m[$.id]||"16:9":l==="9:16"?"9:16":"16:9",_=!!w&&mt(w,c,n)&&C(w)==="9:16",K=!!w&&p.some($=>ka($)===w.id&&rl($)),L=g?K:_,F=x||!!((U=s.verticalLive)!=null&&U.busy),S=g?s.programFormat==="9:16":l==="9:16";let O=null;s.perms.externalBroadcast?w?L&&S?O=g?"Весь эфир идёт в 9:16 — вертикаль остановится вместе с эфиром":"Весь эфир пойдёт в 9:16 — формат меняется в «Выйти в эфир»":g&&h&&!s.setVerticalLive&&(O="Вертикаль на ходу добавляет продюсер, который ведёт эфир"):O=T?"VK уже получает эфир 16:9. Для Клипов добавьте отдельную площадку с ключом вертикального эфира — Настройки → Интеграции":"Подключите VK Видео в Настройки → Интеграции, чтобы вести вертикальный эфир в Клипы":O="Эфир на площадки ведёт продюсер с доступом к трансляции";const z=w?/клип/i.test(q)?"VK Клипы":Us(w):"";return{title:q,checked:L,disabled:F||!!O,note:O,onChange:$=>{var v;if(!(!w||F)){if(!g){if($)u(B=>({...B,[w.id]:!0})),l==="16:9"&&r("both"),o(B=>({...B,[w.id]:"9:16"})),a.show(`${z}: вертикаль пойдёт в эфир с его началом`);else{o(se=>({...se,[w.id]:"16:9"})),ll.test(w.displayName||"")&&u(se=>({...se,[w.id]:!1}));const B=N.some(se=>se.id!==w.id&&mt(se,c,n)&&C(se)==="9:16");l==="both"&&!B&&r("16:9"),a.show(`${z}: без вертикального эфира`)}return}if(f(!0),!h){const B=Kn();vi(s,{destinations:[{id:w.id,picture:"9:16"}],format:"9:16",record:s.autoRecord,latency:B.latency,quality:B.quality,privacy:B.privacy,title:s.room.title,description:"",workspaceId:((v=n.event)==null?void 0:v.workspaceId)??null}).then(se=>{se.ok?(u(A=>({...A,[w.id]:!0})),a.success(`${z}: подключаем вертикальный эфир`)):a.error(se.error||"Не удалось начать вертикальный эфир")}).finally(()=>f(!1));return}if(!s.setVerticalLive){f(!1);return}s.setVerticalLive(w.id,$).then(B=>{B.ok?$?a.success(`${z}: подключаем вертикальный эфир`):a.show(`${z}: вертикальный эфир остановлен`):a.error(B.error||"Площадка не ответила — попробуйте ещё раз")}).finally(()=>f(!1))}}}}const Fm={renderPanel:()=>null,counts:{},dots:{},modals:null,actions:{}},ol=s=>String(s||"").trim().split(/\s+/)[0]||s;function Rm(s){return s.length?s.length===1?s[0].member.name:s.length===2?`${s[0].member.name} и ${s[1].member.name}`:`${ol(s[0].member.name)}, ${ol(s[1].member.name)} и ещё ${s.length-2}`:""}function Sa({api:s,producer:n,scene:t,afterOpening:a,final:i}){var l;return t?t.id===s.program.sourceSceneId?e.jsxs("span",{className:"sn-tag sn-tag-red",title:"Сцена блока уже в эфире",children:["сцена «",t.name,"» в эфире"]}):((l=n.previewScene)==null?void 0:l.id)===t.id?a?e.jsxs("span",{className:"sn-tag sn-tag-blue",title:"Сцена блока стоит в подготовке",children:["после заставки выведите «",t.name,"»"]}):e.jsxs("span",{className:"sn-tag sn-tag-green",title:`«${t.name}» стоит в подготовке — «Вывести в эфир» или Пробел`,children:[e.jsx(Re,{className:"sn-i",style:{width:14,height:14}}),i?`«${t.name}» уже в подготовке`:"сцена уже в подготовке"]}):e.jsxs("button",{type:"button",className:"sn-tag sn-tag-blue",onClick:()=>n.setPreviewId(t.id),title:"Поставить сцену блока в подготовку",children:[e.jsx(Hn,{className:"sn-i",style:{width:14,height:14}}),"«",t.name,"» — в подготовку"]}):null}function Dm({api:s,producer:n,data:t,view:a,followsProducer:i,now:l,onOpen:r}){const m=t.program;if(!m.length)return null;const o=s.live.isLive,c=a.base,u=!n.programScene||n.programScene.template==="title";let x=null,f=null,g="";if(!o&&!a.current){const h=m[0],p=_n(c,h),N=Rm(rt(h,t.team,s.participants));x=e.jsxs(e.Fragment,{children:["Первый блок: ",e.jsxs("b",{children:[p!==null?`${qe(p)} · `:"",h.title]}),N?` — ${N}`:""]}),g=`Первый блок: ${h.title}`,f=e.jsx(Sa,{api:s,producer:n,scene:Wn(h,n.scenes),afterOpening:u})}else if(a.next){const h=a.next,p=_n(c,h),N=p!==null?Math.floor((p-l)/1e3):null;x=e.jsxs(e.Fragment,{children:["Далее по программе: ",e.jsxs("b",{children:[p!==null?`${qe(p)} · `:"",h.title]}),N!==null&&(N>0?e.jsxs(e.Fragment,{children:[" — через ",e.jsx("span",{className:"sn-mono",children:fs(N)})]}):e.jsxs(e.Fragment,{children:[" — ",e.jsx("span",{className:"is-late",children:"пора начинать"})]}))]}),g=`Далее по программе: ${h.title}`,f=e.jsx(Sa,{api:s,producer:n,scene:Wn(h,n.scenes)})}else if(a.current){const h=a.remainingSec;x=e.jsxs(e.Fragment,{children:["Сейчас последний блок: ",e.jsx("b",{children:a.current.title}),h>=0?e.jsxs(e.Fragment,{children:[" — осталось ",e.jsx("span",{className:"sn-mono",children:fs(h)})]}):e.jsxs(e.Fragment,{children:[" — ",e.jsxs("span",{className:"is-late",children:["сверх плана ",e.jsx("span",{className:"sn-mono",children:fs(-h)})]})]})]}),g=`Сейчас последний блок: ${a.current.title}`,f=e.jsx(Sa,{api:s,producer:n,scene:jr(n.scenes),final:!0})}return x?e.jsxs("div",{className:"sn-crew-bar","data-follows":i?"producer":"clock",children:[e.jsxs("button",{type:"button",className:"sn-crew-bar-main",onClick:r,"aria-label":`${g}. Открыть программу эфира`,children:[e.jsx(Ks,{className:"sn-i sn-i-16"}),e.jsx("span",{children:x})]}),o&&!i&&e.jsx("span",{className:"sn-crew-bar-src",title:"Блоки пока идут по часам — нажмите «Следующий блок» в «Программе», и строка пойдёт за вами",children:"по часам"}),f]}):null}function bn(s,n,t){var a;return gm({program:n.data.program,live:n.live,liveSince:s.live.isLive?s.liveSince??s.live.startedAt??null:null,scheduledAt:s.room.scheduledAt??((a=n.data.event)==null?void 0:a.scheduledAt)??null,history:n.history,now:t})}function qm(s){const n=ts(1e3),{inputs:t,...a}=s;return e.jsx(qu,{...a,rundown:bn(s.api,t,n)})}function _m({api:s,producer:n,inputs:t,onOpen:a}){var l;const i=ts(1e3);return e.jsx(Dm,{api:s,producer:n,data:t.data,view:bn(s,t,i),followsProducer:!!((l=t.live)!=null&&l.itemId),now:i,onOpen:a})}function Um({api:s,producer:n,inputs:t,onNextBlock:a,onCue:i,busy:l}){const r=ts(1e3);return e.jsx(Sm,{api:s,producer:n,data:t.data,view:bn(s,t,r),history:t.history,onNextBlock:a,onCue:i,busy:l})}function Bm({api:s,inputs:n}){var c;const t=ts(5e3),{cues:a}=Vs(),[i,l]=sn(`sn-show:${s.room.id}:autocue`,{}),r=bn(s,n,t),m=r.current,o=!((c=n.live)!=null&&c.by)||n.live.by===s.me.name;return d.useEffect(()=>{if(!s.live.isLive||!s.perms.manageStage||!m||!o)return;const u=m.cueBeforeEndMin;if(!u||u<=0||i[m.id]||r.remainingSec>u*60||r.remainingSec<u*60-90)return;l(h=>({...h,[m.id]:Date.now()}));const x=`Осталось ${u} ${u===1?"минута":u<5?"минуты":"минут"}`,f=rt(m,n.data.team,s.participants).map(h=>h.participant).filter(h=>!!h&&!h.isLocal),g=f.length?f:s.stageParticipants.filter(h=>h.type==="user"&&!h.isLocal);if(!g.length){a.send(null,x,"time");return}g.forEach(h=>void a.send(s.stageIdOf(h),x,"time"))},[t,m==null?void 0:m.id]),null}function Hm(s,n){var r;const t=s.room.scheduledAt?Date.parse(s.room.scheduledAt):NaN,a=Number.isFinite(t)?t:s.liveSince??s.live.startedAt??null,i=n.program.reduce((m,o)=>m+o.durationMin,0);if(a!==null&&i>0)return a+i*6e4;const l=(r=n.event)!=null&&r.endsAt?Date.parse(n.event.endsAt):NaN;return Number.isFinite(l)?l:null}function Vm(s){var ze,os;const{api:n,producer:t,openPanel:a,actions:i}=s,l=Se(),{ended:r}=Vs(),m=n.room.id,o=n.view==="producer",c=uu(m,o,null),[u,x]=mu(n.studioSocket,n.rundownLive),[f,g]=sn(`sn-show:${m}:blocks`,[]),h=lm(m),p=Tm(n,c,h),N=mm(n),k=wu(n,t),b=$u(n),[y,w]=d.use
111State(!1);Am(n,y),dm(n,t);const[T,q]=d.useState(!1),[C,_]=d.useState(null),[K,L]=d.useState(null),[F,S]=d.useState(null),[O,z]=d.useState(null),[M,U]=d.useState(!1),[$,v]=d.useState(!1),[B,se]=d.useState(null),[A,X]=d.useState(null),[ae,ce]=d.useState(!1),xe=d.useMemo(()=>({data:c,live:u,history:f}),[c,u,f]),ye=d.useMemo(()=>jr(t.scenes),[t.scenes]),be=Uu(n),ge=Bu(n,c,ye,be),rs=d.useRef(null);d.useEffect(()=>{if(!r.ended||B)return;const re=r.ended.endedAt?Date.parse(r.ended.endedAt):NaN;se(rs.current||ge(!1,Number.isFinite(re)?re:void 0)),v(!1)},[r.ended]);const Ie=d.useCallback(async re=>{const he=await En(n.studioSocket,"studio:rundown",{itemId:re});return he.success?(x(he.rundown||{itemId:re,startedAt:Date.now(),by:n.me.name}),g(D=>{var V;return[...D.filter(Q=>Q.itemId!==re),{itemId:re,startedAt:((V=he.rundown)==null?void 0:V.startedAt)||Date.now()}].slice(-60)}),{ok:!0}):{ok:!1,error:he.error||"Не удалось переключить блок"}},[n.studioSocket,n.me.name,x,g]),De=async()=>{var D,V;const he=bn(n,xe,Date.now()).next;if(!(!he||ae)){ce(!0);try{const Q=await Ie(he.id);if(!Q.ok){l.error(Q.error);return}const Z=Wn(he,t.scenes);Z&&n.perms.manageStage&&(((D=t.previewScene)==null?void 0:D.id)===Z.id?await t.takePreview():((V=t.programScene)==null?void 0:V.id)!==Z.id&&await t.takeScene(Z));const fe=c.program.findIndex(Be=>Be.id===he.id),ve=Wn(c.program[fe+1]||null,t.scenes);ve&&t.setPreviewId(ve.id),l.show(`Блок «${he.title}»`)}finally{ce(!1)}}},We=d.useRef(n.live.isLive);d.useEffect(()=>{const re=n.live.isLive;re&&!We.current&&!(u!=null&&u.itemId)&&c.program.length&&n.perms.manageStage&&Ie(c.program[0].id),We.current=re},[n.live.isLive]);const W=d.useRef(n.toggleMic);W.current=n.toggleMic,d.useEffect(()=>{if(!o)return;const re=he=>{if(he.defaultPrevented||he.ctrlKey||he.metaKey||he.altKey||he.repeat||ui(he.target)||mi())return;const D=he.key.toLowerCase();D!=="m"&&D!=="ь"||(he.preventDefault(),W.current())};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[o]);const oe=()=>z("devices"),le=re=>{re!=null&&re.length&&b.add(re),U(!0)},ie={openCue:re=>L({target:re,anchor:null}),openLowerThirds:re=>S({focusId:(re==null?void 0:re.id)??null}),openGoLive:()=>q(!0),openSettings:oe,openEnd:()=>v(!0)};if(!o)return Fm;const as=re=>{var he;switch(re){case"media":return e.jsx(fu,{api:n,producer:t,openId:A,setOpenId:X,onUpload:le,video:k,data:c});case"brand":return e.jsx(zu,{api:n,producer:t,data:c});case"sound":return e.jsx(zm,{api:n,producer:t,listen:y,setListen:w});case"rundown":return e.jsx(Um,{api:n,producer:t,inputs:xe,onNextBlock:()=>void De(),onCue:D=>L({target:null,anchor:D}),busy:ae});case"outputs":return e.jsx(pm,{api:n,data:c,choice:h,samples:N,onOpenRecording:_,onOpenGoLive:()=>q(!0)});case"ai":return e.jsx(du,{api:n,workspaceId:((he=c.event)==null?void 0:he.workspaceId)||null});default:return null}},Ze=re=>{switch(re){case"media":return A&&n.media.some(he=>he.id===A)?null:n.perms.mediaTools||n.perms.manageStage?e.jsx(R,{size:"sm",variant:"text",icon:e.jsx(cn,{className:"sn-i sn-i-16"}),onClick:()=>U(!0),style:{height:30,fontSize:13},children:"Загрузить"}):null;case"sound":return e.jsx(R,{size:"sm",variant:"text",icon:e.jsx(oi,{className:"sn-i sn-i-16"}),onClick:oe,style:{height:30,fontSize:13},children:"Устройства"});case"brand":return e.jsx(Tu,{live:n.live.isLive});case"outputs":return n.live.isLive&&n.viewerCount!==null?e.jsxs("span",{className:"sn-shw-headstat",children:[e.jsx(gs,{className:"sn-i",style:{width:14,height:14}}),"зрителей ",e.jsx("b",{className:"sn-mono",children:He(n.viewerCount)})]}):null;case"rundown":{const he=bn(n,xe,Date.now());return he.base!==null&&he.plannedEnd!==null&&c.program.length?e.jsxs("span",{className:"sn-shw-headstat sn-mono",children:[qe(he.base),"–",qe(he.plannedEnd)]}):null}default:return null}},cs=wt(n),Fe={},ne={};(cs.length||(ze=n.recordingUpload)!=null&&ze.lastError)&&(ne.outputs=!0),n.media.some(re=>{var he;return((he=re.participant.videoFile)==null?void 0:he.isPlaying)&&t.programIds.includes(re.id)})&&(ne.media=!0);const je=K?((os=bn(n,xe,Date.now()).next)==null?void 0:os.title)??null:null,Ee=e.jsxs(e.Fragment,{children:[T&&e.jsx(rm,{open:!0,onClose:()=>q(!1),api:n,producer:t,data:c,choice:h}
111),C&&e.jsx(_u,{api:n,anchor:C,onClose:()=>_(null)}),K&&e.jsx(km,{open:!0,anchor:K.anchor,onClose:()=>L(null),api:n,target:K.target,nextTitle:je}),F&&e.jsx(cm,{open:!0,onClose:()=>S(null),api:n,producer:t,focusId:F.focusId}),O&&e.jsx(Lm,{open:!0,onClose:()=>z(null),api:n,producer:t,tab:O,setTab:z}),e.jsx(Iu,{open:M,onClose:()=>U(!1),api:n,uploads:b,onOpenMedia:re=>{a("media"),X(re)}}),$&&!B&&e.jsx(Vu,{open:!0,onClose:()=>v(!1),api:n,producer:t,data:c,plannedEnd:Hm(n,c),finalScene:ye,recordedBefore:be&&!n.recording.active,snapshot:re=>{const he=ge(re);return rs.current=he,he},onEnded:re=>{v(!1),se(he=>he||re)}}),e.jsx(jm,{api:n,onOpenOutputs:()=>a("outputs")}),e.jsx(Bm,{api:n,inputs:xe}),B&&e.jsx(Gu,{api:n,snapshot:B,data:c})]});return{renderPanel:as,panelHeadAction:Ze,counts:Fe,dots:ne,modals:Ee,actions:ie,renderHeader:()=>e.jsx(qm,{api:n,inputs:xe,onOpenPanel:a,onOpenRecording:_,onGoLive:()=>q(!0),onEnd:()=>v(!0),onSettings:oe,onInvite:()=>i.openInvite()}),goLive:()=>q(!0),verticalLive:p,renderProgramBar:()=>e.jsx(_m,{api:n,producer:t,inputs:xe,onOpen:()=>a("rundown")})}}const Et=new Map;function Km(s){const[n,t]=d.useState(()=>Et.get(s)??null);return d.useEffect(()=>{if(!s||Et.has(s)){t(Et.get(s)??null);return}let a=!0;return Ho.get(s).then(i=>{var r;const l=String(((r=i.organizer)==null?void 0:r.name)||"").trim();l&&(Et.set(s,l),a&&t(l))}).catch(()=>{}),()=>{a=!1}},[s]),n}function Pr(s){return s.visibility==="speakers_only"||s.visibility==="private"}function Wm({api:s,message:n,canModerate:t,canAir:a,pinned:i,onAir:l,onBlock:r,onMessage:m,rt:o}){var y,w,T;const c=Se(),u=mn(),x=Ys(s,n.peerId),f=x?Os(x):"",g=((w=(y=s.chatMeta)==null?void 0:y[n.id])==null?void 0:w.senderRole)==="brand",h=g?"организатор":f&&!bt(f)?(hi[f]||"").toLowerCase():"",p=n.visibility==="private"?n.isMine?((T=Ys(s,n.recipientPeerId))==null?void 0:T.name)||"участнику":"вам":null,N=async(q,C)=>{const _=await q;_.ok?C&&c.success(C):c.error(_.error||"Не получилось")},k=t&&!n.isMine&&!h,b=[...x&&!n.isMine?[{label:"Написать лично",icon:e.jsx(Hs,{className:"sn-i sn-i-16"}),onSelect:()=>m(x)}]:[],...k?[{label:"Мьют на 5 минут",description:"Не сможет писать в чат",icon:e.jsx(Rl,{className:"sn-i sn-i-16"}),onSelect:()=>void N(o.chat.muteUser({messageId:n.id,minutes:5}),`${n.senderName} не пишет в чат 5 минут`)},{label:"Удалить все сообщения автора",icon:e.jsx(hn,{className:"sn-i sn-i-16"}),onSelect:()=>void N(o.chat.deleteByAuthor({messageId:n.id}),"Сообщения автора удалены")},{type:"separator"},{label:"Заблокировать автора",icon:e.jsx(yl,{className:"sn-i sn-i-16"}),danger:!0,onSelect:()=>r(n)}]:[]];return e.jsxs("div",{className:`sn-h-msg${l?" is-onair":""}${u.open?" is-open":""}`,children:[e.jsx(Ve,{name:n.senderName,src:g?s.brand.logo||void 0:n.senderAvatar||(x==null?void 0:x.avatarUrl),size:28}),e.jsxs("div",{className:"sn-h-msg-body",children:[e.jsxs("div",{className:"sn-h-msg-head",children:[e.jsxs("b",{children:[n.senderName,n.isMine?" (вы)":""]}),h&&e.jsx("span",{className:"sn-tag sn-tag-blue sn-h-role",children:h}),p&&e.jsxs("span",{className:"sn-tag sn-tag-amber sn-h-role",children:["лично ",n.isMine?`→ ${p}`:p]}),l&&e.jsx("span",{className:"sn-tag sn-tag-live sn-h-role",children:"на экране"}),e.jsx("span",{className:"sn-msg-spacer",style:{flex:1}}),e.jsx("span",{className:"sn-h-msg-time sn-mono",children:Js(n.createdAt)})]}),e.jsx("div",{className:"sn-h-msg-text",children:n.text}),(t||a||b.length>0)&&e.jsxs("div",{className:"sn-h-msg-acts",children:[a&&n.visibility==="public"&&e.jsx(R,{size:"xs",variant:l?"quiet":"soft",icon:l?e.jsx(ls,{className:"sn-i sn-i-16"}):e.jsx(ql,{className:"sn-i sn-i-16"}),onClick:()=>s.showCommentOnAir(l?null:n.id),children:l?"Убрать с экрана":"На экран"}),t&&n.visibility==="public"&&e.jsx(R,{size:"xs",variant:"quiet",icon:i?e.jsx(Vo,{className:"sn-i sn-i-16"}):e.jsx(Dl,{className:"sn-i sn-i-16"}),onClick:()=>void N(i?o.chat.unpin():o.chat.pin(n.id),i?"Сообщение откреплено":"Сообщение закреплено"),children:i?"Открепить":"Закрепить"}),t&&e.jsx(R,{size:"xs",variant:"quiet",onClick:()=>void N(o.chat.deleteMessage(n.id),"Сообщение скрыто"),children:"Скрыть"}),b.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-xs","aria-label":"Ещё действия с сообщением",onClick:u.toggle,children:e.jsx(zs,{className:"sn-i sn-i-16"})}),e.jsx(Cs,{open:u.open,onClose:u.close,anchor:u.anchor,width:260,items:b})]})]})]})]})}function Gm({message:s,onClose:n,rt:t}){const a=Se(),[i,l]=d.useState("spam"),[r,m]=d.useState(!0),[o,c]=d.use
111State(!1);return d.useEffect(()=>{s&&(l("spam"),m(!0),c(!1))},[s]),e.jsx(yn,{open:!!s,onClose:n,title:`Заблокировать ${(s==null?void 0:s.senderName)||""}?`,description:"Не сможет писать в чат, задавать вопросы, голосовать и ставить реакции в этом эфире.",confirmLabel:"Заблокировать",icon:e.jsx(yl,{className:"sn-i"}),onConfirm:async()=>{if(!s)return;const u=await t.chat.block({messageId:s.id,reason:i,deleteMessages:r,removeFromRoom:o});if(!u.ok){a.error(u.error||"Не удалось заблокировать");return}a.success(`${s.senderName} заблокирован(а)${u.deleted?` · удалено сообщений: ${u.deleted}`:""}`),n()},children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsx(we,{ariaLabel:"Причина",value:i,onChange:l,options:[{value:"spam",label:"Спам"},{value:"abuse",label:"Оскорбления"},{value:"other",label:"Другое"}]}),e.jsx(Rn,{checked:r,onChange:m,label:"Удалить все его сообщения"}),e.jsx(Rn,{checked:o,onChange:c,label:"Удалить из эфира",description:"Страница эфира закроется у него сразу"})]})})}const Qm=[{value:"0",label:"Выкл"},{value:"5",label:"5 с"},{value:"10",label:"10 с"},{value:"30",label:"30 с"},{value:"60",label:"1 мин"}];function Ym({open:s,onClose:n,rt:t}){const a=Se(),i=t.chat,[l,r]=d.useState(!1),m=i.refreshBlocked;d.useEffect(()=>{s&&(r(!0),m().finally(()=>r(!1)))},[s,m]);const o=async(u,x)=>{const f=await u;f.ok?a.success(x):a.error(f.error||"Не удалось сохранить")},c=u=>u?`до ${Js(u)}`:"навсегда";return e.jsx(Ke,{open:s,onClose:n,width:560,icon:e.jsx(Hs,{className:"sn-i"}),title:e.jsx("span",{className:"sn-display",children:"Настройки чата"}),subtitle:"Применяются сразу для всех зрителей",children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[e.jsxs("div",{className:"sn-h-perm",children:[e.jsxs("span",{className:"sn-h-perm-text",children:[e.jsx("b",{children:"Кто пишет в чат"}),e.jsx("span",{children:"команда эфира пишет всегда"})]}),e.jsx(we,{size:"sm",ariaLabel:"Кто пишет в чат",value:i.settings.mode,onChange:u=>void o(i.setMode(u),u==="off"?"Чат для зрителей выключен":"Режим чата сохранён"),options:[{value:"all",label:"Все"},{value:"registered",label:"С аккаунтом"},{value:"off",label:"Никто"}]})]}),e.jsxs("div",{className:"sn-h-perm",children:[e.jsxs("span",{className:"sn-h-perm-text",children:[e.jsx("b",{children:"Медленный режим"}),e.jsx("span",{children:"пауза между сообщениями одного зрителя"})]}),e.jsx(we,{size:"sm",ariaLabel:"Медленный режим",value:String(i.settings.slowModeSec),onChange:u=>void o(i.setSlowMode(Number(u)),Number(u)?"Медленный режим включён":"Медленный режим выключен"),options:Qm})]}),e.jsxs("div",{className:"sn-h-perm",children:[e.jsxs("span",{className:"sn-h-perm-text",children:[e.jsx("b",{children:"Ссылки в сообщениях"}),e.jsx("span",{children:"выключите — ссылки зрителей не пройдут"})]}),e.jsx(Pe,{checked:i.settings.linksAllowed,onChange:u=>void o(i.setLinksAllowed(u),u?"Ссылки разрешены":"Ссылки запрещены"),label:"Ссылки в сообщениях"})]}),e.jsxs("div",{style:{marginTop:12,display:"flex",flexDirection:"column",gap:6},children:[e.jsxs("span",{className:"sn-eyebrow",children:["Ограничены · ",i.blocked.length]}),l&&!i.blocked.length&&e.jsx(Zs,{height:36,radius:10}),!l&&!i.blocked.length&&e.jsx("div",{className:"sn-h-empty",children:"Никого — все могут писать"}),i.blocked.map(u=>e.jsxs("div",{className:"sn-h-row",children:[e.jsx(Ve,{name:u.name,size:30}),e.jsxs("span",{className:"sn-h-row-text",children:[e.jsx("span",{className:"sn-h-name",children:u.name}),e.jsxs("span",{className:"sn-h-sub",children:[u.kind==="mute"?`мьют ${c(u.expiresAt)}`:"заблокирован",u.reason?` · ${u.reason==="spam"?"спам":u.reason==="abuse"?"оскорбления":"другое"}`:"",u.createdByName?` · ${u.createdByName}`:""]})]}),e.jsx(R,{size:"sm",variant:"quiet",className:"sn-h-small",onClick:()=>void o(i.unblock(u.id),`${u.name} снова может писать`),children:"Снять"})]},u.id))]})]})})}function Xm({api:s,rt:n,tab:t,onTab:a,dm:i,onDm:l,teamUnread:r}
111){const m=Se(),[o,c]=d.useState(""),[u,x]=d.useState(!1),[f,g]=d.useState(null),h=d.useRef(null),p=d.useRef(!0),N=n.chat.canModerate||s.perms.moderate||s.perms.manageStage,k=s.perms.manageStage,b=n.chat.pinnedMessageId,y=n.chat.pinnedMessage,w=Km(s.room.id),T=d.useMemo(()=>s.chat.filter(_=>(t==="team"?Pr(_):_.visibility==="public")&&_.id!==(t==="viewers"?b:null)),[s.chat,t,b]);d.useLayoutEffect(()=>{const _=h.current;_&&p.current&&(_.scrollTop=_.scrollHeight)},[T.length,t]);const q=async()=>{const _=o.trim();if(!(!_||u)){x(!0);try{const K=i?await n.chat.send(_,{visibility:"private",recipientPeerId:s.stageIdOf(i)}):await n.chat.send(_,t==="team"?{visibility:"team"}:{visibility:"public",asBrand:s.perms.manageStage});if(!K.ok){m.error(K.error||"Сообщение не отправилось");return}c(""),p.current=!0}finally{x(!1)}}},C=t==="viewers"&&n.chat.settings.mode!=="all"?n.chat.settings.mode==="off"?"Зрители не пишут в чат — выключено в настройках":"Пишут только зрители с аккаунтом":t==="viewers"&&n.chat.settings.slowModeSec?`Медленный режим: ${n.chat.settings.slowModeSec} с между сообщениями`:null;return e.jsxs("div",{className:"sn-h-fill",children:[e.jsxs("div",{className:"sn-h-scroll",ref:h,style:{gap:12},onScroll:_=>{const K=_.currentTarget;p.current=K.scrollHeight-K.scrollTop-K.clientHeight<60},children:[e.jsx(we,{className:"sn-h-seg",ariaLabel:"Чат",value:t,onChange:a,options:[{value:"viewers",label:"Зрители"},{value:"team",label:e.jsxs(e.Fragment,{children:["Команда ",r>0&&e.jsx("span",{className:"sn-h-badge",children:r})]})}],style:{flex:"none"}}),t==="viewers"&&y&&!y.isDeleted&&e.jsxs("div",{className:"sn-h-pin",children:[e.jsx(Dl,{className:"sn-i sn-i-16",style:{color:"var(--sn-blue)",flex:"none",marginTop:2}}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{className:"sn-h-pin-label",children:["Закреплено · ",y.senderName]}),e.jsx("div",{className:"sn-h-pin-text",children:y.text})]}),N&&e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-xs","aria-label":"Открепить",onClick:()=>void n.chat.unpin().then(_=>_.ok?m.success("Сообщение откреплено"):m.error(_.error||"Не получилось")),children:e.jsx(ls,{className:"sn-i sn-i-16"})})]}),e.jsxs("div",{className:"sn-h-chat-list",role:"log","aria-live":"polite","aria-label":t==="team"?"Чат команды":"Чат зрителей",children:[T.map(_=>e.jsx(Wm,{api:s,rt:n,message:_,canModerate:N,canAir:k,pinned:_.id===b,onAir:s.activeCommentId===_.id,onBlock:g,onMessage:K=>{a("team"),l(K)}},_.id)),!T.length&&e.jsx("div",{className:"sn-h-empty",style:{padding:"24px 4px",textAlign:"center"},children:t==="team"?"Здесь переписка команды — зрители её не видят":"Сообщений пока нет"})]})]}),C&&e.jsx("div",{className:"sn-h-restrict",children:C}),i&&e.jsx("div",{style:{padding:"0 16px 8px"},children:e.jsxs("div",{className:"sn-h-dm",children:[e.jsx(Hs,{className:"sn-i sn-i-16"}),e.jsxs("span",{style:{flex:1,minWidth:0},children:["Лично ",e.jsx("b",{children:i.name})," — увидит только он(а)"]}),e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-xs","aria-label":"Писать всем",onClick:()=>l(null),children:e.jsx(ls,{className:"sn-i sn-i-16"})})]})}),e.jsxs("form",{className:"sn-h-compose",onSubmit:_=>{_.preventDefault(),q()},children:[e.jsx("input",{className:"sn-input",value:o,maxLength:1e3,onChange:_=>c(_.target.value),placeholder:i?`Сообщение для ${i.name}`:t==="team"?"Написать команде":s.perms.manageStage?`Написать от имени ${w||"организатора"}`:"Написать в чат эфира","aria-label":"Сообщение"}),e.jsx("button",{type:"submit",className:"sn-btn sn-btn-primary sn-h-send","aria-label":"Отправить",disabled:!o.trim()||u,children:e.jsx(sa,{className:"sn-i sn-i-16"})})]}),e.jsx(Gm,{message:f,onClose:()=>g(null),rt:n})]})}const Er=[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],zr=[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],Jm=0;function Tr(s){let n=(16*s+128)*s+64;if(s>=2){const t=Math.floor(s/7)+2;n-=(25*t-10)*t-55,s>=7&&(n-=36)}return n}function cl(s){return Math.floor(Tr(s)/8)-Er[s]*zr[s]}function Ka(s,n){let t=0;for(let a=7;a>=0;a--)t=t<<1^(t>>>7)*285,t^=(n>>>a&1)*s;return t&255}function Zm(s){const n=new Array(s).fill(0);n[s-1]=1;let t=1;for(let a=0;a<s;a++){for(let i=0;i<n.length;
111i++)n[i]=Ka(n[i],t),i+1<n.length&&(n[i]^=n[i+1]);t=Ka(t,2)}return n}function eh(s,n){const t=n.map(()=>0);for(const a of s){const i=a^t.shift();t.push(0),n.forEach((l,r)=>{t[r]^=Ka(l,i)})}return t}function sh(s){return Array.from(new TextEncoder().encode(s))}function nh(s){let n=1;for(;n<=40&&!(4+(n<=9?8:16)+s.length*8<=cl(n)*8);n++);if(n>40)throw new Error("QR: данных слишком много");const t=cl(n)*8,a=[],i=(r,m)=>{for(let o=m-1;o>=0;o--)a.push(r>>>o&1)};i(4,4),i(s.length,n<=9?8:16),s.forEach(r=>i(r,8)),i(0,Math.min(4,t-a.length)),i(0,(8-a.length%8)%8);for(let r=236;a.length<t;r^=253)i(r,8);const l=[];for(let r=0;r<a.length;r+=8){let m=0;for(let o=0;o<8;o++)m=m<<1|a[r+o];l.push(m)}return{version:n,codewords:l}}function th(s,n){const t=zr[s],a=Er[s],i=Math.floor(Tr(s)/8),l=t-i%t,r=Math.floor(i/t),m=Zm(a),o=[];for(let u=0,x=0;u<t;u++){const f=n.slice(x,x+r-a+(u<l?0:1));x+=f.length;const g=eh(f,m);u<l&&f.push(0),o.push(f.concat(g))}const c=[];for(let u=0;u<o[0].length;u++)o.forEach((x,f)=>{(u!==r-a||f>=l)&&c.push(x[u])});return c}function ah(s){if(s===1)return[];const n=Math.floor(s/7)+2,t=s===32?26:Math.ceil((s*4+4)/(n*2-2))*2,a=[6];for(let i=s*4+10;a.length<n;i-=t)a.splice(1,0,i);return a}class ih{constructor(n){this.version=n,this.size=n*4+17,this.modules=Array.from({length:this.size},()=>new Array(this.size).fill(!1)),this.isFunction=Array.from({length:this.size},()=>new Array(this.size).fill(!1))}set(n,t,a){this.modules[t][n]=a,this.isFunction[t][n]=!0}drawFunctionPatterns(){for(let a=0;a<this.size;a++)this.set(6,a,a%2===0),this.set(a,6,a%2===0);this.drawFinder(3,3),this.drawFinder(this.size-4,3),this.drawFinder(3,this.size-4);const n=ah(this.version),t=n.length;for(let a=0;a<t;a++)for(let i=0;i<t;i++)a===0&&i===0||a===0&&i===t-1||a===t-1&&i===0||this.drawAlignment(n[a],n[i]);this.drawFormatBits(0),this.drawVersion()}drawFinder(n,t){for(let a=-4;a<=4;a++)for(let i=-4;i<=4;i++){const l=Math.max(Math.abs(i),Math.abs(a)),r=n+i,m=t+a;r>=0&&r<this.size&&m>=0&&m<this.size&&this.set(r,m,l!==2&&l!==4)}}drawAlignment(n,t){for(let a=-2;a<=2;a++)for(let i=-2;i<=2;i++)this.set(n+i,t+a,Math.max(Math.abs(i),Math.abs(a))!==1)}drawFormatBits(n){const t=Jm<<3|n;let a=t;for(let r=0;r<10;r++)a=a<<1^(a>>>9)*1335;const i=(t<<10|a)^21522,l=r=>(i>>>r&1)!==0;for(let r=0;r<=5;r++)this.set(8,r,l(r));this.set(8,7,l(6)),this.set(8,8,l(7)),this.set(7,8,l(8));for(let r=9;r<15;r++)this.set(14-r,8,l(r));for(let r=0;r<8;r++)this.set(this.size-1-r,8,l(r));for(let r=8;r<15;r++)this.set(8,this.size-15+r,l(r));this.set(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let n=this.version;for(let a=0;a<12;a++)n=n<<1^(n>>>11)*7973;const t=this.version<<12|n;for(let a=0;a<18;a++){const i=(t>>>a&1)!==0,l=this.size-11+a%3,r=Math.floor(a/3);this.set(l,r,i),this.set(r,l,i)}}drawCodewords(n){let t=0;for(let a=this.size-1;a>=1;a-=2){a===6&&(a=5);for(let i=0;i<this.size;i++)for(let l=0;l<2;l++){const r=a-l,o=(a+1&2)===0?this.size-1-i:i;!this.isFunction[o][r]&&t<n.length*8&&(this.modules[o][r]=(n[t>>>3]>>>7-(t&7)&1)!==0,t++)}}}applyMask(n){for(let t=0;t<this.size;t++)for(let a=0;a<this.size;a++){if(this.isFunction[t][a])continue;let i;switch(n){case 0:i=(a+t)%2===0;break;case 1:i=t%2===0;break;case 2:i=a%3===0;break;case 3:i=(a+t)%3===0;break;case 4:i=(Math.floor(a/3)+Math.floor(t/2))%2===0;break;case 5:i=a*t%2+a*t%3===0;break;case 6:i=(a*t%2+a*t%3)%2===0;break;default:i=((a+t)%2+a*t%3)%2===0;break}i&&(this.modules[t][a]=!this.modules[t][a])}}penalty(){const n=this.size,t=this.modules;let a=0;const i=o=>{let c=0,u=o[0],x=1;for(let g=1;g<=o.length;g++){if(g<o.length&&o[g]===u){x++;continue}x>=5&&(c+=3+(x-5)),g<o.length&&(u=o[g],x=1)}const f=[!0,!1,!0,!0,!0,!1,!0];for(let g=0;g+7<=o.length;g++){let h=!0;for(let k=0;k<7;k++)if(o[g+k]!==f[k]){h=!1;break}if(!h)continue;const p=(()=>{for(let k=1;k<=4;k++)if(g-k>=0&&o[g-k])return!1;return!0})(),N=(()=>{for(let k=0;k<4;k++)if(g+7+k<o.length&&o[g+7+k])return!1;return!0})();(p||N)&&(c+=40)}return c};for(let o=0;o<n;o++)a+=i(t[o]);for(let o=0;o<n;o++)a+=i(t.map(c=>c[o]));for(let o=0;o<n-1;o++)for(let c=0;c<n-1;c++){const u=t[o][c];u===t[o][c+1]&&u===t[o+1][c]&&u===t[o+1][c+1]&&(a+=3)}let l=0;t.forEach(o=>
111o.forEach(c=>{c&&l++}));const r=n*n,m=Math.ceil(Math.abs(l*20-r*10)/r)-1;return a+=Math.max(0,m)*10,a}}function lh(s){const{version:n,codewords:t}=nh(sh(s)),a=th(n,t),i=new ih(n);i.drawFunctionPatterns(),i.drawCodewords(a);let l=0,r=1/0;for(let m=0;m<8;m++){i.applyMask(m),i.drawFormatBits(m);const o=i.penalty();o<r&&(r=o,l=m),i.applyMask(m)}return i.applyMask(l),i.drawFormatBits(l),{size:i.size,version:n,modules:i.modules}}function rh(s,n=0){const t=[];return s.modules.forEach((a,i)=>{let l=0;for(;l<s.size;){if(!a[l]){l++;continue}const r=l;for(;l<s.size&&a[l];)l++;t.push(`M${r+n} ${i+n}h${l-r}v1h${r-l}z`)}}),t.join("")}function oh({value:s,label:n}){const t=d.useMemo(()=>{try{return s?lh(s):null}catch{return null}},[s]);if(!t)return e.jsx("div",{className:"sn-h-empty",children:"QR недоступен"});const a=2,i=t.size+a*2;return e.jsxs("svg",{viewBox:`0 0 ${i} ${i}`,role:"img","aria-label":n,shapeRendering:"crispEdges","data-qr-version":t.version,children:[e.jsx("rect",{width:i,height:i,fill:"#fff"}),e.jsx("path",{d:rh(t,a),fill:"#141619"})]})}function dl(s,n,t){return new Promise(a=>{const i=window.setTimeout(()=>a(null),1e4);s.emit(n,t,l=>{window.clearTimeout(i),a(l)})})}function ch(s){const n=String(s??"");return/[;"\n\r]/.test(n)?`"${n.replace(/"/g,'""')}"`:n}function dh(s){const n=new Date(s),t=a=>String(a).padStart(2,"0");return`${t(n.getDate())}.${t(n.getMonth()+1)}.${n.getFullYear()} ${t(n.getHours())}:${t(n.getMinutes())}`}function uh({api:s,title:n}){const t=Se(),[a,i]=pl(),l=s.room.id,r=s.commsSocket,[m,o]=d.useState(null),[c,u]=d.useState(""),[x,f]=d.useState(""),[g,h]=d.useState(""),[p,N]=d.useState(!1),[k,b]=d.useState(null),[y,w]=d.useState(null),[T,q]=d.useState(!1);d.useEffect(()=>{if(!r)return;let F=!1;dl(r,"site-player:get",{roomId:l}).then(O=>{if(F||!(O!=null&&O.ok))return;const z=O.sitePlayer||null;o(z),u((z==null?void 0:z.pageUrl)||""),f((z==null?void 0:z.policyUrl)||""),h((z==null?void 0:z.operator)||"")});const S=O=>o((O==null?void 0:O.sitePlayer)||null);return r.on("site-player:changed",S),()=>{F=!0,r.off("site-player:changed",S)}},[r,l]),d.useEffect(()=>{let F=!1;return Ae.get(`rooms/${l}/studio/site-contacts`).then(S=>{F||w(Array.isArray(S==null?void 0:S.items)?S.items.length:0)}).catch(()=>{F||w(null)}),()=>{F=!0}},[l]);const C=async()=>{var S,O,z,M;if(!r){b("Нет связи со студией — подождите пару секунд");return}N(!0),b(null);const F=await dl(r,"site-player:set",{roomId:l,video:c.trim()||null,policyUrl:x.trim()||null,operator:g.trim()||null});if(N(!1),!(F!=null&&F.ok)){b((F==null?void 0:F.error)||"Не удалось сохранить — попробуйте ещё раз");return}o(F.sitePlayer||null),u(((S=F.sitePlayer)==null?void 0:S.pageUrl)||""),f(((O=F.sitePlayer)==null?void 0:O.policyUrl)||""),h(((z=F.sitePlayer)==null?void 0:z.operator)||""),t.success((M=F.sitePlayer)!=null&&M.src?"Видео VK сохранено — плееры на сайтах переключились":"Сохранено")},_=async()=>{q(!0);try{const F=await Ae.get(`rooms/${l}/studio/site-contacts`),S=Array.isArray(F==null?void 0:F.items)?F.items:[];w(S.length);const z=`\uFEFF${[["ФИО","Телефон","Email","Согласие на обработку данных","Оператор данных","Политика","Страница сайта"],...S.map($=>[$.name,$.phone,$.email||"",dh($.consentAt),$.operator||"",$.policyUrl||"",$.pageUrl||""])].map($=>$.map(ch).join(";")).join(`\r
112`)}`,M=URL.createObjectURL(new Blob([z],{type:"text/csv;charset=utf-8"})),U=document.createElement("a");U.href=M,U.download=`Контакты зрителей сайта — ${n.replace(/[\\/:*?"<>|]/g," ").slice(0,80)}.csv`,document.body.appendChild(U),U.click(),U.remove(),window.setTimeout(()=>URL.revokeObjectURL(M),5e3),t.success(S.length?`Скачано контактов: ${S.length}`:"Контактов пока нет — файл с заголовками скачан")}catch(F){t.error(js(F,"Не удалось выгрузить контакты"))}finally{q(!1)}},K=Ko(l,n),L=c.trim()!==((m==null?void 0:m.pageUrl)||"")||x.trim()!==((m==null?void 0:m.policyUrl)||"")||g.replace(/\s+/g," ").trim()!==((m==null?void 0:m.operator)||"");return e.jsxs("div",{className:"sn-h-siteplayer","data-testid":"inv
112ite-site-player",children:[e.jsxs("div",{className:"sn-h-siteplayer-head",children:[e.jsx("span",{className:"sn-h-link-ico",children:e.jsx(fc,{className:"sn-i sn-i-16"})}),e.jsxs("span",{style:{flex:1,minWidth:0},children:[e.jsx("b",{style:{display:"block"},children:"Плеер VK + чат SNICH"}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Видео — из VK Видео, рядом наш чат, вопросы, голосования и программа. Писать могут те, кто оставил ФИО и телефон."})]})]}),e.jsxs("form",{className:"sn-h-siteplayer-form",onSubmit:F=>{F.preventDefault(),C()},children:[e.jsx(ke,{label:"Трансляция в VK Видео",hint:"Ссылка на видео или «Код для вставки» из VK. Можно поменять во время эфира — плееры на сайтах переключатся сами.",error:k,children:e.jsx(Oe,{value:c,onChange:F=>u(F.target.value),placeholder:"https://vkvideo.ru/live-123456_456239017","aria-label":"Ссылка на трансляцию в VK Видео",className:"sn-mono"})}),e.jsx(ke,{label:"Оператор персональных данных",hint:g.trim()?"Так зрители увидят его в согласии: «…на обработку моих персональных данных (оператор — …)».":"Юрлицо, которое получает ФИО и телефоны зрителей: название и ИНН. Пока не указано — в согласии стоит название пространства SNICH.",children:e.jsx(Oe,{value:g,onChange:F=>h(F.target.value),maxLength:300,placeholder:"ООО «Название», ИНН 0000000000","aria-label":"Оператор персональных данных",invalid:!g.trim()&&!!m})}),e.jsx(ke,{label:"Политика конфиденциальности",aside:"необязательно",hint:"Ссылка на вашу политику — её увидят рядом с согласием. Без ссылки покажем короткое пояснение.",children:e.jsx(Oe,{value:x,onChange:F=>f(F.target.value),placeholder:"https://ваш-сайт.ru/privacy","aria-label":"Ссылка на политику конфиденциальности"})}),e.jsxs("div",{className:"sn-h-siteplayer-row",children:[e.jsx(R,{size:"sm",variant:L?"primary":"quiet",type:"submit",loading:p,disabled:!L&&!!m,children:"Сохранить"}),m!=null&&m.pageUrl?e.jsxs("a",{className:"sn-hint sn-h-siteplayer-now",href:m.pageUrl,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Re,{className:"sn-i sn-i-14"})," Сейчас в плеере: ",m.pageUrl.replace(/^https:\/\//,"")," ",e.jsx(Bt,{className:"sn-i sn-i-12"})]}):e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"Пока без видео — на сайте будет заставка, чат и программа"})]})]}),e.jsxs("div",{className:"sn-h-siteplayer-row",children:[e.jsx(R,{size:"sm",variant:"soft",icon:i?e.jsx(Re,{className:"sn-i sn-i-16"}):e.jsx(vt,{className:"sn-i sn-i-16"}),onClick:()=>void a(K,"Код плеера с чатом скопирован — вставьте его в HTML сайта"),children:"Скопировать код для сайта"}),e.jsxs("a",{className:"sn-btn sn-btn-text sn-btn-sm",href:Wo(l),target:"_blank",rel:"noopener noreferrer",children:["Открыть плеер ",e.jsx(Bt,{className:"sn-i sn-i-14"})]}),e.jsx("span",{style:{flex:1}}),e.jsxs(R,{size:"sm",variant:"quiet",icon:e.jsx(Oa,{className:"sn-i sn-i-16"}),loading:T,onClick:()=>void _(),children:["Контакты зрителей",y!==null?` · ${y}`:""]})]})]})}const mh=[{value:"speaker",label:"Спикер"},{value:"host",label:"Ведущий"},{value:"moderator",label:"Модератор"},{value:"producer",label:"Продюсер"},{value:"guest",label:"Гость"},{value:"viewer",label:"Зритель"}],hh=[{role:"speaker",title:"Спикеры",hint:"за кулисы, с проверкой теÑ
112…ники",icon:e.jsx(Ts,{className:"sn-i sn-i-16"})},{role:"host",title:"Ведущий",hint:"ведёт эфир: сцена, вопросы, подсказки",icon:e.jsx(Sl,{className:"sn-i sn-i-16"})},{role:"guest",title:"Гость",hint:"одноразовая ссылка на 1 человека",icon:e.jsx(Is,{className:"sn-i sn-i-16"}),badge:"1 раз"},{role:"moderator",title:"Модератор",hint:"зал ожидания, вопросы и чат",icon:e.jsx(ii,{className:"sn-i sn-i-16"})},{role:"producer",title:"Продюсер",hint:"все права в студии",icon:e.jsx(_l,{className:"sn-i sn-i-16"})}],xh=/^[^\s@,;]+@[^\s@,;]+\.[^\s@,;]+$/,ul=s=>s.replace(/^https?:\/\//,"");function Ca({value:s,label:n,message:t="Ссылка скопирована"}){const[a,i]=pl();return e.jsx(Ye,{label:n,variant:"quiet",size:"sm",onClick:()=>void a(s,t),disabled:!s,children:i?e.jsx(Re,{className:"sn-i sn-i-16"}):e.jsx(vt,{className:"sn-i sn-i-16"})})}function fh({open:s,onClose:n,api:t}){const a=Se(),i=t.room.id,[l,r]=d.useState(null),[m,o]=d.useState(null),[c,u]=d.useState(null),[x,f]=d.useState(null),[g,h]=d.useState(null),[p,N]=d.useState(""),[k,b]=d.useState("speaker"),[y,w]=d.useState(!1),[T,q]=d.useState(null),C=d.useCallback(async()=>{o(null);try{const[v,B]=await Promise.all([Ae.get(`rooms/${i}/role-links`),Ae.post(`rooms/${i}/role-links/guest`).catch(()=>null)]);r(Array.isArray(v)?v:[]),u(B)}catch(v){r([]),o(js(v,"Не удалось загрузить ссылки"))}try{const v=await Ae.get(`rooms/${i}/team`);q(Array.isArray(v)?v:[])}catch{q([])}},[i]);d.useEffect(()=>{s&&(r(null),u(null),q(null),C())},[s,C]);const _=v=>v==="guest"?c:(l==null?void 0:l.find(B=>B.role===v))||null,K=async v=>{f(v);try{const B=await Ae.post(`rooms/${i}/role-links/${v}/rotate`);v==="guest"?u(B):r(se=>[...(se||[]).filter(A=>A.role!==B.role),B]),a.success(_(v)?"Ссылка заменена — старая больше не работает":"Ссылка создана")}catch(B){a.error(js(B,"Не удалось заменить ссылку"))}finally{f(null),h(null)}},L=d.useMemo(()=>p.split(/[\s,;]+/).map(v=>v.trim()).filter(Boolean),[p]),F=L.filter(v=>!xh.test(v)),S=async()=>{if(!L.length||F.length)return;w(!0);let v=0;const B=[];let se=null;for(const A of L.slice(0,20))try{await Ae.post(`rooms/${i}/team`,{email:A,role:k,sendInvite:!0}),v+=1}catch(X){if(X instanceof Xa&&X.status===409)try{se=se||await Ae.get(`rooms/${i}/team`,{query:{include:"all"}});const ae=se.find(ce=>ce.email.toLowerCase()===A.toLowerCase());if(!ae)throw X;ae.role!==k&&await Ae.patch(`rooms/${i}/team/${ae.id}`,{role:k}),await Ae.post(`rooms/${i}/team/${ae.id}/invite`),v+=1;continue}catch(ae){B.push(`${A}: ${js(ae)}`);continue}B.push(`${A}: ${js(X)}`)}w(!1),v&&(a.success(v===1?"Приглашение отправлено":`Приглашения отправлены: ${v}`),N(""),Ae.get(`rooms/${i}/team`).then(A=>q(Array.isArray(A)?A:[])).catch(()=>{})),B.length&&a.error(B.join(" · "),{duration:8e3})},O=(T||[]).filter(v=>["speaker","host","guest"].includes(v.role)&&!v.isOwner),z=new Set(t.participants.map(v=>v.userId?String(v.userId):null).filter(Boolean)),M=O.filter(v=>v.userId&&z.has(String(v.userId))),U=O.filter(v=>!M.includes(v)),$=t.room.scheduledAt?Js(t.room.scheduledAt):"";return e.jsxs(e.Fragment,{children:[e.jsx(Ke,{open:s,onClose:n,width:640,icon:e.jsx(Is,{className:"sn-i"}),title:e.jsx("span",{className:"sn-display",children:"Пригласить в эфир"}),subtitle:"Ссылка сама определяет роль — отправьте человеку нужную",children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsx("div",{className:"sn-h-links",children:l===null?[0,1,2,3].map(v=>e.jsx(Zs,{height:40,radius:10,style:{margin:"8px 0"}},v)):e.jsxs(e.Fragment,{children:[m&&e.jsx("div",{className:"sn-h-greenbox is-warn",style:{marginBottom:8},children:m}),hh.map(v=>{const B=_(v.role);return!B&&v.role!=="producer"&&!m||!B&&m?null:e.jsxs("div",{className:"sn-h-link",children:[e.jsx("span",{className:"sn-h-link-ico",children:v.icon}),e.jsxs("span",{className:"sn-h-link-text",children:[e.jsxs("b",{children:[v.title,v.badge&&e.jsx("span",{className:"sn-tag sn-tag-amber sn-h-role",children:v.badge})]}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:v.hint})]}),B?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sn-h-link-url",title:B.url,children:ul(B.url)}),e.jsx(Ca,{value:B.url,label:`Скопировать ссылку: ${v.t
112itle}`}),e.jsx(Ye,{label:"Заменить ссылку",variant:"ghost",size:"sm",onClick:()=>h(v.role),disabled:x===v.role,children:e.jsx(zl,{className:"sn-i sn-i-16"})})]}):e.jsx(R,{size:"sm",variant:"quiet",onClick:()=>void K(v.role),loading:x===v.role,style:{marginLeft:"auto"},children:"Создать ссылку"})]},v.role)}),e.jsxs("div",{className:"sn-h-link",children:[e.jsx("span",{className:"sn-h-link-ico",children:e.jsx(gs,{className:"sn-i sn-i-16"})}),e.jsxs("span",{className:"sn-h-link-text",children:[e.jsx("b",{children:"Зрители"}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"страница эфира"})]}),e.jsx("span",{className:"sn-h-link-url",title:t.room.viewerUrl,children:ul(t.room.viewerUrl||t.room.inviteUrl)}),e.jsx(Ca,{value:t.room.viewerUrl||t.room.inviteUrl,label:"Скопировать ссылку для зрителей"}),e.jsx("span",{style:{width:30,flex:"none"}})]}),e.jsxs("div",{className:"sn-h-link","data-testid":"invite-embed",children:[e.jsx("span",{className:"sn-h-link-ico",children:e.jsx(Go,{className:"sn-i sn-i-16"})}),e.jsxs("span",{className:"sn-h-link-text",children:[e.jsx("b",{children:"Плеер на сайт"}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"код для вставки"})]}),e.jsx("span",{className:"sn-h-link-url sn-mono",title:Oi(i,t.room.title),children:'<iframe src="…/embed/…">'}),e.jsx(Ca,{value:Oi(i,t.room.title),label:"Скопировать код плеера для сайта",message:"Код плеера скопирован — вставьте его в HTML сайта"}),e.jsx("span",{style:{width:30,flex:"none"}})]}),e.jsx(uh,{api:t,title:t.room.title})]})}),e.jsxs("div",{className:"sn-h-invite-grid",style:{borderTop:"1px solid var(--sn-line)",paddingTop:16},children:[e.jsxs("form",{style:{display:"flex",flexDirection:"column",gap:10,minWidth:0},onSubmit:v=>{v.preventDefault(),S()},children:[e.jsx("label",{className:"sn-label",htmlFor:"sn-h-invite-emails",children:"По email"}),e.jsx(Oe,{id:"sn-h-invite-emails",value:p,onChange:v=>N(v.target.value),placeholder:"имя@компания.ru, можно несколько",invalid:F.length>0,autoComplete:"off"}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx(Bs,{value:k,onChange:b,options:mh,ariaLabel:"Роль",renderValue:v=>e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sn-hint",children:"Роль"})," ",v==null?void 0:v.label]}),style:{flex:1}}),e.jsx(R,{type:"submit",variant:"primary",icon:e.jsx(sa,{className:"sn-i sn-i-16"}),loading:y,disabled:!L.length||F.length>0,children:"Отправить"})]}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:F.length?`Проверьте адрес: ${F[0]}`:$?`В письме — личная ссылка и время начала, ${$}`:"В письме — личная ссылка в студию"}),T&&O.length>0&&e.jsxs("div",{className:`sn-h-greenbox${U.length?" is-warn":""}`,children:[e.jsx(Xr,{people:O.slice(0,3).map(v=>({name:v.name,src:v.avatarUrl})),size:24}),e.jsx("span",{children:U.length===0?`${O.length===1?"Спикер уже":`Все ${O.length} ${O.length<5?"спикера":"спикеров"} уже`} в студии`:`В студии ${M.length} из ${O.length} · ждём: ${U.slice(0,2).map(v=>v.name).join(", ")}${U.length>2?"…":""}`})]})]}),e.jsxs("div",{className:"sn-h-qr",children:[c?e.jsx(oh,{value:c.url,label:"QR-код гостевой ссылки"}):e.jsx(Zs,{width:100,height:100,radius:8}),e.jsx("b",{style:{fontSize:14},children:"Гость с телефона — отсканируйте"}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5},children:"ссылка одноразовая"})]})]})]})}),e.jsx(yn,{open:!!g,onClose:()=>h(null),onConfirm:()=>g?K(g):void 0,title:"Заменить ссылку?",description:"Старая ссылка сразу перестанет работать. Тем, кто уже в студии, ничего не грозит.",confirmLabel:"Заменить",tone:"primary"})]})}function ph({level:s}){const n=[.45,.8,1,.65],t=Math.min(1,Math.max(0,s/60));return e.jsx("span",{className:"sn-meter","aria-hidden":"true",style:{height:16},children:n.map((a,i)=>e.jsx("span",{style:{height:`${Math.max(3,Math.round(16*a*t))}px`,background:"var(--sn-green)"}},i))})}function Pn({label:s,count:n,tone:t,action:a,children:i}){return e.jsxs("section",{className:"sn-h-sec","aria-label":s,children:[e.jsxs("div",{className:"sn-h-sec-head",children:[e.jsxs("span",{className:`sn-eyebrow${t?` sn-h-eb-${t}`:""}`,children:[s,n!==void 0?` · ${n}`:""]}),e.jsx("span",{style:{flex:1}}),a]}),i]})}function jh({api:s,producer:n,rt:t,search:a,onSearch:i,onPersonMenu:l,onMessage:r,onInvite:m,onPermissions:o}){const c=Se(),u=ts(1e3),[x,f]=d.useState(!1),[g,h]=d.useState(null),p=Tc(s,n),N=(a||"").trim().toLowerCase(),k=v=>
112!N||v.toLowerCase().includes(N),b=s.perms.manageStage,y=Qn(),w=t.invites.invites.filter(v=>v.status==="pending"),T=t.audience.raisedHands.filter(v=>!v.isTeam&&k(v.name)),q=w.filter(v=>!T.some(B=>B.peerId===v.peerId)&&k(v.name)),C=t.audience.viewers||s.viewerCount||0,_=async(v,B,se)=>{h(v);try{const A=await B();A.ok?se&&c.success(se):c.error(A.error||"Не получилось")}finally{h(null)}},K=v=>b&&e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-h-dots","aria-label":`Действия: ${v.name}`,onClick:B=>l(v,B.currentTarget),children:e.jsx(zs,{className:"sn-i sn-i-16"})}),L=(v,B)=>{var be;const se=s.stageIdOf(v),A=!!s.readyPeers[se]||!v.isCameraOff&&!v.isMuted;let X=Rs(v);B==="live"&&(X=e.jsxs(e.Fragment,{children:[Rs(v)," · ",v.isMuted?"микрофон выключен":"в эфире"]}));const ae=B==="preview"&&n.standInIds.has(v.id);B==="preview"&&(X=e.jsxs(e.Fragment,{children:[Rs(v)," · ",ae?"в подготовке · авто":"в подготовке"]}));const ce=(B==="backstage"||B==="preview")&&y?y.callOf(v):null;ce?X=e.jsxs(e.Fragment,{children:[Rs(v)," · ",e.jsx(Zl,{api:s,call:ce,className:"sn-crew-inline"})]}):B==="backstage"&&(X=v.isCameraOff?e.jsxs(e.Fragment,{children:[Rs(v)," · ",e.jsx("span",{className:"sn-h-warn",children:"камера выключена"})]}):A?e.jsxs(e.Fragment,{children:[Rs(v)," · ",e.jsx("span",{className:"sn-h-ok",children:"ждёт выхода"})]}):e.jsxs(e.Fragment,{children:[Rs(v)," · за кулисами"]})),B==="team"&&(X=e.jsxs(e.Fragment,{children:[Rs(v)," · ",e.jsx("span",{className:"sn-h-ok",children:"в сети"})]})),B==="viewer"&&(X=v.isHandRaised?e.jsxs(e.Fragment,{children:["Зритель · ",e.jsx("span",{className:"sn-h-warn",children:"поднял руку"})]}):"Зритель");const xe=((be=s.audioLevels[v.id])==null?void 0:be.level)??0,ye=B==="live"?"var(--sn-red)":B==="preview"?"var(--sn-blue)":void 0;return e.jsxs("div",{className:"sn-h-row",children:[e.jsx(Ve,{name:v.name,src:v.avatarUrl,size:36,ring:ye}),e.jsxs("span",{className:"sn-h-row-text",children:[e.jsxs("span",{className:"sn-h-name",children:[v.name,v.isLocal?" (вы)":""]}),e.jsx("span",{className:"sn-h-sub",children:X})]}),B==="live"&&!v.isMuted&&xe>2&&e.jsx(ph,{level:xe}),(B==="live"||B==="preview")&&v.isMuted&&e.jsx("span",{className:"sn-h-mic is-off",title:"Микрофон выключен",children:e.jsx(Es,{className:"sn-i sn-i-16"})}),ce&&y&&b&&e.jsx(er,{api:s,crew:y,call:ce,participant:v,className:"sn-h-small"}),(B==="backstage"||ae)&&b&&!v.isCameraOff&&!ce&&e.jsx(R,{size:"sm",variant:"quiet",className:"sn-h-small",icon:e.jsx(ps,{className:"sn-i sn-i-16"}),onClick:()=>n.addToPreview(v),children:"В кадр"}),B==="team"&&e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-h-dots","aria-label":`Написать: ${v.name}`,onClick:()=>r(v),children:e.jsx(Hs,{className:"sn-i sn-i-16"})}),K(v)]},v.id)},F=p.live.filter(v=>k(v.name)),S=p.preview.filter(v=>k(v.name)),O=p.backstage.filter(v=>k(v.name)),z=p.team.filter(v=>k(v.name)),M=p.viewers.filter(v=>k(v.name)),U=t.waiting.waiting.filter(v=>k(v.name)),$=N&&!F.length&&!S.length&&!O.length&&!z.length&&!M.length&&!T.length&&!U.length;return e.jsxs("div",{className:"sn-h-fill",children:[e.jsxs("div",{className:"sn-h-scroll",children:[a!==null&&e.jsx(Oe,{inputSize:"sm",icon:e.jsx(ea,{className:"sn-i sn-i-16"}),placeholder:"Найти по имени",value:a,onChange:v=>i(v.target.value),onKeyDown:v=>{v.key==="Escape"&&(v.stopPropagation(),i(null))},action:e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-xs","aria-label":"Закрыть поиск",onClick:()=>i(null),children:e.jsx(ls,{className:"sn-i sn-i-16"})}),autoFocus:!0}),$&&e.jsxs("div",{className:"sn-h-empty",children:["Никого с именем «",a,"»"]}),y&&b&&!N&&e.jsx(sd,{crew:y}),F.length>0&&e.jsx(Pn,{label:"В эфире",count:F.length,tone:"live",children:F.map(v=>L(v,"live"))}),S.length>0&&e.jsx(Pn,{label:"В подготовке",count:S.length,tone:"prev",children:S.map(v=>L(v,"preview"))}),(O.length>0||!N&&!F.length&&!S.length)&&e.jsx(Pn,{label:"За кулисами",count:O.length,children:O.length?O.map(v=>L(v,"backstage")):e.jsx("div",{className:"sn-h-empty",children:"Пока никого — пригласите спикеров по ссылке"})}),y&&b&&!N&&e.jsx(nd,{crew:y}),(T.length>0||q.length>0)&&e.jsx(Pn,{label:"Заявки на сцену",count:T.length+q.length,tone:"amber",children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[T.map(v=>{const B=w.find(A=>A.peerId===v.peerId)||null,se=B?Math.max(0,Math.ceil(((B.localExpiresAt||B.expiresAt)-u)/1e3)):0;return e.jsxs("div",{className:`sn-h-hand${B?" is-sent":""}`,children:[e.jsxs("div",{className:"sn-h-hand-top",children:[e.jsx(Ve,{name:v.name,size:32}),e.jsxs("span",{className:"sn-h-row-text",children:[e.jsx("span",{className:"sn-h-name",children:v.name}),e.jsx("span",{className:"sn-h-sub",style:{whiteSpace:"normal"},children:B?`Приглашение отправлено · ждём ответа ${se}
112 с`:`Зритель${v.topic?` · ${v.topic}`:" · хочет выйти на сцену"}`})]}),!B&&e.jsxs("span",{className:"sn-h-hand-when",children:[e.jsx(Ja,{className:"sn-i sn-i-16"})," ",Ot(v.at,u)]})]}),b&&e.jsx("div",{className:"sn-h-hand-acts",children:B?e.jsx(R,{size:"sm",variant:"quiet",className:"sn-h-small",loading:g===`c:${B.id}`,onClick:()=>void _(`c:${B.id}`,()=>t.invites.cancel(B.id),"Приглашение отменено"),children:"Отменить приглашение"}):e.jsxs(e.Fragment,{children:[e.jsx(R,{size:"sm",variant:"quiet",className:"sn-h-small",loading:g===`i:${v.peerId}`,onClick:()=>void _(`i:${v.peerId}`,()=>t.invites.invite(v.peerId,v.topic?`Про «${v.topic}»`:void 0),`${v.name} получил(а) приглашение за кулисы`),children:"За кулисы"}),e.jsx(R,{size:"sm",variant:"text",className:"sn-h-small",loading:g===`l:${v.peerId}`,onClick:()=>void _(`l:${v.peerId}`,()=>t.invites.lowerHand(v.peerId)),children:"Отклонить"})]})})]},v.peerId)}),q.map(v=>{const B=Math.max(0,Math.ceil(((v.localExpiresAt||v.expiresAt)-u)/1e3));return e.jsxs("div",{className:"sn-h-hand is-sent",children:[e.jsxs("div",{className:"sn-h-hand-top",children:[e.jsx(Ve,{name:v.name,size:32}),e.jsxs("span",{className:"sn-h-row-text",children:[e.jsx("span",{className:"sn-h-name",children:v.name}),e.jsxs("span",{className:"sn-h-sub",children:["Приглашение отправлено · ждём ответа ",B," с"]})]})]}),b&&e.jsx("div",{className:"sn-h-hand-acts",children:e.jsx(R,{size:"sm",variant:"quiet",className:"sn-h-small",loading:g===`c:${v.id}`,onClick:()=>void _(`c:${v.id}`,()=>t.invites.cancel(v.id),"Приглашение отменено"),children:"Отменить приглашение"})})]},v.id)})]})}),e.jsx(Pn,{label:"Зал ожидания",count:t.waiting.ready?t.waiting.waiting.length:void 0,action:t.waiting.ready&&t.waiting.waiting.length>1&&b?e.jsx(R,{size:"sm",variant:"text",className:"sn-h-small",loading:g==="admit-all",onClick:()=>void _("admit-all",()=>t.waiting.admitAll(),"Все из зала ожидания вошли"),children:"Пустить всех"}):null,children:t.waiting.ready?e.jsxs(e.Fragment,{children:[t.waiting.enabled&&e.jsxs("p",{className:"sn-h-hint",children:[e.jsx(un,{className:"sn-i sn-i-16"})," Обычно этим занимается модератор"]}),U.map(v=>e.jsxs("div",{className:"sn-h-row",children:[e.jsx(Ve,{name:v.name,size:32}),e.jsxs("span",{className:"sn-h-row-text",children:[e.jsx("span",{className:"sn-h-name",children:v.name}),e.jsxs("span",{className:"sn-h-sub",children:[v.isRegistered?"Зарегистрирован":"Зритель"," · ",Ot(v.since,u)==="только что"?"только что":`ждёт ${Ot(v.since,u)}`]})]}),b&&e.jsxs(e.Fragment,{children:[e.jsx(R,{size:"sm",variant:"quiet",className:"sn-h-small",loading:g===`a:${v.id}`,onClick:()=>void _(`a:${v.id}`,()=>t.waiting.admit(v.id)),children:"Пустить"}),e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-h-dots","aria-label":`Отклонить: ${v.name}`,onClick:()=>void _(`r:${v.id}`,()=>t.waiting.reject(v.id)),children:e.jsx(ls,{className:"sn-i sn-i-16"})})]})]},v.id)),!U.length&&e.jsx("div",{className:"sn-h-empty",children:t.waiting.enabled?"Никто не ждёт":"Выключен — новые участники входят сразу"}),b&&e.jsxs("div",{className:"sn-h-row",style:{minHeight:36},children:[e.jsx("span",{className:"sn-h-row-text",children:e.jsx("span",{style:{fontSize:13.5},children:"Пускать без ожидания"})}),e.jsx(Pe,{checked:!t.waiting.enabled,onChange:v=>void _("wr",()=>t.waiting.setEnabled(!v)),label:"Пускать без ожидания",disabled:g==="wr"})]})]}):e.jsxs("p",{className:"sn-h-hint",children:[e.jsx(un,{className:"sn-i sn-i-16"})," Зал ожидания ещё не подключён — новые участники входят сразу"]})}),z.length>0&&e.jsx(Pn,{label:"Команда",count:z.length,children:z.map(v=>L(v,"team"))}),e.jsxs("section",{className:"sn-h-sec","aria-label":"Зрители",children:[e.jsxs("button",{type:"button",className:"sn-h-viewers","aria-expanded":x,onClick:()=>f(v=>!v),children:[e.jsx(gs,{className:"sn-i sn-i-16"}),e.jsxs("span",{className:"sn-eyebrow",children:["Зрители · ",e.jsx("span",{className:"sn-mono",children:He(C)})]}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5,flex:1},children:"смотрят сейчас"}),x?e.jsx(Qo,{className:"sn-i sn-i-16"}):e.jsx(Gn,{className:"sn-i sn-i-16"})]}),x&&e.jsxs("div",{style:{paddingTop:6},children:[M.slice(0,100).map(v=>L(v,"viewer")),M.length>100&&e.jsxs("div",{className:"sn-h-empty",children:["и ещё ",He(M.length-100)," — найдите через поиск"]}),!M.length&&e.jsx("div",{className:"sn-h-empty",children:C>0?"Зрители смотрят эфир на странице трансляции — в студию они не заходили":"Пока никто не смотрит"}),t.audience.peak>0&&e.jsxs("p",{className:"sn-h-hint",children:[e.jsx(Ks,{className:"sn-i sn-i-16"})," Пик за эфир: ",e.jsx("span",{className:"sn-mono",children:He(t.audie
112nce.peak)})]})]})]})]}),e.jsxs("div",{className:"sn-h-foot",children:[e.jsx(R,{variant:"quiet",icon:e.jsx(Un,{className:"sn-i sn-i-16"}),onClick:o,children:"Права в комнате"}),e.jsx(R,{variant:"quiet",icon:e.jsx(Is,{className:"sn-i sn-i-16"}),onClick:m,disabled:!s.perms.invites&&!b,children:"Пригласить"})]})]})}const Dt={screenShare:"speakers",upload:"speakers",unmuteWithoutInvite:"team",chat:"all",reactions:!0,raiseHand:!0,downloadSlides:!1,waitingRoom:!1};function gh(s,n){const t=s.studioSocket,[a,i]=d.useState(null),[l,r]=d.useState(!1),[m,o]=d.useState(null),c=d.useCallback(async()=>{if(!t)return;const x=await ot(t,"room:get-permissions",{});x.ok&&x.permissions?(i({...Dt,...x.permissions}),r(!!x.canEdit),o(null)):o(x.error||"Не удалось загрузить права")},[t]);d.useEffect(()=>{if(!n||!t||!s.joined)return;c();const x=f=>{f!=null&&f.permissions&&i({...Dt,...f.permissions})};return t.on("room:permissions",x),()=>{t.off("room:permissions",x)}},[n,t,s.joined,c]);const u=d.useCallback(async x=>{const f=await ot(t,"room:update-permissions",{patch:x});return f.ok&&f.permissions&&i({...Dt,...f.permissions}),f},[t]);return{permissions:a,canEdit:l,error:m,load:c,save:u}}const Qs=s=>{const n=Math.round(Number(s.replace(/\s+/g,"")));return Number.isFinite(n)&&n>0?n:0},vh=ht.forwardRef(function({socket:n,open:t,disabled:a},i){const[l,r]=d.useState(null),[m,o]=d.useState(!1),[c,u]=d.useState(""),[x,f]=d.useState("");if(d.useEffect(()=>{if(!t||!n)return;let h=!1;return ot(n,"room:get-audience-boost",{}).then(p=>{if(h)return;if(!p.ok||!p.available){r(null);return}const N={enabled:!!p.enabled,base:Number(p.base)||0,spread:Number(p.spread)||0};r(N),o(N.enabled),u(N.base?String(N.base):""),f(N.spread?String(N.spread):"")}),()=>{h=!0}},[t,n]),d.useImperativeHandle(i,()=>({async save(){if(!l||!n)return null;const h={enabled:m&&Qs(c)>0,base:Qs(c),spread:Math.min(Qs(x),Qs(c))};if(h.enabled===l.enabled&&h.base===l.base&&h.spread===l.spread)return null;const p=await ot(n,"room:set-audience-boost",h);return p.ok?(r({enabled:!!p.enabled,base:Number(p.base)||0,spread:Number(p.spread)||0}),null):p.error||"счётчик зрителей не сохранился"}}),[l,n,m,c,x]),!l)return null;const g=a||!m;return e.jsxs("section",{"data-testid":"audience-boost",children:[e.jsx("span",{className:"sn-eyebrow",children:"Счётчик зрителей"}),e.jsxs("div",{className:"sn-h-perm",children:[e.jsxs("span",{className:"sn-h-perm-text",children:[e.jsx("b",{children:"Зрители на других площадках"}),e.jsx("span",{children:"добавить к счётчику тех, кто смотрит в VK и на сайте — число видят спикеры, ведущие и зрители; вы видите и реальное"})]}),e.jsx(Pe,{checked:m,onChange:o,label:"Зрители на других площадках",disabled:a})]}),e.jsxs("div",{className:"sn-h-perm sn-h-boost",children:[e.jsxs("label",{className:"sn-h-boost-field",children:[e.jsx("span",{children:"Сколько добавить"}),e.jsx(Oe,{inputMode:"numeric",value:c,onChange:h=>u(h.target.value.replace(/[^\d]/g,"").slice(0,7)),placeholder:"3000","aria-label":"Сколько зрителей добавить",disabled:g})]}),e.jsxs("label",{className:"sn-h-boost-field",children:[e.jsx("span",{children:"Колебание, ±"}),e.jsx(Oe,{inputMode:"numeric",value:x,onChange:h=>f(h.target.value.replace(/[^\d]/g,"").slice(0,6)),placeholder:"30","aria-label":"Колебание числа зрителей",disabled:g})]}),e.jsx("span",{className:"sn-hint",children:m&&Qs(c)>0?`Счётчик покажет реальных зрителей + ${Qs(c).toLocaleString("ru-RU")}${Qs(x)?` ± ${Math.min(Qs(x),Qs(c)).toLocaleString("ru-RU")}`:""}, число меняется каждые 5 секунд`:"Счётчик показывает только зрителей этой комнаты"})]})]})}),$a=[{value:"team",label:"Команда"},{value:"speakers",label:"Спикеры"},{value:"all",label:"Все"}],bh=[{value:"all",label:"Все"},{value:"team",label:"Только команда"},{value:"off",label:"Выкл"}];function yh({open:s,onClose:n,perms:t,rt:a,socket:i=null}){const l=Se(),r=d.useRef(null),[m,o]=d.useState(null),[c,u]=d.useState(!1),{load:x}=t;d.useEffect(()=>{s&&x()},[s,x]),d.useEffect(()=>{if(!s){o(null);return}!m&&t.permissions&&o({...t.permissions,premoderation:a.qna.settings.requireApproval})},[s,t.permissions,a.qna.settings.requireApproval,m]);const f=d.useMemo(()=>({...t.permissions||Dt,premoderation:a.qna.settings.requireApproval}),[t.permissions,a.qna.settings.requireApproval]),g=(y,w)=>o(T=>T&&{...T,[y]:w}),h=async()=>{var y;if(m){u(!0);try{const{premoderation:w,...T}=m,q={};Object.keys(T).forEach(K=>
112{T[K]!==f[K]&&(q[K]=T[K])});const C=[];if(Object.keys(q).length){const K=await t.save(q);if(!K.ok){l.error(K.error||"Не удалось сохранить права");return}}if(w!==f.premoderation){const K=await a.qna.updateSettings({requireApproval:w});K.ok||C.push(K.error||"премодерация вопросов не сохранилась")}if(q.chat!==void 0){const K=await a.chat.setMode(q.chat==="all"?"all":"off");K.ok||C.push(K.error||"режим чата не сохранился")}if(q.waitingRoom!==void 0&&a.waiting.ready){const K=await a.waiting.setEnabled(q.waitingRoom);K.ok||C.push(K.error||"зал ожидания не переключился")}const _=await((y=r.current)==null?void 0:y.save());_&&C.push(_),C.length?l.error(`Права сохранены, но ${C.join(", ")}`):l.success("Права в комнате сохранены"),n()}finally{u(!1)}}},p=m,N=!t.canEdit||c,k=(y,w,T)=>e.jsx(we,{size:"sm",ariaLabel:T,value:(p==null?void 0:p[y])??w[0].value,onChange:q=>g(y,q),options:w.map(q=>({...q,disabled:N}))}),b=(y,w,T=!1)=>e.jsx(Pe,{checked:!!(p!=null&&p[y]),onChange:q=>g(y,q),label:w,disabled:N||T});return e.jsx(Ke,{open:s,onClose:()=>c?void 0:n(),width:640,icon:e.jsx(Un,{className:"sn-i"}),title:e.jsx("span",{className:"sn-display",children:"Права в комнате"}),subtitle:"Для всех в эфире. Продюсер, ведущая и модератор могут всё.",footer:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"sn-hint",style:{flex:1,fontSize:13},children:t.canEdit||!t.permissions?"Изменения применятся сразу, без перезахода":"Права меняют продюсер, организатор и ведущие"}),e.jsx(R,{variant:"quiet",onClick:n,disabled:c,children:"Отмена"}),e.jsx(R,{variant:"primary",onClick:h,loading:c,disabled:!p||!t.canEdit,children:"Сохранить"})]}),children:p?e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[e.jsxs("section",{children:[e.jsx("span",{className:"sn-eyebrow",children:"Кто может"}),e.jsxs("div",{className:"sn-h-perm",children:[e.jsxs("span",{className:"sn-h-perm-text",children:[e.jsx("b",{children:"Демонстрация экрана"}),e.jsx("span",{children:"показывать свой экран в студии"})]}),k("screenShare",$a,"Демонстрация экрана")]}),e.jsxs("div",{className:"sn-h-perm",children:[e.jsxs("span",{className:"sn-h-perm-text",children:[e.jsx("b",{children:"Загрузка файлов"}),e.jsx("span",{children:"презентации, видео и изображения"})]}),k("upload",$a,"Загрузка файлов")]}),e.jsxs("div",{className:"sn-h-perm",children:[e.jsxs("span",{className:"sn-h-perm-text",children:[e.jsx("b",{children:"Включать микрофон без приглашения"}),e.jsx("span",{children:"иначе — только по разрешению"})]}),k("unmuteWithoutInvite",$a,"Включать микрофон без приглашения")]}),e.jsxs("div",{className:"sn-h-perm",children:[e.jsxs("span",{className:"sn-h-perm-text",children:[e.jsx("b",{children:"Чат"}),e.jsx("span",{children:"писать в общий чат эфира"})]}),k("chat",bh,"Чат")]})]}),e.jsxs("section",{children:[e.jsx("span",{className:"sn-eyebrow",children:"Зрители"}),e.jsxs("div",{className:"sn-h-perm",children:[e.jsxs("span",{className:"sn-h-perm-text",children:[e.jsx("b",{children:"Вопросы с премодерацией"}),e.jsx("span",{children:"модератор отбирает вопросы перед публикацией"})]}),b("premoderation","Вопросы с премодерацией")]}),e.jsxs("div",{className:"sn-h-perm",children:[e.jsxs("span",{className:"sn-h-perm-text",children:[e.jsx("b",{children:"Реакции"}),e.jsx("span",{children:"летят поверх плеера у зрителей"})]}),b("reactions","Реакции")]}),e.jsxs("div",{className:"sn-h-perm",children:[e.jsxs("span",{className:"sn-h-perm-text",children:[e.jsx("b",{children:"Поднятая рука"}),e.jsx("span",{children:"зритель может попроситься на сцену"})]}),b("raiseHand","Поднятая рука")]}),e.jsxs("div",{className:"sn-h-perm",children:[e.jsxs("span",{className:"sn-h-perm-text",children:[e.jsx("b",{children:"Скачивание презентаций"}),e.jsx("span",{children:"после эфира — вместе с записью"})]}),b("downloadSlides","Скачивание презентаций")]}),e.jsxs("div",{className:"sn-h-perm",children:[e.jsxs("span",{className:"sn-h-perm-text",children:[e.jsx("b",{children:"Зал ожидания"}),e.jsx("span",{children:a.waiting.ready?"новые участники ждут, пока их пустят":"новые участники ждут, пока их пустят · включится, когда зал подключат к студии"})]}),b("waitingRoom","Зал ожидания")]})]}),e.jsx(vh,{ref:r,socket:i,open:s,disabled:N})]}):t.error?e.jsx("div",{className:"sn-h-greenbox is-warn",children:t.error}):e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[0,1,2,3,4].map(y=>e.jsx(Zs,{height:40,radius:10},y))})})}function Nh({api:s,producer:n,target:t,onClose:a,handlers:i}){const l=(t==null?void 0:t.participant)||null,r=u=>u,m=Qn();let o=[],c="";if(l){const u=na(s,n,l),x=bt(Os(l));c=`${Rs(l)} · ${x?"смотрит эфир":ta[u]}`;const f=l.isLocal,g=!f&&s.assignableRoles(l).length>0;x?o=[{label:"Позвать за кулисы",description:"Зритель увидит приглашение и сам решит",icon:r(e.jsx(ps,{className:"sn-i sn-i-16"})),onSelect:()=>i.onInviteToStage(l)},{label:"Написать лично",icon:r(e.jsx(Hs,{className:"sn-i sn-i-16"})),onSelect:()=>i.onMessage(l)},{label:"Изменить роль",icon:r(e.jsx(Un,{className:"sn-i sn-i-16"})),onSelect:()=>i.onRole(l),disabled:!g},{type:"separator"},{label:"Удалить из комнаты",icon:r(e.jsx(ct,{className:"sn-i sn-i-16"})),danger:!0,onSelect:()=>i.onKick(l)}]:o=[u==="live"?{label:"Убрать из эфира",icon:r(e.jsx(gs,{className:"sn-i sn-i-16"})),onSelect:()=>void n.removeFromProgram(l),disabled:!s.perms.manageStage}:u==="preview"?{label:"Убрать из подготовки",icon:r(e.jsx(gs,{className:"sn-i sn-i-16"})),onSelect:()=>n.toggleCast(l)}:{label:"В кадр (в подготовку)",icon:r(e.jsx(ps,{className:"sn-i sn-i-16"})),onSelect:()=>n.addToPreview(l)},...u!=="live"?[{label:"Сразу в эфир",icon:r(e.jsx(ws,{className:"sn-i sn-i-16"})),onSelect:()=>void n.putOnAir(l),disabled:!s.perms.manageStage}]:[],...sr(m,l,(t==null?void 0:t.anchor)||null),f?{label:l.isMuted?"Включить микрофон":"Выключить микрофон",
112icon:r(l.isMuted?e.jsx(Ts,{className:"sn-i sn-i-16"}):e.jsx(Es,{className:"sn-i sn-i-16"})),onSelect:()=>s.toggleMic()}:l.isMuted?{label:"Попросить включить микрофон",icon:r(e.jsx(Ts,{className:"sn-i sn-i-16"})),onSelect:()=>i.onAskUnmute(l)}:{label:"Выключить микрофон",icon:r(e.jsx(Es,{className:"sn-i sn-i-16"})),onSelect:()=>i.onMute(l)},f?{label:l.isCameraOff?"Включить камеру":"Выключить камеру",icon:r(l.isCameraOff?e.jsx(Sn,{className:"sn-i sn-i-16"}):e.jsx(kn,{className:"sn-i sn-i-16"})),onSelect:()=>s.toggleCamera()}:{label:"Выключить камеру",icon:r(e.jsx(kn,{className:"sn-i sn-i-16"})),onSelect:()=>i.onCameraOff(l),disabled:l.isCameraOff},{type:"separator"},{label:"Написать лично",icon:r(e.jsx(Hs,{className:"sn-i sn-i-16"})),onSelect:()=>i.onMessage(l),disabled:f},{label:"Сигнал «Осталось 5 минут»",icon:r(e.jsx(Za,{className:"sn-i sn-i-16"})),onSelect:()=>i.onCue(l),disabled:f},{label:"Изменить роль",icon:r(e.jsx(Un,{className:"sn-i sn-i-16"})),onSelect:()=>i.onRole(l),disabled:!g},{label:"Плашка с именем",icon:r(e.jsx(Kl,{className:"sn-i sn-i-16"})),onSelect:()=>i.onLowerThirds(l)},{type:"separator"},{label:"Отправить в зрители",icon:r(e.jsx(en,{className:"sn-i sn-i-16"})),onSelect:()=>i.onToAudience(l),disabled:f},{label:"Удалить из комнаты",icon:r(e.jsx(ct,{className:"sn-i sn-i-16"})),danger:!0,onSelect:()=>i.onKick(l),disabled:f}]}return e.jsx(Cs,{open:!!t,onClose:a,anchor:(t==null?void 0:t.anchor)||null,placement:"bottom-end",width:290,header:l?e.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center",padding:"8px 10px 12px",borderBottom:"1px solid var(--sn-line)",marginBottom:4},children:[e.jsx(Ve,{name:l.name,src:l.avatarUrl,size:40}),e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:{fontWeight:600,fontSize:14,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:l.name}),e.jsx("div",{className:"sn-hint",style:{fontSize:12.5},children:c})]})]}):null,items:o})}const wh=["1 — плохо","2","3","4","5 — отлично"],kh=10;let Sh=0;const Or=()=>`q${Date.now().toString(36)}${Sh+=1}`;function Ch(){const s=typeof crypto<"u"?crypto:null;if(s&&typeof s.randomUUID=="function")return s.randomUUID();const n=new Uint8Array(16);if(s!=null&&s.getRandomValues)s.getRandomValues(n);else for(let a=0;a<16;a++)n[a]=Math.floor(Math.random()*256);n[6]=n[6]&15|64,n[8]=n[8]&63|128;const t=Array.from(n,a=>a.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}const Zn=s=>({key:Or(),question:s==="rating"?"Оцените эфир":"",options:s==="rating"?wh:["",""],correct:-1});function $h(s,n,t,a){const i=a?`Вопрос ${t+1}: `:"";if(!s.question.trim())return`${i}напишите вопрос`;if(s.question.trim().length>500)return`${i}вопрос длиннее 500 символов`;const l=s.options.map(r=>r.trim());return l.some(r=>!r)?`${i}заполните все варианты или удалите пустые`:l.length<2?`${i}нужно минимум 2 варианта`:l.some(r=>r.length>200)?`${i}вариант длиннее 200 символов`:new Set(l.map(r=>r.toLowerCase())).size!==l.length?`${i}
112варианты повторяются`:n==="quiz"&&(s.correct<0||s.correct>=l.length)?`${i}отметьте правильный ответ`:null}function Ih({draft:s,kind:n,onChange:t}){const[a,i]=d.useState(null),l=(o,c)=>t({...s,options:s.options.map((u,x)=>x===o?c.slice(0,200):u)}),r=o=>t({...s,options:s.options.filter((c,u)=>u!==o),correct:s.correct===o?-1:s.correct>o?s.correct-1:s.correct}),m=(o,c)=>{if(o===c)return;const u=[...s.options],[x]=u.splice(o,1);u.splice(c,0,x);let f=s.correct;f===o?f=c:o<f&&c>=f?f-=1:o>f&&c<=f&&(f+=1),t({...s,options:u,correct:f})};return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.options.map((o,c)=>e.jsxs("div",{className:"sn-h-opt-row",onDragOver:u=>{a!==null&&u.preventDefault()},onDrop:u=>{u.preventDefault(),a!==null&&m(a,c),i(null)},children:[e.jsx("span",{className:"sn-h-grab",draggable:!0,onDragStart:()=>i(c),onDragEnd:()=>i(null),"aria-hidden":"true",title:"Перетащите, чтобы поменять порядок",style:{color:"var(--sn-ink-3)",display:"inline-flex"},children:e.jsx(Ul,{className:"sn-i sn-i-16"})}),n==="quiz"&&e.jsx("button",{type:"button",role:"radio",className:"sn-h-correct","aria-checked":s.correct===c,"aria-label":`Правильный ответ: вариант ${c+1}`,title:"Правильный ответ",onClick:()=>t({...s,correct:c}),children:e.jsx(Re,{className:"sn-i sn-i-16"})}),e.jsx(Oe,{value:o,onChange:u=>l(c,u.target.value),placeholder:`Вариант ${c+1}`,"aria-label":`Вариант ${c+1}`,maxLength:200,style:{flex:1}}),e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":`Удалить вариант ${c+1}`,onClick:()=>r(c),disabled:s.options.length<=2,children:e.jsx(ls,{className:"sn-i sn-i-16"})})]},c)),s.options.length<kh&&e.jsx(R,{size:"sm",variant:"text",icon:e.jsx(ps,{className:"sn-i sn-i-16"}),onClick:()=>t({...s,options:[...s.options,""]}),style:{alignSelf:"flex-start",marginLeft:24},children:"Добавить вариант"})]})}function Mh({open:s,onClose:n,control:t,editing:a,onLaunched:i}
112){const l=Se(),[r,m]=d.useState("poll"),[o,c]=d.useState(""),[u,x]=d.useState([Zn("poll")]),[f,g]=d.useState("0"),[h,p]=d.useState(!0),[N,k]=d.useState("after_vote"),[b,y]=d.useState("stage"),[w,T]=d.useState(null),[q,C]=d.useState(null);d.useEffect(()=>{if(s)if(T(null),C(null),a){const O=Ll(a),z=[...a.options].sort((M,U)=>M.sortOrder-U.sortOrder);m(O),c(a.seriesTitle||""),x([{key:Or(),question:a.question,options:z.map(M=>M.text),correct:a.correctOptionId?z.findIndex(M=>M.id===a.correctOptionId):-1}]),g(a.timeLimitSeconds===30?"30":a.timeLimitSeconds===60?"60":"0"),p(a.isAnonymous),k(a.resultsVisibility==="hidden"?"hidden":a.resultsVisibility==="instant"?"instant":"after_vote"),y(a.launchOnStage===!1?"chat":"stage")}else m("poll"),c(""),x([Zn("poll")]),g("0"),p(!0),k("after_vote"),y("stage")},[s,a]);const _=O=>{O!==r&&(m(O),C(null),x(z=>{var v;if(O==="rating")return[{...Zn("rating"),question:((v=z[0])==null?void 0:v.question.trim())||"Оцените эфир"}];const M=z[0],U=M&&r!=="rating"?M.options:["",""],$={...M||Zn(O),question:r==="rating"?"":(M==null?void 0:M.question)||"",options:U,correct:-1};return O==="quiz"?[$,...z.slice(1)]:[$]}),O==="quiz"&&(g("30"),k("after_vote")),O==="rating"&&k("instant"))},K=(O,z)=>x(M=>M.map((U,$)=>$===O?z:U)),L=async O=>{const z=r==="quiz"&&u.length>1;for(let M=0;M<u.length;M++){const U=$h(u[M],r,M,z);if(U){C(U);return}}if(r==="quiz"&&z&&!o.trim()){C("Назовите викторину — название увидят зрители в таблице лидеров");return}C(null),T(O?"launch":"save");try{const M={kind:r,timeLimitSeconds:Number(f),isAnonymous:r==="quiz"?!1:h,resultsVisibility:N,showOnStage:b==="stage"},U=(v,B={})=>({...M,question:v.question,options:v.options,correctOptionIndex:r==="quiz"?v.correct:void 0,...B});let $=null;if(a){const v=await t.update(a.id,U(u[0],{seriesTitle:o.trim()||null}));if(!v.ok){C(v.error||"Не удалось сохранить");return}$=a.id}else{const v=r==="quiz"?Ch():null,B=r==="quiz"?(o.trim()||u[0].question.trim()).slice(0,200):null;for(let se=0;se<u.length;se++){const A=await t.create(U(u[se],{seriesId:v,seriesTitle:B,seriesOrder:r==="quiz"?se+1:null}));if(!A.ok||!A.poll){C(A.error||"Не удалось сохранить");return}$||($=A.poll.id)}}if(O&&$){const v=await t.publish($,{showOnStage:b==="stage"});if(!v.ok){l.error(v.error||"Сохранено, но не запустилось"),n();return}l.success(b==="stage"?"Запущено — на экране и в чате":"Запущено — в чате у зрителей"),i==null||i($)}else l.success(r==="quiz"&&u.length>1?`Викторина сохранена: ${u.length} вопроса(ов)`:"Сохранено — запустите, когда будет нужно");n()}finally{T(null)}},F=r==="quiz",S=a?"Изменить":r==="quiz"?"Новая викторина":r==="rating"?"Новая оценка":"Новый опрос";return e.jsx(Ke,{open:s,onClose:()=>w?void 0:n(),width:620,icon:r==="quiz"?e.jsx(Fa,{className:"sn-i"}):r==="rating"?e.jsx(gn,{className:"sn-i"}):e.jsx(xn,{className:"sn-i"}),iconTone:r==="quiz"?"green":r==="rating"?"amber":"blue",title:e.jsx("span",{className:"sn-display",children:S}),subtitle:"Зрители ответят в чате и на телефоне",footer:e.jsxs(e.Fragment,{children:[q?e.jsx("span",{style:{flex:1,color:"var(--sn-red)",fontSize:13},role:"alert",children:q}):e.jsx("span",{style:{flex:1}}),e.jsx(R,{variant:"quiet",size:"lg",onClick:()=>void L(!1),loading:w==="save",disabled:!!w,children:"Сохранить"}),e.jsx(R,{variant:"primary",size:"lg",icon:e.jsx(fn,{className:"sn-i sn-i-16"}),onClick:()=>void L(!0),loading:w==="launch",disabled:!!w,children:"Запустить сейчас"})]}),children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[!a&&e.jsxs("div",{className:"sn-field",children:[e.jsx("span",{className:"sn-label",children:"Тип"}),e.jsx(we,{ariaLabel:"Тип",value:r,onChange:_,options:[{value:"poll",label:"Опрос",icon:e.jsx(xn,{className:"sn-i sn-i-16"})},{value:"quiz",label:"Викторина",icon:e.jsx(Fa,{className:"sn-i sn-i-16"})},{value:"rating",label:"Оценка",icon:e.jsx(gn,{className:"sn-i sn-i-16"})}],style:{width:"100%"}})]}),F&&e.jsxs("div",{className:"sn-field",children:[e.jsx("label",{className:"sn-label",htmlFor:"sn-h-quiz-title",children:"Название викторины"}),e.jsx(Oe,{id:"sn-h-quiz-title",value:o,maxLength:200,onChange:O=>c(O.target.value),placeholder:"Например, «5 вопросов о SNICH 3.0»"})]}),u.map((O,z)=>
112{const M=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sn-field",children:[e.jsx("label",{className:"sn-label",htmlFor:`sn-h-q-${O.key}`,children:F&&u.length>1?`Вопрос ${z+1}`:"Вопрос"}),e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx(Oe,{id:`sn-h-q-${O.key}`,value:O.question,maxLength:500,onChange:U=>K(z,{...O,question:U.target.value}),placeholder:F?"Сколько зрителей вмещает эфир на тарифе «Старт»?":"Чем вы пользуетесь чаще всего?","data-autofocus":z===0?!0:void 0,style:{flex:1}}),F&&u.length>1&&!a&&e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost","aria-label":`Удалить вопрос ${z+1}`,onClick:()=>x(U=>U.filter(($,v)=>v!==z)),children:e.jsx(hn,{className:"sn-i sn-i-16"})})]})]}),r==="rating"?e.jsxs("div",{className:"sn-field",children:[e.jsx("span",{className:"sn-label",children:"Ответы"}),e.jsxs("div",{className:"sn-h-stars","aria-label":"Шкала от 1 до 5",children:[[1,2,3,4,5].map(U=>e.jsx(gn,{className:"sn-i",fill:"currentColor"},U)),e.jsx("span",{className:"sn-hint",style:{fontSize:13,alignSelf:"center"},children:"от 1 до 5"})]})]}):e.jsxs("div",{className:"sn-field",children:[e.jsx("span",{className:"sn-label",children:F?"Варианты ответа · отметьте правильный":"Варианты ответа"}),e.jsx(Ih,{draft:O,kind:r,onChange:U=>K(z,U)})]})]});return F&&u.length>1?e.jsx("div",{className:"sn-h-qblock",children:M},O.key):e.jsx(ht.Fragment,{children:M},O.key)}),F&&!a&&u.length<20&&e.jsx(R,{size:"sm",variant:"quiet",icon:e.jsx(ps,{className:"sn-i sn-i-16"}),onClick:()=>x(O=>[...O,Zn("quiz")]),style:{alignSelf:"flex-start"},children:"Ещё вопрос"}),e.jsxs("div",{style:{borderTop:"1px solid var(--sn-line)",paddingTop:8},children:[e.jsxs("div",{className:"sn-h-setrow",children:[e.jsx("span",{children:F?"Время на ответ":"Таймер"}),e.jsx(we,{size:"sm",ariaLabel:"Таймер",value:f,onChange:g,options:[{value:"0",label:"Без"},{value:"30",label:"30 сек"},{value:"60",label:"1 мин"}]})]}),e.jsxs("div",{className:"sn-h-setrow",children:[e.jsxs("span",{children:["Анонимно ",e.jsx("span",{className:"sn-hint",style:{fontWeight:400,fontSize:13},children:F?"— в викторине имена нужны для таблицы лидеров":"— имена не видны даже команде"})]}),e.jsx(Pe,{checked:F?!1:h,onChange:p,label:"Анонимно",disabled:F})]}),e.jsxs("div",{className:"sn-h-setrow",children:[e.jsx("span",{children:"Результаты зрителям"}),e.jsx(we,{size:"sm",ariaLabel:"Результаты зрителям",value:N,onChange:k,options:[{value:"instant",label:"Сразу"},{value:"after_vote",label:"После голосования"},{value:"hidden",label:"Не показывать"}]})]}),e.jsxs("div",{className:"sn-h-setrow",children:[e.jsx("span",{children:"Где"}),e.jsx(we,{size:"sm",ariaLabel:"Где",value:b,onChange:y,options:[{value:"stage",label:"На экран и в чат"},{value:"chat",label:"Только в чат"}]})]})]})]})})}function Fr(s){const n=[],t=new Map;s.forEach(i=>{if(i.status!=="archived"){if(i.seriesId){const l=t.get(i.seriesId)||[];l.push(i),t.set(i.seriesId,l);return}n.push({id:i.id,kind:Ll(i),title:i.question,polls:[i],state:i.status==="live"?"live":i.status==="closed"?"done":"ready",seriesId:null})}}),t.forEach((i,l)=>{var c,u;const r=[...i].sort((x,f)=>(x.seriesOrder??0)-(f.seriesOrder??0)),m=r.some(x=>x.status==="live"),o=r.filter(x=>x.status==="closed").length;n.push({id:`series:${l}`,kind:"quiz",title:((c=r[0])==null?void 0:c.seriesTitle)||((u=r[0])==null?void 0:u.question)||"Викторина",polls:r,state:m?"live":o===0?"ready":o===r.length?"done":"progress",seriesId:l})});const a=i=>Math.max(...i.polls.map(l=>Date.parse(l.closedAt||l.publishedAt||l.createdAt)||0));return n.sort((i,l)=>a(l)-a(i))}function Wa(s){return s.polls.find(n=>n.status==="draft"||n.status==="scheduled")||null}const Rr={poll:"Опрос",quiz:"Викторина",rating:"Оценка 1–5"};function Qt({kind:s,done:n}
112){return e.jsx("span",{className:`sn-h-poll-ico${n?" is-done":s==="quiz"?" is-quiz":s==="rating"?" is-rating":""}`,children:n?e.jsx(Re,{className:"sn-i sn-i-16"}):s==="quiz"?e.jsx(Fa,{className:"sn-i sn-i-16"}):s==="rating"?e.jsx(gn,{className:"sn-i sn-i-16"}):e.jsx(xn,{className:"sn-i sn-i-16"})})}function Dr({total:s,done:n,live:t}){return e.jsx("span",{className:"sn-h-progress","aria-hidden":"true",children:Array.from({length:s},(a,i)=>e.jsx("i",{className:i<n+(t?1:0)?"is-done":""},i))})}function Lh(s){const n=Math.max(0,Math.round(s));return`${Math.floor(n/60)}:${String(n%60).padStart(2,"0")}`}function Ah({poll:s,reveal:n}){const t=[...s.options].sort((l,r)=>l.sortOrder-r.sortOrder),a=s.results||[],i=Math.max(0,...a.map(l=>l.count));return e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:t.map(l=>{const r=a.find(u=>u.optionId===l.id),m=(r==null?void 0:r.count)??0,o=(r==null?void 0:r.percentage)??0,c=n&&s.correctOptionId===l.id;return e.jsxs("div",{className:"sn-h-bar",children:[e.jsxs("div",{className:"sn-h-bar-top",children:[e.jsxs("span",{children:[c&&e.jsx(si,{className:"sn-i sn-i-16",style:{color:"var(--sn-green)",verticalAlign:"-3px",marginRight:4}}),l.text]}),e.jsx("span",{className:"sn-mono",children:He(m)}),e.jsxs("span",{className:"sn-mono",children:[o,"%"]})]}),e.jsx("div",{className:"sn-h-track",children:e.jsx("i",{className:c?"is-correct":m>0&&m===i?"is-top":"",style:{width:`${o}%`}})})]},l.id)})})}function Ph(s){return s==="hidden"?"не показывать":s==="instant"?"сразу":s==="after_close"||s==="after_timer"?"после завершения":"после голосования"}function Ia({unit:s,onOpen:n,onRun:t,onEdit:a,onDelete:i,busy:l}){const r=mn(),m=s.polls[0],o=s.polls.find(g=>g.status==="live")||null,c=s.polls.filter(g=>g.status==="closed").length,u=(o==null?void 0:o.totalVotes)??Math.max(0,...s.polls.map(g=>g.totalVotes||0)),x=s.polls.length>1||!!s.seriesId;let f=Rr[s.kind];if(s.state==="ready"?(f+=x?` · ${s.polls.length} ${Xe(s.polls.length,"вопрос","вопроса","вопросов")}`:s.kind==="rating"?"":` · ${m.options.length} ${Xe(m.options.length,"вариант","варианта","вариантов")}`,m.timeLimitSeconds&&(f+=` · ${m.timeLimitSeconds} сек`)):s.state!=="done"&&(f+=` · ${He(u)} ${s.kind==="quiz"?Xe(u,"участник","участника","участников"):Xe(u,"голос","голоса","голосов")}`),s.state==="done"){const g=Math.max(...s.polls.map(h=>Date.parse(h.closedAt||"")||0));return e.jsx("div",{className:"sn-h-card",children:e.jsxs("div",{className:"sn-h-card-top",children:[e.jsx(Qt,{kind:s.kind,done:!0}),e.jsxs("div",{className:"sn-h-row-text",children:[e.jsx("span",{className:"sn-h-ptitle",children:s.title}),e.jsxs("span",{className:"sn-kind sn-h-kind",children:[g?`в ${Js(g)} · `:"",He(u)," ",Xe(u,"голос","голоса","голосов")]})]}),e.jsx(R,{size:"sm",variant:"text",className:"sn-h-small",onClick:n,children:"Итоги"})]})})}return e.jsxs("div",{className:"sn-h-card",children:[e.jsxs("div",{className:"sn-h-card-top",children:[e.jsx(Qt,{kind:s.kind}),e.jsxs("div",{className:"sn-h-row-text",style:{gap:4},children:[e.jsx("span",{className:"sn-h-kind",children:f}),e.jsx("span",{className:"sn-h-ptitle",children:s.title})]})]}),x&&s.state!=="ready"&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[e.jsx("span",{style:{flex:1},children:e.jsx(Dr,{total:s.polls.length,done:c,live:!!o})}),e.jsxs("span",{className:"sn-hint",style:{fontSize:12.5},children:["вопрос ",Math.min(s.polls.length,c+(o?1:0))||1," из ",s.polls.length]})]}),s.state==="ready"&&!x&&s.kind==="poll"&&e.jsx("div",{className:"sn-h-chips",children:[...m.options].sort((g,h)=>g.sortOrder-h.sortOrder).map(g=>e.jsx("span",{className:"sn-h-chip",title:g.text,children:g.text},g.id))}),e.jsx("div",{style:{display:"flex",alignItems:"center",gap:8},children:s.state==="ready"?e.jsxs(e.Fragment,{children:[e.jsx(R,{size:"sm",variant:"primary",icon:e.jsx(fn,{className:"sn-i sn-i-16"}),onClick:t,loading:l,children:"Запустить"}),!x&&e.jsx(R,{size:"sm",variant:"text",onClick:a,children:"Изменить"}),e.jsx("span",{style:{flex:1}}),e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-h-dots","aria-label":"Ещё",onClick:r.toggle,children:e.jsx(zs,{className:"sn-i sn-i-16"})}),e.jsx(Cs,{open:r.open,onClose:r.close,anchor:r.anchor,width:220,items:[{label:
112x?"Удалить викторину":"Удалить",icon:e.jsx(hn,{className:"sn-i sn-i-16"}),danger:!0,onSelect:i}]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"sn-tag sn-tag-green",children:[e.jsx("span",{className:"sn-live-dot",style:{background:"currentColor"}}),s.state==="live"?"идёт":"между вопросами"]}),e.jsx("span",{style:{flex:1}}),e.jsx(R,{size:"sm",variant:"quiet",className:"sn-h-small",onClick:n,children:"Открыть"})]})})]})}function Eh({api:s,rt:n,control:t,focus:a,onFocus:i,onNew:l,onEdit:r,onRun:m,runningId:o}){const c=Se(),[u,x]=d.useState(null),[f,g]=d.useState(null),h=d.useMemo(()=>Fr(t.polls),[t.polls]),p=n.audience.viewers||s.viewerCount||0,N=s.perms.manageStage||s.perms.moderate,k=async(C,_,K)=>{g(C);try{const L=await _();return L.ok?K&&c.success(K):c.error(L.error||"Не получилось"),L.ok}finally{g(null)}},b=a&&h.find(C=>C.id===a||C.polls.some(_=>_.id===a))||null;d.useEffect(()=>{if(!a||!t.ready||b)return;const C=window.setTimeout(()=>i(null),3e3);return()=>window.clearTimeout(C)},[a,b,t.ready,i]);const y=e.jsx(yn,{open:!!u,onClose:()=>x(null),title:u&&u.polls.length>1?`Удалить викторину «${u.title}»?`:"Удалить опрос?",description:"Удаляются вопросы и ответы — вернуть их не получится.",confirmLabel:"Удалить",onConfirm:async()=>{if(u){for(const C of u.polls)if(!await k(`del:${C.id}`,()=>t.remove(C.id)))break;c.success("Удалено"),x(null)}}});if(!t.ready)return t.error?e.jsxs("div",{className:"sn-h-empty",children:[t.error," ",e.jsx(R,{size:"sm",variant:"text",onClick:()=>void t.refresh(),children:"Повторить"})]}):e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsx(Zs,{height:96,radius:14}),e.jsx(Zs,{height:120,radius:14})]});if(b)return e.jsxs(e.Fragment,{children:[e.jsx(zh,{api:s,control:t,unit:b,others:h.filter(C=>C.id!==b.id&&C.state!=="done"),viewers:p,acting:f,act:k,onBack:()=>i(null),onOpen:i,onRun:m,canManage:N,runningId:o}),y]});const w=h.filter(C=>C.state==="live"||C.state==="progress"),T=h.filter(C=>C.state==="ready"),q=h.filter(C=>C.state==="done");return e.jsxs(e.Fragment,{children:[!ni(s,"polls")&&e.jsxs($o,{block:!0,icon:e.jsx(xn,{className:"sn-i sn-i-16"}),testId:"polls-off",children:[ti.polls," — зрители их не увидят. Включите опросы в настройках эфира, чтобы запускать."]}),!h.length&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:10,padding:"32px 8px",textAlign:"center"},children:[e.jsx(Qt,{kind:"poll"}),e.jsx("b",{style:{fontSize:15},children:"Опросов пока нет"}),e.jsx("span",{className:"sn-hint",style:{fontSize:13.5},children:"Подготовьте опрос, викторину или оценку заранее — запуск в эфире в одно нажатие"}),N&&e.jsx(R,{variant:"primary",size:"sm",onClick:l,children:"Новый опрос"})]}),w.length>0&&e.jsxs("section",{className:"sn-h-sec",style:{gap:8},children:[e.jsxs("span",{className:"sn-eyebrow",style:{color:"var(--sn-green)"},children:["Идёт · ",w.length]}),w.map(C=>e.jsx(Ia,{unit:C,busy:o===C.id,onOpen:()=>i(C.id),onRun:()=>void m(C),onEdit:()=>r(C.polls[0]),onDelete:()=>x(C)},C.id))]}),T.length>0&&e.jsxs("section",{className:"sn-h-sec",style:{gap:8},children:[e.jsxs("span",{className:"sn-eyebrow",children:["Готовы к запуску · ",T.length]}),T.map(C=>e.jsx(Ia,{unit:C,busy:o===C.id,onOpen:()=>i(C.id),onRun:()=>void m(C),onEdit:()=>r(C.polls[0]),onDelete:()=>x(C)},C.id))]}),q.length>0&&e.jsxs("section",{className:"sn-h-sec",style:{gap:8},children:[e.jsxs("span",{className:"sn-eyebrow",children:["Завершённые · ",q.length]}),q.map(C=>e.jsx(Ia,{unit:C,busy:!1,onOpen:()=>i(C.id),onRun:()=>void m(C),onEdit:()=>r(C.polls[0]),onDelete:()=>x(C)},C.id))]}),y]})}function zh({api:s,control:n,unit:t,others:a,viewers:i,acting:l,act:r,onBack:m,onOpen:o,onRun:c,canManage:u,runningId:x}){var z;const f=t.polls.length>1||!!t.seriesId,g=t.polls.find(M=>M.status==="live")||null,h=t.polls.filter(M=>M.status==="closed"),p=g||h[h.length-1]||t.polls[0],N=Wa(t),k=t.polls.indexOf(p)+1,b=p.status==="live",y=p.showOnStage,[w,T]=d.useState(null),q=!!t.seriesId&&n.leadersOnStage===t.seriesId,C=t.polls.map(M=>`${M.id}:${M.status}:${M.totalVotes??0}`).join("|"),_=d.useCallback(async()=>
112{if(!t.seriesId)return;const M=await n.leaders(t.seriesId,5);M.ok&&M.series&&T({series:M.series,rows:M.leaders||[],onStage:!!M.onStage})},[n,t.seriesId]);d.useEffect(()=>{_()},[_,C]);const K=(z=p.timer)==null?void 0:z.remainingSeconds,L=p.totalVotes||0,F=(()=>{var U;if(t.kind!=="quiz"||!p.correctOptionId||!L)return null;const M=(U=p.results)==null?void 0:U.find($=>$.optionId===p.correctOptionId);return M?M.percentage:0})(),S=y?"на экране и в чате":"в чате",O=f?e.jsxs("span",{className:"sn-eyebrow",style:{whiteSpace:"nowrap"},children:["Викторина · вопрос ",k," из ",t.polls.length]}):b?e.jsxs("span",{className:"sn-tag sn-tag-live",children:[e.jsx("span",{className:"sn-live-dot"}),t.kind==="rating"?"Идёт оценка":"Идёт опрос"]}):e.jsxs("span",{className:"sn-tag sn-tag-gray",children:["Завершён",p.closedAt?` в ${Js(p.closedAt)}`:""]});return e.jsxs("div",{className:"sn-h-fill",children:[e.jsxs("div",{className:"sn-h-scroll",style:{gap:16},children:[e.jsx(R,{size:"sm",variant:"text",icon:e.jsx(Ol,{className:"sn-i sn-i-16"}),onClick:m,style:{alignSelf:"flex-start",height:28,marginBottom:-6},children:"Все опросы"}),e.jsxs("section",{className:`sn-h-live${b?"":" is-closed"}`,"aria-label":p.question,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[O,f&&e.jsx("span",{style:{width:56,flex:"none"},children:e.jsx(Dr,{total:t.polls.length,done:h.length,live:!!g})}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5,flex:1},children:!f&&b?S:""}),b&&typeof K=="number"&&e.jsxs("span",{className:"sn-h-timer",children:[e.jsx(Ks,{className:"sn-i sn-i-16"}),e.jsx("span",{className:"sn-mono",children:Lh(K)})]})]}),e.jsx("div",{style:{fontSize:16,fontWeight:600,lineHeight:1.3},children:p.question}),e.jsx(Ah,{poll:p,reveal:t.kind==="quiz"}),e.jsxs("div",{className:"sn-hint",style:{display:"flex",alignItems:"center",gap:8,fontSize:13,borderTop:"1px solid rgba(20,22,25,.08)",paddingTop:10},children:[e.jsx(nn,{className:"sn-i sn-i-16"}),e.jsxs("span",{style:{flex:1},children:[t.kind==="quiz"?"Ответили":"Проголосовали"," ",e.jsx("b",{className:"sn-mono",style:{color:"var(--sn-ink)"},children:He(L)}),i>0?e.jsxs(e.Fragment,{children:[" из ",e.jsx("span",{className:"sn-mono",children:He(i)})]}):null,F!==null?e.jsxs(e.Fragment,{children:[" · верно ",e.jsxs("span",{className:"sn-mono",style:{color:"var(--sn-green)"},children:[F,"%"]})]}):null,!b&&p.timeLimitSeconds?" · время вышло":""]}),i>0&&e.jsxs("span",{className:"sn-mono",children:[Math.min(100,Math.round(L/i*100)),"%"]})]})]}),t.seriesId&&e.jsxs("section",{className:"sn-h-sec",style:{gap:4},children:[e.jsxs("div",{className:"sn-h-sec-head",children:[e.jsxs("span",{className:"sn-eyebrow",children:["Лидеры после ",h.length," ",Xe(h.length,"вопроса","вопросов","вопросов")]}),e.jsx("span",{style:{flex:1}}),q&&e.jsx("span",{className:"sn-tag sn-tag-live",children:"на экране"}),u&&w&&w.rows.length>0&&e.jsx(R,{size:"sm",variant:"text",className:"sn-h-small",loading:l==="leaders-head",onClick:()=>void r("leaders-head",()=>q?n.hideLeaders():n.showLeaders(t.seriesId),q?"Лидеры убраны с экрана":"Лидеры на экране"),children:q?"Убрать":"На экран"})]}),!w&&e.jsx(Zs,{height:40,radius:10}),w&&!w.rows.length&&e.jsx("div",{className:"sn-h-empty",children:"Пока никто не ответил верно"}),w==null?void 0:w.rows.map(M=>e.jsxs("div",{className:`sn-h-leader${M.place===1?" is-first":""}`,children:[e.jsx("span",{className:"sn-mono",style:{width:16},children:M.place}),e.jsx(Ve,{name:M.name,size:28}),e.jsx("b",{children:M.name}),e.jsx("span",{className:"sn-mono",style:{fontWeight:600},children:He(M.points)})]},`${M.place}-${M.name}`))]}),f&&N&&e.jsxs("section",{className:"sn-h-sec",style:{gap:6},children:[e.jsxs("span",{className:"sn-eyebrow",children:["Дальше · вопрос ",t.polls.indexOf(N)+1," из ",t.polls.length]}),e.jsxs("div",{className:"sn-h-card",style:{borderStyle:"dashed"},children:[e.jsx("span",{className:"sn-h-ptitle",children:N.question}),e.jsxs("span",{className:"sn-h-kind",children:[N.options.length," ",Xe(N.options.length,"вариант","варианта","вариантов"),N.timeLimitSeconds?` · ${N.timeLimitSeconds} сек на ответ`:""]})]})]}),!f&&e.jsxs("section",{className:"sn-h-sec",style:{gap:0},children:[e.jsx("span",{className:"sn-eyebrow",style:{marginBottom:4},children:"Настройки"}),e.jsxs("div",{className:"sn-h-kv",children:[e.jsx("span",{children:"Результаты зрителям"}),e.jsx("span",{children:Ph(p.resultsVisibility)})]}),e.jsxs("div",{className:"sn-h-kv",children:[e.jsx("span",{children:"Анонимно"}),e.jsx("span",{children:p.isAnonymous?"да":"нет"})]}),e.jsxs("div",{className:"sn-h-kv",children:[e.jsx("span",{children:"Таймер"}),e.jsx("span",{children:p.timeLimitSeconds?`${p.timeLimitSeconds} сек`:"без таймера"})]})]}),a.length>0&&e.jsxs("section",{className:"sn-h-sec",style:{gap:4},children:[e.jsxs("span",{className:"sn-eyebrow",children:["Ещё в списке · ",a.length]}),a.slice(0,5).map(M=>{const U=M.polls.find(v=>v.status==="live"),$=M.polls.filter(v=>v.status==="closed").length;return e.jsxs("div",{className:"sn-h-row",children:[e.jsx(Qt,{kind:M.kind}),e.jsxs("span",{className:"sn-h-row-text",children:[e.jsx("span",{className:"sn-h-name",children:M.title}),e.jsx("span",{className:"sn-h-sub",children:M.state==="ready"?`${Rr[M.kind]} · готов к запуску`:M.polls.length>1?`${U?"идёт":"между вопросами"} · вопрос ${Math.max(1,$+(U?1:0))} из ${M.polls.length}`:"идёт"})]}),M.state==="ready"&&u?e.jsx(R,{size:"sm",variant:"quiet",className:"sn-h-small",loading:x===M.id,onClick:()=>void c(M),children:"Запустить"}):e.jsx(R,{size:"sm",variant:"quiet",className:"sn-h-small",onClick:()=>o(M.id),children:"Открыть"})]},M.id)})]})]}),u&&e.jsx("div",{className:"sn-h-foot",children:b?e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"quiet",loading:l==="stage",onClick:()=>void r("stage",()=>y?n.hide(p.id):n.show(p.id),y?"Убрано с экрана — голосование продолжается в чате":"Опрос на экране"),children:y?"Убрать с экрана":"Показать на экране"}),e.jsx(R,{variant:"primary",loading:l==="close",onClick:()=>
112void r("close",()=>n.close(p.id),f?"Вопрос завершён":"Опрос завершён"),children:f?"Завершить вопрос":t.kind==="rating"?"Завершить оценку":"Завершить опрос"})]}):t.seriesId?e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"quiet",loading:l==="leaders",onClick:()=>void r("leaders",()=>q?n.hideLeaders():y?n.hide(p.id):n.showLeaders(t.seriesId),q||y?"Убрано с экрана":"Лидеры на экране"),children:q||y?"Убрать с экрана":"Лидеры на экран"}),N?e.jsx(R,{variant:"primary",loading:x===t.id,onClick:()=>void c(t),children:"Следующий вопрос"}):e.jsx(R,{variant:"quiet",onClick:m,children:"К списку"})]}):e.jsxs(e.Fragment,{children:[e.jsx(R,{variant:"quiet",loading:l==="stage",onClick:()=>void r("stage",()=>y?n.hide(p.id):n.show(p.id),y?"Итоги убраны с экрана":"Итоги на экране"),children:y?"Убрать с экрана":"Итоги на экран"}),e.jsx(R,{variant:"quiet",loading:l==="reopen",onClick:()=>void r("reopen",()=>n.reopen(p.id),"Голосование снова открыто"),children:"Открыть снова"})]})})]})}const Ma={votes:"По голосам",new:"Сначала новые",old:"Сначала старые"};function La(s,n){const t=a=>Date.parse(a.createdAt)||0;return[...s].sort((a,i)=>n==="votes"?i.votes-a.votes||t(a)-t(i):n==="new"?t(i)-t(a):t(a)-t(i))}
112function Th({rt:s,sort:n,onSort:t,canModerate:a}){const i=Se(),l=mn(),r=mn(),m=async(c,u)=>{const x=await s.qna.updateSettings(c);x.ok?i.success(u):i.error(x.error||"Не удалось сохранить")},o=s.qna.settings;return e.jsxs(e.Fragment,{children:[e.jsx(R,{size:"sm",variant:"text",onClick:l.toggle,iconRight:e.jsx(Gn,{className:"sn-i sn-i-16"}),style:{height:30,fontSize:13},"aria-haspopup":"menu",children:Ma[n]}),e.jsx(Cs,{open:l.open,onClose:l.close,anchor:l.anchor,width:220,items:Object.keys(Ma).map(c=>({label:Ma[c],checked:c===n,onSelect:()=>t(c)}))}),a&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":"Настройки вопросов",onClick:r.toggle,children:e.jsx(Yo,{className:"sn-i sn-i-16"})}),e.jsx(xt,{open:r.open,onClose:r.close,anchor:r.anchor,placement:"bottom-end",width:320,children:e.jsxs("div",{style:{padding:"10px 12px 12px",display:"flex",flexDirection:"column",gap:14},children:[e.jsx("span",{className:"sn-eyebrow",children:"Вопросы зрителей"}),e.jsx(Fn,{title:"Принимать вопросы",description:"Выключите — кнопка «Задать вопрос» пропадёт у зрителей",checked:o.enabled,onChange:c=>void m({enabled:c},c?"Вопросы снова принимаются":"Приём вопросов выключен")}),e.jsx(Fn,{title:"Премодерация",description:"Зрители видят вопрос после того, как его отберут",checked:o.requireApproval,onChange:c=>void m({requireApproval:c},c?"Премодерация включена":"Премодерация выключена")}),e.jsx(Fn,{title:"Анонимные вопросы",description:"Зритель может скрыть своё имя",checked:o.allowAnonymous,onChange:c=>void m({allowAnonymous:c},c?"Анонимные вопросы разрешены":"Анонимные вопросы выключены")})]})})]})]})}function zt({question:s,next:n,tag:t,actions:a,drag:i,busy:l}){const r=mn(),m=s.isAnonymous?"Аноним":s.authorName;return e.jsxs("article",{className:`sn-h-q${n?" is-next":""}${s.status==="hidden"?" is-hidden":""}${i!=null&&i.dragging?" is-dragging":""}${i!=null&&i.over?" is-drop":""}`,draggable:!!i,onDragStart:i==null?void 0:i.onDragStart,onDragOver:i==null?void 0:i.onDragOver,onDrop:i==null?void 0:i.onDrop,onDragEnd:i==null?void 0:i.onDragEnd,"aria-label":s.text,children:[e.jsxs("div",{className:"sn-h-q-top",children:[e.jsxs("span",{className:"sn-h-votes",title:`Голосов: ${s.votes}`,children:[e.jsx("span",{children:"▲"}),e.jsx("span",{className:"sn-mono",children:s.votes})]}),e.jsxs("div",{className:"sn-h-q-body",children:[n&&e.jsx("span",{className:"sn-eyebrow sn-h-eb-prev",children:"Следующий"}),t,e.jsx("p",{className:"sn-h-q-text",children:s.text}),e.jsxs("span",{className:"sn-h-q-meta",children:[e.jsx(Ve,{name:m,size:18}),e.jsx("span",{className:"sn-h-author",children:m}),e.jsx("span",{className:"sn-mono",children:Js(s.createdAt)})]})]}),(i||a.menu&&a.menu.length>0)&&e.jsxs("span",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:2,marginRight:-4,marginTop:-4},children:[a.menu&&a.menu.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-h-dots","aria-label":"Ещё действия с вопросом",onClick:r.toggle,children:e.jsx(zs,{className:"sn-i sn-i-16"})}),e.jsx(Cs,{open:r.open,onClose:r.close,anchor:r.anchor,width:250,items:a.menu})]}),i&&e.jsx("span",{className:"sn-h-grab","aria-hidden":"true",title:"Перетащите, чтобы поменять порядок",children:e.jsx(Ul,{className:"sn-i sn-i-16",style:{color:"var(--sn-ink-3)"}})})]})]}),e.jsxs("div",{className:"sn-h-q-acts",children:[a.onAir&&e.jsx(R,{size:"sm",variant:n?"primary":"soft",className:"sn-h-small",icon:e.jsx(ql,{className:"sn-i sn-i-16"}),onClick:a.onAir,disabled:l,children:"На экран"}),a.select&&e.jsx(R,{size:"sm",variant:"soft",className:"sn-h-small",icon:e.jsx(gn,{className:"sn-i sn-i-16"}),onClick:a.select,children:"Отобрать"}),a.toHost&&e.jsx(R,{size:"sm",variant:"quiet",className:"sn-h-small",icon:e.jsx(sa,{className:"sn-i sn-i-16"}),onClick:a.toHost,title:"Показать вопрос ведущему — у него на экране",children:s.sentToHostAt?"Отправлен":"Ведущей"}),e.jsx("span",{style:{flex:1}}),a.answered&&e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-h-dots","aria-label":"Отметить отвеченным",title:"Отметить отвеченным",onClick:a.answered,children:e.jsx(si,{className:"sn-i sn-i-16"})})]})]})}function Oh({api:s,producer:n,rt:t,tab:a,onTab:i,sort:l,control:r}){var F;const m=Se(),o=ts(1e3),c=t.qna,[u,x]=d.useState(null),[f,g]=d.useState(null),[h,p]=d.useState(!1),N=c.canModerate||s.perms.moderate||s.perms.manageStage,k=s.perms.manageStage,b=async(S,O)=>{const z=await S;z.ok?O&&m.success(O):m.error(z.error||"Не получилось")},y=c.queue,w=d.useMemo(()=>La(c.questions.filter(S=>S.status==="new"||S.status==="selected"||S.status==="on_air"),l),[c.questions,l]),T=d.useMemo(()=>{const S=c.answered;return l==="votes"?La(S,"votes"):[...S].sort((O,z)=>{const M=U=>Date.parse(U.answeredAt||U.onAirAt||U.createdAt)||0;return l==="old"?M(O)-M(z):M(z)-M(O)})},[c.answered,l]),q=s.participants.find(S=>!S.isLocal&&Os(S)==="co_host"),C=(S,O)=>{const z=y.map($=>
112$.id),M=z.indexOf(S),U=M+O;M<0||U<0||U>=z.length||(z.splice(M,1),z.splice(U,0,S),b(c.reorder(z)))},_=S=>{if(!u||u===S)return;const O=y.map(M=>M.id).filter(M=>M!==u),z=O.indexOf(S);O.splice(z<0?O.length:z,0,u),b(c.reorder(O),"Порядок сохранён")},K=c.onAir,L=((F=n.programScene)==null?void 0:F.name)||s.program.name;return e.jsxs(e.Fragment,{children:[K&&e.jsxs("section",{className:"sn-h-onair","aria-label":"Вопрос на экране",children:[e.jsxs("div",{className:"sn-h-onair-top",children:[e.jsxs("span",{className:"sn-tag sn-tag-live",children:[e.jsx("span",{className:"sn-live-dot"}),"На экране"]}),e.jsx("span",{className:"sn-hint",style:{fontSize:12.5,flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:L?`поверх сцены «${L}»`:"в эфире"}),e.jsxs("span",{className:"sn-h-timer",children:[e.jsx(Ks,{className:"sn-i sn-i-16"}),e.jsx("span",{className:"sn-mono",children:Oc(K.onAirAt,o)})]})]}),e.jsx("p",{className:"sn-h-onair-text",children:K.text}),e.jsxs("span",{className:"sn-h-q-meta",children:[e.jsx(Ve,{name:K.isAnonymous?"Аноним":K.authorName,size:20}),e.jsx("span",{className:"sn-h-author",children:K.isAnonymous?"Аноним":K.authorName}),e.jsxs("span",{style:{color:"var(--sn-blue-ink)"},children:["▲ ",e.jsx("span",{className:"sn-mono",children:K.votes})]}),e.jsx("span",{className:"sn-mono",children:Js(K.createdAt)})]}),k&&e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx(R,{size:"sm",variant:"quiet",className:"sn-h-red-btn",icon:e.jsx(ls,{className:"sn-i sn-i-16"}),onClick:()=>void r.remove(),disabled:r.busy,style:{flex:1},children:"Убрать с экрана"}),e.jsx(R,{size:"sm",variant:"quiet",iconRight:e.jsx(Xs,{className:"sn-i sn-i-16"}),onClick:r.next,disabled:r.busy||!y.length,style:{flex:1},children:"Следующий"})]})]}),e.jsx(we,{className:"sn-h-seg",ariaLabel:"Вопросы",value:a,onChange:i,options:[{value:"queue",label:e.jsxs(e.Fragment,{children:["Отобранные ",e.jsx("span",{className:"sn-mono",children:y.length})]})},{value:"all",label:e.jsxs(e.Fragment,{children:["Все ",e.jsx("span",{className:"sn-mono",children:w.length})]})},{value:"shown",label:e.jsxs(e.Fragment,{children:["На экране были ",e.jsx("span",{className:"sn-mono",children:T.length})]})}],style:{flex:"none"}}),!c.settings.enabled&&e.jsxs("p",{className:"sn-h-note",children:[e.jsx(As,{className:"sn-i sn-i-16"}),e.jsx("span",{children:"Приём вопросов выключен — включите его в настройках вопросов"})]}),a==="queue"&&e.jsxs(e.Fragment,{children:[q?e.jsxs("p",{className:"sn-h-note",children:[e.jsx(Ve,{name:q.name,src:q.avatarUrl,size:28}),e.jsxs("span",{children:["Модератор ",e.jsx("b",{children:q.name})," отбирает вопросы — здесь только готовые к эфиру"]})]}):y.length>1?e.jsx("p",{className:"sn-h-hint",children:"Порядок выхода — перетащите карточку или нажмите Q, чтобы вывести следующий"}):null,y.map((S,O)=>e.jsx(zt,{question:S,next:O===0,busy:r.busy,drag:N?{onDragStart:z=>{z.dataTransfer.effectAllowed="move",x(S.id)},onDragOver:z=>{u&&(z.preventDefault(),f!==S.id&&g(S.id))},onDrop:z=>{z.preventDefault(),_(S.id),x(null),g(null)},onDragEnd:()=>{x(null),g(null)},dragging:u===S.id,over:f===S.id&&u!==S.id}:void 0,actions:{onAir:k?()=>void r.put(S.id):void 0,toHost:N?()=>void b(c.sendToHost(S.id),"Вопрос у ведущего на экране"):void 0,answered:N?()=>void b(c.markAnswered(S.id),"Отмечен отвеченным"):void 0,menu:N?[{label:"Выше",icon:e.jsx(li,{className:"sn-i sn-i-16"}),onSelect:()=>C(S.id,-1),disabled:O===0},{label:"Ниже",icon:e.jsx(ri,{className:"sn-i sn-i-16"}),onSelect:()=>C(S.id,1),disabled:O===y.length-1},{label:"Упорядочить все по голосам",icon:e.jsx(gn,{className:"sn-i sn-i-16"}),onSelect:()=>void b(c.reorder(La(y,"votes").map(z=>z.id)),"Отобранные — по голосам")},{type:"separator"},{label:"Убрать из отобранных",icon:e.jsx(zn,{className:"sn-i sn-i-16"}),onSelect:()=>void b(c.unselect(S.id))},{label:"Скрыть",icon:e.jsx(As,{className:"sn-i sn-i-16"}),danger:!0,onSelect:()=>void b(c.hide(S.id),"Вопрос скрыт")}]:void 0}},S.id)),!y.length&&e.jsx("div",{className:"sn-h-empty",style:{lineHeight:1.45},children:c.incoming.length?`Новых вопросов: ${c.incoming.length}. Отберите лучшие во вкладке «Все» — они выстроятся здесь по порядку выхода.`:"Пока нет отобранных вопросов. Зрители задают их на странице эфира."})]}),a==="all"&&e.jsxs(e.Fragment,{children:[c.settings.requireApproval&&e.jsxs("p",{className:"sn-h-hint",children:[e.jsx(gs,{className:"sn-i sn-i-16"})," Премодерация: зрители видят вопрос, когда его отберут"]}),w.map(S=>e.jsx(zt,{question:S,busy:r.busy,tag:S.status==="selected"?e.jsxs("span",{className:"sn-tag sn-tag-blue sn-h-role",style:{alignSelf:"flex-start"},children:["отобран · ",S.queueOrder??""]}):S.status==="on_air"?e.jsx("span",{className:"sn-tag sn-tag-live sn-h-role",style:{alignSelf:"flex-start"},children:"на экране"}):null,actions:{select:N&&S.status==="new"?()=>void b(c.select(S.id),"Вопрос отобран"):void 0,onAir:k&&S.status!=="on_air"?()=>void r.put(S.id):void 0,answered:N&&S.status!=="on_air"?()=>void b(c.markAnswered(S.id),"Отмечен отвеченным"):void 0,menu:N?[...S.status==="selected"?[{label:"Убрать из отобранных",icon:e.jsx(zn,{className:"sn-i sn-i-16"}),onSelect:()=>void b(c.unselect(S.id))}]:[],{label:"Ведущей",icon:e.jsx(sa,{className:"sn-i sn-i-16"}),onSelect:()=>
112void b(c.sendToHost(S.id),"Вопрос у ведущего на экране")},{label:"Скрыть",icon:e.jsx(As,{className:"sn-i sn-i-16"}),danger:!0,onSelect:()=>void b(c.hide(S.id),"Вопрос скрыт"),disabled:S.status==="on_air"}]:void 0}},S.id)),!w.length&&e.jsx("div",{className:"sn-h-empty",children:"Вопросов пока нет"}),c.hidden.length>0&&N&&e.jsxs("section",{className:"sn-h-sec",children:[e.jsxs("button",{type:"button",className:"sn-h-viewers",onClick:()=>p(S=>!S),"aria-expanded":h,children:[e.jsx(As,{className:"sn-i sn-i-16"}),e.jsxs("span",{className:"sn-eyebrow",style:{flex:1},children:["Скрытые · ",c.hidden.length]}),e.jsx(Gn,{className:"sn-i sn-i-16",style:{transform:h?"rotate(180deg)":void 0}})]}),h&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8,paddingTop:8},children:c.hidden.map(S=>e.jsx(zt,{question:S,actions:{menu:[{label:"Вернуть",icon:e.jsx(zn,{className:"sn-i sn-i-16"}),onSelect:()=>void b(c.restore(S.id),"Вопрос возвращён")}]}},S.id))})]})]}),a==="shown"&&e.jsxs(e.Fragment,{children:[T.map(S=>e.jsx(zt,{question:S,busy:r.busy,tag:e.jsx("span",{className:"sn-hint",style:{fontSize:12}
112,children:S.onAirAt?`был на экране в ${Js(S.onAirAt)}`:`отвечен${S.answeredAt?` в ${Js(S.answeredAt)}`:""}`}),actions:{onAir:k?()=>void r.put(S.id):void 0,menu:N?[{label:"Вернуть в отобранные",icon:e.jsx(zn,{className:"sn-i sn-i-16"}),onSelect:()=>void b(c.select(S.id),"Вопрос снова в отобранных")},{label:"Скрыть",icon:e.jsx(As,{className:"sn-i sn-i-16"}),danger:!0,onSelect:()=>void b(c.hide(S.id),"Вопрос скрыт")}]:void 0}},S.id)),!T.length&&e.jsx("div",{className:"sn-h-empty",children:"Здесь появятся вопросы, которые уже были на экране или отвечены"})]})]})}const ml=[{value:"streamer",label:"Продюсер",description:"Эфир, сцены, площадки и все права в комнате",icon:e.jsx(_l,{className:"sn-i sn-i-16"})},{value:"host",label:"Ведущий",description:"В эфире, видит сценарий и вопросы, просит вывести вопрос",icon:e.jsx(gn,{className:"sn-i sn-i-16"})},{value:"co_host",label:"Модератор",description:"Зал ожидания, вопросы и чат — в кадр не выходит",icon:e.jsx(ii,{className:"sn-i sn-i-16"})},{value:"speaker",label:"Спикер",description:"Выступает, видит свои заметки, вопросы и сигналы продюсера",icon:e.jsx(Ts,{className:"sn-i sn-i-16"})},{value:"guest",label:"Гость",description:"Выходит на сцену по приглашению, на одно выступление",icon:e.jsx(Is,{className:"sn-i sn-i-16"})},{value:"viewer",label:"Зритель",description:"Только смотрит эфир — без доступа к студии",icon:e.jsx(gs,{className:"sn-i sn-i-16"})}];function Fh({api:s,producer:n,participant:t,onClose:a}){const i=Se(),[l,r]=d.useState("speaker"),[m,o]=d.useState(!1),c=t?Os(t):"";if(d.useEffect(()=>{t&&(r(c||"speaker"),o(!1))},[t,c]),!t)return null;const u=new Set(s.assignableRoles(t)),x=na(s,n,t),f=bt(c)?"смотрит эфир":`сейчас ${ta[x]}`,g=Fc(t.name),h=async()=>{var p;o(!0);try{const N=s.changeRole?await s.changeRole(t.id,l):(s.setRole(t.id,l),{ok:!0,error:void 0});if(!N.ok){i.error(N.error||"Не удалось сменить роль");return}const k=((p=ml.find(b=>b.value===l))==null?void 0:p.label)||hi[l]||l;i.success(`${t.name}: ${k.toLowerCase()}`),a()}finally{o(!1)}};return e.jsx(Ke,{open:!!t,onClose:()=>m?void 0:a(),width:580,icon:e.jsx(Ve,{name:t.name,src:t.avatarUrl,size:44}),iconTone:"gray",title:e.jsxs("span",{className:"sn-display",children:["Роль: ",t.name]}),subtitle:[t.headline,f].filter(Boolean).join(" · "),footer:e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"sn-hint",style:{flex:1,fontSize:13},children:[g," получит новую роль сразу — переподключаться не нужно"]}),e.jsx(R,{variant:"quiet",onClick:a,disabled:m,children:"Отмена"}),e.jsx(R,{variant:"primary",onClick:h,loading:m,disabled:l===c,children:"Сохранить роль"})]}),children:e.jsx("div",{role:"radiogroup","aria-label":"Роль в комнате",style:{display:"flex",flexDirection:"column",gap:8},children:ml.map(p=>{const N=!u.has(p.value)&&p.value!==c,k=l===p.value;return e.jsxs("button",{type:"button",role:"radio","aria-checked":k,disabled:N,className:"sn-h-role-opt",onClick:()=>r(p.value),title:N?"Эту роль вы назначить не можете":void 0,children:[e.jsx("span",{className:"sn-h-role-ico",children:p.icon}),e.jsxs("span",{style:{flex:1,minWidth:0},children:[e.jsxs("span",{style:{display:"flex",alignItems:"center",gap:8,fontWeight:600,fontSize:15},children:[p.label,p.value===c&&e.jsx("span",{className:"sn-tag sn-tag-blue sn-h-role",children:"сейчас"})]}),e.jsx("span",{className:"sn-hint",style:{display:"block",fontSize:13,marginTop:2},children:p.description})]}),e.jsx("span",{className:"sn-radio","aria-hidden":"true","data-checked":k?"true":void 0})]},p.value)})})})}const Rh={x:3,y:60,w:70,h:25},Dh={x:5,y:62,w:90,h:14};function hl(s,n,t){return{id:`${s}-qna`,type:"question",...t,zIndex:60,text:n.text,eyebrow:wo,caption:n.authorName,badge:n.votes>0?`▲ ${n.votes}`:void 0,radius:20}}function qh(s,n,t){const a=n.programScene;if(!a)return null;const i=ks(a,{participants:s.participants,personKeyOf:s.personKeyOf,stageIdOf:s.stageIdOf,previewCast:[],programIds:n.programIds,question:t,logoUrl:s.brand.logo}),l=i.slots.some(r=>r.kind==="question");return!t||l?i:{...i,customLayout:[...i.customLayout,hl(a.id,t,Rh)],customLayoutVertical:[...i.customLayoutVertical,hl(a.id,t,Dh)],question:t}}function _h(s,n){const t=n.programScene;return t?t.template==="question"||t.slots.some(a=>a.kind==="question"):!1}async function Uh(s,n,t){if(!s.perms.manageStage)return{ok:!1,error:"Выводить на экран может продюсер"};const a=qh(s,n,t);
112if(!a)return{ok:!1,error:"В эфире нет сцены студии — выведите сцену, и вопрос появится поверх неё"};const i=n.wantedTicker;i&&await s.ensureBanner(i);const l=Qa(a,"fade",(i==null?void 0:i.id)??null);l.brandPatch={showNames:a.brandPatch.showNames!==!1&&n.prefs.names,showHeadlines:a.brandPatch.showHeadlines!==!1&&n.prefs.names,showLogo:a.brandPatch.showLogo!==!1&&n.prefs.logo};const r=await s.take(l);return r.success?{ok:!0,revision:r.revision}:{ok:!1,error:r.error||"Не удалось обновить эфир"}}function qr(s){return s?{id:s.id,text:s.text,authorName:s.isAnonymous?"Аноним":s.authorName,votes:s.votes}:null}function Bh(s,n,t){const a=Se(),i=t.qna,[l,r]=d.useState(!1),m=d.useRef({revision:null,until:0}),o=d.useRef({api:s,producer:n,qna:i});o.current={api:s,producer:n,qna:i};const c=d.useCallback(async(h,p)=>{const{api:N,producer:k,qna:b}=o.current;if(!N.perms.manageStage)return a.error("Выводить вопросы на экран может продюсер"),!1;const y=h&&b.questions.find(w=>w.id===h)||null;if(h&&!y)return a.error("Вопрос уже удалён"),!1;r(!0);try{const w=await b.setOnAir(h);if(!w.ok)return a.error(w.error||"Не удалось вывести вопрос"),!1;m.current={revision:null,until:Date.now()+4e3};const T=await Uh(N,k,qr(y));return T.ok?(m.current={revision:T.revision??null,until:Date.now()+1500},p!=null&&p.quiet||(y?a.success("Вопрос выведен поверх эфира · Esc — убрать с экрана"):a.show("Вопрос убран с экрана")),!0):(a.error(T.error||"Не удалось обновить эфир"),!1)}finally{r(!1)}},[a]),u=d.useCallback(()=>c(null),[c]),x=d.useCallback(()=>{const{qna:h}=o.current,p=h.queue[0];if(!p){a.show("Нет отобранных вопросов — отберите их во вкладке «Все»");return}c(p.id)},[c,a]),f=s.program.revision,g=d.useRef(f);return d.useEffect(()=>{if(f===g.current)return;g.current=f;const h=m.current;if(h.revision!==null&&h.revision===f||Date.now()<h.until)return;const{api:p,producer:N,qna:k}=o.current;if(!p.perms.manageStage)return;const b=_h(p,N);k.onAir&&!b?k.setOnAir(null):!k.onAir&&b&&k.queue[0]&&k.setOnAir(k.queue[0].id)},[f]),d.useEffect(()=>{const h=p=>{p.key!=="Escape"||p.defaultPrevented||!o.current.qna.onAir||!o.current.api.perms.manageStage||ui(p.target)||mi()||document.querySelector(".sn-sed-overlay")||(p.preventDefault(),c(null))};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[c]),{put:c,remove:u,next:x,busy:l}}function Hh(s){const{api:n,producer:t,panel:a,panelOpen:i,openPanel:l,actions:r,setQuestionOnDeck:m}=s,o=Vs(),c=Se(),u=n.perms.manageStage,x=u||n.perms.moderate,[f,g]=d.useState(null),[h,p]=d.useState(null),[N,k]=d.useState(null),[b,y]=d.useState(null),[w,T]=d.useState(!1),[q,C]=d.useState(!1),[_,K]=d.useState(!1),[L,F]=d.useState("viewers"),[S,O]=d.useState(null),[z,M]=d.useState("queue"),[U,$]=d.useState("votes"),[v,B]=d.useState(null),[se,A]=d.useState(null),[X,ae]=d.useState(null),ce=gh(n,u),xe=Lo(n,x),ye=Bh(n,t,o),be=o.qna.onAir??o.qna.queue[0]??null,ge=qr(be),rs=ge?`${ge.id}|${ge.votes}|${ge.text}|${ge.authorName}`:"",Ie=d.useRef(ge);Ie.current=ge,d.useEffect(()=>{m(Ie.current)},[rs,m]);const De=xe.lastError;d.useEffect(()=>{De&&x&&c.error(De.message||"Опрос: что-то пошло не так")},[De,x,c]);const We=d.useMemo(()=>o.invites.invites.filter(G=>G.status!=="pending"&&G.respondedAt),[o.invites.invites]),W=d.useRef(null);d.useEffect(()=>{if(!W.current){W.current=new Set(We.map(G=>G.id));return}We.forEach(G=>{W.current.has(G.id)||(W.current.add(G.id),G.status==="accepted"?c.success(`${G.name} принял(а) приглашение — уже за кулисами`):G.status==="declined"?c.show(`${G.name} отказался(ась) выходить на сцену`):G.status==="expired"&&c.show(`${G.name} не ответил(а) на приглашение`))})},[We,c]);const oe=d.useMemo(()=>n.chat.filter(G=>G.visibility==="public"&&!G.isMine).length,[n.chat]),le=d.useMemo(()=>n.chat.filter(G=>Pr(G)&&!G.isMine).length,[n.chat]),[ie,as]=d.useState(oe),[Ze,cs]=d.useState(le),Fe=d.useRef(Date.now()),ne=i&&a==="chat";d.useEffect(()=>{const G=Date.now()-Fe.current<5e3;(G||ne&&L==="viewers")&&as(oe),(G||ne&&L==="team")&&cs(le)},[oe,le,ne,L]);const je=Math.max(0,oe-ie),Ee=Math.max(0,le-Ze),ze=d.useMemo(()=>Fr(xe.polls),[xe.polls]),os=d.useCallback(async G=>{if(G.polls.find(E=>E.status==="live")){A(G.id);return}const es=Wa(G);if(!es){A(G.id);return}ae(G.id);try{const E=await xe.publish(es.id,{showOnStage:es.launchOnStage!==!1});if(!E.ok){c.error(E.error||"Не удалось запустить");return}A(G.id),c.success(es.launchOnStage!==!1?"Запущено — на экране и в чате":"Запущено — в чате у зрителей")}finally{ae(null)}},[xe,c]),re=d.useRef(ze);re.current=ze;const he=d.useCallback((G,Ne)=>{G.ok?c.success(Ne):c.error(G.error||"Не получилось")},[c]),D=d.useCallback(G=>{F("team"),O(G.isLocal?null:G),l("chat")},[l]),V={onMute:G=>void n.forceMute(G.id).then(Ne=>he(Ne,`Микрофон выключен: ${G.name}`)),onAskUnmute:G=>void n.requestUnmute(G.id).then(Ne=>he(Ne,`Попросили ${G.name} включить микрофон`)),onCameraOff:G=>void n.forceCameraOff(G.id).then(Ne=>he(Ne,`Камера выключена: ${G.name}`)),onMessage:D,onCue:G=>r.openCue(G),onRole:G=>k(G),onLowerThirds:G=>r.openLowerThirds(G),onToAudience:G=>{(async()=>{const Ne=await o.invites.returnToAudience(n.stageIdOf(G));if(Ne.ok){c.success(`${G.name} вернулся(ась) к зрителям`);return}if(Ne.code==="bad_request"&&n.assignableRoles(G).includes("viewer")){const es=n.changeRole?await n.changeRole(G.id,"viewer"):(n.setRole(G.id,"viewer"),{ok:!0});he(es,`${G.name} теперь зритель`);return}c.error(Ne.error||"Не получилось")})()},onInviteToStage:G=>void o.invites.invite(n.stageIdOf(G)).then(Ne=>he(Ne,`${G.name} получил(а) приглашение за кулисы`)),onKick:G=>y(G)},Q={openInvite:()=>T(!0),messagePerson:D,questionOnAir:G=>{G?ye.put(G):ye.next()},runPoll:G=>{l("polls");const Ne=re.current.find(es=>es.polls.some(E=>E.id===G));if(!Ne){c.error("Опрос не найден — обновите список");return}os(Ne)},openRole:G=>k(G),showQuestion:G=>ye.put(G),hidePoll:async G=>{const Ne=await xe.hide(G);return Ne.ok?(c.success("Опрос убран с экрана"),!0):(c.error(Ne.error||"Не удалось убрать опрос с экрана"),!1)}},Z=o.audience.raisedHands.filter(G=>!G.isTeam).length,fe=o.waiting.ready?o.waiting.waiting.length:0,ve=xe.polls.some(G=>G.status==="live"),Be={people:Z+fe,questions:o.qna.incoming.length},Y={chat:!ne&&(je>0||Ee>0),polls:ve,questions:!!o.qna.onAir},Le=o.qna.queue[0]||null,Ge=Le&&u?{id:Le.id,text:Le.text,authorName:Le.isAnonymous?"Аноним":Le.authorName,votes:Le.votes,note:"Вопрос · отобран"}:null,Je=ze.find(G=>G.state==="live")||ze.find(G=>G.state==="progress")||ze.find(G=>G.state==="ready")||null,ds=Je?Je.polls.find(G=>G.status==="live")||Wa(Je)||Je.polls[0]:null,pn=Je&&ds&&x?{id:ds.id,question:Je.polls.length>1?`${Je.title} · вопрос ${Je.polls.indexOf(ds)+1}`:ds.question,optionsCount:ds.options.length,running:Je.state==="live"}:null,$n=G=>G==="people"?e.jsx(jh,{api:n,producer:t,rt:o,search:f,onSearch:g,onPersonMenu:(Ne,es)=>p({participant:Ne,anchor:es}),onMessage:D,onInvite:()=>T(!0),onPermissions:()=>C(!0)}):G==="questions"?e.jsx(Oh,{api:n,producer:t,rt:o,tab:z,onTab:M,sort:U,control:ye}):G==="chat"?e.jsx(Xm,{api:n,rt:o,tab:L,onTab:F,dm:S,onDm:O,teamUnread:L==="team"?0:Ee}):G==="polls"?e.jsx(Eh,{api:n,rt:o,control:xe,focus:se,onFocus:A,onNew:()=>B({editing:null}),onEdit:Ne=>B({editing:Ne}),onRun:os,runningId:X}):null,In=G=>G==="people"?e.jsx(Vh,{searching:f!==null,onSearch:()=>g(Ne=>Ne===null?"":null),canManage:u,onMuteAll:Ne=>void n.muteAll({exceptTeam:Ne}).then(es=>he(es,es.muted!==void 0?`Микрофоны выключены: ${es.muted}`:"Микрофоны выключены")),onInvite:()=>T(!0),onPermissions:()=>C(!0)}):G==="questions"?e.jsx(Th,{rt:o,sort:U,onSort:$,canModerate:x}):G==="chat"&&x?e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":"Настройки чата",title:"Настройки чата",onClick:()=>K(!0),children:e.jsx(oi,{className:"sn-i sn-i-16"})}):G==="polls"&&x?e.jsx(R,{size:"sm",variant:"text",onClick:()=>B({editing:null}),style:{height:30,fontSize:13},children:"+ Новый"}):null,Mn=e.jsxs(e.Fragment,{children:[e.jsx(Nh,{api:n,producer:t,target:h,onClose:()=>p(null),handlers:V}),e.jsx(Fh,{api:n,producer:t,participant:N,onClose:()=>k(null)}),e.jsx(yn,{open:!!b,onClose:()=>y(null),icon:e.jsx(ct,{className:"sn-i"}),title:`Удалить ${(b==null?void 0:b.name)||""} из комнаты?`,description:"Человек сразу выйдет из студии. Вернуться сможет по ссылке, если она у него есть.",confirmLabel:"Удалить",onConfirm:async()=>
112{if(!b)return;const G=b;if(n.kickFromRoom){const Ne=await n.kickFromRoom(G.id);if(he(Ne,`${G.name} удалён(а) из комнаты`),!Ne.ok)return}else n.removeFromRoom(G.id);y(null)}}),e.jsx(fh,{open:w,onClose:()=>T(!1),api:n}),e.jsx(yh,{open:q,onClose:()=>C(!1),perms:ce,rt:o,socket:n.studioSocket}),e.jsx(Ym,{open:_,onClose:()=>K(!1),rt:o}),e.jsx(Mh,{open:!!v,onClose:()=>B(null),control:xe,editing:(v==null?void 0:v.editing)??null,onLaunched:G=>{const Ne=re.current.find(es=>es.polls.some(E=>E.id===G));A(Ne?Ne.id:G),l("polls")}})]});return{renderPanel:$n,panelHeadAction:In,counts:Be,dots:Y,modals:Mn,actions:Q,onNextQuestion:()=>ye.next(),quickQuestion:Ge,quickPoll:pn}}function Vh({searching:s,onSearch:n,canManage:t,onMuteAll:a,onInvite:i,onPermissions:l}){const r=mn();return e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":"Поиск","aria-pressed":s,onClick:n,children:e.jsx(ea,{className:"sn-i sn-i-16"})}),t&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm","aria-label":"Ещё",onClick:r.toggle,children:e.jsx(zs,{className:"sn-i sn-i-16"})}),e.jsx(Cs,{open:r.open,onClose:r.close,anchor:r.anchor,width:290,items:[{label:"Выключить звук всем, кроме команды",description:"Спикеры и гости — без продюсера и ведущих",icon:e.jsx(Es,{className:"sn-i sn-i-16"}),onSelect:()=>a(!0)},{label:"Выключить звук всем",icon:e.jsx(Es,{className:"sn-i sn-i-16"}),onSelect:()=>a(!1)},{type:"separator"},{label:"Пригласить",icon:e.jsx(Is,{className:"sn-i sn-i-16"}),onSelect:i},{label:"Права в комнате",icon:e.jsx(Un,{className:"sn-i sn-i-16"}),onSelect:l}]})]})]})}const xl="(max-width: 760px)";function Kh(){const s=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(xl).matches,[n,t]=d.useState(s);return d.useEffect(()=>{var l;if(typeof window>"u"||typeof window.matchMedia!="function")return;const a=window.matchMedia(xl),i=()=>t(a.matches);return i(),(l=a.addEventListener)==null||l.call(a,"change",i),()=>{var r;return(r=a.removeEventListener)==null?void 0:r.call(a,"change",i)}},[]),n}const Wh=["people","questions","chat"],Gh=[{id:"console",label:"Пульт",icon:e.jsx(Hn,{className:"sn-i"})},{id:"people",label:"Люди",icon:e.jsx(nn,{className:"sn-i"})},{id:"questions",label:"Вопросы",icon:e.jsx(wn,{className:"sn-i"})},{id:"chat",label:"Чат",icon:e.jsx(Hs,{className:"sn-i"})},{id:"more",label:"Ещё",icon:e.jsx(mc,{className:"sn-i"})}];function Qh({active:s,onSelect:n,counts:t,dots:a}){return e.jsx("nav",{className:"sn-prod-tabs","aria-label":"Разделы пульта",children:Gh.map(i=>{const l=i.id,r=i.id==="console"||i.id==="more"?0:t[l]||0,m=i.id!=="console"&&i.id!=="more"&&!r&&!!a[l];return e.jsxs("button",{type:"button",className:"sn-prod-tab","aria-current":s===i.id?"page":void 0,onClick:()=>n(i.id),children:[e.jsxs("span",{className:"sn-prod-tab-ico",children:[i.icon,r>0?e.jsx("span",{className:"sn-prod-tab-count",children:r>99?"99+":r}):m?e.jsx("span",{className:"sn-prod-tab-dot"}):null]}),i.label]},i.id)})})}function Yh({api:s,producer:n,onConsole:t}){const a=s.live.isLive,i=n.scenes.find(m=>m.id===s.program.sourceSceneId)||null,l=n.previewScene,r=a&&s.perms.manageStage&&!!n.compiledPreview&&!n.previewMatchesProgram;return e.jsxs("div",{className:"sn-prod-pstrip",children:[e.jsxs("button",{type:"button",className:"sn-prod-pstrip-main",onClick:t,"aria-label":"Вернуться к пульту",children:[e.jsx("span",{className:`sn-prod-pstrip-thumb${a?" is-live":""}`,children:i?e.jsx(Kt,{api:s,producer:n,scene:i}):null}),e.jsxs("span",{className:"sn-prod-pstrip-text",children:[e.jsxs("span",{className:"sn-prod-pstrip-title",children:[a?e.jsx(ns,{tone:"live",style:{height:20,fontSize:11},children:"ЭФИР"}):e.jsx(ns,{tone:"gray",style:{height:20,fontSize:11},children:"НЕ В ЭФИРЕ"}),e.jsx("b",{children:s.program.name||"Пусто"})]}),e.jsx("span",{className:"sn-prod-pstrip-sub",children:l&&!n.previewMatchesProgram?e.jsxs(e.Fragment,{children:["Подготовка: ",e.jsx("b",{children:l.name})]}):"Подготовка совпадает с эфиром"})]}),!r&&e.jsx(Ps,{className:"sn-i sn-i-16","aria-hidden":"true",style:{color:"var(--sn-ink-3)"}})]}),r&&e.jsxs("button",{type:"button",className:"sn-prod-pstrip-take",onClick:()=>void n.takePreview(),disabled:n.taking,"aria-busy":n.taking||void 0,children:["В эфир",e.jsx(Xs,{className:"sn-i sn-i-16","aria-hidden":"true"})]})]})}function Xh({api:s,producer:n,onEdit:t}){const a=n.previewScene,i=n.compiledPreview,l=n.cast.length>0||n.excluded.length>0;return e.jsxs("section",{className:"sn-prod-prow","aria-label":"Подготовка",children:[e.jsx("span",{className:"sn-prod-prow-thumb",children:i?e.jsx(Nn,{compiled:i,brand:pi(s,n),bar:yt(s,n),mode:"thumb",className:"sn-scene-thumb"}):null}),e.jsxs("span",{className:"sn-prod-prow-text",children:[e.jsx("span",{className:"sn-kicker",children:"ПОДГОТОВКА"}),e.jsx("b",{children:(a==null?void 0:a.name)||"Сцена не выбрана"}),e.jsxs("span",{className:"sn-prod-prow-actions",children:[a&&s.perms.changeLayouts&&e.jsxs("button",{type:"button",onClick:t,children:[e.jsx(ei,{className:"sn-i sn-i-14","aria-hidden":"true"}),"Изменить кадр"]}),l&&e.jsx("button",{type:"button",onClick:n.clearPreview,title:"Вернуть сцену в подготовке к исходному составу",children:"Очистить"})]}),n.compiledPreview&&n.compiledPreview.warnings.length>0&&e.jsx("span",{className:"sn-prod-prow-warn",role:"status",children:n.compiledPreview.warnings[0]})]})]})}function Jh({api:s,producer:n,openPanel:t,onLowerThirds:a,onRecording:i,onInvite:l,onSettings:r}){var p,N,k;const m=s.live.isLive,o=n.banners.filter(b=>b.kind==="banner").length,c=wt(s),u=pr(s),x=!!((p=s.recordingPause)!=null&&p.paused),f=[{id:"banner",title:"Баннер",note:o?`${o} в списке`:"баннеры и бегущая строка",icon:e.jsx(Bn,{className:"sn-i"}),onSelect:()=>t("graphics")},{id:"names",title:"Плашки с именами",note:n.prefs.names?"включены":"выключены",icon:e.jsx($c,{
112className:"sn-i"}),onSelect:a},{id:"brand",title:"Бренд",note:"логотип, цвета",icon:e.jsx(ai,{className:"sn-i"}),onSelect:()=>t("brand")},...s.verticalFormat?[{id:"format",title:s.aspect==="9:16"?"Формат 16:9":"Формат 9:16",note:s.aspect==="9:16"?"сейчас пульт в 9:16":"вертикальная версия",icon:e.jsx(Xo,{className:"sn-i"}),onSelect:()=>s.setAspect(s.aspect==="9:16"?"16:9":"9:16")}]:[]],g=[{id:"polls",title:"Опросы",note:"опросы и викторины",icon:e.jsx(xn,{className:"sn-i"}),onSelect:()=>t("polls")},{id:"media",title:"Медиа",note:"слайды, ролики",icon:e.jsx(gt,{className:"sn-i"}),onSelect:()=>t("media")},{id:"rundown",title:"Программа",note:((k=(N=s.rundown)==null?void 0:N.current)==null?void 0:k.title)||"план эфира",icon:e.jsx(Il,{className:"sn-i"}),onSelect:()=>t("rundown")},{id:"sound",title:"Звук",note:"микшер, музыка",icon:e.jsx(Cn,{className:"sn-i"}),onSelect:()=>t("sound")},{id:"outputs",title:"Площадки",note:c.length?`сбой: ${c[0].name}`:m?`${u+1} работают`:"куда идёт эфир",tone:c.length?"amber":m?"green":void 0,icon:e.jsx(ws,{className:"sn-i"}),onSelect:()=>t("outputs")},{id:"recording",title:"Запись",note:s.recording.active?x?"на паузе":`идёт ${Nt(dt(s))}`:s.autoRecord?"начнётся с эфиром":"выключена",tone:s.recording.active&&!x?"red":void 0,icon:e.jsx(Jo,{className:"sn-i"}),onSelect:i,hidden:!s.perms.recording},{id:"ai",title:"AI",note:"соведущий",icon:e.jsx(Vn,{className:"sn-i"}),onSelect:()=>t("ai")},{id:"invite",title:"Пригласить",note:"ссылки для команды",icon:e.jsx(Is,{className:"sn-i"}),onSelect:l,hidden:!s.perms.invites}],h=b=>e.jsxs("button",{type:"button",className:`sn-prod-more-tile${b.tone?` is-${b.tone}`:""}`,onClick:y=>b.onSelect(y.currentTarget),children:[e.jsx("span",{className:"sn-prod-more-ico","aria-hidden":"true",children:b.icon}),e.jsxs("span",{className:"sn-prod-more-text",children:[e.jsx("b",{children:b.title}),e.jsx("span",{children:b.note})]})]},b.id);return e.jsxs("div",{className:"sn-prod-more",children:[e.jsx("span",{className:"sn-eyebrow",children:"Графика"}),e.jsx("div",{className:"sn-prod-more-grid",children:f.filter(b=>!b.hidden).map(h)}),e.jsx("span",{className:"sn-eyebrow",children:"Эфир"}),e.jsx("div",{className:"sn-prod-more-grid",children:g.filter(b=>!b.hidden).map(h)}),e.jsxs("button",{type:"button",className:"sn-prod-more-row",onClick:r,children:[e.jsx("span",{className:"sn-prod-more-ico","aria-hidden":"true",children:e.jsx(Yt,{className:"sn-i"})}),e.jsxs("span",{className:"sn-prod-more-text",children:[e.jsx("b",{children:"Настройки студии"}),e.jsx("span",{children:"камера, микрофон, шумоподавление"})]}),e.jsx(Ps,{className:"sn-i sn-i-16","aria-hidden":"true",style:{color:"var(--sn-ink-3)"}})]})]})}function Dp({api:s,ext:n={}}){var Q,Z,fe,ve,Be;const t=Se(),[a,i]=d.useState(null),l=kd(s,n.question??a);ou(s),Ju(s),Zu(s);const[r,m]=d.useState(s.live.isLive?"graphics":"prelive"),[o,c]=d.use
112State(!1),u=Kh(),[x,f]=d.useState(!1),[g,h]=d.useState(null),[p,N]=d.useState("16:9"),[k,b]=d.useState(null),y=(Y,Le="16:9")=>{Y&&(N(Le),b(null),h(Y))},[w,T]=d.useState(!1),[q,C]=d.useState(null),[_,K]=d.useState(null),[L,F]=d.useState(null),[S,O]=d.useState(null),z=d.useCallback((Y,Le)=>O({participant:Y,anchor:Le}),[]),[M,U]=d.useState(null),[$,v]=d.useState(null),[B,se]=d.useState(null),[A,X]=d.useState(!1),[ae,ce]=d.useState(null),xe=d.useRef(null),ye=d.useRef(s.live.isLive),be=d.useRef(!1);d.useEffect(()=>{!u||be.current||(be.current=!0,s.aspect==="9:16"&&s.programFormat!=="9:16"&&s.setAspect("16:9"))},[u,s]),d.useEffect(()=>{s.live.isLive&&!ye.current&&r==="prelive"&&m("graphics"),ye.current=s.live.isLive},[s.live.isLive,r]);const ge=d.useCallback(Y=>{m(Y),c(!0),f(!1)},[]),rs=l.setMediaSpeaker,Ie=d.useCallback(Y=>{rs(Y),ge("media")},[rs,ge]),De=d.useRef(s);De.current=s;const We=d.useRef({}),W=d.useMemo(()=>{const Y=(Le,Ge)=>(...Je)=>(We.current[Le]||Ge)(...Je);return{openInvite:Y("openInvite",()=>De.current.openInvite()),messagePerson:Y("messagePerson",()=>ge("chat")),questionOnAir:Y("questionOnAir",()=>ge("questions")),runPoll:Y("runPoll",()=>ge("polls")),openRole:Y("openRole",Le=>U(Le)),openCue:Y("openCue",()=>ge("rundown")),openLowerThirds:Y("openLowerThirds",()=>ge("graphics")),openGoLive:Y("openGoLive",()=>De.current.openGoLive()),openSettings:Y("openSettings",()=>De.current.openDeviceSettings()),openEnd:Y("openEnd",()=>X(!0)),showQuestion:Y("showQuestion",async()=>(ge("questions"),!1)),hidePoll:Y("hidePoll",async()=>(ge("polls"),!1))}},[ge]),oe={api:s,producer:l,panel:r,panelOpen:o,openPanel:ge,actions:W,setQuestionOnDeck:i},le=Hh(oe),ie=Vm(oe);We.current={...ie.actions,...le.actions};const as=Kc(oe),Ze=$s(s).filter(Y=>!Y.isLocal),cs=Ze.filter(Y=>s.readyPeers[s.stageIdOf(Y)]||!Y.isCameraOff&&!Y.isMuted).length,Fe=d.useRef(()=>{});Fe.current=Y=>{if(Y.defaultPrevented||Y.ctrlKey||Y.metaKey||Y.altKey||ui(Y.target)||mi()||g)return;if(Y.code==="Space"||Y.key===" "){if(!s.perms.manageStage)return;Y.preventDefault(),Y.repeat||l.takePreview();return}if(/^[1-9]$/.test(Y.key)){const Je=l.scenes.find(ds=>ds.hotkey===Number(Y.key));if(!Je)return;Y.preventDefault(),Y.shiftKey&&s.perms.manageStage?l.takeScene(Je):l.setPreviewId(Je.id);return}const Le=Y.key.toLowerCase();if((Le==="b"||Le==="и")&&s.perms.manageStage){const Je=xe.current||l.banners.find(ds=>ds.kind==="banner")||null;if(!Je)return;Y.preventDefault(),s.activeBannerId===Je.id?s.hideBanner("banner"):l.showBanner(Je);return}const Ge=le.onNextQuestion||n.onNextQuestion;(Le==="q"||Le==="й")&&Ge&&s.perms.manageStage&&(Y.preventDefault(),Ge())},d.useEffect(()=>{const Y=Le=>Fe.current(Le);return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[]);const ne=d.useMemo(()=>{const Y=l.scenes.find(Ge=>/финал|спасибо/i.test(Ge.name));if(Y)return Y;const Le=l.scenes.filter(Ge=>Ge.template==="title");return Le.length>1?Le[Le.length-1]:null},[l.scenes]),je=(()=>{var Le;if(r==="prelive")return e.jsx(Bi,{api:s,producer:l,onOpenPanel:ge});if(r==="graphics")return e.jsx(Md,{api:s,producer:l,onNewBanner:Ge=>ce({initial:null,kind:Ge}),onEditBanner:Ge=>ce({initial:Ge,kind:Ge.kind}),onLowerThirds:()=>W.openLowerThirds(null),onBrand:()=>ge("brand"),quickQuestion:le.quickQuestion??null,onQuestionOnAir:Ge=>W.questionOnAir(Ge),quickPoll:le.quickPoll??null,onRunPoll:Ge=>W.runPoll(Ge),lowerThirdCount:$s(s).length});const Y=le.renderPanel(r)??ie.renderPanel(r)??((Le=n.renderPanel)==null?void 0:Le.call(n,r,{openPanel:ge}));return Y||e.jsxs("div",{className:"sn-hint",style:{fontSize:13.5},children:["Раздел «",Vt[r],"» загружается…"]})})(),Ee=Ed(s,as.state.missing.length),ze=r==="graphics"&&s.perms.manageStage?e.jsx(R,{size:"sm",variant:"text",onClick:()=>ce({initial:null,kind:"banner"}),style:{height:30,fontSize:13},children:"+ Баннер"}):r==="prelive"?e.jsxs("span",{className:`sn-tag ${Ee.ready===Ee.total?"sn-tag-green":"sn-tag-amber"}`,children:[Ee.ready," из ",Ee.total," готово"]}):((Q=le.panelHeadAction)==null?void 0:Q.call(le,r))??((Z=ie.panelHeadAction)==null?void 0:Z.call(ie,r))??null,os=l.previewMatchesProgram?"Уже в эфире":"Вывести в эфир",re={...n.panelCounts,...ie.counts,...le.counts,people:(le.counts.people??((fe=n.panelCounts)==null?void 0:fe.people)??0)+as.pendingRequests},he={...n.panelDots,...ie.dots,...le.dots},D=x?"more":o?Wh.includes(r)?r:"more":"console",V=Y=>{if(g){t.show("Сначала сохраните или закройте редактор сцены");return}Y==="console"?(c(!1),f(!1)):Y==="more"?(c(!1),f(!0)):ge(Y)};return e.jsx(_c,{value:as.state,children:e.jsxs("div",{className:"sn sn-studio","data-view":"producer",children:[((ve=ie.renderHeader)==null?void 0:ve.call(ie,{onEnd:()=>W.openEnd(),onOpenRecording:se}))??e.jsx(Zh,{api:s,readyCount:cs,total:Ze.length,onOpenPanel:ge,onOpenRecording:se,onEnd:()=>W.openEnd(),onGoLive:()=>W.openGoLive()}),e.jsxs("div",{className:"sn-prod-body",children:[e.jsxs(e.Fragment,{children:[e.jsxs("main",{className:"sn-prod-main",style:{position:"relative",isolation:"isolate"},"aria-hidden":g?!0:void 0,children:[l.notice&&!g&&e.jsx(vd,{notice:l.notice,onUndo:l.notice.previous?()=>{var Y;return void l.undoTake(((Y=l.notice)==null?void 0:Y.previous)??null)}:null,onClose:l.dismissNotice}),s.aspect==="9:16"?e.jsxs("div",{className:"sn-prod-vrow",children:[e.jsx(_i,{api:s,producer:l,onEdit:()=>y(l.previewScene,"9:16"),onPersonMenu:z}),e.jsxs("div",{className:"sn-prod-vtake",children:[e.jsxs("button",{type:"button",className:`sn-prod-vtake-btn${l.previewMatchesProgram?" is-same":""}`,onClick:()=>void l.takePreview(),disabled:!s.perms.manageStage||!l.compiledPreview||l.taking,"aria-busy":l.taking||void 0,children:[e.jsx(Xs,{className:"sn-i","aria-hidden":"true"}),e.jsx("span",{children:os}),e.jsx("span",{className:"sn-kbd",children:"Пробел"})]}),e.jsx(we,{className:"sn-seg-tight",ariaLabel:"Переход",value:l.transition,onChange:l.setTransition,options:[{value:"cut",label:"Сразу"},{value:"fade",label:"Плавно"}],style:{width:"100%"}}),e.jsx(R,{size:"sm",variant:"text",onClick:l.clearPreview,disabled:!l.cast.length&&!l.excluded.length,title:"Вернуть сцену в подготовке к исходному составу",children:"Очистить"})]}),e.jsx(oa,{api:s,producer:l,onPersonMenu:z}),e.jsx(jd,{api:s,onFixFrame:()=>
112y(l.previewScene,"9:16"),canFix:!!l.previewScene&&l.previewScene.template!=="auto"&&s.perms.changeLayouts,fixNote:((Be=l.previewScene)==null?void 0:Be.template)==="auto"?"Сцена «Авто» раскладывает вертикальный кадр сама":null,verticalLive:ie.verticalLive})]}):u?e.jsxs("div",{className:"sn-prod-monitors",children:[e.jsx(oa,{api:s,producer:l,onPersonMenu:z}),e.jsx(Xh,{api:s,producer:l,onEdit:()=>y(l.previewScene)})]}):e.jsxs("div",{className:"sn-prod-monitors",children:[e.jsx(_i,{api:s,producer:l,onEdit:()=>y(l.previewScene),onPersonMenu:z}),e.jsx(oa,{api:s,producer:l,onPersonMenu:z})]}),u&&s.aspect!=="9:16"&&e.jsx("div",{className:"sn-prod-ptake",children:e.jsx(R,{size:"lg",variant:"primary",className:`sn-prod-take${l.previewMatchesProgram?" is-same":""}`,onClick:()=>void l.takePreview(),loading:l.taking,disabled:!s.perms.manageStage||!l.compiledPreview,iconRight:e.jsx(Xs,{className:"sn-i"}),children:os})}),u&&!s.live.isLive&&s.perms.broadcastLive&&e.jsx("div",{className:"sn-prod-ptake",children:e.jsx(R,{size:"lg",variant:"live",icon:e.jsx(ws,{className:"sn-i"}),onClick:()=>W.openGoLive(),loading:s.live.starting,children:"Выйти в эфир"})}),u&&!s.live.isLive&&e.jsxs("section",{className:"sn-prod-sec","aria-label":"Перед эфиром",children:[e.jsxs("div",{className:"sn-prod-sec-head",children:[e.jsx("span",{className:"sn-t",children:"Перед эфиром"}),e.jsx("div",{className:"sn-st-grow"}),e.jsxs("span",{className:`sn-tag ${Ee.ready===Ee.total?"sn-tag-green":"sn-tag-amber"}`,children:[Ee.ready," из ",Ee.total," готово"]})]}),e.jsx(Bi,{api:s,producer:l,onOpenPanel:ge,phone:!0})]}),!u&&s.aspect!=="9:16"&&e.jsxs("div",{className:"sn-prod-takebar",children:[e.jsxs("div",{className:"sn-prod-takebar-left",children:[e.jsx(R,{size:"sm",variant:"quiet",icon:e.jsx(Hl,{className:"sn-i sn-i-16"}),onClick:()=>y(l.previewScene),disabled:!l.previewScene||!s.perms.changeLayouts,children:"Изменить кадр"}),e.jsx(R,{size:"sm",variant:"text",onClick:l.clearPreview,disabled:!l.cast.length&&!l.excluded.length,title:"Вернуть сцену в подготовке к исходному составу",children:"Очистить"})]}),e.jsx(R,{size:"lg",variant:"primary",className:`sn-prod-take${l.previewMatchesProgram?" is-same":""}`,onClick:()=>void l.takePreview(),loading:l.taking,disabled:!s.perms.manageStage||!l.compiledPreview,iconRight:e.jsxs(e.Fragment,{children:[e.jsx(Xs,{className:"sn-i"}),e.jsx("span",{className:"sn-kbd",children:"Пробел"})]}),children:os}),e.jsxs("div",{className:"sn-prod-takebar-right",children:[e.jsx(we,{className:"sn-seg-tight",ariaLabel:"Переход",value:l.transition,onChange:l.setTransition,options:[{value:"cut",label:"Сразу"},{value:"fade",label:"Плавно"}]}),s.verticalFormat&&e.jsx(we,{className:"sn-seg-tight",ariaLabel:"Формат",value:s.aspect,onChange:s.setAspect,options:[{value:"16:9",label:"16:9"},{value:"9:16",label:"9:16"}]})]})]}),ie.renderProgramBar?ie.renderProgramBar():e.jsx(ex,{api:s,onOpen:()=>ge("rundown")}),e.jsx(eu,{api:s,producer:l,onNew:Y=>T(Y??null),onEdit:Y=>h(Y),onRename:C,onHotkey:K,onDelete:F,touch:u}),!u&&e.jsx(od,{api:s,producer:l,onPersonMenu:(Y,Le)=>O({participant:Y,anchor:Le}),onMedia:Y=>n.onMedia?n.onMedia(Y):l.addToPreview(Y),onUpload:s.uploadMedia,onInvite:()=>W.openInvite(),onOpenMedia:Ie})]}),e.jsxs("aside",{className:`sn-prod-panel${o||u&&x?" is-open":""}`,"aria-label":"Панель",children:[u&&(o||x)&&e.jsx(Yh,{api:s,producer:l,onConsole:()=>V("console")}),u&&x?e.jsx("div",{className:"sn-panel-body",children:e.jsx(Jh,{api:s,producer:l,openPanel:ge,onLowerThirds:()=>W.openLowerThirds(null),onRecording:se,onInvite:()=>W.openInvite(),onSettings:()=>W.openSettings()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sn-panel-head",children:[e.jsx("h2",{children:Vt[r]}),ze,e.jsx("button",{type:"button",className:"sn-ibtn sn-ibtn-ghost sn-ibtn-sm sn-panel-close","aria-label":"Скрыть панель",onClick:()=>c(!1),children:e.jsx(ls,{className:"sn-i sn-i-16"})})]}),e.jsx("div",{className:"sn-panel-body",children:je})]})]})]}),g&&u&&p==="16:9"&&!k&&e.jsx(Yd,{api:s,producer:l,scene:g,onClose:()=>h(null),onFull:Y=>{b({saved:g}),h(Y)}},g.id),g&&(!u||p==="9:16"||k)&&e.jsx("div",{className:"sn-sed-overlay",children:e.jsx(Wd,{api:s,producer:l,scene:g,saved:k==null?void 0:k.saved,orientation:p,onClose:()=>{h(null),b(null)},onHotkey:Y=>K(Y)},g.id)}),u?e.jsx(Qh,{active:D,onSelect:V,counts:re,dots:he}):e.jsx(zd,{active:g?null:r,onSelect:Y=>{if(g){t.show("Сначала сохраните или закройте редактор сцены");return}Y===r&&o?c(!1):ge(Y)},counts:re,dots:he,showPrelive:!1})]}),e.jsx(Cd,{open:w!==!1,folderId:w||null,onClose:()=>T(!1),api:s,producer:l,onCreated:Y=>y(Y)}),e.jsx(cd,{scene:q,onClose:()=>C(null),producer:l}),e.jsx(dd,{scene:_,onClose:()=>K(null),producer:l}),e.jsx(yn,{open:!!L,onClose:()=>F(null),onConfirm:async()=>{L&&await l.deleteScene(L),F(null)},title:`Удалить сцену «${(L==null?void 0:L.name)||""}»?`,description:"Сцена пропадёт из списка у всей команды эфира. Люди и файлы останутся в студии.",confirmLabel:"Удалить"}),e.jsx(hd,{api:s,producer:l,target:S,onClose:()=>O(null),onRole:U,onCue:Y=>n.onCue?n.onCue(Y):W.openCue(Y),onLowerThirds:Y=>n.onLowerThirds?n.onLowerThirds(Y):W.openLowerThirds(Y),onMessage:Y=>n.onMessage?n.onMessage(Y):W.messagePerson(Y),onKick:v,onFiles:Ie}),e.jsx(md,{api:s,participant:M,onClose:()=>U(null)}),e.jsx(yn,{open:!!$,onClose:()=>v(null),onConfirm:()=>{$&&s.removeFromRoom($.id),v(null)},title:`Удалить ${($==null?void 0:$.name)||""} из комнаты?`,description:"Человек сразу выйдет из студии. Вернуться сможет по ссылке, если она у него есть.",confirmLabel:"Удалить"}
112),e.jsx(xd,{api:s,anchor:B,onClose:()=>se(null)}),e.jsx(fd,{open:A,onClose:()=>X(!1),api:s,producer:l,finalScene:ne}),e.jsx(bd,{open:!!ae,onClose:()=>ce(null),api:s,producer:l,initial:(ae==null?void 0:ae.initial)||null,kind:(ae==null?void 0:ae.kind)||"banner",onShown:Y=>{Y.kind==="banner"&&(xe.current=Y)}}),le.modals,ie.modals,as.modals]})})}function Zh({api:s,readyCount:n,total:t,onOpenPanel:a,onOpenRecording:i,onEnd:l,onGoLive:r}){return e.jsx($d,{api:s,backstageReady:n,backstageTotal:t,onOpenPanel:a,onOpenRecording:i,onGoLive:r,onEnd:l,onLeave:s.leave,rundownLabel:null})}function ex({api:s,onOpen:n}){if(!s.rundown)return null;const{current:t,next:a}=s.rundown;return!t&&!a?null:e.jsxs("button",{type:"button",className:"sn-prod-rundown",onClick:n,children:[e.jsx(Ks,{className:"sn-i sn-i-16"}),e.jsx("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t?e.jsxs(e.Fragment,{children:["Сейчас: ",e.jsx("b",{children:t.title}),a?e.jsxs(e.Fragment,{children:[" · Далее: ",e.jsx("b",{children:a.title})]}):null]}):a?e.jsxs(e.Fragment,{children:["Далее по программе: ",e.jsx("b",{children:a.title})]}):null}),e.jsx(Ga,{children:"Программа"})]})}export{Dp as ProducerView};

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.