File size: 5,933 Bytes
29e58e3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Main application JavaScript
class SingularityPortal {
    constructor() {
        this.apiBase = '/api';
        this.currentUser = null;
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.checkAuthStatus();
        this.loadInitialData();
    }

    setupEventListeners() {
        // Global event listeners
        document.addEventListener('keydown', this.handleKeyboardShortcuts.bind(this));
    }

    handleKeyboardShortcuts(event) {
        if (event.ctrlKey && event.key === 'k') {
            event.preventDefault();
            this.toggleAIAssistant();
        }
    }

    async checkAuthStatus() {
        try {
            const response = await fetch(`${this.apiBase}/auth/status`);
            if (response.ok) {
                this.currentUser = await response.json();
                this.updateUIForAuth();
            }
        } catch (error) {
            console.log('Auth check failed:', error);
        }
    }

    updateUIForAuth() {
        const authElements = document.querySelectorAll('[data-auth]');
        authElements.forEach(element => {
            const authType = element.getAttribute('data-auth');
            if (authType === 'required' && !this.currentUser) {
                element.style.display = 'none';
            } else if (authType === 'admin' && (!this.currentUser || !this.currentUser.isAdmin)) {
                element.style.display = 'none';
            }
        });
    }

    async loadInitialData() {
        await this.loadLatestUpdates();
    }

    async loadLatestUpdates() {
        try {
            const response = await fetch(`${this.apiBase}/content/latest`);
            if (response.ok) {
                const updates = await response.json();
                this.renderLatestUpdates(updates);
            }
        } catch (error) {
            console.log('Failed to load latest updates:', error);
        }
    }

    renderLatestUpdates(updates) {
        const container = document.getElementById('latest-updates');
        if (!container) return;

        container.innerHTML = updates.map(update => `
            <div class="cyber-timeline-item">
                <div class="flex justify-between items-start mb-2">
                    <h4 class="font-cyber text-cyber-primary">${update.title}</h4>
                    <span class="text-sm text-gray-400">${this.formatDate(update.date)}</span>
                </div>
                <p class="text-gray-300">${update.description}</p>
                <a href="${update.link}" class="cyber-link text-sm mt-2">Подробнее →</a>
            </div>
        `).join('');
    }

    formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('ru-RU');
    }

    toggleAIAssistant() {
        const assistant = document.querySelector('ai-assistant');
        if (assistant) {
            assistant.toggleChat();
        }
    }
}

// Initialize the portal
let portal;

document.addEventListener('DOMContentLoaded', function() {
    portal = new SingularityPortal();
    feather.replace();
});

// Utility functions
const Utils = {
    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    generateId() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    },

    formatFileSize(bytes) {
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        if (bytes === 0) return '0 Bytes';
        const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
    }
};

// API service for backend communication
class APIService {
    constructor() {
        this.baseURL = '/api';
    }

    async request(endpoint, options = {}) {
        const url = `${this.baseURL}${endpoint}`;
        const config = {
            headers: {
                'Content-Type': 'application/json',
            },
            ...options
        };

        try {
            const response = await fetch(url, config);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            console.error('API request failed:', error);
            throw error;
        }
    }

    // Content management
    async getContent(section, filters = {}) {
        const query = new URLSearchParams(filters).toString();
        return this.request(`/content/${section}?${query}`);
    }

    async createContent(contentData) {
        return this.request('/content', {
            method: 'POST',
            body: JSON.stringify(contentData)
        });
    }

    async updateContent(id, contentData) {
        return this.request(`/content/${id}`, {
            method: 'PUT',
            body: JSON.stringify(contentData)
        });
    }

    // AI Assistant communication
    async sendMessageToAI(message, context = {}) {
        return this.request('/ai/chat', {
            method: 'POST',
            body: JSON.stringify({ message, context })
        });
    }

    // User management
    async login(credentials) {
        return this.request('/auth/login', {
            method: 'POST',
            body: JSON.stringify(credentials)
        });
    }

    async register(userData) {
        return this.request('/auth/register', {
            method: 'POST',
            body: JSON.stringify(userData)
        });
    }
}

// Initialize API service
const apiService = new APIService();

// Export for use in components
window.SingularityPortal = SingularityPortal;
window.APIService = APIService;
window.Utils = Utils;