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
 
 
 
 
 
 
 
505f014
 
 
 
eb8712a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505f014
 
 
 
eb8712a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505f014
eb8712a
 
 
 
 
505f014
 
 
 
eb8712a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505f014
 
 
 
eb8712a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505f014
 
 
eb8712a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505f014
 
 
eb8712a
 
 
 
 
 
 
 
 
 
505f014
 
 
eb8712a
 
 
505f014
 
 
eb8712a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505f014
 
 
 
 
 
 
 
 
 
eb8712a
505f014
eb8712a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505f014
 
eb8712a
505f014
 
eb8712a
 
 
505f014
eb8712a
 
 
 
505f014
 
eb8712a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
// Application state
let appState = {
    jobs: [],
    currentUser: null,
    favorites: [],
    userJobs: [],
    notifications: [],
    messages: [],
    currentView: 'home'
};

// DOM elements
const elements = {
    // Views
    homeView: document.getElementById('home-view'),
    allJobsView: document.getElementById('all-jobs-view'),
    favoritesView: document.getElementById('favorites-view'),
    employersView: document.getElementById('employers-view'),
    postJobView: document.getElementById('post-job-view'),

    // Job containers
    jobCards: document.getElementById('job-cards'),
    allJobsCards: document.getElementById('all-jobs-cards'),
    favoritesCards: document.getElementById('favorites-cards'),
    employerJobsCards: document.getElementById('employer-jobs-cards'),

    // Empty states
    emptyFavorites: document.getElementById('empty-favorites'),
    emptyEmployerJobs: document.getElementById('empty-employer-jobs'),

    // Notifications and messages
    notificationsView: document.getElementById('notifications-view'),
    notificationsContainer: document.getElementById('notifications-container'),
    emptyNotifications: document.getElementById('empty-notifications'),
    messagesView: document.getElementById('messages-view'),
    messagesContainer: document.getElementById('messages-container'),
    emptyMessages: document.getElementById('empty-messages'),

    // Badges
    notificationBadge: document.getElementById('notification-badge'),
    messageBadge: document.getElementById('message-badge'),

    // Modals
    loginModal: document.getElementById('login-modal'),
    registerModal: document.getElementById('register-modal'),

    // Forms
    loginForm: document.getElementById('login-form'),
    registerForm: document.getElementById('register-form'),
    postJobForm: document.getElementById('post-job-form'),

    // Toast
    toast: document.getElementById('toast'),
    toastMessage: document.getElementById('toast-message'),

    // Counters
    jobsCount: document.getElementById('jobs-count'),
    favoritesCount: document.getElementById('favorites-count')
};

// Load data from localStorage on initialization
async function loadFromLocalStorage() {
    try {
        // Restore favorites
        const savedFavorites = localStorage.getItem('jobHubFavorites');
        if (savedFavorites) {
            appState.favorites = JSON.parse(savedFavorites);
        }

        // Restore user jobs
        const savedUserJobs = localStorage.getItem('jobHubUserJobs');
        if (savedUserJobs) {
            appState.userJobs = JSON.parse(savedUserJobs);
        }

        // Restore notifications
        const savedNotifications = localStorage.getItem('jobHubNotifications');
        if (savedNotifications) {
            appState.notifications = JSON.parse(savedNotifications);
        }

        // Restore messages
        const savedMessages = localStorage.getItem('jobHubMessages');
        if (savedMessages) {
            appState.messages = JSON.parse(savedMessages);
        }

        // Restore current user
        const savedUser = localStorage.getItem('jobHubCurrentUser');
        if (savedUser) {
            appState.currentUser = JSON.parse(savedUser);

            // If user exists, reload their data from server
            if (appState.currentUser && appState.currentUser.id) {
                await loadUserFavorites(appState.currentUser.id);
                if (appState.currentUser.type === 'employer') {
                    await loadUserJobs(appState.currentUser.id);
                }
                // Load notifications and messages from server
                await loadUserNotifications(appState.currentUser.id);
                await loadUserMessages(appState.currentUser.id);
            }
        }

        console.log('Data loaded from localStorage');
    } catch (error) {
        console.error('Error loading from localStorage:', error);
    }
}

// Save data to localStorage
function saveToLocalStorage() {
    try {
        localStorage.setItem('jobHubFavorites', JSON.stringify(appState.favorites));
        localStorage.setItem('jobHubUserJobs', JSON.stringify(appState.userJobs));
        localStorage.setItem('jobHubNotifications', JSON.stringify(appState.notifications));
        localStorage.setItem('jobHubMessages', JSON.stringify(appState.messages));

        if (appState.currentUser) {
            localStorage.setItem('jobHubCurrentUser', JSON.stringify(appState.currentUser));
        } else {
            localStorage.removeItem('jobHubCurrentUser');
        }

        console.log('Data saved to localStorage');
    } catch (error) {
        console.error('Error saving to localStorage:', error);
    }
}

