sldshr commited on
Commit
ebe2703
·
verified ·
1 Parent(s): 134848b

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +443 -1003
index.html CHANGED
@@ -2,7 +2,7 @@
2
  <html lang="en">
3
  <head>
4
  <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
  <title>SupaMessenger</title>
7
  <style>
8
  :root {
@@ -16,14 +16,10 @@
16
  --border: #45475a;
17
  --error: #f38ba8;
18
  --success: #a6e3a1;
 
19
  }
20
 
21
- * {
22
- box-sizing: border-box;
23
- margin: 0;
24
- padding: 0;
25
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
26
- }
27
 
28
  body {
29
  background-color: var(--bg-dark);
@@ -31,494 +27,113 @@
31
  height: 100vh;
32
  display: flex;
33
  overflow: hidden;
 
34
  }
35
 
36
  /* Utility Classes */
37
  .hidden { display: none !important; }
38
  .flex { display: flex; }
39
- .flex-col { flex-direction: column; }
40
  .items-center { align-items: center; }
41
  .justify-center { justify-content: center; }
42
- .w-full { width: 100%; }
43
- .h-full { height: 100%; }
44
 
45
  /* Custom Scrollbars */
46
- ::-webkit-scrollbar {
47
- width: 8px;
48
- height: 8px;
49
- }
50
-
51
- ::-webkit-scrollbar-track {
52
- background: var(--bg-dark);
53
- }
54
-
55
- ::-webkit-scrollbar-thumb {
56
- background: var(--border);
57
- border-radius: 4px;
58
- }
59
-
60
- ::-webkit-scrollbar-thumb:hover {
61
- background: var(--accent);
62
- }
63
-
64
- /* Firefox Scrollbars */
65
- * {
66
- scrollbar-width: thin;
67
- scrollbar-color: var(--border) var(--bg-dark);
68
- }
69
-
70
- /* Language Toggle Button */
71
- .lang-btn {
72
- position: fixed;
73
- top: 1rem;
74
- right: 1rem;
75
- width: auto;
76
- padding: 0.4rem 0.8rem;
77
- background-color: var(--bg-panel);
78
- color: var(--accent);
79
- border: 1px solid var(--border);
80
- border-radius: 20px;
81
- font-size: 0.85rem;
82
- font-weight: bold;
83
- cursor: pointer;
84
- z-index: 300;
85
- transition: all 0.2s ease;
86
- box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
87
- }
88
-
89
- .lang-btn:hover {
90
- background-color: var(--bg-hover);
91
- border-color: var(--accent);
92
- color: var(--accent-hover);
93
- }
94
-
95
- #login-screen {
96
- position: absolute;
97
- top: 0;
98
- left: 0;
99
- width: 100%;
100
- height: 100%;
101
- background-color: var(--bg-dark);
102
- z-index: 100;
103
- }
104
-
105
- .login-container {
106
- background-color: var(--bg-panel);
107
- padding: 2rem;
108
- border-radius: 8px;
109
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
110
- width: 100%;
111
- max-width: 400px;
112
- }
113
-
114
- .login-container h1 {
115
- text-align: center;
116
- margin-bottom: 1.5rem;
117
- color: var(--accent);
118
- }
119
-
120
- .input-group {
121
- margin-bottom: 1rem;
122
- }
123
-
124
- .input-group label {
125
- display: block;
126
- margin-bottom: 0.5rem;
127
- color: var(--text-secondary);
128
- font-size: 0.9rem;
129
- }
130
 
 
131
  input {
132
- width: 100%;
133
- padding: 0.75rem;
134
- border: 1px solid var(--border);
135
- border-radius: 4px;
136
- background-color: var(--bg-dark);
137
- color: var(--text-primary);
138
- outline: none;
139
- transition: border-color 0.2s;
140
  }
141
-
142
- input:focus {
143
- border-color: var(--accent);
144
- }
145
-
146
  button {
147
- width: 100%;
148
- padding: 0.75rem;
149
- border: none;
150
- border-radius: 4px;
151
- background-color: var(--accent);
152
- color: var(--bg-dark);
153
- font-weight: bold;
154
- cursor: pointer;
155
- transition: background-color 0.2s;
156
- }
157
-
158
- button:hover {
159
- background-color: var(--accent-hover);
160
- }
161
-
162
- .error-message {
163
- color: var(--error);
164
- font-size: 0.85rem;
165
- margin-top: 0.5rem;
166
- text-align: center;
167
- min-height: 1.2em;
168
- }
169
-
170
- .start-server-btn {
171
- background-color: transparent;
172
- color: var(--text-secondary);
173
- border: 1px solid var(--border);
174
- margin-top: 1rem;
175
- }
176
-
177
- .start-server-btn:hover {
178
- background-color: var(--bg-hover);
179
- color: var(--text-primary);
180
- }
181
-
182
- .settings-btn {
183
- background: none;
184
- border: none;
185
- color: var(--text-secondary);
186
- font-size: 0.85rem;
187
- cursor: pointer;
188
- margin-top: 0.8rem;
189
- text-decoration: underline;
190
- width: 100%;
191
- text-align: center;
192
- }
193
-
194
- .settings-btn:hover {
195
- color: var(--accent);
196
- }
197
-
198
- #setup-modal, #settings-modal {
199
- position: fixed;
200
- top: 0;
201
- left: 0;
202
- width: 100%;
203
- height: 100%;
204
- background-color: rgba(0, 0, 0, 0.7);
205
- display: flex;
206
- align-items: center;
207
- justify-content: center;
208
- z-index: 200;
209
- }
210
-
211
- .modal-content {
212
- background-color: var(--bg-panel);
213
- padding: 2rem;
214
- border-radius: 8px;
215
- width: 90%;
216
- max-width: 600px;
217
- max-height: 90vh;
218
- overflow-y: auto;
219
- position: relative;
220
- }
221
-
222
- .close-modal {
223
- position: absolute;
224
- top: 1rem;
225
- right: 1rem;
226
- background: none;
227
- border: none;
228
- color: var(--text-secondary);
229
- font-size: 1.5rem;
230
- cursor: pointer;
231
- width: auto;
232
- padding: 0;
233
  }
 
 
234
 
235
- .close-modal:hover {
236
- color: var(--text-primary);
237
- background: none;
238
- }
239
-
240
- .code-block {
241
- background-color: var(--bg-dark);
242
- padding: 1rem;
243
- border-radius: 4px;
244
- overflow-x: auto;
245
- font-family: monospace;
246
- margin: 1rem 0;
247
- color: var(--text-primary);
248
- border: 1px solid var(--border);
249
- position: relative;
250
- }
251
-
252
- .copy-btn {
253
- position: absolute;
254
- top: 0.5rem;
255
- right: 0.5rem;
256
- width: auto;
257
- padding: 0.25rem 0.5rem;
258
- font-size: 0.8rem;
259
- background-color: var(--bg-panel);
260
- color: var(--text-primary);
261
- }
262
-
263
- #app-screen {
264
- display: flex;
265
- width: 100%;
266
- height: 100%;
267
- }
268
-
269
- /* Sidebar Styles */
270
- .sidebar {
271
- width: 250px;
272
- background-color: var(--bg-panel);
273
- border-right: 1px solid var(--border);
274
- display: flex;
275
- flex-direction: column;
276
- }
277
-
278
- .sidebar-header {
279
- padding: 1rem;
280
- border-bottom: 1px solid var(--border);
281
- font-weight: bold;
282
- color: var(--text-primary);
283
- }
284
-
285
- .channels-list {
286
- flex: 1;
287
- overflow-y: auto;
288
- padding: 0.5rem 0;
289
- }
290
-
291
- .channel-item {
292
- padding: 0.5rem 1rem;
293
- cursor: pointer;
294
- color: var(--text-secondary);
295
- display: flex;
296
- align-items: center;
297
- }
298
-
299
- .channel-item:before {
300
- content: '#';
301
- margin-right: 0.5rem;
302
- opacity: 0.5;
303
- }
304
-
305
- .channel-item:hover {
306
- background-color: var(--bg-hover);
307
- color: var(--text-primary);
308
- }
309
-
310
- .channel-item.active {
311
- background-color: var(--bg-hover);
312
- color: var(--text-primary);
313
- font-weight: bold;
314
- }
315
-
316
- .channel-header-row {
317
- display: flex;
318
- justify-content: space-between;
319
- align-items: center;
320
- padding: 1rem;
321
- border-bottom: 1px solid var(--border);
322
- }
323
-
324
- .add-channel-btn {
325
- background: none;
326
- border: none;
327
- color: var(--text-secondary);
328
- cursor: pointer;
329
- font-size: 1.2rem;
330
- display: flex;
331
- align-items: center;
332
- justify-content: center;
333
- width: 24px;
334
- height: 24px;
335
- border-radius: 4px;
336
- }
337
-
338
- .add-channel-btn:hover {
339
- color: var(--accent);
340
- background-color: var(--bg-hover);
341
- }
342
-
343
- .user-info {
344
- padding: 1rem;
345
- border-top: 1px solid var(--border);
346
- display: flex;
347
- justify-content: space-between;
348
- align-items: center;
349
- }
350
-
351
- .logout-btn {
352
- width: auto;
353
- padding: 0.25rem 0.5rem;
354
- font-size: 0.8rem;
355
- background-color: transparent;
356
- border: 1px solid var(--border);
357
- color: var(--text-secondary);
358
- }
359
-
360
- .logout-btn:hover {
361
- color: var(--error);
362
- border-color: var(--error);
363
- }
364
-
365
- /* Main Chat Area Styles */
366
- .chat-area {
367
- flex: 1;
368
- display: flex;
369
- flex-direction: column;
370
- background-color: var(--bg-dark);
371
- }
372
-
373
- .chat-header {
374
- padding: 1rem;
375
- border-bottom: 1px solid var(--border);
376
- display: flex;
377
- justify-content: space-between;
378
- align-items: center;
379
- }
380
-
381
- .messages-container {
382
- flex: 1;
383
- overflow-y: auto;
384
- padding: 1rem;
385
- display: flex;
386
- flex-direction: column;
387
- gap: 1rem;
388
- }
389
-
390
- .message {
391
- display: flex;
392
- flex-direction: column;
393
- }
394
-
395
- .message-header {
396
- display: flex;
397
- align-items: baseline;
398
- margin-bottom: 0.25rem;
399
- }
400
-
401
- .message-author {
402
- font-weight: bold;
403
- color: var(--accent);
404
- margin-right: 0.5rem;
405
- }
406
-
407
- .message-time {
408
- font-size: 0.75rem;
409
- color: var(--text-secondary);
410
- }
411
-
412
- .message-content {
413
- color: var(--text-primary);
414
- word-break: break-word;
415
- line-height: 1.4;
416
- }
417
-
418
- .message-content code {
419
- background-color: rgba(0,0,0,0.3);
420
- padding: 0.1rem 0.3rem;
421
- border-radius: 3px;
422
- font-family: monospace;
423
- font-size: 0.9em;
424
- color: var(--accent-hover);
425
- }
426
 
