magan-balalar-oyynshygyn-sat/script.js

286 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Saryarq Oyyn — каталог и корзина (статика, без бэкенда)
// Корзина хранится в localStorage; оформление — через WhatsApp.
var WA_PHONE = "77000000000"; // заменить на свой номер в формате +7XXXXXXXXXX (только цифры)
var CART_KEY = "saryarq-cart";
var PRICE_LOCALE = "ru-RU";
var TINTS = [
"var(--kt-ai-primary-subtle)",
"var(--kt-ai-chip-green-bg)",
"var(--kt-ai-chip-purple-bg)",
"var(--kt-ai-chip-orange-bg)",
"var(--kt-ai-chip-blue-bg)",
"var(--kt-ai-chip-pink-bg)"
];
var TINT_NAMES = {
"var(--kt-ai-primary-subtle)": "blue",
"var(--kt-ai-chip-green-bg)": "green",
"var(--kt-ai-chip-purple-bg)": "purple",
"var(--kt-ai-chip-orange-bg)": "orange",
"var(--kt-ai-chip-blue-bg)": "blue2",
"var(--kt-ai-chip-pink-bg)": "pink"
};
var TOYS = [
{ id: "blocks-300", name: "Конструктор «Город» 300 деталей", cat: "Конструкторы", age: "3+", price: 18500, icon: "grid-3x3", pop: 98 },
{ id: "robot-x5", name: "Робот-трансформер ROBO X5", cat: "Роботы", age: "5+", price: 24900, icon: "cpu", pop: 95 },
{ id: "teddy-bear", name: "Мягкий медвежонок, 40 см", cat: "Мягкие игрушки", age: "0+", price: 9900, icon: "heart", pop: 92 },
{ id: "wooden-cabinet", name: "Детский шкаф для игр (дерево)", cat: "Народные игрушки", age: "1+", price: 14200, icon: "home", pop: 88 },
{ id: "puzzle-100", name: "Пазл 3D «Волшебный лес», 100 деталей", cat: "Пазлы и мозаики", age: "3+", price: 6500, icon: "layers", pop: 85 },
{ id: "barbie-dream", name: "Кукла Друзья — нарядный набор", cat: "Куклы", age: "4+", price: 12800, icon: "user", pop: 90 },
{ id: "car-set", name: "Машинки — набор 6 штук", cat: "Машинки", age: "2+", price: 15400, icon: "truck", pop: 93 },
{ id: "train-city", name: "Полигон железных дорог «Город»", cat: "Машинки", age: "4+", price: 21900, icon: "truck", pop: 87 },
{ id: "kubiks-500", name: "Пропеллер-конструктор 500 деталей", cat: "Конструкторы", age: "6+", price: 27500, icon: "cube", pop: 84 },
{ id: "puzzle-animals", name: "Животные фермы, пазл 60 деталей", cat: "Пазлы и мозаики", age: "3+", price: 4800, icon: "layers", pop: 78 },
{ id: "plush-bunny", name: "Мягкая заяц, 25 см (малыш)", cat: "Мягкие игрушки", age: "0+", price: 5600, icon: "heart", pop: 82 },
{ id: "doll-princess", name: "Кукла-принцесса с платьем", cat: "Куклы", age: "4+", price: 11200, icon: "user", pop: 80 },
{ id: "robot-dino", name: "Робот-дина (свет и звук)", cat: "Роботы", age: "4+", price: 19900, icon: "cpu", pop: 89 },
{ id: "blocks-wood", name: "Деревянные кубики, 48 штук", cat: "Народные игрушки", age: "1+", price: 7300, icon: "grid-3x3", pop: 86 },
{ id: "truck-cargo", name: "Грузовик-самосвал, масштаб 1:32", cat: "Машинки", age: "3+", price: 8900, icon: "truck", pop: 76 },
{ id: "doll-dream-room", name: "Нарядная куколка + набор аксессуаров", cat: "Куклы", age: "5+", price: 16700, icon: "user", pop: 79 }
];
var CATS = ["Все", "Конструкторы", "Роботы", "Мягкие игрушки", "Куклы", "Машинки", "Пазлы и мозаики", "Народные игрушки"];
var state = {
cat: "Все",
q: "",
sort: "popular",
cart: loadCart()
};
// ---------- утилиты ----------
function esc(s) {
return String(s).replace(/[&<>"']/g, function (c) {
return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c];
});
}
function fmtPrice(n) {
return n.toLocaleString(PRICE_LOCALE) + " ₸";
}
function tint(i) {
return TINTS[i % TINTS.length];
}
function tintName(i) {
return TINT_NAMES[tint(i)] || "blue";
}
function iconSvg(name, extra) {
return '<svg class="kt-icon' + (extra ? " " + extra : "") + '" aria-hidden="true"><use href="#' + name + '"></use></svg>';
}
// ---------- корзина ----------
function loadCart() {
try {
var raw = localStorage.getItem(CART_KEY);
return raw ? JSON.parse(raw) : {};
} catch (e) {
return {};
}
}
function saveCart() {
try {
localStorage.setItem(CART_KEY, JSON.stringify(state.cart));
} catch (e) { /* приватный режим — молча */ }
}
function cartCount() {
var c = 0;
for (var id in state.cart) c += state.cart[id];
return c;
}
function cartTotal() {
var t = 0;
for (var id in state.cart) {
var toy = TOYS.find(function (x) { return x.id === id; });
if (toy) t += toy.price * state.cart[id];
}
return t;
}
function addToCart(id) {
state.cart[id] = (state.cart[id] || 0) + 1;
saveCart();
renderCart();
}
function changeQty(id, delta) {
var q = (state.cart[id] || 0) + delta;
if (q <= 0) delete state.cart[id];
else state.cart[id] = q;
saveCart();
renderCart();
}
function waLink(text) {
return "https://wa.me/" + WA_PHONE + "?text=" + encodeURIComponent(text);
}
// ---------- рендер каталога ----------
function filtered() {
var list = TOYS.filter(function (t) {
var okCat = state.cat === "Все" || t.cat === state.cat;
var okQ = !state.q || t.name.toLowerCase().indexOf(state.q) !== -1;
return okCat && okQ;
});
if (state.sort === "price-asc") list.sort(function (a, b) { return a.price - b.price; });
else if (state.sort === "price-desc") list.sort(function (a, b) { return b.price - a.price; });
else if (state.sort === "name") list.sort(function (a, b) { return a.name.localeCompare(b.name, "ru"); });
else list.sort(function (a, b) { return b.pop - a.pop; });
return list;
}
function renderCatalog() {
var grid = document.getElementById("prodGrid");
var list = filtered();
var html = "";
list.forEach(function (t) {
var inCart = state.cart[t.id] ? ' data-added="true"' : "";
html += '<article class="prod-card">' +
'<div class="prod-thumb" style="background:' + tint(t.name.length) + '">' +
'<span>' + t.name.charAt(0) + '</span>' +
iconSvg(t.icon) +
'</div>' +
'<div class="prod-body">' +
'<div class="prod-name">' + esc(t.name) + '</div>' +
'<div class="prod-age">' + esc(t.cat) + " · " + esc(t.age) + '</div>' +
'<div class="prod-foot">' +
'<span class="prod-price">' + fmtPrice(t.price) + '</span>' +
'<button class="kt-ai-btn" data-size="sm"' + (inCart ? ' data-variant="ghost"' : '') + ' data-id="' + t.id + '" data-action="add">' +
'<svg class="kt-icon" aria-hidden="true" style="width:14px;height:14px;margin-right:5px"><use href="#plus"></use></svg>В корзину' +
'</button>' +
'</div>' +
'</div>' +
'</article>';
});
grid.innerHTML = html;
document.getElementById("noResults").style.display = list.length ? "none" : "block";
}
function renderChips() {
var box = document.getElementById("catChips");
box.innerHTML = CATS.map(function (c) {
return '<button class="chip-cat"' + (c === state.cat ? ' data-active="true"' : '') + ' data-cat="' + esc(c) + '">' + esc(c) + '</button>';
}).join("");
}
// ---------- рендер корзины ----------
function renderCart() {
var n = cartCount();
document.getElementById("cartCount").textContent = n;
document.getElementById("cartCountFab").textContent = n;
document.body.classList.toggle("has-cart", n > 0);
var itemsBox = document.getElementById("cartItems");
var foot = document.getElementById("cartFoot");
var ids = Object.keys(state.cart);
if (!ids.length) {
itemsBox.innerHTML = '<p class="cart-empty">Корзина пуста.<br>Добавьте игрушки из каталога.</p>';
foot.style.display = "none";
return;
}
foot.style.display = "flex";
document.getElementById("cartTotal").textContent = fmtPrice(cartTotal());
var html = "";
ids.forEach(function (id, i) {
var toy = TOYS.find(function (x) { return x.id === id; });
if (!toy) return;
var q = state.cart[id];
html += '<div class="cart-item">' +
'<div class="cart-item-art" style="background:' + tint(i) + '">' +
'<span>' + esc(toy.name.charAt(0)) + '</span>' +
iconSvg(toy.icon) +
'</div>' +
'<div class="cart-item-info">' +
'<div class="cart-item-name">' + esc(toy.name) + '</div>' +
'<div class="cart-item-price">' + fmtPrice(toy.price) + " × " + q + '</div>' +
'</div>' +
'<div class="stepper">' +
'<button data-id="' + toy.id + '" data-action="dec" aria-label="Меньше">−</button>' +
'<span class="qty">' + q + '</span>' +
'<button data-id="' + toy.id + '" data-action="inc" aria-label="Больше">+</button>' +
'</div>' +
'</div>';
});
itemsBox.innerHTML = html;
// текст заказа для WhatsApp
var lines = ids.map(function (id, i) {
var toy = TOYS.find(function (x) { return x.id === id; });
if (!toy) return "";
return (i + 1) + ". " + toy.name + " × " + state.cart[id] + " — " + fmtPrice(toy.price * state.cart[id]);
});
var msg = "Здравствуйте! Хочу заказать:\n" + lines.join("\n") + "\nИтого: " + fmtPrice(cartTotal());
document.getElementById("cartWa").href = waLink(msg);
}
// ---------- ящик (drawer) ----------
function openCart() {
document.getElementById("cartDrawer").classList.add("open");
document.getElementById("cartOverlay").classList.add("open");
document.getElementById("cartDrawer").setAttribute("aria-hidden", "false");
}
function closeCart() {
document.getElementById("cartDrawer").classList.remove("open");
document.getElementById("cartOverlay").classList.remove("open");
document.getElementById("cartDrawer").setAttribute("aria-hidden", "true");
}
// ---------- события ----------
document.addEventListener("click", function (e) {
var btn = e.target.closest("[data-action]");
if (!btn) return;
var id = btn.getAttribute("data-id");
var action = btn.getAttribute("data-action");
if (action === "add") addToCart(id);
else if (action === "inc") changeQty(id, 1);
else if (action === "dec") changeQty(id, -1);
});
document.getElementById("catChips").addEventListener("click", function (e) {
var c = e.target.closest(".chip-cat");
if (!c) return;
state.cat = c.getAttribute("data-cat");
renderChips();
renderCatalog();
});
document.getElementById("shopSearch").addEventListener("input", function (e) {
state.q = e.target.value.trim().toLowerCase();
renderCatalog();
});
document.getElementById("sortSelect").addEventListener("change", function (e) {
state.sort = e.target.value;
renderCatalog();
});
document.getElementById("cartClose").addEventListener("click", closeCart);
document.getElementById("cartOverlay").addEventListener("click", closeCart);
document.getElementById("cartFab").addEventListener("click", openCart);
document.addEventListener("keydown", function (e) {
if (e.key === "Escape") closeCart();
});
document.getElementById("cartWa").addEventListener("click", function () {
closeCart();
});
// ссылка-кнопка «Оформить заказ» в шапке и CTA
document.querySelectorAll('a[href="#catalog"]').forEach(function (a) {
// кнопка «В корзину» в шапке — открывает ящик
});
var headerCartBtn = document.querySelector('.kt-ai-pagehead a[data-variant="ghost"]');
if (headerCartBtn) headerCartBtn.addEventListener("click", function (e) {
e.preventDefault();
openCart();
});
document.getElementById("ctaWa").href = waLink("Здравствуйте! Есть вопрос по выбору игрушки.");
document.getElementById("waPhone").textContent = "+" + WA_PHONE;
document.getElementById("waPhone").href = "https://wa.me/" + WA_PHONE;
// ---------- старт ----------
renderChips();
renderCatalog();
renderCart();