// Initialize the app
async function initApp() {
    await loadJobsFromServer();
    updateCounters();
    updateNotificationBadge();
    updateMessageBadge();
    switchView('home');
    updateAuthButtons();

    // If user is logged in, make sure their data is properly loaded
    if (appState.currentUser) {
        if (appState.currentUser.id) {
            await loadUserFavorites(appState.currentUser.id);
            if (appState.currentUser.type === 'employer') {
                await loadUserJobs(appState.currentUser.id);
            }
        }
    }
}

// Load jobs from server
async function loadJobsFromServer() {
    try {
        const response = await fetch('/api/jobs');
        if (response.ok) {
            appState.jobs = await response.json();
        } else {
            console.error('Failed to load jobs from server');
            // Fallback to sample data if server is not available
            appState.jobs = getSampleJobs();
        }
    } catch (error) {
        console.error('Error loading jobs:', error);
        appState.jobs = getSampleJobs();
    }
}

// Get sample jobs for fallback
function getSampleJobs() {
    return [
        {
            id: 1,
            title: "Senior Frontend Разработчик",
            company: "TechNova",
            location: "Москва",
            salary: "180 000 - 250 000 ₽",
            description: "Требуется опытный frontend разработчик для работы с современным стеком: React, TypeScript, Next.js. Опыт работы от 5 лет, знание Redux, GraphQL будет плюсом.",
            tags: ["React", "TypeScript", "Next.js", "Redux", "GraphQL"],
            type: "full-time"
        },
        {
            id: 2,
            title: "Backend Разработчик (Node.js)",
            company: "CloudSolutions",
            location: "Санкт-Петербург",
            salary: "200 000 - 280 000 ₽",
            description: "Ищем backend разработчика с опытом работы с Node.js, Express и микросервисной архитектурой. Знание Docker, Kubernetes и AWS обязательно.",
            tags: ["Node.js", "Express", "Docker", "Kubernetes", "AWS"],
            type: "full-time"
        },
        {
            id: 3,
            title: "Full Stack Разработчик",
            company: "DigitalAgency Pro",
            location: "Екатеринбург",
            salary: "150 000 - 220 000 ₽",
            description: "Нужен full stack разработчик для работы над веб-приложениями. Опыт с React и Node.js обязателен. Знание TypeScript будет преимуществом.",
            tags: ["React", "Node.js", "TypeScript", "Full Stack"],
            type: "full-time"
        },
        {
            id: 4,
            title: "Python Разработчик (ML)",
            company: "DataScience Inc",
            location: "Новосибирск",
            salary: "160 000 - 240 000 ₽",
            description: "Требуется Python разработчик для работы с данными и машинным обучением. Опыт с Django/Flask, TensorFlow/PyTorch обязателен.",
            tags: ["Python", "Django", "Machine Learning", "TensorFlow"],
            type: "full-time"
        },
        {
            id: 5,
            title: "DevOps Инженер",
            company: "CloudTech",
            location: "Казань",
            salary: "220 000 - 300 000 ₽",
            description: "Ищем DevOps инженера с опытом работы с AWS, Kubernetes и CI/CD. Знание Terraform и Ansible будет плюсом.",
            tags: ["DevOps", "AWS", "Kubernetes", "CI/CD"],
            type: "full-time"
        },
        {
            id: 6,
            title: "UI/UX Дизайнер",
            company: "CreativeMinds",
            location: "Москва",
            salary: "120 000 - 180 000 ₽",
            description: "Требуется UI/UX дизайнер для создания пользовательских интерфейсов. Опыт с Figma, Adobe XD обязателен.",
            tags: ["UI/UX", "Figma", "Adobe XD", "Design"],
            type: "full-time"
        }
    ];
}