427
- .message-content pre {
428
- background-color: rgba(0,0,0,0.3);
429
- padding: 0.5rem;
430
- border-radius: 4px;
431
- overflow-x: auto;
432
- margin-top: 0.5rem;
433
- }
434
-
435
- .message-content pre code {
436
- background-color: transparent;
437
- padding: 0;
438
- color: var(--text-primary);
439
- }
440
-
441
- .avatar {
442
- width: 32px;
443
- height: 32px;
444
- border-radius: 50%;
445
- display: flex;
446
- align-items: center;
447
- justify-content: center;
448
- font-weight: bold;
449
- color: white;
450
- font-size: 0.85rem;
451
- margin-right: 0.75rem;
452
- flex-shrink: 0;
453
- text-shadow: 0 1px 2px rgba(0,0,0,0.5);
454
- }
455
-
456
- .member-avatar {
457
- width: 24px;
458
- height: 24px;
459
- font-size: 0.7rem;
460
- margin-right: 0;
461
- }
462
-
463
- .message-input-area {
464
- padding: 1rem;
465
- border-top: 1px solid var(--border);
466
- }
467
-
468
- .message-form {
469
- display: flex;
470
- gap: 0.5rem;
471
- }
472
-
473
- .message-form input {
474
- flex: 1;
475
- }
476
-
477
- .message-form button {
478
- width: auto;
479
- padding: 0 1.5rem;
480
- }
481
-
482
- /* Members List Styles */
483
- .members-list {
484
- width: 200px;
485
- background-color: var(--bg-panel);
486
- border-left: 1px solid var(--border);
487
- display: flex;
488
- flex-direction: column;
489
- }
490
-
491
- .members-header {
492
- padding: 1rem;
493
- border-bottom: 1px solid var(--border);
494
- font-weight: bold;
495
- font-size: 0.9rem;
496
- color: var(--text-secondary);
497
- text-transform: uppercase;
498
  }
499
 
500
- .members-container {
501
- flex: 1;
502
- overflow-y: auto;
503
- padding: 0.5rem 0;
504
- }
 
 
505
 
506
- .member-item {
507
- padding: 0.5rem 1rem;
508
- display: flex;
509
- align-items: center;
510
- gap: 0.5rem;
511
- }
512
 
513
- .status-dot {
514
- width: 8px;
515
- height: 8px;
516
- border-radius: 50%;
517
- background-color: var(--success);
518
- }
 
 
 
 
 
 
 
 
 
 
 
519
 
520
- .status-dot.offline {
521
- background-color: var(--text-secondary);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
522
  }
523
  </style>
524
  </head>
@@ -526,717 +141,542 @@
526
 
527
  <button id="lang-btn" class="lang-btn">🌐 RU</button>
528
 
529
- <div id="login-screen" class="flex items-center justify-center">
 
530
  <div class="login-container">
531
  <h1 data-i18n="appTitle">SupaMessenger</h1>
532
  <form id="login-form">
533
  <div class="input-group">
534
- <label for="cfg-project-url" data-i18n="labelProjectUrl">Project URL</label>
535
- <input type="url" id="cfg-project-url" placeholder="https://xyz.supabase.co" required>
536
  </div>
537
  <div class="input-group">
538
- <label for="cfg-api-key" data-i18n="labelApiKey">API Key (Anon Key)</label>
539
- <input type="password" id="cfg-api-key" placeholder="eyJh..." required>
540
  </div>
541
- <div style="height: 1px; background-color: var(--border); margin: 1.5rem 0;"></div>
542
  <div class="input-group">
543
- <label for="username" data-i18n="labelUsername">Username</label>
544
- <input type="text" id="username" data-i18n-ph="phUsername" placeholder="Enter your username" required>
545
  </div>
546
  <div class="input-group">
547
- <label for="password" data-i18n="labelPassword">Password</label>
548
- <input type="password" id="password" data-i18n-ph="phPassword" placeholder="Enter your password" required>
549
  </div>
550
  <div id="login-error" class="error-message"></div>
551
- <button type="submit" data-i18n="btnConnect">Connect to Server</button>
552
  </form>
553
- <button id="show-setup-btn" class="start-server-btn" data-i18n="btnStartServer">Start a Server (Setup Guide)</button>
554
  </div>
555
  </div>
556
 
557
- <div id="setup-modal" class="hidden">
 
558
  <div class="modal-content">
559
- <button id="close-setup-btn" class="close-modal">&times;</button>
560
- <h2 data-i18n="setupTitle">Server Setup & Settings</h2>
561
 
562
- <div style="background-color: var(--bg-dark); padding: 1rem; border-radius: 6px; margin: 1rem 0; border: 1px solid var(--border);">
563
- <h3 style="margin-bottom: 1rem; font-size: 1rem; color: var(--accent);" data-i18n="setupConfigTitle">⚙️ Configure Your Server</h3>
564
- <div class="input-group">
565
- <label data-i18n="setupAppName">Application Name</label>
566
- <input type="text" id="gen-app-name" value="SupaServer">
 
567
  </div>
568
- <div class="input-group">
569
- <label data-i18n="setupChannels">Default Channels (comma separated)</label>
570
- <input type="text" id="gen-channels" value="general, random, announcements">
 
 
 
 
 
571
  </div>
572
  </div>
573
 
574
- <p style="margin-top: 1rem; color: var(--text-secondary);" data-i18n="setupDesc">
575
- Run this generated SQL in your Supabase SQL Editor. It includes strict RLS policies.
576
- </p>
577
-
578
- <div class="code-block">
579
- <button class="copy-btn" onclick="copyToClipboard('sql-code')" data-i18n="btnCopy">Copy</button>
580
- <pre id="sql-code"></pre>
581
  </div>
 
 
 
 
 
 
 
 
582
 
583
- <p style="margin-top: 0.5rem; font-size: 0.85rem; color: var(--error);" data-i18n="setupNote">
584
- Note: This uses custom table authentication. For production security, use Supabase Auth for true RLS (JWTs).
585
- </p>
 
 
 
 
 
 
586
  </div>
587
  </div>
588
 
 
589
  <div id="app-screen" class="hidden">
590
- <!-- Sidebar: Channels -->
591
- <div class="sidebar">
592
- <div class="channel-header-row">
593
- <span id="app-title-display" style="font-weight: bold; color: var(--text-primary);">SupaServer</span>
594
- <button id="add-channel-btn" class="add-channel-btn" title="Create Channel">+</button>
 
 
595
  </div>
596
- <div class="channels-list" id="channels-list">
597
- <!-- Channels will be injected here -->
598
  </div>
599
- <div class="user-info">
600
- <span id="current-username" style="font-weight: bold;">User</span>
601
- <button id="logout-btn" class="logout-btn" data-i18n="btnLogout">Logout</button>
 
 
 
602
  </div>
603
  </div>
604
 
605
- <!-- Main: Chat -->
606
  <div class="chat-area">
607
- <div class="chat-header">
608
- <h3 id="current-channel-name">#general</h3>
 
 
 
 
609
  </div>
610
  <div class="messages-container" id="messages-container">
611
- <!-- Messages will be injected here -->
612
  </div>
613
  <div class="message-input-area">
614
  <form id="message-form" class="message-form">
615
- <input type="text" id="message-input" placeholder="Message #general" autocomplete="off" disabled>
616
  <button type="submit" id="send-btn" data-i18n="btnSend" disabled>Send</button>
617
  </form>
618
  </div>
619
  </div>
620
 
621
- <!-- Sidebar: Members -->
622
- <div class="members-list">
623
- <div class="members-header" data-i18n="headerMembers">
624
- Members
 
625
  </div>
626
- <div class="members-container" id="members-container">
627
- <!-- Members will be injected here -->
628
  </div>
629
  </div>
630
  </div>
631
 
632
  <script>
633
- // --- State Management ---
634
- const DEFAULT_PROJECT_URL = ""; // Optional: Paste default URL here
635
- const DEFAULT_API_KEY = ""; // Optional: Paste default Anon Key here
636
-
637
  const state = {
638
- projectUrl: localStorage.getItem('supa_url') || DEFAULT_PROJECT_URL,
639
- apiKey: localStorage.getItem('supa_key') || DEFAULT_API_KEY,
640
- currentUser: null,
641
- channels: [],
642
- activeChannel: null,
643
- users: new Map(),
644
- messages: [],
645
  lang: 'ru'
646
  };
647
 
