shadowduck-web 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/idk.html +3896 -0
  2. package/package.json +7 -6
  3. package/README.md +0 -3
package/idk.html ADDED
@@ -0,0 +1,3896 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en"><head>
3
+ <meta charset="UTF-8">
4
+ <title>Bored Chat</title>
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <link href="https://fonts.googleapis.com/css2?family=Int er:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap" rel="stylesheet">
7
+
8
+ <!-- Firebase (compat SDK) -->
9
+ <script src="https://www.gstatic.com/firebasejs/10.13.0/firebase-app-compat.js"></script>
10
+ <script src="https://www.gstatic.com/firebasejs/10.13.0/firebase-auth-compat.js"></script>
11
+ <script src="https://www.gstatic.com/firebasejs/10.13.0/firebase-database-compat.js"></script>
12
+
13
+
14
+ <style>
15
+ :root{
16
+ --bg-rail:#1e1f22;--bg-list:#2b2d31;--bg-chat:#313338;--bg-input:#383a40;--bg-hover:#3a3c43;
17
+ --blurple:#5865f2;--blurple-hover:#4752c4;--online:#23a55a;--danger:#f23f42;--danger-hover:#da373c;--gold:#f0b232;
18
+ --text-bright:#f2f3f5;--text-normal:#dbdee1;--text-muted:#949ba4;--text-faint:#6a6e77;--border:#232428;
19
+ }
20
+ *{box-sizing:border-box;}
21
+ html,body{margin:0;padding:0;height:100%;background:var(--bg-rail);font-family:'Inter',sans-serif;color:var(--text-normal);overflow:hidden;}
22
+ #app{position:relative;width:100%;height:100vh;overflow:hidden;}
23
+ ::-webkit-scrollbar{width:8px;height:8px;}
24
+ ::-webkit-scrollbar-track{background:transparent;}
25
+ ::-webkit-scrollbar-thumb{background:#1a1b1e;border-radius:4px;}
26
+
27
+ #authScreen{position:relative;height:100%;display:flex;align-items:center;justify-content:center;flex-direction:column;text-align:center;padding:20px;
28
+ background:radial-gradient(circle at 30% 20%, #3a3d6b 0%, transparent 45%),radial-gradient(circle at 80% 80%, #2a2140 0%, transparent 50%),var(--bg-rail);}
29
+ .logo-mark{width:56px;height:56px;border-radius:16px;background:var(--blurple);display:flex;align-items:center;justify-content:center;font-size:1.7rem;font-weight:700;color:#fff;margin-bottom:14px;box-shadow:0 8px 24px rgba(88,101,242,0.4);}
30
+ .logo-word{font-size:1.6rem;font-weight:700;color:var(--text-bright);letter-spacing:-0.5px;margin-bottom:4px;}
31
+ .tagline{color:var(--text-muted);margin-bottom:30px;font-size:0.92rem;}
32
+ .auth-card{width:100%;max-width:380px;background:var(--bg-chat);border-radius:8px;padding:32px 28px;box-shadow:0 12px 40px rgba(0,0,0,0.4);}
33
+ .tabs{display:flex;margin-bottom:20px;border-radius:6px;overflow:hidden;background:var(--bg-input);}
34
+ .tab-btn{flex:1;padding:9px 0;background:transparent;border:none;color:var(--text-muted);font-family:'Inter';font-weight:600;cursor:pointer;font-size:0.84rem;transition:all .15s;}
35
+ .tab-btn.active{background:var(--blurple);color:#fff;}
36
+ .field{margin-bottom:16px;text-align:left;}
37
+ .field label{display:block;font-size:0.72rem;font-weight:700;text-transform:uppercase;letter-spacing:0.3px;color:var(--text-muted);margin-bottom:7px;}
38
+ .field input{width:100%;padding:10px 11px;border-radius:4px;background:#1e1f22;border:1px solid var(--border);color:var(--text-normal);font-size:0.95rem;outline:none;transition:border .15s;}
39
+ .field input:focus{border-color:var(--blurple);}
40
+ .field input[type=color]{height:38px;padding:2px;cursor:pointer;}
41
+ .primary-btn{width:100%;padding:11px;border:none;border-radius:4px;background:var(--blurple);color:#fff;font-weight:600;font-size:0.92rem;cursor:pointer;transition:background .15s;margin-top:6px;}
42
+ .primary-btn:hover{background:var(--blurple-hover);}
43
+ .primary-btn:disabled{opacity:0.55;cursor:not-allowed;}
44
+ .ghost-btn{width:100%;padding:10px;border-radius:4px;margin-top:8px;background:transparent;border:1px solid var(--border);color:var(--text-muted);font-weight:600;font-size:0.85rem;cursor:pointer;transition:all .15s;}
45
+ .ghost-btn:hover{border-color:var(--text-muted);color:var(--text-normal);}
46
+ .auth-msg{min-height:18px;font-size:0.8rem;color:var(--danger);margin-top:10px;word-break:break-word;text-align:left;}
47
+
48
+ .yt-banner{margin-top:24px;max-width:380px;width:100%;background:var(--bg-chat);border:1px solid var(--border);border-radius:8px;padding:13px 16px;display:flex;align-items:center;gap:12px;text-decoration:none;color:var(--text-normal);transition:border-color .15s;}
49
+ .yt-banner:hover{border-color:var(--danger);}
50
+ .yt-icon{width:32px;height:32px;flex:0 0 auto;border-radius:8px;background:var(--danger);display:flex;align-items:center;justify-content:center;}
51
+ .yt-icon svg{width:16px;height:16px;fill:#fff;}
52
+ .yt-text{text-align:left;line-height:1.3;}
53
+ .yt-text b{font-size:0.86rem;}
54
+ .yt-text span{font-size:0.74rem;color:var(--text-muted);}
55
+
56
+ #chatScreen{position:relative;height:100%;display:none;flex-direction:row;}
57
+
58
+ .avatar{border-radius:50%;flex:0 0 auto;display:flex;align-items:center;justify-content:center;font-weight:700;color:#fff;overflow:hidden;background:var(--blurple);}
59
+ .avatar img{width:100%;height:100%;object-fit:cover;}
60
+ .avatar-xs{width:20px;height:20px;font-size:0.6rem;}
61
+ .avatar-sm{width:32px;height:32px;font-size:0.8rem;}
62
+ .avatar-md{width:40px;height:40px;font-size:0.9rem;}
63
+ .presence-dot{width:10px;height:10px;border-radius:50%;flex:0 0 auto;border:3px solid var(--bg-list);background:var(--text-faint);margin-left:-12px;margin-top:14px;}
64
+ .presence-dot.online{background:var(--online);}
65
+
66
+ /* server rail */
67
+ #serverRail{width:72px;flex:0 0 auto;background:var(--bg-rail);display:flex;flex-direction:column;align-items:center;padding:12px 0;gap:8px;overflow-y:auto;overflow-x:hidden;}
68
+ .rail-icon{width:48px;height:48px;border-radius:50%;background:var(--bg-list);display:flex;align-items:center;justify-content:center;font-size:1.3rem;cursor:pointer;transition:all .15s;color:var(--text-normal);position:relative;overflow:hidden;flex:0 0 auto;font-weight:700;}
69
+ .rail-shortcut{border:0;padding:0;}
70
+ .rail-shortcut .badge-dot{position:absolute;top:7px;right:7px;}
71
+ .rail-icon img{pointer-events:none;}
72
+ .rail-icon:hover, .rail-icon.active{border-radius:16px;background:var(--blurple);color:#fff;}
73
+ .rail-icon.active::before{content:'';position:absolute;left:-12px;top:50%;transform:translateY(-50%);width:4px;height:24px;background:#fff;border-radius:0 4px 4px 0;}
74
+ .rail-divider{width:32px;height:2px;background:var(--border);border-radius:1px;margin:2px 0;flex:0 0 auto;}
75
+ #serverRailList, #pinnedRailList{display:flex;flex-direction:column;gap:8px;align-items:center;}
76
+ .rail-add{color:var(--online);font-size:1.6rem;font-weight:400;}
77
+ .rail-add:hover{background:var(--online);color:#fff;}
78
+ .rail-icon.pin-friend{background:transparent;}
79
+ .rail-icon.pin-friend .avatar{width:100%!important;height:100%!important;border-radius:0;font-size:1.1rem;}
80
+ .rail-pres{position:absolute;right:1px;bottom:1px;width:13px;height:13px;border-radius:50%;border:3px solid var(--bg-rail);background:var(--text-faint);}
81
+ .rail-pres.online{background:var(--online);}
82
+
83
+ /* channel column */
84
+ #chanCol{width:240px;flex:0 0 auto;background:var(--bg-list);display:flex;flex-direction:column;min-height:0;}
85
+ #chanColHeader{padding:14px 16px;border-bottom:1px solid var(--border);font-weight:700;color:var(--text-bright);font-size:0.98rem;box-shadow:0 1px 0 rgba(0,0,0,0.15);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
86
+ #chanColBanner{display:none;height:104px;flex:0 0 auto;background-size:cover;background-position:center;border-bottom:1px solid var(--border);align-items:flex-end;padding:10px 14px;}
87
+ #chanColBanner .banner-name{color:#fff;font-weight:700;font-size:1.02rem;text-shadow:0 1px 6px rgba(0,0,0,.7);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
88
+ .upload-row{margin:-6px 0 14px;font-size:0.74rem;color:var(--text-muted);}
89
+ .upload-row input[type=file]{width:100%;font-size:0.74rem;color:var(--text-muted);margin-top:4px;}
90
+ #chanColDesc{display:none;padding:8px 16px;font-size:0.74rem;color:var(--text-muted);border-bottom:1px solid var(--border);line-height:1.4;word-break:break-word;}
91
+
92
+ .voice-status-bar{display:none;align-items:center;gap:8px;padding:9px 12px;background:#292b2f;font-size:0.78rem;color:var(--online);margin:0;border-top:1px solid var(--border);}
93
+ .voice-status-bar.show{display:flex;}
94
+ .voice-status-bar span.vname{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
95
+ .voice-status-bar button{background:transparent;border:1px solid rgba(242,63,66,0.4);color:var(--danger);border-radius:4px;font-size:0.68rem;padding:3px 7px;cursor:pointer;}
96
+
97
+ .sidebar-tabs{display:flex;gap:4px;padding:10px 8px 6px;}
98
+ .sidebar-tab-btn{flex:1;padding:7px 0;border-radius:4px;border:none;background:transparent;color:var(--text-muted);font-weight:600;font-size:0.76rem;cursor:pointer;transition:all .15s;letter-spacing:0.2px;}
99
+ .sidebar-tab-btn.active{background:var(--bg-hover);color:var(--text-bright);}
100
+ .sidebar-tab-btn .badge-dot{display:inline-block;min-width:16px;height:16px;line-height:16px;background:var(--danger);color:#fff;border-radius:8px;font-size:0.62rem;margin-left:4px;padding:0 4px;}
101
+
102
+ .sidebar-section-title{font-size:0.68rem;letter-spacing:0.4px;text-transform:uppercase;color:var(--text-muted);margin:14px 0 4px;padding:0 12px;display:flex;align-items:center;justify-content:space-between;font-weight:700;}
103
+ .new-group-btn{background:transparent;border:none;color:var(--text-muted);font-size:1rem;cursor:pointer;transition:color .15s;line-height:1;}
104
+ .new-group-btn:hover{color:var(--text-bright);}
105
+ .add-friend-row{display:flex;gap:6px;padding:0 8px;margin-bottom:6px;}
106
+ .add-friend-row input{flex:1;min-width:0;padding:8px 10px;border-radius:4px;background:#1e1f22;border:1px solid var(--border);color:var(--text-normal);font-size:0.8rem;outline:none;font-family:'Inter';}
107
+ .add-friend-row input:focus{border-color:var(--blurple);}
108
+ .add-friend-row button{border:none;border-radius:4px;padding:0 12px;cursor:pointer;font-size:0.76rem;font-weight:600;background:var(--blurple);color:#fff;}
109
+ .add-friend-row button:hover{background:var(--blurple-hover);}
110
+ .add-friend-msg{font-size:0.72rem;min-height:16px;margin:2px 12px 6px;color:var(--danger);}
111
+ .add-friend-msg.ok{color:var(--online);}
112
+
113
+ #panelScroll{flex:1;overflow-y:auto;padding-bottom:10px;}
114
+ .empty-list-note{color:var(--text-faint);font-size:0.76rem;padding:10px 14px;text-align:center;}
115
+
116
+ .list-item{display:flex;align-items:center;gap:9px;padding:7px 8px;border-radius:4px;cursor:pointer;font-size:0.86rem;color:var(--text-muted);transition:all .1s;margin:1px 8px;}
117
+ .list-item:hover{background:var(--bg-hover);color:var(--text-normal);}
118
+ .list-item.active{background:var(--bg-hover);color:var(--text-bright);}
119
+ .list-item .item-name{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
120
+ .list-item .hash{opacity:0.55;font-weight:600;}
121
+ .list-item .mini-btn{opacity:0;background:transparent;border:none;cursor:pointer;font-size:0.82rem;padding:0 3px;line-height:1;}
122
+ .list-item:hover .mini-btn{opacity:0.85;}
123
+ .list-item .mini-btn.call{color:var(--online);}
124
+ .list-item .mini-btn.video{color:var(--blurple);}
125
+ .list-item .mini-btn.del, .list-item .mini-btn.block{color:var(--danger);}
126
+ .list-item .mini-btn.nick, .list-item .mini-btn.pin{color:var(--gold);}
127
+ .list-item .mini-btn.invite{color:var(--blurple);}
128
+ .list-item .mini-btn.addppl{color:var(--online);}
129
+ .list-item .mini-btn.leave{color:var(--gold);}
130
+ .list-item .voice-count{font-size:0.68rem;color:var(--online);white-space:nowrap;}
131
+
132
+ .request-row{display:flex;align-items:center;gap:6px;padding:8px 10px;border-radius:6px;font-size:0.82rem;background:var(--bg-chat);margin:0 8px 6px;}
133
+ .request-row .req-name{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text-normal);}
134
+ .request-row button{border:none;border-radius:4px;padding:5px 9px;font-size:0.72rem;cursor:pointer;font-weight:600;}
135
+ .req-accept{background:var(--online);color:#fff;}
136
+ .req-decline, .req-cancel, .req-unblock{background:transparent;border:1px solid var(--border);color:var(--text-muted);}
137
+ .req-decline:hover, .req-cancel:hover{border-color:var(--danger);color:var(--danger);}
138
+ .req-unblock:hover{border-color:var(--online);color:var(--online);}
139
+
140
+ #userBar{display:flex;align-items:center;gap:8px;padding:8px 8px;background:#232428;flex:0 0 auto;}
141
+ #userBar .user-block{display:flex;align-items:center;gap:8px;flex:1;min-width:0;cursor:pointer;padding:4px;border-radius:4px;}
142
+ #userBar .user-block:hover{background:var(--bg-hover);}
143
+ #userBar .user-info{display:flex;flex-direction:column;min-width:0;}
144
+ #userBar .user-info b{font-size:0.82rem;color:var(--text-bright);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:110px;}
145
+ #userBar .user-info span{font-size:0.68rem;color:var(--text-muted);}
146
+ #userBar .bar-icon-btn{background:transparent;border:none;color:var(--text-muted);font-size:1rem;cursor:pointer;padding:6px;border-radius:4px;}
147
+ #userBar .bar-icon-btn:hover{background:var(--bg-hover);color:var(--text-bright);}
148
+
149
+ #chatMain{flex:1;display:flex;flex-direction:column;min-width:0;background:var(--bg-chat);}
150
+ .chat-header{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid var(--border);gap:10px;flex-wrap:wrap;box-shadow:0 1px 0 rgba(0,0,0,0.1);}
151
+ .chat-header .header-left{display:flex;align-items:center;gap:8px;min-width:0;}
152
+ .sidebar-toggle-btn{display:none;background:transparent;border:none;color:var(--text-muted);padding:6px;cursor:pointer;font-size:1.1rem;}
153
+ .current-chat-label-wrap{display:flex;flex-direction:column;min-width:0;}
154
+ .current-chat-label{font-size:0.98rem;font-weight:700;color:var(--text-bright);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
155
+ .current-chat-sub{font-size:0.72rem;color:var(--text-muted);white-space:nowrap;}
156
+ .header-right{display:flex;align-items:center;gap:8px;flex-wrap:wrap;}
157
+ .call-header-btn{background:transparent;border:none;color:var(--text-muted);padding:6px;border-radius:4px;font-size:1.05rem;cursor:pointer;transition:all .15s;}
158
+ .call-header-btn:hover{background:var(--bg-hover);color:var(--online);}
159
+ .call-header-btn.video:hover{color:var(--blurple);}
160
+ .chan-action-btn{background:var(--bg-input);border:none;color:var(--text-normal);padding:6px 10px;border-radius:4px;font-size:0.76rem;font-weight:600;cursor:pointer;transition:all .15s;}
161
+ .chan-action-btn:hover{background:var(--bg-hover);color:var(--text-bright);}
162
+ .chan-action-btn.warn:hover{color:var(--gold);}
163
+ .my-profile-btn{background:none;border:none;padding:0;cursor:pointer;display:none;}
164
+ .admin-badge{background:#ffd60a;color:#1e1f22;padding:4px 10px;border-radius:4px;font-size:0.7rem;font-weight:700;letter-spacing:0.4px;box-shadow:0 0 0 1px rgba(255,214,10,0.4);}
165
+ .conn-pill{padding:5px 10px;border-radius:4px;font-size:0.68rem;color:var(--text-muted);background:var(--bg-input);}
166
+ .conn-pill.online{color:var(--online);}
167
+ .conn-pill.offline{color:var(--danger);}
168
+
169
+ .promo-strip{display:flex;align-items:center;gap:10px;background:rgba(88,101,242,0.08);border-bottom:1px solid var(--border);padding:8px 16px;font-size:0.8rem;color:var(--text-muted);flex-wrap:wrap;}
170
+ .promo-strip a{color:#a6b1ff;font-weight:600;text-decoration:none;}
171
+ .promo-strip a:hover{text-decoration:underline;}
172
+
173
+ .voice-panel{display:none;align-items:center;gap:10px;flex-wrap:wrap;padding:10px 16px;border-bottom:1px solid var(--border);background:#2b2d31;}
174
+ .voice-panel.show{display:flex;}
175
+ .voice-panel .voice-join-btn{border:none;border-radius:4px;padding:7px 14px;font-size:0.8rem;font-weight:600;cursor:pointer;background:var(--online);color:#fff;}
176
+ .voice-panel .voice-join-btn.leave{background:var(--danger);}
177
+ .voice-chip{display:flex;align-items:center;gap:6px;background:var(--bg-input);border-radius:16px;padding:4px 10px 4px 4px;font-size:0.76rem;color:var(--text-normal);}
178
+
179
+ #messages{flex:1;overflow-y:auto;padding:12px 16px;display:flex;flex-direction:column;gap:2px;}
180
+ .msg{display:flex;gap:12px;padding:4px 8px;border-radius:6px;max-width:100%;}
181
+ .msg:hover{background:rgba(4,4,5,0.15);}
182
+ .msg .avatar-slot{flex:0 0 auto;width:40px;padding-top:2px;}
183
+ .msg .msg-body{flex:1;min-width:0;}
184
+ .msg .name-row{display:flex;align-items:baseline;gap:8px;margin-bottom:2px;}
185
+ .msg .name-row .who{font-weight:600;font-size:0.9rem;color:var(--text-bright);}
186
+ .msg .name-row .when{font-size:0.68rem;color:var(--text-faint);}
187
+ .msg .bubble{font-size:0.92rem;line-height:1.4;word-wrap:break-word;white-space:pre-wrap;color:var(--text-normal);}
188
+ .msg.me .name-row .who{color:#a6b1ff;}
189
+ .msg-actions{display:none;gap:2px;margin-left:auto;padding-top:2px;}
190
+ .msg:hover .msg-actions{display:flex;}
191
+ .msg-del-btn, .msg-block-btn{background:var(--bg-input);border:none;cursor:pointer;font-size:0.78rem;padding:4px 6px;border-radius:4px;color:var(--text-muted);}
192
+ .msg-del-btn:hover{color:var(--danger);}
193
+ .msg-block-btn:hover{color:var(--text-bright);}
194
+
195
+ #typingBar{min-height:22px;padding:0 16px;font-size:0.76rem;color:var(--text-muted);font-style:italic;}
196
+ #composer{display:flex;gap:8px;padding:0 16px 20px;align-items:center;}
197
+ #attachBtn{flex:0 0 auto;background:var(--bg-input);border:none;color:var(--text-muted);width:40px;height:40px;border-radius:50%;font-size:1.05rem;cursor:pointer;transition:all .15s;}
198
+ #attachBtn:hover{color:var(--text-bright);background:var(--bg-hover);}
199
+ .msg-media{max-width:320px;max-height:280px;border-radius:8px;margin-top:6px;display:block;cursor:pointer;}
200
+ .media-blocked{margin-top:6px;padding:10px 12px;border-radius:8px;background:var(--bg-input);color:var(--text-muted);font-size:0.8rem;max-width:320px;}
201
+ .owner-tag{display:inline-flex;align-items:center;gap:2px;background:#ffd60a;color:#1e1f22;font-size:0.62rem;font-weight:700;padding:1px 6px;border-radius:3px;letter-spacing:0.2px;vertical-align:middle;}
202
+ .admin-tag{background:#b91c1c;color:#fff;}
203
+ .muted-tag{font-size:0.68rem;color:var(--text-faint);}
204
+ .mini-btn.mute{color:var(--gold);}
205
+ .mini-btn.ban{color:var(--danger);}
206
+ #msgInputWrap{flex:1;display:flex;align-items:center;background:var(--bg-input);border-radius:8px;padding:0 12px;}
207
+ #msgInput{flex:1;padding:12px 8px;background:transparent;border:none;color:var(--text-normal);font-size:0.94rem;outline:none;font-family:'Inter';}
208
+ #sendBtn{padding:0 16px;border:none;background:transparent;color:var(--blurple);font-weight:600;cursor:pointer;font-size:0.85rem;}
209
+ #sendBtn:hover{color:var(--blurple-hover);}
210
+ #sendBtn:disabled{opacity:0.4;cursor:not-allowed;}
211
+ .empty-state{text-align:center;color:var(--text-muted);margin-top:60px;font-size:0.9rem;}
212
+ .empty-state .glyph{font-size:2.4rem;display:block;margin-bottom:12px;opacity:0.5;}
213
+ .composer-note{padding:0 16px 14px;font-size:0.78rem;color:var(--gold);}
214
+
215
+ .modal-overlay{position:fixed;inset:0;z-index:10;background:rgba(0,0,0,0.72);display:none;align-items:center;justify-content:center;padding:20px;}
216
+ .modal-overlay.open{display:flex;}
217
+ .modal-card{width:100%;max-width:360px;background:var(--bg-chat);border-radius:8px;padding:24px 22px;box-shadow:0 12px 44px rgba(0,0,0,0.5);text-align:left;max-height:88vh;overflow-y:auto;display:flex;flex-direction:column;}
218
+ .modal-card h3{margin:0 0 4px;font-size:1.1rem;color:var(--text-bright);}
219
+ .modal-card p.sub{margin:0 0 16px;font-size:0.8rem;color:var(--text-muted);}
220
+ .modal-card input[type=text]{width:100%;padding:10px 11px;border-radius:4px;background:#1e1f22;border:1px solid var(--border);color:var(--text-normal);font-size:0.95rem;outline:none;margin-bottom:12px;flex:0 0 auto;}
221
+ .modal-card input[type=text]:focus{border-color:var(--blurple);}
222
+ .modal-card .field{flex:0 0 auto;}
223
+ .modal-actions{display:flex;gap:10px;margin-top:4px;flex:0 0 auto;}
224
+ .modal-actions button{flex:1;}
225
+ .modal-err{min-height:16px;font-size:0.78rem;color:var(--danger);margin:-4px 0 10px;flex:0 0 auto;}
226
+ .modal-err.ok{color:var(--online);}
227
+ .member-picker{overflow-y:auto;flex:1;margin-bottom:10px;border-top:1px solid var(--border);border-bottom:1px solid var(--border);padding:8px 0;min-height:60px;}
228
+ .member-row{display:flex;align-items:center;gap:9px;padding:7px 4px;font-size:0.86rem;cursor:pointer;color:var(--text-normal);}
229
+ .member-row input{width:auto;margin:0;flex:0 0 auto;}
230
+ .member-row span{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
231
+ .member-row .mini-btn{background:transparent;border:none;cursor:pointer;font-size:0.82rem;padding:0 4px;line-height:1;color:var(--danger);}
232
+ .inline-row{display:flex;gap:8px;align-items:center;margin-bottom:10px;}
233
+ .inline-row input{margin-bottom:0!important;}
234
+ .inline-row button{border:none;border-radius:4px;background:var(--blurple);color:#fff;font-weight:600;font-size:0.8rem;padding:10px 14px;cursor:pointer;white-space:nowrap;}
235
+ .inline-row button:hover{background:var(--blurple-hover);}
236
+ .type-choice{display:flex;gap:8px;margin-bottom:14px;}
237
+ .type-choice button{flex:1;padding:9px 6px;border-radius:4px;border:1px solid var(--border);background:transparent;color:var(--text-muted);font-weight:600;font-size:0.78rem;cursor:pointer;font-family:'Inter';}
238
+ .type-choice button.active{background:var(--blurple);border-color:var(--blurple);color:#fff;}
239
+ .code-box{font-family:'JetBrains Mono',monospace;font-size:1.5rem;letter-spacing:4px;text-align:center;background:#1e1f22;border:1px solid var(--border);border-radius:6px;padding:16px;color:var(--text-bright);margin-bottom:12px;user-select:all;}
240
+ .modal-note{font-size:0.75rem;color:var(--text-faint);margin:0 0 12px;}
241
+
242
+ .search-btn{background:transparent;border:none;color:var(--text-muted);padding:6px;border-radius:4px;font-size:1.05rem;cursor:pointer;transition:all .15s;}
243
+ .search-btn:hover, .search-btn.active{background:var(--bg-hover);color:var(--text-bright);}
244
+ #searchBar{display:none;align-items:center;gap:10px;padding:10px 16px;border-bottom:1px solid var(--border);background:var(--bg-input);}
245
+ #searchBar.open{display:flex;}
246
+ #searchInput{flex:1;padding:8px 12px;border-radius:4px;background:#1e1f22;border:1px solid var(--border);color:var(--text-normal);font-size:0.86rem;outline:none;font-family:'Inter';}
247
+ #searchInput:focus{border-color:var(--blurple);}
248
+ #searchCount{font-size:0.74rem;color:var(--text-muted);white-space:nowrap;min-width:56px;text-align:right;}
249
+ .search-close-btn{background:transparent;border:none;color:var(--text-muted);cursor:pointer;font-size:1rem;padding:2px 4px;}
250
+ .search-close-btn:hover{color:var(--danger);}
251
+ mark.hl{background:rgba(240,178,50,0.4);color:inherit;border-radius:2px;padding:0 1px;}
252
+ .msg.dimmed{opacity:0.28;}
253
+
254
+ .call-overlay{position:fixed;inset:0;z-index:30;background:rgba(0,0,0,0.9);display:none;align-items:center;justify-content:center;flex-direction:column;text-align:center;padding:24px;}
255
+ .call-overlay.open{display:flex;}
256
+ .call-avatar{width:100px;height:100px;border-radius:50%;background:var(--blurple);display:flex;align-items:center;justify-content:center;font-size:2.2rem;color:#fff;animation:pulseRing 1.6s ease-out infinite;margin-bottom:18px;}
257
+ @keyframes pulseRing{0%{box-shadow:0 0 0 0 rgba(88,101,242,0.55);}70%{box-shadow:0 0 0 28px rgba(88,101,242,0);}100%{box-shadow:0 0 0 0 rgba(88,101,242,0);}}
258
+ .call-peer-name{font-size:1.5rem;font-weight:700;color:var(--text-bright);margin-bottom:4px;}
259
+ .call-status-text{color:var(--text-muted);font-size:0.9rem;margin-bottom:28px;}
260
+ .call-btn-row{display:flex;gap:22px;}
261
+ .round-btn{width:58px;height:58px;border-radius:50%;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:1.4rem;transition:transform .15s;}
262
+ .round-btn:hover{transform:translateY(-2px);}
263
+ .round-btn.accept{background:var(--online);color:#fff;}
264
+ .round-btn.decline, .round-btn.hangup{background:var(--danger);color:#fff;}
265
+ .round-btn.mute, .round-btn.vidtoggle, .round-btn.sharetoggle{background:var(--bg-input);border:1px solid var(--border);color:var(--text-normal);}
266
+ .round-btn.mute.active{background:var(--danger);color:#fff;}
267
+ .round-btn.vidtoggle.active{background:var(--blurple);color:#fff;}
268
+ .round-btn.sharetoggle.active{background:var(--online);color:#fff;}
269
+
270
+ #inCallOverlay{justify-content:flex-end;}
271
+ .in-call-videos{position:relative;width:100%;max-width:640px;flex:1;display:flex;align-items:center;justify-content:center;}
272
+ #remoteVideoEl{width:100%;max-height:60vh;border-radius:12px;background:#1e1f22;object-fit:cover;border:1px solid var(--border);}
273
+ #localVideoEl{position:absolute;bottom:12px;right:12px;width:110px;border-radius:8px;border:1px solid var(--border);background:#1e1f22;object-fit:cover;box-shadow:0 4px 20px rgba(0,0,0,0.5);}
274
+ .in-call-audio-mode #remoteVideoEl, .in-call-audio-mode #localVideoEl{display:none;}
275
+ .call-timer{color:var(--text-muted);font-size:0.82rem;margin:14px 0 18px;}
276
+
277
+ .call-overlay.docked{position:fixed;inset:auto;left:auto;right:16px;bottom:16px;top:auto;width:280px;max-width:calc(100vw - 32px);height:auto;background:var(--bg-chat);border:1px solid var(--border);border-radius:12px;box-shadow:0 12px 32px rgba(0,0,0,0.5);padding:14px;z-index:25;}
278
+ .call-overlay.docked .in-call-videos{max-width:100%;margin-bottom:8px;}
279
+ .call-overlay.docked #remoteVideoEl{max-height:150px;}
280
+ .call-overlay.docked #localVideoEl{width:64px;bottom:8px;right:8px;}
281
+ .call-overlay.docked .call-avatar{width:56px;height:56px;font-size:1.3rem;margin-bottom:8px;}
282
+ .call-overlay.docked .call-peer-name{font-size:0.92rem;margin-bottom:0;}
283
+ .call-overlay.docked .call-timer{font-size:0.72rem;margin:2px 0 10px;}
284
+ .call-overlay.docked .call-btn-row{gap:10px;}
285
+ .call-overlay.docked .round-btn{width:42px;height:42px;font-size:1.05rem;}
286
+ .dock-toggle-btn{position:absolute;top:8px;right:8px;background:var(--bg-input);border:none;color:var(--text-muted);width:26px;height:26px;border-radius:50%;cursor:pointer;font-size:0.85rem;display:flex;align-items:center;justify-content:center;z-index:1;}
287
+ .dock-toggle-btn:hover{background:var(--bg-hover);color:var(--text-bright);}
288
+ #inCallOverlay.open{ pointer-events:none; }
289
+ #inCallOverlay.open > *{ pointer-events:auto; }
290
+ #inCallOverlay:not(.docked){ background:rgba(0,0,0,0.9); }
291
+ #inCallOverlay.docked{ background:transparent; }
292
+
293
+ #onlineCol{width:220px;flex:0 0 auto;background:var(--bg-list);border-left:1px solid var(--border);display:flex;flex-direction:column;min-height:0;}
294
+ #onlineColHeader, #serverMembersHeader{padding:16px 16px 8px;font-size:0.68rem;font-weight:700;letter-spacing:0.4px;text-transform:uppercase;color:var(--text-muted);}
295
+ #onlineColScroll, #serverMembersScroll{flex:1;overflow-y:auto;padding:0 8px 12px;}
296
+ .online-section{flex:1 1 0;min-height:0;display:flex;flex-direction:column;}
297
+ #serverMembersSection{border-top:1px solid var(--border);}
298
+ .mdot{width:9px;height:9px;border-radius:50%;flex:0 0 auto;}
299
+ .mdot.on{background:var(--online);box-shadow:0 0 6px rgba(35,165,90,.7);}
300
+ .mdot.off{background:var(--danger);}
301
+ .online-item.offline .item-name{opacity:.6;}
302
+ .online-item{display:flex;align-items:center;gap:9px;padding:6px 8px;border-radius:4px;cursor:pointer;font-size:0.85rem;color:var(--text-normal);margin-bottom:1px;position:relative;}
303
+ .online-item:hover{background:var(--bg-hover);}
304
+ .online-item .item-name{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
305
+ .online-item .you-tag{font-size:0.68rem;color:var(--text-faint);}
306
+ .online-empty-note{color:var(--text-faint);font-size:0.78rem;padding:10px 8px;text-align:center;}
307
+
308
+ .tutorial-btn{background:transparent;border:none;color:var(--text-muted);padding:6px;border-radius:4px;font-size:1.05rem;cursor:pointer;transition:all .15s;}
309
+ .tutorial-btn:hover{background:var(--bg-hover);color:var(--text-bright);}
310
+ #tutorialModal .modal-card{max-width:440px;}
311
+ .tut-step{display:none;}
312
+ .tut-step.active{display:block;}
313
+ .tut-step h4{margin:0 0 8px;color:var(--text-bright);font-size:1.02rem;}
314
+ .tut-step p{margin:0 0 10px;font-size:0.86rem;color:var(--text-normal);line-height:1.5;}
315
+ .tut-step .tut-glyph{font-size:1.8rem;margin-bottom:8px;display:block;}
316
+ .tut-dots{display:flex;gap:6px;justify-content:center;margin:4px 0 14px;}
317
+ .tut-dot{width:7px;height:7px;border-radius:50%;background:var(--border);cursor:pointer;}
318
+ .tut-dot.active{background:var(--blurple);}
319
+ .tut-nav-row{display:flex;gap:10px;}
320
+ .tut-skip-row{text-align:center;margin-top:8px;}
321
+ .tut-skip-row button{background:transparent;border:none;color:var(--text-faint);font-size:0.76rem;cursor:pointer;text-decoration:underline;}
322
+
323
+ #chanColHeader{display:flex;align-items:center;gap:8px;}
324
+ .notify-btn{background:transparent;border:none;cursor:pointer;font-size:1.05rem;padding:0;line-height:1;}
325
+ .unread-badge{background:var(--danger);color:#fff;border-radius:8px;font-size:0.62rem;min-width:16px;height:16px;line-height:16px;text-align:center;padding:0 4px;font-weight:700;flex:0 0 auto;}
326
+ .rail-badge{position:absolute;right:2px;top:2px;background:var(--danger);color:#fff;border-radius:9px;font-size:0.62rem;min-width:17px;height:17px;line-height:17px;text-align:center;padding:0 4px;font-weight:700;border:2px solid var(--bg-rail);box-sizing:content-box;}
327
+ #toastHost{position:fixed;top:14px;right:14px;z-index:50;display:flex;flex-direction:column;gap:8px;pointer-events:none;}
328
+ .toast{pointer-events:auto;cursor:pointer;width:300px;max-width:calc(100vw - 28px);background:var(--bg-list);border:1px solid var(--border);border-left:4px solid var(--blurple);border-radius:8px;padding:10px 12px;box-shadow:0 8px 28px rgba(0,0,0,.5);animation:toastIn .2s ease;}
329
+ .toast b{display:block;font-size:0.84rem;color:var(--text-bright);margin-bottom:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
330
+ .toast span{display:block;font-size:0.8rem;color:var(--text-normal);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
331
+ @keyframes toastIn{from{transform:translateX(30px);opacity:0;}to{transform:none;opacity:1;}}
332
+ .members-toggle-btn{display:none;background:transparent;border:none;color:var(--text-muted);padding:6px;border-radius:4px;font-size:1.05rem;cursor:pointer;}
333
+ .members-toggle-btn:hover{background:var(--bg-hover);color:var(--text-bright);}
334
+ @media (max-width: 860px){
335
+ #onlineCol{display:none;}
336
+ #onlineCol.mobile-open{display:flex;position:fixed;top:0;right:0;bottom:0;width:240px;z-index:9;box-shadow:-8px 0 28px rgba(0,0,0,.5);}
337
+ .members-toggle-btn{display:inline-flex;}
338
+ }
339
+ @media (max-width: 720px){
340
+ #serverRail{width:56px;}
341
+ .rail-icon{width:42px;height:42px;}
342
+ #chanCol{position:fixed;top:0;left:56px;bottom:0;width:250px;z-index:8;transform:translateX(calc(-100% - 56px));transition:transform .2s ease;}
343
+ #chanCol.mobile-open{transform:translateX(0);}
344
+ .sidebar-toggle-btn{display:inline-flex;}
345
+ .my-profile-btn{display:inline-flex;}
346
+ .list-item .mini-btn{opacity:0.7;}
347
+ .call-overlay.docked{right:10px;bottom:10px;width:220px;}
348
+ }
349
+
350
+ #commandsScreen,#friendsScreen{position:fixed;inset:0;z-index:900;overflow:auto;background:var(--bg-chat);color:var(--text);padding:clamp(14px,4vw,36px);}
351
+ #friendsScreen[hidden],#commandsScreen[hidden]{display:none!important;}
352
+ #friendsScreen:not([hidden]){display:block;width:100%;height:100%;box-sizing:border-box;}
353
+ #commandsScreen [hidden]{display:none!important;}
354
+ .commands-wrap{max-width:960px;margin:auto;}
355
+ .commands-header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:20px;}
356
+ .commands-header h1{font-size:clamp(1.25rem,4vw,1.8rem);}
357
+ .commands-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,340px),1fr));gap:16px;}
358
+ .commands-grid>div{background:var(--bg-list);border-radius:12px;padding:16px!important;min-width:0;}
359
+ .commands-grid h2{font-size:1rem;margin:0 0 12px;}
360
+ .commands-grid p{margin:8px 0;overflow-wrap:anywhere;}
361
+ .commands-grid hr{border:0;border-top:1px solid var(--bg-input);margin:18px 0;}
362
+ #commandsScreen button,#backFromFriends{background:var(--blurple);color:#fff;border:0;border-radius:6px;padding:8px 12px;cursor:pointer;margin:4px 2px;}
363
+ #commandsScreen input:not([type=checkbox]){min-width:0;max-width:100%;background:var(--bg-input);color:inherit;border:0;border-radius:6px;padding:8px;}
364
+ #adminPermissionChoices{margin:8px 0;}
365
+ #adminPermissionChoices label{padding:4px 0;}
366
+ #friendsPanel{background:var(--bg-list);border-radius:12px;padding:16px;}
367
+ #friendsPanel #pinnedRailList{flex-direction:row;flex-wrap:wrap;margin:8px;}
368
+
369
+ /* Keep the caret inside editable fields, including browser caret-browsing mode. */
370
+ body {caret-color:transparent;cursor:default;}
371
+ input,textarea,[contenteditable="true"] {caret-color:auto;cursor:text;user-select:text;}
372
+ button,a,label,select,input[type="checkbox"],input[type="color"],input[type="file"] {cursor:pointer;}
373
+ </style>
374
+ </head>
375
+ <body>
376
+ <div id="app">
377
+
378
+ <!-- AUTH SCREEN -->
379
+ <div id="authScreen">
380
+ <div class="logo-mark">B</div>
381
+ <div class="logo-word">Bored Chat</div>
382
+ <div class="tagline">Where your crew hangs out.</div>
383
+ <div class="auth-card">
384
+ <div class="tabs">
385
+ <button class="tab-btn active" id="tabLogin" onclick="switchTab('login')">Log In</button>
386
+ <button class="tab-btn" id="tabRegister" onclick="switchTab('register')">Create Account</button>
387
+ </div>
388
+ <div id="authForm">
389
+ <div class="field"><label>Username</label><input type="text" id="usernameInput" autocomplete="username" maxlength="20" placeholder="e.g. nightowl" onkeydown="if(event.key==='Enter')handleAuthSubmit(event)"></div>
390
+ <div class="field"><label>Password</label><input type="password" id="passwordInput" autocomplete="current-password" placeholder="••••••••" onkeydown="if(event.key==='Enter')handleAuthSubmit(event)"></div>
391
+ <div class="field" id="firstNameField" hidden><label for="firstNameInput">First name only</label><input type="text" id="firstNameInput" autocomplete="given-name" maxlength="80" onkeydown="if(event.key==='Enter')handleAuthSubmit(event)"></div>
392
+ <button type="button" class="primary-btn" id="submitBtn" onclick="handleAuthSubmit(event)">Continue</button>
393
+ <div class="auth-msg" id="authMsg"></div>
394
+ </div>
395
+ <button class="ghost-btn" onclick="openTutorial()" type="button">📖 How does this work?</button>
396
+ </div>
397
+ <a class="yt-banner" href="https://www.youtube.com/@ShadowDefender2" target="_blank" rel="noopener">
398
+ <span class="yt-icon"><svg viewBox="0 0 24 24"><path d="M8 5v14l11-7z"></path></svg></span>
399
+ <span class="yt-text"><b>Subscribe to ShadowDefender2</b><br><span>on YouTube — join the crew 🔔</span></span>
400
+ </a>
401
+ </div>
402
+
403
+
404
+ <!-- CHAT SCREEN -->
405
+ <section id="commandsScreen" hidden aria-labelledby="commandsTitle">
406
+ <div class="commands-wrap">
407
+ <header class="commands-header">
408
+ <h1 id="commandsTitle">Admin commands</h1>
409
+ <button type="button" id="backToChat" onclick="closeCommandsScreen()">Back to chat</button>
410
+ </header>
411
+ <div class="commands-grid">
412
+ <div id="ownerCommandPanel" hidden style="padding:8px;">
413
+ <h2>Admin permissions</h2>
414
+ <input id="adminPermissionUser" placeholder="Admin username" maxlength="20" aria-label="Admin username" style="width:100%;">
415
+ <button type="button" onclick="editAdminPermissions('load')">Load</button>
416
+ <div id="adminPermissionChoices"></div>
417
+ <button type="button" onclick="editAdminPermissions('save')">Save admin</button>
418
+ <button type="button" onclick="editAdminPermissions('remove')">Remove admin</button>
419
+ <div id="adminPermissionMessage" role="status"></div>
420
+ <hr>
421
+ <h2>Look up a first name</h2>
422
+ <div>
423
+ <input id="firstNameLookup" aria-label="Username to look up" placeholder="Username" maxlength="20" onkeydown="if(event.key==='Enter') lookupFirstName(event)">
424
+ <button type="button" onclick="lookupFirstName(event)">Look up</button>
425
+ </div>
426
+ <p id="firstNameLookupResult" role="status"></p>
427
+ <hr>
428
+ <h2>Admins</h2><p>Click an admin’s name to see their command history.</p>
429
+ <div id="auditAdmins"></div>
430
+ <h2>Banned-word mutes</h2><div id="wordMuteList"></div><h2>Spam mutes</h2><div id="spamMuteList"></div>
431
+ <h2>Banned words</h2>
432
+ <p id="bannedWordList" role="status"></p>
433
+ <button type="button" onclick="editBannedWords()">Edit banned words</button>
434
+ <p>These words mute you in that public server until the owner unmutes you. Fancy letters are converted to plain letters before sending.</p>
435
+ <hr>
436
+ <button type="button" onclick="setPanic(true)">Panic mode · Ban all</button>
437
+ <button type="button" onclick="setPanic(false)">End panic mode</button>
438
+ <ol id="adminActivityList" style="max-height:16rem;overflow:auto;padding-left:1.4rem;" aria-live="polite"></ol>
439
+ </div>
440
+ <div id="modBlock" style="display:none;">
441
+ <h2>Moderation</h2>
442
+ <p id="availableAdminCommands"></p>
443
+ <div class="add-friend-row">
444
+ <input type="text" id="modUsernameInput" placeholder="Username…" maxlength="20" onkeydown="if(event.key==='Enter')modActionByUsername('ban')">
445
+ <button style="background:var(--danger);" data-mod-permission="ban" onclick="modActionByUsername('ban')">Ban</button>
446
+ <button style="background:var(--gold);color:#1e1f22;" data-mod-permission="mute" onclick="modActionByUsername('mute')">Mute</button>
447
+ </div>
448
+ <div class="add-friend-row">
449
+ <button style="background:var(--online);flex:1;padding:8px 0;" data-mod-permission="unban" onclick="modActionByUsername('unban')">Unban username</button>
450
+ <button style="background:var(--bg-input);flex:1;padding:8px 0;" data-mod-permission="unmute" onclick="modActionByUsername('unmute')">Unmute username</button>
451
+ </div>
452
+ <div>
453
+ <input id="panelCommandInput" aria-label="Command" placeholder="/cmd" onkeydown="if(event.key==='Enter') submitPanelCommand(event)">
454
+ <button type="button" onclick="submitPanelCommand(event)">Run</button>
455
+ </div>
456
+ <div class="add-friend-msg" id="modUsernameMsg" role="status"></div>
457
+ <div class="sidebar-section-title"><span>Muted</span></div>
458
+ <div id="mutedAdminList"></div>
459
+ <div class="sidebar-section-title"><span>Banned</span></div>
460
+ <div id="bannedAdminList"></div>
461
+ </div>
462
+ </div>
463
+ </div>
464
+ </section>
465
+
466
+ <section id="friendsScreen" hidden aria-labelledby="friendsTitle">
467
+ <div class="commands-wrap">
468
+ <header class="commands-header">
469
+ <h1 id="friendsTitle">Friends</h1>
470
+ <button type="button" id="backFromFriends" onclick="closeFriendsScreen()">Back to chat</button>
471
+ </header>
472
+ <div id="friendsPanel">
473
+ <div class="add-friend-row">
474
+ <input type="text" id="addFriendInput" placeholder="Add friend by username…" maxlength="20" onkeydown="if(event.key==='Enter')sendFriendRequestFromInput()">
475
+ <button onclick="sendFriendRequestFromInput()">Add</button>
476
+ </div>
477
+ <div class="add-friend-msg" id="addFriendMsg"></div>
478
+
479
+ <div id="incomingRequestsBlock" style="display:none;"><div class="sidebar-section-title">Requests</div><div id="incomingRequestsList"></div></div>
480
+ <div id="outgoingRequestsBlock" style="display:none;"><div class="sidebar-section-title">Pending</div><div id="outgoingRequestsList"></div></div>
481
+
482
+ <div class="sidebar-section-title"><span>All friends</span></div>
483
+ <div id="pinnedRailList"></div>
484
+ <div id="friendsList"></div>
485
+
486
+ <div id="blockedBlock" style="display:none;"><div class="sidebar-section-title"><span>Blocked</span></div><div id="blockedList"></div></div>
487
+
488
+ </div>
489
+ </div>
490
+ </section>
491
+
492
+ <div id="chatScreen">
493
+
494
+ <div id="serverRail">
495
+ <div class="rail-icon active" id="railHome" title="Home" onclick="goHome()">B</div>
496
+ <div class="rail-divider" id="pinnedDivider" style="display:none;"></div>
497
+ <div class="rail-divider"></div>
498
+ <button type="button" class="rail-icon rail-shortcut" id="friendsButton" title="Friends" aria-label="Friends" onclick="openFriendsScreen()">👥<span class="badge-dot" id="incomingReqBadge" style="display:none;"></span></button>
499
+ <button type="button" class="rail-icon rail-shortcut" id="adminBadge" title="Commands" aria-label="Commands" style="display:none;" onclick="openCommandsScreen()">⚙</button>
500
+ <div class="rail-divider" role="separator" aria-label="Servers"></div>
501
+ <div id="serverRailList"></div>
502
+ <div class="rail-icon rail-add" title="Add a server" onclick="openServerModal()">+</div>
503
+ </div>
504
+
505
+ <div id="chanCol">
506
+ <div id="chanColHeader"><button class="notify-btn" id="notifyBtn" hidden style="display:none" title="Notifications">🔔</button><span id="headerUnread"></span><span id="chanColTitle">Bored Chat</span></div>
507
+ <div id="chanColBanner"></div>
508
+ <div id="chanColDesc"></div>
509
+
510
+ <div id="panelScroll">
511
+ <div id="groupsPanel">
512
+ <div class="general-nav-btn-wrap" style="padding:0 8px 6px;">
513
+ <div class="list-item" id="generalNavBtn" onclick="openGeneralChat()" style="margin:0 0 6px;">
514
+ <span class="hash">#</span><span class="item-name">general</span><span id="generalUnread"></span>
515
+ </div>
516
+ </div>
517
+
518
+ <div id="serverActions" style="display:none;padding:4px 8px 0;">
519
+ <div style="display:flex;gap:6px;">
520
+ <button class="chan-action-btn" style="flex:1;" onclick="openServerInvite()">🔗 Invite</button>
521
+ <button class="chan-action-btn" style="flex:1;" onclick="openServerSettings()">⚙️ Settings</button>
522
+ </div>
523
+ <div style="display:flex;gap:6px;margin-top:6px;">
524
+ <button class="chan-action-btn" id="muteServerBtn" style="flex:1;" onclick="toggleMuteCurrentServer()">🔔 Server alerts on</button>
525
+ </div>
526
+ <div style="display:flex;gap:6px;margin-top:6px;">
527
+ <button class="chan-action-btn warn" style="flex:1;" onclick="leaveCurrentServer()">Leave</button>
528
+ <button class="chan-action-btn" id="deleteServerBtn" style="flex:1;display:none;color:var(--danger);" onclick="deleteCurrentServer()">Delete</button>
529
+ </div>
530
+ </div>
531
+ <div class="add-friend-row" style="margin-top:4px;">
532
+ <input type="text" id="joinCodeInput" placeholder="Join with an invite code…" maxlength="12" onkeydown="if(event.key==='Enter')joinChannelByCode()">
533
+ <button onclick="joinChannelByCode()">Join</button>
534
+ </div>
535
+ <div class="add-friend-msg" id="joinCodeMsg"></div>
536
+
537
+ <div id="publicChannelsBlock">
538
+ <div class="sidebar-section-title"><span>Public Servers</span></div>
539
+ <div id="publicChannelsList"></div>
540
+ </div>
541
+
542
+ <div class="sidebar-section-title">
543
+ <span id="channelsTitle">Your Channels</span>
544
+ <button class="new-group-btn" onclick="openNewGroupModal()" title="Create server">+</button>
545
+ </div>
546
+ <div id="groupsList"></div>
547
+ </div>
548
+ </div>
549
+
550
+ <div class="voice-status-bar" id="voiceStatusBar">
551
+ 🎙️ <span class="vname" id="voiceStatusName"></span>
552
+ <button onclick="leaveVoiceChannel()">Leave</button>
553
+ </div>
554
+
555
+ <div id="userBar">
556
+ <div class="user-block" onclick="openProfileModal()">
557
+ <span id="currentUserAvatarSlot"></span>
558
+ <div class="user-info"><b id="userBarName"></b><span id="userBarStatus">Online</span></div>
559
+ </div>
560
+
561
+ <button class="bar-icon-btn" onclick="logout()" title="Log out">⏻</button>
562
+ </div>
563
+ </div>
564
+
565
+ <div id="chatMain">
566
+ <div class="chat-header">
567
+ <div class="header-left">
568
+ <button class="sidebar-toggle-btn" onclick="toggleSidebarMobile()">☰<span id="mobileUnread"></span></button>
569
+ <div class="current-chat-label-wrap">
570
+ <span class="current-chat-label" id="currentChatLabel"></span>
571
+ <span class="current-chat-sub" id="currentChatSub"></span><label id="staffOnlyControl" hidden style="font-size:12px;margin-top:6px;"><input id="staffOnlyCheckbox" type="checkbox" onchange="setStaffOnlyChannel(this.checked)"> Only owner and admins can type</label>
572
+ </div>
573
+ </div>
574
+ <div class="header-right">
575
+ <button class="chan-action-btn" id="headerMuteBtn" style="display:none;" onclick="toggleMuteCurrentChat()" title="Mute or unmute this chat">🔔 Alerts on</button>
576
+ <button class="chan-action-btn" id="headerAddPeopleBtn" style="display:none;" onclick="openAddMemberModal()">+ Add people</button>
577
+ <button class="chan-action-btn" id="headerRenameBtn" style="display:none;" onclick="renameCurrentChannel()">✏️ Rename</button>
578
+ <button class="chan-action-btn" id="headerInviteBtn" style="display:none;" onclick="openInviteModal()">🔗 Invite code</button>
579
+ <button class="chan-action-btn warn" id="headerLeaveBtn" style="display:none;" onclick="leaveCurrentChannel()">Leave</button>
580
+ <button class="call-header-btn" id="headerCallAudioBtn" style="display:none;" onclick="startCallWithCurrentFriend('audio')" title="Voice call">📞</button>
581
+ <button class="call-header-btn video" id="headerCallVideoBtn" style="display:none;" onclick="startCallWithCurrentFriend('video')" title="Video call">🎥</button>
582
+ <button class="members-toggle-btn" onclick="document.getElementById('onlineCol').classList.toggle('mobile-open')" title="Show online users and server members">👥</button>
583
+ <button class="search-btn" id="searchToggleBtn" onclick="toggleSearch()" title="Search messages">🔍</button>
584
+ <button class="tutorial-btn" onclick="openTutorial()" title="How this works">❓</button>
585
+ <span class="conn-pill" id="connPill">connecting…</span>
586
+ <button class="my-profile-btn" onclick="openProfileModal()" title="Profile">👤</button>
587
+ </div>
588
+ </div>
589
+
590
+ <div id="searchBar">
591
+ <input type="text" id="searchInput" placeholder="Search this server…" oninput="handleSearchInput()">
592
+ <span id="searchCount"></span>
593
+ <button class="search-close-btn" onclick="closeSearch()" title="Close search">✕</button>
594
+ </div>
595
+
596
+ <div class="promo-strip">
597
+ 🎥 Enjoying Bored Chat? Check out
598
+ <a href="https://www.youtube.com/@ShadowDefender2" target="_blank" rel="noopener">ShadowDefender2 on YouTube</a> and subscribe.
599
+ </div>
600
+
601
+ <div class="voice-panel" id="voicePanel">
602
+ <button class="voice-join-btn" id="voiceJoinBtn" onclick="voiceJoinBtnClick()">🎙️ Join Voice</button><button id="voiceVideoBtn" class="voice-join-btn" onclick="joinVoiceChannel(currentChatId, true)" hidden>🎥 Join with video</button><div id="privateVideoTiles"></div>
603
+ <div id="voiceChipsRow" style="display:flex;gap:8px;flex-wrap:wrap;flex:1;"></div>
604
+ </div>
605
+
606
+ <div id="messages"></div>
607
+ <div id="typingBar"></div>
608
+ <div class="composer-note" id="composerNote" style="display:none;">You're muted, so you can't send messages right now.</div>
609
+
610
+ <div id="composer">
611
+ <button id="attachBtn" onclick="openAttachMediaModal()" title="Upload an image" hidden>📎</button>
612
+ <div id="msgInputWrap">
613
+ <input type="text" id="msgInput" placeholder="Message…" maxlength="500" onkeydown="if(event.key==='Enter')sendMessage()">
614
+ <button id="sendBtn" onclick="sendMessage()">Send</button>
615
+ </div>
616
+ </div>
617
+ </div>
618
+
619
+ <div id="onlineCol">
620
+ <div class="online-section" id="onlineSection">
621
+ <div id="onlineColHeader">Online — <span id="onlineCount">0</span></div>
622
+ <div id="onlineColScroll"></div>
623
+ </div>
624
+ <div class="online-section" id="serverMembersSection" style="display:none;">
625
+ <div id="serverMembersHeader">Server members — <span id="serverMembersCount"></span></div>
626
+ <div id="serverMembersScroll"></div>
627
+ </div>
628
+ </div>
629
+ </div>
630
+
631
+ <!-- ADD SERVER MODAL -->
632
+ <div class="modal-overlay" id="serverModal">
633
+ <div class="modal-card">
634
+ <h3>Add a Server</h3>
635
+ <p class="sub">Create your own private server, or join one with an invite code.</p>
636
+ <input type="text" id="newServerName" maxlength="24" placeholder="Server name" onkeydown="if(event.key==='Enter')createServer()">
637
+ <button class="primary-btn" style="margin-top:0;" onclick="createServer()">Create server</button>
638
+ <p class="sub" style="margin:18px 0 8px;">Or join an existing server</p>
639
+ <input type="text" id="joinServerCode" maxlength="12" placeholder="Invite code" onkeydown="if(event.key==='Enter')joinServerByCode()">
640
+ <button class="ghost-btn" style="margin-top:0;" onclick="joinServerByCode()">Join server</button>
641
+ <div class="modal-err" id="serverErr" style="margin-top:10px;"></div>
642
+ <button class="ghost-btn" style="margin-top:0;" onclick="closeServerModal()">Close</button>
643
+ </div>
644
+ </div>
645
+
646
+ <!-- NEW CHANNEL MODAL -->
647
+ <div class="modal-overlay" id="newGroupModal">
648
+ <div class="modal-card">
649
+ <h3>Create a Channel</h3>
650
+ <p class="sub">Anyone in a server can invite more people later.</p>
651
+ <div class="type-choice" id="newGroupTypeChoice" style="display:none;">
652
+ <button id="typeBtnPrivate" class="active" onclick="setNewChannelType('group')">Invite only</button>
653
+ <button id="typeBtnPublic" onclick="setNewChannelType('public')">Public (like #general)</button>
654
+ </div>
655
+ <input type="text" id="newGroupName" maxlength="24" placeholder="Channel name">
656
+ <div id="newGroupPickerWrap"><div class="member-picker" id="newGroupMemberPicker"></div></div>
657
+ <p class="modal-note" id="newGroupNote">You'll get an invite code once it's created, so you can add people who aren't friends yet.</p>
658
+ <div class="modal-err" id="newGroupErr"></div>
659
+ <div class="modal-actions">
660
+ <button class="ghost-btn" style="margin-top:0;" onclick="closeNewGroupModal()">Cancel</button>
661
+ <button class="primary-btn" style="margin-top:0;" onclick="submitNewGroup()">Create server</button>
662
+ </div>
663
+ </div>
664
+ </div>
665
+
666
+ <!-- ADD MEMBER MODAL -->
667
+ <div class="modal-overlay" id="addMemberModal">
668
+ <div class="modal-card">
669
+ <h3>Add people</h3>
670
+ <p class="sub">Add anyone by username, or tick friends from the list.</p>
671
+ <div class="inline-row">
672
+ <input type="text" id="addByUsernameInput" placeholder="Username" maxlength="20" onkeydown="if(event.key==='Enter')addMemberByUsername()">
673
+ <button onclick="addMemberByUsername()">Add</button>
674
+ </div>
675
+ <div class="member-picker" id="addMemberPicker"></div>
676
+ <div class="modal-err" id="addMemberErr"></div>
677
+ <div class="modal-actions">
678
+ <button class="ghost-btn" style="margin-top:0;" onclick="closeAddMemberModal()">Done</button>
679
+ <button class="primary-btn" style="margin-top:0;" onclick="submitAddMembers()">Add selected</button>
680
+ </div>
681
+ </div>
682
+ </div>
683
+
684
+ <!-- INVITE CODE MODAL -->
685
+ <div class="modal-overlay" id="inviteModal">
686
+ <div class="modal-card">
687
+ <h3>Invite code</h3>
688
+ <p class="sub">Anyone with this code can join — they don't need to be your friend.</p>
689
+ <div class="code-box" id="inviteCodeBox">------</div>
690
+ <div class="modal-err" id="inviteErr"></div>
691
+ <div class="modal-actions">
692
+ <button class="ghost-btn" style="margin-top:0;" onclick="copyInviteCode()">Copy code</button>
693
+ <button class="ghost-btn" style="margin-top:0;" onclick="regenerateInviteCode()">New code</button>
694
+ </div>
695
+ <div class="modal-actions"><button class="primary-btn" style="margin-top:0;" onclick="closeInviteModal()">Done</button></div>
696
+ </div>
697
+ </div>
698
+
699
+ <!-- SERVER SETTINGS MODAL -->
700
+ <div class="modal-overlay" id="serverSettingsModal">
701
+ <div class="modal-card">
702
+ <h3>Server Settings</h3>
703
+ <p class="sub" id="serverSettingsSub">Make this server yours.</p>
704
+
705
+ <div id="serverSettingsOwnerFields">
706
+ <div class="field"><label>Server name</label><input type="text" id="serverSettingsName" maxlength="24" placeholder="Server name"></div>
707
+ <div class="field"><label>Description</label><input type="text" id="serverSettingsDesc" maxlength="100" placeholder="What's this server about?"></div>
708
+ <div class="field"><label>Icon emoji (used when there's no image)</label><input type="text" id="serverSettingsEmoji" maxlength="4" placeholder="🎮"></div>
709
+ <div class="field"><label>Icon image (URL or upload)</label><input type="text" id="serverSettingsIcon" placeholder="https://example.com/icon.png"></div>
710
+ <div class="upload-row">…or upload from your device<input type="file" accept="image/*" onchange="loadServerImageFile(this,'serverSettingsIcon',160,160)"></div>
711
+ <div class="field"><label>Banner image (URL or upload)</label><input type="text" id="serverSettingsBanner" placeholder="https://example.com/banner.png"></div>
712
+ <div class="upload-row">…or upload from your device — no banner image? Your accent color makes a gradient banner<input type="file" accept="image/*" onchange="loadServerImageFile(this,'serverSettingsBanner',800,260)"></div>
713
+ <div class="field"><label>Accent color</label><input type="color" id="serverSettingsColor" value="#5865f2"></div>
714
+ <button class="primary-btn" style="margin-top:0;" onclick="saveServerSettings()">Save changes</button>
715
+ </div>
716
+
717
+ <div class="sidebar-section-title" style="padding:0;margin:16px 0 2px;"><span>Members</span></div>
718
+ <div class="member-picker" id="serverMembersList"></div>
719
+ <div class="modal-err" id="serverSettingsErr"></div>
720
+
721
+ <div class="modal-actions">
722
+ <button class="ghost-btn" style="margin-top:0;" onclick="openServerInviteFromSettings()">🔗 Invite</button>
723
+ <button class="primary-btn" style="margin-top:0;" onclick="closeServerSettings()">Done</button>
724
+ </div>
725
+ <div class="modal-actions">
726
+ <button class="ghost-btn" style="margin-top:0;color:var(--danger);" onclick="leaveCurrentServerFromSettings()">Leave server</button>
727
+ <button class="ghost-btn" id="serverSettingsDeleteBtn" style="margin-top:0;color:var(--danger);display:none;" onclick="deleteCurrentServerFromSettings()">Delete server</button>
728
+ </div>
729
+ </div>
730
+ </div>
731
+
732
+ <!-- PROFILE MODAL -->
733
+ <div class="modal-overlay" id="profileModal">
734
+ <div class="modal-card">
735
+ <h3>Profile Picture</h3>
736
+ <p class="sub">Paste a direct image URL (jpg/png/webp). Leave blank to use your initial instead.</p>
737
+ <input type="text" id="profileAvatarInput" placeholder="https://example.com/avatar.png"><input id="avatarFile" type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label="Upload profile picture">
738
+ <div class="modal-err" id="profileErr"></div>
739
+ <div class="modal-actions">
740
+ <button class="ghost-btn" style="margin-top:0;" onclick="closeProfileModal()">Cancel</button>
741
+ <button class="primary-btn" style="margin-top:0;" onclick="submitProfileAvatar()">Save</button>
742
+ </div>
743
+ </div>
744
+ </div>
745
+
746
+ <!-- ATTACH MEDIA MODAL -->
747
+ <div class="modal-overlay" id="attachMediaModal">
748
+ <div class="modal-card">
749
+ <h3>Upload an Image</h3>
750
+ <p class="sub">Pick a PNG, JPEG, WebP, or GIF up to 200 KB, or paste a direct HTTPS image link.</p>
751
+ <input type="file" id="attachMediaUrl" accept="image/png,image/jpeg,image/webp,image/gif">
752
+ <input type="url" id="attachImageLink" aria-label="Direct image link" placeholder="https://… (image link)" maxlength="2048">
753
+ <input type="text" id="attachMediaCaption" placeholder="Caption (optional)" maxlength="500">
754
+ <div class="modal-err" id="attachMediaErr"></div>
755
+ <div class="modal-actions">
756
+ <button class="ghost-btn" style="margin-top:0;" onclick="closeAttachMediaModal()">Cancel</button>
757
+ <button class="primary-btn" style="margin-top:0;" onclick="submitAttachMedia()">Send</button>
758
+ </div>
759
+ </div>
760
+ </div>
761
+
762
+ <!-- TUTORIAL MODAL -->
763
+ <div class="modal-overlay" id="tutorialModal">
764
+ <div class="modal-card">
765
+ <div id="tutSteps">
766
+ <div class="tut-step active" data-step="0"><span class="tut-glyph">👋</span><h4>Welcome to Bored Chat</h4><p>A quick tour of everything: friends, servers, notifications, calls and the rules. Click Next, or skip any time.</p></div>
767
+ <div class="tut-step" data-step="1"><span class="tut-glyph">👥</span><h4>Friends &amp; DMs</h4><p>Add someone by username in the Friends tab. Once they accept, they show up under Direct Messages. Press 📌 next to a friend to pin them to the left bar under Home — right-click a pinned friend to unpin.</p></div>
768
+ <div class="tut-step" data-step="2"><span class="tut-glyph">#️⃣</span><h4>Channels</h4><p>#general is open to everyone. In the Channels tab you can make invite-only channels and share the invite code. Channels inside a server are for that server's members only.</p></div>
769
+ <div class="tut-step" data-step="3"><span class="tut-glyph">🔔</span><h4>Notifications</h4><p>Every new message notifies you: a beep, a pop-up and a red unread number. The 🔔 at the top left (next to Bored Chat) turns all notifications on or off, and its red number is your total unread. To silence one chat press <b>🔔 Alerts on</b> in the chat's top bar; to silence a whole server press <b>🔔 Server alerts on</b> in the server sidebar. Muted chats show 🔕. Mutes are saved in this browser, and notifications only work while the page is open.</p></div>
770
+ <div class="tut-step" data-step="4"><span class="tut-glyph">📞</span><h4>Calls</h4><p>Call a friend with the 📞 or 🎥 buttons. While on a call click ⤢ to shrink the call window into a small floating bar so you can keep chatting.</p></div>
771
+ <div class="tut-step" data-step="5"><span class="tut-glyph">🖥️</span><h4>Screen sharing</h4><p>During any call, hit the 🖥️ button to share your screen instead of your camera. Click it again to switch back.</p></div>
772
+ <div class="tut-step" data-step="6"><span class="tut-glyph">🎙️</span><h4>Voice channels</h4><p>Open any channel and click “Join Voice” to hop into a live group voice chat with everyone else in that channel.</p></div>
773
+ <div class="tut-step" data-step="7"><span class="tut-glyph">🔒</span><h4>Private servers</h4><p>Servers are invite-only and enforced by the database — only members can see them, not even the site owner. Server owners can press ⚙️ Settings to set a name, description, emoji or image icon, a banner (paste a link or upload a file) and an accent color that recolors the app while you're in that server.</p></div>
774
+ <div class="tut-step" data-step="8"><span class="tut-glyph">🟢</span><h4>Who's online</h4><p>The right side has two halves. The top shows everyone online right now. When you're inside a server, the bottom half lists that server's members: green dot = online, red dot = offline. On a small window tap 👥 in the top bar to open it.</p></div>
775
+ <div class="tut-step" data-step="9"><span class="tut-glyph">🚫</span><h4>Rules</h4><p>Keep it clean. Slurs and strong swearing are blocked, and saying them gets you banned automatically. Bans follow you: a banned device or connection can't make new accounts, and clearing cookies won't help.</p></div>
776
+ <div class="tut-step" data-step="10" data-owner="1"><span class="tut-glyph">👑</span><h4>Owner tools</h4><p>Friends tab → “Ban / mute by username” has Ban, Mute, Unban username and Unmute username. In any chat box you can type <b>/ban name</b>, <b>/unban name</b>, <b>/mute name</b> or <b>/unmute name</b>. Each browser tab keeps its own login, so you can test with a second account in another tab.</p></div>
777
+ </div>
778
+ <div class="tut-dots" id="tutDots"></div>
779
+ <div class="tut-nav-row">
780
+ <button class="ghost-btn" style="margin-top:0;" id="tutBackBtn" onclick="tutorialBack()">Back</button>
781
+ <button class="primary-btn" style="margin-top:0;" id="tutNextBtn" onclick="tutorialNext()">Next</button>
782
+ </div>
783
+ <div class="tut-skip-row"><button onclick="closeTutorial()">Skip / close</button></div>
784
+ </div>
785
+ </div>
786
+
787
+ <!-- CALL OVERLAYS -->
788
+ <div class="call-overlay" id="incomingCallOverlay">
789
+ <div class="call-avatar" id="incomingCallAvatar">📞</div>
790
+ <div class="call-peer-name" id="incomingCallName"></div>
791
+ <div class="call-status-text" id="incomingCallStatus">is calling you…</div>
792
+ <div class="call-btn-row">
793
+ <button class="round-btn decline" onclick="declineIncomingCall()" title="Decline">✕</button>
794
+ <button class="round-btn accept" onclick="acceptIncomingCall()" title="Accept">✓</button>
795
+ </div>
796
+ </div>
797
+ <div class="call-overlay" id="outgoingCallOverlay">
798
+ <div class="call-avatar" id="outgoingCallAvatar">📞</div>
799
+ <div class="call-peer-name" id="outgoingCallName"></div>
800
+ <div class="call-status-text" id="outgoingCallStatus">Ringing…</div>
801
+ <div class="call-btn-row"><button class="round-btn hangup" onclick="cancelOutgoingCall()" title="Cancel">✕</button></div>
802
+ </div>
803
+ <div class="call-overlay" id="inCallOverlay">
804
+ <button class="dock-toggle-btn" id="dockToggleBtn" onclick="toggleCallDocked()" title="Shrink / expand call window">⤢</button>
805
+ <div class="in-call-videos">
806
+ <video id="remoteVideoEl" autoplay playsinline></video>
807
+ <video id="localVideoEl" autoplay playsinline muted></video>
808
+ </div>
809
+ <div class="call-avatar" id="inCallAudioAvatar" style="display:none;">🎙️</div>
810
+ <div class="call-peer-name" id="inCallName"></div>
811
+ <div class="call-timer" id="inCallTimer">00:00</div>
812
+ <div class="call-btn-row">
813
+ <button class="round-btn mute" id="muteBtn" onclick="toggleMute()" title="Mute">🎤</button>
814
+ <button class="round-btn vidtoggle" id="vidToggleBtn" onclick="toggleVideo()" title="Toggle video" style="display:none;">🎥</button>
815
+ <button class="round-btn sharetoggle" id="shareToggleBtn" onclick="toggleScreenShare()" title="Share screen">🖥️</button>
816
+ <button class="round-btn hangup" onclick="endCall()" title="Hang up">☎</button>
817
+ </div>
818
+ </div>
819
+
820
+ <div id="toastHost"></div>
821
+ <div id="voiceAudioContainer" style="display:none;"></div>
822
+ </div>
823
+
824
+ <script>
825
+ /* =========================================================
826
+ FIREBASE CONFIG
827
+ ========================================================= */
828
+ const firebaseConfig = {
829
+ apiKey: "AIzaSyCqfKnFXqgOpw2PDZe99ceLidTPahj-gCM",
830
+ authDomain: "chat12412412.firebaseapp.com",
831
+ databaseURL: "https://chat12412412-default-rtdb.firebaseio.com/",
832
+ projectId: "chat12412412",
833
+ storageBucket: "chat12412412.firebasestorage.app",
834
+ messagingSenderId: "690794971369",
835
+ appId: "1:690794971369:web:05972a70431bb6519db078"
836
+ };
837
+ firebase.initializeApp(firebaseConfig);
838
+ const db = firebase.database();
839
+ const auth = firebase.auth();
840
+ // Keep the login per TAB, not per browser: logging into another account in a second tab used to sign
841
+ // the first tab out underneath you (which made owner actions fail with "permission denied").
842
+ const authReady = auth.setPersistence(firebase.auth.Auth.Persistence.SESSION).catch(() => {});
843
+ let myUid = null;
844
+
845
+ const PANIC_MESSAGE = '😂 NO. THIS IS PANIC MODE.';
846
+ const GENERAL_CHAT_ID = 'general';
847
+ const ICE_SERVERS = [{ urls: ['stun:stun.l.google.com:19302', 'stun:stun1.l.google.com:19302'] }];
848
+ const AVATAR_COLORS = ['#5865f2','#eb459e','#faa61a','#23a55a','#f23f42','#3ba55d','#5865f2'];
849
+
850
+ let currentUser = null, myKey = null, isAdmin = false;
851
+ auth.onAuthStateChanged((u) => {
852
+ if(currentUser && myUid && (!u || u.uid !== myUid)){
853
+ alert('You were signed out because this account was signed in somewhere else. Please log in again.');
854
+ location.reload();
855
+ }
856
+ });
857
+ let authMode = 'login', needInitialChat = false;
858
+ let serversCache = {}, currentServerId = null, inviteModalServerId = null;
859
+
860
+ let friendsCache = {}, incomingRequestsCache = {}, outgoingRequestsCache = {}, blockedCache = {};
861
+ let chatsMetaCache = {}, nicknamesCache = {}, statusCache = {}, avatarsCache = {};
862
+ let voiceParticipantsAllCache = {}, mutedCache = {}, bannedCache = {}, pinnedCache = {};
863
+
864
+ let currentChatId = null, currentChatMeta = null, currentMessagesList = [], searchQuery = '';
865
+
866
+ let friendsRef=null, incomingReqRef=null, outgoingReqRef=null, blockedRef=null, nicknamesRef=null,
867
+ statusRef=null, avatarsRef=null, myStatusRef=null, mutedRef=null, bannedRef=null, pinnedRef=null;
868
+ let messagesRef=null, messagesListener=null, typingRef=null, typingListener=null;
869
+ let typingSelfTimeout=null, iAmTyping=false, incomingCallRef=null;
870
+
871
+ /* ---------- helpers ---------- */
872
+ function sanitizeUsernameKey(u){ return u.toLowerCase().trim().replace(/[.#$\[\]\/\s]/g, '_'); }
873
+ function dmChatId(a, b){ const p=[a,b].sort(); return 'dm_' + p[0] + '__' + p[1]; }
874
+ function pairId(a, b){ const p=[a,b].sort(); return p[0] + '__' + p[1]; }
875
+ async function hashPassword(s){
876
+ const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s));
877
+ return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2,'0')).join('');
878
+ }
879
+ function escapeHtml(str){ const d=document.createElement('div'); d.textContent=str; return d.innerHTML.replace(/"/g, '&quot;').replace(/'/g, '&#39;'); }
880
+ function inlineArg(value){ return "decodeURIComponent('" + encodeURIComponent(String(value)).replace(/'/g, '%27') + "')"; }
881
+ function escapeRegExp(str){ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
882
+ function colorForKey(key){ let h=0; for(let i=0;i<key.length;i++) h=(h*31+key.charCodeAt(i))>>>0; return AVATAR_COLORS[h % AVATAR_COLORS.length]; }
883
+ function waitFor(cond, ms){
884
+ return new Promise(res => { const t0 = Date.now(); (function tick(){ if(cond()) return res(true); if(Date.now()-t0 > ms) return res(false); setTimeout(tick, 80); })(); });
885
+ }
886
+
887
+ function nameIsClean(){ return true; }
888
+
889
+ /* ---------- images ----------
890
+ No image scanning or verification anywhere. These tiny helpers exist so the rest of the code keeps working. */
891
+ const VIDEO_RE = /\.(mp4|webm|ogv|mov|m4v)(\?|#|$)/i;
892
+ function isPrivateMeta(meta){ return !!meta && meta.type !== 'public'; }
893
+ function imageVerdict(url){ return 'safe'; }
894
+ async function isImageSafeNow(url){ return 'safe'; }
895
+
896
+ /* ---------- one account per device ---------- */
897
+ function getDeviceId(){
898
+ let id = null;
899
+ try{ id = localStorage.getItem('bc_device_id'); }catch(e){}
900
+ if(!id){ const m = document.cookie.match(/(?:^|; )bc_device_id=([^;]+)/); if(m) id = m[1]; }
901
+ if(!id) id = (crypto.randomUUID ? crypto.randomUUID() : 'd' + Date.now().toString(36) + Math.random().toString(36).slice(2)).replace(/-/g,'');
902
+ try{ localStorage.setItem('bc_device_id', id); }catch(e){}
903
+ document.cookie = 'bc_device_id=' + id + '; max-age=315360000; path=/; SameSite=Lax';
904
+ return id;
905
+ }
906
+ /* Ban evasion protection. Anyone can make accounts, but each login records two "signals":
907
+ 1. a device ID kept in the browser (cookie + localStorage), and
908
+ 2. a signature = hash(browser/hardware fingerprint + public IP address).
909
+ Banning an account bans both. Register/login is refused if EITHER matches a banned one, so clearing
910
+ cookies or making a new account doesn't help. Only hashes are stored, never the IP itself. */
911
+ let cachedSignals = null;
912
+ async function fetchPublicIp(){
913
+ try{
914
+ const ctl = new AbortController();
915
+ const t = setTimeout(() => ctl.abort(), 3500);
916
+ const r = await fetch('https://api.ipify.org?format=json', { signal: ctl.signal });
917
+ clearTimeout(t);
918
+ const j = await r.json();
919
+ return j.ip || 'noip';
920
+ }catch(e){ return 'noip'; }
921
+ }
922
+ async function computeFingerprint(){
923
+ const parts = [navigator.userAgent, navigator.language, navigator.platform,
924
+ screen.width + 'x' + screen.height + 'x' + screen.colorDepth,
925
+ (Intl.DateTimeFormat().resolvedOptions().timeZone || ''), navigator.hardwareConcurrency || '', navigator.deviceMemory || ''];
926
+ try{
927
+ const c = document.createElement('canvas'); c.width = 220; c.height = 40;
928
+ const x = c.getContext('2d'); x.textBaseline = 'top'; x.font = '16px Arial';
929
+ x.fillStyle = '#f60'; x.fillRect(10, 5, 100, 25); x.fillStyle = '#069'; x.fillText('BoredChat fp 123', 12, 8);
930
+ parts.push(c.toDataURL());
931
+ }catch(e){}
932
+ try{
933
+ const g = document.createElement('canvas').getContext('webgl');
934
+ const ext = g && g.getExtension('WEBGL_debug_renderer_info');
935
+ if(ext) parts.push(g.getParameter(ext.UNMASKED_RENDERER_WEBGL));
936
+ }catch(e){}
937
+ return (await hashPassword(parts.join('||'))).slice(0, 40);
938
+ }
939
+ async function getSignals(){
940
+ if(cachedSignals) return cachedSignals;
941
+ const [fp, ip] = await Promise.all([computeFingerprint(), fetchPublicIp()]);
942
+ cachedSignals = { deviceId: getDeviceId(), ip, sig: (await hashPassword('sig|' + fp + '|' + ip)).slice(0, 40) };
943
+ return cachedSignals;
944
+ }
945
+ async function checkAndBindDevice(userKey){
946
+ if(isOwnerKey(userKey)) return null; // the owner can never be locked out
947
+ const sg = await getSignals();
948
+ const [byDevice, byGroup] = await Promise.all([
949
+ db.ref('bannedDevices/' + sg.deviceId).get(),
950
+ db.ref('linkedDeviceBans/' + sg.deviceId).get()
951
+ ]);
952
+ const origins = Object.keys(byGroup.val() || {});
953
+ const previous = byDevice.val();
954
+ if(typeof previous === 'string' && (await db.ref('bannedUsers/' + previous).get()).exists()) origins.push(previous);
955
+ if(origins.length) return 'This browser is blocked by a ban on ' + [...new Set(origins)].join(', ') + '.';
956
+ return null;
957
+ }
958
+ async function bindDevice(userKey){
959
+ const sg = await getSignals();
960
+ await db.ref('users/' + userKey).update({ deviceId: sg.deviceId, sig: sg.sig });
961
+ }
962
+ // Ban every signal we know for this account (called by owner bans and the auto-moderator).
963
+ async function banSignalsOfKey(key, record){
964
+ const [d, sgn, registration] = await Promise.all([
965
+ db.ref('users/' + key + '/deviceId').get(),
966
+ db.ref('users/' + key + '/sig').get(),
967
+ db.ref('registeredAccounts/' + key + '/device').get()
968
+ ]);
969
+ const deviceId = d.val(), sig = sgn.val(), registeredDevice = registration.val();
970
+ const up = { ['bannedUsers/' + key]: record };
971
+ const groupDevice = registeredDevice || deviceId;
972
+ if(groupDevice) up['linkedDeviceBans/' + groupDevice + '/' + key] = true;
973
+ if(deviceId && deviceId !== groupDevice) up['bannedDevices/' + deviceId] = key;
974
+ if(deviceId || sig || registeredDevice) up['banInfo/' + key] = { d: deviceId || '', s: sig || '', registeredDevice: registeredDevice || '', groupDevice: groupDevice || '' };
975
+ await moderationUpdate(up, 'ban', key);
976
+ }
977
+
978
+ function avatarHtml(username, size){
979
+ const key = sanitizeUsernameKey(username || '?');
980
+ const rawUrl = avatarsCache[key];
981
+ const url = typeof rawUrl === 'string' && /^(https?:\/\/|data:image\/(png|jpeg|webp|gif);base64,)/i.test(rawUrl) ? rawUrl : null;
982
+ const cls = 'avatar avatar-' + (size || 'sm');
983
+ if(url){
984
+ return `<span class="${cls}"><img src="${escapeHtml(url)}" alt="" referrerpolicy="no-referrer"></span>`;
985
+ }
986
+ return window.__fallbackAvatar(username, size);
987
+ }
988
+ window.__fallbackAvatar = function(username, size){
989
+ const key = sanitizeUsernameKey(username || '?');
990
+ const letter = (username || '?').trim().charAt(0).toUpperCase() || '?';
991
+ return `<span class="avatar avatar-${size || 'sm'}" style="background:${colorForKey(key)}">${escapeHtml(letter)}</span>`;
992
+ };
993
+
994
+ function displayNameFor(username){
995
+ const key = sanitizeUsernameKey(username || '');
996
+ return nicknamesCache[key] || username;
997
+ }
998
+ function isBlockedUsername(u){ return !!blockedCache[sanitizeUsernameKey(u || '')]; }
999
+ let ownerKey = null; // lowercase owner username, set at login
1000
+ function isOwnerKey(key){ return !!ownerKey && key === ownerKey; }
1001
+ function roleBadgeHtml(key){
1002
+ if(isOwnerKey(key)) return ' <span class="owner-tag">👑 OWNER</span>';
1003
+ return adminRoles[key] === true ? ' <span class="owner-tag admin-tag">ADMIN</span>' : '';
1004
+ }
1005
+ function mutedTagHtml(key){
1006
+ if(isOwnerKey(key)) return '';
1007
+ const status = ownerMuteStatus[key] || {};
1008
+ const scoped = status.scoped || {};
1009
+ const word = status.words?.[currentChatId];
1010
+ const muted = mutedCache[key] || (!adminRoles[key] && status.spam?.locked) || scoped.rooms?.[currentChatId] ||
1011
+ (currentChatMeta?.type === 'public' && scoped.public) ||
1012
+ (!adminRoles[key] && !!word);
1013
+ return muted ? ' <span class="muted-tag">🔇 muted</span>' : '';
1014
+ }
1015
+
1016
+ function amMuted(){ return !!muteRecord(); }
1017
+
1018
+ function setConnPill(state){
1019
+ const pill = document.getElementById('connPill');
1020
+ if(state === 'online'){ pill.textContent='● Connected'; pill.className='conn-pill online'; }
1021
+ else if(state === 'offline'){ pill.textContent='● Offline'; pill.className='conn-pill offline'; }
1022
+ else { pill.textContent='connecting…'; pill.className='conn-pill'; }
1023
+ }
1024
+ let chatDatabaseConnected = false;
1025
+ db.ref('.info/connected').on('value', (snap) => {
1026
+ chatDatabaseConnected = snap.val() === true;
1027
+ if(document.getElementById('chatScreen').style.display === 'flex') setConnPill(snap.val() === true ? 'online' : 'offline');
1028
+ });
1029
+
1030
+ /* ---------- tutorial ---------- */
1031
+ let tutStepIndex = 0;
1032
+ function tutSteps(){ return Array.from(document.querySelectorAll('.tut-step')).filter(el => !el.dataset.owner || isAdmin); }
1033
+ function openTutorial(){ tutStepIndex = 0; renderTutorialStep(); document.getElementById('tutorialModal').classList.add('open'); }
1034
+ function closeTutorial(){ document.getElementById('tutorialModal').classList.remove('open'); }
1035
+ function renderTutorialStep(){
1036
+ const steps = tutSteps();
1037
+ if(tutStepIndex > steps.length - 1) tutStepIndex = steps.length - 1;
1038
+ document.querySelectorAll('.tut-step').forEach(el => el.classList.remove('active'));
1039
+ if(steps[tutStepIndex]) steps[tutStepIndex].classList.add('active');
1040
+ document.getElementById('tutDots').innerHTML = steps.map((_, i) =>
1041
+ `<span class="tut-dot ${i === tutStepIndex ? 'active' : ''}" onclick="tutorialGoTo(${i})"></span>`).join('');
1042
+ document.getElementById('tutBackBtn').style.visibility = tutStepIndex === 0 ? 'hidden' : 'visible';
1043
+ document.getElementById('tutNextBtn').textContent = tutStepIndex === steps.length - 1 ? 'Done' : 'Next';
1044
+ }
1045
+ function tutorialNext(){ if(tutStepIndex >= tutSteps().length - 1){ closeTutorial(); return; } tutStepIndex++; renderTutorialStep(); }
1046
+ function tutorialBack(){ if(tutStepIndex <= 0) return; tutStepIndex--; renderTutorialStep(); }
1047
+ function tutorialGoTo(i){ tutStepIndex = i; renderTutorialStep(); }
1048
+
1049
+ /* =========================================================
1050
+ AUTH — Firebase ANONYMOUS sign-in + a password proof checked by the database rules.
1051
+ ========================================================= */
1052
+ function switchTab(mode){
1053
+ authMode = mode;
1054
+ document.getElementById('firstNameField').hidden = mode !== 'register';
1055
+ document.getElementById('firstNameInput').value = '';
1056
+ document.getElementById('tabLogin').classList.toggle('active', mode==='login');
1057
+ document.getElementById('tabRegister').classList.toggle('active', mode==='register');
1058
+ document.getElementById('submitBtn').textContent = mode==='login' ? 'Continue' : 'Create Account';
1059
+ document.getElementById('authMsg').textContent = '';
1060
+ document.getElementById('passwordInput').autocomplete = mode==='login' ? 'current-password' : 'new-password';
1061
+ }
1062
+
1063
+ async function authSecret(userKey, password){ return await hashPassword('bc-pw|' + userKey + '|' + password); }
1064
+ let signOutTimer = null;
1065
+ let autoMutes = {}, muteExpiryTimer;
1066
+ let spamMuted = false, wordMutes = {};
1067
+ let ownerMuteStatus = {};
1068
+ let moderationRefs = [], scopedMutes = {}, realName = '', kickToken = 0;
1069
+
1070
+ function validFirstName(name){
1071
+ return typeof name === 'string' && name.length <= 80 && /^\S+$/.test(name);
1072
+ }
1073
+ function moderationReason(record){
1074
+ return record && typeof record === 'object' ? record.reason : '';
1075
+ }
1076
+ function muteRecord(){
1077
+ if(isOwnerKey(myKey)) return null;
1078
+ if(adminRoles[myKey] === true) return mutedCache[myKey] || scopedMutes.rooms?.[currentChatId] || ((chatsMetaCache[currentChatId] || currentChatMeta)?.type === 'public' ? scopedMutes.public : null);
1079
+ const meta = chatsMetaCache[currentChatId] || currentChatMeta;
1080
+ return (spamMuted ? {reason:'Spamming. Only the owner can unmute you.'} : null) || wordMutes[currentChatId] || mutedCache[myKey] || scopedMutes.rooms?.[currentChatId] || (meta?.type === 'public' ? scopedMutes.public : null) || [autoMutes.all, autoMutes.rooms?.[currentChatId]].find(record => record?.until > Date.now());
1081
+ }
1082
+ function protectTarget(key){
1083
+ if(!isAdmin || key === myKey || isOwnerKey(key)) throw Error('That account is protected.');
1084
+ if(!isOwnerKey(myKey) && adminRoles[key]) throw Error('Only the owner can moderate another admin.');
1085
+ }
1086
+ let adminRoles = {}, myAdminPermissions = {};
1087
+ const adminCommandUsage = {
1088
+ ban: '/ban username reason', unban: '/unban username',
1089
+ mute: '/mute username all|public|here reason',
1090
+ unmute: '/unmute username [all|public|here]',
1091
+ kick: '/kick username', deleteMessage: 'Delete messages', publicChannels: 'Manage public channels'
1092
+ };
1093
+ function canUseAdmin(command){
1094
+ return isOwnerKey(myKey) || (isAdmin && myAdminPermissions[command] === true);
1095
+ }
1096
+ async function editAdminPermissions(action){
1097
+ if(!isOwnerKey(myKey)) return;
1098
+ const key = sanitizeUsernameKey(document.getElementById('adminPermissionUser').value);
1099
+ const message = document.getElementById('adminPermissionMessage');
1100
+ try{
1101
+ if(!key || isOwnerKey(key) || /[\x00-\x1f\x7f]/.test(key)) throw Error('Enter an admin username.');
1102
+ if(!(await db.ref('users/' + key + '/username').get()).exists()) throw Error('That username does not exist.');
1103
+ const fields = Array.from(document.querySelectorAll('#adminPermissionChoices input'));
1104
+ if(action === 'load'){
1105
+ const saved = (await db.ref('adminPermissions/' + key).get()).val() || {};
1106
+ fields.forEach(field => { field.checked = saved[field.value] === true; });
1107
+ message.textContent = 'Loaded permissions for ' + key + '.';
1108
+ return;
1109
+ }
1110
+ const selected = Object.fromEntries(fields.filter(field => field.checked).map(field => [field.value, true]));
1111
+ await db.ref().update({
1112
+ ['adminRoles/' + key]: action === 'remove' ? null : true,
1113
+ ['adminPermissions/' + key]: action === 'remove' ? null : selected
1114
+ });
1115
+ message.textContent = action === 'remove' ? 'Admin removed.' : 'Admin permissions saved.';
1116
+ }catch(err){ message.textContent = err.message; }
1117
+ }
1118
+ function moderationUpdate(updates, action, target){
1119
+ if(!isOwnerKey(myKey) && canUseAdmin(action)){
1120
+ const entry = db.ref('adminActivity').push();
1121
+ updates['adminActivity/' + entry.key] = {
1122
+ actor: myKey, action, target, time: firebase.database.ServerValue.TIMESTAMP
1123
+ };
1124
+ }
1125
+ return db.ref().update(updates);
1126
+ }
1127
+
1128
+ function watchModeration(){
1129
+ const watch = (path, callback) => {
1130
+ const ref = db.ref(path);
1131
+ moderationRefs.push(ref);
1132
+ ref.on('value', callback);
1133
+ };
1134
+ watch('deletedAccounts/' + myKey, snap => {
1135
+ if(snap.exists() && !isOwnerKey(myKey)){
1136
+ logout();
1137
+ document.getElementById('authMsg').textContent = 'The owner deleted this account.';
1138
+ }
1139
+ });
1140
+ watch('system/access/panic', snap => {
1141
+ if(snap.val() === true && myKey && !isAdmin){
1142
+ logout();
1143
+ document.getElementById('authMsg').textContent = PANIC_MESSAGE;
1144
+ }
1145
+ });
1146
+ watch('autoMutes/' + myKey, snap => { autoMutes = snap.val() || {}; updateComposerState(); });
1147
+ watch('accountKicks/' + myKey, snap => {
1148
+ if((snap.val() || 0) !== kickToken && myKey && !isOwnerKey(myKey)){
1149
+ logout();
1150
+ document.getElementById('authMsg').textContent = 'You were kicked. You can log in again.';
1151
+ }
1152
+ });
1153
+ watch('wordMutes/' + myKey, snap => { wordMutes = snap.val() || {}; updateComposerState(); });
1154
+ watch('messageThrottle/' + myKey, snap => { spamMuted = snap.val()?.locked === true; updateComposerState(); });
1155
+ if(isOwnerKey(myKey)){
1156
+ for(const [path, kind] of [['messageThrottle','spam'],['scopedMutes','scoped'],['wordMutes','words']]){
1157
+ watch(path, snap => {
1158
+ for(const key of Object.keys(ownerMuteStatus)) delete ownerMuteStatus[key][kind];
1159
+ for(const [key, value] of Object.entries(snap.val() || {})){
1160
+ ownerMuteStatus[key] ||= {};
1161
+ ownerMuteStatus[key][kind] = value;
1162
+ }
1163
+ renderMessages(); renderOnlineList(); renderFriendsList();
1164
+ });
1165
+ }
1166
+ }
1167
+ if(isOwnerKey(myKey)) watch('wordMutes', snap => {
1168
+ const list = document.getElementById('wordMuteList');
1169
+ list.replaceChildren();
1170
+ for(const [key, rooms] of Object.entries(snap.val() || {})){
1171
+ for(const [room, mute] of Object.entries(rooms)){
1172
+ const row = document.createElement('div');
1173
+ const label = document.createElement('span');
1174
+ label.textContent = key + ' — ' + (chatsMetaCache[room]?.name || room) + ' — ' + mute.reason;
1175
+ const button = document.createElement('button');
1176
+ button.textContent = 'Unmute';
1177
+ button.onclick = () => ownerAction(() => db.ref('wordMutes/' + key + '/' + room).remove());
1178
+ row.append(label, button); list.append(row);
1179
+ }
1180
+ }
1181
+ if(!list.children.length) list.textContent = 'No banned-word mutes.';
1182
+ });
1183
+ if(isOwnerKey(myKey)) watch('messageThrottle', snap => {
1184
+ const list = document.getElementById('spamMuteList');
1185
+ list.replaceChildren();
1186
+ for(const [key, rate] of Object.entries(snap.val() || {})){
1187
+ if(!rate.locked) continue;
1188
+ const button = document.createElement('button');
1189
+ button.textContent = 'Unmute ' + key;
1190
+ button.onclick = () => ownerAction(() => db.ref('messageThrottle/' + key).remove());
1191
+ list.append(button);
1192
+ }
1193
+ if(!list.children.length) list.textContent = 'No spam mutes.';
1194
+ });
1195
+ watch('scopedMutes/' + myKey, snap => { scopedMutes = snap.val() || {}; updateComposerState(); });
1196
+ watch('adminPermissions/' + myKey, snap => {
1197
+ myAdminPermissions = snap.val() || {};
1198
+ renderModBlock();
1199
+ renderMessages();
1200
+ renderPublicChannelsList();
1201
+ renderFriendsList();
1202
+ renderOnlineList();
1203
+ });
1204
+ watch('adminRoles', snap => {
1205
+ adminRoles = snap.val() || {};
1206
+ isAdmin = isOwnerKey(myKey) || adminRoles[myKey] === true;
1207
+ const badge = document.getElementById('adminBadge');
1208
+ badge.title = isOwnerKey(myKey) ? 'Owner commands' : 'Admin commands';
1209
+ badge.setAttribute('aria-label', badge.title);
1210
+ badge.style.display = isAdmin ? 'flex' : 'none';
1211
+ renderModBlock();
1212
+ renderMessages();
1213
+ renderFriendsList();
1214
+ renderOnlineList();
1215
+ });
1216
+ }
1217
+
1218
+
1219
+ async function signInStep(label, operation){
1220
+ try{ return await operation; }
1221
+ catch(error){
1222
+ if(!/permission.denied/i.test((error.code || '') + ' ' + error.message)) throw error;
1223
+ throw Error('Firebase blocked ' + label + '.');
1224
+ }
1225
+ }
1226
+
1227
+ // Firebase verifies the owner account before granting access.
1228
+ async function finishLogin(displayName, userKey){
1229
+ const panic = await signInStep('checking panic mode', db.ref('system/access/panic').get());
1230
+ if(panic.val() === true && !isOwnerKey(userKey)){
1231
+ const role = await signInStep('checking staff access', db.ref('adminRoles/' + userKey).get());
1232
+ if(role.val() !== true) throw Error(PANIC_MESSAGE);
1233
+ }
1234
+ let registeredDevice = null;
1235
+ myUid = auth.currentUser ? auth.currentUser.uid : null;
1236
+ if(!isOwnerKey(userKey)){
1237
+ const registration = (await db.ref('registeredAccounts/' + userKey).get()).val();
1238
+ registeredDevice = registration?.device || (await db.ref('users/' + userKey + '/deviceId').get()).val();
1239
+ if(registeredDevice){
1240
+ const [legacy, linked] = await Promise.all(['bannedDevices','linkedDeviceBans'].map(path => db.ref(path + '/' + registeredDevice).get()));
1241
+ const origins = Object.keys(linked.val() || {});
1242
+ if(typeof legacy.val() === 'string' && (await db.ref('bannedUsers/' + legacy.val()).get()).exists()) origins.push(legacy.val());
1243
+ if(origins.length) throw Error('This browser is blocked by a ban on ' + [...new Set(origins)].join(', ') + '.');
1244
+ }
1245
+ const profile = db.ref('users/' + userKey + '/firstName');
1246
+ const saved = (await profile.get()).val();
1247
+ if(saved){
1248
+ realName = saved;
1249
+ }else{
1250
+ const input = document.getElementById('firstNameInput');
1251
+ const entered = registration?.firstName || (!document.getElementById('firstNameField').hidden ? input.value.trim() : '');
1252
+ if(!validFirstName(entered)){
1253
+ await auth.signOut();
1254
+ document.getElementById('firstNameField').hidden = false;
1255
+ document.getElementById('authMsg').textContent = 'Enter your first name only to continue.';
1256
+ input.focus();
1257
+ return;
1258
+ }
1259
+ realName = entered;
1260
+ await profile.set(realName);
1261
+ }
1262
+ }else{
1263
+ realName = displayName;
1264
+ await signInStep('the owner permission check', db.ref('system/adminCheck').set(firebase.database.ServerValue.TIMESTAMP));
1265
+ const profileName = db.ref('users/' + userKey + '/username');
1266
+ const saved = await signInStep('reading the owner profile', profileName.get());
1267
+ if(saved.exists()) displayName = saved.val();
1268
+ else await signInStep('creating the owner profile', profileName.set(displayName));
1269
+ }
1270
+ if(!isOwnerKey(userKey)) await signInStep('updating your device profile', bindDevice(userKey));
1271
+ const kick = await db.ref('accountKicks/' + userKey).get();
1272
+ kickToken = kick.val() || 0;
1273
+ await signInStep('starting your chat session', db.ref('chatSessions/' + myUid).set({ token: kickToken }));
1274
+ adminRoles = (await signInStep('loading chat permissions', db.ref('adminRoles').get())).val() || {};
1275
+ isAdmin = isOwnerKey(userKey) || adminRoles[userKey] === true;
1276
+ loginSuccess(displayName, userKey);
1277
+ watchModeration();
1278
+ for(const path of registeredDevice ? ['bannedDevices','linkedDeviceBans'] : []){
1279
+ const ref = db.ref(path + '/' + registeredDevice);
1280
+ moderationRefs.push(ref);
1281
+ ref.on('value', async snap => {
1282
+ const value = snap.val();
1283
+ const blocked = path === 'linkedDeviceBans' ? snap.exists()
1284
+ : typeof value === 'string' && (await db.ref('bannedUsers/' + value).get()).exists();
1285
+ if(blocked && myKey === userKey){
1286
+ logout();
1287
+ document.getElementById('authMsg').textContent = 'This account is linked to a banned browser.';
1288
+ }
1289
+ });
1290
+ }
1291
+ }
1292
+
1293
+ /* Anonymous Firebase sign-in gives each browser a uid. To prove "I am <username>" the page
1294
+ writes a password proof (a hash) to proofs/<uid>; the database rules compare it with the
1295
+ stored secret WITHOUT ever letting anyone read it, and only then link uid -> username. */
1296
+ async function handleAuthSubmit(e){
1297
+ if(e && e.preventDefault) e.preventDefault();
1298
+ const usernameRaw = document.getElementById('usernameInput').value.trim();
1299
+ const password = document.getElementById('passwordInput').value;
1300
+ const msgEl = document.getElementById('authMsg');
1301
+ const submitBtn = document.getElementById('submitBtn');
1302
+ msgEl.style.color = 'var(--danger)';
1303
+ msgEl.textContent = '';
1304
+
1305
+ if(!usernameRaw || !password){ msgEl.textContent = 'Enter your username and password.'; return; }
1306
+ const firstNameInput = document.getElementById('firstNameInput');
1307
+ const firstName = firstNameInput.value.trim();
1308
+ if(authMode === 'register' && !/^[A-Za-z0-9_-]{1,20}$/.test(usernameRaw)){ msgEl.textContent = 'Use letters, numbers, underscores or hyphens in your username.'; return; }
1309
+ if(authMode === 'register' && !validFirstName(firstName)){
1310
+ msgEl.textContent = 'Enter your first name only.';
1311
+ firstNameInput.focus();
1312
+ return;
1313
+ }
1314
+ if(password.length < 4){ msgEl.textContent = 'Password must be at least 4 characters.'; return; }
1315
+ const userKey = sanitizeUsernameKey(usernameRaw);
1316
+ if(!/^[a-z0-9_-]{1,20}$/.test(userKey)){ msgEl.textContent = 'Please choose a different username.'; return; }
1317
+
1318
+ submitBtn.disabled = true;
1319
+ const originalLabel = submitBtn.textContent;
1320
+ submitBtn.textContent = 'Please wait…';
1321
+
1322
+ try{
1323
+ const secret = await authSecret(userKey, password);
1324
+ const legacy = await hashPassword(password); // old accounts used this
1325
+ clearTimeout(signOutTimer);
1326
+ await authReady;
1327
+ if(auth.currentUser) await auth.signOut();
1328
+ const cred = await auth.signInAnonymously();
1329
+ const uid = cred.user.uid;
1330
+ await signInStep('checking for database.rules-v24.json', db.ref('rulesCheck/v24').get());
1331
+ const [ownerSetting, panicSetting] = await Promise.all([
1332
+ db.ref('system/adminKey').get(), db.ref('system/access/panic').get()
1333
+ ]);
1334
+ ownerKey = ownerSetting.val();
1335
+ if(!ownerKey) throw Error('The Firebase system/adminKey value is missing.');
1336
+ const settings = {panic: panicSetting.val()};
1337
+ const ownerLogin = isOwnerKey(userKey);
1338
+ if(ownerLogin && authMode !== 'login') throw Error('This username is reserved.');
1339
+ const fail = async (m) => { try{ await auth.signOut(); }catch(_){} msgEl.textContent = m; };
1340
+ const claim = async (proof) => {
1341
+ await db.ref('proofs/' + uid).set(proof);
1342
+ await db.ref('uidToKey/' + uid).set(userKey); // rejected by the rules if the proof is wrong
1343
+ };
1344
+
1345
+ const devErr = authMode === 'register' ? await checkAndBindDevice(userKey) : null;
1346
+ if(devErr && authMode === 'register'){ await fail(devErr); return; }
1347
+
1348
+ if(authMode === 'register'){
1349
+ if(settings?.panic === true) throw Error(PANIC_MESSAGE);
1350
+ const signals = await getSignals();
1351
+ await db.ref().update({
1352
+ ['secrets/' + userKey]: secret,
1353
+ ['registeredAccounts/' + userKey]: { device: signals.deviceId, firstName }
1354
+ });
1355
+ await claim(secret);
1356
+ await db.ref('users/' + userKey).set({ username: usernameRaw, firstName, deviceId: signals.deviceId, sig: signals.sig, joined: firebase.database.ServerValue.TIMESTAMP });
1357
+ await finishLogin(usernameRaw, userKey);
1358
+ } else {
1359
+ let ok = false, usedLegacy = false;
1360
+ try{ await claim(secret); ok = true; }catch(err){}
1361
+ if(!ok && !ownerLogin){ try{ await claim(legacy); ok = true; usedLegacy = true; }catch(err){} }
1362
+ if(!ok){ await fail('Incorrect username or password.'); return; }
1363
+ if(usedLegacy){ // upgrade an old account to the new secret and drop its old hash
1364
+ try{ await db.ref('secrets/' + userKey).set(secret); await db.ref('users/' + userKey + '/passwordHash').remove(); }
1365
+ catch(err){ console.error('upgrade failed', err); }
1366
+ }
1367
+ const banSnap = await db.ref('bannedUsers/' + userKey).get();
1368
+ if(banSnap.exists()){ await fail('You have been banned from Bored Chat.' + (moderationReason(banSnap.val()) ? ' Reason: ' + moderationReason(banSnap.val()) : '')); return; }
1369
+ const browserBlock = await checkAndBindDevice(userKey);
1370
+ if(browserBlock){ await fail(browserBlock); return; }
1371
+ let display = usernameRaw;
1372
+ try{ const n = await db.ref('users/' + userKey + '/username').get(); if(n.exists()) display = n.val(); }catch(err){}
1373
+ if(!(await db.ref('users/' + userKey + '/username').get()).exists()){
1374
+ const registered = (await db.ref('registeredAccounts/' + userKey).get()).val();
1375
+ if(registered) await db.ref('users/' + userKey).update({ username: usernameRaw, ...(registered.firstName ? {firstName: registered.firstName} : {}) });
1376
+ }
1377
+ await finishLogin(display, userKey);
1378
+ }
1379
+ }catch(err){
1380
+ if(!myKey && auth.currentUser) await auth.signOut().catch(() => {});
1381
+ console.error(err);
1382
+ const code = err && err.code ? ' (' + err.code + ')' : '';
1383
+ if(err.message === PANIC_MESSAGE){ msgEl.textContent = PANIC_MESSAGE; return; }
1384
+ msgEl.textContent = 'Could not sign in' + code + ': ' + (err && err.message ? err.message : 'unknown error');
1385
+ if(isOwnerKey(userKey) && /permission.denied/i.test(err.message || '')){
1386
+ msgEl.textContent += '. Publish the matching database.rules.json in Firebase Realtime Database.';
1387
+ }
1388
+ }finally{
1389
+ submitBtn.disabled = false;
1390
+ submitBtn.textContent = originalLabel;
1391
+ }
1392
+ }
1393
+
1394
+ function loginSuccess(username, userKey){
1395
+ document.getElementById('commandsScreen').hidden = true;
1396
+ document.getElementById('friendsScreen').hidden = true;
1397
+ document.getElementById('chatScreen').inert = false;
1398
+ currentUser = username;
1399
+ myKey = userKey;
1400
+ document.getElementById('authScreen').style.display = 'none';
1401
+ document.getElementById('chatScreen').style.display = 'flex';
1402
+ document.getElementById('adminBadge').style.display = isAdmin ? 'flex' : 'none';
1403
+ setConnPill('connecting');
1404
+ renderMyUserBar();
1405
+ updateNotifyButton();
1406
+
1407
+ ensureGeneralChatExists();
1408
+ needInitialChat = true;
1409
+ startFriendsListener();
1410
+ startIncomingRequestsListener();
1411
+ startOutgoingRequestsListener();
1412
+ startBlockedListener();
1413
+ startMembershipListeners();
1414
+ startNicknamesListener();
1415
+ startStatusListener();
1416
+ startAvatarsListener();
1417
+ startIncomingCallListener();
1418
+ startMutedListener();
1419
+ startBannedListener();
1420
+ startPinnedListener();
1421
+ startPresence();
1422
+ if(isOwnerKey(myKey)) ownerSelfTest();
1423
+ }
1424
+
1425
+ function logout(){
1426
+ closeFriendsScreen();
1427
+ closeCommandsScreen();
1428
+ document.getElementById('panelCommandInput').value = '';
1429
+ moderationRefs.forEach(ref => ref.off());
1430
+ moderationRefs = [];
1431
+ spamMuted = false; wordMutes = {}; ownerMuteStatus = {};
1432
+ scopedMutes = {}; autoMutes = {}; clearTimeout(muteExpiryTimer);
1433
+ adminRoles = {};
1434
+ myAdminPermissions = {};
1435
+ document.getElementById('adminPermissionChoices').replaceChildren();
1436
+ document.getElementById('adminPermissionUser').value = '';
1437
+ document.getElementById('adminPermissionMessage').textContent = '';
1438
+ realName = '';
1439
+ endCall();
1440
+ leaveVoiceChannel();
1441
+ stopMessageListener();
1442
+ stopTypingListener();
1443
+ clearInterval(heartbeatTimer); clearInterval(presenceRenderTimer); window.onpagehide = null;
1444
+ if(connPresenceRef){ connPresenceRef.off('value'); connPresenceRef = null; }
1445
+ if(myStatusRef) myStatusRef.set({ state:'offline', username: currentUser, last_changed: firebase.database.ServerValue.TIMESTAMP });
1446
+ [friendsRef,incomingReqRef,outgoingReqRef,blockedRef,nicknamesRef,statusRef,avatarsRef,incomingCallRef,mutedRef,bannedRef]
1447
+ .forEach(r => { if(r) r.off('value'); });
1448
+ stopAllWatchers();
1449
+ friendsRef=incomingReqRef=outgoingReqRef=blockedRef=nicknamesRef=statusRef=avatarsRef=incomingCallRef=myStatusRef=mutedRef=bannedRef=null;
1450
+
1451
+ currentUser=null; myKey=null; myUid=null; isAdmin=false; needInitialChat=false;
1452
+ friendsCache={}; incomingRequestsCache={}; outgoingRequestsCache={}; blockedCache={};
1453
+ chatsMetaCache={}; nicknamesCache={}; statusCache={}; avatarsCache={}; voiceParticipantsAllCache={};
1454
+ mutedCache={}; bannedCache={}; serversCache={}; currentServerId=null; pinnedCache={};
1455
+ currentChatId=null; currentChatMeta=null; currentMessagesList=[];
1456
+ applyServerTheme(null);
1457
+
1458
+ document.getElementById('chatScreen').style.display = 'none';
1459
+ document.getElementById('authScreen').style.display = 'flex';
1460
+ document.getElementById('firstNameInput').value = '';
1461
+ document.getElementById('firstNameField').hidden = authMode !== 'register';
1462
+ document.getElementById('usernameInput').value = '';
1463
+ document.getElementById('passwordInput').value = '';
1464
+ document.getElementById('authMsg').textContent = '';
1465
+ document.getElementById('chanCol').classList.remove('mobile-open');
1466
+ signOutTimer = setTimeout(() => { auth.signOut(); }, 800);
1467
+ }
1468
+
1469
+ /* Runs once when the owner logs in: tells you straight away if the Firebase rules you published are out of date. */
1470
+ async function ownerSelfTest(){
1471
+ const msgEl = document.getElementById('modUsernameMsg');
1472
+ let problem = null;
1473
+ try{ await db.ref('rulesCheck/v24').get(); }
1474
+ catch(e){ problem = 'The rules published in Firebase are OUT OF DATE.'; }
1475
+ if(problem){
1476
+ const text = problem + ' Open Firebase → Realtime Database → Rules, paste the newest database.rules.json, press Publish, then reload this page.';
1477
+ if(msgEl){ msgEl.className = 'add-friend-msg'; msgEl.textContent = '⚠️ ' + text; }
1478
+ alert('⚠️ ' + text);
1479
+ } else if(msgEl){ msgEl.className = 'add-friend-msg ok'; msgEl.textContent = '✅ Owner permissions are working.'; }
1480
+ }
1481
+
1482
+ /* ---------- presence ---------- */
1483
+ function startPresence(){
1484
+ const TS = firebase.database.ServerValue.TIMESTAMP;
1485
+ myStatusRef = db.ref('status/' + myKey);
1486
+ if(connPresenceRef) connPresenceRef.off('value');
1487
+ connPresenceRef = db.ref('.info/connected');
1488
+ connPresenceRef.on('value', (snap) => {
1489
+ if(snap.val() === false || !myKey) return;
1490
+ myStatusRef.onDisconnect().set({ state:'offline', username: currentUser, last_changed: TS })
1491
+ .then(() => myStatusRef.set({ state:'online', username: currentUser, last_changed: TS }));
1492
+ });
1493
+ clearInterval(heartbeatTimer); clearInterval(presenceRenderTimer);
1494
+ heartbeatTimer = setInterval(() => {
1495
+ if(myStatusRef) myStatusRef.update({ state:'online', username: currentUser, last_changed: TS }).catch(()=>{});
1496
+ }, 30000);
1497
+ presenceRenderTimer = setInterval(() => { renderOnlineList(); renderFriendsList(); renderServerRail(); updateCurrentChatLabel(); }, 30000);
1498
+ window.onpagehide = () => { if(myStatusRef) myStatusRef.set({ state:'offline', username: currentUser, last_changed: TS }); };
1499
+ }
1500
+
1501
+ function startStatusListener(){
1502
+ statusRef = db.ref('status');
1503
+ statusRef.on('value', (snap) => {
1504
+ statusCache = snap.val() || {};
1505
+ renderFriendsList(); updateCurrentChatLabel(); renderOnlineList(); renderServerRail();
1506
+ });
1507
+ }
1508
+ let serverOffset = 0, heartbeatTimer = null, presenceRenderTimer = null, connPresenceRef = null;
1509
+ db.ref('.info/serverTimeOffset').on('value', s => { serverOffset = s.val() || 0; });
1510
+ const ONLINE_FRESH_MS = 90000; // no heartbeat for 90s => shown offline
1511
+ function isOnline(k){
1512
+ const st = statusCache[k];
1513
+ return !!(st && st.state === 'online' && st.last_changed && (Date.now() + serverOffset - st.last_changed) < ONLINE_FRESH_MS);
1514
+ }
1515
+
1516
+ function renderServerMembers(){
1517
+ const sec = document.getElementById('serverMembersSection');
1518
+ const scroll = document.getElementById('serverMembersScroll');
1519
+ const countEl = document.getElementById('serverMembersCount');
1520
+ if(!sec || !scroll || !countEl) return;
1521
+ const sv = currentServerId ? serversCache[currentServerId] : null;
1522
+ if(!sv){ sec.style.display = 'none'; return; }
1523
+ sec.style.display = 'flex';
1524
+ const keys = Object.keys(sv.members || {});
1525
+ const nameFor = (k) => (statusCache[k] && statusCache[k].username) || friendsCache[k] || (k === myKey ? currentUser : k);
1526
+ countEl.textContent = keys.filter(k => isOnline(k)).length + '/' + keys.length + ' online';
1527
+ keys.sort((a, b) => (isOnline(b) - isOnline(a)) || nameFor(a).localeCompare(nameFor(b)));
1528
+ scroll.innerHTML = keys.map(k => {
1529
+ const on = isOnline(k);
1530
+ const username = nameFor(k);
1531
+ const isMe = k === myKey, clickable = !isMe && !!friendsCache[k];
1532
+ const crown = (k === sv.createdBy) ? ' 👑' : '';
1533
+ return `<div class="online-item ${on ? '' : 'offline'}" ${clickable ? `onclick="openFriendDm(${inlineArg(k)})"` : ''} title="${on ? 'Online' : 'Offline'}${clickable ? ' — click to message' : ''}">
1534
+ ${avatarHtml(username,'xs')}
1535
+ <span class="mdot ${on ? 'on' : 'off'}"></span>
1536
+ <span class="item-name">${escapeHtml(isMe ? username : displayNameFor(username))}${crown}${roleBadgeHtml(k)}</span>
1537
+ ${isMe ? '<span class="you-tag">you</span>' : ''}
1538
+ </div>`;
1539
+ }).join('') || '<div class="online-empty-note">No members yet.</div>';
1540
+ }
1541
+ function renderOnlineList(){
1542
+ const scroll = document.getElementById('onlineColScroll');
1543
+ const countEl = document.getElementById('onlineCount');
1544
+ if(!scroll || !countEl) return;
1545
+ renderServerMembers();
1546
+ const keys = Object.keys(statusCache).filter(k => isOnline(k));
1547
+ countEl.textContent = keys.length;
1548
+ if(!keys.length){ scroll.innerHTML = '<div class="online-empty-note">Nobody else is around right now.</div>'; return; }
1549
+ const nameFor = (k) => (statusCache[k] && statusCache[k].username) || friendsCache[k] || k;
1550
+ keys.sort((a,b) => nameFor(a).localeCompare(nameFor(b)));
1551
+ scroll.innerHTML = keys.map(k => {
1552
+ const username = nameFor(k);
1553
+ const shown = k === myKey ? username : displayNameFor(username);
1554
+ const isMe = k === myKey, isFriend = !!friendsCache[k], clickable = isMe || isFriend;
1555
+ const modBtns = (isAdmin && !isMe) ? `
1556
+ ${canUseAdmin(mutedCache[k] ? 'unmute' : 'mute') ? `<button class="mini-btn mute" onclick="event.stopPropagation(); toggleMuteUserByKey(${inlineArg(k)},${inlineArg(username)})" title="${mutedCache[k] ? 'Unmute' : 'Mute'}">${mutedCache[k] ? '🔊' : '🔇'}</button>` : ''}
1557
+ ${canUseAdmin('ban') ? `<button class="mini-btn ban" onclick="event.stopPropagation(); banUserByKey(${inlineArg(k)},${inlineArg(username)})" title="Ban">⛔</button>` : ''}` : '';
1558
+ return `<div class="online-item" ${clickable && !isMe ? `onclick="openFriendDm(${inlineArg(k)})"` : ''} title="${clickable ? (isMe ? 'You' : 'Open DM') : 'Add them as a friend to message'}">
1559
+ ${avatarHtml(username,'xs')}
1560
+ <span class="presence-dot online" style="margin-left:-20px;margin-top:12px;"></span>
1561
+ <span class="item-name">${escapeHtml(shown)}${roleBadgeHtml(k)}${mutedTagHtml(k)}</span>
1562
+ ${isMe ? '<span class="you-tag">you</span>' : modBtns}
1563
+ </div>`;
1564
+ }).join('');
1565
+ }
1566
+
1567
+ /* ---------- avatars ---------- */
1568
+ function startAvatarsListener(){
1569
+ avatarsRef = db.ref('avatars');
1570
+ avatarsRef.on('value', (snap) => {
1571
+ avatarsCache = snap.val() || {};
1572
+ renderMyUserBar(); renderFriendsList(); renderMessages(); renderOnlineList(); renderServerRail();
1573
+ });
1574
+ }
1575
+ function renderMyUserBar(){
1576
+ document.getElementById('currentUserAvatarSlot').innerHTML = avatarHtml(currentUser, 'sm');
1577
+ document.getElementById('userBarName').textContent = currentUser || '';
1578
+ }
1579
+ function openProfileModal(){
1580
+ document.getElementById('avatarFile').value = '';
1581
+ document.getElementById('profileAvatarInput').value = avatarsCache[myKey] || '';
1582
+ document.getElementById('profileErr').textContent = '';
1583
+ document.getElementById('profileModal').classList.add('open');
1584
+ }
1585
+ function closeProfileModal(){ document.getElementById('profileModal').classList.remove('open'); }
1586
+ async function submitProfileAvatar(){
1587
+ let url = document.getElementById('profileAvatarInput').value.trim();
1588
+ const file = document.getElementById('avatarFile').files[0];
1589
+ if(file){
1590
+ if(!/^image\/(png|jpeg|webp|gif)$/.test(file.type) || file.size > 200000){
1591
+ document.getElementById('profileErr').textContent = 'Choose a PNG, JPEG, WebP or GIF up to 200 KB.';
1592
+ return;
1593
+ }
1594
+ url = await new Promise((resolve, reject) => {
1595
+ const reader = new FileReader();
1596
+ reader.onload = () => resolve(reader.result);
1597
+ reader.onerror = () => reject(reader.error);
1598
+ reader.readAsDataURL(file);
1599
+ }).catch(() => '');
1600
+ if(!url){ document.getElementById('profileErr').textContent = 'Could not read the image.'; return; }
1601
+ }
1602
+ const errEl = document.getElementById('profileErr');
1603
+ if(url && !/^https?:\/\/.+/i.test(url) && !/^data:image\/(png|jpeg|webp|gif);base64,[a-z0-9+/=]+$/i.test(url)){ errEl.textContent = 'That needs to be a full http(s) image URL.'; return; }
1604
+ try{
1605
+ if(url){ await db.ref('avatars/' + myKey).set(url); }
1606
+ else { await db.ref('avatars/' + myKey).remove(); await db.ref('users/' + myKey + '/avatarUrl').remove(); }
1607
+ closeProfileModal();
1608
+ }catch(err){ console.error(err); errEl.textContent = 'Could not save: ' + (err && err.message ? err.message : 'unknown error'); }
1609
+ }
1610
+
1611
+ /* ---------- sidebar tabs ---------- */
1612
+ function openFriendsScreen(){
1613
+ if(!myKey) return;
1614
+ const chat = document.getElementById('chatScreen');
1615
+ chat.style.display = 'none';
1616
+ chat.inert = true;
1617
+ document.getElementById('friendsScreen').hidden = false;
1618
+ document.getElementById('backFromFriends').focus();
1619
+ }
1620
+ function closeFriendsScreen(){
1621
+ const screen = document.getElementById('friendsScreen');
1622
+ if(screen.hidden) return;
1623
+ screen.hidden = true;
1624
+ const chat = document.getElementById('chatScreen');
1625
+ chat.style.display = myKey ? 'flex' : 'none';
1626
+ chat.inert = !document.getElementById('commandsScreen').hidden;
1627
+ if(!chat.inert) document.getElementById('friendsButton').focus();
1628
+ }
1629
+ function toggleSidebarMobile(){ document.getElementById('chanCol').classList.toggle('mobile-open'); }
1630
+ function closeSidebarMobile(){ document.getElementById('chanCol').classList.remove('mobile-open'); }
1631
+
1632
+ /* =========================================================
1633
+ PINNED FRIENDS (shown in the left rail under Home)
1634
+ ========================================================= */
1635
+ function startPinnedListener(){
1636
+ pinnedRef = db.ref('pinnedFriends/' + myKey);
1637
+ pinnedRef.on('value', (snap) => { pinnedCache = snap.val() || {}; renderServerRail(); renderFriendsList(); });
1638
+ }
1639
+ async function togglePinFriend(key){
1640
+ try{
1641
+ const r = db.ref('pinnedFriends/' + myKey + '/' + key);
1642
+ if(pinnedCache[key]) await r.remove(); else await r.set(true);
1643
+ }catch(err){ console.error('pin failed', err); }
1644
+ }
1645
+ function renderPinnedRail(){
1646
+ const el = document.getElementById('pinnedRailList');
1647
+ const div = document.getElementById('pinnedDivider');
1648
+ if(!el || !div) return;
1649
+ const keys = Object.keys(pinnedCache).filter(k => friendsCache[k]).sort((a,b) => friendsCache[a].localeCompare(friendsCache[b]));
1650
+ div.style.display = keys.length ? '' : 'none';
1651
+ el.innerHTML = keys.map(k => {
1652
+ const name = friendsCache[k];
1653
+ const active = !currentServerId && currentChatId === dmChatId(myKey, k);
1654
+ return `<div class="rail-icon pin-friend ${active ? 'active' : ''}" title="${escapeHtml(displayNameFor(name))} — right-click to unpin"
1655
+ onclick="openPinnedDm(${inlineArg(k)})" oncontextmenu="event.preventDefault(); togglePinFriend(${inlineArg(k)})">
1656
+ ${avatarHtml(name,'md')}<span class="rail-pres ${isOnline(k) ? 'online' : ''}"></span>${unreadCache[dmChatId(myKey, k)] ? `<span class="rail-badge">${unreadCache[dmChatId(myKey, k)]}</span>` : ''}</div>`;
1657
+ }).join('');
1658
+ }
1659
+ function openPinnedDm(k){
1660
+ currentServerId = null;
1661
+ updateSidebarForServer();
1662
+ renderGroupsList();
1663
+ openFriendDm(k);
1664
+ }
1665
+
1666
+ /* =========================================================
1667
+ FRIENDS
1668
+ ========================================================= */
1669
+ function startFriendsListener(){
1670
+ friendsRef = db.ref('friends/' + myKey);
1671
+ friendsRef.on('value', (snap) => {
1672
+ friendsCache = snap.val() || {};
1673
+ renderFriendsList(); renderServerRail(); renderNewGroupMemberPicker_ifOpen(); renderAddMemberPicker_ifOpen();
1674
+ });
1675
+ }
1676
+ function startIncomingRequestsListener(){
1677
+ incomingReqRef = db.ref('friendRequests/' + myKey);
1678
+ let firstLoad = true;
1679
+ incomingReqRef.on('value', (snap) => {
1680
+ const prev = incomingRequestsCache;
1681
+ incomingRequestsCache = snap.val() || {};
1682
+ if(!firstLoad){
1683
+ Object.keys(incomingRequestsCache).forEach(k => {
1684
+ if(!prev[k] && !blockedCache[k]) notifyUser('👥 Friend request', incomingRequestsCache[k] + ' wants to be your friend', null);
1685
+ });
1686
+ }
1687
+ firstLoad = false;
1688
+ renderIncomingRequests(); updateRequestBadge();
1689
+ });
1690
+ }
1691
+ function startOutgoingRequestsListener(){
1692
+ outgoingReqRef = db.ref('sentRequests/' + myKey);
1693
+ outgoingReqRef.on('value', (snap) => { outgoingRequestsCache = snap.val() || {}; renderOutgoingRequests(); });
1694
+ }
1695
+ function startBlockedListener(){
1696
+ blockedRef = db.ref('blocked/' + myKey);
1697
+ blockedRef.on('value', (snap) => { blockedCache = snap.val() || {}; renderBlockedList(); renderMessages(); });
1698
+ }
1699
+ function startNicknamesListener(){
1700
+ nicknamesRef = db.ref('nicknames/' + myKey);
1701
+ nicknamesRef.on('value', (snap) => { nicknamesCache = snap.val() || {}; renderFriendsList(); updateCurrentChatLabel(); renderMessages(); renderServerRail(); });
1702
+ }
1703
+
1704
+ /* =========================================================
1705
+ MODERATION: mute + ban (incl. by username)
1706
+ ========================================================= */
1707
+ function startMutedListener(){
1708
+ mutedRef = db.ref('mutedUsers');
1709
+ mutedRef.on('value', (snap) => {
1710
+ mutedCache = snap.val() || {};
1711
+ renderMessages(); renderFriendsList(); renderOnlineList(); renderModBlock(); updateComposerState();
1712
+ });
1713
+ }
1714
+ function isBannedMessage(message){
1715
+ return typeof message.user === 'string' && !isOwnerKey(sanitizeUsernameKey(message.user)) && Object.hasOwn(bannedCache, sanitizeUsernameKey(message.user));
1716
+ }
1717
+ function startBannedListener(){
1718
+ bannedRef = db.ref('bannedUsers');
1719
+ bannedRef.on('value', (snap) => {
1720
+ bannedCache = snap.val() || {};
1721
+ renderMessages();
1722
+ renderModBlock();
1723
+ if(myKey && !isOwnerKey(myKey) && bannedCache[myKey]){ const reason = moderationReason(bannedCache[myKey]); logout(); document.getElementById('authMsg').textContent = 'You were banned.' + (reason ? ' Reason: ' + reason : ''); }
1724
+ });
1725
+ }
1726
+ function mutePath(key, scope){
1727
+ if(scope === 'all') return 'mutedUsers/' + key;
1728
+ if(scope === 'public') return 'scopedMutes/' + key + '/public';
1729
+ if(scope === 'here' && currentChatId) return 'scopedMutes/' + key + '/rooms/' + currentChatId;
1730
+ throw Error('Use all, public, or here.');
1731
+ }
1732
+ async function muteUserByKey(key, username, scope, reason){
1733
+ if(!canUseAdmin('mute')) return false;
1734
+ protectTarget(key);
1735
+ scope = scope || prompt('Mute scope: all, public, or here', 'all');
1736
+ if(!scope) return false;
1737
+ if(!['all','public','here'].includes(scope)) throw Error('Use all, public, or here.');
1738
+ reason = reason || prompt('Reason for muting ' + username + '?');
1739
+ if(!reason?.trim()) return false;
1740
+ await moderationUpdate({ [mutePath(key, scope)]: { username, reason: reason.trim().slice(0, 300) } }, 'mute', key + ' (' + scope + ')');
1741
+ return true;
1742
+ }
1743
+ async function unmuteUserByKey(key, scope){
1744
+ if(!canUseAdmin('unmute')) return false;
1745
+ try{
1746
+ protectTarget(key);
1747
+ const updates = scope ? { [mutePath(key, scope)]: null } : { [mutePath(key, 'all')]: null, [mutePath(key, 'public')]: null };
1748
+ await moderationUpdate(updates, 'unmute', key + (scope ? ' (' + scope + ')' : ''));
1749
+ return true;
1750
+ }catch(err){ flashComposerNote(err.message); return false; }
1751
+ }
1752
+ async function toggleMuteUserByKey(key, username){
1753
+ try{
1754
+ if(mutedCache[key]) await unmuteUserByKey(key);
1755
+ else await muteUserByKey(key, username);
1756
+ }catch(err){ alert(err.message); }
1757
+ }
1758
+ async function banUserByKey(key, username, reason){
1759
+ if(!canUseAdmin('ban')) return false;
1760
+ protectTarget(key);
1761
+ reason = reason || prompt('Reason for banning ' + username + '?');
1762
+ if(!reason?.trim()) return false;
1763
+ await banSignalsOfKey(key, { username, reason: reason.trim().slice(0, 300) });
1764
+ return true;
1765
+ }
1766
+ async function whoAmIText(){
1767
+ try{
1768
+ const u = auth.currentUser;
1769
+ if(!u) return 'Firebase says you are signed out.';
1770
+ const k = await db.ref('uidToKey/' + u.uid).get();
1771
+ return 'Firebase thinks you are: ' + (k.exists() ? k.val() : 'nobody (no account linked)') + '.';
1772
+ }catch(e){ return ''; }
1773
+ }
1774
+ async function unbanUserByKey(key){
1775
+ if(!canUseAdmin('unban')) return false;
1776
+ if(!isAdmin) return false;
1777
+ try{
1778
+ protectTarget(key);
1779
+ const [info, device, signature] = await Promise.all([
1780
+ db.ref('banInfo/' + key).get(),
1781
+ db.ref('users/' + key + '/deviceId').get(),
1782
+ db.ref('users/' + key + '/sig').get()
1783
+ ]);
1784
+ const record = info.val() || {};
1785
+ const updates = { ['bannedUsers/' + key]: null, ['banInfo/' + key]: null };
1786
+ if(record.groupDevice) updates['linkedDeviceBans/' + record.groupDevice + '/' + key] = null;
1787
+ const ids = new Set([record.d, record.registeredDevice, device.val()].filter(Boolean));
1788
+ for(const sig of [record.s, signature.val()].filter(Boolean)) ids.add('s_' + sig);
1789
+ await Promise.all(Array.from(ids, async id => {
1790
+ const path = 'bannedDevices/' + id;
1791
+ if((await db.ref(path).get()).val() === key) updates[path] = null;
1792
+ }));
1793
+ await moderationUpdate(updates, 'unban', key);
1794
+ return true;
1795
+ }catch(err){ console.error('Failed to unban user', err); alert('Unban failed: ' + (err.message || 'unknown error') + '\n\n' + await whoAmIText() + '\nIt should say the owner. If not, log out and back in as the owner in THIS tab. If it does, publish the newest database.rules.json.'); return false; }
1796
+ }
1797
+ // Ban or mute anybody by typing their username (online or not).
1798
+ async function modActionByUsername(action){
1799
+ if(!canUseAdmin(action)) return;
1800
+ const input = document.getElementById('modUsernameInput');
1801
+ const msgEl = document.getElementById('modUsernameMsg');
1802
+ msgEl.className = 'add-friend-msg';
1803
+ const raw = input.value.trim();
1804
+ if(!raw){ msgEl.textContent = 'Type a username first.'; return; }
1805
+ const key = sanitizeUsernameKey(raw);
1806
+ if(key === myKey){ msgEl.textContent = "You can't do that to yourself."; return; }
1807
+ try{
1808
+ const snap = await db.ref('users/' + key + '/username').get();
1809
+ if(!snap.exists() && action !== 'unban' && action !== 'unmute'){ msgEl.textContent = 'No account exists with that name.'; return; }
1810
+ const username = (snap.exists() && snap.val()) || raw;
1811
+ if(action === 'unban'){
1812
+ const ok = await unbanUserByKey(key);
1813
+ if(ok){ msgEl.className = 'add-friend-msg ok'; msgEl.textContent = username + ' was unbanned.'; input.value = ''; }
1814
+ } else if(action === 'unmute'){
1815
+ if(await unmuteUserByKey(key)){ msgEl.className = 'add-friend-msg ok'; msgEl.textContent = username + ' was unmuted.'; input.value = ''; }
1816
+ } else if(action === 'ban'){
1817
+ if(await banUserByKey(key, username)){ msgEl.className = 'add-friend-msg ok'; msgEl.textContent = username + ' was banned.'; input.value = ''; }
1818
+ } else {
1819
+ if(await muteUserByKey(key, username)){ msgEl.className = 'add-friend-msg ok'; msgEl.textContent = username + ' was muted.'; input.value = ''; }
1820
+ }
1821
+ }catch(err){ console.error(err); msgEl.textContent = 'Failed: ' + (err.message || 'unknown error'); }
1822
+ }
1823
+ function renderAuditAdmins(){
1824
+ const container = document.getElementById('auditAdmins');
1825
+ container.replaceChildren();
1826
+ document.getElementById('adminActivityList').replaceChildren();
1827
+ Object.keys(adminRoles).filter(key => adminRoles[key] === true).forEach(key => {
1828
+ const button = document.createElement('button');
1829
+ button.textContent = key;
1830
+ button.onclick = async () => {
1831
+ const list = document.getElementById('adminActivityList');
1832
+ list.textContent = 'Loading ' + key + '…';
1833
+ try{
1834
+ const snapshot = await db.ref('adminActivity').orderByChild('actor').equalTo(key).limitToLast(50).get();
1835
+ if(list.textContent !== 'Loading ' + key + '…' || !isOwnerKey(myKey)) return;
1836
+ list.replaceChildren();
1837
+ snapshot.forEach(child => {
1838
+ const {time, action, target} = child.val();
1839
+ const row = document.createElement('li');
1840
+ row.textContent = new Date(time).toLocaleString() + ' — /' + action + ' ' + target;
1841
+ list.prepend(row);
1842
+ });
1843
+ if(!list.children.length) list.textContent = 'No commands recorded for ' + key + '.';
1844
+ }catch(error){ list.textContent = error.message; }
1845
+ };
1846
+ container.append(button);
1847
+ });
1848
+ }
1849
+ async function ownerAction(action){
1850
+ if(!isOwnerKey(myKey)) return;
1851
+ try{ await action(); }catch(error){ flashComposerNote(error.message); }
1852
+ }
1853
+ function setPanic(enabled){
1854
+ if(enabled && !confirm('Block all non-staff accounts until panic mode is turned off?')) return;
1855
+ ownerAction(() => db.ref('system/access/panic').set(enabled));
1856
+ }
1857
+ async function showBannedWords(){
1858
+ if(!isOwnerKey(myKey)) return;
1859
+ const list = document.getElementById('bannedWordList');
1860
+ const uid = myUid;
1861
+ list.textContent = 'Loading…';
1862
+ try{
1863
+ const snapshot = await db.ref('moderationConfig/bannedWords').get();
1864
+ if(myUid !== uid || !isOwnerKey(myKey)) return;
1865
+ const words = Object.values(snapshot.val() || {});
1866
+ list.textContent = words.length ? words.join(', ') : 'No banned words configured.';
1867
+ }catch(error){
1868
+ if(myUid === uid && isOwnerKey(myKey)) list.textContent = 'Could not load banned words: ' + error.message;
1869
+ }
1870
+ }
1871
+ function editBannedWords(){
1872
+ ownerAction(async () => {
1873
+ const ref = db.ref('moderationConfig/bannedWords');
1874
+ const previous = Object.values((await ref.get()).val() || {}).join(', ');
1875
+ const input = prompt('Banned words in public servers. Separate words with commas.', previous);
1876
+ if(input === null) return;
1877
+ const words = [...new Set(input.split(',').map(word => normalizeChatText(word).trim().toLowerCase()).filter(Boolean))];
1878
+ if(words.length > 100 || words.some(word => !/^[\p{L}\p{N}]{1,40}$/u.test(word))) throw Error('Use up to 100 words, each 1–40 letters or numbers.');
1879
+ await ref.set(words.length ? words : null);
1880
+ await showBannedWords();
1881
+ });
1882
+ }
1883
+
1884
+ function openCommandsScreen(){
1885
+ if(!isAdmin) return;
1886
+ renderModBlock();
1887
+ if(isOwnerKey(myKey)){ renderAuditAdmins(); showBannedWords(); }
1888
+ document.getElementById('commandsTitle').textContent = isOwnerKey(myKey) ? 'Owner commands' : 'Admin commands';
1889
+ document.getElementById('commandsScreen').hidden = false;
1890
+ document.getElementById('chatScreen').inert = true;
1891
+ document.getElementById('backToChat').focus();
1892
+ }
1893
+ function closeCommandsScreen(){
1894
+ const screen = document.getElementById('commandsScreen');
1895
+ const wasOpen = !screen.hidden;
1896
+ screen.hidden = true;
1897
+ document.getElementById('chatScreen').inert = !document.getElementById('friendsScreen').hidden;
1898
+ document.getElementById('firstNameLookupResult').textContent = '';
1899
+ document.getElementById('firstNameLookup').value = '';
1900
+ if(wasOpen && isAdmin) document.getElementById('adminBadge').focus();
1901
+ }
1902
+ async function lookupFirstName(event){
1903
+ event.preventDefault();
1904
+ if(!isOwnerKey(myKey)) return;
1905
+ const input = document.getElementById('firstNameLookup');
1906
+ const output = document.getElementById('firstNameLookupResult');
1907
+ const key = sanitizeUsernameKey(input.value);
1908
+ const session = myUid;
1909
+ output.textContent = 'Looking up…';
1910
+ try{
1911
+ if(!key || /[\x00-\x1f\x7f]/.test(key)) throw Error('Enter a valid username.');
1912
+ const [username, name, registration] = await Promise.all([
1913
+ db.ref('users/' + key + '/username').get(),
1914
+ db.ref('users/' + key + '/firstName').get(),
1915
+ db.ref('registeredAccounts/' + key).get()
1916
+ ]);
1917
+ if(myUid !== session || document.getElementById('commandsScreen').hidden) return;
1918
+ const firstName = name.val() || registration.val()?.firstName;
1919
+ output.textContent = username.exists() || registration.exists()
1920
+ ? (username.val() || input.value.trim()) + (firstName ? ' — First name: ' + firstName : ' — No first name saved.')
1921
+ : 'Username not found.';
1922
+ }catch(err){
1923
+ if(myUid === session && !document.getElementById('commandsScreen').hidden) output.textContent = err.message;
1924
+ }
1925
+ }
1926
+ function submitPanelCommand(event){
1927
+ event.preventDefault();
1928
+ const input = document.getElementById('panelCommandInput');
1929
+ const command = input.value.trim();
1930
+ if(!command.startsWith('/')){
1931
+ flashComposerNote('Start the command with /.');
1932
+ return;
1933
+ }
1934
+ runAdminCommand(command);
1935
+ }
1936
+ function renderModBlock(){
1937
+ const block = document.getElementById('modBlock');
1938
+ if(!block) return;
1939
+ const owner = isOwnerKey(myKey);
1940
+ document.getElementById('ownerCommandPanel').hidden = !owner;
1941
+ if(!isAdmin){ block.style.display = 'none'; closeCommandsScreen(); return; }
1942
+ const choices = document.getElementById('adminPermissionChoices');
1943
+ if(owner && !choices.children.length){
1944
+ choices.innerHTML = Object.entries(adminCommandUsage).map(([key, usage]) =>
1945
+ '<label style="display:block;"><input type="checkbox" value="' + key + '"> ' + escapeHtml(usage) + '</label>').join('');
1946
+ }
1947
+ document.getElementById('availableAdminCommands').textContent = Object.entries(adminCommandUsage)
1948
+ .filter(([key]) => canUseAdmin(key)).map(([, usage]) => usage).join(' • ') || 'No commands assigned.';
1949
+ block.querySelectorAll('[data-mod-permission]').forEach(button => {
1950
+ button.hidden = !canUseAdmin(button.dataset.modPermission);
1951
+ });
1952
+ block.style.display = 'block';
1953
+ const mutedKeys = Object.keys(mutedCache);
1954
+ document.getElementById('mutedAdminList').innerHTML = mutedKeys.length ? mutedKeys.map(k => `
1955
+ <div class="request-row">${avatarHtml(mutedCache[k].username || mutedCache[k],'xs')}<span class="req-name">${escapeHtml((mutedCache[k].username || mutedCache[k]) + (moderationReason(mutedCache[k]) ? " — " + moderationReason(mutedCache[k]) : ""))}</span>
1956
+ ${canUseAdmin('unmute') ? `<button class="req-unblock" onclick="unmuteUserByKey(decodeURIComponent('${escapeHtml(encodeURIComponent(k)).replace(/'/g, '%27')}'))">Unmute</button>` : ''}</div>`).join('') : '<div class="empty-list-note">Nobody is muted.</div>';
1957
+ const bannedKeys = Object.keys(bannedCache);
1958
+ document.getElementById('bannedAdminList').innerHTML = bannedKeys.length ? bannedKeys.map(k => `
1959
+ <div class="request-row">${avatarHtml(bannedCache[k].username || bannedCache[k],'xs')}<span class="req-name">${escapeHtml((bannedCache[k].username || bannedCache[k]) + (moderationReason(bannedCache[k]) ? " — " + moderationReason(bannedCache[k]) : ""))}</span>
1960
+ ${canUseAdmin('unban') ? `<button class="req-unblock" onclick="unbanUserByKey(decodeURIComponent('${escapeHtml(encodeURIComponent(k)).replace(/'/g, '%27')}'))">Unban</button>` : ''}</div>`).join('') : '<div class="empty-list-note">Nobody is banned.</div>';
1961
+ }
1962
+
1963
+ function updateRequestBadge(){
1964
+ const badge = document.getElementById('incomingReqBadge');
1965
+ const n = Object.keys(incomingRequestsCache).filter(k => !blockedCache[k]).length;
1966
+ if(n > 0){ badge.style.display='inline-block'; badge.textContent = n; } else badge.style.display='none';
1967
+ }
1968
+
1969
+ async function sendFriendRequestFromInput(){
1970
+ const input = document.getElementById('addFriendInput');
1971
+ const msgEl = document.getElementById('addFriendMsg');
1972
+ const targetRaw = input.value.trim();
1973
+ msgEl.className = 'add-friend-msg'; msgEl.textContent = '';
1974
+ if(!targetRaw){ msgEl.textContent = 'Type a username first.'; return; }
1975
+ const targetKey = sanitizeUsernameKey(targetRaw);
1976
+ if(targetKey === myKey){ msgEl.textContent = "You can't add yourself."; return; }
1977
+ if(blockedCache[targetKey]){ msgEl.textContent = 'Unblock them first.'; return; }
1978
+ if(friendsCache[targetKey]){ msgEl.textContent = 'Already friends with them.'; return; }
1979
+ if(outgoingRequestsCache[targetKey]){ msgEl.textContent = 'Request already sent.'; return; }
1980
+ try{
1981
+ if(incomingRequestsCache[targetKey]){
1982
+ await acceptFriendRequest(targetKey, incomingRequestsCache[targetKey]);
1983
+ msgEl.className = 'add-friend-msg ok'; msgEl.textContent = 'You were already friends-in-waiting — accepted!'; input.value = '';
1984
+ return;
1985
+ }
1986
+ const targetSnap = await db.ref('users/' + targetKey + '/username').get();
1987
+ if(!targetSnap.exists()){ msgEl.textContent = 'No account exists with that name.'; return; }
1988
+ const targetUsername = targetSnap.val() || targetRaw;
1989
+ await db.ref('friendRequests/' + targetKey + '/' + myKey).set(currentUser);
1990
+ await db.ref('sentRequests/' + myKey + '/' + targetKey).set(targetUsername);
1991
+ msgEl.className = 'add-friend-msg ok'; msgEl.textContent = 'Friend request sent to ' + targetUsername + '.'; input.value = '';
1992
+ }catch(err){ console.error(err); msgEl.textContent = 'Could not send request: ' + (err && err.message ? err.message : 'unknown error'); }
1993
+ }
1994
+ async function acceptFriendRequest(fromKey, fromUsername){
1995
+ await db.ref('friends/' + myKey + '/' + fromKey).set(fromUsername);
1996
+ await db.ref('friends/' + fromKey + '/' + myKey).set(currentUser);
1997
+ await db.ref('friendRequests/' + myKey + '/' + fromKey).remove();
1998
+ await db.ref('sentRequests/' + fromKey + '/' + myKey).remove();
1999
+ }
2000
+ async function declineIncomingRequest(fromKey){
2001
+ try{ await db.ref('friendRequests/' + myKey + '/' + fromKey).remove(); await db.ref('sentRequests/' + fromKey + '/' + myKey).remove(); }
2002
+ catch(err){ console.error('Failed to decline request', err); }
2003
+ }
2004
+ async function cancelOutgoingRequest(toKey){
2005
+ try{ await db.ref('sentRequests/' + myKey + '/' + toKey).remove(); await db.ref('friendRequests/' + toKey + '/' + myKey).remove(); }
2006
+ catch(err){ console.error('Failed to cancel request', err); }
2007
+ }
2008
+ async function acceptFriendRequestUI(fromKey){
2009
+ try{ await acceptFriendRequest(fromKey, incomingRequestsCache[fromKey]); }catch(err){ console.error(err); }
2010
+ }
2011
+ async function unfriend(friendKey){
2012
+ const name = friendsCache[friendKey] || friendKey;
2013
+ if(!confirm('Remove ' + name + ' as a friend? This will not delete your past messages.')) return;
2014
+ try{
2015
+ await db.ref('friends/' + myKey + '/' + friendKey).remove();
2016
+ await db.ref('friends/' + friendKey + '/' + myKey).remove();
2017
+ await db.ref('nicknames/' + myKey + '/' + friendKey).remove();
2018
+ await db.ref('pinnedFriends/' + myKey + '/' + friendKey).remove();
2019
+ if(currentChatMeta && currentChatMeta.type === 'dm' && currentChatId === dmChatId(myKey, friendKey)) clearChatView();
2020
+ }catch(err){ console.error('Failed to unfriend', err); }
2021
+ }
2022
+ async function blockUserByKey(targetKey, targetUsername){
2023
+ if(!targetKey || targetKey === myKey) return;
2024
+ if(!confirm('Block ' + targetUsername + '? You will stop seeing their messages everywhere, and they can no longer call or add you.')) return;
2025
+ try{
2026
+ await db.ref('blocked/' + myKey + '/' + targetKey).set(targetUsername);
2027
+ await db.ref('friends/' + myKey + '/' + targetKey).remove();
2028
+ await db.ref('friends/' + targetKey + '/' + myKey).remove();
2029
+ await db.ref('pinnedFriends/' + myKey + '/' + targetKey).remove();
2030
+ await db.ref('friendRequests/' + myKey + '/' + targetKey).remove();
2031
+ await db.ref('friendRequests/' + targetKey + '/' + myKey).remove();
2032
+ await db.ref('sentRequests/' + myKey + '/' + targetKey).remove();
2033
+ await db.ref('sentRequests/' + targetKey + '/' + myKey).remove();
2034
+ if(currentChatMeta && currentChatMeta.type === 'dm' && currentChatId === dmChatId(myKey, targetKey)) clearChatView();
2035
+ }catch(err){ console.error('Failed to block user', err); }
2036
+ }
2037
+ async function unblockUser(targetKey){
2038
+ try{ await db.ref('blocked/' + myKey + '/' + targetKey).remove(); }catch(err){ console.error('Failed to unblock user', err); }
2039
+ }
2040
+ async function setNicknameFor(friendKey, friendUsername){
2041
+ const val = prompt('Nickname for ' + friendUsername + ' (leave blank to clear):', nicknamesCache[friendKey] || '');
2042
+ if(val === null) return;
2043
+ const trimmed = val.trim();
2044
+ try{
2045
+ if(trimmed) await db.ref('nicknames/' + myKey + '/' + friendKey).set(trimmed);
2046
+ else await db.ref('nicknames/' + myKey + '/' + friendKey).remove();
2047
+ }catch(err){ console.error('Failed to save nickname', err); }
2048
+ }
2049
+
2050
+ function renderIncomingRequests(){
2051
+ const keys = Object.keys(incomingRequestsCache).filter(k => !blockedCache[k]);
2052
+ document.getElementById('incomingRequestsBlock').style.display = keys.length ? 'block' : 'none';
2053
+ document.getElementById('incomingRequestsList').innerHTML = keys.map(k => `
2054
+ <div class="request-row">${avatarHtml(incomingRequestsCache[k],'xs')}<span class="req-name">${escapeHtml(incomingRequestsCache[k])}</span>
2055
+ <button class="req-accept" onclick="acceptFriendRequestUI(${inlineArg(k)})">Accept</button>
2056
+ <button class="req-decline" onclick="declineIncomingRequest(${inlineArg(k)})">✕</button></div>`).join('');
2057
+ }
2058
+ function renderOutgoingRequests(){
2059
+ const keys = Object.keys(outgoingRequestsCache);
2060
+ document.getElementById('outgoingRequestsBlock').style.display = keys.length ? 'block' : 'none';
2061
+ document.getElementById('outgoingRequestsList').innerHTML = keys.map(k => `
2062
+ <div class="request-row">${avatarHtml(outgoingRequestsCache[k],'xs')}<span class="req-name">${escapeHtml(outgoingRequestsCache[k])}</span>
2063
+ <span style="font-size:0.7rem;color:var(--text-muted);">waiting…</span>
2064
+ <button class="req-cancel" onclick="cancelOutgoingRequest(${inlineArg(k)})">✕</button></div>`).join('');
2065
+ }
2066
+ function renderBlockedList(){
2067
+ const keys = Object.keys(blockedCache);
2068
+ document.getElementById('blockedBlock').style.display = keys.length ? 'block' : 'none';
2069
+ document.getElementById('blockedList').innerHTML = keys.map(k => `
2070
+ <div class="request-row">${avatarHtml(blockedCache[k],'xs')}<span class="req-name">${escapeHtml(blockedCache[k])}</span>
2071
+ <button class="req-unblock" onclick="unblockUser(${inlineArg(k)})">Unblock</button></div>`).join('');
2072
+ }
2073
+ function renderFriendsList(){
2074
+ const list = document.getElementById('friendsList');
2075
+ const keys = Object.keys(friendsCache).sort((a,b) => friendsCache[a].localeCompare(friendsCache[b]));
2076
+ if(!keys.length){ list.innerHTML = '<div class="empty-list-note">No friends yet. Add someone by username above.</div>'; return; }
2077
+ list.innerHTML = keys.map(k => {
2078
+ const username = friendsCache[k];
2079
+ const active = currentChatId === dmChatId(myKey, k);
2080
+ const name = escapeHtml(displayNameFor(friendsCache[k])) + roleBadgeHtml(k) + mutedTagHtml(k);
2081
+ const rawEsc = escapeHtml(friendsCache[k]).replace(/'/g,"\\'");
2082
+ const pinned = !!pinnedCache[k];
2083
+ const modBtns = (isAdmin && k !== myKey) ? `
2084
+ ${canUseAdmin(mutedCache[k] ? 'unmute' : 'mute') ? `<button class="mini-btn mute" onclick="event.stopPropagation(); toggleMuteUserByKey(${inlineArg(k)},${inlineArg(username)})" title="${mutedCache[k] ? 'Unmute' : 'Mute'}">${mutedCache[k] ? '🔊' : '🔇'}</button>` : ''}
2085
+ ${canUseAdmin('ban') ? `<button class="mini-btn ban" onclick="event.stopPropagation(); banUserByKey(${inlineArg(k)},${inlineArg(username)})" title="Ban">⛔</button>` : ''}` : '';
2086
+ return `<div class="list-item ${active ? 'active' : ''}" onclick="openFriendDm(${inlineArg(k)})">
2087
+ ${avatarHtml(friendsCache[k],'xs')}
2088
+ <span class="item-name">${name}</span>${unreadBadge(dmChatId(myKey, k))}
2089
+ <span class="presence-dot ${isOnline(k) ? 'online' : ''}" style="margin-left:-20px;margin-top:12px;"></span>
2090
+ <button class="mini-btn pin" style="${pinned ? 'opacity:0.9;' : ''}" onclick="event.stopPropagation(); togglePinFriend(${inlineArg(k)})" title="${pinned ? 'Unpin from sidebar' : 'Pin to sidebar'}">${pinned ? '📍' : '📌'}</button>
2091
+ <button class="mini-btn nick" onclick="event.stopPropagation(); setNicknameFor(${inlineArg(k)},${inlineArg(username)})" title="Set nickname">✏️</button>
2092
+ <button class="mini-btn call" onclick="event.stopPropagation(); startCall(${inlineArg(k)},${inlineArg(username)},'audio')" title="Voice call">📞</button>
2093
+ <button class="mini-btn video" onclick="event.stopPropagation(); startCall(${inlineArg(k)},${inlineArg(username)},'video')" title="Video call">🎥</button>
2094
+ ${modBtns}
2095
+ <button class="mini-btn block" onclick="event.stopPropagation(); blockUserByKey(${inlineArg(k)},${inlineArg(username)})" title="Block">🚫</button>
2096
+ <button class="mini-btn del" onclick="event.stopPropagation(); unfriend(${inlineArg(k)})" title="Remove friend">✕</button>
2097
+ </div>`;
2098
+ }).join('');
2099
+ }
2100
+
2101
+ /* =========================================================
2102
+ DATA LAYER FOR PRIVATE CHATS / SERVERS
2103
+ The app no longer downloads every chat and server. It reads:
2104
+ memberships/<me>/chats|servers (what I belong to)
2105
+ publicChannels (list of public channel ids)
2106
+ serverChannels/<server> (channel ids inside my servers)
2107
+ and then listens only to those individual records, which the
2108
+ database rules allow only for members.
2109
+ ========================================================= */
2110
+ let myChatIds = {}, myServerIds = {}, publicChatIds = {}, serverChanIds = {};
2111
+ let myChatIdsRef=null, myServerIdsRef=null, publicChatIdsRef=null, ownerPublicQuery=null;
2112
+ let ownerPublicIds = {};
2113
+ let chatMetaWatch = {}, chatMetaLoaded = {}, serverWatch = {}, serverChanWatch = {}, voiceWatch = {};
2114
+
2115
+ function startMembershipListeners(){
2116
+ myChatIdsRef = db.ref('memberships/' + myKey + '/chats');
2117
+ myChatIdsRef.on('value', s => { myChatIds = s.val() || {}; reconcileChatMetaWatchers(); });
2118
+ myServerIdsRef = db.ref('memberships/' + myKey + '/servers');
2119
+ myServerIdsRef.on('value', s => { myServerIds = s.val() || {}; reconcileServerWatchers(); });
2120
+ publicChatIdsRef = db.ref('publicChannels');
2121
+ publicChatIdsRef.on('value', s => { publicChatIds = s.val() || {}; reconcileChatMetaWatchers(); });
2122
+ if(isOwnerKey(myKey)){
2123
+ ownerPublicQuery = db.ref('chatsMeta').orderByChild('type').equalTo('public');
2124
+ ownerPublicQuery.on('value', snapshot => {
2125
+ ownerPublicIds = Object.fromEntries(Object.keys(snapshot.val() || {}).map(id => [id, true]));
2126
+ reconcileChatMetaWatchers();
2127
+ });
2128
+ }
2129
+ setTimeout(() => { if(needInitialChat && !currentChatId) openDefaultChat(); }, 3000);
2130
+ }
2131
+
2132
+ function reconcileChatMetaWatchers(){
2133
+ const wanted = Object.assign({}, myChatIds, publicChatIds, ownerPublicIds);
2134
+ Object.values(serverChanIds).forEach(m => Object.assign(wanted, m || {}));
2135
+ Object.keys(chatMetaWatch).forEach(id => {
2136
+ if(!wanted[id]){ chatMetaWatch[id].off(); delete chatMetaWatch[id]; delete chatsMetaCache[id]; delete chatMetaLoaded[id]; }
2137
+ });
2138
+ Object.keys(wanted).forEach(id => {
2139
+ if(chatMetaWatch[id]) return;
2140
+ const ref = db.ref('chatsMeta/' + id);
2141
+ chatMetaWatch[id] = ref;
2142
+ ref.on('value',
2143
+ s => { chatMetaLoaded[id] = true; if(s.exists()) chatsMetaCache[id] = s.val(); else delete chatsMetaCache[id]; onChatsMetaChanged(); },
2144
+ () => { chatMetaLoaded[id] = true; delete chatsMetaCache[id]; onChatsMetaChanged(); });
2145
+ });
2146
+ onChatsMetaChanged();
2147
+ }
2148
+
2149
+ function reconcileServerWatchers(){
2150
+ Object.keys(serverWatch).forEach(id => {
2151
+ if(!myServerIds[id]){
2152
+ serverWatch[id].off(); serverChanWatch[id].off();
2153
+ delete serverWatch[id]; delete serverChanWatch[id]; delete serversCache[id]; delete serverChanIds[id];
2154
+ }
2155
+ });
2156
+ Object.keys(myServerIds).forEach(id => {
2157
+ if(serverWatch[id]) return;
2158
+ serverWatch[id] = db.ref('servers/' + id);
2159
+ serverWatch[id].on('value',
2160
+ s => { if(s.exists()) serversCache[id] = s.val(); else delete serversCache[id]; onServersChanged(); },
2161
+ () => { delete serversCache[id]; onServersChanged(); });
2162
+ serverChanWatch[id] = db.ref('serverChannels/' + id);
2163
+ serverChanWatch[id].on('value',
2164
+ s => { serverChanIds[id] = s.val() || {}; reconcileChatMetaWatchers(); },
2165
+ () => {});
2166
+ });
2167
+ reconcileChatMetaWatchers();
2168
+ onServersChanged();
2169
+ }
2170
+
2171
+ function onChatsMetaChanged(){
2172
+ if(needInitialChat && Object.values(chatsMetaCache).some(meta => meta?.type === 'public')){ needInitialChat = false; openDefaultChat(); }
2173
+ else if(currentChatId && chatMetaLoaded[currentChatId] && !chatsMetaCache[currentChatId]) openDefaultChat();
2174
+ renderGroupsList();
2175
+ renderPublicChannelsList();
2176
+ if(currentChatId){ updateCurrentChatLabel(); updateComposerState(); }
2177
+ updateHeaderCallButtons();
2178
+ reconcileVoiceWatchers();
2179
+
2180
+ }
2181
+
2182
+ function onServersChanged(){
2183
+ if(currentServerId && !myServerIds[currentServerId]){
2184
+ currentServerId = null; updateSidebarForServer(); openDefaultChat();
2185
+ }
2186
+ updateSidebarForServer();
2187
+ renderGroupsList();
2188
+ }
2189
+
2190
+ // voice participants are watched per chat (never a global listener)
2191
+ function reconcileVoiceWatchers(){
2192
+ Object.keys(voiceWatch).forEach(id => {
2193
+ if(!chatsMetaCache[id]){ voiceWatch[id].ref.off('value', voiceWatch[id].cb); delete voiceWatch[id]; delete voiceParticipantsAllCache[id]; }
2194
+ });
2195
+ Object.keys(chatsMetaCache).forEach(id => {
2196
+ const m = chatsMetaCache[id];
2197
+ if(m?.type !== 'group' || voiceWatch[id]) return;
2198
+ const ref = db.ref('voiceChannels/' + id + '/participants');
2199
+ const cb = s => {
2200
+ voiceParticipantsAllCache[id] = s.val() || {};
2201
+ renderGroupsList(); renderPublicChannelsList();
2202
+ if(voiceState.chatId) renderVoiceChips();
2203
+ updateVoiceStatusBar();
2204
+ };
2205
+ voiceWatch[id] = { ref, cb };
2206
+ ref.on('value', cb, () => {});
2207
+ });
2208
+ }
2209
+
2210
+ function stopAllWatchers(){
2211
+ [myChatIdsRef, myServerIdsRef, publicChatIdsRef, ownerPublicQuery].forEach(r => { if(r) r.off('value'); });
2212
+ myChatIdsRef = myServerIdsRef = publicChatIdsRef = ownerPublicQuery = null;
2213
+ ownerPublicIds = {};
2214
+ Object.values(chatMetaWatch).forEach(r => r.off());
2215
+ Object.values(serverWatch).forEach(r => r.off());
2216
+ Object.values(serverChanWatch).forEach(r => r.off());
2217
+ Object.values(voiceWatch).forEach(w => w.ref.off('value', w.cb));
2218
+ Object.values(notifyWatch).forEach(w => w.ref.off('child_added', w.cb));
2219
+ notifyWatch = {}; unreadCache = {}; updateTitleBadge();
2220
+ if(pinnedRef){ pinnedRef.off('value'); pinnedRef = null; }
2221
+ chatMetaWatch = {}; chatMetaLoaded = {}; serverWatch = {}; serverChanWatch = {}; voiceWatch = {};
2222
+ myChatIds = {}; myServerIds = {}; publicChatIds = {}; serverChanIds = {};
2223
+ }
2224
+
2225
+ /* =========================================================
2226
+ CHATS
2227
+ ========================================================= */
2228
+ async function ensureGeneralChatExists(){
2229
+ if(!isOwnerKey(myKey)) return;
2230
+ try{
2231
+ if((await db.ref('system/generalInitialized').get()).val() === true) return;
2232
+ const pc = await db.ref('publicChannels/' + GENERAL_CHAT_ID).get();
2233
+ if(pc.exists()){ await db.ref('system/generalInitialized').set(true); return; }
2234
+ await db.ref('chatsMeta/' + GENERAL_CHAT_ID).set({ type:'public', name:'general', createdBy:'system', created: firebase.database.ServerValue.TIMESTAMP });
2235
+ await db.ref('publicChannels/' + GENERAL_CHAT_ID).set(true);
2236
+ await db.ref('system/generalInitialized').set(true);
2237
+ }catch(err){ console.error('Could not create #general', err); }
2238
+ }
2239
+
2240
+ function isMemberOf(meta){
2241
+ if(!meta) return false;
2242
+ if(meta.type === 'public') return true;
2243
+ if(meta.serverId){ const sv = serversCache[meta.serverId]; return !!sv?.members?.[myKey]; }
2244
+ return !!(meta.members && meta.members[myKey]);
2245
+ }
2246
+ function canAccessChat(meta){ return isMemberOf(meta); }
2247
+ function canManageChannel(meta){
2248
+ if(!meta) return false;
2249
+ if(meta.createdBy === myKey) return true;
2250
+ const sv = meta.serverId ? serversCache[meta.serverId] : null;
2251
+ if(sv && sv.createdBy === myKey) return true;
2252
+ if(canUseAdmin('publicChannels') && meta.type === 'public') return true;
2253
+ return false;
2254
+ }
2255
+
2256
+ /* ---------- invite codes ---------- */
2257
+ function generateInviteCode(){
2258
+ const chars = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
2259
+ let s = ''; for(let i=0;i<6;i++) s += chars[Math.floor(Math.random()*chars.length)];
2260
+ return s;
2261
+ }
2262
+ async function ensureInviteCode(chatId){
2263
+ const meta = chatsMetaCache[chatId];
2264
+ if(meta && meta.inviteCode) return meta.inviteCode;
2265
+ let code = generateInviteCode();
2266
+ for(let tries=0; tries<5; tries++){
2267
+ const taken = await db.ref('inviteCodes/' + code).get();
2268
+ if(!taken.exists()) break;
2269
+ code = generateInviteCode();
2270
+ }
2271
+ await db.ref('inviteCodes/' + code).set(chatId);
2272
+ await db.ref('chatsMeta/' + chatId + '/inviteCode').set(code);
2273
+ return code;
2274
+ }
2275
+ let inviteModalChatId = null;
2276
+ async function openInviteModal(){
2277
+ if(!currentChatId) return;
2278
+ const meta = chatsMetaCache[currentChatId];
2279
+ if(!meta || meta.type !== 'group' || meta.serverId) return;
2280
+ inviteModalChatId = currentChatId; inviteModalServerId = null;
2281
+ document.getElementById('inviteErr').textContent = '';
2282
+ document.getElementById('inviteErr').className = 'modal-err';
2283
+ document.getElementById('inviteCodeBox').textContent = '······';
2284
+ document.getElementById('inviteModal').classList.add('open');
2285
+ try{ document.getElementById('inviteCodeBox').textContent = await ensureInviteCode(currentChatId); }
2286
+ catch(err){ console.error(err); document.getElementById('inviteErr').textContent = 'Could not create a code: ' + (err.message || 'unknown error'); }
2287
+ }
2288
+ function closeInviteModal(){ document.getElementById('inviteModal').classList.remove('open'); inviteModalChatId = null; inviteModalServerId = null; }
2289
+ function copyInviteCode(){
2290
+ const code = document.getElementById('inviteCodeBox').textContent.trim();
2291
+ const errEl = document.getElementById('inviteErr');
2292
+ if(!code || code.indexOf('·') === 0) return;
2293
+ const done = () => { errEl.className = 'modal-err ok'; errEl.textContent = 'Code copied.'; };
2294
+ if(navigator.clipboard && navigator.clipboard.writeText){
2295
+ navigator.clipboard.writeText(code).then(done).catch(() => { errEl.className = 'modal-err'; errEl.textContent = 'Copy failed — select the code and copy it manually.'; });
2296
+ } else { errEl.className = 'modal-err'; errEl.textContent = 'Select the code above and copy it manually.'; }
2297
+ }
2298
+ async function regenerateInviteCode(){
2299
+ const errEl = document.getElementById('inviteErr');
2300
+ errEl.className = 'modal-err';
2301
+ if(inviteModalServerId){
2302
+ const sv = serversCache[inviteModalServerId];
2303
+ if(!sv || sv.createdBy !== myKey){ errEl.textContent = 'Only the server owner can reset the code.'; return; }
2304
+ try{
2305
+ if(sv.inviteCode) await db.ref('serverInvites/' + sv.inviteCode).remove();
2306
+ await db.ref('servers/' + inviteModalServerId + '/inviteCode').remove();
2307
+ document.getElementById('inviteCodeBox').textContent = await ensureServerInvite(inviteModalServerId);
2308
+ errEl.className = 'modal-err ok'; errEl.textContent = 'New code created. The old one no longer works.';
2309
+ }catch(err){ console.error(err); errEl.textContent = 'Could not reset the code: ' + (err.message || 'unknown error'); }
2310
+ return;
2311
+ }
2312
+ if(!inviteModalChatId) return;
2313
+ const meta = chatsMetaCache[inviteModalChatId];
2314
+ if(!canManageChannel(meta)){ errEl.textContent = 'Only the server creator can reset the code.'; return; }
2315
+ try{
2316
+ if(meta.inviteCode) await db.ref('inviteCodes/' + meta.inviteCode).remove();
2317
+ await db.ref('chatsMeta/' + inviteModalChatId + '/inviteCode').remove();
2318
+ document.getElementById('inviteCodeBox').textContent = await ensureInviteCode(inviteModalChatId);
2319
+ errEl.className = 'modal-err ok'; errEl.textContent = 'New code created. The old one no longer works.';
2320
+ }catch(err){ console.error(err); errEl.textContent = 'Could not reset the code: ' + (err.message || 'unknown error'); }
2321
+ }
2322
+
2323
+ async function joinChannelByCode(){
2324
+ const input = document.getElementById('joinCodeInput');
2325
+ const msgEl = document.getElementById('joinCodeMsg');
2326
+ msgEl.className = 'add-friend-msg';
2327
+ const code = input.value.trim().toUpperCase();
2328
+ if(!code){ msgEl.textContent = 'Paste an invite code first.'; return; }
2329
+ try{
2330
+ const snap = await db.ref('inviteCodes/' + code).get();
2331
+ if(!snap.exists()){ msgEl.textContent = 'That code does not match any channel.'; return; }
2332
+ const chatId = snap.val();
2333
+ // the code itself is the proof of invitation; the database rules check it
2334
+ await db.ref('chatsMeta/' + chatId + '/members/' + myKey).set(code);
2335
+ await db.ref('memberships/' + myKey + '/chats/' + chatId).set(true);
2336
+ input.value = '';
2337
+ msgEl.className = 'add-friend-msg ok'; msgEl.textContent = 'Joined!';
2338
+ await waitFor(() => chatsMetaCache[chatId], 4000);
2339
+ openChat(chatId); closeSidebarMobile();
2340
+ }catch(err){ console.error(err); msgEl.textContent = 'Could not join: ' + (err.message || 'unknown error'); }
2341
+ }
2342
+
2343
+ /* ---------- channel lists ---------- */
2344
+ function renderPublicChannelsList(){
2345
+ const list = document.getElementById('publicChannelsList');
2346
+ if(!list) return;
2347
+ const gn = document.getElementById('generalNavBtn');
2348
+ if(gn) gn.style.display = chatsMetaCache[GENERAL_CHAT_ID] ? '' : 'none';
2349
+ const gu = document.getElementById('generalUnread'); if(gu) gu.innerHTML = unreadBadge(GENERAL_CHAT_ID);
2350
+ const ids = Object.keys(chatsMetaCache).filter(id => chatsMetaCache[id] && chatsMetaCache[id].type === 'public');
2351
+ ids.sort((a,b) => { if(a === GENERAL_CHAT_ID) return -1; if(b === GENERAL_CHAT_ID) return 1; return (chatsMetaCache[a].created||0) - (chatsMetaCache[b].created||0); });
2352
+ if(!ids.length){ list.innerHTML = '<div class="empty-list-note">No public channels yet.</div>'; return; }
2353
+ list.innerHTML = ids.map(id => {
2354
+ const meta = chatsMetaCache[id];
2355
+ const voiceCount = Object.keys(voiceParticipantsAllCache[id] || {}).length;
2356
+ const manage = canManageChannel(meta);
2357
+ return `<div class="list-item ${id === currentChatId ? 'active' : ''}" onclick="openChatFromSidebar(${inlineArg(id)})">
2358
+ <span class="hash">#</span>
2359
+ <span class="item-name">${escapeHtml(meta.name || 'unnamed')}</span>${unreadBadge(id)}
2360
+ ${voiceCount ? `<span class="voice-count">🎙️${voiceCount}</span>` : ''}
2361
+ ${manage ? `<button class="mini-btn nick" onclick="event.stopPropagation(); renameChannel(${inlineArg(id)})" title="Rename server">✏️</button>` : ''}
2362
+ ${manage ? `<button class="mini-btn del" onclick="event.stopPropagation(); deleteChannel(${inlineArg(id)})" title="Delete server">✕</button>` : ''}
2363
+ </div>`;
2364
+ }).join('');
2365
+ }
2366
+ function renderGroupsList(){
2367
+ const list = document.getElementById('groupsList');
2368
+ let ids = Object.keys(chatsMetaCache).filter(id => {
2369
+ const meta = chatsMetaCache[id];
2370
+ if(!meta || meta.type !== 'group') return false;
2371
+ if(!isMemberOf(meta)) return false;
2372
+ if(currentServerId) return meta.serverId === currentServerId;
2373
+ return !meta.serverId;
2374
+ });
2375
+ ids.sort((a,b) => (chatsMetaCache[a].created||0) - (chatsMetaCache[b].created||0));
2376
+ if(!ids.length){ list.innerHTML = '<div class="empty-list-note">No channels yet. Create one, or join with an invite code.</div>'; return; }
2377
+ list.innerHTML = ids.map(id => {
2378
+ const meta = chatsMetaCache[id];
2379
+ const voiceCount = Object.keys(voiceParticipantsAllCache[id] || {}).length;
2380
+ const amMember = !!(meta.members && meta.members[myKey]);
2381
+ const inServer = !!meta.serverId;
2382
+ return `<div class="list-item ${id === currentChatId ? 'active' : ''}" onclick="openChatFromSidebar(${inlineArg(id)})">
2383
+ <span class="hash">#</span>
2384
+ <span class="item-name">${escapeHtml(meta.name || 'unnamed')}</span>${unreadBadge(id)}
2385
+ ${voiceCount ? `<span class="voice-count">🎙️${voiceCount}</span>` : ''}
2386
+ ${inServer ? '' : `<button class="mini-btn addppl" onclick="event.stopPropagation(); openAddMemberFor(${inlineArg(id)})" title="Add people">+</button>`}
2387
+ ${canManageChannel(meta) ? `<button class="mini-btn nick" onclick="event.stopPropagation(); renameChannel(${inlineArg(id)})" title="Rename server">✏️</button>` : ''}
2388
+ ${inServer ? '' : `<button class="mini-btn invite" onclick="event.stopPropagation(); openInviteFor(${inlineArg(id)})" title="Invite code">🔗</button>`}
2389
+ ${(amMember && !inServer) ? `<button class="mini-btn leave" onclick="event.stopPropagation(); leaveChannel(${inlineArg(id)})" title="Leave server">🚪</button>` : ''}
2390
+ ${canManageChannel(meta) ? `<button class="mini-btn del" onclick="event.stopPropagation(); deleteChannel(${inlineArg(id)})" title="Delete server">✕</button>` : ''}
2391
+ </div>`;
2392
+ }).join('');
2393
+ }
2394
+ function openChatFromSidebar(chatId){ openChat(chatId); closeSidebarMobile(); }
2395
+ function openInviteFor(chatId){ openChat(chatId); setTimeout(openInviteModal, 30); }
2396
+ function openAddMemberFor(chatId){ openChat(chatId); setTimeout(openAddMemberModal, 30); }
2397
+ function openGeneralChat(){ openDefaultChat(); }
2398
+ function openDefaultChat(){
2399
+ if(chatsMetaCache[GENERAL_CHAT_ID]){ openChat(GENERAL_CHAT_ID); return; }
2400
+ const firstPublic = Object.keys(chatsMetaCache).find(id => chatsMetaCache[id] && chatsMetaCache[id].type === 'public');
2401
+ if(firstPublic) openChat(firstPublic); else clearChatView();
2402
+ }
2403
+ function openFriendDm(friendKey){
2404
+ if(!friendsCache[friendKey]) return;
2405
+ closeFriendsScreen();
2406
+ const id = dmChatId(myKey, friendKey);
2407
+ ensureDmChatExists(id, friendKey).then(() => { openChat(id); closeSidebarMobile(); });
2408
+ }
2409
+ async function ensureDmChatExists(chatId, friendKey){
2410
+ if(myChatIds[chatId] && chatsMetaCache[chatId]) return;
2411
+ try{
2412
+ await db.ref('chatsMeta/' + chatId).set({ type:'dm', members:{ [myKey]:true, [friendKey]:true }, created: firebase.database.ServerValue.TIMESTAMP });
2413
+ }catch(err){ /* already exists — fine */ }
2414
+ try{
2415
+ await db.ref('memberships/' + myKey + '/chats/' + chatId).set(true);
2416
+ await db.ref('memberships/' + friendKey + '/chats/' + chatId).set(true);
2417
+ }catch(err){ console.error('Could not index DM', err); }
2418
+ }
2419
+
2420
+ function openChat(chatId){
2421
+ document.getElementById('commandsScreen').hidden = true;
2422
+ document.getElementById('friendsScreen').hidden = true;
2423
+ document.getElementById('chatScreen').inert = false;
2424
+
2425
+ needInitialChat = false;
2426
+ const _meta = chatsMetaCache[chatId];
2427
+ if(_meta && !canAccessChat(_meta)){ clearChatView(); return; }
2428
+ currentChatId = chatId;
2429
+ currentChatMeta = chatsMetaCache[chatId] || null;
2430
+ currentMessagesList = [];
2431
+ delete unreadCache[chatId]; updateTitleBadge();
2432
+ closeSearch();
2433
+ document.getElementById('generalNavBtn').classList.toggle('active', chatId === GENERAL_CHAT_ID);
2434
+ renderFriendsList(); renderGroupsList(); renderPublicChannelsList(); renderServerRail();
2435
+ updateCurrentChatLabel(); updateHeaderCallButtons(); updateVoicePanelVisibility(); updateComposerState();
2436
+ startMessageListener();
2437
+ }
2438
+ function clearChatView(){
2439
+ stopMessageListener(); stopTypingListener();
2440
+ currentChatId = null; currentChatMeta = null; currentMessagesList = [];
2441
+ document.getElementById('currentChatLabel').textContent = '';
2442
+ document.getElementById('currentChatSub').textContent = '';
2443
+ document.getElementById('messages').innerHTML = '<div class="empty-state"><span class="glyph">👥</span>Pick a server or a friend to begin.</div>';
2444
+ updateHeaderCallButtons(); updateVoicePanelVisibility(); renderServerRail();
2445
+ }
2446
+ function updateCurrentChatLabel(){
2447
+ const meta = chatsMetaCache[currentChatId] || currentChatMeta;
2448
+ currentChatMeta = meta || currentChatMeta;
2449
+ const label = document.getElementById('currentChatLabel');
2450
+ const sub = document.getElementById('currentChatSub');
2451
+ if(!meta){ label.textContent=''; sub.textContent=''; return; }
2452
+ if(meta.type === 'public'){
2453
+ label.textContent = '# ' + (meta.name || 'general');
2454
+ sub.textContent = 'Public server — everyone can read';
2455
+ } else if(meta.type === 'dm'){
2456
+ const otherKey = Object.keys(meta.members || {}).find(k => k !== myKey);
2457
+ label.textContent = '@' + displayNameFor(friendsCache[otherKey] || (otherKey || ''));
2458
+ sub.textContent = isOnline(otherKey) ? 'Online' : 'Offline';
2459
+ } else {
2460
+ label.textContent = '#' + (meta.name || 'unnamed');
2461
+ const sv = meta.serverId ? serversCache[meta.serverId] : null;
2462
+ if(sv){ sub.textContent = (sv.name || 'Server') + ' · private server'; }
2463
+ else { const n = Object.keys(meta.members || {}).length; sub.textContent = n + (n === 1 ? ' member' : ' members') + ' · anyone here can invite'; }
2464
+ }
2465
+ }
2466
+ function currentDmFriendKey(){
2467
+ if(!currentChatMeta || currentChatMeta.type !== 'dm') return null;
2468
+ return Object.keys(currentChatMeta.members || {}).find(k => k !== myKey) || null;
2469
+ }
2470
+ function updateHeaderCallButtons(){
2471
+ const friendKey = currentDmFriendKey();
2472
+ const showCall = !!friendKey && !!friendsCache[friendKey];
2473
+ document.getElementById('headerCallAudioBtn').style.display = showCall ? 'inline-block' : 'none';
2474
+ document.getElementById('headerCallVideoBtn').style.display = showCall ? 'inline-block' : 'none';
2475
+ const meta = chatsMetaCache[currentChatId] || currentChatMeta;
2476
+ const isGroup = !!meta && meta.type === 'group';
2477
+ const isPublic = !!meta && meta.type === 'public';
2478
+ const inServer = isGroup && !!meta.serverId;
2479
+ const amMember = isGroup && !inServer && !!(meta.members && meta.members[myKey]);
2480
+ const manage = canManageChannel(meta);
2481
+ document.getElementById('headerAddPeopleBtn').style.display = (isGroup && !inServer) ? 'inline-block' : 'none';
2482
+ document.getElementById('headerRenameBtn').style.display = ((isGroup || isPublic) && manage) ? 'inline-block' : 'none';
2483
+ document.getElementById('headerInviteBtn').style.display = (isGroup && !inServer) ? 'inline-block' : 'none';
2484
+ document.getElementById('headerLeaveBtn').style.display = amMember ? 'inline-block' : 'none';
2485
+ updateMuteButtons();
2486
+ }
2487
+ function startCallWithCurrentFriend(type){
2488
+ const friendKey = currentDmFriendKey();
2489
+ if(!friendKey || !friendsCache[friendKey]) return;
2490
+ startCall(friendKey, friendsCache[friendKey], type);
2491
+ }
2492
+
2493
+ /* =========================================================
2494
+ SERVERS — private, member-only, customizable
2495
+ ========================================================= */
2496
+ function shade(hex, amt){
2497
+ const n = parseInt(hex.slice(1), 16);
2498
+ const c = [(n>>16)+amt, ((n>>8)&255)+amt, (n&255)+amt].map(v => Math.max(0, Math.min(255, v)));
2499
+ return '#' + ((1<<24) + (c[0]<<16) + (c[1]<<8) + c[2]).toString(16).slice(1);
2500
+ }
2501
+ function applyServerTheme(sv){
2502
+ const c = (sv && /^#[0-9a-f]{6}$/i.test(sv.color || '')) ? sv.color : '#5865f2';
2503
+ document.documentElement.style.setProperty('--blurple', c);
2504
+ document.documentElement.style.setProperty('--blurple-hover', shade(c, -24));
2505
+ }
2506
+
2507
+ function renderServerRail(){
2508
+ const list = document.getElementById('serverRailList');
2509
+ const home = document.getElementById('railHome');
2510
+ if(!list || !home) return;
2511
+ home.classList.toggle('active', !currentServerId);
2512
+ const ids = Object.keys(serversCache)
2513
+ .filter(id => serversCache[id] && serversCache[id].members && serversCache[id].members[myKey])
2514
+ .sort((a,b) => (serversCache[a].created||0) - (serversCache[b].created||0));
2515
+ list.innerHTML = ids.map(id => {
2516
+ const sv = serversCache[id];
2517
+ const safeIcon = sv.icon || null;
2518
+ const inner = safeIcon
2519
+ ? `<img src="${escapeHtml(safeIcon)}" alt="" style="width:100%;height:100%;object-fit:cover;">`
2520
+ : escapeHtml(sv.emoji || (sv.name || '?').trim().charAt(0).toUpperCase() || '?');
2521
+ const un = Object.keys(chatsMetaCache).filter(c => chatsMetaCache[c] && chatsMetaCache[c].serverId === id).reduce((n, c) => n + (unreadCache[c] || 0), 0);
2522
+ return `<div class="rail-icon ${id === currentServerId ? 'active' : ''}" title="${escapeHtml(sv.name || 'server')}" onclick="selectServer(${inlineArg(id)})">${inner}${un ? `<span class="rail-badge">${un > 99 ? '99+' : un}</span>` : ''}</div>`;
2523
+ }).join('');
2524
+ renderPinnedRail();
2525
+ }
2526
+ function updateSidebarForServer(){
2527
+ const sv = currentServerId ? serversCache[currentServerId] : null;
2528
+ document.getElementById('publicChannelsBlock').style.display = sv ? 'none' : 'block';
2529
+ document.getElementById('channelsTitle').textContent = sv ? 'Server Channels' : 'Your Channels';
2530
+ document.getElementById('serverActions').style.display = sv ? 'block' : 'none';
2531
+ const del = document.getElementById('deleteServerBtn');
2532
+ if(del) del.style.display = (sv && sv.createdBy === myKey) ? 'inline-block' : 'none';
2533
+ applyServerTheme(sv);
2534
+ updateMuteButtons();
2535
+ renderServerMembers();
2536
+ const desc = document.getElementById('chanColDesc');
2537
+ desc.textContent = (sv && sv.description) ? sv.description : '';
2538
+ desc.style.display = (sv && sv.description) ? 'block' : 'none';
2539
+ const ban = document.getElementById('chanColBanner');
2540
+ const head = document.getElementById('chanColHeader');
2541
+ if(sv){
2542
+ const accent = /^#[0-9a-f]{6}$/i.test(sv.color || '') ? sv.color : '#5865f2';
2543
+ const bUrl = sv.banner || null;
2544
+ ban.style.display = 'flex';
2545
+ ban.style.backgroundImage = bUrl
2546
+ ? 'linear-gradient(rgba(0,0,0,0) 35%, rgba(0,0,0,.7)), url("' + bUrl.replace(/"/g, '%22') + '")'
2547
+ : 'linear-gradient(135deg, ' + accent + ', ' + shade(accent, -70) + ')';
2548
+ ban.innerHTML = '<span class="banner-name">' + escapeHtml((sv.emoji ? sv.emoji + ' ' : '') + (sv.name || 'Server')) + '</span>';
2549
+ head.style.display = '';
2550
+ } else {
2551
+ ban.style.display = 'none'; ban.innerHTML = ''; ban.style.backgroundImage = '';
2552
+ head.style.display = '';
2553
+ }
2554
+ renderServerRail();
2555
+ }
2556
+ function goHome(){
2557
+ currentServerId = null;
2558
+ updateSidebarForServer(); renderGroupsList(); openDefaultChat();
2559
+ }
2560
+ function selectServer(id, preferChatId){
2561
+ const sv = serversCache[id];
2562
+ if(!sv || !(sv.members && sv.members[myKey])) return;
2563
+ currentServerId = id;
2564
+ updateSidebarForServer(); renderGroupsList();
2565
+ let chatId = preferChatId;
2566
+ if(!chatId){
2567
+ const ids = Object.keys(chatsMetaCache).filter(c => chatsMetaCache[c] && chatsMetaCache[c].serverId === id)
2568
+ .sort((a,b) => (chatsMetaCache[a].created||0) - (chatsMetaCache[b].created||0));
2569
+ chatId = ids[0];
2570
+ }
2571
+ if(chatId) openChat(chatId); else clearChatView();
2572
+ }
2573
+ function openServerModal(){
2574
+ document.getElementById('newServerName').value = '';
2575
+ document.getElementById('joinServerCode').value = '';
2576
+ document.getElementById('serverErr').textContent = '';
2577
+ document.getElementById('serverErr').className = 'modal-err';
2578
+ document.getElementById('serverModal').classList.add('open');
2579
+ setTimeout(() => document.getElementById('newServerName').focus(), 50);
2580
+ }
2581
+ function closeServerModal(){ document.getElementById('serverModal').classList.remove('open'); }
2582
+
2583
+ async function ensureServerInvite(serverId){
2584
+ const sv = serversCache[serverId];
2585
+ if(sv && sv.inviteCode) return sv.inviteCode;
2586
+ let code = generateInviteCode();
2587
+ for(let tries=0; tries<5; tries++){
2588
+ const taken = await db.ref('serverInvites/' + code).get();
2589
+ if(!taken.exists()) break;
2590
+ code = generateInviteCode();
2591
+ }
2592
+ await db.ref('serverInvites/' + code).set(serverId);
2593
+ await db.ref('servers/' + serverId + '/inviteCode').set(code);
2594
+ return code;
2595
+ }
2596
+
2597
+ async function createServer(){
2598
+ const errEl = document.getElementById('serverErr');
2599
+ errEl.className = 'modal-err';
2600
+ const name = document.getElementById('newServerName').value.trim();
2601
+ if(!name){ errEl.textContent = 'Give the server a name.'; return; }
2602
+ if(!nameIsClean(name)){ errEl.textContent = "That server name isn't allowed."; return; }
2603
+ try{
2604
+ const TS = firebase.database.ServerValue.TIMESTAMP;
2605
+ const srvRef = db.ref('servers').push();
2606
+ await srvRef.set({ name, createdBy: myKey, members: { [myKey]: true }, created: TS });
2607
+ const chRef = db.ref('chatsMeta').push();
2608
+ await chRef.set({ type:'group', name:'general', serverId: srvRef.key, members: { [myKey]: true }, createdBy: myKey, created: TS });
2609
+ await db.ref('serverChannels/' + srvRef.key + '/' + chRef.key).set(true);
2610
+ await db.ref('memberships/' + myKey + '/servers/' + srvRef.key).set(true);
2611
+ await ensureServerInvite(srvRef.key);
2612
+ closeServerModal();
2613
+ await waitFor(() => serversCache[srvRef.key] && chatsMetaCache[chRef.key], 4000);
2614
+ selectServer(srvRef.key, chRef.key);
2615
+ }catch(err){ console.error(err); errEl.textContent = 'Could not create server: ' + (err && err.message ? err.message : 'unknown error'); }
2616
+ }
2617
+
2618
+ async function joinServerByCode(){
2619
+ const errEl = document.getElementById('serverErr');
2620
+ errEl.className = 'modal-err';
2621
+ const code = document.getElementById('joinServerCode').value.trim().toUpperCase();
2622
+ if(!code){ errEl.textContent = 'Paste an invite code first.'; return; }
2623
+ try{
2624
+ const snap = await db.ref('serverInvites/' + code).get();
2625
+ if(!snap.exists()){ errEl.textContent = 'That code does not match any server.'; return; }
2626
+ const id = snap.val();
2627
+ await db.ref('servers/' + id + '/members/' + myKey).set(code); // the code is the proof of invitation
2628
+ await db.ref('memberships/' + myKey + '/servers/' + id).set(true);
2629
+ closeServerModal();
2630
+ await waitFor(() => serversCache[id] && Object.keys(serverChanIds[id] || {}).some(c => chatsMetaCache[c]), 4000);
2631
+ selectServer(id);
2632
+ }catch(err){ console.error(err); errEl.textContent = 'Could not join: ' + (err && err.message ? err.message : 'unknown error'); }
2633
+ }
2634
+
2635
+ async function openServerInvite(){
2636
+ if(!currentServerId) return;
2637
+ inviteModalChatId = null; inviteModalServerId = currentServerId;
2638
+ document.getElementById('inviteErr').textContent = '';
2639
+ document.getElementById('inviteErr').className = 'modal-err';
2640
+ document.getElementById('inviteCodeBox').textContent = '······';
2641
+ document.getElementById('inviteModal').classList.add('open');
2642
+ try{ document.getElementById('inviteCodeBox').textContent = await ensureServerInvite(currentServerId); }
2643
+ catch(err){ console.error(err); document.getElementById('inviteErr').textContent = 'Could not create a code: ' + (err.message || 'unknown error'); }
2644
+ }
2645
+ async function leaveCurrentServer(){
2646
+ const id = currentServerId, sv = serversCache[id];
2647
+ if(!sv) return;
2648
+ if(!confirm('Leave "' + (sv.name || 'this server') + '"? You can rejoin with an invite code.')) return;
2649
+ try{
2650
+ await db.ref('servers/' + id + '/members/' + myKey).remove();
2651
+ await db.ref('memberships/' + myKey + '/servers/' + id).remove();
2652
+ goHome();
2653
+ }catch(err){ console.error('Failed to leave server', err); }
2654
+ }
2655
+ async function deleteCurrentServer(){
2656
+ const id = currentServerId, sv = serversCache[id];
2657
+ if(!sv) return;
2658
+ if(sv.createdBy !== myKey){ alert('Only the server owner can delete this.'); return; }
2659
+ if(!confirm('Delete server "' + (sv.name || id) + '" and ALL its channels and messages? This cannot be undone.')) return;
2660
+ try{
2661
+ for(const c of Object.keys(serverChanIds[id] || {})){
2662
+ const m = chatsMetaCache[c];
2663
+ await db.ref('chatsMsgs/' + c).remove();
2664
+ await db.ref('voiceChannels/' + c).remove();
2665
+ if(m && m.inviteCode) await db.ref('inviteCodes/' + m.inviteCode).remove();
2666
+ await db.ref('chatsMeta/' + c).remove();
2667
+ }
2668
+ await db.ref('serverChannels/' + id).remove();
2669
+ for(const k of Object.keys(sv.members || {})) await db.ref('memberships/' + k + '/servers/' + id).remove().catch(()=>{});
2670
+ if(sv.inviteCode) await db.ref('serverInvites/' + sv.inviteCode).remove();
2671
+ await db.ref('servers/' + id).remove();
2672
+ goHome();
2673
+ }catch(err){ console.error('Failed to delete server', err); alert('Could not delete server: ' + err.message); }
2674
+ }
2675
+
2676
+ /* ---------- server settings (name, description, emoji, icon, banner, color) ---------- */
2677
+ let serverSettingsId = null;
2678
+ function openServerSettings(){
2679
+ if(!currentServerId) return;
2680
+ const sv = serversCache[currentServerId];
2681
+ if(!sv) return;
2682
+ serverSettingsId = currentServerId;
2683
+ const isOwner = sv.createdBy === myKey;
2684
+ document.getElementById('serverSettingsSub').textContent = 'Editing: ' + (sv.name || 'server');
2685
+ document.getElementById('serverSettingsOwnerFields').style.display = isOwner ? 'block' : 'none';
2686
+ document.getElementById('serverSettingsName').value = sv.name || '';
2687
+ document.getElementById('serverSettingsDesc').value = sv.description || '';
2688
+ document.getElementById('serverSettingsEmoji').value = sv.emoji || '';
2689
+ document.getElementById('serverSettingsIcon').value = sv.icon || '';
2690
+ document.getElementById('serverSettingsBanner').value = sv.banner || '';
2691
+ document.getElementById('serverSettingsColor').value = /^#[0-9a-f]{6}$/i.test(sv.color || '') ? sv.color : '#5865f2';
2692
+ document.getElementById('serverSettingsDeleteBtn').style.display = isOwner ? 'inline-block' : 'none';
2693
+ const err = document.getElementById('serverSettingsErr');
2694
+ err.className = 'modal-err'; err.textContent = '';
2695
+ renderServerMembersList();
2696
+ document.getElementById('serverSettingsModal').classList.add('open');
2697
+ }
2698
+ function closeServerSettings(){ document.getElementById('serverSettingsModal').classList.remove('open'); serverSettingsId = null; }
2699
+ function renderServerMembersList(){
2700
+ const sv = serversCache[serverSettingsId];
2701
+ const list = document.getElementById('serverMembersList');
2702
+ if(!sv){ list.innerHTML = ''; return; }
2703
+ const isOwner = sv.createdBy === myKey;
2704
+ const keys = Object.keys(sv.members || {});
2705
+ if(!keys.length){ list.innerHTML = '<div class="empty-list-note">No members yet.</div>'; return; }
2706
+ list.innerHTML = keys.map(k => {
2707
+ const name = (statusCache[k] && statusCache[k].username) || friendsCache[k] || (k === myKey ? currentUser : k);
2708
+ const own = (k === sv.createdBy) ? ' <span class="owner-tag">👑 OWNER</span>' : '';
2709
+ const kick = (isOwner && k !== myKey) ? `<button class="mini-btn" onclick="kickServerMember(${inlineArg(k)})" title="Kick">✕</button>` : '';
2710
+ return `<div class="member-row"><span>${escapeHtml(displayNameFor(name))}${own}</span>${kick}</div>`;
2711
+ }).join('');
2712
+ }
2713
+ async function kickServerMember(key){
2714
+ const sv = serversCache[serverSettingsId];
2715
+ if(!sv || sv.createdBy !== myKey || key === myKey || isOwnerKey(key) || (adminRoles[key] && !isOwnerKey(myKey))) return;
2716
+ if(!confirm('Remove this member from the server?')) return;
2717
+ try{
2718
+ await db.ref('servers/' + serverSettingsId + '/members/' + key).remove();
2719
+ await db.ref('memberships/' + key + '/servers/' + serverSettingsId).remove();
2720
+ }catch(err){ console.error('Failed to kick member', err); }
2721
+ }
2722
+ // Resize + crop a picked image on the device and store it as a small data URL (scannable, no hosting needed).
2723
+ function loadServerImageFile(fileInput, targetId, w, h){
2724
+ const file = fileInput.files && fileInput.files[0];
2725
+ const errEl = document.getElementById('serverSettingsErr');
2726
+ if(!file) return;
2727
+ if(!/^image\//.test(file.type)){ errEl.className = 'modal-err'; errEl.textContent = 'Pick an image file.'; return; }
2728
+ const img = new Image();
2729
+ img.onload = () => {
2730
+ const c = document.createElement('canvas'); c.width = w; c.height = h;
2731
+ const ctx = c.getContext('2d');
2732
+ const k = Math.max(w / img.width, h / img.height);
2733
+ const dw = img.width * k, dh = img.height * k;
2734
+ ctx.drawImage(img, (w - dw) / 2, (h - dh) / 2, dw, dh);
2735
+ document.getElementById(targetId).value = c.toDataURL('image/jpeg', 0.8);
2736
+ errEl.className = 'modal-err ok'; errEl.textContent = 'Image loaded — press Save changes.';
2737
+ URL.revokeObjectURL(img.src);
2738
+ };
2739
+ img.onerror = () => { errEl.className = 'modal-err'; errEl.textContent = "Couldn't read that image."; };
2740
+ img.src = URL.createObjectURL(file);
2741
+ }
2742
+ async function checkImageField(url, label){
2743
+ if(!url) return '';
2744
+ if(!/^(https?:\/\/|data:image\/)/i.test(url)) return 'The ' + label + ' must be a full http(s) image link or an uploaded image.';
2745
+ return '';
2746
+ }
2747
+ async function saveServerSettings(){
2748
+ const sv = serversCache[serverSettingsId];
2749
+ const errEl = document.getElementById('serverSettingsErr');
2750
+ errEl.className = 'modal-err'; errEl.textContent = '';
2751
+ if(!sv || sv.createdBy !== myKey) return;
2752
+ const name = document.getElementById('serverSettingsName').value.trim();
2753
+ const desc = document.getElementById('serverSettingsDesc').value.trim();
2754
+ const emoji = document.getElementById('serverSettingsEmoji').value.trim();
2755
+ const icon = document.getElementById('serverSettingsIcon').value.trim();
2756
+ const banner = document.getElementById('serverSettingsBanner').value.trim();
2757
+ const color = document.getElementById('serverSettingsColor').value;
2758
+ if(!name){ errEl.textContent = 'Give the server a name.'; return; }
2759
+ if(!nameIsClean(name) || !nameIsClean(desc) || !nameIsClean(emoji)){ errEl.textContent = "That text isn't allowed."; return; }
2760
+ const e1 = await checkImageField(icon, 'icon'); if(e1){ errEl.textContent = e1; return; }
2761
+ const e2 = await checkImageField(banner, 'banner'); if(e2){ errEl.textContent = e2; return; }
2762
+ try{
2763
+ const b = 'servers/' + serverSettingsId + '/';
2764
+ await db.ref().update({
2765
+ [b+'name']: name, [b+'description']: desc || null, [b+'emoji']: emoji || null,
2766
+ [b+'icon']: icon || null, [b+'banner']: banner || null, [b+'color']: /^#[0-9a-f]{6}$/i.test(color) ? color : null
2767
+ });
2768
+ errEl.className = 'modal-err ok'; errEl.textContent = 'Saved.';
2769
+ }catch(err){ console.error(err); errEl.textContent = 'Could not save: ' + (err.message || 'unknown error'); }
2770
+ }
2771
+ function openServerInviteFromSettings(){ closeServerSettings(); setTimeout(openServerInvite, 30); }
2772
+ function leaveCurrentServerFromSettings(){ closeServerSettings(); leaveCurrentServer(); }
2773
+ function deleteCurrentServerFromSettings(){ closeServerSettings(); setTimeout(deleteCurrentServer, 30); }
2774
+
2775
+ /* ---------- channel rename ---------- */
2776
+ async function renameChannel(chatId){
2777
+ if(!chatId) return;
2778
+ const meta = chatsMetaCache[chatId];
2779
+ if(!meta || meta.type === 'dm') return;
2780
+ if(!canManageChannel(meta)){ alert('Only the server creator or the server owner can rename this.'); return; }
2781
+ const val = prompt('New server name:', meta.name || '');
2782
+ if(val === null) return;
2783
+ const name = val.trim();
2784
+ if(!name){ alert('Channel name cannot be empty.'); return; }
2785
+ if(!nameIsClean(name)){ alert("That channel name isn't allowed."); return; }
2786
+ try{ await db.ref('chatsMeta/' + chatId + '/name').set(name); }catch(err){ console.error('Failed to rename channel', err); }
2787
+ }
2788
+ function renameCurrentChannel(){ renameChannel(currentChatId); }
2789
+
2790
+ /* ---------- new channel modal ---------- */
2791
+ let newGroupSelected = new Set();
2792
+ let newChannelType = 'group';
2793
+ function setNewChannelType(type){
2794
+ newChannelType = type;
2795
+ document.getElementById('typeBtnPrivate').classList.toggle('active', type === 'group');
2796
+ document.getElementById('typeBtnPublic').classList.toggle('active', type === 'public');
2797
+ document.getElementById('newGroupPickerWrap').style.display = type === 'group' ? 'block' : 'none';
2798
+ document.getElementById('newGroupNote').textContent = type === 'public'
2799
+ ? 'Public servers show up for everyone, exactly like #general.'
2800
+ : (currentServerId ? 'Everyone in this server can see this server.' : "You'll get an invite code once it's created, so you can add people who aren't friends yet.");
2801
+ }
2802
+ function openNewGroupModal(){
2803
+ newGroupSelected = new Set();
2804
+ document.getElementById('newGroupName').value = '';
2805
+ document.getElementById('newGroupErr').textContent = '';
2806
+ document.getElementById('newGroupTypeChoice').style.display = (isOwnerKey(myKey) && !currentServerId) ? 'flex' : 'none';
2807
+ setNewChannelType('group');
2808
+ document.getElementById('newGroupPickerWrap').style.display = currentServerId ? 'none' : 'block';
2809
+ renderNewGroupMemberPicker();
2810
+ document.getElementById('newGroupModal').classList.add('open');
2811
+ setTimeout(() => document.getElementById('newGroupName').focus(), 50);
2812
+ }
2813
+ function closeNewGroupModal(){ document.getElementById('newGroupModal').classList.remove('open'); }
2814
+ function renderNewGroupMemberPicker_ifOpen(){ if(document.getElementById('newGroupModal').classList.contains('open')) renderNewGroupMemberPicker(); }
2815
+ function renderNewGroupMemberPicker(){
2816
+ const picker = document.getElementById('newGroupMemberPicker');
2817
+ const keys = Object.keys(friendsCache).sort((a,b) => friendsCache[a].localeCompare(friendsCache[b]));
2818
+ if(!keys.length){ picker.innerHTML = '<div class="empty-list-note">No friends to tick yet — create the server anyway and share its invite code.</div>'; return; }
2819
+ picker.innerHTML = keys.map(k => `
2820
+ <label class="member-row"><input type="checkbox" ${newGroupSelected.has(k) ? 'checked' : ''} onchange="toggleNewGroupMember('${k}', this.checked)">
2821
+ <span>${escapeHtml(displayNameFor(friendsCache[k]))}</span></label>`).join('');
2822
+ }
2823
+ function toggleNewGroupMember(key, checked){ if(checked) newGroupSelected.add(key); else newGroupSelected.delete(key); }
2824
+
2825
+ async function submitNewGroup(){
2826
+ const name = document.getElementById('newGroupName').value.trim();
2827
+ const errEl = document.getElementById('newGroupErr');
2828
+ errEl.className = 'modal-err';
2829
+ if(!name){ errEl.textContent = 'Give the server a name.'; return; }
2830
+ if(!nameIsClean(name)){ errEl.textContent = "That channel name isn't allowed."; return; }
2831
+ const type = (isOwnerKey(myKey) && !currentServerId && newChannelType === 'public') ? 'public' : 'group';
2832
+ const TS = firebase.database.ServerValue.TIMESTAMP;
2833
+ try{
2834
+ const newRef = db.ref('chatsMeta').push();
2835
+ const id = newRef.key;
2836
+ if(type === 'public'){
2837
+ await newRef.set({ type:'public', name, createdBy: myKey, created: TS });
2838
+ await db.ref('publicChannels/' + id).set(true);
2839
+ } else if(currentServerId){
2840
+ await newRef.set({ type:'group', name, serverId: currentServerId, members:{ [myKey]: true }, createdBy: myKey, created: TS });
2841
+ await db.ref('serverChannels/' + currentServerId + '/' + id).set(true);
2842
+ } else {
2843
+ const members = { [myKey]: true };
2844
+ newGroupSelected.forEach(k => members[k] = true);
2845
+ await newRef.set({ type:'group', name, members, createdBy: myKey, created: TS });
2846
+ const up = {};
2847
+ Object.keys(members).forEach(k => { up['memberships/' + k + '/chats/' + id] = true; });
2848
+ await db.ref().update(up);
2849
+ await ensureInviteCode(id);
2850
+ }
2851
+ closeNewGroupModal();
2852
+ await waitFor(() => chatsMetaCache[id], 4000);
2853
+ openChat(id); closeSidebarMobile();
2854
+ }catch(err){ console.error(err); errEl.textContent = 'Could not create channel: ' + (err && err.message ? err.message : 'unknown error'); }
2855
+ }
2856
+
2857
+ /* ---------- add members (any member can invite) ---------- */
2858
+ let addMemberSelected = new Set();
2859
+ function openAddMemberModal(){
2860
+ if(!currentChatId || !currentChatMeta || currentChatMeta.type !== 'group' || currentChatMeta.serverId) return;
2861
+ addMemberSelected = new Set();
2862
+ document.getElementById('addMemberErr').textContent = '';
2863
+ document.getElementById('addMemberErr').className = 'modal-err';
2864
+ document.getElementById('addByUsernameInput').value = '';
2865
+ renderAddMemberPicker();
2866
+ document.getElementById('addMemberModal').classList.add('open');
2867
+ }
2868
+ function closeAddMemberModal(){ document.getElementById('addMemberModal').classList.remove('open'); }
2869
+ function renderAddMemberPicker_ifOpen(){ if(document.getElementById('addMemberModal').classList.contains('open')) renderAddMemberPicker(); }
2870
+ function renderAddMemberPicker(){
2871
+ const picker = document.getElementById('addMemberPicker');
2872
+ const members = (chatsMetaCache[currentChatId] && chatsMetaCache[currentChatId].members) || {};
2873
+ const keys = Object.keys(friendsCache).filter(k => !members[k]).sort((a,b) => friendsCache[a].localeCompare(friendsCache[b]));
2874
+ if(!keys.length){ picker.innerHTML = '<div class="empty-list-note">No friends left to tick. Add someone by username above, or share the invite code.</div>'; return; }
2875
+ picker.innerHTML = keys.map(k => `
2876
+ <label class="member-row"><input type="checkbox" ${addMemberSelected.has(k) ? 'checked' : ''} onchange="toggleAddMember('${k}', this.checked)">
2877
+ <span>${escapeHtml(displayNameFor(friendsCache[k]))}</span></label>`).join('');
2878
+ }
2879
+ function toggleAddMember(key, checked){ if(checked) addMemberSelected.add(key); else addMemberSelected.delete(key); }
2880
+ async function addChatMembers(chatId, keys){
2881
+ const up = {};
2882
+ keys.forEach(k => { up['chatsMeta/' + chatId + '/members/' + k] = true; up['memberships/' + k + '/chats/' + chatId] = true; });
2883
+ await db.ref().update(up);
2884
+ }
2885
+ async function addMemberByUsername(){
2886
+ const input = document.getElementById('addByUsernameInput');
2887
+ const errEl = document.getElementById('addMemberErr');
2888
+ errEl.className = 'modal-err';
2889
+ const raw = input.value.trim();
2890
+ if(!raw){ errEl.textContent = 'Type a username first.'; return; }
2891
+ if(!currentChatId || !currentChatMeta || currentChatMeta.type !== 'group'){ errEl.textContent = 'Open a server first.'; return; }
2892
+ const key = sanitizeUsernameKey(raw);
2893
+ const meta = chatsMetaCache[currentChatId] || {};
2894
+ if(meta.members && meta.members[key]){ errEl.textContent = 'They are already in this server.'; return; }
2895
+ try{
2896
+ const snap = await db.ref('users/' + key + '/username').get();
2897
+ if(!snap.exists()){ errEl.textContent = 'No account exists with that name.'; return; }
2898
+ await addChatMembers(currentChatId, [key]);
2899
+ errEl.className = 'modal-err ok';
2900
+ errEl.textContent = (snap.val() || raw) + ' was added to the server.';
2901
+ input.value = '';
2902
+ renderAddMemberPicker();
2903
+ }catch(err){ console.error(err); errEl.textContent = 'Could not add them: ' + (err.message || 'unknown error'); }
2904
+ }
2905
+ async function submitAddMembers(){
2906
+ const errEl = document.getElementById('addMemberErr');
2907
+ errEl.className = 'modal-err';
2908
+ if(addMemberSelected.size === 0){ errEl.textContent = 'Tick at least one friend, or add someone by username.'; return; }
2909
+ try{
2910
+ await addChatMembers(currentChatId, Array.from(addMemberSelected));
2911
+ addMemberSelected = new Set();
2912
+ errEl.className = 'modal-err ok'; errEl.textContent = 'Added.';
2913
+ renderAddMemberPicker();
2914
+ }catch(err){ console.error(err); errEl.textContent = 'Could not add members: ' + (err && err.message ? err.message : 'unknown error'); }
2915
+ }
2916
+
2917
+ /* ---------- leaving / deleting channels ---------- */
2918
+ async function leaveChannel(chatId){
2919
+ const meta = chatsMetaCache[chatId];
2920
+ if(!meta || meta.type !== 'group' || meta.serverId) return;
2921
+ if(!confirm('Leave "' + (meta.name || chatId) + '"? You can rejoin with an invite code.')) return;
2922
+ try{
2923
+ if(voiceState.chatId === chatId) await leaveVoiceChannel();
2924
+ await db.ref('chatsMeta/' + chatId + '/members/' + myKey).remove();
2925
+ await db.ref('memberships/' + myKey + '/chats/' + chatId).remove();
2926
+ if(currentChatId === chatId) openDefaultChat();
2927
+ }catch(err){ console.error('Failed to leave channel', err); }
2928
+ }
2929
+ function leaveCurrentChannel(){ if(currentChatId) leaveChannel(currentChatId); }
2930
+ async function deleteChannel(chatId){
2931
+ const meta = chatsMetaCache[chatId];
2932
+ if(!meta) return;
2933
+ if(!canManageChannel(meta)){ alert('Only the server creator or the server owner can delete this.'); return; }
2934
+ if(!confirm('Delete server "' + (meta.name || chatId) + '" and all its messages?')) return;
2935
+ try{
2936
+ if(meta.type === 'public'){
2937
+ const updates = {
2938
+ ['chatsMsgs/' + chatId]: null,
2939
+ ['publicChannels/' + chatId]: null,
2940
+ ['chatsMeta/' + chatId]: null
2941
+ };
2942
+ await db.ref().update(updates);
2943
+ if(currentChatId === chatId) openDefaultChat();
2944
+ return;
2945
+ }
2946
+ await db.ref('chatsMsgs/' + chatId).remove();
2947
+ await db.ref('voiceChannels/' + chatId).remove();
2948
+ if(meta.inviteCode) await db.ref('inviteCodes/' + meta.inviteCode).remove();
2949
+ if(meta.serverId) await db.ref('serverChannels/' + meta.serverId + '/' + chatId).remove();
2950
+ for(const k of Object.keys(meta.members || {})) await db.ref('memberships/' + k + '/chats/' + chatId).remove().catch(()=>{});
2951
+ await db.ref('chatsMeta/' + chatId).remove();
2952
+ if(currentChatId === chatId) openDefaultChat();
2953
+ }catch(err){ alert('Could not delete the server: ' + err.message); }
2954
+ }
2955
+
2956
+ /* ---------- messages ---------- */
2957
+ function startMessageListener(){
2958
+ stopMessageListener();
2959
+ const chatId = currentChatId;
2960
+ document.getElementById('messages').innerHTML = '<div class="empty-state">Loading…</div>';
2961
+ messagesRef = db.ref('chatsMsgs/' + chatId).limitToLast(200);
2962
+ messagesListener = messagesRef.on('value', (snapshot) => {
2963
+ if(chatId !== currentChatId) return;
2964
+ const data = snapshot.val() || {};
2965
+ const list = Object.keys(data).map(key => ({ id:key, ...data[key] }));
2966
+ list.sort((a,b) => (a.time||0) - (b.time||0));
2967
+ currentMessagesList = list;
2968
+ renderMessages();
2969
+ }, (err) => {
2970
+ if(chatId !== currentChatId) return;
2971
+ const error = document.createElement('div');
2972
+ error.className = 'empty-state';
2973
+ error.textContent = 'Could not load messages: ' + err.message;
2974
+ document.getElementById('messages').replaceChildren(error);
2975
+ });
2976
+ }
2977
+ function stopMessageListener(){
2978
+ if(messagesRef && messagesListener) messagesRef.off('value', messagesListener);
2979
+ messagesRef = null; messagesListener = null;
2980
+ }
2981
+ function highlightMatch(rawText, query){
2982
+ const safe = escapeHtml(rawText || '');
2983
+ if(!query) return safe;
2984
+ return safe.replace(new RegExp(escapeRegExp(escapeHtml(query)), 'ig'), (m) => '<mark class="hl">' + m + '</mark>');
2985
+ }
2986
+ function mediaHtmlFor(url){
2987
+ if(!url) return '';
2988
+ if(!/^https?:\/\/[^\s"<>]+$/i.test(url) && !/^data:image\/(?:png|jpeg|webp|gif);base64,[A-Za-z0-9+/=]+$/.test(url)) return '';
2989
+ const safe = escapeHtml(url);
2990
+ if(VIDEO_RE.test(url)) return `<video class="msg-media" src="${safe}" controls playsinline></video>`;
2991
+ return `<img class="msg-media" src="${safe}" alt="Chat image" referrerpolicy="no-referrer" onclick="window.open(this.src,'_blank','noopener,noreferrer')">`;
2992
+ }
2993
+ function renderMessages(){
2994
+ const container = document.getElementById('messages');
2995
+ const wasNearBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 80;
2996
+ const list = currentMessagesList.filter(m => !isBannedMessage(m) && (m.user === currentUser || !isBlockedUsername(typeof m.user === 'string' ? m.user : '')));
2997
+ const q = searchQuery.trim().toLowerCase();
2998
+ if(!list.length){
2999
+ container.innerHTML = '<div class="empty-state"><span class="glyph">💬</span>No messages yet. Say something to break the ice.</div>';
3000
+ updateSearchCount(0, 0);
3001
+ return;
3002
+ }
3003
+ let matchCount = 0;
3004
+ container.innerHTML = list.map(m => {
3005
+ const mine = m.user === currentUser;
3006
+ const time = m.time ? new Date(m.time).toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'}) : '';
3007
+ const text = typeof m.text === 'string' ? m.text : '';
3008
+ const user = typeof m.user === 'string' ? m.user : 'unknown';
3009
+ const shownName = user;
3010
+ const isMatch = q && (text.toLowerCase().includes(q) || shownName.toLowerCase().includes(q));
3011
+ if(isMatch) matchCount++;
3012
+ const dimClass = (q && !isMatch) ? ' dimmed' : '';
3013
+ const media = mediaHtmlFor(m.media, sanitizeUsernameKey(user), isPrivateMeta(chatsMetaCache[currentChatId] || currentChatMeta));
3014
+ const delBtn = (canRemoveMessage(user) && (canUseAdmin('deleteMessage') || canManageChannel(currentChatMeta || {}))) ? `<button class="msg-del-btn" onclick="deleteMessage(${inlineArg(m.id)})" title="Delete message">✕</button>` : '';
3015
+ const blockBtn = !mine ? `<button class="msg-block-btn" onclick="blockUserByKey(${inlineArg(sanitizeUsernameKey(user))},${inlineArg(user)})" title="Block ${escapeHtml(user)}">🚫</button>` : '';
3016
+ return `<div class="msg ${mine ? 'me' : 'other'}${dimClass}">
3017
+ <div class="avatar-slot">${avatarHtml(user,'md')}</div>
3018
+ <div class="msg-body">
3019
+ <div class="name-row"><span class="who">${highlightMatch(shownName, q)}${roleBadgeHtml(sanitizeUsernameKey(user))}${mutedTagHtml(sanitizeUsernameKey(user))}</span><span class="when">${time}</span></div>
3020
+ <div class="bubble">${highlightMatch(text, q)}</div>
3021
+ ${media}
3022
+ </div>
3023
+ <div class="msg-actions">${blockBtn}${delBtn}</div>
3024
+ </div>`;
3025
+ }).join('');
3026
+ updateSearchCount(matchCount, list.length);
3027
+ if(wasNearBottom || list.length <= 1) container.scrollTop = container.scrollHeight;
3028
+ }
3029
+
3030
+ /* =========================================================
3031
+ NOTIFICATIONS — sound, pop-up toast, desktop notification, unread badges, tab title.
3032
+ Works while the page is open (even in a background tab). EVERY new message notifies unless you mute that chat or server.
3033
+ ========================================================= */
3034
+ let notifyEnabled = false, unreadCache = {}, notifyWatch = {}, audioCtx = null, askedNotifyPermission = false;
3035
+ let notifyMutes = { chats: {}, servers: {} }; // chats / servers you've muted (saved in this browser)
3036
+ try{ const m = JSON.parse(localStorage.getItem('bc_notify_mutes') || 'null'); if(m) notifyMutes = { chats: m.chats || {}, servers: m.servers || {} }; }catch(e){}
3037
+ function saveNotifyMutes(){ try{ localStorage.setItem('bc_notify_mutes', JSON.stringify(notifyMutes)); }catch(e){} }
3038
+ function isChatMuted(chatId){
3039
+ const meta = chatsMetaCache[chatId];
3040
+ return !!notifyMutes.chats[chatId] || !!(meta && meta.serverId && notifyMutes.servers[meta.serverId]);
3041
+ }
3042
+ function updateMuteButtons(){
3043
+ const b = document.getElementById('headerMuteBtn');
3044
+ if(b){
3045
+ if(!currentChatId){ b.style.display = 'none'; }
3046
+ else {
3047
+ const meta = chatsMetaCache[currentChatId] || currentChatMeta;
3048
+ const serverMuted = !!(meta && meta.serverId && notifyMutes.servers[meta.serverId]);
3049
+ const muted = isChatMuted(currentChatId);
3050
+ b.style.display = 'inline-block';
3051
+ b.textContent = muted ? '🔕 Muted' : '🔔 Alerts on';
3052
+ b.title = serverMuted ? 'This whole server is muted (use the server button in the sidebar)' : (muted ? 'Click to unmute this chat' : 'Click to mute this chat');
3053
+ }
3054
+ }
3055
+ const sb = document.getElementById('muteServerBtn');
3056
+ if(sb) sb.textContent = (currentServerId && notifyMutes.servers[currentServerId]) ? '🔕 Server muted' : '🔔 Server alerts on';
3057
+ }
3058
+ function toggleMuteCurrentChat(){
3059
+ if(!currentChatId) return;
3060
+ if(notifyMutes.chats[currentChatId]) delete notifyMutes.chats[currentChatId];
3061
+ else { notifyMutes.chats[currentChatId] = true; delete unreadCache[currentChatId]; }
3062
+ saveNotifyMutes(); updateMuteButtons(); renderUnread();
3063
+ }
3064
+ function toggleMuteCurrentServer(){
3065
+ const id = currentServerId;
3066
+ if(!id) return;
3067
+ if(notifyMutes.servers[id]) delete notifyMutes.servers[id];
3068
+ else {
3069
+ notifyMutes.servers[id] = true;
3070
+ Object.keys(chatsMetaCache).forEach(c => { if(chatsMetaCache[c] && chatsMetaCache[c].serverId === id) delete unreadCache[c]; });
3071
+ }
3072
+ saveNotifyMutes(); updateMuteButtons(); renderUnread();
3073
+ }
3074
+ try{ if(localStorage.getItem('bc_notify') === 'off') notifyEnabled = false; }catch(e){}
3075
+
3076
+ function unreadBadge(id){ if(isChatMuted(id)) return '<span title="Muted" style="font-size:0.7rem;opacity:.6;flex:0 0 auto;">🔕</span>'; const n = unreadCache[id]; return n ? `<span class="unread-badge">${n > 99 ? '99+' : n}</span>` : ''; }
3077
+ function updateTitleBadge(){
3078
+ const total = Object.values(unreadCache).reduce((a, b) => a + b, 0);
3079
+ document.title = (total ? '(' + total + ') ' : '') + 'Bored Chat';
3080
+ const label = total > 99 ? '99+' : total;
3081
+ const h = document.getElementById('headerUnread');
3082
+ if(h) h.innerHTML = total ? '<span class="unread-badge">' + label + '</span>' : '';
3083
+ const mu = document.getElementById('mobileUnread');
3084
+ if(mu) mu.innerHTML = total ? '<span class="unread-badge" style="margin-left:4px;">' + label + '</span>' : '';
3085
+ }
3086
+ function renderUnread(){
3087
+ renderFriendsList(); renderGroupsList(); renderPublicChannelsList(); renderServerRail(); updateTitleBadge();
3088
+ }
3089
+ function beep(){
3090
+ try{
3091
+ audioCtx = audioCtx || new (window.AudioContext || window.webkitAudioContext)();
3092
+ const o = audioCtx.createOscillator(), g = audioCtx.createGain();
3093
+ o.type = 'sine'; o.frequency.value = 880; g.gain.value = 0.05;
3094
+ o.connect(g); g.connect(audioCtx.destination);
3095
+ o.start(); o.stop(audioCtx.currentTime + 0.14);
3096
+ }catch(e){}
3097
+ }
3098
+ function updateNotifyButton(){
3099
+ const b = document.getElementById('notifyBtn');
3100
+ if(!b) return;
3101
+ const perm = ('Notification' in window) ? Notification.permission : 'denied';
3102
+ b.textContent = notifyEnabled ? '🔔' : '🔕';
3103
+ b.title = !notifyEnabled ? 'Notifications are off — click to turn on'
3104
+ : perm === 'granted' ? 'Notifications on — click to mute'
3105
+ : perm === 'denied' ? 'Notifications on (desktop pop-ups blocked in browser settings) — click to mute'
3106
+ : 'Click to allow desktop notifications';
3107
+ }
3108
+ async function toggleNotifications(){
3109
+ if(notifyEnabled && ('Notification' in window) && Notification.permission === 'default'){
3110
+ try{ await Notification.requestPermission(); }catch(e){}
3111
+ updateNotifyButton(); return;
3112
+ }
3113
+ notifyEnabled = !notifyEnabled;
3114
+ try{ localStorage.setItem('bc_notify', notifyEnabled ? 'on' : 'off'); }catch(e){}
3115
+ updateNotifyButton();
3116
+ }
3117
+ document.addEventListener('click', () => { // ask for desktop-notification permission on the first click after login
3118
+ if(!currentUser || askedNotifyPermission || !notifyEnabled || !('Notification' in window)) return;
3119
+ askedNotifyPermission = true;
3120
+ if(Notification.permission === 'default'){ try{ Notification.requestPermission().then(updateNotifyButton); }catch(e){} }
3121
+ });
3122
+ function showToast(title, body, chatId){
3123
+ const host = document.getElementById('toastHost');
3124
+ if(!host) return;
3125
+ const el = document.createElement('div');
3126
+ el.className = 'toast';
3127
+ el.innerHTML = '<b>' + escapeHtml(title) + '</b><span>' + escapeHtml(body || '') + '</span>';
3128
+ el.onclick = () => { el.remove(); if(chatId) openChatById(chatId); };
3129
+ host.appendChild(el);
3130
+ setTimeout(() => el.remove(), 5000);
3131
+ while(host.children.length > 3) host.firstChild.remove();
3132
+ }
3133
+ function openChatById(chatId){
3134
+ const meta = chatsMetaCache[chatId];
3135
+ if(!meta) return;
3136
+ if(meta.serverId){ selectServer(meta.serverId, chatId); }
3137
+ else {
3138
+ currentServerId = null; updateSidebarForServer();
3139
+ openChat(chatId);
3140
+ }
3141
+ closeSidebarMobile();
3142
+ }
3143
+ function notifyUser(title, body, chatId){
3144
+ if(!notifyEnabled) return;
3145
+ beep();
3146
+ if(!document.hidden) showToast(title, body, chatId);
3147
+ if(('Notification' in window) && Notification.permission === 'granted' && (document.hidden || !document.hasFocus())){
3148
+ try{
3149
+ const n = new Notification(title, { body: body, tag: chatId || 'bored-chat' });
3150
+ n.onclick = () => { window.focus(); if(chatId) openChatById(chatId); n.close(); };
3151
+ }catch(e){}
3152
+ }
3153
+ }
3154
+ function handleIncomingMessage(chatId, m){
3155
+ if(isBannedMessage(m)) return;
3156
+ if(!currentUser || m.user === currentUser || isBlockedUsername(m.user)) return;
3157
+ const meta = chatsMetaCache[chatId];
3158
+ if(!meta) return;
3159
+ const text = m.text || (m.media ? (VIDEO_RE.test(m.media) ? '🎞️ sent a video' : '📷 sent an image') : '');
3160
+ if(isChatMuted(chatId)) return;
3161
+ const viewing = chatId === currentChatId && !document.hidden && document.hasFocus();
3162
+ if(viewing) return;
3163
+ unreadCache[chatId] = (unreadCache[chatId] || 0) + 1;
3164
+ renderUnread();
3165
+ let title;
3166
+ if(meta.type === 'dm') title = '💬 ' + displayNameFor(m.user);
3167
+ else {
3168
+ const sv = meta.serverId ? serversCache[meta.serverId] : null;
3169
+ title = (sv ? (sv.name || 'Server') + ' · ' : '') + '#' + (meta.name || 'channel') + ' — ' + displayNameFor(m.user);
3170
+ }
3171
+ notifyUser(title, text.slice(0, 140), chatId);
3172
+ }
3173
+ function reconcileNotifyWatchers(){
3174
+ Object.keys(notifyWatch).forEach(id => {
3175
+ if(!chatsMetaCache[id]){ notifyWatch[id].ref.off('child_added', notifyWatch[id].cb); delete notifyWatch[id]; delete unreadCache[id]; }
3176
+ });
3177
+ Object.keys(chatsMetaCache).forEach(id => {
3178
+ if(notifyWatch[id] || !chatsMetaCache[id]) return;
3179
+ const start = Date.now() + serverOffset;
3180
+ const ref = db.ref('chatsMsgs/' + id).limitToLast(1);
3181
+ const cb = (snap) => { const m = snap.val(); if(m && m.time && m.time > start) handleIncomingMessage(id, m); };
3182
+ notifyWatch[id] = { ref, cb };
3183
+ ref.on('child_added', cb, () => {});
3184
+ });
3185
+ }
3186
+ function clearCurrentUnread(){
3187
+ if(currentChatId && unreadCache[currentChatId] && !document.hidden){ delete unreadCache[currentChatId]; renderUnread(); }
3188
+ }
3189
+ window.addEventListener('focus', clearCurrentUnread);
3190
+ document.addEventListener('visibilitychange', clearCurrentUnread);
3191
+
3192
+ /* ---------- typing ---------- */
3193
+ function startTypingListener(){
3194
+ stopTypingListener();
3195
+ const chatId = currentChatId;
3196
+ typingRef = db.ref('typing/' + chatId);
3197
+ typingListener = typingRef.on('value', (snap) => {
3198
+ if(chatId !== currentChatId) return;
3199
+ const data = snap.val() || {};
3200
+ const others = Object.keys(data).filter(k => k !== myKey && data[k]);
3201
+ const bar = document.getElementById('typingBar');
3202
+ if(!others.length){ bar.textContent = ''; return; }
3203
+ const names = others.map(k => displayNameFor(friendsCache[k] || (statusCache[k] && statusCache[k].username) || k));
3204
+ bar.textContent = (names.length === 1 ? names[0] + ' is typing…' : names.join(', ') + ' are typing…');
3205
+ }, () => {});
3206
+ }
3207
+ function stopTypingListener(){
3208
+ if(typingRef && typingListener) typingRef.off('value', typingListener);
3209
+ typingRef = null; typingListener = null;
3210
+ document.getElementById('typingBar').textContent = '';
3211
+ clearMyTypingFlag();
3212
+ }
3213
+ function handleTypingInput(){
3214
+ if(!currentChatId) return;
3215
+ if(!iAmTyping){
3216
+ iAmTyping = true;
3217
+ db.ref('typing/' + currentChatId + '/' + myKey).set(true).catch(()=>{});
3218
+ db.ref('typing/' + currentChatId + '/' + myKey).onDisconnect().remove();
3219
+ }
3220
+ clearTimeout(typingSelfTimeout);
3221
+ typingSelfTimeout = setTimeout(clearMyTypingFlag, 2500);
3222
+ }
3223
+ function clearMyTypingFlag(){
3224
+ if(iAmTyping && currentChatId) db.ref('typing/' + currentChatId + '/' + myKey).remove().catch(()=>{});
3225
+ iAmTyping = false;
3226
+ clearTimeout(typingSelfTimeout);
3227
+ }
3228
+
3229
+ /* ---------- search ---------- */
3230
+ function toggleSearch(){
3231
+ const bar = document.getElementById('searchBar');
3232
+ const isOpen = bar.classList.toggle('open');
3233
+ document.getElementById('searchToggleBtn').classList.toggle('active', isOpen);
3234
+ if(isOpen) setTimeout(() => document.getElementById('searchInput').focus(), 30); else closeSearch();
3235
+ }
3236
+ function closeSearch(){
3237
+ document.getElementById('searchBar').classList.remove('open');
3238
+ document.getElementById('searchToggleBtn').classList.remove('active');
3239
+ document.getElementById('searchInput').value = '';
3240
+ searchQuery = '';
3241
+ updateSearchCount(0, 0, true);
3242
+ renderMessages();
3243
+ }
3244
+ function handleSearchInput(){ searchQuery = document.getElementById('searchInput').value; renderMessages(); }
3245
+ function updateSearchCount(matchCount, totalCount, hide){
3246
+ const el = document.getElementById('searchCount');
3247
+ if(hide || !searchQuery.trim()){ el.textContent = ''; return; }
3248
+ el.textContent = matchCount + ' of ' + totalCount;
3249
+ }
3250
+ function canRemoveMessage(user){
3251
+ const key = sanitizeUsernameKey(user || '');
3252
+ return key === myKey || (!isOwnerKey(key) && (!adminRoles[key] || isOwnerKey(myKey)));
3253
+ }
3254
+ async function deleteMessage(msgId){
3255
+ const target = currentMessagesList.find(message => message.id === msgId);
3256
+ if(!target || !canRemoveMessage(target.user)) return;
3257
+ if(!currentChatId || (!canUseAdmin('deleteMessage') && !canManageChannel(currentChatMeta || {}))) return;
3258
+ try{ await moderationUpdate({ ['chatsMsgs/' + currentChatId + '/' + msgId]: null }, 'deleteMessage', currentChatMeta?.name || currentChatId); }catch(err){ console.error('Failed to delete message', err); }
3259
+ }
3260
+
3261
+ function canUploadImage(chatId){
3262
+ return !!(myKey && chatId && (isOwnerKey(myKey) || (chatsMetaCache[chatId] || currentChatMeta)?.serverId));
3263
+ }
3264
+ function canPostToChat(chatId){
3265
+ const meta = chatsMetaCache[chatId] || currentChatMeta;
3266
+ return meta?.staffOnly !== true || isOwnerKey(myKey) || adminRoles[myKey] === true;
3267
+ }
3268
+ async function setStaffOnlyChannel(enabled){
3269
+ const chatId = currentChatId;
3270
+ if(!isOwnerKey(myKey) || !chatId || currentChatMeta?.type === 'dm') return;
3271
+ try{ await db.ref('chatsMeta/' + chatId + '/staffOnly').set(enabled); }
3272
+ catch(error){ alert('Could not save channel setting: ' + error.message); }
3273
+ updateComposerState();
3274
+ }
3275
+ function updateComposerState(){
3276
+ const record = muteRecord();
3277
+ const readOnly = !canPostToChat(currentChatId);
3278
+ const muted = !!record || readOnly;
3279
+ const meta = chatsMetaCache[currentChatId] || currentChatMeta;
3280
+ document.getElementById('staffOnlyControl').hidden = !isOwnerKey(myKey) || !currentChatId || !meta || meta.type === 'dm';
3281
+ document.getElementById('staffOnlyCheckbox').checked = meta?.staffOnly === true;
3282
+ clearTimeout(muteExpiryTimer);
3283
+ if(record?.until) muteExpiryTimer = setTimeout(updateComposerState, Math.max(1, record.until - Date.now() + 20));
3284
+ document.getElementById('composerNote').style.display = muted ? 'block' : 'none';
3285
+ document.getElementById('msgInput').disabled = muted;
3286
+ document.getElementById('sendBtn').disabled = muted;
3287
+ const attach = document.getElementById('attachBtn');
3288
+ attach.hidden = !canUploadImage(currentChatId);
3289
+ attach.disabled = muted || attach.hidden;
3290
+ if(muted) document.getElementById('composerNote').textContent = 'You are muted.' + (moderationReason(muteRecord()) ? ' Reason: ' + moderationReason(muteRecord()) : '');
3291
+ if(readOnly) document.getElementById('composerNote').textContent = 'Announcement channel — only the owner and admins can type. You can still read messages.';
3292
+ document.getElementById('msgInput').placeholder = readOnly ? 'Only owner and admins can type' : muted ? "You can't send messages while muted" : 'Message…';
3293
+ }
3294
+
3295
+ let composerNoteTimer = null;
3296
+ function flashComposerNote(text){
3297
+ if(!document.getElementById('commandsScreen').hidden){
3298
+ document.getElementById('modUsernameMsg').textContent = text;
3299
+ return;
3300
+ }
3301
+ const note = document.getElementById('composerNote');
3302
+ note.textContent = text; note.style.display = 'block';
3303
+ clearTimeout(composerNoteTimer);
3304
+ composerNoteTimer = setTimeout(() => { note.textContent = "You're muted, so you can't send messages right now."; updateComposerState(); }, 6000);
3305
+ }
3306
+ // Use quotes around usernames with spaces.
3307
+ const modCommands = ['ban','unban','mute','unmute','kick','admin','unadmin','checkaccount','modhelp','cmd'];
3308
+ async function runAdminCommand(text){
3309
+ if(!myKey || !isAdmin){
3310
+ flashComposerNote('Only owners and admins can use commands.');
3311
+ return;
3312
+ }
3313
+ const [, typedCommand, args = ''] = text.match(/^\/(\w+)\s*(.*)$/) || [];
3314
+ const command = typedCommand?.toLowerCase();
3315
+ if(!modCommands.includes(command)){ flashComposerNote('Unknown command. Type /cmd for the list.'); return; }
3316
+ if(command === 'cmd' || command === 'modhelp'){
3317
+ const commands = Object.entries(adminCommandUsage).filter(([key]) => canUseAdmin(key)).map(([, usage]) => usage);
3318
+ if(isOwnerKey(myKey)) commands.push('/checkaccount username', '/admin username', '/unadmin username');
3319
+ openCommandsScreen();
3320
+ document.getElementById('modUsernameMsg').textContent = commands.join(' • ') || 'No commands assigned.';
3321
+ return;
3322
+ }
3323
+ const [, quoted, word, rest = ''] = args.match(/^(?:"([^"]+)"|(\S+))(?:\s+(.*))?$/) || [];
3324
+ const raw = quoted || word;
3325
+ if(!raw){ flashComposerNote('Type a username. Use quotes around names with spaces.'); return; }
3326
+ const key = sanitizeUsernameKey(raw);
3327
+ try{
3328
+ if(/[\x00-\x1f\x7f]/.test(key)) throw Error('Invalid username.');
3329
+ if(['checkaccount','admin','unadmin'].includes(command)){
3330
+ if(!isOwnerKey(myKey)) throw Error('Only the owner can use this command.');
3331
+ if(command === 'checkaccount'){
3332
+ const [user, registered] = await Promise.all([
3333
+ db.ref('users/' + key + '/username').get(), db.ref('registeredAccounts/' + key).get()
3334
+ ]);
3335
+ alert(user.exists() || registered.exists() ? 'Account already created.' : 'Username is available.');
3336
+ }else{
3337
+ if(isOwnerKey(key)) throw Error('The owner role is permanent.');
3338
+ if(!(await db.ref('users/' + key + '/username').get()).exists()) throw Error('No account has that username.');
3339
+ if(command === 'admin') await db.ref('adminRoles/' + key).set(true);
3340
+ else await db.ref().update({ ['adminRoles/' + key]: null, ['adminPermissions/' + key]: null });
3341
+ }
3342
+ }else{
3343
+ if(!canUseAdmin(command)) throw Error('The owner has not enabled that command for you.');
3344
+ protectTarget(key);
3345
+ const snap = await db.ref('users/' + key + '/username').get();
3346
+ if(!snap.exists() && !['unban','unmute'].includes(command)) throw Error('No account has that username.');
3347
+ const name = snap.val() || raw;
3348
+ if(command === 'ban' && !await banUserByKey(key, name, rest)) return;
3349
+ if(command === 'unban' && !await unbanUserByKey(key)) return;
3350
+ if(command === 'kick') await moderationUpdate({ ['accountKicks/' + key]: firebase.database.ServerValue.TIMESTAMP }, 'kick', key);
3351
+ if(command === 'mute'){
3352
+ const [scope, ...reason] = rest.split(/\s+/);
3353
+ if(!await muteUserByKey(key, name, scope, reason.join(' '))) return;
3354
+ }
3355
+ if(command === 'unmute' && !await unmuteUserByKey(key, rest)) return;
3356
+ }
3357
+ flashComposerNote('Done: /' + command + ' ' + raw);
3358
+ }catch(err){ flashComposerNote('Command failed: ' + err.message); }
3359
+ }
3360
+
3361
+ function normalizeChatText(value){
3362
+ return String(value).normalize('NFKD')
3363
+ .replace(/[\p{M}\p{Cf}]/gu, '')
3364
+ .replace(/[\u{1F130}-\u{1F149}\u{1F150}-\u{1F169}\u{1F170}-\u{1F189}\u{1F1E6}-\u{1F1FF}]/gu, letter => {
3365
+ const point = letter.codePointAt(0);
3366
+ const base = point >= 0x1F1E6 ? 0x1F1E6 : point >= 0x1F170 ? 0x1F170 : point >= 0x1F150 ? 0x1F150 : 0x1F130;
3367
+ return String.fromCharCode(65 + point - base);
3368
+ });
3369
+ }
3370
+ async function writeChatMessage(chatId, text, media){
3371
+ text = normalizeChatText(text);
3372
+ if(text.length > 500) throw Error('Your message is too long after converting fancy letters.');
3373
+ if(!chatDatabaseConnected) throw Error('Firebase is disconnected. Reconnect and try again.');
3374
+ const key = myKey;
3375
+ if(muteRecord()) throw Error('You are muted by the owner or a moderator.');
3376
+ if(!canPostToChat(chatId)) throw Error('Only the owner and admins can type in this channel.');
3377
+ if(isOwnerKey(key) || adminRoles[key] === true){
3378
+ await db.ref('chatsMsgs/' + chatId).push({user:currentUser, text, ...(media ? {media} : {}), time:firebase.database.ServerValue.TIMESTAMP});
3379
+ return;
3380
+ }
3381
+ if((chatsMetaCache[chatId] || currentChatMeta)?.type === 'public' && text){
3382
+ const words = (await db.ref('moderationConfig/bannedWords').get()).val() || {};
3383
+ const match = Object.entries(words).find(([, word]) => typeof word === 'string' && text.toLowerCase().includes(normalizeChatText(word).toLowerCase()));
3384
+ if(match){
3385
+ const [index, word] = match;
3386
+ const timestamp = firebase.database.ServerValue.TIMESTAMP;
3387
+ await db.ref('wordMutes/' + key + '/' + chatId).set({index, text, reason:'Cursing: ' + word, time:timestamp});
3388
+ throw Error('Muted in this server until the owner unmutes you. Reason: Cursing: ' + word);
3389
+ }
3390
+ }
3391
+ const ratePath = 'messageThrottle/' + key;
3392
+ const rateRef = db.ref(ratePath);
3393
+ const messagePath = 'chatsMsgs/' + chatId + '/';
3394
+ const id = db.ref(messagePath).push().key;
3395
+ const time = firebase.database.ServerValue.TIMESTAMP;
3396
+ for(let attempt = 0; attempt < 3; attempt++){
3397
+ const rate = (await rateRef.get()).val() || {};
3398
+ if(rate.locked) throw Error('Muted for spamming. Only the owner can unmute you.');
3399
+ const next = {id, room:chatId, locked:false, t0:time};
3400
+ for(let i = 1; i < 20; i++) next['t' + i] = rate['t' + (i - 1)] || 0;
3401
+ try{
3402
+ await db.ref().update({
3403
+ [ratePath]: next,
3404
+ [messagePath + id]: {user:currentUser, text, ...(media ? {media} : {}), time}
3405
+ });
3406
+ return;
3407
+ }catch(error){
3408
+ if(!/permission.denied/i.test((error.code || '') + ' ' + error.message)) throw error;
3409
+ if(rate.t19){
3410
+ let locked = false;
3411
+ try{ await rateRef.child('locked').set(true); locked = true; }catch(_){}
3412
+ if(locked) throw Error('Muted for spamming. Only the owner can unmute you.');
3413
+ }
3414
+ const latest = (await rateRef.get()).val() || {};
3415
+ if(latest.locked) throw Error('Muted for spamming. Only the owner can unmute you.');
3416
+ if(latest.id === rate.id) throw error;
3417
+ }
3418
+ }
3419
+ throw Error('Chat changed while sending. Try again.');
3420
+ }
3421
+ async function sendMessage(){
3422
+ const input = document.getElementById('msgInput');
3423
+ const sendBtn = document.getElementById('sendBtn');
3424
+ const text = input.value.trim();
3425
+ if(!text || !currentUser || sendBtn.disabled) return;
3426
+ if(!currentChatId){ flashComposerNote('Pick a server or a friend first — there is nowhere to send this yet.'); return; }
3427
+ if(amMuted()){ updateComposerState(); return; }
3428
+ if(text.startsWith('/') && modCommands.includes(text.slice(1).split(/\s+/)[0].toLowerCase())){
3429
+ input.value = '';
3430
+ await runAdminCommand(text);
3431
+ return;
3432
+ }
3433
+ input.value = '';
3434
+ sendBtn.disabled = true;
3435
+ const pending = setTimeout(() => flashComposerNote('Waiting for Firebase to confirm your message…'), 3000);
3436
+ try{
3437
+ await writeChatMessage(currentChatId, text);
3438
+ }catch(err){ console.error('Failed to send message', err); input.value = text; flashComposerNote('Message not sent: ' + (err.message || 'permission denied')); }
3439
+ finally{ clearTimeout(pending); updateComposerState(); input.focus(); }
3440
+ }
3441
+
3442
+ /* ---------- attach image ---------- */
3443
+ function openAttachMediaModal(){
3444
+ if(!canUploadImage(currentChatId) || amMuted() || !canPostToChat(currentChatId)) return;
3445
+ document.getElementById('attachMediaUrl').value = '';
3446
+ document.getElementById('attachImageLink').value = '';
3447
+ document.getElementById('attachMediaCaption').value = '';
3448
+ document.getElementById('attachMediaErr').textContent = '';
3449
+ document.getElementById('attachMediaModal').classList.add('open');
3450
+ setTimeout(() => document.getElementById('attachMediaUrl').focus(), 50);
3451
+ }
3452
+ function closeAttachMediaModal(){ document.getElementById('attachMediaModal').classList.remove('open'); }
3453
+ function normalizeImageLink(link){
3454
+ const url = new URL(link);
3455
+ if(url.protocol !== 'https:' || url.username || url.password || url.href.length > 2048 ||
3456
+ !/^https:\/\/[^\s"<>]+$/.test(url.href)){
3457
+ throw Error('Paste a direct HTTPS image link.');
3458
+ }
3459
+ return url.href;
3460
+ }
3461
+ async function submitAttachMedia(){
3462
+ const file = document.getElementById('attachMediaUrl').files[0];
3463
+ const link = document.getElementById('attachImageLink').value.trim();
3464
+ const caption = document.getElementById('attachMediaCaption').value.trim();
3465
+ const errEl = document.getElementById('attachMediaErr');
3466
+ const chatId = currentChatId;
3467
+ if(!canUploadImage(chatId) || amMuted()) return;
3468
+ if(file && link){ errEl.textContent = 'Choose a file or paste a link.'; return; }
3469
+ if(!link && (!file || !/^image\/(png|jpeg|webp|gif)$/.test(file.type) || file.size > 200000)){
3470
+ errEl.textContent = 'Choose a PNG, JPEG, WebP, or GIF up to 200 KB.';
3471
+ return;
3472
+ }
3473
+ const button = errEl.parentElement.querySelector('.primary-btn');
3474
+ button.disabled = true;
3475
+ try{
3476
+ const media = link ? normalizeImageLink(link) : await new Promise((resolve, reject) => {
3477
+ const reader = new FileReader();
3478
+ reader.onload = () => resolve(reader.result);
3479
+ reader.onerror = () => reject(reader.error);
3480
+ reader.readAsDataURL(file);
3481
+ });
3482
+ if(chatId !== currentChatId || !canUploadImage(chatId) || amMuted()) throw Error('Open the chat again before sending.');
3483
+ await writeChatMessage(chatId, caption, media);
3484
+ closeAttachMediaModal();
3485
+ }catch(err){ errEl.textContent = 'Could not send: ' + err.message; }
3486
+ finally{ button.disabled = false; }
3487
+ }
3488
+
3489
+ /* =========================================================
3490
+ 1:1 CALLING (WebRTC, signaled through Firebase RTDB)
3491
+ ========================================================= */
3492
+ let callState = {
3493
+ active:false, role:null, peerKey:null, peerUsername:null, type:null,
3494
+ pc:null, localStream:null, outgoingRef:null, remoteCandidatesRef:null,
3495
+ timerInterval:null, startTime:null, currentIncomingCallKey:null,
3496
+ cameraTrack:null, screenSharing:false
3497
+ };
3498
+
3499
+ function startIncomingCallListener(){
3500
+ incomingCallRef = db.ref('calls/' + myKey);
3501
+ incomingCallRef.on('value', (snap) => {
3502
+ const data = snap.val();
3503
+ if(!data){
3504
+ if(callState.active && callState.role === 'callee') cleanupCall();
3505
+ hideIncomingCallUI();
3506
+ callState.currentIncomingCallKey = null;
3507
+ return;
3508
+ }
3509
+ if(data.status === 'ringing'){
3510
+ if(blockedCache[data.from]){ db.ref('calls/' + myKey).update({status:'declined', reason:'blocked'}); return; }
3511
+ const callKey = data.from + '_' + (data.time || '');
3512
+ if(callState.active){ db.ref('calls/' + myKey).update({status:'declined', reason:'busy'}); return; }
3513
+ if(callState.currentIncomingCallKey !== callKey){ callState.currentIncomingCallKey = callKey; showIncomingCallUI(data); }
3514
+ } else if(data.status === 'ended' || data.status === 'declined'){
3515
+ if(callState.active && callState.role === 'callee') cleanupCall();
3516
+ hideIncomingCallUI();
3517
+ callState.currentIncomingCallKey = null;
3518
+ }
3519
+ });
3520
+ }
3521
+ function newPeerConnection(){
3522
+ const pc = new RTCPeerConnection({ iceServers: ICE_SERVERS });
3523
+ pc.ontrack = (event) => {
3524
+ const remoteVideo = document.getElementById('remoteVideoEl');
3525
+ if(remoteVideo.srcObject !== event.streams[0]) remoteVideo.srcObject = event.streams[0];
3526
+ };
3527
+ return pc;
3528
+ }
3529
+ async function getLocalStream(type){ return await navigator.mediaDevices.getUserMedia({ audio:true, video: type==='video' }); }
3530
+
3531
+ async function startCall(friendKey, friendUsername, type){
3532
+ if(callState.active){ alert("You're already on a call."); return; }
3533
+ if(!friendsCache[friendKey]){ alert('You can only call friends.'); return; }
3534
+ if(blockedCache[friendKey]){ alert('Unblock them first.'); return; }
3535
+ try{
3536
+ const existing = await db.ref('calls/' + friendKey).get();
3537
+ if(existing.exists() && existing.val().status === 'ringing'){ alert(friendUsername + ' already has a call ringing.'); return; }
3538
+ callState.localStream = await getLocalStream(type);
3539
+ }catch(err){
3540
+ console.error(err);
3541
+ alert('Could not access microphone' + (type==='video' ? '/camera' : '') + '. Check your browser permissions.');
3542
+ return;
3543
+ }
3544
+ callState.active = true; callState.role = 'caller'; callState.peerKey = friendKey;
3545
+ callState.peerUsername = friendUsername; callState.type = type;
3546
+
3547
+ const pc = newPeerConnection();
3548
+ callState.pc = pc;
3549
+ callState.localStream.getTracks().forEach(track => pc.addTrack(track, callState.localStream));
3550
+ pc.onicecandidate = (event) => { if(event.candidate) db.ref('calls/' + friendKey + '/callerCandidates').push(event.candidate.toJSON()); };
3551
+ try{
3552
+ const offer = await pc.createOffer();
3553
+ await pc.setLocalDescription(offer);
3554
+ await db.ref('calls/' + friendKey).set({
3555
+ from: myKey, fromUsername: currentUser, type, status:'ringing',
3556
+ offer:{type:offer.type, sdp:offer.sdp}, time: firebase.database.ServerValue.TIMESTAMP
3557
+ });
3558
+ }catch(err){ console.error(err); cleanupCall(); alert('Could not start the call.'); return; }
3559
+
3560
+ callState.outgoingRef = db.ref('calls/' + friendKey);
3561
+ callState.outgoingRef.on('value', handleOutgoingCallUpdate);
3562
+ callState.remoteCandidatesRef = db.ref('calls/' + friendKey + '/calleeCandidates');
3563
+ callState.remoteCandidatesRef.on('child_added', (snap) => {
3564
+ if(callState.pc) callState.pc.addIceCandidate(new RTCIceCandidate(snap.val())).catch(console.error);
3565
+ });
3566
+ showOutgoingCallUI(friendUsername, type);
3567
+ }
3568
+ async function handleOutgoingCallUpdate(snapshot){
3569
+ const data = snapshot.val();
3570
+ if(!callState.active || callState.role !== 'caller') return;
3571
+ if(!data){ cleanupCall(); return; }
3572
+ if(data.status === 'accepted' && data.answer && callState.pc && !callState.pc.currentRemoteDescription){
3573
+ try{ await callState.pc.setRemoteDescription(new RTCSessionDescription(data.answer)); hideOutgoingCallUI(); showInCallUI(); }
3574
+ catch(err){ console.error(err); }
3575
+ } else if(data.status === 'declined'){ hideOutgoingCallUI(); cleanupCall(); }
3576
+ else if(data.status === 'ended'){ cleanupCall(); }
3577
+ }
3578
+ function cancelOutgoingCall(){
3579
+ if(callState.role === 'caller' && callState.peerKey){
3580
+ const peer = callState.peerKey;
3581
+ db.ref('calls/' + peer).update({status:'ended'}).then(() => setTimeout(() => db.ref('calls/' + peer).remove(), 1000));
3582
+ }
3583
+ cleanupCall();
3584
+ }
3585
+ function showIncomingCallUI(data){
3586
+ notifyUser((data.type === 'video' ? '🎥 Video call' : '📞 Voice call'), (data.fromUsername || 'Someone') + ' is calling you…', null);
3587
+ document.getElementById('incomingCallName').textContent = data.fromUsername || data.from;
3588
+ document.getElementById('incomingCallAvatar').textContent = data.type === 'video' ? '🎥' : '📞';
3589
+ document.getElementById('incomingCallStatus').textContent = (data.type === 'video' ? 'Video call' : 'Voice call') + ' — incoming…';
3590
+ document.getElementById('incomingCallOverlay').classList.add('open');
3591
+ document.getElementById('incomingCallOverlay').dataset.callData = JSON.stringify(data);
3592
+ }
3593
+ function hideIncomingCallUI(){ document.getElementById('incomingCallOverlay').classList.remove('open'); }
3594
+
3595
+ async function acceptIncomingCall(){
3596
+ const overlay = document.getElementById('incomingCallOverlay');
3597
+ let data; try{ data = JSON.parse(overlay.dataset.callData || '{}'); }catch(e){ data = null; }
3598
+ hideIncomingCallUI();
3599
+ if(!data || !data.from) return;
3600
+ try{ callState.localStream = await getLocalStream(data.type); }
3601
+ catch(err){ console.error(err); alert('Could not access microphone' + (data.type==='video'?'/camera':'') + '. Declining call.'); declineIncomingCallRaw(); return; }
3602
+
3603
+ callState.active = true; callState.role='callee'; callState.peerKey=data.from;
3604
+ callState.peerUsername=data.fromUsername; callState.type=data.type;
3605
+
3606
+ const pc = newPeerConnection();
3607
+ callState.pc = pc;
3608
+ callState.localStream.getTracks().forEach(track => pc.addTrack(track, callState.localStream));
3609
+ pc.onicecandidate = (event) => { if(event.candidate) db.ref('calls/' + myKey + '/calleeCandidates').push(event.candidate.toJSON()); };
3610
+ try{
3611
+ await pc.setRemoteDescription(new RTCSessionDescription(data.offer));
3612
+ const answer = await pc.createAnswer();
3613
+ await pc.setLocalDescription(answer);
3614
+ await db.ref('calls/' + myKey).update({ status:'accepted', answer:{type:answer.type, sdp:answer.sdp} });
3615
+ }catch(err){ console.error(err); cleanupCall(); return; }
3616
+
3617
+ callState.remoteCandidatesRef = db.ref('calls/' + myKey + '/callerCandidates');
3618
+ callState.remoteCandidatesRef.on('child_added', (snap) => {
3619
+ if(callState.pc) callState.pc.addIceCandidate(new RTCIceCandidate(snap.val())).catch(console.error);
3620
+ });
3621
+ showInCallUI();
3622
+ }
3623
+ function declineIncomingCallRaw(){
3624
+ db.ref('calls/' + myKey).update({status:'declined'}).then(() => setTimeout(() => db.ref('calls/' + myKey).remove(), 1000));
3625
+ callState.currentIncomingCallKey = null;
3626
+ }
3627
+ function declineIncomingCall(){ hideIncomingCallUI(); declineIncomingCallRaw(); }
3628
+
3629
+ function showOutgoingCallUI(name, type){
3630
+ document.getElementById('outgoingCallAvatar').textContent = type === 'video' ? '🎥' : '📞';
3631
+ document.getElementById('outgoingCallName').textContent = name;
3632
+ document.getElementById('outgoingCallStatus').textContent = 'Ringing…';
3633
+ document.getElementById('outgoingCallOverlay').classList.add('open');
3634
+ }
3635
+ function hideOutgoingCallUI(){ document.getElementById('outgoingCallOverlay').classList.remove('open'); }
3636
+
3637
+ function showInCallUI(){
3638
+ const overlay = document.getElementById('inCallOverlay');
3639
+ overlay.classList.remove('docked');
3640
+ document.getElementById('dockToggleBtn').textContent = '⤢';
3641
+ document.getElementById('inCallName').textContent = callState.peerUsername || '';
3642
+ document.getElementById('localVideoEl').srcObject = callState.localStream;
3643
+ const isVideo = callState.type === 'video';
3644
+ overlay.classList.toggle('in-call-audio-mode', !isVideo);
3645
+ document.getElementById('inCallAudioAvatar').style.display = isVideo ? 'none' : 'flex';
3646
+ document.getElementById('vidToggleBtn').style.display = isVideo ? 'inline-flex' : 'none';
3647
+ overlay.classList.add('open');
3648
+ callState.startTime = Date.now();
3649
+ updateCallTimer();
3650
+ callState.timerInterval = setInterval(updateCallTimer, 1000);
3651
+ document.getElementById('muteBtn').classList.remove('active'); document.getElementById('muteBtn').textContent = '🎤';
3652
+ document.getElementById('vidToggleBtn').classList.remove('active'); document.getElementById('vidToggleBtn').textContent = '🎥';
3653
+ document.getElementById('shareToggleBtn').classList.remove('active'); document.getElementById('shareToggleBtn').textContent = '🖥️';
3654
+ }
3655
+ function hideInCallUI(){
3656
+ document.getElementById('inCallOverlay').classList.remove('open');
3657
+ document.getElementById('inCallOverlay').classList.remove('docked');
3658
+ document.getElementById('remoteVideoEl').srcObject = null;
3659
+ document.getElementById('localVideoEl').srcObject = null;
3660
+ if(callState.timerInterval){ clearInterval(callState.timerInterval); callState.timerInterval = null; }
3661
+ }
3662
+ function updateCallTimer(){
3663
+ if(!callState.startTime) return;
3664
+ const secs = Math.floor((Date.now() - callState.startTime) / 1000);
3665
+ document.getElementById('inCallTimer').textContent = String(Math.floor(secs/60)).padStart(2,'0') + ':' + String(secs%60).padStart(2,'0');
3666
+ }
3667
+ function toggleMute(){
3668
+ if(!callState.localStream) return;
3669
+ const track = callState.localStream.getAudioTracks()[0];
3670
+ if(!track) return;
3671
+ track.enabled = !track.enabled;
3672
+ document.getElementById('muteBtn').classList.toggle('active', !track.enabled);
3673
+ document.getElementById('muteBtn').textContent = track.enabled ? '🎤' : '🔇';
3674
+ }
3675
+ function toggleVideo(){
3676
+ if(!callState.localStream) return;
3677
+ const track = callState.localStream.getVideoTracks()[0];
3678
+ if(!track) return;
3679
+ track.enabled = !track.enabled;
3680
+ document.getElementById('vidToggleBtn').classList.toggle('active', !track.enabled);
3681
+ document.getElementById('vidToggleBtn').textContent = track.enabled ? '🎥' : '🚫';
3682
+ }
3683
+ function toggleCallDocked(){
3684
+ const overlay = document.getElementById('inCallOverlay');
3685
+ if(!overlay.classList.contains('open')) return;
3686
+ const nowDocked = overlay.classList.toggle('docked');
3687
+ document.getElementById('dockToggleBtn').textContent = nowDocked ? '⤡' : '⤢';
3688
+ }
3689
+
3690
+ /* ---------- screen sharing during a call ---------- */
3691
+ async function toggleScreenShare(){
3692
+ if(!callState.active || !callState.pc) return;
3693
+ if(callState.screenSharing){ await stopScreenShare(); return; }
3694
+ if(!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia){ alert('Screen sharing is not supported in this browser.'); return; }
3695
+ let screenStream;
3696
+ try{ screenStream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: false }); }
3697
+ catch(err){ console.error(err); return; }
3698
+ const screenTrack = screenStream.getVideoTracks()[0];
3699
+ if(!screenTrack) return;
3700
+ const sender = callState.pc.getSenders().find(s => s.track && s.track.kind === 'video');
3701
+ const existingVideoTrack = callState.localStream.getVideoTracks()[0] || null;
3702
+ callState.cameraTrack = existingVideoTrack;
3703
+ if(sender) await sender.replaceTrack(screenTrack);
3704
+ else callState.pc.addTrack(screenTrack, callState.localStream);
3705
+ if(existingVideoTrack) callState.localStream.removeTrack(existingVideoTrack);
3706
+ callState.localStream.addTrack(screenTrack);
3707
+ document.getElementById('localVideoEl').srcObject = callState.localStream;
3708
+ document.getElementById('inCallOverlay').classList.remove('in-call-audio-mode');
3709
+ document.getElementById('inCallAudioAvatar').style.display = 'none';
3710
+ callState.screenSharing = true;
3711
+ document.getElementById('shareToggleBtn').classList.add('active');
3712
+ document.getElementById('shareToggleBtn').textContent = '🛑';
3713
+ screenTrack.onended = () => { stopScreenShare(); };
3714
+ }
3715
+ async function stopScreenShare(){
3716
+ if(!callState.screenSharing) return;
3717
+ const sender = callState.pc ? callState.pc.getSenders().find(s => s.track && s.track.kind === 'video') : null;
3718
+ const screenTrack = callState.localStream ? callState.localStream.getVideoTracks()[0] : null;
3719
+ if(callState.cameraTrack && sender) await sender.replaceTrack(callState.cameraTrack);
3720
+ else if(sender && callState.type !== 'video') callState.pc.removeTrack(sender);
3721
+ if(screenTrack){ if(callState.localStream) callState.localStream.removeTrack(screenTrack); screenTrack.stop(); }
3722
+ if(callState.cameraTrack && callState.localStream) callState.localStream.addTrack(callState.cameraTrack);
3723
+ document.getElementById('localVideoEl').srcObject = callState.localStream;
3724
+ const stillVideo = callState.type === 'video';
3725
+ document.getElementById('inCallOverlay').classList.toggle('in-call-audio-mode', !stillVideo);
3726
+ document.getElementById('inCallAudioAvatar').style.display = stillVideo ? 'none' : 'flex';
3727
+ callState.screenSharing = false;
3728
+ callState.cameraTrack = null;
3729
+ document.getElementById('shareToggleBtn').classList.remove('active');
3730
+ document.getElementById('shareToggleBtn').textContent = '🖥️';
3731
+ }
3732
+
3733
+ function endCall(){
3734
+ if(!callState.active){
3735
+ if(document.getElementById('outgoingCallOverlay').classList.contains('open')) cancelOutgoingCall();
3736
+ return;
3737
+ }
3738
+ if(callState.screenSharing) stopScreenShare();
3739
+ const rootKey = callState.role === 'caller' ? callState.peerKey : myKey;
3740
+ if(rootKey){
3741
+ db.ref('calls/' + rootKey).update({status:'ended'}).then(() => setTimeout(() => db.ref('calls/' + rootKey).remove(), 1000)).catch(()=>{});
3742
+ }
3743
+ cleanupCall();
3744
+ }
3745
+ function cleanupCall(){
3746
+ if(callState.localStream) callState.localStream.getTracks().forEach(t => t.stop());
3747
+ if(callState.cameraTrack){ try{ callState.cameraTrack.stop(); }catch(e){} }
3748
+ if(callState.pc){ callState.pc.onicecandidate=null; callState.pc.ontrack=null; callState.pc.close(); }
3749
+ if(callState.outgoingRef) callState.outgoingRef.off('value', handleOutgoingCallUpdate);
3750
+ if(callState.remoteCandidatesRef) callState.remoteCandidatesRef.off('child_added');
3751
+ hideOutgoingCallUI(); hideInCallUI();
3752
+ callState = { active:false, role:null, peerKey:null, peerUsername:null, type:null, pc:null, localStream:null,
3753
+ outgoingRef:null, remoteCandidatesRef:null, timerInterval:null, startTime:null,
3754
+ currentIncomingCallKey: callState.currentIncomingCallKey, cameraTrack:null, screenSharing:false };
3755
+ }
3756
+
3757
+ /* =========================================================
3758
+ VOICE CHANNELS (audio mesh, best for a handful of people)
3759
+ ========================================================= */
3760
+ let voiceState = { chatId:null, localStream:null, peers:{} };
3761
+ let voiceParticipantsListenerRef = null;
3762
+
3763
+ function updateVoicePanelVisibility(){
3764
+ const panel = document.getElementById('voicePanel');
3765
+ const meta = chatsMetaCache[currentChatId] || currentChatMeta;
3766
+ const canVoice = meta?.type === 'group';
3767
+ document.getElementById("voiceVideoBtn").hidden = !canVoice || voiceState.chatId === currentChatId;
3768
+ panel.classList.toggle('show', canVoice);
3769
+ if(canVoice) renderVoiceChips();
3770
+ }
3771
+ function renderVoiceChips(){
3772
+ const row = document.getElementById('voiceChipsRow');
3773
+ const participants = (voiceParticipantsAllCache[currentChatId] || {});
3774
+ row.innerHTML = Object.keys(participants).map(k => `
3775
+ <span class="voice-chip">${avatarHtml(participants[k],'xs')}${escapeHtml(displayNameFor(participants[k]))}${k===myKey && voiceState.chatId===currentChatId ? ' (you)' : ''}</span>`).join('');
3776
+ const joinBtn = document.getElementById('voiceJoinBtn');
3777
+ const inThis = voiceState.chatId === currentChatId;
3778
+ joinBtn.textContent = inThis ? '🎙️ Leave Voice' : '🎙️ Join Voice';
3779
+ joinBtn.classList.toggle('leave', inThis);
3780
+ }
3781
+ function updateVoiceStatusBar(){
3782
+ const bar = document.getElementById('voiceStatusBar');
3783
+ if(!voiceState.chatId){ bar.classList.remove('show'); return; }
3784
+ const meta = chatsMetaCache[voiceState.chatId];
3785
+ document.getElementById('voiceStatusName').textContent = 'In voice — ' + (meta ? meta.name : 'channel');
3786
+ bar.classList.add('show');
3787
+ }
3788
+ function voiceJoinBtnClick(){
3789
+ if(voiceState.chatId === currentChatId) leaveVoiceChannel(); else joinVoiceChannel(currentChatId);
3790
+ }
3791
+ async function joinVoiceChannel(chatId, video = false){
3792
+ if(chatsMetaCache[chatId]?.type !== "group" || !canAccessChat(chatsMetaCache[chatId])) return;
3793
+ if(voiceState.chatId) await leaveVoiceChannel();
3794
+ try{ voiceState.localStream = await navigator.mediaDevices.getUserMedia({ audio:true, video }); }
3795
+ catch(err){ console.error(err); alert('Could not access your microphone. Check browser permissions.'); return; }
3796
+ voiceState.chatId = chatId;
3797
+ voiceState.peers = {};
3798
+ const participantsRef = db.ref('voiceChannels/' + chatId + '/participants');
3799
+ const myParticipantRef = participantsRef.child(myKey);
3800
+ myParticipantRef.onDisconnect().remove();
3801
+ try{ await myParticipantRef.set(currentUser); }catch(error){ await leaveVoiceChannel(); alert(error.message); return; }
3802
+ voiceParticipantsListenerRef = participantsRef;
3803
+ participantsRef.on('child_added', (snap) => {
3804
+ const otherKey = snap.key;
3805
+ if(otherKey === myKey || voiceState.chatId !== chatId) return;
3806
+ connectToVoicePeer(chatId, otherKey);
3807
+ });
3808
+ participantsRef.on('child_removed', (snap) => { teardownVoicePeer(chatId, snap.key, true); });
3809
+ updateVoiceStatusBar();
3810
+ updateVoicePanelVisibility();
3811
+ }
3812
+ function connectToVoicePeer(chatId, otherKey){
3813
+ if(voiceState.peers[otherKey]) return;
3814
+ const amInitiator = myKey < otherKey;
3815
+ const signalRef = db.ref('voiceChannels/' + chatId + '/signals/' + pairId(myKey, otherKey));
3816
+ const pc = new RTCPeerConnection({ iceServers: ICE_SERVERS });
3817
+ const audioEl = document.createElement('video');
3818
+ audioEl.playsInline = true;
3819
+ audioEl.style.maxWidth = '180px';
3820
+ audioEl.autoplay = true;
3821
+ audioEl.id = 'voice-audio-' + otherKey;
3822
+ document.getElementById('privateVideoTiles').appendChild(audioEl);
3823
+ audioEl.hidden = true;
3824
+ pc.ontrack = (event) => { audioEl.srcObject = event.streams[0]; if(event.track.kind === "video") audioEl.hidden = false; };
3825
+ voiceState.localStream.getTracks().forEach(t => pc.addTrack(t, voiceState.localStream));
3826
+ if(amInitiator && !voiceState.localStream.getVideoTracks().length) pc.addTransceiver('video', {direction:'recvonly'});
3827
+ const queuedCandidates = [];
3828
+ function addCandidate(snapshot){
3829
+ if(!pc.remoteDescription) queuedCandidates.push(snapshot.val());
3830
+ else pc.addIceCandidate(snapshot.val()).catch(console.error);
3831
+ }
3832
+ async function setRemote(description){
3833
+ await pc.setRemoteDescription(description);
3834
+ for(const candidate of queuedCandidates.splice(0)) await pc.addIceCandidate(candidate).catch(console.error);
3835
+ }
3836
+ voiceState.peers[otherKey] = { pc, audioEl, signalRef };
3837
+
3838
+ if(amInitiator){
3839
+ pc.onicecandidate = (event) => { if(event.candidate) signalRef.child('callerCandidates').push(event.candidate.toJSON()); };
3840
+ pc.createOffer().then(offer => pc.setLocalDescription(offer)).then(() => {
3841
+ signalRef.update({ callerKey: myKey, calleeKey: otherKey, offer: { type: pc.localDescription.type, sdp: pc.localDescription.sdp } });
3842
+ }).catch(console.error);
3843
+ signalRef.on('value', (snap) => {
3844
+ const data = snap.val();
3845
+ if(data && data.answer && pc.signalingState === 'have-local-offer') setRemote(data.answer).catch(console.error);
3846
+ });
3847
+ signalRef.child('calleeCandidates').on('child_added', addCandidate);
3848
+ } else {
3849
+ pc.onicecandidate = (event) => { if(event.candidate) signalRef.child('calleeCandidates').push(event.candidate.toJSON()); };
3850
+ let answered = false;
3851
+ signalRef.on('value', async (snap) => {
3852
+ const data = snap.val();
3853
+ if(data && data.offer && !answered){
3854
+ answered = true;
3855
+ try{
3856
+ await setRemote(data.offer);
3857
+ const answer = await pc.createAnswer();
3858
+ await pc.setLocalDescription(answer);
3859
+ await signalRef.update({ answer: { type: answer.type, sdp: answer.sdp } });
3860
+ }catch(err){ console.error(err); }
3861
+ }
3862
+ });
3863
+ signalRef.child('callerCandidates').on('child_added', addCandidate);
3864
+ }
3865
+ }
3866
+ function teardownVoicePeer(chatId, otherKey, cleanupSignalNode){
3867
+ const peer = voiceState.peers[otherKey];
3868
+ if(!peer) return;
3869
+ peer.signalRef.off('value');
3870
+ peer.signalRef.child('callerCandidates').off('child_added');
3871
+ peer.signalRef.child('calleeCandidates').off('child_added');
3872
+ peer.pc.ontrack = null; peer.pc.onicecandidate = null; peer.pc.close();
3873
+ if(peer.audioEl){ peer.audioEl.srcObject = null; peer.audioEl.remove(); }
3874
+ delete voiceState.peers[otherKey];
3875
+ if(cleanupSignalNode) db.ref('voiceChannels/' + chatId + '/signals/' + pairId(myKey, otherKey)).remove().catch(()=>{});
3876
+ }
3877
+ async function leaveVoiceChannel(){
3878
+ if(!voiceState.chatId) return;
3879
+ const chatId = voiceState.chatId;
3880
+ Object.keys(voiceState.peers).forEach(k => teardownVoicePeer(chatId, k, false));
3881
+ if(voiceParticipantsListenerRef){ voiceParticipantsListenerRef.off('child_added'); voiceParticipantsListenerRef.off('child_removed'); }
3882
+ voiceParticipantsListenerRef = null;
3883
+ if(voiceState.localStream) voiceState.localStream.getTracks().forEach(t => t.stop());
3884
+ await db.ref('voiceChannels/' + chatId + '/participants/' + myKey).remove().catch(()=>{});
3885
+ voiceState = { chatId:null, localStream:null, peers:{} };
3886
+ updateVoiceStatusBar();
3887
+ if(currentChatId === chatId) updateVoicePanelVisibility();
3888
+ }
3889
+
3890
+ document.addEventListener('keydown', (e) => {
3891
+ if(e.key !== 'Enter') return;
3892
+ if(document.getElementById('newGroupModal').classList.contains('open')) submitNewGroup();
3893
+ });
3894
+ </script>
3895
+
3896
+ </body></html>