Загрузка данных


<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Веломагазин</title>
    <style>
        body {font-family: Arial, sans-serif; margin: 20px; background: #f4f4f9;}
        .container {display: flex; gap: 20px;}
        .products-grid, #cart {flex: 1; background: #fff; padding: 15px; border-radius: 5px;}
        .product-card {border: 1px solid #ddd; border-radius: 5px; padding: 10px; margin-bottom: 15px; display: flex; flex-direction: column;}
        .product-image {max-width: 100%; height: auto; border-radius: 5px;}
        .product-title {font-size: 1.2em; margin: 10px 0 5px;}
        .product-price {font-weight: bold; color: #28a745;}
        .add-to-cart {background: #007bff; color: white; border: none; padding: 8px; cursor: pointer; border-radius: 3px;}
        .add-to-cart:hover {background: #0056b3;}
        #category-filter {margin-bottom: 15px; padding: 5px;}
        #cart h4 {margin-top: 0;}
        #cart-items li {list-style: none; margin-bottom: 5px;}
        form input {display: block; margin-bottom: 10px; padding: 8px; width: 100%; box-sizing: border-box;}
        form button {background: #28a745; color: white; border: none; padding: 10px; cursor: pointer;}
    </style>
</head>
<body>

<div class="container">
    <!-- Блок с товарами -->
    <div class="products-grid" id="products-grid">
        <!-- Карточка товара -->
        <div class="product-card" data-category="mountain" data-id="1">
            <img src="https://placehold.co/300x200/FFB6C1/000000?text=Велосипед+1" alt="Горный велосипед" class="product-image">
            <h3 class="product-title">Aist Rockrider</h3>
            <p class="product-price">29 990 ₽</p>
            <p class="product-description">Горный велосипед для взрослых, 21 скорость.</p>
            <button class="add-to-cart" data-id="1" data-title="Aist Rockrider" data-price="29990">Добавить в корзину</button>
        </div>

        <!-- Карточка товара -->
        <div class="product-card" data-category="road" data-id="2">
            <img src="https://placehold.co/300x200/87CEFA/000000?text=Велосипед+2" alt="Шоссейный велосипед" class="product-image">
            <h3 class="product-title">Forward Sporting</h3>
            <p class="product-price">35 500 ₽</p>
            <p class="product-description">Шоссейный велосипед, легкая алюминиевая рама.</p>
            <button class="add-to-cart" data-id="2" data-title="Forward Sporting" data-price="35500">Добавить в корзину</button>
        </div>

         <!-- Карточка товара -->
         <div class="product-card" data-category="mountain" data-id="3">
             <img src="https://placehold.co/300x200/98FB98/000000?text=Велосипед+3" alt="Горный велосипед" class="product-image">
             <h3 class="product-title">Stark Tank</h3>
             <p class="product-price">42 000 ₽</p>
             <p class="product-description">Профессиональный горный велосипед, амортизация.</p>
             <button class="add-to-cart" data-id="3" data-title="Stark Tank" data-price="42000">Добавить в корзину</button>
         </div>
    </div>

    <!-- Корзина -->
    <div id="cart">
        <h4>Корзина</h4>
        <ul id="cart-items"></ul>
        <p><strong>Итого:</strong> <span id="cart-total">0</span> ₽</p>
    </div>
</div>

<!-- Фильтр и регистрация -->
<div style="margin-top: 25px;">
    <select id="category-filter">
        <option value="all">Все категории</option>
        <option value="mountain">Горные</option>
        <option value="road">Шоссейные</option>
    </select>

    <h3>Регистрация</h3>
    <form id="register-form">
        <input type="text" name="name" placeholder="Ваше имя" required>
        <input type="email" name="email" placeholder="Email" required>
        <input type="password" name="password" placeholder="Пароль (от 6 символов)" required minlength="6">
        <button type="submit">Зарегистрироваться</button>
    </form>
</div>

<script>
// --- Корзина ---
let cart = [];

function addToCart(id, title, price) {
    const existing = cart.find(item => item.id === id);
    if (existing) {
        existing.quantity++;
    } else {
        cart.push({id, title, price, quantity: 1});
    }
    updateCart();
}

function updateCart() {
    const list = document.getElementById('cart-items');
    const totalEl = document.getElementById('cart-total');
    list.innerHTML = '';
    let sum = 0;

    cart.forEach(item => {
        const li = document.createElement('li');
        li.textContent = `${item.title} — ${item.quantity} × ${item.price} ₽`;
        list.appendChild(li);
        sum += item.price * item.quantity;
    });

    totalEl.textContent = sum.toLocaleString('ru-RU');
}

// --- Фильтрация ---
document.getElementById('category-filter').addEventListener('change', function() {
    const category = this.value;
    const cards = document.querySelectorAll('.product-card');

    cards.forEach(card => {
        const cat = card.getAttribute('data-category');
        if (category === 'all' || cat === category) {
            card.style.display = 'block';
        } else {
            card.style.display = 'none';
        }
    });
});

// --- Добавление в корзину ---
document.getElementById('products-grid').addEventListener('click', function(e) {
    if (e.target.classList.contains('add-to-cart')) {
       const btn = e.target;
       const id = btn.getAttribute('data-id');
       const title = btn.getAttribute('data-title');
       const price = parseInt(btn.getAttribute('data-price'));
       addToCart(id, title, price);
    }
});

// --- Валидация формы регистрации ---
document.getElementById('register-form').addEventListener('submit', function(e) {
   e.preventDefault();
   const email = this.elements.email.value;
   const password = this.elements.password.value;

   // Валидация email
   if (!/^\S+@\S+\.\S+$/.test(email)) {
       alert('Пожалуйста, введите корректный адрес электронной почты.');
       return;
   }

   // Валидация пароля (уже есть minlength в HTML, но проверим еще раз)
   if (password.length < 6) {
       alert('Пароль должен содержать не менее 6 символов.');
       return;
   }

   // Здесь можно добавить отправку данных на сервер
   alert('✅ Регистрация прошла успешно! Данные:\nИмя: ' + this.elements.name.value + '\nEmail: ' + email);
   this.reset(); // Очистка формы после успешной отправки
});
</script>

</body>
</html>