648
- // --- Translations Dictionary ---
649
  const i18n = {
650
  ru: {
651
  appTitle: 'SupaMessenger',
652
- labelProjectUrl: 'URL проекта',
653
- labelApiKey: 'API Key (Anon Key)',
654
- labelUsername: 'Имя пользователя',
655
- phUsername: 'Введите имя пользователя',
656
- labelPassword: 'Пароль',
657
- phPassword: 'Введите пароль',
658
- btnConnect: 'Войти в мессенджер',
659
- btnStartServer: 'Создать сервер (Настройки)',
660
- setupTitle: 'Настройки сервера и Установка',
661
- setupConfigTitle: '⚙️ Настройте ваш сервер',
662
- setupAppName: 'Название приложения',
663
- setupChannels: 'Стартовые каналы (через запятую)',
664
- setupDesc: 'Выполните этот сгенерированный SQL в Supabase SQL Editor. Включены строгие политики RLS.',
665
- setupNote: 'Примечание: Используется базовая авторизация в таблицах. Для production безопасности используйте Supabase Auth (JWT).',
666
- btnCopy: 'Копировать',
667
- btnLogout: 'Выйти',
668
- btnSend: 'Отправить',
669
- headerMembers: 'Уча��тники',
670
- msgPlaceholder: 'Сообщение в #',
671
- copySuccess: 'SQL код скопирован в буфер обмена!',
672
- errInvalidLogin: 'Неверное имя пользователя или пароль.',
673
- errConnection: 'Ошибка подключения. Проверьте URL, API Key и настройки базы. ',
674
- alertDataLoadFail: 'Подключено, но не удалось загрузить данные. Вы создали таблицы?',
675
- unknownUser: 'Неизвестный',
676
- promptNewChannel: 'Введите название нового канала (без пробелов):'
677
  },
678
  en: {
679
  appTitle: 'SupaMessenger',
680
- labelProjectUrl: 'Project URL',
681
- labelApiKey: 'API Key (Anon Key)',
682
- labelUsername: 'Username',
683
- phUsername: 'Enter your username',
684
- labelPassword: 'Password',
685
- phPassword: 'Enter your password',
686
- btnConnect: 'Log In',
687
- btnStartServer: 'Create Server (Setup)',
688
- setupTitle: 'Server Setup & Settings',
689
- setupConfigTitle: '⚙️ Configure Your Server',
690
- setupAppName: 'Application Name',
691
- setupChannels: 'Default Channels (comma separated)',
692
- setupDesc: 'Run this generated SQL in your Supabase SQL Editor. It includes strict RLS policies.',
693
- setupNote: 'Note: Uses custom table authentication. For production security, use Supabase Auth for true RLS (JWTs).',
694
- btnCopy: 'Copy',
695
- btnLogout: 'Logout',
696
- btnSend: 'Send',
697
- headerMembers: 'Members',
698
  msgPlaceholder: 'Message #',
699
- copySuccess: 'SQL code copied to clipboard!',
700
- errInvalidLogin: 'Invalid username or password.',
701
- errConnection: 'Connection error. Check URL, API Key, and database settings. ',
702
- alertDataLoadFail: 'Connected, but failed to load data. Did you create the tables?',
703
- unknownUser: 'Unknown',
704
- promptNewChannel: 'Enter new channel name (no spaces):'
705
  }
706
  };
707
 
708
- function setLanguage(lang) {
709
- state.lang = lang;
710
- const t = i18n[lang];
711
-
712
- document.querySelectorAll('[data-i18n]').forEach(el => {
713
- const key = el.getAttribute('data-i18n');
714
- if (t[key]) el.textContent = t[key];
715
- });
716
-
717
- document.querySelectorAll('[data-i18n-ph]').forEach(el => {
718
- const key = el.getAttribute('data-i18n-ph');
719
- if (t[key]) el.placeholder = t[key];
720
- });
721
 
722
- const langBtn = document.getElementById('lang-btn');
723
- if (langBtn) {
724
- langBtn.textContent = lang === 'ru' ? '🌐 RU' : '🌐 EN';
725
- }
726
 
 
 
 
 
 
 
727
  if (state.activeChannel) {
728
  const chan = state.channels.find(c => c.id === state.activeChannel);
729
- if (chan) {
730
- els.messageInput.placeholder = `${t.msgPlaceholder}${chan.name}`;
731
- }
732
  }
733
  }
734
 
735
- // --- DOM Elements ---
736
- const els = {
737
- loginScreen: document.getElementById('login-screen'),
738
- appScreen: document.getElementById('app-screen'),
739
- loginForm: document.getElementById('login-form'),
740
- loginError: document.getElementById('login-error'),
741
- setupModal: document.getElementById('setup-modal'),
742
-
743
- channelsList: document.getElementById('channels-list'),
744
- messagesContainer: document.getElementById('messages-container'),
745
- membersContainer: document.getElementById('members-container'),
746
-
747
- currentUsername: document.getElementById('current-username'),
748
- currentChannelName: document.getElementById('current-channel-name'),
749
- messageForm: document.getElementById('message-form'),
750
- messageInput: document.getElementById('message-input'),
751
- sendBtn: document.getElementById('send-btn'),
752
- logoutBtn: document.getElementById('logout-btn')
753
- };
754
-
755
- // --- Utility Functions ---
756
  function copyToClipboard(elementId) {
757
  const text = document.getElementById(elementId).innerText;
758
- const textArea = document.createElement("textarea");
759
- textArea.value = text;
760
- document.body.appendChild(textArea);
761
- textArea.select();
762
- try {
763
- document.execCommand('copy');
764
- alert(i18n[state.lang].copySuccess);
765
- } catch (err) {
766
- console.error('Unable to copy', err);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
767
  }
768
- document.body.removeChild(textArea);
 
 
 
 
 
 
 
 
 
769
  }
770
 
771
  class SupabaseREST {
772
  constructor(url, apiKey) {
773
  this.baseUrl = url.replace(/\/$/, '') + '/rest/v1';
774
- this.headers = {
775
- 'Content-Type': 'application/json',
776
- 'Prefer': 'return=representation',
777
- 'apikey': apiKey,
778
- 'Authorization': `Bearer ${apiKey}`
779
- };
780
  }
781
 
782
- async login(username, password) {
783
- try {
784
- const response = await fetch(`${this.baseUrl}/app_users?username=eq.${encodeURIComponent(username)}&password=eq.${encodeURIComponent(password)}&select=*`, {
785
- method: 'GET',
786
- headers: this.headers
787
- });
788
-
789
- if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
790
- const data = await response.json();
791
-
792
- if (data.length === 0) {
793
- throw new Error(i18n[state.lang].errInvalidLogin);
794
- }
795
- return data[0];
796
- } catch (error) {
797
- throw new Error(i18n[state.lang].errConnection + error.message);
798
- }
799
  }
800
 
801
- async setOnlineStatus(userId, isOnline) {
802
- try {
803
- await fetch(`${this.baseUrl}/app_users?id=eq.${userId}`, {
804
- method: 'PATCH',
805
- headers: this.headers,
806
- body: JSON.stringify({ is_online: isOnline, last_seen: new Date().toISOString() })
807
- });
808
- } catch(e) { console.error("Failed to update status", e); }
809
  }
810
 
811
- async getChannels() {
812
- const response = await fetch(`${this.baseUrl}/channels?select=*&order=created_at.asc`, { headers: this.headers });
813
- if (!response.ok) throw new Error('Failed to fetch channels');
814
- return await response.json();
815
  }
816
 
817
- async getUsers() {
818
- const response = await fetch(`${this.baseUrl}/app_users?select=id,username,is_online`, { headers: this.headers });
819
- if (!response.ok) throw new Error('Failed to fetch users');
820
- return await response.json();
821
  }
822
 
823
- async getMessages(channelId) {
824
- const response = await fetch(`${this.baseUrl}/messages?channel_id=eq.${channelId}&select=*,app_users(username)&order=created_at.asc`, { headers: this.headers });
825
- if (!response.ok) throw new Error('Failed to fetch messages');
826
- return await response.json();
827
  }
828
 
829
- async sendMessage(channelId, userId, content) {
830
- const response = await fetch(`${this.baseUrl}/messages`, {
831
- method: 'POST',
832
- headers: this.headers,
833
- body: JSON.stringify({ channel_id: channelId, user_id: userId, content: content })
834
- });
835
- if (!response.ok) throw new Error('Failed to send message');
836
- return await response.json();
837
  }
838
 
839
- async createChannel(name) {
840
- const response = await fetch(`${this.baseUrl}/channels`, {
841
- method: 'POST',
842
- headers: this.headers,
843
- body: JSON.stringify({ name: name.toLowerCase().replace(/\s+/g, '-') })
844
- });
845
- if (!response.ok) throw new Error('Failed to create channel');
846
- return await response.json();
847
  }
848
  }
849
-
850
  let db = null;
851
 
852
- // --- STREAMING_CHUNK: Helpers ---
853
- function stringToColor(str) {
854
- let hash = 0;
855
- for (let i = 0; i < str.length; i++) hash = str.charCodeAt(i) + ((hash << 5) - hash);
856
- const c = (hash & 0x00FFFFFF).toString(16).toUpperCase();
857
- return '#' + '00000'.substring(0, 6 - c.length) + c;
858
- }
859
-
860
- function getInitials(name) {
861
- return name.substring(0, 2).toUpperCase();
862
  }
863
-
864
- function parseMarkdown(text) {
865
- let html = text.replace(/</g, '&lt;').replace(/>/g, '&gt;');
866
- html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
867
- html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');
868
- html = html.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>');
869
- html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
870
- return html;
871
- }
872
-
873
- // --- STREAMING_CHUNK: UI Rendering Logic ---
874
 
875
- function showError(msg) {
876
- els.loginError.textContent = msg;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
877
  }
878
 
879
  function renderChannels() {
880
  els.channelsList.innerHTML = '';
881
- state.channels.forEach(channel => {
882
  const div = document.createElement('div');
883
- div.className = `channel-item ${state.activeChannel === channel.id ? 'active' : ''}`;
884
- div.textContent = channel.name;
885
- div.onclick = () => selectChannel(channel);
886
  els.channelsList.appendChild(div);
887
  });
888
  }
889
 
890
  function renderMembers() {
891
  els.membersContainer.innerHTML = '';
892
- // Sort: Online first, then by name
893
- const sortedUsers = Array.from(state.users.values()).sort((a, b) => {
894
- if (a.is_online === b.is_online) return a.username.localeCompare(b.username);
895
- return a.is_online ? -1 : 1;
896
- });
897
-
898
- sortedUsers.forEach(user => {
899
  const div = document.createElement('div');
900
  div.className = 'member-item';
901
-
902
- const dot = document.createElement('div');
903
- dot.className = `status-dot ${user.is_online ? '' : 'offline'}`;
904
-
905
- const avatar = document.createElement('div');
906
- avatar.className = 'avatar member-avatar';
907
- avatar.style.backgroundColor = stringToColor(user.username);
908
- avatar.textContent = getInitials(user.username);
909
-
910
  const name = document.createElement('span');
911
- name.textContent = user.username;
912
- name.style.color = user.is_online ? 'var(--text-primary)' : 'var(--text-secondary)';
913
-
914
- div.appendChild(dot);
915
- div.appendChild(avatar);
916
  div.appendChild(name);
917
  els.membersContainer.appendChild(div);
918
  });
919
  }
920
 
