// =====================
// СОЗДАНИЕ ОБЪЯВЛЕНИЯ
// =====================
function updatePriceVisibility() {
const category = document.querySelector('input[name="category"]:checked')?.value;
const priceGroup = document.getElementById('priceGroup');
if (category === 'free' || category === 'lost') {
priceGroup.classList.remove('active');
priceGroup.style.display = 'none';
document.getElementById('createPrice').value = '';
} else {
priceGroup.classList.add('active');
priceGroup.style.display = 'block';
}
}
function handleImageUpload(input) {
const files = Array.from(input.files);
if (uploadedImages.length + files.length > 5) {
showAlert('createAlert', 'Максимум 5 фотографий', 'error');
return;
}
files.forEach(file => {
if (file.size > 5 * 1024 * 1024) {
showAlert('createAlert', 'Файл слишком большой (макс. 5 МБ)', 'error');
return;
}
const reader = new FileReader();
reader.onload = (e) => {
uploadedImages.push(e.target.result);
updateImagePreview();
};
reader.readAsDataURL(file);
});
}
function updateImagePreview() {
const preview = document.getElementById('imagePreview');
preview.innerHTML = uploadedImages.map((img, index) => `
`).join('');
}
function removeImage(index) {
uploadedImages.splice(index, 1);
updateImagePreview();
}
function handleCreateListing(event) {
event.preventDefault();
if (!currentUser) {
closeModal('createModal');
openModal('loginModal');
return;
}
const category = document.querySelector('input[name="category"]:checked')?.value;
const title = document.getElementById('createTitle').value.trim();
const price = parseInt(document.getElementById('createPrice').value) || 0;
const description = document.getElementById('createDescription').value.trim();
if (!category) {
showAlert('createAlert', 'Выберите категорию', 'error');
return;
}
const listings = DB.get('listings');
const newListing = {
id: Date.now(),
userId: currentUser.id,
category,
title,
price: (category === 'free' || category === 'lost') ? 0 : price,
description,
images: uploadedImages.length > 0 ? [...uploadedImages] : ['https://via.placeholder.com/400x300?text=Нет+фото'],
date: Date.now(),
views: 0,
sellerName: currentUser.name,
sellerPhone: currentUser.phone
};
listings.unshift(newListing);
DB.set('listings', listings);
// Очищаем форму
document.getElementById('createForm').reset();
uploadedImages = [];
updateImagePreview();
document.getElementById('priceGroup').style.display = 'none';
closeModal('createModal');
// Показываем все объявления
currentCategory = 'all';
document.querySelectorAll('.category-btn').forEach(b => b.classList.remove('active'));
document.querySelector('.category-btn').classList.add('active');
document.getElementById('pageTitle').textContent = 'Свежие объявления';
renderListings();
}
// =====================
// МОИ ОБЪЯВЛЕНИЯ
// =====================
function showMyListings() {
document.getElementById('userDropdown').classList.remove('active');
if (!currentUser) return;
const listings = DB.get('listings').filter(l => l.userId === currentUser.id);
document.getElementById('pageTitle').textContent = 'Мои объявления';
currentCategory = 'all';
document.querySelectorAll('.category-btn').forEach(b => b.classList.remove('active'));
document.querySelector('.category-btn').classList.add('active');
showHome();
renderListings(listings);
}
// =====================
// ЧАТ / СООБЩЕНИЯ
// =====================
function openChat(listingId) {
if (!currentUser) {
openModal('loginModal');
return;
}
const listings = DB.get('listings');
const listing = listings.find(l => l.id === listingId);
if (!listing) return;
currentListingId = listingId;
document.getElementById('chatTitle').textContent = listing.sellerName;
renderChatMessages(listingId);
openModal('chatModal');
setTimeout(() => {
document.getElementById('chatInput').focus();
}, 100);
}
function renderChatMessages(listingId) {
const allMessages = DB.get('messages') || {};
const chatKey = `${currentUser.id}_${listingId}`;
const messages = allMessages[chatKey] || [];
const container = document.getElementById('chatMessages');
if (messages.length === 0) {
container.innerHTML = `
????
Начните диалог с продавцом
`;
return;
}
container.innerHTML = messages.map(m => `
`).join('');
container.scrollTop = container.scrollHeight;
}
function handleChatEnter(event) {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
sendMessage();
}
}
function sendMessage() {
const input = document.getElementById('chatInput');
const text = input.value.trim();
if (!text || !currentUser || !currentListingId) return;
const allMessages = DB.get('messages') || {};
const chatKey = `${currentUser.id}_${currentListingId}`;
if (!allMessages[chatKey]) {
allMessages[chatKey] = [];
}
allMessages[chatKey].push({
id: Date.now(),
senderId: currentUser.id,
text,
date: Date.now()
});
DB.set('messages', allMessages);
input.value = '';
renderChatMessages(currentListingId);
}
function showMessages() {
document.getElementById('userDropdown').classList.remove('active');
// TODO: Страница со всеми диалогами
alert('Раздел сообщений в разработке');
}
// =====================
// УТИЛИТЫ
// =====================
function formatPrice(price) {
return price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
}
function formatDate(timestamp) {
const date = new Date(timestamp);
const now = new Date();
const diff = now - date;
const minutes = Math.floor(diff / 60000);
const hours = Math.floor(diff / 3600000);
const days = Math.floor(diff / 86400000);
if (minutes < 1) return 'Только что';
if (minutes < 60) return `${minutes} мин. назад`;
if (hours < 24) return `${hours} ч. назад`;
if (days === 1) return 'Вчера';
if (days < 7) return `${days} дн. назад`;
return date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' });
}
function showAlert(containerId, message, type) {
const container = document.getElementById(containerId);
container.innerHTML = `
${message}
`;
setTimeout(() => {
container.innerHTML = '';
}, 4000);
}
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// =====================
// ЗАПУСК
// =====================
init();