File size: 7,670 Bytes
2d8afac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Global application state
const AppState = {
    currentUser: null,
    posts: [],
    scheduledPosts: [],
    analytics: {},
    settings: {}
};

// Platform configurations
const PLATFORMS = {
    telegram: {
        name: 'Telegram',
        icon: 'message-circle',
        color: '#0088cc',
        maxLength: 4096,
        supportsMedia: true,
        supportsLinks: true
    },
    vk: {
        name: 'VK',
        icon: 'users',
        color: '#4a76a8',
        maxLength: 4096,
        supportsMedia: true,
        supportsLinks: true
    },
    linkedin: {
        name: 'LinkedIn',
        icon: 'briefcase',
        color: '#0077b5',
        maxLength: 3000,
        supportsMedia: true,
        supportsLinks: true
    },
    yandex_zen: {
        name: 'Яндекс.Дзен',
        icon: 'trending-up',
        color: '#ff0000',
        maxLength: 5000,
        supportsMedia: true,
        supportsLinks: true
    }
};

// Initialize application
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
    setupEventListeners();
    loadInitialData();
});

function initializeApp() {
    // Check for saved user preferences
    const savedTheme = localStorage.getItem('theme') || 'light';
    setTheme(savedTheme);
    
    // Initialize platform connections
    initializePlatformConnections();
}

function setupEventListeners() {
    // Theme toggle
    const themeToggle = document.getElementById('theme-toggle');
    if (themeToggle) {
        themeToggle.addEventListener('click', toggleTheme);
    }

    // Platform selection toggles
    document.querySelectorAll('input[type="checkbox"][name="platform"]').forEach(checkbox => {
        checkbox.addEventListener('change', updatePlatformSelection);
    });

    // Post character counters
    document.querySelectorAll('.post-content').forEach(textarea => {
        textarea.addEventListener('input', updateCharacterCount);
    });
}

function loadInitialData() {
    // Load posts from localStorage or API
    const savedPosts = localStorage.getItem('userPosts');
    if (savedPosts) {
        AppState.posts = JSON.parse(savedPosts);
        renderRecentPosts();
    }

    // Load scheduled posts
    const savedScheduled = localStorage.getItem('scheduledPosts');
    if (savedScheduled) {
        AppState.scheduledPosts = JSON.parse(savedScheduled);
        renderScheduledPosts();
    }
}

// Theme management
function setTheme(theme) {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem('theme', theme);
}

function toggleTheme() {
    const currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
    const newTheme = currentTheme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
}

// Platform management
function initializePlatformConnections() {
    // Check which platforms are connected
    const connectedPlatforms = JSON.parse(localStorage.getItem('connectedPlatforms') || '{}');
    
    Object.keys(PLATFORMS).forEach(platform => {
        const isConnected = connectedPlatforms[platform];
        if (isConnected) {
            console.log(`${PLATFORMS[platform].name} подключен`);
        updatePlatformUI(platform, true);
    });
}

function updatePlatformSelection(event) {
    const platform = event.target.value;
    const isSelected = event.target.checked;
    
    if (isSelected && !isPlatformConnected(platform)) {
        // Show connection modal
        showPlatformConnectionModal(platform);
    }
}

function isPlatformConnected(platform) {
    const connectedPlatforms = JSON.parse(localStorage.getItem('connectedPlatforms') || '{}');
    return !!connectedPlatforms[platform];
}

function showPlatformConnectionModal(platform) {
    // Implementation for platform connection modal
    const platformConfig = PLATFORMS[platform];
    alert(`Для публикации в ${platformConfig.name} необходимо подключить аккаунт. Перейдите в настройки для подключения.`);
}

// Post management
function createPost(postData) {
    const newPost = {
        id: generateId(),
        ...postData,
        createdAt: new Date().toISOString(),
        status: postData.scheduleFor ? 'scheduled' : 'draft'
    };

    AppState.posts.unshift(newPost);
    savePostsToStorage();
    
    if (postData.scheduleFor) {
        schedulePost(newPost);
    }
    
    return newPost;
}

function schedulePost(post) {
    AppState.scheduledPosts.push(post);
    saveScheduledPostsToStorage();
    
    // Schedule the actual posting (simplified)
    const scheduleTime = new Date(post.scheduleFor).getTime();
    const now = Date.now();
    
    if (scheduleTime > now) {
        setTimeout(() => {
            publishPost(post);
        }, scheduleTime - now);
    }
}

function publishPost(post) {
    // Simulate publishing to selected platforms
    const selectedPlatforms = post.platforms || [];
    
    selectedPlatforms.forEach(platform => {
        console.log(`Публикация в ${PLATFORMS[platform].name}: ${post.content.substring(0, 50)}...`);
        
        // Update post status
        post.status = 'published';
        post.publishedAt = new Date().toISOString();
        
        // Move from scheduled to published
        const scheduledIndex = AppState.scheduledPosts.findIndex(p => p.id === post.id);
        if (scheduledIndex > -1) {
            AppState.scheduledPosts.splice(scheduledIndex, 1);
        saveScheduledPostsToStorage();
    });
    
    savePostsToStorage();
    renderRecentPosts();
    renderScheduledPosts();
}

// Analytics functions
function calculateEngagementRate(views, interactions) {
    return views > 0 ? (interactions / views * 100).toFixed(1) : 0;
}

function getPlatformPerformance(platform) {
    // Mock data - replace with actual API call
    return {
        reach: Math.floor(Math.random() * 10000),
        engagement: (Math.random() * 10).toFixed(1),
        growth: (Math.random() * 20 - 5).toFixed(1)
    };
}

// Utility functions
function generateId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('ru-RU', {
        day: 'numeric',
        month: 'short',
        hour: '2-digit',
        minute: '2-digit'
    });
}

function savePostsToStorage() {
    localStorage.setItem('userPosts', JSON.stringify(AppState.posts));
}

function saveScheduledPostsToStorage() {
    localStorage.setItem('scheduledPosts', JSON.stringify(AppState.scheduledPosts));
}

// Render functions
function renderRecentPosts() {
    const container = document.querySelector('.recent-posts-container');
    if (!container) return;
    
    // Implementation for rendering recent posts
}

function renderScheduledPosts() {
    const container = document.querySelector('.scheduled-posts-container');
    if (!container) return;
    
    // Implementation for rendering scheduled posts
}

function updateCharacterCount(event) {
    const textarea = event.target;
    const counter = textarea.nextElementSibling;
    if (counter && counter.classList.contains('char-counter')) {
        const count = textarea.value.length;
        const maxLength = textarea.getAttribute('maxlength') || 4096;
        counter.textContent = `${count}/${maxLength}`;
        
        if (count > maxLength * 0.9) {
            counter.classList.add('text-red-500');
        } else {
            counter.classList.remove('text-red-500');
        }
    }
}

// Export for use in other modules
window.AppState = AppState;
window.PLATFORMS = PLATFORMS;