921
  function renderMessages() {
 
922
  els.messagesContainer.innerHTML = '';
923
  state.messages.forEach(msg => {
924
- const div = document.createElement('div');
925
- div.className = 'message';
926
- div.style.flexDirection = 'row';
927
 
928
- const username = msg.app_users ? msg.app_users.username : (state.users.get(msg.user_id)?.username || i18n[state.lang].unknownUser);
929
 
930
- const avatar = document.createElement('div');
931
- avatar.className = 'avatar';
932
- avatar.style.backgroundColor = stringToColor(username);
933
- avatar.textContent = getInitials(username);
934
 
935
- const contentWrapper = document.createElement('div');
936
- contentWrapper.style.flex = '1';
937
-
938
- const header = document.createElement('div');
939
- header.className = 'message-header';
940
-
941
- const author = document.createElement('span');
942
- author.className = 'message-author';
943
- author.textContent = username;
944
-
945
- const time = document.createElement('span');
946
- time.className = 'message-time';
947
- const date = new Date(msg.created_at);
948
- time.textContent = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
949
-
950
- header.appendChild(author);
951
- header.appendChild(time);
952
-
953
- const content = document.createElement('div');
954
- content.className = 'message-content';
955
  content.innerHTML = parseMarkdown(msg.content);
956
 
957
- contentWrapper.appendChild(header);
958
- contentWrapper.appendChild(content);
959
-
960
- div.appendChild(avatar);
961
- div.appendChild(contentWrapper);
962
  els.messagesContainer.appendChild(div);
963
  });
964
- els.messagesContainer.scrollTop = els.messagesContainer.scrollHeight;
965
  }
966
 
967
- // --- STREAMING_CHUNK: Application Actions ---
968
-
969
  async function selectChannel(channel) {
970
  state.activeChannel = channel.id;
971
  els.currentChannelName.textContent = `#${channel.name}`;
972
- els.messageInput.placeholder = `${i18n[state.lang].msgPlaceholder}${channel.name}`;
973
- els.messageInput.disabled = false;
974
- els.sendBtn.disabled = false;
975
-
976
  renderChannels();
977
-
978
- try {
979
- state.messages = await db.getMessages(channel.id);
980
- renderMessages();
981
- } catch (e) {
982
- console.error("Error loading messages", e);
983
- state.messages = [];
984
- renderMessages();
985
- }
986
  }
987
 
988
  async function loadInitialData() {
989
- try {
990
- const usersData = await db.getUsers();
991
- state.users.clear();
992
- usersData.forEach(u => state.users.set(u.id, u));
993
- renderMembers();
994
-
995
- state.channels = await db.getChannels();
996
- renderChannels();
997
-
998
- if (state.channels.length > 0) {
999
- selectChannel(state.channels[0]);
1000
- }
1001
- } catch (e) {
1002
- console.error("Error loading data", e);
1003
- alert(i18n[state.lang].alertDataLoadFail);
1004
- }
1005
  }
1006
 
1007
- // Polling for updates
1008
  let pollInterval;
1009
  function startPolling() {
1010
  pollInterval = setInterval(async () => {
1011
- if (!state.currentUser) return;
1012
-
1013
  try {
1014
- // Update Members
1015
- const usersData = await db.getUsers();
1016
- let membersChanged = false;
1017
- usersData.forEach(u => {
1018
- const existing = state.users.get(u.id);
1019
- if (!existing || existing.is_online !== u.is_online) {
1020
- membersChanged = true;
1021
- }
1022
- state.users.set(u.id, u);
1023
- });
1024
- if (membersChanged) renderMembers();
1025
-
1026
- // Update Channels
1027
- const newChannels = await db.getChannels();
1028
- if (newChannels.length !== state.channels.length) {
1029
- state.channels = newChannels;
1030
- renderChannels();
1031
- }
1032
 
1033
- // Update Messages if active channel
1034
- if (state.activeChannel) {
1035
- const newMessages = await db.getMessages(state.activeChannel);
1036
- if (newMessages.length !== state.messages.length) {
1037
- state.messages = newMessages;
1038
- renderMessages();
1039
- }
1040
  }
1041
- } catch (e) {
1042
- // Silently fail polling
1043
- }
1044
- }, 3000);
1045
  }
1046
 
1047
- function stopPolling() {
1048
- if (pollInterval) clearInterval(pollInterval);
1049
- }
 
 
 
 
 
 
1050
 
1051
- // --- STREAMING_CHUNK: Event Listeners ---
1052
-
1053
- // Prefill inputs
1054
- document.getElementById('cfg-project-url').value = state.projectUrl;
1055
- document.getElementById('cfg-api-key').value = state.apiKey;
1056
 
1057
  els.loginForm.addEventListener('submit', async (e) => {
1058
  e.preventDefault();
1059
- const url = document.getElementById('cfg-project-url').value.trim();
1060
- const key = document.getElementById('cfg-api-key').value.trim();
1061
- const user = document.getElementById('username').value.trim();
1062
- const pass = document.getElementById('password').value.trim();
1063
-
1064
- if (!url || !key) {
1065
- showError(i18n[state.lang].errConnection);
1066
- return;
1067
- }
1068
-
1069
- state.projectUrl = url;
1070
- state.apiKey = key;
1071
- localStorage.setItem('supa_url', url);
1072
- localStorage.setItem('supa_key', key);
1073
-
1074
- showError('Connecting...');
1075
-
1076
- db = new SupabaseREST(url, key);
1077
-
1078
  try {
1079
- const userData = await db.login(user, pass);
1080
-
1081
- state.currentUser = userData;
1082
- els.currentUsername.textContent = userData.username;
1083
-
1084
- await db.setOnlineStatus(userData.id, true);
1085
-
1086
- els.loginScreen.classList.add('hidden');
1087
- els.appScreen.classList.remove('hidden');
1088
-
1089
- await loadInitialData();
1090
- startPolling();
1091
-
1092
- } catch (error) {
1093
- showError(error.message);
1094
- }
1095
- });
1096
-
1097
- // Add Channel Action
1098
- document.getElementById('add-channel-btn').addEventListener('click', async () => {
1099
- const name = prompt(i18n[state.lang].promptNewChannel);
1100
- if (name && name.trim()) {
1101
- try {
1102
- await db.createChannel(name.trim());
1103
- state.channels = await db.getChannels();
1104
- renderChannels();
1105
- } catch(e) {
1106
- console.error('Error creating channel', e);
1107
- }
1108
- }
1109
  });
1110
 
1111
- els.logoutBtn.addEventListener('click', async () => {
1112
- if (state.currentUser && db) {
1113
- await db.setOnlineStatus(state.currentUser.id, false);
1114
- }
1115
- stopPolling();
1116
- state.currentUser = null;
1117
- els.appScreen.classList.add('hidden');
1118
- els.loginScreen.classList.remove('hidden');
1119
- document.getElementById('password').value = '';
 
1120
  });
1121
 
1122
- els.messageForm.addEventListener('submit', async (e) => {
 
 
1123
  e.preventDefault();
1124
- if (!state.activeChannel || !state.currentUser) return;
 
 
 
 
 
 
 
 
1125
 
1126
- const content = els.messageInput.value.trim();
1127
- if (!content) return;
 
 
 
 
 
 
1128
 
1129
- els.messageInput.value = '';
1130
-
1131
- try {
1132
- await db.sendMessage(state.activeChannel, state.currentUser.id, content);
1133
- // Immediately fetch messages to feel responsive
1134
- state.messages = await db.getMessages(state.activeChannel);
1135
- renderMessages();
1136
- } catch (e) {
1137
- console.error("Failed to send", e);
1138
- // Revert input on fail
1139
- els.messageInput.value = content;
1140
- }
1141
- });
1142
 
1143
- // Modal & SQL Setup Handling
1144
- function generateSQL() {
1145
- const channelsStr = document.getElementById('gen-channels').value;
1146
- const appName = document.getElementById('gen-app-name').value || 'SupaServer';
1147
-
1148
- const channelsList = channelsStr.split(',').map(s => `'${s.trim().replace(/\s+/g, '-').toLowerCase()}'`).filter(s => s !== "''" && s !== "''");
1149
-
1150
- const insertChannels = channelsList.length > 0
1151
- ? `INSERT INTO public.channels (name) VALUES \n (${channelsList.join('),\n (')})\nON CONFLICT DO NOTHING;`
1152
- : `-- No default channels`;
1153
 
1154
- const sql = `
1155
- -- App Name: ${appName}
1156
- -- 1. Create Users Table
1157
  CREATE TABLE IF NOT EXISTS public.app_users (
1158
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
1159
- username TEXT UNIQUE NOT NULL,
1160
- password TEXT NOT NULL,
1161
- is_online BOOLEAN DEFAULT false,
1162
- last_seen TIMESTAMP WITH TIME ZONE DEFAULT NOW()
1163
  );
1164
-
1165
- -- 2. Create Channels Table
1166
  CREATE TABLE IF NOT EXISTS public.channels (
1167
- id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
1168
- name TEXT UNIQUE NOT NULL,
1169
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
1170
  );
1171
-
1172
- -- 3. Create Messages Table
1173
  CREATE TABLE IF NOT EXISTS public.messages (
1174
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
1175
  channel_id UUID REFERENCES public.channels(id) ON DELETE CASCADE,
1176
  user_id UUID REFERENCES public.app_users(id) ON DELETE CASCADE,
1177
- content TEXT NOT NULL,
1178
- created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
1179
  );
1180
-
1181
- -- 4. Enable Row Level Security (RLS)
1182
  ALTER TABLE public.app_users ENABLE ROW LEVEL SECURITY;
1183
  ALTER TABLE public.channels ENABLE ROW LEVEL SECURITY;
1184
  ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY;
1185
-
1186
- -- 5. Strict RLS Policies for Anon Key (Custom Auth)
1187
- -- Read access
1188
- CREATE POLICY "Allow read channels" ON public.channels FOR SELECT TO anon USING (true);
1189
- CREATE POLICY "Allow read messages" ON public.messages FOR SELECT TO anon USING (true);
1190
- CREATE POLICY "Allow read users" ON public.app_users FOR SELECT TO anon USING (true);
1191
-
1192
- -- Insert access
1193
- CREATE POLICY "Allow insert channels" ON public.channels FOR INSERT TO anon WITH CHECK (true);
1194
- CREATE POLICY "Allow insert messages" ON public.messages FOR INSERT TO anon WITH CHECK (true);
1195
-
1196
- -- Update restrictions
1197
- CREATE POLICY "Allow status update" ON public.app_users FOR UPDATE TO anon USING (true);
1198
-
1199
- -- 6. Insert Default Channels
1200
- ${insertChannels}
1201
-
1202
- -- 7. Grant access
1203
  GRANT USAGE ON SCHEMA public TO anon, authenticated;
1204
  GRANT ALL ON ALL TABLES IN SCHEMA public TO anon, authenticated;
1205
- GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO anon, authenticated;
1206
  `.trim();
1207
- document.getElementById('sql-code').textContent = sql;
1208
-
1209
- // Update Title Display in App Side too
1210
- document.getElementById('app-title-display').textContent = appName;
1211
- }
1212
-
1213
- document.getElementById('gen-channels').addEventListener('input', generateSQL);
1214
- document.getElementById('gen-app-name').addEventListener('input', generateSQL);
1215
-
1216
- document.getElementById('show-setup-btn').addEventListener('click', () => {
1217
- generateSQL();
1218
- els.setupModal.classList.remove('hidden');
1219
- });
1220
-
1221
- document.getElementById('close-setup-btn').addEventListener('click', () => {
1222
- els.setupModal.classList.add('hidden');
1223
- });
1224
 
