-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
509 lines (430 loc) · 13.4 KB
/
script.js
File metadata and controls
509 lines (430 loc) · 13.4 KB
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
const STORAGE_KEYS = {
carrinho: "carrinho",
usuario: "usuarioLogado",
usuarios: "usuariosSmartZone",
compras: "historicoCompras"
};
let carrinho = JSON.parse(localStorage.getItem(STORAGE_KEYS.carrinho)) || [];
let usuario = JSON.parse(localStorage.getItem(STORAGE_KEYS.usuario)) || null;
let usuarios = JSON.parse(localStorage.getItem(STORAGE_KEYS.usuarios)) || [];
const loginBtn = document.getElementById("loginBtn");
const userStatus = document.getElementById("userStatus");
const cartCount = document.getElementById("cartCount");
const authPanel = document.getElementById("authPanel");
const authTitle = document.getElementById("authTitle");
const authMessage = document.getElementById("authMessage");
const closeAuth = document.getElementById("closeAuth");
const tabLogin = document.getElementById("tabLogin");
const tabRegister = document.getElementById("tabRegister");
const loginForm = document.getElementById("loginForm");
const registerForm = document.getElementById("registerForm");
const loginEmail = document.getElementById("loginEmail");
const loginPassword = document.getElementById("loginPassword");
const registerName = document.getElementById("registerName");
const registerEmail = document.getElementById("registerEmail");
const registerPassword = document.getElementById("registerPassword");
const lista = document.getElementById("lista");
const input = document.getElementById("search");
const status = document.getElementById("status");
const btnOrdenar = document.getElementById("ordenar");
const precoMaxInput = document.getElementById("precoMax");
const cartToggle = document.getElementById("cartToggle");
const cartPanel = document.getElementById("cartPanel");
const fecharCarrinho = document.getElementById("fecharCarrinho");
const limparCarrinhoBtn = document.getElementById("limparCarrinho");
const cartItems = document.getElementById("cartItems");
const cartEmpty = document.getElementById("cartEmpty");
const cartTotal = document.getElementById("cartTotal");
const checkoutBtn = document.getElementById("checkoutBtn");
const produtos = [
{
id: 1,
nome: "Camera Canon",
preco: 11000,
imagem: "imag/camera.png",
detalhes: [
{ label: "Modelo", valor: "Canon EOS" },
{ label: "Lente", valor: "8x16 mm" },
{ label: "Uso", valor: "Fotos e videos profissionais" }
]
},
{
id: 2,
nome: "Samsung Galaxy S23",
preco: 9500,
imagem: "imag/sansung.png",
detalhes: [
{ label: "Modelo", valor: "Galaxy S23" },
{ label: "Tela", valor: '6.1"' },
{ label: "Memoria", valor: "128 GB" }
]
},
{
id: 3,
nome: "Laptop Lenovo",
preco: 210000,
imagem: "imag/leptop.png",
detalhes: [
{ label: "Modelo", valor: "Lenovo IdeaPad" },
{ label: "Tela", valor: '15.6"' },
{ label: "Processador", valor: "Intel Core i7" }
]
},
{
id: 4,
nome: "AirPod Bluetooth",
preco: 1500,
imagem: "imag/airpod.png",
detalhes: [
{ label: "Modelo", valor: "AirPod Pro" },
{ label: "Conexao", valor: "Bluetooth 5.0" },
{ label: "Bateria", valor: "Ate 24 horas" }
]
},
{
id: 5,
nome: "Monitor Gamer",
preco: 5000,
imagem: "imag/monitor.png",
detalhes: [
{ label: "Modelo", valor: "Gamer Vision" },
{ label: "Tamanho", valor: '27"' },
{ label: "Taxa", valor: "144 Hz" }
]
},
{
id: 6,
nome: "Teclados Wireless",
preco: 600,
imagem: "imag/teclados.png",
detalhes: [
{ label: "Modelo", valor: "Wireless Compact" },
{ label: "Ligacao", valor: "USB e Bluetooth" },
{ label: "Layout", valor: "ABNT2" }
]
},
{
id: 7,
nome: "Mouse Gamer",
preco: 450,
imagem: "imag/mouse.png",
detalhes: [
{ label: "Modelo", valor: "Speed Mouse X" },
{ label: "Sensor", valor: "6400 DPI" },
{ label: "Iluminacao", valor: "RGB" }
]
},
{
id: 8,
nome: "Pen Drive 128GB",
preco: 2000,
imagem: "imag/pendrive.png",
detalhes: [
{ label: "Modelo", valor: "Flash Storage" },
{ label: "Capacidade", valor: "128 GB" },
{ label: "Entrada", valor: "USB 3.0" }
]
}
];
const cache = {};
let dados = [...produtos];
function normalizarCarrinho() {
carrinho = carrinho.map((item) => {
if (item.quantidade) return item;
return { ...item, quantidade: 1 };
});
salvarCarrinho();
}
function salvarCarrinho() {
localStorage.setItem(STORAGE_KEYS.carrinho, JSON.stringify(carrinho));
}
function salvarUsuarios() {
localStorage.setItem(STORAGE_KEYS.usuarios, JSON.stringify(usuarios));
}
function salvarSessao() {
localStorage.setItem(STORAGE_KEYS.usuario, JSON.stringify(usuario));
}
function debounce(fn, delay) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => fn.apply(this, args), delay);
};
}
function destacar(texto, busca) {
if (!busca) return texto;
const regex = new RegExp(`(${busca})`, "gi");
return texto.replace(regex, "<mark>$1</mark>");
}
function formatarDetalhes(detalhes) {
return detalhes
.map(item => `<p class="descricao"><strong>${item.label}:</strong> ${item.valor}</p>`)
.join("");
}
function formatarPreco(valor) {
return `${Number(valor).toLocaleString("pt-PT")} MT`;
}
function validarEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
function validarSenha(senha) {
return senha.length >= 4;
}
function getTotalItens() {
return carrinho.reduce((total, item) => total + item.quantidade, 0);
}
function calcularTotal() {
return carrinho.reduce((total, item) => total + (item.preco * item.quantidade), 0);
}
function mostrarMensagemAuth(texto, tipo) {
authMessage.textContent = texto;
authMessage.className = tipo ? `auth-message ${tipo}` : "auth-message";
}
function alternarAuth(modo) {
const loginAtivo = modo === "login";
tabLogin.classList.toggle("active", loginAtivo);
tabRegister.classList.toggle("active", !loginAtivo);
loginForm.classList.toggle("hidden", !loginAtivo);
registerForm.classList.toggle("hidden", loginAtivo);
authTitle.textContent = loginAtivo ? "Entrar" : "Criar conta";
mostrarMensagemAuth("", "");
}
function abrirAuth(modo) {
authPanel.classList.remove("hidden");
alternarAuth(modo);
if (modo === "login") {
loginEmail.focus();
} else {
registerName.focus();
}
}
function fecharAuthPanel() {
authPanel.classList.add("hidden");
mostrarMensagemAuth("", "");
loginForm.reset();
registerForm.reset();
}
function atualizarUI() {
cartCount.textContent = getTotalItens();
userStatus.textContent = usuario ? `Usuario: ${usuario.nome}` : "Nao logado";
loginBtn.textContent = usuario ? "Sair" : "Entrar";
renderCarrinho();
}
function adicionarCarrinho(produto) {
const existente = carrinho.find((item) => item.id === produto.id);
if (existente) {
existente.quantidade += 1;
} else {
carrinho.push({ ...produto, quantidade: 1 });
}
salvarCarrinho();
atualizarUI();
alert("Produto adicionado ao carrinho!");
}
function atualizarQuantidade(idProduto, delta) {
const item = carrinho.find((produto) => produto.id === idProduto);
if (!item) return;
item.quantidade += delta;
if (item.quantidade <= 0) {
carrinho = carrinho.filter((produto) => produto.id !== idProduto);
}
salvarCarrinho();
atualizarUI();
}
function removerDoCarrinho(idProduto) {
carrinho = carrinho.filter((produto) => produto.id !== idProduto);
salvarCarrinho();
atualizarUI();
}
function limparCarrinho() {
carrinho = [];
salvarCarrinho();
atualizarUI();
}
function renderCarrinho() {
cartItems.innerHTML = "";
if (carrinho.length === 0) {
cartEmpty.style.display = "block";
checkoutBtn.classList.add("disabled-link");
limparCarrinhoBtn.disabled = true;
} else {
cartEmpty.style.display = "none";
checkoutBtn.classList.remove("disabled-link");
limparCarrinhoBtn.disabled = false;
}
carrinho.forEach((produto) => {
const item = document.createElement("li");
item.className = "cart-item";
item.innerHTML = `
<div class="cart-item-info">
<strong>${produto.nome}</strong>
<p>${formatarPreco(produto.preco)} cada</p>
</div>
<div class="cart-item-controls">
<div class="qty-controls">
<button class="btn-qty" data-action="decrease">-</button>
<span class="qty-value">${produto.quantidade}</span>
<button class="btn-qty" data-action="increase">+</button>
</div>
<p class="cart-item-subtotal">${formatarPreco(produto.preco * produto.quantidade)}</p>
<button class="btn-remover">Remover</button>
</div>
`;
item.querySelector('[data-action="decrease"]').addEventListener("click", () => {
atualizarQuantidade(produto.id, -1);
});
item.querySelector('[data-action="increase"]').addEventListener("click", () => {
atualizarQuantidade(produto.id, 1);
});
item.querySelector(".btn-remover").addEventListener("click", () => {
removerDoCarrinho(produto.id);
});
cartItems.appendChild(item);
});
cartTotal.textContent = `Total: ${formatarPreco(calcularTotal())}`;
}
function filtrar(texto, precoMax) {
const chave = texto + "_" + precoMax;
if (cache[chave]) return cache[chave];
const resultado = produtos.filter(produto =>
produto.nome.toLowerCase().includes(texto.toLowerCase()) &&
(precoMax ? produto.preco <= precoMax : true)
);
cache[chave] = resultado;
return resultado;
}
function render(listaProdutos) {
lista.innerHTML = "";
if (listaProdutos.length === 0) {
status.textContent = "Nenhum produto encontrado";
return;
}
const fragment = document.createDocumentFragment();
listaProdutos.slice(0, 50).forEach(produto => {
const li = document.createElement("li");
li.innerHTML = `
<img src="${produto.imagem}" alt="${produto.nome}">
<div class="info">
<h3>${destacar(produto.nome, input.value)}</h3>
<div class="detalhes">${formatarDetalhes(produto.detalhes)}</div>
</div>
<div class="lado-direito">
<p class="preco">${formatarPreco(produto.preco)}</p>
<button class="btn-comprar">Adicionar</button>
</div>
`;
li.querySelector(".btn-comprar").addEventListener("click", () => {
adicionarCarrinho(produto);
});
fragment.appendChild(li);
});
lista.appendChild(fragment);
status.textContent = `Mostrando ${listaProdutos.length} resultados`;
}
loginBtn.addEventListener("click", () => {
if (usuario) {
usuario = null;
localStorage.removeItem(STORAGE_KEYS.usuario);
fecharAuthPanel();
atualizarUI();
return;
}
abrirAuth("login");
});
tabLogin.addEventListener("click", () => alternarAuth("login"));
tabRegister.addEventListener("click", () => alternarAuth("register"));
closeAuth.addEventListener("click", fecharAuthPanel);
loginForm.addEventListener("submit", (event) => {
event.preventDefault();
const email = loginEmail.value.trim().toLowerCase();
const senha = loginPassword.value.trim();
if (!validarEmail(email)) {
mostrarMensagemAuth("Digite um email valido.", "error");
return;
}
if (!validarSenha(senha)) {
mostrarMensagemAuth("A senha deve ter pelo menos 4 caracteres.", "error");
return;
}
const conta = usuarios.find(item => item.email === email && item.senha === senha);
if (!conta) {
mostrarMensagemAuth("Email ou senha incorretos.", "error");
return;
}
usuario = {
nome: conta.nome,
email: conta.email
};
salvarSessao();
fecharAuthPanel();
atualizarUI();
});
registerForm.addEventListener("submit", (event) => {
event.preventDefault();
const nome = registerName.value.trim();
const email = registerEmail.value.trim().toLowerCase();
const senha = registerPassword.value.trim();
if (nome.length < 3) {
mostrarMensagemAuth("Digite um nome com pelo menos 3 letras.", "error");
return;
}
if (!validarEmail(email)) {
mostrarMensagemAuth("Digite um email valido.", "error");
return;
}
if (!validarSenha(senha)) {
mostrarMensagemAuth("A senha deve ter pelo menos 4 caracteres.", "error");
return;
}
const existe = usuarios.some(item => item.email === email);
if (existe) {
mostrarMensagemAuth("Ja existe uma conta com esse email.", "error");
return;
}
const novaConta = { nome, email, senha };
usuarios.push(novaConta);
salvarUsuarios();
usuario = { nome, email };
salvarSessao();
fecharAuthPanel();
atualizarUI();
});
input.addEventListener("input", debounce((event) => {
const valor = event.target.value;
const precoMax = precoMaxInput.value;
status.textContent = "A procurar...";
dados = filtrar(valor, precoMax);
render(dados);
}, 300));
btnOrdenar.addEventListener("click", () => {
dados.sort((a, b) => a.nome.localeCompare(b.nome));
render(dados);
});
cartToggle.addEventListener("click", () => {
cartPanel.classList.toggle("hidden");
});
fecharCarrinho.addEventListener("click", () => {
cartPanel.classList.add("hidden");
});
limparCarrinhoBtn.addEventListener("click", () => {
const confirmar = confirm("Tens certeza que desejas limpar todo o carrinho?");
if (confirmar) {
limparCarrinho();
}
});
checkoutBtn.addEventListener("click", (event) => {
if (carrinho.length === 0) {
event.preventDefault();
alert("Adicione produtos ao carrinho antes de continuar.");
return;
}
if (!usuario) {
event.preventDefault();
cartPanel.classList.add("hidden");
abrirAuth("login");
mostrarMensagemAuth("Faca login para continuar no checkout.", "error");
}
});
normalizarCarrinho();
render(produtos);
atualizarUI();