// Display jobs
function displayJobs(jobs, container) {
    container.innerHTML = '';

    if (jobs.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <div class="empty-state-icon">🔍</div>
                <h3>Вакансий не найдено</h3>
                <p>Попробуйте изменить параметры поиска</p>
            </div>
        `;
        return;
    }

    jobs.forEach(job => {
        const jobCard = document.createElement('div');
        jobCard.className = 'job-card';
        
        // Check if job is favorited
        const isFavorited = appState.favorites.some(fav => fav.id === job.id);
        
        jobCard.innerHTML = `
            <div class="job-card-header">
                <div>
                    <h3 class="job-title">${job.title}</h3>
                    <div class="job-company">${job.company}</div>
                </div>
            </div>
            <div class="job-meta">
                <div class="job-location">${job.location}</div>
                <div class="job-salary">${job.salary}</div>
            </div>
            <p class="job-description">${job.description}</p>
            <div class="job-tags">
                ${job.tags.map(tag => `<span class="job-tag">${tag}</span>`).join('')}
            </div>
            <div class="job-actions">
                <button class="btn-favorite ${isFavorited ? 'active' : ''}" onclick="toggleFavorite(${job.id})">
                    ${isFavorited ? '❤️' : '🤍'} В избранное
                </button>
                <button class="btn-apply" onclick="applyForJob(${job.id})">Откликнуться</button>
            </div>
        `;
        container.appendChild(jobCard);
    });
}

// Switch between views
function switchView(view) {
    // Hide all views
    document.querySelectorAll('.view').forEach(v => v.classList.add('hidden'));
    document.querySelectorAll('nav a').forEach(a => a.classList.remove('active'));

    // Show selected view
    const viewElement = document.getElementById(`${view}-view`);
    if (viewElement) {
        viewElement.classList.remove('hidden');
        appState.currentView = view;

        // Update active nav link
        const navLink = document.querySelector(`nav a[onclick="switchView('${view}')"]`);
        if (navLink) {
            navLink.classList.add('active');
        }

        // Handle specific view logic
        switch (view) {
            case 'home':
                displayJobs(appState.jobs.slice(0, 6), elements.jobCards);
                break;
            case 'all-jobs':
                displayJobs(appState.jobs, elements.allJobsCards);
                elements.jobsCount.textContent = `${appState.jobs.length} вакансий`;
                break;
            case 'favorites':
                displayFavorites();
                break;
            case 'notifications':
                displayNotifications();
                break;
            case 'messages':
                displayMessages();
                break;
            case 'employers':
                displayEmployerJobs();
                break;
            case 'post-job':
                // Clear form
                elements.postJobForm.reset();
                break;
        }
    }
}

// Filter jobs based on search criteria
function filterJobs() {
    const jobSearchTerm = document.getElementById('job-search').value.trim().toLowerCase();
    const locationSearchTerm = document.getElementById('location-search').value.trim().toLowerCase();

    let filteredJobs = appState.jobs;

    // Filter by job title, description, or tags if search term is provided
    if (jobSearchTerm) {
        filteredJobs = filteredJobs.filter(job => {
            return job.title.toLowerCase().includes(jobSearchTerm) ||
                   job.description.toLowerCase().includes(jobSearchTerm) ||
                   job.tags.some(tag => tag.toLowerCase().includes(jobSearchTerm));
        });
    }

    // Filter by location if location term is provided
    if (locationSearchTerm) {
        filteredJobs = filteredJobs.filter(job => {
            return job.location.toLowerCase().includes(locationSearchTerm);
        });
    }

    // Sort results by relevance (prioritize matches in title)
    filteredJobs.sort((a, b) => {
        const aTitleMatch = a.title.toLowerCase().includes(jobSearchTerm);
        const bTitleMatch = b.title.toLowerCase().includes(jobSearchTerm);
        
        if (aTitleMatch && !bTitleMatch) return -1;
        if (!aTitleMatch && bTitleMatch) return 1;
        return 0;
    });

    if (appState.currentView === 'home') {
        displayJobs(filteredJobs.slice(0, 6), elements.jobCards);
    } else if (appState.currentView === 'all-jobs') {
        displayJobs(filteredJobs, elements.allJobsCards);
        elements.jobsCount.textContent = `${filteredJobs.length} вакансий`;
    }
}

// Advanced search functionality
function advancedFilterJobs(filters) {
    let filteredJobs = appState.jobs;

    // Apply keyword filter
    if (filters.keyword) {
        const keyword = filters.keyword.toLowerCase();
        filteredJobs = filteredJobs.filter(job => {
            return job.title.toLowerCase().includes(keyword) ||
                   job.description.toLowerCase().includes(keyword) ||
                   job.tags.some(tag => tag.toLowerCase().includes(keyword));
        });
    }

    // Apply location filter
    if (filters.location) {
        const location = filters.location.toLowerCase();
        filteredJobs = filteredJobs.filter(job => {
            return job.location.toLowerCase().includes(location);
        });
    }

    // Apply salary range filter
    if (filters.minSalary || filters.maxSalary) {
        filteredJobs = filteredJobs.filter(job => {
            // Extract numeric salary values for comparison
            const salaryText = job.salary.replace(/[^\d\s]/g, '').trim();
            if (!salaryText) return true; // If no salary info, include by default
            
            const salaryNumbers = salaryText.match(/\d+/g);
            if (!salaryNumbers) return true;
            
            const avgSalary = salaryNumbers.reduce((sum, num) => sum + parseInt(num), 0) / salaryNumbers.length;
            
            if (filters.minSalary && avgSalary < filters.minSalary) return false;
            if (filters.maxSalary && avgSalary > filters.maxSalary) return false;
            
            return true;
        });
    }

    // Apply job type filter
    if (filters.jobType && filters.jobType !== 'all') {
        filteredJobs = filteredJobs.filter(job => job.type === filters.jobType);
    }

    // Apply tags filter
    if (filters.tags && filters.tags.length > 0) {
        filteredJobs = filteredJobs.filter(job => {
            return filters.tags.every(tag => 
                job.tags.some(jobTag => 
                    jobTag.toLowerCase().includes(tag.toLowerCase())
                )
            );
        });
    }

    // Sort results by relevance
    if (filters.keyword) {
        filteredJobs.sort((a, b) => {
            const keyword = filters.keyword.toLowerCase();
            const aTitleMatch = a.title.toLowerCase().includes(keyword);
            const bTitleMatch = b.title.toLowerCase().includes(keyword);
            
            if (aTitleMatch && !bTitleMatch) return -1;
            if (!aTitleMatch && bTitleMatch) return 1;
            return 0;
        });
    }

    return filteredJobs;
}

// Debounced search function to improve performance
let searchTimeout;
function debouncedSearch() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => {
        filterJobs();
    }, 300); // Wait 300ms after user stops typing
}

// Display favorites
function displayFavorites() {
    if (appState.favorites.length === 0) {
        elements.favoritesCards.innerHTML = '';
        elements.emptyFavorites.classList.remove('hidden');
    } else {
        elements.emptyFavorites.classList.add('hidden');
        displayJobs(appState.favorites, elements.favoritesCards);
    }
    updateCounters();
}

// Display notifications
async function displayNotifications() {
    // Load notifications from server if user is logged in
    if (appState.currentUser && appState.currentUser.id) {
        try {
            const response = await fetch(`/api/users/${appState.currentUser.id}/notifications`);
            if (response.ok) {
                const serverNotifications = await response.json();
                // Update local state with server data
                appState.notifications = serverNotifications.map(n => ({
                    id: n.id,
                    title: n.title,
                    text: n.text,
                    icon: n.icon,
                    timestamp: n.created_at,
                    read: n.read_status
                }));
            }
        } catch (error) {
            console.error('Error loading notifications from server:', error);
        }
    }

    elements.notificationsContainer.innerHTML = '';

    if (appState.notifications.length === 0) {
        elements.emptyNotifications.classList.remove('hidden');
        return;
    }

    elements.emptyNotifications.classList.add('hidden');

    appState.notifications.forEach(notification => {
        const notificationItem = document.createElement('div');
        notificationItem.className = `notification-item ${!notification.read ? 'unread' : ''}`;
        
        notificationItem.innerHTML = `
            <div class="notification-icon">${notification.icon || '🔔'}</div>
            <div class="notification-content">
                <div class="notification-title">${notification.title}</div>
                <div class="notification-text">${notification.text}</div>
                <div class="notification-time">${formatTimeAgo(notification.timestamp)}</div>
            </div>
        `;
        
        // Mark as read when displayed
        if (!notification.read) {
            notification.read = true;
            updateNotificationBadge();
            
            // Update server as well
            if (appState.currentUser && appState.currentUser.id) {
                fetch(`/api/users/${appState.currentUser.id}/notifications/${notification.id}/read`, {
                    method: 'PUT'
                }).catch(console.error);
            }
        }
        
        elements.notificationsContainer.appendChild(notificationItem);
    });
}

// Display messages
async function displayMessages() {
    // Load messages from server if user is logged in
    if (appState.currentUser && appState.currentUser.id) {
        try {
            const response = await fetch(`/api/users/${appState.currentUser.id}/messages`);
            if (response.ok) {
                const serverMessages = await response.json();
                // Update local state with server data
                appState.messages = serverMessages.map(m => ({
                    id: m.id,
                    sender: {
                        name: m.sender_name || 'Unknown',
                        avatar: '👤'
                    },
                    content: m.content,
                    timestamp: m.created_at,
                    read: m.read_status
                }));
            }
        } catch (error) {
            console.error('Error loading messages from server:', error);
        }
    }

    elements.messagesContainer.innerHTML = '';

    if (appState.messages.length === 0) {
        elements.emptyMessages.classList.remove('hidden');
        return;
    }

    elements.emptyMessages.classList.add('hidden');

    appState.messages.forEach(message => {
        const messageItem = document.createElement('div');
        messageItem.className = `message-item ${!message.read ? 'unread' : ''}`;
        
        messageItem.innerHTML = `
            <div class="message-icon">${message.sender.avatar || '👤'}</div>
            <div class="message-content">
                <div class="message-title">${message.sender.name}</div>
                <div class="message-text">${message.content}</div>
                <div class="message-time">${formatTimeAgo(message.timestamp)}</div>
                <div class="message-actions">
                    <button class="btn btn-secondary" onclick="replyToMessage(${message.id})">Ответить</button>
                    <button class="btn btn-secondary" onclick="deleteMessage(${message.id})">Удалить</button>
                </div>
            </div>
        `;
        
        // Mark as read when displayed
        if (!message.read) {
            message.read = true;
            updateMessageBadge();
            
            // Update server as well
            if (appState.currentUser && appState.currentUser.id) {
                fetch(`/api/users/${appState.currentUser.id}/messages/${message.id}/read`, {
                    method: 'PUT'
                }).catch(console.error);
            }
        }
        
        elements.messagesContainer.appendChild(messageItem);
    });
}

// Add notification
async function addNotification(title, text, icon = '🔔') {
    const notification = {
        id: Date.now(),
        title: title,
        text: text,
        icon: icon,
        timestamp: new Date().toISOString(),
        read: false
    };
    
    // Add to local state
    appState.notifications.unshift(notification);
    updateNotificationBadge();
    saveToLocalStorage();
    
    // Try to add to server if user is logged in
    if (appState.currentUser && appState.currentUser.id) {
        try {
            await fetch(`/api/users/${appState.currentUser.id}/notifications`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ title, text, icon })
            });
        } catch (error) {
            console.error('Error adding notification to server:', error);
        }
    }
    
    // Show toast notification as well
    showToast(text);
}

// Add message
async function addMessage(sender, content) {
    const message = {
        id: Date.now(),
        sender: sender,
        content: content,
        timestamp: new Date().toISOString(),
        read: false
    };
    
    appState.messages.unshift(message);
    updateMessageBadge();
    saveToLocalStorage();
    
    // Show notification about new message
    await addNotification('Новое сообщение', `Сообщение от ${sender.name}`, '💬');
}

// Format time ago
function formatTimeAgo(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const seconds = Math.floor((now - date) / 1000);
    
    if (seconds < 60) return 'только что';
    if (seconds < 3600) return `${Math.floor(seconds / 60)} мин назад`;
    if (seconds < 86400) return `${Math.floor(seconds / 3600)} ч назад`;
    return `${Math.floor(seconds / 86400)} дн назад`;
}

// Update notification badge
function updateNotificationBadge() {
    const unreadCount = appState.notifications.filter(n => !n.read).length;
    if (unreadCount > 0) {
        elements.notificationBadge.textContent = unreadCount;
        elements.notificationBadge.classList.remove('hidden');
    } else {
        elements.notificationBadge.classList.add('hidden');
    }
}

// Update message badge
function updateMessageBadge() {
    const unreadCount = appState.messages.filter(m => !m.read).length;
    if (unreadCount > 0) {
        elements.messageBadge.textContent = unreadCount;
        elements.messageBadge.classList.remove('hidden');
    } else {
        elements.messageBadge.classList.add('hidden');
    }
}

// Clear all notifications
async function clearNotifications() {
    appState.notifications = [];
    updateNotificationBadge();
    saveToLocalStorage();
    
    // Clear notifications on server if user is logged in
    if (appState.currentUser && appState.currentUser.id) {
        try {
            await fetch(`/api/users/${appState.currentUser.id}/notifications`, {
                method: 'DELETE'
            });
        } catch (error) {
            console.error('Error clearing notifications from server:', error);
        }
    }
    
    displayNotifications();
}

// Reply to message
function replyToMessage(messageId) {
    if (!appState.currentUser) {
        showToast('Для ответа на сообщение нужно авторизоваться');
        showLoginModal();
        return;
    }
    
    // For a real implementation, we would need to know who sent the original message
    // For now, we'll just allow sending a message to another user by ID
    const recipientId = prompt('Введите ID получателя (для тестирования используйте ID другого пользователя):');
    if (recipientId) {
        const reply = prompt('Введите ваш ответ:');
        if (reply) {
            sendMessageToUser(parseInt(recipientId), reply);
        }
    }
}

// Send message to user
async function sendMessageToUser(receiverId, content) {
    if (!appState.currentUser || !appState.currentUser.id) {
        showToast('Для отправки сообщения нужно авторизоваться');
        showLoginModal();
        return;
    }
    
    try {
        const response = await fetch('/api/messages', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                sender_id: appState.currentUser.id,
                receiver_id: receiverId,
                content: content
            })
        });
        
        if (response.ok) {
            showToast('Сообщение отправлено');
        } else {
            const errorData = await response.json();
            showToast(errorData.error || 'Ошибка отправки сообщения');
        }
    } catch (error) {
        console.error('Error sending message:', error);
        showToast('Ошибка отправки сообщения');
    }
}

// Delete message
async function deleteMessage(messageId) {
    appState.messages = appState.messages.filter(m => m.id !== messageId);
    updateMessageBadge();
    saveToLocalStorage();
    
    // Delete message on server if user is logged in
    if (appState.currentUser && appState.currentUser.id) {
        try {
            await fetch(`/api/users/${appState.currentUser.id}/messages/${messageId}`, {
                method: 'DELETE'
            });
        } catch (error) {
            console.error('Error deleting message from server:', error);
        }
    }
    
    displayMessages();
}

// Display employer's jobs
function displayEmployerJobs() {
    if (appState.userJobs.length === 0) {
        elements.employerJobsCards.innerHTML = '';
        elements.emptyEmployerJobs.classList.remove('hidden');
    } else {
        elements.emptyEmployerJobs.classList.add('hidden');
        displayJobs(appState.userJobs, elements.employerJobsCards);
    }
}

// Update counters
function updateCounters() {
    elements.favoritesCount.textContent = `${appState.favorites.length} избранных`;
}

// Show login modal
function showLoginModal() {
    elements.loginModal.classList.add('active');
}

// Hide login modal
function hideLoginModal() {
    elements.loginModal.classList.remove('active');
    elements.loginForm.reset();
}

// Show register modal
function showRegisterModal() {
    elements.registerModal.classList.add('active');
}

// Hide register modal
function hideRegisterModal() {
    elements.registerModal.classList.remove('active');
    elements.registerForm.reset();
}

// Handle login
async function handleLogin(e) {
    e.preventDefault();
    const email = document.getElementById('login-email').value;
    const password = document.getElementById('login-password').value;
    const userType = document.getElementById('login-type').value;

    // Simple validation
    if (!email || !password) {
        showToast('Пожалуйста, заполните все поля');
        return;
    }

    try {
        // Try to login via server API
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ email, password })
        });

        if (response.ok) {
            const userData = await response.json();
            appState.currentUser = {
                id: userData.id,
                name: userData.name,
                email: userData.email,
                type: userData.type
            };

            // Load user's favorites, jobs, notifications and messages
            await loadUserFavorites(userData.id);
            if (userData.type === 'employer') {
                await loadUserJobs(userData.id);
            }
            await loadUserNotifications(userData.id);
            await loadUserMessages(userData.id);

            hideLoginModal();
            showToast(`Добро пожаловать, ${appState.currentUser.name}!`);
            updateAuthButtons();
            saveToLocalStorage();
        } else {
            // Fallback to client-side login simulation
            appState.currentUser = {
                name: 'Пользователь',
                email: email,
                type: userType
            };

            hideLoginModal();
            showToast(`Добро пожаловать, ${appState.currentUser.name}!`);
            updateAuthButtons();
            saveToLocalStorage();
        }
    } catch (error) {
        console.error('Login error:', error);
        // Fallback to client-side login simulation
        appState.currentUser = {
            name: 'Пользователь',
            email: email,
            type: userType
        };

        hideLoginModal();
        showToast(`Добро пожаловать, ${appState.currentUser.name}!`);
        updateAuthButtons();
        saveToLocalStorage();
    }
}

// Load user favorites from server
async function loadUserFavorites(userId) {
    try {
        const response = await fetch(`/api/users/${userId}/favorites`);
        if (response.ok) {
            appState.favorites = await response.json();
        }
    } catch (error) {
        console.error('Error loading favorites:', error);
    }
}

// Load user jobs from server
async function loadUserJobs(userId) {
    try {
        const response = await fetch(`/api/users/${userId}/jobs`);
        if (response.ok) {
            appState.userJobs = await response.json();
        }
    } catch (error) {
        console.error('Error loading user jobs:', error);
    }
}

// Load user notifications from server
async function loadUserNotifications(userId) {
    try {
        const response = await fetch(`/api/users/${userId}/notifications`);
        if (response.ok) {
            const serverNotifications = await response.json();
            appState.notifications = serverNotifications.map(n => ({
                id: n.id,
                title: n.title,
                text: n.text,
                icon: n.icon,
                timestamp: n.created_at,
                read: n.read_status
            }));
            updateNotificationBadge();
        }
    } catch (error) {
        console.error('Error loading user notifications:', error);
    }
}

// Load user messages from server
async function loadUserMessages(userId) {
    try {
        const response = await fetch(`/api/users/${userId}/messages`);
        if (response.ok) {
            const serverMessages = await response.json();
            appState.messages = serverMessages.map(m => ({
                id: m.id,
                sender: {
                    name: m.sender_name || 'Unknown',
                    avatar: '👤'
                },
                content: m.content,
                timestamp: m.created_at,
                read: m.read_status
            }));
            updateMessageBadge();
        }
    } catch (error) {
        console.error('Error loading user messages:', error);
    }
}

// Handle registration
async function handleRegister(e) {
    e.preventDefault();
    const name = document.getElementById('register-name').value;
    const email = document.getElementById('register-email').value;
    const password = document.getElementById('register-password').value;
    const userType = document.getElementById('register-type').value;

    // Simple validation
    if (!name || !email || !password) {
        showToast('Пожалуйста, заполните все поля');
        return;
    }

    try {
        // Try to register via server API
        const response = await fetch('/api/users', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name, email, password, type: userType })
        });

        if (response.ok) {
            const userData = await response.json();
            appState.currentUser = {
                id: userData.id,
                name: userData.name,
                email: userData.email,
                type: userData.type
            };

            // Initialize empty notifications and messages arrays for new user
            appState.notifications = [];
            appState.messages = [];

            hideRegisterModal();
            showToast(`Регистрация успешна! Добро пожаловать, ${name}!`);
            updateAuthButtons();
            saveToLocalStorage();
        } else {
            const errorData = await response.json();
            showToast(errorData.error || 'Ошибка регистрации');
        }
    } catch (error) {
        console.error('Registration error:', error);
        // Fallback to client-side registration simulation
        appState.currentUser = {
            name: name,
            email: email,
            type: userType
        };

        // Initialize empty notifications and messages arrays for new user
        appState.notifications = [];
        appState.messages = [];

        hideRegisterModal();
        showToast(`Регистрация успешна! Добро пожаловать, ${name}!`);
        updateAuthButtons();
        saveToLocalStorage();
    }
}

// Handle post job
async function handlePostJob(e) {
    e.preventDefault();

    if (!appState.currentUser || appState.currentUser.type !== 'employer') {
        showToast('Только работодатели могут размещать вакансии');
        return;
    }

    const job = {
        title: document.getElementById('job-title').value,
        company: document.getElementById('job-company').value,
        location: document.getElementById('job-location').value,
        salary: document.getElementById('job-salary').value || 'По договоренности',
        description: document.getElementById('job-description').value,
        tags: document.getElementById('job-tags').value.split(',').map(tag => tag.trim()).filter(tag => tag),
        type: document.getElementById('job-type').value,
        user_id: appState.currentUser.id
    };

    try {
        // Try to post job via server API
        const response = await fetch('/api/jobs', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(job)
        });

        if (response.ok) {
            const newJob = await response.json();

            // Add to jobs and user jobs
            appState.jobs.unshift(newJob);
            appState.userJobs.unshift(newJob);

            showToast('Вакансия успешно размещена!');
            
            // Add notification about successful job posting
            addNotification('Вакансия опубликована', `Ваша вакансия "${job.title}" успешно опубликована`, '✅');
            
            elements.postJobForm.reset();
            switchView('employers');
            saveToLocalStorage();
        } else {
            const errorData = await response.json();
            showToast(errorData.error || 'Ошибка размещения вакансии');
        }
    } catch (error) {
        console.error('Error posting job:', error);
        // Fallback to client-side addition
        job.id = Date.now();
        job.created_at = new Date().toISOString();

        // Add to jobs and user jobs
        appState.jobs.unshift(job);
        appState.userJobs.unshift(job);

        showToast('Вакансия успешно размещена!');
        
        // Add notification about successful job posting
        addNotification('Вакансия опубликована', `Ваша вакансия "${job.title}" успешно опубликована`, '✅');
        
        elements.postJobForm.reset();
        switchView('employers');
        saveToLocalStorage();
    }
}

// Toggle favorite
async function toggleFavorite(jobId) {
    if (!appState.currentUser) {
        showToast('Для добавления в избранное нужно авторизоваться');
        showLoginModal();
        return;
    }

    const job = appState.jobs.find(j => j.id === jobId);
    if (!job) return;

    const isFavorite = appState.favorites.some(fav => fav.id === jobId);

    try {
        if (isFavorite) {
            // Remove from favorites via server API
            const response = await fetch(`/api/users/${appState.currentUser.id}/favorites/${jobId}`, {
                method: 'DELETE'
            });

            if (response.ok || response.status === 404) {
                appState.favorites = appState.favorites.filter(fav => fav.id !== jobId);
                showToast('Вакансия удалена из избранного');
                
                // Add notification
                addNotification('Избранное обновлено', `Вакансия "${job.title}" удалена из избранного`, '🗑️');
            } else {
                throw new Error('Failed to remove from favorites');
            }
        } else {
            // Add to favorites via server API
            const response = await fetch(`/api/users/${appState.currentUser.id}/favorites`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ jobId })
            });

            if (response.ok) {
                appState.favorites.push(job);
                showToast('Вакансия добавлена в избранное');
                
                // Add notification
                addNotification('Избранное обновлено', `Вакансия "${job.title}" добавлена в избранное`, '❤️');
            } else {
                throw new Error('Failed to add to favorites');
            }
        }
    } catch (error) {
        console.error('Favorite toggle error:', error);
        // Fallback to client-side toggle
        if (isFavorite) {
            appState.favorites = appState.favorites.filter(fav => fav.id !== jobId);
            showToast('Вакансия удалена из избранного');
            
            // Add notification
            addNotification('Избранное обновлено', `Вакансия "${job.title}" удалена из избранного`, '🗑️');
        } else {
            appState.favorites.push(job);
            showToast('Вакансия добавлена в избранное');
            
            // Add notification
            addNotification('Избранное обновлено', `Вакансия "${job.title}" добавлена в избранное`, '❤️');
        }
    }

    // Update UI
    if (appState.currentView === 'home') {
        displayJobs(appState.jobs.slice(0, 6), elements.jobCards);
    } else if (appState.currentView === 'all-jobs') {
        displayJobs(appState.jobs, elements.allJobsCards);
    } else if (appState.currentView === 'favorites') {
        displayFavorites();
    }
    updateCounters();
    saveToLocalStorage();
}

// Apply for job
function applyForJob(jobId) {
    if (!appState.currentUser) {
        showToast('Для отклика на вакансию нужно авторизоваться');
        showLoginModal();
        return;
    }

    const job = appState.jobs.find(j => j.id === jobId);
    if (job) {
        showToast('Ваш отклик отправлен работодателю!');
        
        // Add notification about job application
        addNotification('Отклик отправлен', `Ваш отклик на вакансию "${job.title}" отправлен работодателю`, '📤');
    } else {
        showToast('Ваш отклик отправлен работодателю!');
    }

    // Here would be the logic to actually submit an application
    // For now, we'll just show a success message and add a notification
}

// Update auth buttons
function updateAuthButtons() {
    const authButtons = document.getElementById('auth-buttons');
    if (appState.currentUser) {
        authButtons.innerHTML = `
            <div style="color: white; padding: 0.75rem 1.5rem;">
                Привет, ${appState.currentUser.name}! (${appState.currentUser.type === 'employer' ? 'Работодатель' : 'Соискатель'})
            </div>
            <button class="btn btn-secondary" onclick="handleLogout()">Выйти</button>
        `;
    } else {
        authButtons.innerHTML = `
            <button id="login-btn" class="btn btn-secondary" onclick="showLoginModal()">Войти</button>
            <button id="register-btn" class="btn btn-primary" onclick="showRegisterModal()">Регистрация</button>
        `;
    }
}

// Handle logout
function handleLogout() {
    appState.currentUser = null;
    appState.favorites = [];
    appState.userJobs = [];
    appState.notifications = [];
    appState.messages = [];
    updateAuthButtons();
    updateNotificationBadge();
    updateMessageBadge();
    showToast('Вы успешно вышли из аккаунта');
    switchView('home');
    saveToLocalStorage();

    // Also remove from localStorage
    localStorage.removeItem('jobHubCurrentUser');
    localStorage.removeItem('jobHubFavorites');
    localStorage.removeItem('jobHubUserJobs');
    localStorage.removeItem('jobHubNotifications');
    localStorage.removeItem('jobHubMessages');
}

// Show toast notification
function showToast(message) {
    elements.toastMessage.textContent = message;
    elements.toast.classList.add('active');

    setTimeout(() => {
        elements.toast.classList.remove('active');
    }, 3000);
}

// Initialize the app when DOM is loaded
document.addEventListener('DOMContentLoaded', async function() {
    await loadFromLocalStorage();
    await initApp();
    
    // Add event listeners for search inputs
    document.getElementById('job-search').addEventListener('input', debouncedSearch);
    document.getElementById('location-search').addEventListener('input', debouncedSearch);
    
    // Add event listeners for Enter key submission
    document.getElementById('job-search').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            filterJobs();
        }
    });

    document.getElementById('location-search').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            filterJobs();
        }
    });
});