1225
- // Handle page close to set offline status
1226
- window.addEventListener('beforeunload', () => {
1227
- if (state.currentUser && db) {
1228
- db.setOnlineStatus(state.currentUser.id, false);
1229
- }
1230
- });
1231
 
1232
- // Language Switcher Setup
1233
- document.getElementById('lang-btn').addEventListener('click', () => {
1234
- const nextLang = state.lang === 'ru' ? 'en' : 'ru';
1235
- setLanguage(nextLang);
1236
- });
1237
 
1238
- // Set default language on load
1239
  setLanguage('ru');
 
1240
 
1241
  </script>
1242
  </body>
 
2
  <html lang="en">
3
  <head>
4
  <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
6
  <title>SupaMessenger</title>
7
  <style>
8
  :root {
 
16
  --border: #45475a;
17
  --error: #f38ba8;
18
  --success: #a6e3a1;
19
+ --overlay: rgba(0, 0, 0, 0.6);
20
  }
21
 
22
+ * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
 
 
 
 
 
23
 
24
  body {
25
  background-color: var(--bg-dark);
 
27
  height: 100vh;
28
  display: flex;
29
  overflow: hidden;
30
+ overscroll-behavior-y: none;
31
  }
32
 
33
  /* Utility Classes */
34
  .hidden { display: none !important; }
35
  .flex { display: flex; }
 
36
  .items-center { align-items: center; }
37
  .justify-center { justify-content: center; }
 
 
38
 
39
  /* Custom Scrollbars */
