noah33565 commited on
Commit
1da347e
·
verified ·
1 Parent(s): 1ef64b6

Upload app (3).js

Browse files
Files changed (1) hide show
  1. app (3).js +1873 -0
app (3).js ADDED
@@ -0,0 +1,1873 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ const JSONBIN_KEY = '$2a$10$Hurr28g4Cy7NWpA/Abd6YOzkBLuC8PdAOPQR34g4pEkA24LpXo7NK'; // ← eintragen
4
+ const JSONBIN_BIN = '69976e43ae596e708f382b97'; // ← eintragen
5
+
6
+ // ─── CONFIG ───────────────────────────────────────────────────
7
+ const OWNER_NAME = 'Noah';
8
+ const OWNER_PASS = '';
9
+ const POLL_MS = 3000; // Polling-Intervall in ms
10
+
11
+ // ─── SESSION PERSISTENCE ──────────────────────────────────────
12
+ function saveSession(user) {
13
+ if (user) localStorage.setItem('nc_session', JSON.stringify({ username: user.username, ts: Date.now() }));
14
+ else localStorage.removeItem('nc_session');
15
+ }
16
+ function loadSession() {
17
+ try {
18
+ const s = localStorage.getItem('nc_session');
19
+ if (!s) return null;
20
+ const parsed = JSON.parse(s);
21
+ if (Date.now() - parsed.ts > 7 * 86400000) { localStorage.removeItem('nc_session'); return null; }
22
+ return parsed;
23
+ } catch { return null; }
24
+ }
25
+
26
+ // ─── DM READ TRACKING (persistent) ───────────────────────────
27
+ function getDMReadTs(otherUser) {
28
+ try {
29
+ const data = JSON.parse(localStorage.getItem('nc_dm_read') || '{}');
30
+ return data[otherUser.toLowerCase()] || 0;
31
+ } catch { return 0; }
32
+ }
33
+ function setDMReadTs(otherUser, ts) {
34
+ try {
35
+ const data = JSON.parse(localStorage.getItem('nc_dm_read') || '{}');
36
+ data[otherUser.toLowerCase()] = ts;
37
+ localStorage.setItem('nc_dm_read', JSON.stringify(data));
38
+ } catch {}
39
+ }
40
+
41
+ // ─── STATE ────────────────────────────────────────────────────
42
+ let currentUser = null;
43
+ let currentChannel = 'allgemein';
44
+ let currentDM = null;
45
+ let pollTimer = null;
46
+ let spamTs = [];
47
+ let captchaData = {};
48
+ let pendingSpamMsg = null;
49
+ let appConfig = {};
50
+ let voiceActive = false;
51
+ let voiceChannel = null;
52
+ let micMuted = false;
53
+ let deafened = false;
54
+ let translationEnabled = false;
55
+ let userLanguage = 'de';
56
+ let unreadCounts = {};
57
+ let lastMsgCounts = {};
58
+
59
+ // ─── IN-MEMORY DB CACHE ───────────────────────────────────────
60
+ // Die komplette DB liegt immer im RAM.
61
+ // Schreiben: sofort im Cache sichtbar, async zu JSONBin gesendet.
62
+ // Lesen: aus Cache (kein Extra-Request nötig).
63
+ // Polling lädt alle POLL_MS die DB neu von JSONBin.
64
+ let DB = null;
65
+ let isSaving = false;
66
+ let saveQueued = false;
67
+
68
+ const DB_DEFAULT = () => ({
69
+ users: {},
70
+ msgs: {},
71
+ dms: {},
72
+ online: {},
73
+ voice: {},
74
+ tickets: {},
75
+ pins: [],
76
+ blocks: {}, // { username: [blockedUsername, ...] }
77
+ moderation: { bans:{}, banned_fps:{}, kicked:{}, timeouts:{} },
78
+ config: {}
79
+ });
80
+
81
+ // ─── FINGERPRINT ──────────────────────────────────────────────
82
+ function getFingerprint() {
83
+ const s = navigator.userAgent + screen.width + screen.height + screen.colorDepth
84
+ + (Intl.DateTimeFormat().resolvedOptions().timeZone||'') + navigator.language;
85
+ let h = 0;
86
+ for (let i = 0; i < s.length; i++) { h = ((h<<5)-h) + s.charCodeAt(i); h = h&h; }
87
+ return Math.abs(h).toString(36);
88
+ }
89
+ const MY_FP = getFingerprint();
90
+
91
+ let heartbeatTimer = null;
92
+ function scheduleHeartbeatSave() {
93
+ // Nur alle 6 Sekunden wirklich speichern (Polling ist 3s, also jeden 2. Tick)
94
+ if (heartbeatTimer) return;
95
+ heartbeatTimer = setTimeout(() => {
96
+ heartbeatTimer = null;
97
+ apiSave();
98
+ }, 6000);
99
+ }
100
+
101
+ // ─── JSONBIN API ──────────────────────────────────────────────
102
+ const isConfigured = () =>
103
+ !JSONBIN_KEY.includes('DEIN') && !JSONBIN_BIN.includes('DEINE');
104
+
105
+ async function apiLoad(isMerge = false) {
106
+ if (!isConfigured()) {
107
+ const v = localStorage.getItem('nc_db');
108
+ DB = v ? JSON.parse(v) : DB_DEFAULT();
109
+ ensureFields();
110
+ return;
111
+ }
112
+ try {
113
+ const r = await fetch(`https://api.jsonbin.io/v3/b/${JSONBIN_BIN}/latest`, {
114
+ headers: { 'X-Master-Key': JSONBIN_KEY, 'X-Bin-Meta': 'false' }
115
+ });
116
+ if (!r.ok) throw new Error(r.status);
117
+ const remote = await r.json();
118
+
119
+ if (isMerge && DB) {
120
+ // Smart merge: Remote-Daten haben Vorrang, aber lokale Änderungen die
121
+ // noch nicht gepusht wurden (pending saves) bleiben erhalten.
122
+ // Nachrichten: Union beider Sets (remote + lokal), remote gewinnt bei Konflikt
123
+ const mergedMsgs = {};
124
+ const allChannels = new Set([...Object.keys(DB.msgs || {}), ...Object.keys(remote.msgs || {})]);
125
+ for (const ch of allChannels) {
126
+ const localCh = DB.msgs?.[ch] || {};
127
+ const remoteCh = remote.msgs?.[ch] || {};
128
+ mergedMsgs[ch] = { ...localCh, ...remoteCh }; // Remote überschreibt lokal bei gleichem Key
129
+ }
130
+ const mergedDms = {};
131
+ const allDms = new Set([...Object.keys(DB.dms || {}), ...Object.keys(remote.dms || {})]);
132
+ for (const dm of allDms) {
133
+ const localDm = DB.dms?.[dm] || {};
134
+ const remoteDm = remote.dms?.[dm] || {};
135
+ mergedDms[dm] = { ...localDm, ...remoteDm };
136
+ }
137
+ DB = { ...remote, msgs: mergedMsgs, dms: mergedDms };
138
+ } else {
139
+ DB = remote;
140
+ }
141
+
142
+ ensureFields();
143
+ localStorage.setItem('nc_db', JSON.stringify(DB));
144
+ } catch(e) {
145
+ console.warn('Load fehlgeschlagen:', e);
146
+ const v = localStorage.getItem('nc_db');
147
+ if (v) DB = JSON.parse(v);
148
+ else DB = DB_DEFAULT();
149
+ ensureFields();
150
+ }
151
+ }
152
+
153
+ async function apiSave() {
154
+ // Immer lokal speichern
155
+ localStorage.setItem('nc_db', JSON.stringify(DB));
156
+ if (!isConfigured()) return;
157
+
158
+ if (isSaving) { saveQueued = true; return; }
159
+ isSaving = true;
160
+ try {
161
+ const r = await fetch(`https://api.jsonbin.io/v3/b/${JSONBIN_BIN}`, {
162
+ method: 'PUT',
163
+ headers: {
164
+ 'Content-Type': 'application/json',
165
+ 'X-Master-Key': JSONBIN_KEY,
166
+ 'X-Bin-Versioning': 'false' // Kein Versionsverlauf → schneller
167
+ },
168
+ body: JSON.stringify(DB)
169
+ });
170
+ if (!r.ok) console.warn('Save Fehler:', r.status);
171
+ } catch(e) {
172
+ console.warn('Save Exception:', e);
173
+ } finally {
174
+ isSaving = false;
175
+ if (saveQueued) { saveQueued = false; apiSave(); }
176
+ }
177
+ }
178
+
179
+ // Fehlende Felder ergänzen falls DB älter ist
180
+ function ensureFields() {
181
+ const def = DB_DEFAULT();
182
+ for (const k of Object.keys(def)) {
183
+ if (DB[k] === undefined) DB[k] = def[k];
184
+ }
185
+ if (!DB.moderation.bans) DB.moderation.bans = {};
186
+ if (!DB.moderation.banned_fps) DB.moderation.banned_fps = {};
187
+ if (!DB.moderation.kicked) DB.moderation.kicked = {};
188
+ if (!DB.moderation.timeouts) DB.moderation.timeouts = {};
189
+ if (!DB.blocks) DB.blocks = {};
190
+ }
191
+
192
+ // ─── BLOCK HELPERS ────────────────────────────────────────────
193
+ function isBlocked(username) {
194
+ const myBlocks = DB.blocks?.[currentUser?.username?.toLowerCase()] || [];
195
+ return myBlocks.includes(username.toLowerCase());
196
+ }
197
+ function isBlockedBy(username) {
198
+ const theirBlocks = DB.blocks?.[username.toLowerCase()] || [];
199
+ return theirBlocks.includes(currentUser?.username?.toLowerCase());
200
+ }
201
+ function blockUser(username) {
202
+ const key = currentUser.username.toLowerCase();
203
+ if (!DB.blocks[key]) DB.blocks[key] = [];
204
+ if (!DB.blocks[key].includes(username.toLowerCase())) {
205
+ DB.blocks[key].push(username.toLowerCase());
206
+ apiSave();
207
+ showToast(`🚫 ${username} blockiert`, 'var(--warn)');
208
+ if (currentDM === username) openChannel('allgemein');
209
+ updateDMList();
210
+ }
211
+ }
212
+ function unblockUser(username) {
213
+ const key = currentUser.username.toLowerCase();
214
+ if (!DB.blocks[key]) return;
215
+ DB.blocks[key] = DB.blocks[key].filter(u => u !== username.toLowerCase());
216
+ apiSave();
217
+ showToast(`✓ ${username} entblockt`, 'var(--green)');
218
+ updateDMList();
219
+ }
220
+
221
+ // Hilfsfunktionen: Pfad-Zugriff (z.B. "users/noah")
222
+ function dbGet(path) {
223
+ const parts = path.split('/').filter(Boolean);
224
+ let o = DB;
225
+ for (const p of parts) { if (o==null) return undefined; o = o[p]; }
226
+ return o;
227
+ }
228
+
229
+ function dbSet(path, val) {
230
+ const parts = path.split('/').filter(Boolean);
231
+ let o = DB;
232
+ for (let i = 0; i < parts.length-1; i++) {
233
+ if (o[parts[i]] == null) o[parts[i]] = {};
234
+ o = o[parts[i]];
235
+ }
236
+ o[parts[parts.length-1]] = val;
237
+ apiSave(); // Async, blockiert nicht
238
+ }
239
+
240
+ function dbDelete(path) {
241
+ const parts = path.split('/').filter(Boolean);
242
+ let o = DB;
243
+ for (let i = 0; i < parts.length-1; i++) {
244
+ if (o[parts[i]] == null) return;
245
+ o = o[parts[i]];
246
+ }
247
+ delete o[parts[parts.length-1]];
248
+ apiSave();
249
+ }
250
+
251
+ function dbPush(path, val) {
252
+ const key = Date.now().toString(36) + Math.random().toString(36).slice(2,5);
253
+ val._key = key;
254
+ dbSet(path+'/'+key, val);
255
+ return key;
256
+ }
257
+
258
+ // ─── ROLE HELPERS ─────────────────────────────────────────────
259
+ const ROLE_PRIORITY = { owner:5, admin:4, mod:3, vip:2, member:1 };
260
+ const ROLE_BADGE = { owner:'👑', admin:'🔰', mod:'⭐', vip:'💎', member:'' };
261
+ const ROLE_LABELS = { owner:'Owner', admin:'Admin', mod:'Moderator', vip:'VIP', member:'Mitglied' };
262
+ const ROLE_COLORS = { owner:'name-color-1', admin:'name-color-0', mod:'name-color-2', vip:'name-color-4', member:'' };
263
+ function hasRole(r) { return currentUser && ROLE_PRIORITY[currentUser.role] >= ROLE_PRIORITY[r]; }
264
+
265
+ // ─── CAPTCHA ──────────────────────────────────────────────────
266
+ function genCaptcha() {
267
+ const a=Math.floor(Math.random()*18)+2, b=Math.floor(Math.random()*18)+2;
268
+ if (Math.random()>.4) return {q:`${a} + ${b} = ?`, ans:a+b};
269
+ const big=Math.max(a,b), sm=Math.min(a,b);
270
+ return {q:`${big} − ${sm} = ?`, ans:big-sm};
271
+ }
272
+ function refreshCaptcha(id) {
273
+ const d=genCaptcha(); captchaData[id]=d;
274
+ const q=document.getElementById(id+'-q'); if(q) q.textContent=d.q;
275
+ const a=document.getElementById(id+'-a'); if(a) a.value='';
276
+ }
277
+ function verifyCaptcha(id) {
278
+ return captchaData[id] && parseInt(document.getElementById(id+'-a')?.value)===captchaData[id].ans;
279
+ }
280
+
281
+ // ─── AUTH TABS ────────────────────────────────────────────────
282
+ function switchTab(tab) {
283
+ ['login','register'].forEach((t,i)=>{
284
+ document.getElementById('tab-'+t).style.display=t===tab?'':'none';
285
+ document.querySelectorAll('.auth-tab')[i].classList.toggle('active',t===tab);
286
+ });
287
+ document.getElementById('auth-error').textContent='';
288
+ }
289
+
290
+ // ─── REGISTER ─────────────────────────────────────────────────
291
+ async function doRegister() {
292
+ const u=document.getElementById('reg-user').value.trim();
293
+ const p=document.getElementById('reg-pass').value;
294
+ const p2=document.getElementById('reg-pass2').value;
295
+ const err=t=>document.getElementById('auth-error').textContent=t;
296
+ if (u.length<2) return err('Username mind. 2 Zeichen');
297
+ if (u.length>20) return err('Username max. 20 Zeichen');
298
+ if (!/^[a-zA-Z0-9_]+$/.test(u)) return err('Nur Buchstaben, Zahlen, _');
299
+ if (p.length<4) return err('Passwort mind. 4 Zeichen');
300
+ if (p!==p2) return err('Passwörter stimmen nicht überein');
301
+ if (!verifyCaptcha('reg')) { refreshCaptcha('reg'); return err('❌ Falsches Captcha!'); }
302
+ if (DB.moderation.bans?.[u.toLowerCase()]) return err('Dieser Account ist gesperrt.');
303
+ if (DB.moderation.banned_fps?.[MY_FP]) return showBanned();
304
+ if (DB.users[u.toLowerCase()]) return err('Username bereits vergeben');
305
+ dbSet(`users/${u.toLowerCase()}`, {
306
+ username:u, password:encode(p),
307
+ color:Math.floor(Math.random()*5), role:'member', joined:Date.now(),
308
+ settings:{lang:'de', translate:false, notif:true}
309
+ });
310
+ refreshCaptcha('reg');
311
+ showAuthSuccess('✓ Account erstellt! Du kannst dich jetzt einloggen.');
312
+ setTimeout(()=>{ switchTab('login'); document.getElementById('login-user').value=u; }, 1300);
313
+ }
314
+
315
+ // ─── LOGIN ────────────────────────────────────────────────────
316
+ async function doLogin() {
317
+ const u=document.getElementById('login-user').value.trim();
318
+ const p=document.getElementById('login-pass').value;
319
+ const err=t=>document.getElementById('auth-error').textContent=t;
320
+ if (!verifyCaptcha('login')) { refreshCaptcha('login'); return err('❌ Falsches Captcha!'); }
321
+ if (DB.moderation.banned_fps?.[MY_FP]) return showBanned();
322
+ const entry=DB.users[u.toLowerCase()];
323
+ if (!entry) return err('Falscher Username oder Passwort');
324
+ if (decode(entry.password)!==p)return err('Falscher Username oder Passwort');
325
+ if (DB.moderation.bans?.[u.toLowerCase()]) return err('🚫 Du bist von NoahsChat gebannt.');
326
+ currentUser={...entry};
327
+ saveSession(currentUser);
328
+ refreshCaptcha('login');
329
+ dbSet(`users/${u.toLowerCase()}/_fp`, MY_FP);
330
+ dbSet(`online/${entry.username}`, Date.now());
331
+ userLanguage=entry.settings?.lang||'de';
332
+ translationEnabled=entry.settings?.translate||false;
333
+ launchApp();
334
+ }
335
+
336
+ // ─── LOGOUT ───────────────────────────────────────────────────
337
+ async function doLogout() {
338
+ if (!currentUser) return;
339
+ saveSession(null);
340
+ if (voiceActive) await leaveVoice();
341
+ dbDelete(`online/${currentUser.username}`);
342
+ if (voiceActive) leaveVoice();
343
+ clearInterval(pollTimer);
344
+ currentUser=null;
345
+ document.getElementById('app').classList.remove('visible');
346
+ document.getElementById('auth-screen').style.display='flex';
347
+ document.getElementById('login-pass').value='';
348
+ refreshCaptcha('login');
349
+ }
350
+
351
+ // ─── LAUNCH APP ───────────────────────────────────────────────
352
+ async function launchApp() {
353
+ document.getElementById('auth-screen').style.display='none';
354
+ document.getElementById('app').classList.add('visible');
355
+ appConfig = DB.config || {};
356
+ if (!appConfig.channels) {
357
+ appConfig.channels = window.DEFAULT_CHANNELS||[];
358
+ appConfig.automod = window.DEFAULT_AUTOMOD||{};
359
+ dbSet('config', appConfig);
360
+ }
361
+ updateTopbar();
362
+ buildChannelList();
363
+ restoreVoiceState();
364
+ openChannel('allgemein');
365
+ startPolling();
366
+ }
367
+
368
+ // ─── POLLING ──────────────────────────────────────────────────
369
+ function startPolling() {
370
+ pollTimer = setInterval(pollTick, POLL_MS);
371
+ }
372
+
373
+ async function pollTick() {
374
+ if (!currentUser) return;
375
+
376
+ // DB neu laden → bekommt Änderungen anderer User (mit Merge, damit lokale Msgs nicht verloren gehen)
377
+ setSyncStatus('sync');
378
+ await apiLoad(true);
379
+ setSyncStatus('ok');
380
+
381
+ // Eigene Daten aktualisieren (Rolle könnte geändert worden sein)
382
+ const me = DB.users[currentUser.username.toLowerCase()];
383
+ if (me) {
384
+ currentUser = {...me};
385
+ updateTopbar();
386
+ userLanguage = me.settings?.lang||'de';
387
+ translationEnabled = me.settings?.translate||false;
388
+ }
389
+
390
+ // Heartbeat — NUR den eigenen Online-Eintrag setzen, NICHT die komplette DB speichern
391
+ // Direkt im Objekt setzen und gezielt speichern um Race-Conditions zu vermeiden
392
+ DB.online[currentUser.username] = Date.now();
393
+ // Heartbeat-only save: kleines Debounce damit nicht zu viele Requests entstehen
394
+ scheduleHeartbeatSave();
395
+
396
+ // Moderation-Checks
397
+ const mod = DB.moderation;
398
+ if (mod.bans?.[currentUser.username.toLowerCase()] || mod.banned_fps?.[MY_FP]) {
399
+ clearInterval(pollTimer); showBanned(); return;
400
+ }
401
+ const kick = mod.kicked?.[currentUser.username.toLowerCase()];
402
+ if (kick && Date.now()-kick.ts < 60000) { clearInterval(pollTimer); showKickedModal(); return; }
403
+ updateTimeoutBar();
404
+
405
+ // Online-User-Liste
406
+ const now = Date.now();
407
+ const onlineNames = Object.entries(DB.online)
408
+ .filter(([,ts])=>now-ts<12000).map(([u])=>u);
409
+ document.getElementById('online-count').textContent = onlineNames.length;
410
+ renderUserList(onlineNames);
411
+ updateDMList();
412
+
413
+ // Nachrichten anzeigen
414
+ if (currentDM) renderDMMessages(currentDM);
415
+ else {
416
+ renderChannelMessages(currentChannel);
417
+ // Unread-Badges für andere Channels
418
+ for (const ch of (appConfig.channels||[])) {
419
+ if (ch.id===currentChannel) continue;
420
+ const msgs = getMsgs(ch.id);
421
+ const key = 'ch_'+ch.id;
422
+ const prev = lastMsgCounts[key]||0;
423
+ if (msgs.length>prev) {
424
+ unreadCounts[key] = (unreadCounts[key]||0) + (msgs.length-prev);
425
+ updateBadge('badge-'+ch.id, unreadCounts[key]);
426
+ lastMsgCounts[key] = msgs.length;
427
+ }
428
+ }
429
+ }
430
+
431
+ // DM Unread-Badges
432
+ for (const entry of Object.values(DB.users)) {
433
+ if (entry.username===currentUser.username) continue;
434
+ if (currentDM===entry.username) continue;
435
+ const key = 'dm_'+entry.username.toLowerCase();
436
+ const msgs = getDMMsgs(getDMKey(currentUser.username, entry.username));
437
+ const prev = lastMsgCounts[key]||0;
438
+ if (msgs.length>prev) {
439
+ unreadCounts[key] = (unreadCounts[key]||0) + (msgs.length-prev);
440
+ lastMsgCounts[key] = msgs.length;
441
+ updateDMList();
442
+ }
443
+ }
444
+
445
+ // Abgelaufene Voice-Einträge aufräumen (20s Timeout)
446
+ for (const [vcId, parts] of Object.entries(DB.voice||{})) {
447
+ for (const [uname, data] of Object.entries(parts||{})) {
448
+ if (now-(data.ts||0) > 20000) {
449
+ delete DB.voice[vcId][uname];
450
+ }
451
+ }
452
+ }
453
+
454
+ // Voice: neue User im Channel erkennen und anrufen
455
+ voicePollConnect();
456
+
457
+ // Voice-Heartbeat: eigenen Eintrag aktuell halten
458
+ if (voiceActive && voiceChannel && DB.voice?.[voiceChannel]?.[currentUser.username]) {
459
+ DB.voice[voiceChannel][currentUser.username].ts = now;
460
+ }
461
+
462
+ buildChannelList();
463
+ }
464
+
465
+ // ─── SYNC STATUS INDICATOR ────────────────────────────────────
466
+ function setSyncStatus(state) { /* deaktiviert – keine störende Animation */ }
467
+
468
+ function restoreVoiceState() {
469
+ const vcNames = {'voice-allgemein':'Allgemein','voice-gaming':'Gaming','voice-musik':'Musik'};
470
+ for (const [vcId, parts] of Object.entries(DB.voice||{})) {
471
+ if (parts?.[currentUser.username]) {
472
+ // Nach Reload: Voice neu joinen (stellt PeerJS-Verbindung wieder her)
473
+ const name = vcNames[vcId] || vcId;
474
+ joinVoice(vcId, name);
475
+ break;
476
+ }
477
+ }
478
+ }
479
+
480
+ // ─── TOPBAR ───────────────────────────────────────────────────
481
+ function updateTopbar() {
482
+ const av=document.getElementById('topbar-avatar');
483
+ av.textContent=currentUser.username[0].toUpperCase();
484
+ av.className=`user-avatar-sm av-color-${currentUser.color}`;
485
+ document.getElementById('topbar-username').textContent=currentUser.username;
486
+ document.getElementById('topbar-role-badge').textContent=ROLE_BADGE[currentUser.role]||'';
487
+ }
488
+
489
+ // ─── SIDEBAR ──────────────────────────────────────────────────
490
+ function buildChannelList() {
491
+ const channels=appConfig.channels||window.DEFAULT_CHANNELS||[];
492
+ const list=document.getElementById('channel-list');
493
+ list.innerHTML='';
494
+ const cats={info:'Info',chat:'Text-Channels',fun:'Community',staff:'Staff'};
495
+ const grouped={};
496
+ for (const ch of channels) {
497
+ const cat=ch.category||'chat';
498
+ if (!grouped[cat]) grouped[cat]=[];
499
+ grouped[cat].push(ch);
500
+ }
501
+ for (const [catId,label] of Object.entries(cats)) {
502
+ const chs=grouped[catId]; if (!chs) continue;
503
+ if (catId==='staff'&&!hasRole('mod')) continue;
504
+ const catEl=document.createElement('div');
505
+ catEl.className='channel-category';
506
+ catEl.textContent='— '+label;
507
+ list.appendChild(catEl);
508
+ for (const ch of chs) {
509
+ if (ch.adminOnly&&!hasRole('admin')) {
510
+ if (catId==='staff') continue;
511
+ const div=document.createElement('div');
512
+ div.className='channel-item ch-locked';
513
+ div.innerHTML=`<span class="channel-icon">${ch.icon}</span><span class="channel-name">${ch.name}</span><span style="font-size:.65rem;color:var(--muted)">🔒</span>`;
514
+ list.appendChild(div); continue;
515
+ }
516
+ if (ch.modOnly&&!hasRole('mod')) continue;
517
+ const div=document.createElement('div');
518
+ div.className='channel-item'+(ch.id===currentChannel&&!currentDM?' active':'');
519
+ div.dataset.channel=ch.id;
520
+ div.innerHTML=`<span class="channel-icon">${ch.icon}</span><span class="channel-name">${ch.name}</span><span class="unread-badge" id="badge-${ch.id}" style="display:none"></span>`;
521
+ div.onclick=()=>openChannel(ch.id);
522
+ list.appendChild(div);
523
+ }
524
+ }
525
+ // ─── Ticket-Button in Sidebar ───
526
+ const ticketCat = document.createElement('div');
527
+ ticketCat.className = 'channel-category';
528
+ ticketCat.textContent = '— Support';
529
+ list.appendChild(ticketCat);
530
+
531
+ const myOpenTickets = Object.values(DB.tickets||{}).filter(t=>
532
+ (t.author===currentUser.username || hasRole('mod')) && t.status==='open'
533
+ ).length;
534
+
535
+ const ticketBtn = document.createElement('div');
536
+ ticketBtn.className = 'channel-item ticket-sidebar-btn';
537
+ ticketBtn.innerHTML = `
538
+ <span class="channel-icon">🎫</span>
539
+ <span class="channel-name">tickets</span>
540
+ ${myOpenTickets>0 ? `<span class="unread-badge" style="background:var(--purple)">${myOpenTickets}</span>` : ''}
541
+ `;
542
+ ticketBtn.onclick = () => openTicketMenu();
543
+ list.appendChild(ticketBtn);
544
+
545
+ const newTicketBtn = document.createElement('div');
546
+ newTicketBtn.className = 'channel-item';
547
+ newTicketBtn.style.cssText = 'opacity:.75';
548
+ newTicketBtn.innerHTML = `<span class="channel-icon">➕</span><span class="channel-name">neues ticket</span>`;
549
+ newTicketBtn.onclick = () => openCreateTicket();
550
+ list.appendChild(newTicketBtn);
551
+
552
+ // Voice Channels
553
+ const vcCat=document.createElement('div');
554
+ vcCat.className='channel-category';
555
+ vcCat.textContent='— Voice Channels';
556
+ list.appendChild(vcCat);
557
+ for (const vc of [{id:'voice-allgemein',name:'Allgemein',icon:'🔊'},{id:'voice-gaming',name:'Gaming',icon:'🎮'},{id:'voice-musik',name:'Musik',icon:'🎵'}]) {
558
+ const isActive=voiceActive&&voiceChannel===vc.id;
559
+ const div=document.createElement('div');
560
+ div.className='channel-item'+(isActive?' active':'');
561
+ div.innerHTML=`<span class="channel-icon">${vc.icon}</span><span class="channel-name">${vc.name}</span>`;
562
+ div.onclick=()=>joinVoice(vc.id,vc.name);
563
+ list.appendChild(div);
564
+ for (const p of Object.values(DB.voice?.[vc.id]||{})) {
565
+ const pe=document.createElement('div');
566
+ pe.style.cssText='padding:3px 14px 3px 32px;font-size:.78rem;color:var(--green);display:flex;gap:6px;align-items:center;pointer-events:none';
567
+ pe.innerHTML=`<span>🎙</span><span>${escHtml(p.name)}</span>${p.muted?'<span style="color:var(--muted)">🔇</span>':''}`;
568
+ list.appendChild(pe);
569
+ }
570
+ }
571
+ }
572
+
573
+ // ─── CHANNELS ─────────────────────────────────────────────────
574
+ function openChannel(chId) {
575
+ currentChannel=chId; currentDM=null;
576
+ document.querySelectorAll('.channel-item').forEach(el=>el.classList.remove('active'));
577
+ document.querySelector(`[data-channel="${chId}"]`)?.classList.add('active');
578
+ document.querySelectorAll('.dm-item').forEach(el=>el.classList.remove('active'));
579
+ const ch=(appConfig.channels||[]).find(c=>c.id===chId)||{name:chId,icon:'💬',sub:''};
580
+ document.getElementById('chat-title').textContent=ch.icon+' '+ch.name;
581
+ document.getElementById('chat-sub').textContent=ch.sub||'';
582
+ document.getElementById('topbar-channel-name').textContent='# '+ch.name;
583
+ unreadCounts['ch_'+chId]=0; updateBadge('badge-'+chId,0);
584
+ const locked=(ch.adminOnly&&!hasRole('admin'))||(ch.readOnly&&!hasRole('admin'))||(ch.modOnly&&!hasRole('mod'));
585
+ document.getElementById('msg-input').disabled=locked;
586
+ document.getElementById('send-btn').disabled=locked;
587
+ document.getElementById('msg-input').placeholder=locked?'🔒 Du kannst hier nicht schreiben':'Nachricht schreiben...';
588
+ renderChannelMessages(chId);
589
+ }
590
+
591
+ function getMsgs(chId) {
592
+ return Object.values(DB.msgs[chId]||{}).sort((a,b)=>a.ts-b.ts);
593
+ }
594
+
595
+ function renderChannelMessages(chId) {
596
+ const msgs=getMsgs(chId);
597
+ lastMsgCounts['ch_'+chId]=msgs.length;
598
+ renderMessages(msgs);
599
+ }
600
+
601
+ // ─── DMs ──────────────────────────────────────────────────────
602
+ function getDMKey(a,b) { return [a.toLowerCase(),b.toLowerCase()].sort().join('__'); }
603
+
604
+ function getDMMsgs(key) {
605
+ return Object.values(DB.dms[key]||{}).sort((a,b)=>a.ts-b.ts);
606
+ }
607
+
608
+ function openDM(username) {
609
+ // Blockiert?
610
+ if (isBlocked(username)) { showToast('Du hast diesen User blockiert.','var(--warn)'); return; }
611
+ if (isBlockedBy(username)) { showToast('Du kannst dieser Person keine Nachrichten senden.','var(--warn)'); return; }
612
+ currentDM=username; currentChannel=null;
613
+ document.querySelectorAll('.channel-item').forEach(el=>el.classList.remove('active'));
614
+ document.querySelectorAll('.dm-item').forEach(el=>{
615
+ el.classList.toggle('active',el.dataset.user===username.toLowerCase());
616
+ });
617
+ document.getElementById('chat-title').textContent='@ '+username;
618
+ document.getElementById('chat-sub').textContent='Direktnachricht – privat';
619
+ document.getElementById('topbar-channel-name').textContent='@ '+username;
620
+ document.getElementById('msg-input').disabled=false;
621
+ document.getElementById('send-btn').disabled=false;
622
+ document.getElementById('msg-input').placeholder=`Nachricht an @${username}...`;
623
+ unreadCounts['dm_'+username.toLowerCase()]=0;
624
+ // Lesestand persistieren
625
+ const msgs=getDMMsgs(getDMKey(currentUser.username,username));
626
+ if (msgs.length) setDMReadTs(username, msgs[msgs.length-1].ts||0);
627
+ updateDMList();
628
+ renderDMMessages(username);
629
+ }
630
+
631
+ function renderDMMessages(username) {
632
+ const key=getDMKey(currentUser.username,username);
633
+ let msgs=getDMMsgs(key);
634
+ // Nachrichten von blockierten Usern ausblenden
635
+ if (isBlocked(username)||isBlockedBy(username)) {
636
+ document.getElementById('messages').innerHTML='<div class="empty-chat"><div class="empty-chat-icon">🚫</div><p>Du kannst keine Nachrichten mit diesem User austauschen.</p></div>';
637
+ document.getElementById('msg-input').disabled=true;
638
+ document.getElementById('send-btn').disabled=true;
639
+ return;
640
+ }
641
+ lastMsgCounts['dm_'+username.toLowerCase()]=msgs.length;
642
+ // Lesestand beim Rendern aktualisieren
643
+ if (msgs.length) setDMReadTs(username, msgs[msgs.length-1].ts||0);
644
+ renderMessages(msgs,true);
645
+ }
646
+
647
+ // ─── RENDER MESSAGES ──────────────────────────────────────────
648
+ function renderMessages(msgs, isDM=false) {
649
+ const c=document.getElementById('messages');
650
+ const atBottom=c.scrollHeight-c.scrollTop<=c.clientHeight+80;
651
+ if (!msgs.length) {
652
+ c.innerHTML='<div class="empty-chat"><div class="empty-chat-icon">💬</div><p>Noch keine Nachrichten. Schreib was!</p></div>';
653
+ return;
654
+ }
655
+ let html='', lastDay='', lastAuthor='', lastTime=0;
656
+ for (let i=0; i<msgs.length; i++) {
657
+ const m=msgs[i];
658
+ if (m.system) { html+=`<div class="msg-system">⚙ ${escHtml(m.text)}</div>`; lastAuthor=''; continue; }
659
+ if (m.automod){ html+=`<div class="msg-automod">🤖 AutoMod: ${escHtml(m.text)}</div>`; lastAuthor=''; continue; }
660
+ const date=new Date(m.ts);
661
+ const day=date.toLocaleDateString('de-DE',{day:'2-digit',month:'2-digit',year:'numeric'});
662
+ const time=date.toLocaleTimeString('de-DE',{hour:'2-digit',minute:'2-digit'});
663
+ if (day!==lastDay) { html+=`<div class="day-divider">${day}</div>`; lastDay=day; lastAuthor=''; }
664
+ const color=m.color??0;
665
+ const consec=m.author===lastAuthor&&(m.ts-lastTime)<5*60000;
666
+ lastAuthor=m.author; lastTime=m.ts;
667
+ const initials=(m.author||'?')[0].toUpperCase();
668
+ const role=m.role||'member';
669
+ const badge=ROLE_BADGE[role]||'';
670
+ const nc=ROLE_COLORS[role]||`name-color-${color}`;
671
+ const canDel=hasRole('mod')||m.author===currentUser?.username;
672
+ const canPin=hasRole('mod')&&!isDM;
673
+ const safeT=escHtml((m.text||'').substring(0,50));
674
+ html+=`<div class="msg ${consec?'consecutive':''}" data-key="${m._key||''}">
675
+ <div class="msg-avatar av-color-${color}" onclick="onAvatarClick(event,'${escHtml(m.author)}')">${initials}</div>
676
+ <div class="msg-content">
677
+ <div class="msg-header">
678
+ <span class="msg-name ${nc}" onclick="onAvatarClick(event,'${escHtml(m.author)}')">${escHtml(m.author)}${badge?` <span class="msg-role-badge">${badge}</span>`:''}</span>
679
+ <span class="msg-time">${time}</span>
680
+ <div class="msg-actions">
681
+ ${canPin?`<button class="msg-action-btn" onclick="pinMsg('${escHtml(m.author)}','${safeT}')">📌</button>`:''}
682
+ ${canDel?`<button class="msg-action-btn danger" onclick="deleteMsg('${m._key||''}',${isDM})">🗑</button>`:''}
683
+ </div>
684
+ </div>
685
+ <div class="msg-text">${formatMsg(m.text)}</div>
686
+ </div>
687
+ </div>`;
688
+ }
689
+ c.innerHTML=html;
690
+ if (atBottom) c.scrollTop=c.scrollHeight;
691
+ }
692
+
693
+ function formatMsg(text) {
694
+ return escHtml(text)
695
+ .replace(/\*\*(.*?)\*\*/g,'<strong>$1</strong>')
696
+ .replace(/\*(.*?)\*/g,'<em>$1</em>')
697
+ .replace(/`(.*?)`/g,'<code style="background:rgba(0,212,255,0.08);padding:1px 5px;border-radius:2px;font-family:monospace">$1</code>')
698
+ .replace(/(https?:\/\/[^\s]+)/g,'<a href="$1" target="_blank" rel="noopener">$1</a>')
699
+ .replace(/@(alle|here|everyone)/gi,'<span class="ping-everyone">@$1</span>')
700
+ .replace(/@([a-zA-Z0-9_]+)/g,(match,name)=>{
701
+ if(DB.users[name.toLowerCase()]) return `<span class="ping-user${name.toLowerCase()===currentUser?.username?.toLowerCase()?' ping-me':''}">${match}</span>`;
702
+ return match;
703
+ });
704
+ }
705
+
706
+ // ─── SEND ─────────────────────────────────────────────────────
707
+ async function sendMessage() {
708
+ const input=document.getElementById('msg-input');
709
+ const text=input.value.trim();
710
+ if (!text||!currentUser) return;
711
+ const mod=DB.moderation;
712
+ const to=mod.timeouts?.[currentUser.username.toLowerCase()];
713
+ if (to&&to.until>Date.now()) { showToast('Du bist stummgeschaltet!','var(--warn)'); return; }
714
+ if (!currentDM) {
715
+ const ch=(appConfig.channels||[]).find(c=>c.id===currentChannel);
716
+ if (ch?.adminOnly&&!hasRole('admin')) return;
717
+ if (ch?.readOnly&&!hasRole('admin')) return;
718
+ if (ch?.modOnly&&!hasRole('mod')) return;
719
+ const am=autoModCheck(text);
720
+ if (am.blocked) { showToast('🤖 AutoMod: '+am.reason,'var(--warn)'); input.value=''; input.style.height=''; return; }
721
+ }
722
+ const now=Date.now();
723
+ spamTs=spamTs.filter(t=>now-t<(appConfig.automod?.spamWindow||10000));
724
+ spamTs.push(now);
725
+ if (spamTs.length>(appConfig.automod?.spamThreshold||5)) {
726
+ pendingSpamMsg=text; input.value=''; input.style.height='';
727
+ showSpamCaptchaModal(); return;
728
+ }
729
+ input.value=''; input.style.height='';
730
+ const msg={author:currentUser.username,color:currentUser.color,role:currentUser.role,text,ts:Date.now()};
731
+
732
+ // Ping-Erkennung für Desktop-Notifications
733
+ const isPingAll = /@(alle|here|everyone)/i.test(text);
734
+ const isPingMe = new RegExp('@'+currentUser.username,'i').test(text);
735
+
736
+ if (currentDM) {
737
+ const key=getDMKey(currentUser.username,currentDM);
738
+ if (!DB.dms[key]) DB.dms[key]={};
739
+ dbPush(`dms/${key}`,msg);
740
+ renderDMMessages(currentDM);
741
+ } else {
742
+ if (!DB.msgs[currentChannel]) DB.msgs[currentChannel]={};
743
+ dbPush(`msgs/${currentChannel}`,msg);
744
+ renderChannelMessages(currentChannel);
745
+ document.getElementById('messages').scrollTop=9999999;
746
+ }
747
+ }
748
+
749
+ function autoModCheck(text) {
750
+ const am=appConfig.automod||{};
751
+ if (!am.enabled) return {blocked:false};
752
+ if (am.maxMsgLength&&text.length>am.maxMsgLength) return {blocked:true,reason:`Zu lang (max. ${am.maxMsgLength})`};
753
+ const lower=text.toLowerCase();
754
+ for (const w of (am.bannedWords||[])) { if(lower.includes(w.toLowerCase())) return {blocked:true,reason:'Verbotenes Wort'}; }
755
+ if (am.capsFilter&&text.length>10) {
756
+ const caps=(text.match(/[A-ZÄÖÜ]/g)||[]).length;
757
+ if (caps/text.length>(am.capsThreshold||0.7)) return {blocked:true,reason:'Zu viele Großbuchstaben'};
758
+ }
759
+ return {blocked:false};
760
+ }
761
+
762
+ function deleteMsg(key,isDM=false) {
763
+ if (!key) return;
764
+ if (isDM&&currentDM) {
765
+ const dmKey=getDMKey(currentUser.username,currentDM);
766
+ const m=DB.dms[dmKey]?.[key];
767
+ if (!m||(m.author!==currentUser.username&&!hasRole('mod'))) return;
768
+ dbDelete(`dms/${dmKey}/${key}`);
769
+ renderDMMessages(currentDM);
770
+ } else {
771
+ const m=DB.msgs[currentChannel]?.[key];
772
+ if (!m||(m.author!==currentUser.username&&!hasRole('mod'))) return;
773
+ dbDelete(`msgs/${currentChannel}/${key}`);
774
+ renderChannelMessages(currentChannel);
775
+ }
776
+ }
777
+
778
+ function pinMsg(author,text) {
779
+ if (!Array.isArray(DB.pins)) DB.pins=[];
780
+ DB.pins.push({author,text,by:currentUser.username,ts:Date.now(),channel:currentChannel});
781
+ if (DB.pins.length>50) DB.pins.shift();
782
+ apiSave();
783
+ showToast('📌 Nachricht angepinnt','var(--green)');
784
+ }
785
+
786
+ function handleKey(e) { if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();sendMessage();} }
787
+ function autoResize(el) { el.style.height='auto'; el.style.height=Math.min(el.scrollHeight,120)+'px'; }
788
+
789
+ // ─── TIMEOUT BAR ──────────────────────────────────────────────
790
+ function updateTimeoutBar() {
791
+ const t=DB.moderation.timeouts?.[currentUser.username.toLowerCase()];
792
+ const bar=document.getElementById('timeout-bar');
793
+ if (t&&t.until>Date.now()) {
794
+ bar.style.display='';
795
+ document.getElementById('timeout-until').textContent=
796
+ new Date(t.until).toLocaleTimeString('de-DE',{hour:'2-digit',minute:'2-digit',second:'2-digit'});
797
+ document.getElementById('msg-input').disabled=true;
798
+ document.getElementById('send-btn').disabled=true;
799
+ } else {
800
+ bar.style.display='none';
801
+ if (!currentDM) {
802
+ const ch=(appConfig.channels||[]).find(c=>c.id===currentChannel);
803
+ const locked=(ch?.adminOnly&&!hasRole('admin'))||(ch?.readOnly&&!hasRole('admin'));
804
+ document.getElementById('msg-input').disabled=!!locked;
805
+ document.getElementById('send-btn').disabled=!!locked;
806
+ }
807
+ }
808
+ }
809
+
810
+ function updateBadge(id,count) {
811
+ const el=document.getElementById(id); if (!el) return;
812
+ if (count>0){el.style.display='';el.textContent=count>99?'99+':count;}
813
+ else el.style.display='none';
814
+ }
815
+
816
+ // ═══════════════════════════════════════════════════════════════
817
+ // REAL VOICE — WebRTC via PeerJS
818
+ // ═══════════════════════════════════════════════════════════════
819
+ let myPeer = null; // PeerJS-Instanz
820
+ let localStream = null; // Mikrofon-Stream
821
+ let activeCalls = {}; // { peerId: Call }
822
+ let activeAudios = {}; // { peerId: <audio> }
823
+
824
+ // Peer-ID: kurzer Hash damit sie garantiert valid und eindeutig ist
825
+ function makePeerId(username, vcId) {
826
+ // Nur lowercase alphanumeric + Bindestrich erlaubt
827
+ // Einfacher deterministischer Hash
828
+ const raw = (username + '_' + vcId).toLowerCase();
829
+ let h = 5381;
830
+ for (let i = 0; i < raw.length; i++) h = ((h << 5) + h) ^ raw.charCodeAt(i);
831
+ const hash = Math.abs(h).toString(16).slice(0, 8);
832
+ return 'nc-' + username.toLowerCase().replace(/[^a-z0-9]/g, '') + '-' + hash;
833
+ }
834
+
835
+ async function joinVoice(vcId, vcName) {
836
+ if (voiceActive && voiceChannel === vcId) { leaveVoice(); return; }
837
+ if (voiceActive) await leaveVoice();
838
+
839
+ // Mikrofon anfordern
840
+ try {
841
+ localStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
842
+ } catch(e) {
843
+ showToast('🎙 Mikrofon-Zugriff verweigert!', 'var(--danger)');
844
+ return;
845
+ }
846
+
847
+ voiceActive = true;
848
+ voiceChannel = vcId;
849
+ micMuted = false;
850
+ deafened = false;
851
+
852
+ const peerId = makePeerId(currentUser.username, vcId);
853
+
854
+ // Alten Peer aufräumen
855
+ if (myPeer && !myPeer.destroyed) { myPeer.destroy(); myPeer = null; }
856
+
857
+ // PeerJS mit dem offiziellen 0.peerjs.com Server
858
+ myPeer = new Peer(peerId, {
859
+ host: '0.peerjs.com',
860
+ port: 443,
861
+ secure: true,
862
+ path: '/',
863
+ debug: 0,
864
+ config: {
865
+ iceServers: [
866
+ { urls: 'stun:stun.l.google.com:19302' },
867
+ { urls: 'stun:stun1.l.google.com:19302' },
868
+ { urls: 'stun:stun2.l.google.com:19302' },
869
+ ]
870
+ }
871
+ });
872
+
873
+ myPeer.on('open', (id) => {
874
+ console.log('[Voice] Peer offen:', id);
875
+ // In DB eintragen
876
+ if (!DB.voice[vcId]) DB.voice[vcId] = {};
877
+ DB.voice[vcId][currentUser.username] = {
878
+ name: currentUser.username,
879
+ peerId: id,
880
+ muted: false,
881
+ ts: Date.now()
882
+ };
883
+ apiSave();
884
+
885
+ // Mit allen anderen im Channel verbinden
886
+ const others = Object.entries(DB.voice[vcId] || {})
887
+ .filter(([uname]) => uname !== currentUser.username);
888
+ for (const [uname, data] of others) {
889
+ if (data.peerId) callPeer(data.peerId);
890
+ }
891
+
892
+ // Panel anzeigen
893
+ document.getElementById('voice-panel').classList.add('active');
894
+ document.getElementById('voice-channel-name').textContent = '🔊 ' + vcName;
895
+ document.getElementById('voice-mute-btn').textContent = '🎙 Stumm';
896
+ document.getElementById('voice-deaf-btn').textContent = '🔔 Taub';
897
+ document.getElementById('voice-mute-btn').classList.remove('active');
898
+ document.getElementById('voice-deaf-btn').classList.remove('active');
899
+ buildChannelList();
900
+ showToast(`🔊 Beigetreten: ${vcName}`, 'var(--green)');
901
+ });
902
+
903
+ // Eingehende Anrufe entgegennehmen
904
+ myPeer.on('call', (call) => {
905
+ call.answer(localStream);
906
+ handleCallStream(call);
907
+ });
908
+
909
+ myPeer.on('error', (err) => {
910
+ console.warn('[Voice] Peer-Fehler:', err.type, err.message);
911
+ if (err.type === 'unavailable-id') {
912
+ // ID besetzt → zufälligen Suffix anhängen und neu verbinden
913
+ if (myPeer && !myPeer.destroyed) { myPeer.destroy(); myPeer = null; }
914
+ const fallbackId = makePeerId(currentUser.username, vcId) + '-' + Math.random().toString(36).slice(2,6);
915
+ myPeer = new Peer(fallbackId, {
916
+ host: '0.peerjs.com', port: 443, secure: true, path: '/',
917
+ config: { iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] }
918
+ });
919
+ myPeer.on('open', (id) => {
920
+ if (!DB.voice[vcId]) DB.voice[vcId] = {};
921
+ DB.voice[vcId][currentUser.username] = { name: currentUser.username, peerId: id, muted: false, ts: Date.now() };
922
+ apiSave();
923
+ const others = Object.entries(DB.voice[vcId] || {}).filter(([u]) => u !== currentUser.username);
924
+ for (const [, data] of others) { if (data.peerId) callPeer(data.peerId); }
925
+ });
926
+ myPeer.on('call', (call) => { call.answer(localStream); handleCallStream(call); });
927
+ myPeer.on('error', (e) => showToast('🔊 Voice-Fehler: ' + e.type, 'var(--warn)'));
928
+ } else if (err.type === 'peer-unavailable') {
929
+ // Anderer Peer nicht erreichbar - ignorieren, wird beim nächsten Poll nochmal versucht
930
+ console.warn('[Voice] Peer nicht erreichbar:', err.message);
931
+ } else if (err.type === 'network' || err.type === 'server-error') {
932
+ showToast('🔊 Voice-Verbindungsfehler, versuche Neuverbindung...', 'var(--warn)');
933
+ setTimeout(() => { if (voiceActive) myPeer?.reconnect(); }, 2000);
934
+ } else {
935
+ showToast('🔊 Voice-Fehler: ' + err.type, 'var(--warn)');
936
+ }
937
+ });
938
+
939
+ myPeer.on('disconnected', () => {
940
+ if (voiceActive) myPeer.reconnect();
941
+ });
942
+ }
943
+
944
+ function callPeer(remotePeerId) {
945
+ if (!localStream || !myPeer || activeCalls[remotePeerId]) return;
946
+ console.log('[Voice] Rufe an:', remotePeerId);
947
+ const call = myPeer.call(remotePeerId, localStream);
948
+ if (!call) return;
949
+ handleCallStream(call);
950
+ }
951
+
952
+ function handleCallStream(call) {
953
+ activeCalls[call.peer] = call;
954
+ call.on('stream', (remoteStream) => {
955
+ if (activeAudios[call.peer]) {
956
+ activeAudios[call.peer].srcObject = remoteStream;
957
+ return;
958
+ }
959
+ const audio = document.createElement('audio');
960
+ audio.autoplay = true;
961
+ audio.srcObject = remoteStream;
962
+ document.body.appendChild(audio);
963
+ activeAudios[call.peer] = audio;
964
+ console.log('[Voice] Stream von:', call.peer);
965
+ });
966
+ call.on('close', () => {
967
+ cleanupPeer(call.peer);
968
+ });
969
+ call.on('error', (e) => {
970
+ console.warn('[Voice] Call-Fehler:', e);
971
+ cleanupPeer(call.peer);
972
+ });
973
+ }
974
+
975
+ function cleanupPeer(peerId) {
976
+ if (activeCalls[peerId]) { try { activeCalls[peerId].close(); } catch {} delete activeCalls[peerId]; }
977
+ if (activeAudios[peerId]) { activeAudios[peerId].remove(); delete activeAudios[peerId]; }
978
+ }
979
+
980
+ async function leaveVoice() {
981
+ if (!voiceActive) return;
982
+ const ch = voiceChannel;
983
+ voiceActive = false;
984
+ voiceChannel = null;
985
+
986
+ // Alle Calls beenden
987
+ for (const pid of Object.keys(activeCalls)) cleanupPeer(pid);
988
+ activeCalls = {};
989
+
990
+ // Mikrofon stoppen
991
+ if (localStream) {
992
+ localStream.getTracks().forEach(t => t.stop());
993
+ localStream = null;
994
+ }
995
+
996
+ // Peer zerstören
997
+ if (myPeer && !myPeer.destroyed) {
998
+ myPeer.destroy();
999
+ myPeer = null;
1000
+ }
1001
+
1002
+ // DB-Eintrag entfernen
1003
+ if (DB.voice?.[ch]?.[currentUser.username]) {
1004
+ delete DB.voice[ch][currentUser.username];
1005
+ apiSave();
1006
+ }
1007
+
1008
+ document.getElementById('voice-panel').classList.remove('active');
1009
+ buildChannelList();
1010
+ showToast('Voice verlassen', 'var(--muted)');
1011
+ }
1012
+
1013
+ function toggleMute() {
1014
+ micMuted = !micMuted;
1015
+ const btn = document.getElementById('voice-mute-btn');
1016
+ btn.textContent = micMuted ? '🔇 Stumm' : '🎙 Stumm';
1017
+ btn.classList.toggle('active', micMuted);
1018
+ // Mikrofon-Track stumm/laut schalten
1019
+ if (localStream) {
1020
+ localStream.getAudioTracks().forEach(t => { t.enabled = !micMuted; });
1021
+ }
1022
+ if (voiceActive && DB.voice?.[voiceChannel]?.[currentUser.username]) {
1023
+ DB.voice[voiceChannel][currentUser.username].muted = micMuted;
1024
+ DB.voice[voiceChannel][currentUser.username].ts = Date.now();
1025
+ apiSave();
1026
+ }
1027
+ }
1028
+
1029
+ function toggleDeafen() {
1030
+ deafened = !deafened;
1031
+ const btn = document.getElementById('voice-deaf-btn');
1032
+ btn.textContent = deafened ? '🔕 Taub' : '🔔 Taub';
1033
+ btn.classList.toggle('active', deafened);
1034
+ // Alle eingehenden Audios stumm/laut schalten
1035
+ for (const audio of Object.values(activeAudios)) {
1036
+ audio.muted = deafened;
1037
+ }
1038
+ }
1039
+
1040
+ // Im Poll-Tick: neue User im Channel erkennen und anrufen
1041
+ function voicePollConnect() {
1042
+ if (!voiceActive || !voiceChannel || !myPeer || myPeer.disconnected) return;
1043
+ const others = Object.entries(DB.voice[voiceChannel] || {})
1044
+ .filter(([uname]) => uname !== currentUser.username);
1045
+ for (const [uname, data] of others) {
1046
+ if (data.peerId && !activeCalls[data.peerId]) {
1047
+ callPeer(data.peerId);
1048
+ }
1049
+ }
1050
+ }
1051
+
1052
+ // ─── USER LIST ────────────────────────────────────────────────
1053
+ function renderUserList(onlineNames) {
1054
+ const listEl=document.getElementById('user-list');
1055
+ listEl.innerHTML='';
1056
+ const groups={owner:[],admin:[],mod:[],vip:[],member:[]};
1057
+ for (const u of Object.values(DB.users)) {
1058
+ if (groups[u.role||'member']) groups[u.role||'member'].push(u);
1059
+ else groups.member.push(u);
1060
+ }
1061
+ for (const [roleId,users] of Object.entries(groups)) {
1062
+ if (!users.length) continue;
1063
+ const hdr=document.createElement('div');
1064
+ hdr.className='role-group-header';
1065
+ hdr.innerHTML=`<span>${ROLE_LABELS[roleId]}</span><span style="color:var(--muted);font-size:.7rem">${users.length}</span>`;
1066
+ listEl.appendChild(hdr);
1067
+ for (const u of users) {
1068
+ const isMe=u.username===currentUser?.username;
1069
+ const isOnline=onlineNames.includes(u.username);
1070
+ const div=document.createElement('div');
1071
+ div.className='user-item'+(isMe?' me':'')+(!isOnline?' offline':'');
1072
+ div.innerHTML=`<div class="${isOnline?'online-dot':'offline-dot'}"></div>
1073
+ <div class="user-avatar-sm av-color-${u.color??0}">${u.username[0].toUpperCase()}</div>
1074
+ <span>${escHtml(u.username)}${ROLE_BADGE[u.role]?' '+ROLE_BADGE[u.role]:''}</span>`;
1075
+ if (!isMe) div.onclick=e=>{e.stopPropagation();showUserCtx(e,u.username);};
1076
+ listEl.appendChild(div);
1077
+ }
1078
+ }
1079
+ }
1080
+
1081
+ function updateDMList() {
1082
+ const dmEl=document.getElementById('dm-list');
1083
+ dmEl.innerHTML='';
1084
+ for (const u of Object.values(DB.users)) {
1085
+ if (u.username===currentUser?.username) continue;
1086
+ if (isBlocked(u.username)) continue; // Blockierte nicht anzeigen
1087
+ // Unread berechnen: Nachrichten neuer als letzter Lesestand
1088
+ const msgs=getDMMsgs(getDMKey(currentUser.username,u.username));
1089
+ const readTs=getDMReadTs(u.username);
1090
+ const unread=msgs.filter(m=>m.author!==currentUser.username&&(m.ts||0)>readTs).length;
1091
+ if (unread>0) unreadCounts['dm_'+u.username.toLowerCase()]=unread;
1092
+ const count=unreadCounts['dm_'+u.username.toLowerCase()]||0;
1093
+ const div=document.createElement('div');
1094
+ div.className=`channel-item dm-item ${currentDM===u.username?'active':''}`;
1095
+ div.dataset.user=u.username.toLowerCase();
1096
+ div.innerHTML=`<span class="channel-icon">@</span><span class="channel-name">${escHtml(u.username)}</span>${count>0?`<span class="unread-badge">${count}</span>`:''}`;
1097
+ div.onclick=()=>openDM(u.username);
1098
+ dmEl.appendChild(div);
1099
+ }
1100
+ }
1101
+
1102
+ // ─── CONTEXT MENU ─────────────────────────────────────────────
1103
+ function onAvatarClick(e,username) {
1104
+ e.preventDefault(); e.stopPropagation();
1105
+ hideCtx();
1106
+ if (username===currentUser?.username) return;
1107
+ showUserCtx(e,username);
1108
+ }
1109
+ function showUserCtx(e,username) {
1110
+ e.preventDefault(); e.stopPropagation();
1111
+ hideCtx();
1112
+ const menu=document.getElementById('context-menu');
1113
+ menu.innerHTML='';
1114
+ const h=document.createElement('div'); h.className='ctx-header'; h.textContent=username; menu.appendChild(h);
1115
+ addCtxItem(menu,'💬 Direktnachricht','',()=>{hideCtx();openDM(username);});
1116
+ addCtxItem(menu,'👤 Profil','',()=>{hideCtx();showProfileModal(username);});
1117
+ // Block/Unblock
1118
+ if (isBlocked(username)) {
1119
+ addCtxItem(menu,'✅ Entblocken','',()=>{hideCtx();unblockUser(username);});
1120
+ } else {
1121
+ addCtxItem(menu,'🚫 Blockieren','warn',()=>{hideCtx();confirmBlock(username);});
1122
+ }
1123
+ if (hasRole('mod')) {
1124
+ addCtxDivider(menu);
1125
+ addCtxItem(menu,'👢 Kicken','warn',()=>{hideCtx();openKickModal(username);});
1126
+ addCtxItem(menu,'⏱ Timeout','warn',()=>{hideCtx();openTimeoutModal(username);});
1127
+ addCtxItem(menu,'🗑 Nachrichten löschen','warn',()=>{hideCtx();clearUserMsgs(username);});
1128
+ }
1129
+ if (hasRole('admin')) {
1130
+ addCtxItem(menu,'🚫 Bannen','danger',()=>{hideCtx();openBanModal(username);});
1131
+ addCtxDivider(menu);
1132
+ addCtxItem(menu,'🎖 Rolle ändern','',()=>{hideCtx();openRoleModal(username);});
1133
+ }
1134
+ menu.style.left=Math.min(e.clientX,window.innerWidth-210)+'px';
1135
+ menu.style.top=Math.min(e.clientY,window.innerHeight-200)+'px';
1136
+ menu.style.display='';
1137
+ }
1138
+ function addCtxItem(menu,label,cls,fn){const i=document.createElement('div');i.className='ctx-item'+(cls?' '+cls:'');i.textContent=label;i.onclick=fn;menu.appendChild(i);}
1139
+ function addCtxDivider(menu){const d=document.createElement('div');d.className='ctx-divider';menu.appendChild(d);}
1140
+ function hideCtx(){document.getElementById('context-menu').style.display='none';}
1141
+ document.addEventListener('click',hideCtx);
1142
+
1143
+ function confirmBlock(username) {
1144
+ showModal(`<div class="modal-title">🚫 ${escHtml(username)} blockieren?</div>
1145
+ <div class="modal-sub" style="margin-bottom:16px">Du siehst keine DMs mehr von dieser Person und kannst ihr keine senden.</div>
1146
+ <div class="modal-btns">
1147
+ <button class="modal-btn secondary" onclick="clearModal()">Abbrechen</button>
1148
+ <button class="modal-btn warn-btn" onclick="blockUser('${escHtml(username)}');clearModal()">Blockieren</button>
1149
+ </div>`);
1150
+ }
1151
+
1152
+ // ─── MODERATION ───────────────────────────────────────────────
1153
+ function openKickModal(u) {
1154
+ showModal(`<div class="modal-title">👢 Kick: ${escHtml(u)}</div>
1155
+ <div class="modal-sub">Der User wird aus dem Chat geworfen.</div>
1156
+ <div class="modal-field"><label>Grund (optional)</label><input type="text" id="m-reason" placeholder="z.B. Regelverstoß"></div>
1157
+ <div class="modal-btns">
1158
+ <button class="modal-btn secondary" onclick="clearModal()">Abbrechen</button>
1159
+ <button class="modal-btn warn-btn" onclick="doKick('${escHtml(u)}')">Kicken</button>
1160
+ </div>`);
1161
+ }
1162
+ function doKick(u) {
1163
+ const reason=document.getElementById('m-reason')?.value||'';
1164
+ if (!DB.moderation.kicked) DB.moderation.kicked={};
1165
+ DB.moderation.kicked[u.toLowerCase()]={by:currentUser.username,ts:Date.now(),reason};
1166
+ apiSave();
1167
+ sysMsg(`${u} wurde von ${currentUser.username} gekickt.${reason?' Grund: '+reason:''}`);
1168
+ clearModal(); showToast(`${u} gekickt`,'var(--warn)');
1169
+ }
1170
+ function openTimeoutModal(u) {
1171
+ showModal(`<div class="modal-title">⏱ Timeout: ${escHtml(u)}</div>
1172
+ <div class="modal-sub">Stummschalten für eine bestimmte Zeit.</div>
1173
+ <div class="modal-field"><label>Dauer</label>
1174
+ <select id="m-dur">
1175
+ <option value="60000">1 Minute</option><option value="300000">5 Minuten</option>
1176
+ <option value="600000">10 Minuten</option><option value="1800000">30 Minuten</option>
1177
+ <option value="3600000">1 Stunde</option><option value="86400000">24 Stunden</option>
1178
+ </select></div>
1179
+ <div class="modal-field"><label>Grund</label><input type="text" id="m-reason" placeholder="z.B. Spam"></div>
1180
+ <div class="modal-btns">
1181
+ <button class="modal-btn secondary" onclick="clearModal()">Abbrechen</button>
1182
+ <button class="modal-btn warn-btn" onclick="doTimeout('${escHtml(u)}')">Timeout</button>
1183
+ </div>`);
1184
+ }
1185
+ function doTimeout(u) {
1186
+ const dur=parseInt(document.getElementById('m-dur').value);
1187
+ const reason=document.getElementById('m-reason')?.value||'';
1188
+ if (!DB.moderation.timeouts) DB.moderation.timeouts={};
1189
+ DB.moderation.timeouts[u.toLowerCase()]={until:Date.now()+dur,by:currentUser.username,reason};
1190
+ apiSave();
1191
+ sysMsg(`${u} stummgeschaltet für ${Math.round(dur/60000)} Min.${reason?' Grund: '+reason:''}`);
1192
+ clearModal(); showToast(`${u} stummgeschaltet`,'var(--warn)');
1193
+ }
1194
+ function openBanModal(u) {
1195
+ showModal(`<div class="modal-title" style="color:var(--danger)">🚫 Ban: ${escHtml(u)}</div>
1196
+ <div class="modal-sub">Permanenter Bann.</div>
1197
+ <div class="modal-field"><label>Grund</label><input type="text" id="m-reason" placeholder="Banngrund (Pflicht)"></div>
1198
+ <div class="modal-btns">
1199
+ <button class="modal-btn secondary" onclick="clearModal()">Abbrechen</button>
1200
+ <button class="modal-btn danger-btn" onclick="doBan('${escHtml(u)}')">BANNEN</button>
1201
+ </div>`);
1202
+ }
1203
+ function doBan(u) {
1204
+ const reason=document.getElementById('m-reason')?.value||'';
1205
+ if (!reason) { showToast('Bitte einen Grund angeben!','var(--danger)'); return; }
1206
+ if (!DB.moderation.bans) DB.moderation.bans={};
1207
+ DB.moderation.bans[u.toLowerCase()]={by:currentUser.username,ts:Date.now(),reason};
1208
+ const fp=DB.users[u.toLowerCase()]?._fp;
1209
+ if (fp) { if (!DB.moderation.banned_fps) DB.moderation.banned_fps={}; DB.moderation.banned_fps[fp]=true; }
1210
+ apiSave();
1211
+ sysMsg(`${u} wurde von ${currentUser.username} gebannt. Grund: ${reason}`);
1212
+ clearModal(); showToast(`${u} gebannt`,'var(--danger)');
1213
+ }
1214
+ function openRoleModal(u) {
1215
+ showModal(`<div class="modal-title">🎖 Rolle: ${escHtml(u)}</div>
1216
+ <div class="modal-sub">Rolle des Users ändern.</div>
1217
+ <div class="modal-field"><label>Neue Rolle</label>
1218
+ <select id="m-role">
1219
+ <option value="member">Mitglied</option><option value="vip">💎 VIP</option>
1220
+ <option value="mod">⭐ Moderator</option>
1221
+ ${currentUser.role==='owner'?'<option value="admin">🔰 Admin</option>':''}
1222
+ </select></div>
1223
+ <div class="modal-btns">
1224
+ <button class="modal-btn secondary" onclick="clearModal()">Abbrechen</button>
1225
+ <button class="modal-btn primary" onclick="doSetRole('${escHtml(u)}')">Speichern</button>
1226
+ </div>`);
1227
+ }
1228
+ function doSetRole(u) {
1229
+ const newRole=document.getElementById('m-role').value;
1230
+ const target=DB.users[u.toLowerCase()]; if (!target) return clearModal();
1231
+ if (target.role==='owner'){showToast('Owner-Rolle kann nicht geändert werden','var(--danger)');return clearModal();}
1232
+ if (currentUser.role!=='owner'&&ROLE_PRIORITY[target.role]>=ROLE_PRIORITY[currentUser.role]){
1233
+ showToast('Keine Berechtigung','var(--danger)');return clearModal();
1234
+ }
1235
+ DB.users[u.toLowerCase()].role=newRole;
1236
+ apiSave();
1237
+ sysMsg(`${u} → Rolle "${ROLE_LABELS[newRole]}" (von ${currentUser.username})`);
1238
+ clearModal(); showToast(`${u} → ${ROLE_LABELS[newRole]}`,'var(--green)');
1239
+ }
1240
+ function clearUserMsgs(u) {
1241
+ if (!hasRole('mod')) return;
1242
+ const ch=DB.msgs[currentChannel]||{};
1243
+ for (const [k,m] of Object.entries(ch)) { if (m.author===u) delete DB.msgs[currentChannel][k]; }
1244
+ apiSave();
1245
+ renderChannelMessages(currentChannel);
1246
+ showToast(`Nachrichten von ${u} gelöscht`,'var(--warn)');
1247
+ }
1248
+ function sysMsg(text) {
1249
+ if (!currentChannel) return;
1250
+ if (!DB.msgs[currentChannel]) DB.msgs[currentChannel]={};
1251
+ dbPush(`msgs/${currentChannel}`,{system:true,text,ts:Date.now()});
1252
+ }
1253
+
1254
+ // ─── PROFILE ──────────────────────────────────────────────────
1255
+ function showProfileModal(username) {
1256
+ const u=DB.users[username.toLowerCase()]; if (!u) return;
1257
+ showModal(`<div class="modal-title">👤 ${escHtml(u.username)} ${ROLE_BADGE[u.role]||''}</div>
1258
+ <div class="modal-sub">Rolle: ${ROLE_LABELS[u.role]||'Mitglied'} · Beigetreten: ${new Date(u.joined||Date.now()).toLocaleDateString('de-DE')}</div>
1259
+ <div style="text-align:center;margin:14px 0">
1260
+ <div class="user-avatar-sm av-color-${u.color}" style="width:60px;height:60px;font-size:1.5rem;margin:0 auto 12px">${u.username[0].toUpperCase()}</div>
1261
+ </div>
1262
+ <div class="modal-btns">
1263
+ <button class="modal-btn secondary" onclick="clearModal()">Schließen</button>
1264
+ <button class="modal-btn primary" onclick="clearModal();openDM('${escHtml(u.username)}')">💬 DM senden</button>
1265
+ </div>`);
1266
+ }
1267
+
1268
+ // ─── SETTINGS ─────────────────────────────────────────────────
1269
+ const _st={};
1270
+ function openSettings() {
1271
+ const s=currentUser.settings||{};
1272
+ showModal(`<div class="modal-title">⚙️ Einstellungen</div>
1273
+ <div class="modal-tabs">
1274
+ <button class="modal-tab active" onclick="switchSettingsTab('konto',this)">Konto</button>
1275
+ <button class="modal-tab" onclick="switchSettingsTab('darstellung',this)">Darstellung</button>
1276
+ ${hasRole('mod')?'<button class="modal-tab" onclick="switchSettingsTab(\'automod\',this)">AutoMod</button>':''}
1277
+ ${hasRole('admin')?'<button class="modal-tab" onclick="switchSettingsTab(\'admin\',this)">Admin</button>':''}
1278
+ <button class="modal-tab" onclick="switchSettingsTab(\'blockiert\',this)">Blockiert</button> </div>
1279
+ <div id="settings-tab-konto">
1280
+ <div class="settings-section"><h4>Konto</h4>
1281
+ <div class="modal-field"><label>Neuer Username</label><input type="text" id="s-user" placeholder="${escHtml(currentUser.username)}"></div>
1282
+ <div class="modal-field"><label>Neues Passwort</label><input type="password" id="s-pass" placeholder="Leer = keine Änderung"></div>
1283
+ <div class="modal-field"><label>Passwort bestätigen</label><input type="password" id="s-pass2"></div>
1284
+ </div>
1285
+ <div class="settings-section"><h4>Benachrichtigungen</h4>
1286
+ <div class="toggle-row"><label>DM-Benachrichtigungen</label>
1287
+ <div class="toggle ${s.notif!==false?'on':''}" id="toggle-notif" onclick="toggleST('notif')"></div>
1288
+ </div>
1289
+ </div>
1290
+ </div>
1291
+ <div id="settings-tab-darstellung" style="display:none">
1292
+ <div class="settings-section"><h4>Avatar-Farbe</h4>
1293
+ <div style="display:flex;gap:10px;margin:10px 0">
1294
+ ${[0,1,2,3,4].map(i=>`<div class="user-avatar-sm av-color-${i}" style="width:36px;height:36px;cursor:pointer${currentUser.color===i?';box-shadow:0 0 8px currentColor':''}" onclick="setAvatarColor(${i})">${currentUser.username[0].toUpperCase()}</div>`).join('')}
1295
+ </div>
1296
+ </div>
1297
+ </div>
1298
+ ${hasRole('mod')?`<div id="settings-tab-automod" style="display:none">
1299
+ <div class="settings-section"><h4>AutoMod</h4>
1300
+ <div class="toggle-row"><label>AutoMod aktiv</label><div class="toggle ${appConfig.automod?.enabled?'on':''}" id="toggle-am" onclick="toggleST('am')"></div></div>
1301
+ <div class="modal-field"><label>Max. Nachrichtenlänge</label><input type="number" id="s-maxlen" value="${appConfig.automod?.maxMsgLength||800}"></div>
1302
+ <div class="modal-field"><label>Spam-Grenze (Nachrichten/10s)</label><input type="number" id="s-spam" value="${appConfig.automod?.spamThreshold||5}"></div>
1303
+ <div class="modal-field"><label>Verbotene Wörter</label>
1304
+ <div id="bw-tags">${(appConfig.automod?.bannedWords||[]).map(w=>`<span class="tag">${escHtml(w)}<button class="tag-remove" onclick="removeBW('${escHtml(w)}')">×</button></span>`).join('')}</div>
1305
+ <div style="display:flex;gap:6px;margin-top:6px">
1306
+ <input class="tag-input" type="text" id="new-bw" placeholder="Wort hinzufügen" style="flex:1">
1307
+ <button class="modal-btn primary" style="flex:none;width:auto;padding:5px 12px;font-size:.7rem" onclick="addBW()">+</button>
1308
+ </div>
1309
+ </div>
1310
+ <div class="toggle-row"><label>Caps-Filter</label><div class="toggle ${appConfig.automod?.capsFilter?'on':''}" id="toggle-caps" onclick="toggleST('caps')"></div></div>
1311
+ <div class="toggle-row"><label>Link-Filter</label><div class="toggle ${appConfig.automod?.linkFilter?'on':''}" id="toggle-links" onclick="toggleST('links')"></div></div>
1312
+ </div>
1313
+ </div>`:''}
1314
+ ${hasRole('admin')?`<div id="settings-tab-admin" style="display:none">
1315
+ <div class="settings-section"><h4>Ticket-Übersicht</h4><div id="admin-tickets-list">Wird geladen...</div></div>
1316
+ </div>`:''}
1317
+ <div id="settings-tab-blockiert" style="display:none">
1318
+ <div class="settings-section"><h4>Blockierte User</h4>
1319
+ <div id="blocked-list">
1320
+ ${(()=>{
1321
+ const bl=DB.blocks?.[currentUser.username.toLowerCase()]||[];
1322
+ if(!bl.length) return '<div style="color:var(--muted);font-size:.85rem;padding:12px 0">Niemand blockiert</div>';
1323
+ return bl.map(u=>`<div style="display:flex;justify-content:space-between;align-items:center;padding:7px 0;border-bottom:1px solid var(--border)">
1324
+ <span>${escHtml(u)}</span>
1325
+ <button class="modal-btn secondary" style="padding:3px 10px;font-size:.7rem;width:auto" onclick="unblockUser('${escHtml(u)}');this.closest('.settings-section').parentElement.parentElement.querySelector('#blocked-list').innerHTML='<div style=color:var(--muted);font-size:.85rem;padding:12px 0>Aktualisiert – bitte Tab neu öffnen</div>'">Entblocken</button>
1326
+ </div>`).join('');
1327
+ })()}
1328
+ </div>
1329
+ </div>
1330
+ </div> <div class="modal-btns">
1331
+ <button class="modal-btn secondary" onclick="clearModal()">Schließen</button>
1332
+ <button class="modal-btn primary" onclick="saveSettings()">Speichern</button>
1333
+ </div>`,true);
1334
+ if (hasRole('admin')) setTimeout(loadAdminTickets,100);
1335
+ }
1336
+ function loadAdminTickets(){
1337
+ const el=document.getElementById('admin-tickets-list');if(!el)return;
1338
+ const tickets=Object.values(DB.tickets||{}).sort((a,b)=>b.ts-a.ts);
1339
+ if(!tickets.length){el.innerHTML='<div style="color:var(--muted);text-align:center;padding:20px;font-size:.85rem">Keine Tickets</div>';return;}
1340
+ el.innerHTML=renderTicketList(tickets);
1341
+ }
1342
+ function toggleST(id){const el=document.getElementById('toggle-'+id);if(!el)return;const on=!el.classList.contains('on');el.classList.toggle('on',on);_st[id]=on;}
1343
+ function switchSettingsTab(tab,btn){
1344
+ document.querySelectorAll('[id^="settings-tab-"]').forEach(el=>el.style.display='none');
1345
+ document.querySelectorAll('.modal-tab').forEach(el=>el.classList.remove('active'));
1346
+ const el=document.getElementById('settings-tab-'+tab);if(el)el.style.display='';
1347
+ if(btn)btn.classList.add('active');
1348
+ if(tab==='admin')loadAdminTickets();
1349
+ }
1350
+ function addBW(){const i=document.getElementById('new-bw');const w=i.value.trim().toLowerCase();if(!w)return;if(!appConfig.automod)appConfig.automod={};if(!appConfig.automod.bannedWords)appConfig.automod.bannedWords=[];if(!appConfig.automod.bannedWords.includes(w)){appConfig.automod.bannedWords.push(w);document.getElementById('bw-tags').insertAdjacentHTML('beforeend',`<span class="tag">${escHtml(w)}<button class="tag-remove" onclick="removeBW('${escHtml(w)}')">×</button></span>`);}i.value='';}
1351
+ function removeBW(w){if(!appConfig.automod?.bannedWords)return;appConfig.automod.bannedWords=appConfig.automod.bannedWords.filter(x=>x!==w);const el=document.getElementById('bw-tags');if(el)el.innerHTML=appConfig.automod.bannedWords.map(x=>`<span class="tag">${escHtml(x)}<button class="tag-remove" onclick="removeBW('${escHtml(x)}')">×</button></span>`).join('');}
1352
+ function setAvatarColor(c){currentUser.color=c;DB.users[currentUser.username.toLowerCase()].color=c;apiSave();updateTopbar();}
1353
+ function saveSettings(){
1354
+ const me=DB.users[currentUser.username.toLowerCase()];if(!me)return clearModal();
1355
+ const newU=document.getElementById('s-user')?.value.trim();
1356
+ if(newU&&newU!==currentUser.username){
1357
+ if(newU.length<2||newU.length>20){showToast('Username: 2-20 Zeichen','var(--danger)');return;}
1358
+ if(!/^[a-zA-Z0-9_]+$/.test(newU)){showToast('Nur Buchstaben, Zahlen, _','var(--danger)');return;}
1359
+ if(DB.users[newU.toLowerCase()]&&newU.toLowerCase()!==currentUser.username.toLowerCase()){showToast('Username bereits vergeben','var(--danger)');return;}
1360
+ delete DB.users[currentUser.username.toLowerCase()];
1361
+ me.username=newU;
1362
+ DB.users[newU.toLowerCase()]=me;
1363
+ currentUser.username=newU;
1364
+ }
1365
+ const np=document.getElementById('s-pass')?.value,np2=document.getElementById('s-pass2')?.value;
1366
+ if(np){if(np.length<4){showToast('Passwort mind. 4 Zeichen','var(--danger)');return;}if(np!==np2){showToast('Passwörter stimmen nicht überein','var(--danger)');return;}me.password=encode(np);}
1367
+ if(!me.settings)me.settings={};
1368
+ if('notif' in _st)me.settings.notif=_st.notif;
1369
+ if(hasRole('mod')&&appConfig.automod){
1370
+ const ml=document.getElementById('s-maxlen'),sp=document.getElementById('s-spam');
1371
+ if(ml)appConfig.automod.maxMsgLength=parseInt(ml.value)||800;
1372
+ if(sp)appConfig.automod.spamThreshold=parseInt(sp.value)||5;
1373
+ if('am' in _st)appConfig.automod.enabled=_st.am;
1374
+ if('caps' in _st)appConfig.automod.capsFilter=_st.caps;
1375
+ if('links' in _st)appConfig.automod.linkFilter=_st.links;
1376
+ DB.config.automod=appConfig.automod;
1377
+ }
1378
+ DB.users[me.username.toLowerCase()]=me;
1379
+ apiSave();
1380
+ currentUser={...me};
1381
+ updateTopbar();clearModal();
1382
+ showToast('✓ Einstellungen gespeichert','var(--green)');
1383
+ }
1384
+
1385
+ // ─── TICKETS ──────────────────────────────────────────────────
1386
+ function openCreateTicket(){
1387
+ if (!currentUser) return;
1388
+ showModal(`
1389
+ <div class="modal-title">🎫 Ticket erstellen</div>
1390
+ <div class="modal-sub">Das Team wird sich so schnell wie möglich melden.</div>
1391
+ <div class="modal-field">
1392
+ <label>Kategorie</label>
1393
+ <select id="t-cat">
1394
+ <option value="support">❓ Support</option>
1395
+ <option value="report">🚨 Meldung</option>
1396
+ <option value="appeal">⚖️ Ban-Appeal</option>
1397
+ <option value="bug">🐛 Bug-Report</option>
1398
+ <option value="other">💭 Sonstiges</option>
1399
+ </select>
1400
+ </div>
1401
+ <div class="modal-field"><label>Betreff</label><input type="text" id="t-title" maxlength="80" placeholder="Kurze Beschreibung"></div>
1402
+ <div class="modal-field"><label>Beschreibung</label><textarea id="t-desc" rows="4" placeholder="Beschreibe dein Anliegen genau..."></textarea></div>
1403
+ <div class="modal-btns">
1404
+ <button class="modal-btn secondary" onclick="clearModal()">Abbrechen</button>
1405
+ <button class="modal-btn primary" onclick="submitTicket()">Ticket erstellen ▶</button>
1406
+ </div>`, true);
1407
+ }
1408
+
1409
+ function submitTicket(){
1410
+ const cat=document.getElementById('t-cat')?.value;
1411
+ const title=document.getElementById('t-title')?.value.trim();
1412
+ const desc=document.getElementById('t-desc')?.value.trim();
1413
+ if(!title||!desc){showToast('Bitte alle Felder ausfüllen','var(--danger)');return;}
1414
+ if(!DB.tickets)DB.tickets={};
1415
+ const tktNum = Object.keys(DB.tickets).length + 1;
1416
+ const id='TKT-'+String(tktNum).padStart(4,'0');
1417
+ dbPush('tickets',{
1418
+ id, cat, title, desc,
1419
+ author: currentUser.username,
1420
+ status: 'open',
1421
+ ts: Date.now(),
1422
+ replies: []
1423
+ });
1424
+ clearModal();
1425
+ showToast(`✅ Ticket ${id} erstellt! Das Team meldet sich.`,'var(--green)');
1426
+ // Mod-Notification
1427
+ sendSystemMsg(`📬 Neues Ticket von @${currentUser.username}: "${title}" (${id})`, 'moderators');
1428
+ }
1429
+
1430
+ function openMyTickets(){
1431
+ const myTickets = Object.values(DB.tickets||{})
1432
+ .filter(t=>t.author===currentUser.username||hasRole('mod'))
1433
+ .sort((a,b)=>b.ts-a.ts);
1434
+
1435
+ showModal(`
1436
+ <div class="modal-title">🎫 ${hasRole('mod')?'Alle Tickets':'Meine Tickets'}</div>
1437
+ <div style="display:flex;gap:8px;margin-bottom:12px">
1438
+ <button class="modal-btn secondary" style="flex:1;padding:5px" onclick="filterTickets('all',this)">Alle</button>
1439
+ <button class="modal-btn secondary" style="flex:1;padding:5px" onclick="filterTickets('open',this)">Offen</button>
1440
+ <button class="modal-btn secondary" style="flex:1;padding:5px" onclick="filterTickets('closed',this)">Geschlossen</button>
1441
+ </div>
1442
+ <div id="ticket-list-container" style="max-height:380px;overflow-y:auto">
1443
+ ${renderTicketList(myTickets)}
1444
+ </div>
1445
+ <div class="modal-btns">
1446
+ <button class="modal-btn secondary" onclick="clearModal()">Schließen</button>
1447
+ <button class="modal-btn primary" onclick="clearModal();openCreateTicket()">+ Neues Ticket</button>
1448
+ </div>`, true);
1449
+ }
1450
+
1451
+ function renderTicketList(tickets){
1452
+ if(!tickets.length) return '<div style="color:var(--muted);text-align:center;padding:24px;font-size:.85rem">Keine Tickets</div>';
1453
+ const catIcon={support:'❓',report:'🚨',appeal:'⚖️',bug:'🐛',other:'💭'};
1454
+ return tickets.map(t=>`
1455
+ <div class="ticket-item ${t.status}" onclick="openTicketDetail('${t._key||t.id}')" style="cursor:pointer;padding:10px 12px;border:1px solid var(--border);border-radius:4px;margin-bottom:8px;background:var(--surface2);transition:border-color .2s" onmouseover="this.style.borderColor='var(--accent)'" onmouseout="this.style.borderColor='var(--border)'">
1456
+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px">
1457
+ <span style="font-family:Orbitron,monospace;font-size:.65rem;color:var(--accent)">${t.id}</span>
1458
+ <span style="font-size:.65rem;padding:2px 7px;border-radius:2px;background:${t.status==='open'?'rgba(78,255,145,0.15)':'rgba(74,122,153,0.2)'};color:${t.status==='open'?'var(--green)':'var(--muted)'}">● ${t.status==='open'?'OFFEN':'GESCHLOSSEN'}</span>
1459
+ </div>
1460
+ <div style="font-size:.9rem;font-weight:700;margin-bottom:2px">${catIcon[t.cat]||'💭'} ${escHtml(t.title)}</div>
1461
+ <div style="font-size:.72rem;color:var(--muted)">${t.author} · ${new Date(t.ts).toLocaleDateString('de-DE')} · ${(t.replies||[]).length} Antwort${(t.replies||[]).length!==1?'en':''}</div>
1462
+ </div>`).join('');
1463
+ }
1464
+
1465
+ function filterTickets(filter, btn){
1466
+ document.querySelectorAll('#active-modal .modal-btn.secondary').forEach(b=>b.classList.remove('active'));
1467
+ btn?.classList.add('active');
1468
+ const all = Object.values(DB.tickets||{})
1469
+ .filter(t=>t.author===currentUser.username||hasRole('mod'))
1470
+ .filter(t=>filter==='all'||t.status===filter)
1471
+ .sort((a,b)=>b.ts-a.ts);
1472
+ const container = document.getElementById('ticket-list-container');
1473
+ if(container) container.innerHTML = renderTicketList(all);
1474
+ }
1475
+
1476
+ function openTicketDetail(key){
1477
+ // Key kann entweder _key oder id sein
1478
+ const t = DB.tickets[key] || Object.values(DB.tickets||{}).find(x=>x.id===key);
1479
+ if(!t) return showToast('Ticket nicht gefunden','var(--danger)');
1480
+ const realKey = t._key || key;
1481
+ const catIcon={support:'❓',report:'🚨',appeal:'⚖️',bug:'🐛',other:'💭'};
1482
+ const replies = (t.replies||[]).map(r=>`
1483
+ <div style="padding:10px;border-left:2px solid ${r.isStaff?'var(--accent)':'var(--border)'};margin:8px 0;background:rgba(0,0,0,0.2);border-radius:0 4px 4px 0">
1484
+ <div style="font-size:.68rem;color:${r.isStaff?'var(--accent)':'var(--muted)'};font-family:Orbitron,monospace;margin-bottom:4px">
1485
+ ${r.isStaff?'🛡 ':''}${escHtml(r.author)} · ${new Date(r.ts).toLocaleString('de-DE',{day:'2-digit',month:'2-digit',hour:'2-digit',minute:'2-digit'})}
1486
+ </div>
1487
+ <div style="font-size:.88rem">${escHtml(r.text)}</div>
1488
+ </div>`).join('');
1489
+
1490
+ const canReply = t.author===currentUser.username || hasRole('mod');
1491
+ const canClose = hasRole('mod') || t.author===currentUser.username;
1492
+
1493
+ showModal(`
1494
+ <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:12px">
1495
+ <div>
1496
+ <div class="modal-title" style="margin-bottom:2px">${catIcon[t.cat]||'💭'} ${escHtml(t.title)}</div>
1497
+ <div style="font-family:Orbitron,monospace;font-size:.62rem;color:var(--accent)">${t.id} · ${t.author} · ${new Date(t.ts).toLocaleDateString('de-DE')}</div>
1498
+ </div>
1499
+ <span style="font-size:.65rem;padding:3px 8px;border-radius:2px;white-space:nowrap;background:${t.status==='open'?'rgba(78,255,145,0.15)':'rgba(74,122,153,0.2)'};color:${t.status==='open'?'var(--green)':'var(--muted)'}">● ${t.status==='open'?'OFFEN':'GESCHLOSSEN'}</span>
1500
+ </div>
1501
+ <div style="background:rgba(0,0,0,0.3);padding:12px;border:1px solid var(--border);font-size:.9rem;margin-bottom:12px;border-radius:4px;line-height:1.5">${escHtml(t.desc)}</div>
1502
+ ${replies?`<div style="max-height:200px;overflow-y:auto;margin-bottom:12px">${replies}</div>`:''}
1503
+ ${canReply&&t.status==='open'?`
1504
+ <div class="modal-field" style="margin-bottom:8px">
1505
+ <textarea id="ticket-reply" rows="2" placeholder="Antwort schreiben..." style="font-size:.88rem"></textarea>
1506
+ </div>`:''}
1507
+ <div class="modal-btns">
1508
+ <button class="modal-btn secondary" onclick="clearModal()">Schließen</button>
1509
+ ${canReply&&t.status==='open'?`<button class="modal-btn primary" onclick="replyTicket('${realKey}')">Antworten</button>`:''}
1510
+ ${canClose?`<button class="modal-btn ${t.status==='open'?'warn-btn':'success-btn'}" onclick="toggleTicket('${realKey}')">${t.status==='open'?'Schließen':'Wieder öffnen'}</button>`:''}
1511
+ </div>`, true);
1512
+ }
1513
+
1514
+ function replyTicket(key){
1515
+ const t=DB.tickets[key];if(!t)return;
1516
+ const text=document.getElementById('ticket-reply')?.value.trim();
1517
+ if(!text){showToast('Antwort darf nicht leer sein','var(--danger)');return;}
1518
+ if(!t.replies)t.replies=[];
1519
+ t.replies.push({
1520
+ author: currentUser.username,
1521
+ text,
1522
+ ts: Date.now(),
1523
+ isStaff: hasRole('mod')
1524
+ });
1525
+ apiSave();
1526
+ clearModal();
1527
+ showToast('✅ Antwort gesendet','var(--green)');
1528
+ // Notification an Ticket-Ersteller
1529
+ if(t.author!==currentUser.username){
1530
+ sendSystemMsg(`📬 Neue Antwort auf Ticket ${t.id} von @${currentUser.username}`, 'moderators');
1531
+ }
1532
+ }
1533
+
1534
+ function toggleTicket(key){
1535
+ const t=DB.tickets[key];if(!t)return;
1536
+ t.status=t.status==='open'?'closed':'open';
1537
+ apiSave();clearModal();
1538
+ showToast(`Ticket ${t.id} ${t.status==='open'?'geöffnet':'geschlossen'}`,'var(--accent)');
1539
+ }
1540
+
1541
+ function sendSystemMsg(text, channelId){
1542
+ if(!DB.msgs) DB.msgs={};
1543
+ if(!DB.msgs[channelId]) DB.msgs[channelId]={};
1544
+ dbPush(`msgs/${channelId}`,{system:true,text,ts:Date.now()});
1545
+ }
1546
+
1547
+ // Ticket-Button auch für normale User sichtbar machen (meine Tickets)
1548
+ function openTicketMenu(){
1549
+ if(hasRole('mod')) return openMyTickets();
1550
+ openMyTickets();
1551
+ }
1552
+
1553
+ // ─── SEARCH & PINS ────────────────────────────────────────────
1554
+ async function openSearchModal(){
1555
+ showModal(`<div class="modal-title">🔍 Nachrichten durchsuchen</div>
1556
+ <div class="modal-field"><label>Suchbegriff</label>
1557
+ <input type="text" id="search-q" placeholder="Suche im aktuellen Channel..." oninput="liveSearch(this.value)">
1558
+ </div>
1559
+ <div id="search-results" style="max-height:300px;overflow-y:auto;margin-top:10px"></div>
1560
+ <div class="modal-btns"><button class="modal-btn secondary" onclick="clearModal()">Schließen</button></div>`);
1561
+ }
1562
+ function liveSearch(query){
1563
+ const res=document.getElementById('search-results');
1564
+ if(!query||query.length<2){res.innerHTML='';return;}
1565
+ const msgs=getMsgs(currentChannel).filter(m=>!m.system&&m.text?.toLowerCase().includes(query.toLowerCase()));
1566
+ if(!msgs.length){res.innerHTML='<div style="color:var(--muted);text-align:center;padding:12px;font-size:.85rem">Keine Ergebnisse</div>';return;}
1567
+ res.innerHTML=msgs.slice(-20).map(m=>`<div style="padding:8px 0;border-bottom:1px solid var(--border)">
1568
+ <div style="font-size:.72rem;color:var(--muted);font-family:Orbitron,monospace">${m.author} · ${new Date(m.ts).toLocaleDateString('de-DE')}</div>
1569
+ <div style="font-size:.9rem;color:var(--text)">${escHtml(m.text).replace(new RegExp(escHtml(query),'gi'),s=>`<mark style="background:rgba(0,212,255,0.2);color:var(--accent)">${s}</mark>`)}</div>
1570
+ </div>`).join('');
1571
+ }
1572
+ async function openPinsModal(){
1573
+ const pins=Array.isArray(DB.pins)?DB.pins.filter(p=>p.channel===currentChannel):[];
1574
+ showModal(`<div class="modal-title">📌 Angepinnte Nachrichten</div>
1575
+ <div style="max-height:350px;overflow-y:auto">
1576
+ ${!pins.length?'<div style="color:var(--muted);text-align:center;padding:20px;font-size:.85rem">Keine angepinnten Nachrichten</div>':
1577
+ pins.map(p=>`<div style="padding:10px 0;border-bottom:1px solid var(--border)">
1578
+ <div style="font-size:.7rem;color:var(--muted);font-family:Orbitron,monospace">📌 ${p.author} · angeheftet von ${p.by}</div>
1579
+ <div style="font-size:.9rem;color:var(--text);margin-top:4px">${escHtml(p.text)}</div>
1580
+ </div>`).join('')}
1581
+ </div>
1582
+ <div class="modal-btns"><button class="modal-btn secondary" onclick="clearModal()">Schließen</button></div>`);
1583
+ }
1584
+
1585
+ // ─── SPAM CAPTCHA ─────────────────────────────────────────────
1586
+ function showSpamCaptchaModal(){
1587
+ const d=genCaptcha();captchaData.spam=d;
1588
+ showModal(`<div class="modal-title">🤖 Anti-Spam Prüfung</div>
1589
+ <div class="modal-sub">Du schreibst zu schnell. Löse das Captcha.</div>
1590
+ <div class="captcha-modal-question" id="spam-q">${d.q}</div>
1591
+ <div class="modal-field"><label>Antwort</label><input type="number" id="spam-a" placeholder="?" onkeydown="if(event.key==='Enter')spamSubmit()"></div>
1592
+ <div class="auth-error" id="spam-err"></div>
1593
+ <div class="modal-btns">
1594
+ <button class="modal-btn secondary" onclick="clearModal()">Abbrechen</button>
1595
+ <button class="modal-btn primary" onclick="spamSubmit()">Bestätigen</button>
1596
+ </div>`);
1597
+ }
1598
+ async function spamSubmit(){
1599
+ const ans=parseInt(document.getElementById('spam-a')?.value);
1600
+ if(ans!==captchaData.spam?.ans){
1601
+ const d=genCaptcha();captchaData.spam=d;
1602
+ const q=document.getElementById('spam-q');if(q)q.textContent=d.q;
1603
+ const e=document.getElementById('spam-err');if(e)e.textContent='❌ Falsche Antwort!';
1604
+ return;
1605
+ }
1606
+ clearModal();spamTs=[];
1607
+ if(pendingSpamMsg){await sendMessage();pendingSpamMsg=null;}
1608
+ }
1609
+
1610
+ // ─── MODAL SYSTEM ─────────────────────────────────────────────
1611
+ function showModal(html,wide=false){
1612
+ clearModal();
1613
+ const o=document.createElement('div');
1614
+ o.className='modal-overlay';o.id='active-modal';
1615
+ o.innerHTML=`<div class="modal${wide?' wide':''}">${html}</div>`;
1616
+ o.onclick=e=>{if(e.target===o)clearModal();};
1617
+ document.getElementById('modal-container').appendChild(o);
1618
+ }
1619
+ function clearModal(){document.getElementById('active-modal')?.remove();}
1620
+ function showKickedModal(){
1621
+ showModal(`<div class="modal-title">👢 Du wurdest gekickt</div>
1622
+ <div class="modal-sub">Ein Moderator hat dich aus dem Chat entfernt.</div>
1623
+ <div class="modal-btns"><button class="modal-btn primary" onclick="doLogout();clearModal()">Zum Login</button></div>`);
1624
+ }
1625
+
1626
+ // ─── EMOJI REACTIONS (NEW) ────────────────────────────────────
1627
+ function addReaction(msgKey, emoji, isDM=false) {
1628
+ const path = isDM ? `dms/${getDMKey(currentUser.username, currentDM)}/${msgKey}` : `msgs_${currentChannel}/${msgKey}`;
1629
+ const msgs = isDM ? getDMMsgs(getDMKey(currentUser.username, currentDM)) : getMsgs(currentChannel);
1630
+ const msg = msgs?.find(m => m._key === msgKey || m.id === msgKey);
1631
+ if (!msg) return;
1632
+
1633
+ if (!msg.reactions) msg.reactions = {};
1634
+ if (!msg.reactions[emoji]) msg.reactions[emoji] = [];
1635
+ if (!msg.reactions[emoji].includes(currentUser.username)) {
1636
+ msg.reactions[emoji].push(currentUser.username);
1637
+ }
1638
+ apiSave();
1639
+ if (isDM) renderDMMessages(currentDM);
1640
+ else renderChannelMessages(currentChannel);
1641
+ }
1642
+
1643
+ function removeReaction(msgKey, emoji, isDM=false) {
1644
+ const msgs = isDM ? getDMMsgs(getDMKey(currentUser.username, currentDM)) : getMsgs(currentChannel);
1645
+ const msg = msgs?.find(m => m._key === msgKey || m.id === msgKey);
1646
+ if (!msg || !msg.reactions?.[emoji]) return;
1647
+ msg.reactions[emoji] = msg.reactions[emoji].filter(u => u !== currentUser.username);
1648
+ if (!msg.reactions[emoji].length) delete msg.reactions[emoji];
1649
+ apiSave();
1650
+ if (isDM) renderDMMessages(currentDM);
1651
+ else renderChannelMessages(currentChannel);
1652
+ }
1653
+
1654
+ function showReactionPicker(msgKey, isDM=false) {
1655
+ const x = event.clientX, y = event.clientY;
1656
+ const picker = document.createElement('div');
1657
+ picker.className = 'emoji-picker';
1658
+ picker.style.left = x + 'px';
1659
+ picker.style.top = y + 'px';
1660
+ picker.innerHTML = QUICK_EMOJIS.map(em =>
1661
+ `<button class="emoji-btn" onclick="addReaction('${msgKey}','${em}',${isDM});this.parentElement.remove()">${em}</button>`
1662
+ ).join('');
1663
+ document.body.appendChild(picker);
1664
+ setTimeout(() => picker.remove(), 5000);
1665
+ }
1666
+
1667
+ // ─── MESSAGE EDITING (NEW) ────────────────────────────────────
1668
+ function editMessage(msgKey, isDM=false) {
1669
+ const msgs = isDM ? getDMMsgs(getDMKey(currentUser.username, currentDM)) : getMsgs(currentChannel);
1670
+ const msg = msgs?.find(m => m._key === msgKey || m.id === msgKey);
1671
+ if (!msg || msg.author !== currentUser.username) return showToast('Nur eigene Nachrichten editierbar','var(--danger)');
1672
+
1673
+ showModal(`
1674
+ <div class="modal-title">✏️ Nachricht bearbeiten</div>
1675
+ <div class="modal-field">
1676
+ <textarea id="edit-text" rows="3">${escHtml(msg.text)}</textarea>
1677
+ </div>
1678
+ <div class="modal-btns">
1679
+ <button class="modal-btn secondary" onclick="clearModal()">Abbrechen</button>
1680
+ <button class="modal-btn primary" onclick="submitEdit('${msgKey}',${isDM})">Speichern</button>
1681
+ </div>`);
1682
+ }
1683
+
1684
+ function submitEdit(msgKey, isDM=false) {
1685
+ const newText = document.getElementById('edit-text')?.value.trim();
1686
+ if (!newText) { showToast('Nachricht kann nicht leer sein','var(--danger)'); return; }
1687
+
1688
+ const msgs = isDM ? getDMMsgs(getDMKey(currentUser.username, currentDM)) : getMsgs(currentChannel);
1689
+ const msg = msgs?.find(m => m._key === msgKey || m.id === msgKey);
1690
+ if (!msg) return;
1691
+
1692
+ msg.text = newText;
1693
+ msg.edited = Date.now();
1694
+ apiSave();
1695
+ clearModal();
1696
+ showToast('✓ Nachricht bearbeitet','var(--green)');
1697
+ if (isDM) renderDMMessages(currentDM);
1698
+ else renderChannelMessages(currentChannel);
1699
+ }
1700
+
1701
+ // ─── USER STATISTICS (NEW) ────────────────────────────────────
1702
+ function getUserStats(username) {
1703
+ let msgCount = 0, lastMsg = 0, totalWords = 0;
1704
+
1705
+ for (const [chId, msgs] of Object.entries(DB.msgs || {})) {
1706
+ if (Array.isArray(msgs)) {
1707
+ msgs.forEach(m => {
1708
+ if (m.author === username) {
1709
+ msgCount++;
1710
+ lastMsg = Math.max(lastMsg, m.ts || 0);
1711
+ totalWords += (m.text || '').split(/\s+/).length;
1712
+ }
1713
+ });
1714
+ }
1715
+ }
1716
+
1717
+ return { msgCount, lastMsg, totalWords, avgWords: msgCount > 0 ? Math.round(totalWords / msgCount) : 0 };
1718
+ }
1719
+
1720
+ function showUserStats() {
1721
+ const stats = getUserStats(currentUser.username);
1722
+ const joined = new Date(currentUser.joined || Date.now());
1723
+ const daysActive = Math.floor((Date.now() - currentUser.joined) / 86400000);
1724
+
1725
+ showModal(`
1726
+ <div class="modal-title">📊 Meine Statistiken</div>
1727
+ <div style="background:rgba(0,200,255,0.1);padding:14px;border-radius:4px;margin:12px 0">
1728
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;text-align:center">
1729
+ <div>
1730
+ <div style="font-size:.7rem;color:var(--muted);margin-bottom:4px">NACHRICHTEN</div>
1731
+ <div style="font-size:1.4rem;font-weight:700">${stats.msgCount}</div>
1732
+ </div>
1733
+ <div>
1734
+ <div style="font-size:.7rem;color:var(--muted);margin-bottom:4px">AVG WÖRTER</div>
1735
+ <div style="font-size:1.4rem;font-weight:700">${stats.avgWords}</div>
1736
+ </div>
1737
+ <div>
1738
+ <div style="font-size:.7rem;color:var(--muted);margin-bottom:4px">TAGE AKTIV</div>
1739
+ <div style="font-size:1.4rem;font-weight:700">${daysActive}</div>
1740
+ </div>
1741
+ <div>
1742
+ <div style="font-size:.7rem;color:var(--muted);margin-bottom:4px">BEIGETRETEN</div>
1743
+ <div style="font-size:.9rem">${joined.toLocaleDateString('de-DE')}</div>
1744
+ </div>
1745
+ </div>
1746
+ </div>
1747
+ <div class="modal-btns">
1748
+ <button class="modal-btn secondary" onclick="clearModal()">Schließen</button>
1749
+ </div>`);
1750
+ }
1751
+
1752
+ // ─── ADVANCED SEARCH (NEW) ────────────────────────────────────
1753
+ function openAdvancedSearch() {
1754
+ showModal(`
1755
+ <div class="modal-title">🔍 Erweiterte Suche</div>
1756
+ <div class="modal-field">
1757
+ <label>Suchtext</label>
1758
+ <input type="text" id="adv-search-text" placeholder="Suche...">
1759
+ </div>
1760
+ <div class="modal-field">
1761
+ <label>Von Benutzer</label>
1762
+ <input type="text" id="adv-search-author" placeholder="Optional">
1763
+ </div>
1764
+ <div class="modal-field">
1765
+ <label>Zeitraum</label>
1766
+ <select id="adv-search-time">
1767
+ <option value="">Alle</option>
1768
+ <option value="3600000">Letzte Stunde</option>
1769
+ <option value="86400000">Letzte 24h</option>
1770
+ <option value="604800000">Letzte Woche</option>
1771
+ </select>
1772
+ </div>
1773
+ <div id="adv-search-results" style="max-height:250px;overflow-y:auto;margin:12px 0"></div>
1774
+ <div class="modal-btns">
1775
+ <button class="modal-btn secondary" onclick="clearModal()">Schließen</button>
1776
+ <button class="modal-btn primary" onclick="doAdvancedSearch()">Suchen</button>
1777
+ </div>`, true);
1778
+ }
1779
+
1780
+ function doAdvancedSearch() {
1781
+ const text = document.getElementById('adv-search-text')?.value.toLowerCase() || '';
1782
+ const author = document.getElementById('adv-search-author')?.value.toLowerCase() || '';
1783
+ const timespan = parseInt(document.getElementById('adv-search-time')?.value) || 0;
1784
+ const now = Date.now();
1785
+
1786
+ let results = [];
1787
+ const msgs = getMsgs(currentChannel) || [];
1788
+
1789
+ msgs.forEach(m => {
1790
+ if (m.system) return;
1791
+ const textMatch = !text || (m.text || '').toLowerCase().includes(text);
1792
+ const authorMatch = !author || (m.author || '').toLowerCase().includes(author);
1793
+ const timeMatch = !timespan || (now - (m.ts || 0)) <= timespan;
1794
+
1795
+ if (textMatch && authorMatch && timeMatch) results.push(m);
1796
+ });
1797
+
1798
+ const resultsEl = document.getElementById('adv-search-results');
1799
+ if (!results.length) {
1800
+ resultsEl.innerHTML = '<div style="color:var(--muted);text-align:center;padding:20px">Keine Ergebnisse</div>';
1801
+ } else {
1802
+ resultsEl.innerHTML = results.slice(-50).map(m => `
1803
+ <div style="padding:8px 0;border-bottom:1px solid var(--border)">
1804
+ <div style="font-size:.7rem;color:var(--muted);font-family:Orbitron,monospace">${m.author} · ${new Date(m.ts).toLocaleString('de-DE')}</div>
1805
+ <div style="font-size:.9rem;color:var(--text)">${escHtml(m.text)}</div>
1806
+ </div>
1807
+ `).join('');
1808
+ }
1809
+ }
1810
+
1811
+ // ─── HELPERS ──────────────────────────────────────────────────
1812
+ function encode(s){try{return btoa(unescape(encodeURIComponent(s)));}catch{return btoa(s);}}
1813
+ function decode(s){try{return decodeURIComponent(escape(atob(s)));}catch{try{return atob(s);}catch{return '';}}}
1814
+ function escHtml(str){return String(str||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#x27;');}
1815
+ function showBanned(){document.getElementById('banned-screen').style.display='flex';document.getElementById('auth-screen').style.display='none';document.getElementById('app').classList.remove('visible');}
1816
+ function showAuthSuccess(msg){const el=document.getElementById('auth-error');el.style.color='var(--green)';el.textContent=msg;setTimeout(()=>{el.style.color='';el.textContent='';},3000);}
1817
+ function showToast(msg,color='var(--accent)'){const t=document.createElement('div');t.className='toast';t.style.borderColor=color;t.style.color=color;t.textContent=msg;document.body.appendChild(t);setTimeout(()=>t.remove(),3000);}
1818
+
1819
+
1820
+
1821
+ // ─── APP INIT ─────────────────────────────────────────────────
1822
+ window.addEventListener('DOMContentLoaded', async () => {
1823
+ // Auth-Screen anzeigen, App & Banned-Screen verstecken
1824
+ document.getElementById('auth-screen').style.display = 'flex';
1825
+ document.getElementById('app').classList.remove('visible');
1826
+ document.getElementById('banned-screen').style.display = 'none';
1827
+
1828
+ // Loading-Overlay anzeigen
1829
+ const loadEl = document.createElement('div');
1830
+ loadEl.id = 'init-loading';
1831
+ loadEl.style.cssText = 'position:fixed;inset:0;background:var(--bg,#0a0e14);display:flex;align-items:center;justify-content:center;z-index:99999;flex-direction:column;gap:12px;font-family:Orbitron,monospace;';
1832
+ loadEl.innerHTML = '<div style="font-size:1.4rem;color:#00d4ff;letter-spacing:.2em">NoahsChat</div><div style="font-size:.7rem;color:#4a5568;letter-spacing:.15em">VERBINDE...</div>';
1833
+ document.body.appendChild(loadEl);
1834
+
1835
+ // DB laden
1836
+ await apiLoad();
1837
+
1838
+ // Owner-Account anlegen falls noch nicht vorhanden
1839
+ if (!DB.users[OWNER_NAME.toLowerCase()]) {
1840
+ DB.users[OWNER_NAME.toLowerCase()] = {
1841
+ username: OWNER_NAME,
1842
+ password: encode(OWNER_PASS),
1843
+ color: 0,
1844
+ role: 'owner',
1845
+ joined: Date.now(),
1846
+ settings: { lang: 'de', translate: false, notif: true }
1847
+ };
1848
+ apiSave();
1849
+ }
1850
+
1851
+ // Loading entfernen
1852
+ loadEl.remove();
1853
+
1854
+ // Session wiederherstellen (Auto-Login nach Reload)
1855
+ const session = loadSession();
1856
+ if (session) {
1857
+ const entry = DB.users[session.username.toLowerCase()];
1858
+ if (entry && !DB.moderation?.bans?.[session.username.toLowerCase()] && !DB.moderation?.banned_fps?.[MY_FP]) {
1859
+ currentUser = { ...entry };
1860
+ userLanguage = entry.settings?.lang || 'de';
1861
+ translationEnabled = entry.settings?.translate || false;
1862
+ saveSession(currentUser); // Timestamp erneuern
1863
+ launchApp();
1864
+ return; // Auth-Screen nicht zeigen
1865
+ } else {
1866
+ saveSession(null); // Ungültige Session löschen
1867
+ }
1868
+ }
1869
+
1870
+ // Captchas immer initialisieren (auch falls Session nicht klappt)
1871
+ refreshCaptcha('login');
1872
+ refreshCaptcha('reg');
1873
+ });