40
+ ::-webkit-scrollbar { width: 6px; height: 6px; }
41
+ ::-webkit-scrollbar-track { background: transparent; }
42
+ ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
43
+ ::-webkit-scrollbar-thumb:hover { background: var(--accent); }
44
+ * { scrollbar-width: thin; scrollbar-color: var(--border) transparent; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ /* General UI Elements */
47
  input {
48
+ width: 100%; padding: 0.75rem; border: 1px solid var(--border); border-radius: 6px;
49
+ background-color: var(--bg-dark); color: var(--text-primary); outline: none; transition: border-color 0.2s;
 
 
 
 
 
 
50
  }
51
+ input:focus { border-color: var(--accent); }
52
+ input:disabled { opacity: 0.5; cursor: not-allowed; }
53
+
 
 
54
  button {
55
+ padding: 0.75rem; border: none; border-radius: 6px;
56
+ background-color: var(--accent); color: var(--bg-dark); font-weight: bold; cursor: pointer; transition: 0.2s;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  }
58
+ button:hover:not(:disabled) { background-color: var(--accent-hover); }
59
+ button:disabled { opacity: 0.5; cursor: not-allowed; }
60
 
61
+ .btn-outline { background-color: transparent; color: var(--text-secondary); border: 1px solid var(--border); }
62
+ .btn-outline:hover { background-color: var(--bg-hover); color: var(--text-primary); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
+ .lang-btn {
65
+ position: fixed; top: 1rem; right: 1rem; padding: 0.4rem 0.8rem; background-color: var(--bg-panel);
66
+ color: var(--accent); border: 1px solid var(--border); border-radius: 20px; font-size: 0.85rem; z-index: 300;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  }
68
 
69
+ /* Modals & Login */
70
+ .screen-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: var(--bg-dark); z-index: 100; }
71
+ .login-container { background-color: var(--bg-panel); padding: 2rem; border-radius: 8px; width: 90%; max-width: 400px; box-shadow: 0 8px 16px rgba(0,0,0,0.4); }
72
+ .login-container h1 { text-align: center; margin-bottom: 1.5rem; color: var(--accent); }
73
+ .input-group { margin-bottom: 1rem; }
74
+ .input-group label { display: block; margin-bottom: 0.5rem; color: var(--text-secondary); font-size: 0.9rem; }
75
+ .error-message { color: var(--error); font-size: 0.85rem; margin-top: 0.5rem; text-align: center; min-height: 1.2em; }
76
 
77
+ .modal-wrapper { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: var(--overlay); z-index: 200; display: flex; align-items: center; justify-content: center; padding: 1rem; }
78
+ .modal-content { background-color: var(--bg-panel); padding: 2rem; border-radius: 8px; width: 100%; max-width: 650px; max-height: 90vh; overflow-y: auto; position: relative; }
79
+ .close-modal { position: absolute; top: 1rem; right: 1rem; background: none; border: none; color: var(--text-secondary); font-size: 1.5rem; width: auto; padding: 0; }
80
+
81
+ .code-block { background-color: var(--bg-dark); padding: 1rem; border-radius: 4px; overflow-x: auto; font-family: monospace; margin: 0.5rem 0 1.5rem 0; color: var(--text-primary); border: 1px solid var(--border); position: relative; font-size: 0.85rem; }
82
+ .copy-btn { position: absolute; top: 0.5rem; right: 0.5rem; padding: 0.25rem 0.5rem; font-size: 0.8rem; background-color: var(--bg-panel); color: var(--text-primary); width: auto; }
83
 
84
+ /* App Layout */
85
+ #app-screen { display: flex; width: 100%; height: 100%; position: relative; }
86
+
87
+ .sidebar { width: 260px; background-color: var(--bg-panel); border-right: 1px solid var(--border); display: flex; flex-direction: column; flex-shrink: 0; }
88
+ .chat-area { flex: 1; display: flex; flex-direction: column; background-color: var(--bg-dark); min-width: 0; }
89
+ .members-list { width: 220px; background-color: var(--bg-panel); border-left: 1px solid var(--border); display: flex; flex-direction: column; flex-shrink: 0; }
90
+
91
+ /* Header Rows */
92
+ .header-row { padding: 1rem; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; font-weight: bold; }
93
+ .header-row h3 { font-size: 1.1rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
94
+
95
+ /* Lists */
96
+ .list-container { flex: 1; overflow-y: auto; padding: 0.5rem 0; }
97
+ .channel-item, .member-item { padding: 0.5rem 1rem; cursor: pointer; display: flex; align-items: center; gap: 0.5rem; color: var(--text-secondary); transition: 0.15s; }
98
+ .channel-item:before { content: '#'; opacity: 0.5; }
99
+ .channel-item:hover, .member-item:hover { background-color: var(--bg-hover); color: var(--text-primary); }
100
+ .channel-item.active { background-color: var(--bg-hover); color: var(--text-primary); font-weight: bold; border-left: 3px solid var(--accent); }
101
 
102
+ /* User Profile Area (Bottom Sidebar) */
103
+ .user-profile-area { padding: 1rem; border-top: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; cursor: pointer; transition: background 0.2s; }
104
+ .user-profile-area:hover { background-color: var(--bg-hover); }
105
+ .user-profile-info { display: flex; align-items: center; gap: 0.5rem; overflow: hidden; }
106
+ .user-profile-info span { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: bold; }
107
+
108
+ /* Chat & Messages */
109
+ .messages-container { flex: 1; overflow-y: auto; padding: 1rem; display: flex; flex-direction: column; gap: 1rem; scroll-behavior: smooth; }
110
+ .message { display: flex; flex-direction: row; gap: 0.75rem; word-break: break-word; }
111
+ .message-header { display: flex; align-items: baseline; gap: 0.5rem; margin-bottom: 0.2rem; }
112
+ .message-author { font-weight: bold; color: var(--accent); }
113
+ .message-time { font-size: 0.75rem; color: var(--text-secondary); }
114
+ .message-content { line-height: 1.4; }
115
+
116
+ .message-input-area { padding: 1rem; border-top: 1px solid var(--border); }
117
+ .message-form { display: flex; gap: 0.5rem; }
118
+ .message-form button { width: auto; padding: 0 1.5rem; }
119
+
120
+ /* Avatars & Status */
121
+ .avatar { width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; color: white; flex-shrink: 0; background-color: var(--border); box-shadow: 0 1px 3px rgba(0,0,0,0.3); }
122
+ .member-avatar { width: 28px; height: 28px; font-size: 0.8rem; }
123
+ .status-dot { width: 10px; height: 10px; border-radius: 50%; background-color: var(--success); border: 2px solid var(--bg-panel); margin-left: -12px; margin-top: 18px; z-index: 2; }
124
+ .status-dot.offline { background-color: var(--text-secondary); }
125
+
126
+ /* Mobile Responsive UI */
127
+ .mobile-toggle-btn { display: none; background: transparent; color: var(--text-primary); border: none; font-size: 1.5rem; padding: 0.2rem; cursor: pointer; }
128
+ #mobile-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: var(--overlay); z-index: 40; }
129
+
130
+ @media (max-width: 768px) {
131
+ .mobile-toggle-btn { display: block; }
132
+ .sidebar { position: absolute; left: -260px; height: 100%; z-index: 50; transition: left 0.3s ease; }
133
+ .sidebar.show { left: 0; }
134
+ .members-list { position: absolute; right: -220px; height: 100%; z-index: 50; transition: right 0.3s ease; }
135
+ .members-list.show { right: 0; }
136
+ .user-profile-area { padding: 0.75rem; }
137
  }
138
  </style>
139
  </head>
 
141
 
142
  <button id="lang-btn" class="lang-btn">🌐 RU</button>
143
 
144
+ <!-- Login Screen -->
145
+ <div id="login-screen" class="screen-overlay flex items-center justify-center">
146
  <div class="login-container">
147
  <h1 data-i18n="appTitle">SupaMessenger</h1>
148
  <form id="login-form">
149
  <div class="input-group">
150
+ <label data-i18n="labelProjectUrl">Project URL</label>
151
+ <input type="url" id="cfg-project-url" required>
152
  </div>
153
  <div class="input-group">
154
+ <label data-i18n="labelApiKey">API Key (Anon Key)</label>
155
+ <input type="password" id="cfg-api-key" required>
156
  </div>
 
157
  <div class="input-group">
158
+ <label data-i18n="labelUsername">Username</label>
159
+ <input type="text" id="username" data-i18n-ph="phUsername" required>
160
  </div>
161
  <div class="input-group">
162
+ <label data-i18n="labelPassword">Password</label>
163
+ <input type="password" id="password" data-i18n-ph="phPassword" required>
164
  </div>
165
  <div id="login-error" class="error-message"></div>
166
+ <button type="submit" class="w-full" data-i18n="btnConnect" style="margin-top: 0.5rem;">Log In</button>
167
  </form>
168
+ <button id="show-setup-btn" class="w-full btn-outline" data-i18n="btnStartServer" style="margin-top: 1rem;">Setup Server / Guide</button>
169
  </div>
170
  </div>
171
 
172
+ <!-- Setup Guide Modal -->
173
+ <div id="setup-modal" class="modal-wrapper hidden">
174
  <div class="modal-content">
175
+ <button class="close-modal" onclick="els.setupModal.classList.add('hidden')">&times;</button>
176
+ <h2 data-i18n="setupTitle" style="margin-bottom: 1.5rem; color: var(--accent);">Server Setup & Guide</h2>
177
 
178
+ <div style="margin-bottom: 1.5rem;">
179
+ <h3 data-i18n="setupNewInstall" style="color: var(--success); margin-bottom: 0.5rem;">1. Установка с нуля</h3>
180
+ <p data-i18n="setupDescNew" style="font-size: 0.9rem; color: var(--text-secondary); margin-bottom: 0.5rem;">Выполните этот код в Supabase SQL Editor, если создаете сервер впервые.</p>
181
+ <div class="code-block">
182
+ <button class="copy-btn" onclick="copyToClipboard('sql-new')">Copy</button>
183
+ <pre id="sql-new"></pre>
184
  </div>
185
+ </div>
186
+
187
+ <div>
188
+ <h3 data-i18n="setupMigration" style="color: var(--accent); margin-bottom: 0.5rem;">2. Обновление старого сервера (Миграция)</h3>
189
+ <p data-i18n="setupDescMig" style="font-size: 0.9rem; color: var(--text-secondary); margin-bottom: 0.5rem;">Если у вас уже были таблицы, выполните этот код, чтобы безопасно добавить поддержку аватарок и групп. Данные не удалятся.</p>
190
+ <div class="code-block">
191
+ <button class="copy-btn" onclick="copyToClipboard('sql-mig')">Copy</button>
192
+ <pre id="sql-mig"></pre>
193
  </div>
194
  </div>
195
 
196
+ <div style="background-color: var(--bg-dark); padding: 1rem; border-radius: 6px; border: 1px solid var(--border); font-size: 0.9rem; margin-top: 1rem;">
197
+ <strong data-i18n="guideGroupsTitle" style="color: var(--accent-hover);">💡 Как работают группы?</strong>
198
+ <p data-i18n="guideGroupsText" style="margin-top: 0.5rem; color: var(--text-secondary);">Чтобы привязать канал или участника к группе, зайдите в Supabase ➔ Table Editor. Создайте группу в таблице <b>groups</b>. Затем скопируйте её <b>id</b> и вставьте в поле <b>group_id</b> у нужного пользователя или канала.</p>
 
 
 
 
199
  </div>
200
+ </div>
201
+ </div>
202
+
203
+ <!-- Profile Settings Modal -->
204
+ <div id="profile-modal" class="modal-wrapper hidden">
205
+ <div class="modal-content" style="max-width: 400px;">
206
+ <button class="close-modal" onclick="els.profileModal.classList.add('hidden')">&times;</button>
207
+ <h2 data-i18n="profileTitle" style="margin-bottom: 1.5rem; color: var(--accent);">Настройки профиля</h2>
208
 
209
+ <form id="profile-form">
210
+ <div class="input-group">
211
+ <label data-i18n="profileAvatarLabel">URL картинки профиля (Avatar)</label>
212
+ <input type="url" id="profile-avatar-url" placeholder="https://example.com/image.jpg">
213
+ </div>
214
+ <div id="profile-error" class="error-message"></div>
215
+ <button type="submit" class="w-full" data-i18n="btnSave" style="margin-top: 1rem;">Сохранить</button>
216
+ <button type="button" id="logout-btn" class="w-full btn-outline" data-i18n="btnLogout" style="margin-top: 0.5rem; color: var(--error); border-color: var(--border);">Выйти из аккаунта</button>
217
+ </form>
218
  </div>
219
  </div>
220
 
221
+ <!-- Main Application UI -->
222
  <div id="app-screen" class="hidden">
223
+ <div id="mobile-overlay" class="hidden"></div>
224
+
225
+ <!-- Left Sidebar: Channels & Profile -->
226
+ <div class="sidebar" id="sidebar">
227
+ <div class="header-row">
228
+ <h3 data-i18n="headerChannels">Каналы</h3>
229
+ <button class="mobile-toggle-btn" id="close-sidebar-btn">&times;</button>
230
  </div>
231
+ <div class="list-container" id="channels-list">
232
+ <!-- Channels injected here -->
233
  </div>
234
+ <div class="user-profile-area" id="open-profile-btn" title="Настройки профиля">
235
+ <div class="user-profile-info">
236
+ <div id="user-profile-avatar-container"></div>
237
+ <span id="current-username">User</span>
238
+ </div>
239
+ <span style="color: var(--text-secondary); font-size: 1.2rem;">⚙️</span>
240
  </div>
241
  </div>
242
 
243
+ <!-- Center: Chat Area -->
244
  <div class="chat-area">
245
+ <div class="header-row" style="background-color: var(--bg-panel);">
246
+ <div class="flex items-center gap-2">
247
+ <button class="mobile-toggle-btn" id="open-sidebar-btn">☰</button>
248
+ <h3 id="current-channel-name">#general</h3>
249
+ </div>
250
+ <button class="mobile-toggle-btn" id="open-members-btn">👥</button>
251
  </div>
252
  <div class="messages-container" id="messages-container">
253
+ <!-- Messages injected here -->
254
  </div>
255
  <div class="message-input-area">
256
  <form id="message-form" class="message-form">
257
+ <input type="text" id="message-input" autocomplete="off" disabled>
258
  <button type="submit" id="send-btn" data-i18n="btnSend" disabled>Send</button>
259
  </form>
260
  </div>
261
  </div>
262
 
263
+ <!-- Right Sidebar: Members -->
264
+ <div class="members-list" id="members-list">
265
+ <div class="header-row">
266
+ <button class="mobile-toggle-btn" id="close-members-btn" style="margin-right: 0.5rem;">&times;</button>
267
+ <h3 data-i18n="headerMembers">Участники</h3>
268
  </div>
269
+ <div class="list-container" id="members-container">
270
+ <!-- Members injected here -->
271
  </div>
272
  </div>
273
  </div>
274
 
275
  <script>
 
 
 
 
276
  const state = {
277
+ projectUrl: '', apiKey: '',
278
+ currentUser: null, channels: [], activeChannel: null,
279
+ users: new Map(), messages: [],
 
 
 
 
280
  lang: 'ru'
281
  };
282
 
 
283
  const i18n = {
284
  ru: {
285
  appTitle: 'SupaMessenger',
286
+ labelProjectUrl: 'URL проекта (Supabase)', labelApiKey: 'API Key (Anon Key)',
287
+ labelUsername: 'Имя пользователя', phUsername: 'Введите имя',
288
+ labelPassword: 'Пароль', phPassword: 'Введите пароль',
289
+ btnConnect: 'Войти', btnStartServer: 'Настроить сервер (Гайд SQL)',
290
+ setupTitle: 'Настройка сервера и Миграция',
291
+ setupNewInstall: '1. Установка с нуля',
292
+ setupDescNew: 'Выполните этот код в Supabase SQL Editor для создания всех таблиц.',
293
+ setupMigration: '2. Обновление (Миграция)',
294
+ setupDescMig: 'Если сервер уже существует, выполните это для добавления групп и аватарок. Данные сохранятся.',
295
+ guideGroupsTitle: '💡 Как привязать канал к группе?',
296
+ guideGroupsText: 'Зайдите в Supabase ➔ Table Editor. Добавьте группу в таблицу "groups". Скопируйте её ID и вставьте в "group_id" нужного канала или пользователя.',
297
+ headerChannels: 'Каналы', headerMembers: 'Участники',
298
+ msgPlaceholder: 'Написать в #',
299
+ profileTitle: 'Настройки профиля', profileAvatarLabel: 'Ссылка на картинку (URL)',
300
+ btnSave: 'Сохранить', btnLogout: 'Выйти из аккаунта', btnSend: 'Отправить',
301
+ errInvalidLogin: 'Неверное имя или пароль.', errConnection: 'Ошибка подключения к Supabase.',
302
+ errRestoring: 'Восстановление сессии...', msgRestored: 'Сессия восстановлена',
303
+ copySuccess: 'Код скопирован!'
 
 
 
 
 
 
 
304
  },
305
  en: {
306
  appTitle: 'SupaMessenger',
307
+ labelProjectUrl: 'Project URL (Supabase)', labelApiKey: 'API Key (Anon Key)',
308
+ labelUsername: 'Username', phUsername: 'Enter username',
309
+ labelPassword: 'Password', phPassword: 'Enter password',
310
+ btnConnect: 'Log In', btnStartServer: 'Server Setup (SQL Guide)',
311
+ setupTitle: 'Server Setup & Migration',
312
+ setupNewInstall: '1. Fresh Install',
313
+ setupDescNew: 'Run this in Supabase SQL Editor to create all necessary tables.',
314
+ setupMigration: '2. Update (Migration)',
315
+ setupDescMig: 'If your server already exists, run this to add group and avatar support safely.',
316
+ guideGroupsTitle: '💡 How to use Groups?',
317
+ guideGroupsText: 'Go to Supabase ➔ Table Editor. Add a group in the "groups" table. Copy its ID and paste it into the "group_id" of a channel or user.',
318
+ headerChannels: 'Channels', headerMembers: 'Members',
 
 
 
 
 
 
319
  msgPlaceholder: 'Message #',
320
+ profileTitle: 'Profile Settings', profileAvatarLabel: 'Avatar Image URL',
321
+ btnSave: 'Save', btnLogout: 'Log Out', btnSend: 'Send',
322
+ errInvalidLogin: 'Invalid username or password.', errConnection: 'Connection error to Supabase.',
323
+ errRestoring: 'Restoring session...', msgRestored: 'Session restored',
324
+ copySuccess: 'Code copied!'
 
325
  }
326
  };
327
 
328
+ const els = {
329
+ loginScreen: document.getElementById('login-screen'), appScreen: document.getElementById('app-screen'),
330
+ loginForm: document.getElementById('login-form'), loginError: document.getElementById('login-error'),
331
+ setupModal: document.getElementById('setup-modal'), profileModal: document.getElementById('profile-modal'),
332
+ channelsList: document.getElementById('channels-list'), messagesContainer: document.getElementById('messages-container'),
333
+ membersContainer: document.getElementById('members-container'), currentUsername: document.getElementById('current-username'),
334
+ currentChannelName: document.getElementById('current-channel-name'), messageForm: document.getElementById('message-form'),
335
+ messageInput: document.getElementById('message-input'), sendBtn: document.getElementById('send-btn'),
336
+ sidebar: document.getElementById('sidebar'), membersList: document.getElementById('members-list'),
337
+ mobileOverlay: document.getElementById('mobile-overlay')
338
+ };
 
 
339
 
340
+ function t(key) { return i18n[state.lang][key] || key; }
 
 
 
341
 
342
+ function setLanguage(lang) {
343
+ state.lang = lang;
344
+ document.querySelectorAll('[data-i18n]').forEach(el => el.textContent = t(el.getAttribute('data-i18n')));
345
+ document.querySelectorAll('[data-i18n-ph]').forEach(el => el.placeholder = t(el.getAttribute('data-i18n-ph')));
346
+ document.getElementById('lang-btn').textContent = lang === 'ru' ? '🌐 RU' : '🌐 EN';
347
+
348
  if (state.activeChannel) {
349
  const chan = state.channels.find(c => c.id === state.activeChannel);
350
+ if (chan) els.messageInput.placeholder = `${t('msgPlaceholder')}${chan.name}`;
 
 
351
  }
352
  }
353
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
  function copyToClipboard(elementId) {
355
  const text = document.getElementById(elementId).innerText;
356
+ const ta = document.createElement("textarea"); ta.value = text; document.body.appendChild(ta);
357
+ ta.select(); document.execCommand('copy'); document.body.removeChild(ta);
358
+ alert(t('copySuccess'));
359
+ }
360
+
361
+ function stringToColor(str) {
362
+ let hash = 0; for (let i = 0; i < str.length; i++) hash = str.charCodeAt(i) + ((hash << 5) - hash);
363
+ const c = (hash & 0x00FFFFFF).toString(16).toUpperCase(); return '#' + '00000'.substring(0, 6 - c.length) + c;
364
+ }
365
+
366
+ function getInitials(name) { return (name || '?').substring(0, 2).toUpperCase(); }
367
+
368
+ function createAvatarEl(user, sizeClass = '') {
369
+ const wrap = document.createElement('div');
370
+ wrap.style.position = 'relative'; wrap.style.display = 'inline-block';
371
+
372
+ const av = document.createElement('div');
373
+ av.className = `avatar ${sizeClass}`;
374
+ if (user && user.avatar_url) {
375
+ av.style.backgroundImage = `url('${user.avatar_url}')`;
376
+ av.style.backgroundSize = 'cover'; av.style.backgroundPosition = 'center'; av.style.color = 'transparent';
377
+ } else {
378
+ av.style.backgroundColor = stringToColor(user ? user.username : '?');
379
+ av.textContent = getInitials(user ? user.username : '?');
380
+ }
381
+ wrap.appendChild(av);
382
+
383
+ if (user && 'is_online' in user) {
384
+ const dot = document.createElement('div');
385
+ dot.className = `status-dot ${user.is_online ? '' : 'offline'}`;
386
+ dot.style.position = 'absolute'; dot.style.bottom = '0'; dot.style.right = '0';
387
+ wrap.appendChild(dot);
388
  }
389
+ return wrap;
390
+ }
391
+
392
+ function parseMarkdown(text) {
393
+ let html = text.replace(/</g, '&lt;').replace(/>/g, '&gt;');
394
+ html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
395
+ html = html.replace(/\*(.*?)\*/g, '<em>$1</em>');
396
+ html = html.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>');
397
+ html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
398
+ return html;
399
  }
400
 
401
  class SupabaseREST {
402
  constructor(url, apiKey) {
403
  this.baseUrl = url.replace(/\/$/, '') + '/rest/v1';
404
+ this.headers = { 'Content-Type': 'application/json', 'Prefer': 'return=representation', 'apikey': apiKey, 'Authorization': `Bearer ${apiKey}` };
 
 
 
 
 
405
  }
406
 
407
+ async fetchApi(endpoint, options = {}) {
408
+ options.headers = { ...this.headers, ...options.headers };
409
+ const res = await fetch(`${this.baseUrl}${endpoint}`, options);
410
+ if (!res.ok) throw new Error(`API Error: ${res.status}`);
411
+ return res.json();
 
 
 
 
 
 
 
 
 
 
 
 
412
  }
413
 
414
+ async login(username, password) {
415
+ const data = await this.fetchApi(`/app_users?username=eq.${encodeURIComponent(username)}&password=eq.${encodeURIComponent(password)}&select=*`);
416
+ if (!data.length) throw new Error(t('errInvalidLogin'));
417
+ return data[0];
 
 
 
 
418
  }
419
 
420
+ async getUserById(id) {
421
+ const data = await this.fetchApi(`/app_users?id=eq.${id}&select=*`);
422
+ return data.length ? data[0] : null;
 
423
  }
424
 
425
+ async setOnlineStatus(userId, isOnline) {
426
+ try { await this.fetchApi(`/app_users?id=eq.${userId}`, { method: 'PATCH', body: JSON.stringify({ is_online: isOnline, last_seen: new Date().toISOString() }) }); } catch(e){}
 
 
427
  }
428
 
429
+ async updateProfile(userId, updates) {
430
+ return await this.fetchApi(`/app_users?id=eq.${userId}`, { method: 'PATCH', body: JSON.stringify(updates) });
 
 
431
  }
432
 
433
+ async getChannels(groupId) {
434
+ const filter = groupId ? `or=(group_id.is.null,group_id.eq.${groupId})` : `group_id=is.null`;
435
+ return await this.fetchApi(`/channels?select=*&${filter}&order=created_at.asc`);
 
 
 
 
 
436
  }
437
 
438
+ async getUsers() { return await this.fetchApi(`/app_users?select=id,username,is_online,avatar_url,group_id`); }
439
+
440
+ async getMessages(channelId) { return await this.fetchApi(`/messages?channel_id=eq.${channelId}&select=*,app_users(username,avatar_url)&order=created_at.asc`); }
441
+
442
+ async sendMessage(channelId, userId, content) {
443
+ return await this.fetchApi(`/messages`, { method: 'POST', body: JSON.stringify({ channel_id: channelId, user_id: userId, content: content }) });
 
 
444
  }
445
  }
 
446
  let db = null;
447
 
448
+ function saveSession(user) {
449
+ localStorage.setItem('supa_session', JSON.stringify({ userId: user.id, url: state.projectUrl, key: state.apiKey }));
 
 
 
 
 
 
 
 
450
  }
 
 
 
 
 
 
 
 
 
 
 
451
 
452
+ function clearSession() { localStorage.removeItem('supa_session'); }
453
+
454
+ async function attemptAutoLogin() {
455
+ const sess = localStorage.getItem('supa_session');
456
+ if (sess) {
457
+ try {
458
+ els.loginError.textContent = t('errRestoring');
459
+ const parsed = JSON.parse(sess);
460
+ state.projectUrl = parsed.url; state.apiKey = parsed.key;
461
+ document.getElementById('cfg-project-url').value = state.projectUrl;
462
+ document.getElementById('cfg-api-key').value = state.apiKey;
463
+ db = new SupabaseREST(parsed.url, parsed.key);
464
+ const user = await db.getUserById(parsed.userId);
465
+ if (user) await completeLogin(user);
466
+ else throw new Error("User not found");
467
+ } catch(e) {
468
+ clearSession(); els.loginError.textContent = '';
469
+ }
470
+ }
471
  }
472
 
473
  function renderChannels() {
474
  els.channelsList.innerHTML = '';
475
+ state.channels.forEach(ch => {
476
  const div = document.createElement('div');
477
+ div.className = `channel-item ${state.activeChannel === ch.id ? 'active' : ''}`;
478
+ div.innerHTML = `<span style="flex:1; overflow:hidden; text-overflow:ellipsis;">${ch.name}</span>`;
479
+ div.onclick = () => { selectChannel(ch); closeMobileMenus(); };
480
  els.channelsList.appendChild(div);
481
  });
482
  }
483
 
484
  function renderMembers() {
485
  els.membersContainer.innerHTML = '';
486
+ const sorted = Array.from(state.users.values()).sort((a,b) => (a.is_online === b.is_online ? a.username.localeCompare(b.username) : (a.is_online?-1:1)));
487
+ sorted.forEach(u => {
 
 
 
 
 
488
  const div = document.createElement('div');
489
  div.className = 'member-item';
490
+ div.appendChild(createAvatarEl(u, 'member-avatar'));
 
 
 
 
 
 
 
 
491
  const name = document.createElement('span');
492
+ name.textContent = u.username; name.style.color = u.is_online ? 'var(--text-primary)' : 'var(--text-secondary)';
493
+ name.style.overflow = 'hidden'; name.style.textOverflow = 'ellipsis';
 
 
 
494
  div.appendChild(name);
495
  els.membersContainer.appendChild(div);
496
  });
497
  }
498
 
499
  function renderMessages() {
500
+ const wasScrolledToBottom = els.messagesContainer.scrollHeight - els.messagesContainer.scrollTop <= els.messagesContainer.clientHeight + 50;
501
  els.messagesContainer.innerHTML = '';
502
  state.messages.forEach(msg => {
503
+ const div = document.createElement('div'); div.className = 'message';
504
+ const userObj = msg.app_users || state.users.get(msg.user_id) || { username: 'Unknown' };
 
505
 
506
+ div.appendChild(createAvatarEl(userObj));
507
 
508
+ const wrap = document.createElement('div'); wrap.style.flex = '1'; wrap.style.minWidth = '0';
509
+ const head = document.createElement('div'); head.className = 'message-header';
510
+ head.innerHTML = `<span class="message-author">${userObj.username}</span><span class="message-time">${new Date(msg.created_at).toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'})}</span>`;
 
511
 
512
+ const content = document.createElement('div'); content.className = 'message-content';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
513
  content.innerHTML = parseMarkdown(msg.content);
514
 
515
+ wrap.appendChild(head); wrap.appendChild(content); div.appendChild(wrap);
 
 
 
 
516
  els.messagesContainer.appendChild(div);
517
  });
518
+ if (wasScrolledToBottom) els.messagesContainer.scrollTop = els.messagesContainer.scrollHeight;
519
  }
520
 
 
 
521
  async function selectChannel(channel) {
522
  state.activeChannel = channel.id;
523
  els.currentChannelName.textContent = `#${channel.name}`;
524
+ els.messageInput.placeholder = `${t('msgPlaceholder')}${channel.name}`;
525
+ els.messageInput.disabled = false; els.sendBtn.disabled = false;
 
 
526
  renderChannels();
527
+ try { state.messages = await db.getMessages(channel.id); renderMessages(); els.messagesContainer.scrollTop = els.messagesContainer.scrollHeight; }
528
+ catch(e) { state.messages=[]; renderMessages(); }
 
 
 
 
 
 
 
529
  }
530
 
531
  async function loadInitialData() {
532
+ const usersData = await db.getUsers();
533
+ state.users.clear(); usersData.forEach(u => state.users.set(u.id, u)); renderMembers();
534
+ state.channels = await db.getChannels(state.currentUser.group_id); renderChannels();
535
+ if (state.channels.length > 0) selectChannel(state.channels[0]);
 
 
 
 
 
 
 
 
 
 
 
 
536
  }
537
 
 
538
  let pollInterval;
539
  function startPolling() {
540
  pollInterval = setInterval(async () => {
541
+ if(!state.currentUser) return;
 
542
  try {
543
+ const uData = await db.getUsers();
544
+ let mChanged = false;
545
+ uData.forEach(u => { const ex = state.users.get(u.id); if(!ex || ex.is_online!==u.is_online || ex.avatar_url!==u.avatar_url) mChanged = true; state.users.set(u.id, u); });
546
+ if(mChanged) renderMembers();
547
+
548
+ const cData = await db.getChannels(state.currentUser.group_id);
549
+ if(cData.length !== state.channels.length) { state.channels = cData; renderChannels(); }
 
 
 
 
 
 
 
 
 
 
 
550
 
551
+ if(state.activeChannel) {
552
+ const msgData = await db.getMessages(state.activeChannel);
553
+ if(msgData.length !== state.messages.length) { state.messages = msgData; renderMessages(); }
 
 
 
 
554
  }
555
+ } catch(e) {}
556
+ }, 3000);
 
 
557
  }
558
 
559
+ async function completeLogin(user) {
560
+ state.currentUser = user;
561
+ saveSession(user);
562
+ await db.setOnlineStatus(user.id, true);
563
+
564
+ els.currentUsername.textContent = user.username;
565
+ const avContainer = document.getElementById('user-profile-avatar-container');
566
+ avContainer.innerHTML = ''; avContainer.appendChild(createAvatarEl(user, 'member-avatar'));
567
+ document.getElementById('profile-avatar-url').value = user.avatar_url || '';
568
 
569
+ els.loginScreen.classList.add('hidden'); els.appScreen.classList.remove('hidden');
570
+ await loadInitialData(); startPolling();
571
+ }
 
 
572
 
573
  els.loginForm.addEventListener('submit', async (e) => {
574
  e.preventDefault();
575
+ state.projectUrl = document.getElementById('cfg-project-url').value.trim();
576
+ state.apiKey = document.getElementById('cfg-api-key').value.trim();
577
+ db = new SupabaseREST(state.projectUrl, state.apiKey);
578
+ els.loginError.textContent = 'Connecting...';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
579
  try {
580
+ const user = await db.login(document.getElementById('username').value.trim(), document.getElementById('password').value.trim());
581
+ await completeLogin(user);
582
+ } catch(e) { els.loginError.textContent = e.message; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
583
  });
584
 
585
+ els.messageForm.addEventListener('submit', async (e) => {
586
+ e.preventDefault();
587
+ if(!state.activeChannel || !state.currentUser) return;
588
+ const text = els.messageInput.value.trim(); if(!text) return;
589
+ els.messageInput.value = '';
590
+ try {
591
+ await db.sendMessage(state.activeChannel, state.currentUser.id, text);
592
+ state.messages = await db.getMessages(state.activeChannel); renderMessages();
593
+ }
594
+ catch(e) { els.messageInput.value = text; console.error(e); }
595
  });
596
 
597
+ document.getElementById('open-profile-btn').onclick = () => els.profileModal.classList.remove('hidden');
598
+
599
+ document.getElementById('profile-form').onsubmit = async (e) => {
600
  e.preventDefault();
601
+ const newUrl = document.getElementById('profile-avatar-url').value.trim();
602
+ try {
603
+ await db.updateProfile(state.currentUser.id, { avatar_url: newUrl });
604
+ state.currentUser.avatar_url = newUrl;
605
+ const avContainer = document.getElementById('user-profile-avatar-container');
606
+ avContainer.innerHTML = ''; avContainer.appendChild(createAvatarEl(state.currentUser, 'member-avatar'));
607
+ els.profileModal.classList.add('hidden');
608
+ } catch(e) { document.getElementById('profile-error').textContent = 'Error saving profile.'; }
609
+ };
610
 
611
+ async function doLogout() {
612
+ if(state.currentUser && db) await db.setOnlineStatus(state.currentUser.id, false);
613
+ clearInterval(pollInterval); clearSession(); state.currentUser = null;
614
+ els.profileModal.classList.add('hidden'); els.appScreen.classList.add('hidden'); els.loginScreen.classList.remove('hidden');
615
+ document.getElementById('password').value = '';
616
+ }
617
+ document.getElementById('logout-btn').onclick = doLogout;
618
+ window.addEventListener('beforeunload', () => { if(state.currentUser && db) db.setOnlineStatus(state.currentUser.id, false); });
619
 
620
+ function toggleMobileMenu(menuId) {
621
+ els.mobileOverlay.classList.remove('hidden');
622
+ document.getElementById(menuId).classList.add('show');
623
+ }
624
+ function closeMobileMenus() {
625
+ els.mobileOverlay.classList.add('hidden');
626
+ els.sidebar.classList.remove('show'); els.membersList.classList.remove('show');
627
+ }
628
+ document.getElementById('open-sidebar-btn').onclick = () => toggleMobileMenu('sidebar');
629
+ document.getElementById('open-members-btn').onclick = () => toggleMobileMenu('members-list');
630
+ document.getElementById('close-sidebar-btn').onclick = closeMobileMenus;
631
+ document.getElementById('close-members-btn').onclick = closeMobileMenus;
632
+ els.mobileOverlay.onclick = closeMobileMenus;
633
 
634
+ document.getElementById('show-setup-btn').onclick = () => els.setupModal.classList.remove('hidden');
635
+ document.getElementById('lang-btn').onclick = () => setLanguage(state.lang === 'ru' ? 'en' : 'ru');
 
 
 
 
 
 
 
 
636
 
637
+ const sqlNew = `
638
+ CREATE TABLE IF NOT EXISTS public.groups ( id UUID DEFAULT gen_random_uuid() PRIMARY KEY, name TEXT UNIQUE NOT NULL );
 
639
  CREATE TABLE IF NOT EXISTS public.app_users (
640
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
641
+ username TEXT UNIQUE NOT NULL, password TEXT NOT NULL,
642
+ is_online BOOLEAN DEFAULT false, last_seen TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
643
+ avatar_url TEXT, group_id UUID REFERENCES public.groups(id) ON DELETE SET NULL
 
644
  );
 
 
645
  CREATE TABLE IF NOT EXISTS public.channels (
646
+ id UUID DEFAULT gen_random_uuid() PRIMARY KEY, name TEXT UNIQUE NOT NULL,
647
+ group_id UUID REFERENCES public.groups(id) ON DELETE CASCADE,
648
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
649
  );
 
 
650
  CREATE TABLE IF NOT EXISTS public.messages (
651
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
652
  channel_id UUID REFERENCES public.channels(id) ON DELETE CASCADE,
653
  user_id UUID REFERENCES public.app_users(id) ON DELETE CASCADE,
654
+ content TEXT NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
 
655
  );
656
+ INSERT INTO public.channels (name) VALUES ('general'), ('random') ON CONFLICT DO NOTHING;
 
657
  ALTER TABLE public.app_users ENABLE ROW LEVEL SECURITY;
658
  ALTER TABLE public.channels ENABLE ROW LEVEL SECURITY;
659
  ALTER TABLE public.messages ENABLE ROW LEVEL SECURITY;
660
+ CREATE POLICY "Allow ALL channels" ON public.channels FOR ALL TO anon USING (true) WITH CHECK (true);
661
+ CREATE POLICY "Allow ALL messages" ON public.messages FOR ALL TO anon USING (true) WITH CHECK (true);
662
+ CREATE POLICY "Allow ALL users" ON public.app_users FOR ALL TO anon USING (true) WITH CHECK (true);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
663
  GRANT USAGE ON SCHEMA public TO anon, authenticated;
664
  GRANT ALL ON ALL TABLES IN SCHEMA public TO anon, authenticated;
 
665
  `.trim();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
666
 
667
+ const sqlMig = `
668
+ CREATE TABLE IF NOT EXISTS public.groups ( id UUID DEFAULT gen_random_uuid() PRIMARY KEY, name TEXT UNIQUE NOT NULL );
669
+ ALTER TABLE public.app_users ADD COLUMN IF NOT EXISTS avatar_url TEXT;
670
+ ALTER TABLE public.app_users ADD COLUMN IF NOT EXISTS group_id UUID REFERENCES public.groups(id) ON DELETE SET NULL;
671
+ ALTER TABLE public.channels ADD COLUMN IF NOT EXISTS group_id UUID REFERENCES public.groups(id) ON DELETE CASCADE;
672
+ `.trim();
673
 
674
+ document.getElementById('sql-new').textContent = sqlNew;
675
+ document.getElementById('sql-mig').textContent = sqlMig;
 
 
 
676
 
677
+ // Init
678
  setLanguage('ru');
679
+ attemptAutoLogin();
680
 
681
  </script>
682
  </body>