Repository navigation
Expand file tree
/
Copy pathscripts.js
More file actions
632 lines (534 loc) · 21.6 KB
/
Copy pathscripts.js
File metadata and controls
632 lines (534 loc) · 21.6 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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
// ==========================================================
// REFRIDEV — EXPERIÊNCIA COMPLETA & INTERATIVA
// ==========================================================
// Elementos Principais
const prevBtn = document.getElementById('prev');
const nextBtn = document.getElementById('next');
const items = document.querySelectorAll('.item');
const flavorBtns = document.querySelectorAll('.flavor-btn');
const currentNum = document.getElementById('currentNum');
const ambientGlow = document.getElementById('ambientGlow');
const bubblesContainer = document.getElementById('bubblesContainer');
const cartCount = document.getElementById('cartCount');
const toast = document.getElementById('toast');
const toastMsg = document.getElementById('toastMsg');
// Cart Drawer Elements
const btnCart = document.getElementById('btnCart');
const btnCloseCart = document.getElementById('btnCloseCart');
const cartOverlay = document.getElementById('cartOverlay');
const cartDrawer = document.getElementById('cartDrawer');
const cartItemsList = document.getElementById('cartItemsList');
const cartBadgeTotal = document.getElementById('cartBadgeTotal');
const cartSubtotal = document.getElementById('cartSubtotal');
const cartDiscountRow = document.getElementById('cartDiscountRow');
const cartDiscount = document.getElementById('cartDiscount');
const cartTotal = document.getElementById('cartTotal');
const couponInput = document.getElementById('couponInput');
const btnApplyCoupon = document.getElementById('btnApplyCoupon');
const couponFeedback = document.getElementById('couponFeedback');
const btnCheckout = document.getElementById('btnCheckout');
// Nutrition Modal Elements
const nutritionModal = document.getElementById('nutritionModal');
const nutritionModalOverlay = document.getElementById('nutritionModalOverlay');
const btnCloseNutrition = document.getElementById('btnCloseNutrition');
const navNutrition = document.getElementById('navNutrition');
const modalFlavorBadge = document.getElementById('modalFlavorBadge');
const modalOrigin = document.getElementById('modalOrigin');
const nutriCal = document.getElementById('nutriCal');
const nutriCarbs = document.getElementById('nutriCarbs');
const nutriSugar = document.getElementById('nutriSugar');
const nutriSodium = document.getElementById('nutriSodium');
const nutriVitamin = document.getElementById('nutriVitamin');
// Sound Elements
const btnAudio = document.getElementById('btnAudio');
const soundLabel = document.getElementById('soundLabel');
let activeIndex = 0;
const totalItems = items.length;
let isAnimating = false;
let audioEnabled = true;
let appliedDiscount = 0; // 0 a 1 (ex: 0.1 para 10%)
// Estado do Carrinho: Array de { id, flavor, packLabel, price, qty, imgCan }
let cart = [];
// Cores de brilho para cada sabor
const glowColors = [
'rgba(234, 61, 65, 0.45)', // Morango
'rgba(45, 86, 67, 0.55)', // Abacate
'rgba(231, 160, 67, 0.45)' // Laranja
];
// ==========================================================
// 1. WEB AUDIO API SYNTHESIZER (SOM DE LATINHA & EFEITOS)
// ==========================================================
let audioCtx = null;
function getAudioContext() {
if (!audioCtx) {
const AudioContext = window.AudioContext || window.webkitAudioContext;
audioCtx = new AudioContext();
}
if (audioCtx.state === 'suspended') {
audioCtx.resume();
}
return audioCtx;
}
// Som de Abrir Latinha (Pop + Pssshhh)
function playCanOpenSound() {
if (!audioEnabled) return;
try {
const ctx = getAudioContext();
const now = ctx.currentTime;
// 1. O "POP" (Estalo do anel de vedação)
const popOsc = ctx.createOscillator();
const popGain = ctx.createGain();
popOsc.type = 'triangle';
popOsc.frequency.setValueAtTime(280, now);
popOsc.frequency.exponentialRampToValueAtTime(70, now + 0.08);
popGain.gain.setValueAtTime(0.7, now);
popGain.gain.exponentialRampToValueAtTime(0.01, now + 0.08);
popOsc.connect(popGain);
popGain.connect(ctx.destination);
popOsc.start(now);
popOsc.stop(now + 0.09);
// 2. O "PSSSHHH" (Gás efervescente pressurizado)
const bufferSize = ctx.sampleRate * 0.4;
const noiseBuffer = ctx.createBuffer(1, bufferSize, ctx.sampleRate);
const output = noiseBuffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
output[i] = Math.random() * 2 - 1;
}
const whiteNoise = ctx.createBufferSource();
whiteNoise.buffer = noiseBuffer;
// Filtro Bandpass para som de ar/gás realista
const filter = ctx.createBiquadFilter();
filter.type = 'bandpass';
filter.frequency.setValueAtTime(3200, now + 0.03);
filter.frequency.exponentialRampToValueAtTime(800, now + 0.35);
filter.Q.value = 3.0;
const noiseGain = ctx.createGain();
noiseGain.gain.setValueAtTime(0, now);
noiseGain.gain.setValueAtTime(0.45, now + 0.03);
noiseGain.gain.exponentialRampToValueAtTime(0.001, now + 0.38);
whiteNoise.connect(filter);
filter.connect(noiseGain);
noiseGain.connect(ctx.destination);
whiteNoise.start(now + 0.02);
whiteNoise.stop(now + 0.4);
} catch (err) {
console.warn('Audio Context não inicializado:', err);
}
}
// Som Suave de Bolha / Transição
function playBubblePopSound() {
if (!audioEnabled) return;
try {
const ctx = getAudioContext();
const now = ctx.currentTime;
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(450, now);
osc.frequency.exponentialRampToValueAtTime(850, now + 0.12);
gain.gain.setValueAtTime(0.2, now);
gain.gain.exponentialRampToValueAtTime(0.01, now + 0.12);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start(now);
osc.stop(now + 0.13);
} catch (e) {}
}
// Som de Celebração de Sucesso (Checkout)
function playSuccessChime() {
if (!audioEnabled) return;
try {
const ctx = getAudioContext();
const now = ctx.currentTime;
const notes = [523.25, 659.25, 783.99, 1046.50]; // C5, E5, G5, C6 (Acorde Maior)
notes.forEach((freq, idx) => {
const osc = ctx.createOscillator();
const gain = ctx.createGain();
const startTime = now + idx * 0.08;
osc.type = 'sine';
osc.frequency.setValueAtTime(freq, startTime);
gain.gain.setValueAtTime(0.25, startTime);
gain.gain.exponentialRampToValueAtTime(0.001, startTime + 0.6);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start(startTime);
osc.stop(startTime + 0.65);
});
} catch (e) {}
}
// Alternar Som On/Off
btnAudio.addEventListener('click', () => {
audioEnabled = !audioEnabled;
if (audioEnabled) {
btnAudio.classList.remove('muted');
soundLabel.textContent = 'Som: ON';
playBubblePopSound();
} else {
btnAudio.classList.add('muted');
soundLabel.textContent = 'Som: OFF';
}
});
// ==========================================================
// 2. SLIDER & NAVEGAÇÃO
// ==========================================================
function showSlide(newIndex) {
if (isAnimating || newIndex === activeIndex) return;
isAnimating = true;
playBubblePopSound();
// Remove active do slide atual
items[activeIndex].classList.remove('active');
flavorBtns[activeIndex].classList.remove('active');
// Atualiza índice
activeIndex = (newIndex + totalItems) % totalItems;
// Adiciona active no novo slide
items[activeIndex].classList.add('active');
flavorBtns[activeIndex].classList.add('active');
// Atualiza contador numérico
currentNum.textContent = `0${activeIndex + 1}`;
// Atualiza luz ambiente
ambientGlow.style.setProperty('--current-glow', glowColors[activeIndex]);
// Recalcula o preço exibido com base no pack selecionado
updateSlidePrice(items[activeIndex]);
// Efervescência
createFizzyBurst();
setTimeout(() => {
isAnimating = false;
}, 600);
}
nextBtn.addEventListener('click', () => showSlide(activeIndex + 1));
prevBtn.addEventListener('click', () => showSlide(activeIndex - 1));
flavorBtns.forEach((btn, idx) => {
btn.addEventListener('click', () => showSlide(idx));
});
window.addEventListener('keydown', (e) => {
if (e.key === 'ArrowRight') showSlide(activeIndex + 1);
if (e.key === 'ArrowLeft') showSlide(activeIndex - 1);
});
// ==========================================================
// 3. SELETOR DE PACKS (1x, 3x, 6x)
// ==========================================================
function setupPackSelectors() {
items.forEach(item => {
const packBtns = item.querySelectorAll('.pack-btn');
packBtns.forEach(btn => {
btn.addEventListener('click', () => {
packBtns.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
updateSlidePrice(item);
playBubblePopSound();
});
});
});
}
setupPackSelectors();
function updateSlidePrice(item) {
const basePrice = parseFloat(item.getAttribute('data-base-price')) || 7.90;
const activePackBtn = item.querySelector('.pack-btn.active');
const mult = activePackBtn ? parseFloat(activePackBtn.getAttribute('data-mult')) : 1;
const priceDisplay = item.querySelector('.price');
const calculatedPrice = (basePrice * mult).toFixed(2).replace('.', ',');
if (priceDisplay) {
priceDisplay.textContent = calculatedPrice;
}
}
// ==========================================================
// 4. REFLEXO METÁLICO & 3D PARALLAX NO MOUSE
// ==========================================================
document.addEventListener('mousemove', (e) => {
const { clientX, clientY } = e;
const centerX = window.innerWidth / 2;
const centerY = window.innerHeight / 2;
const moveX = (clientX - centerX) / centerX;
const moveY = (clientY - centerY) / centerY;
const activeItem = items[activeIndex];
if (!activeItem) return;
const can = activeItem.querySelector('.refrigerator');
const fruit = activeItem.querySelector('.fruit');
const watermark = activeItem.querySelector('.watermark');
// 3D Tilt na lata
if (can) {
can.style.transform = `rotateY(${moveX * 14}deg) rotateX(${-moveY * 10}deg) translate(${moveX * 15}px, ${moveY * 10}px)`;
}
// Frutas em parallax oposto
if (fruit) {
fruit.style.transform = `translate(calc(-50% + ${-moveX * 25}px), calc(-50% + ${-moveY * 15}px))`;
}
// Marca d'água no fundo
if (watermark) {
watermark.style.transform = `translate(calc(-50% + ${moveX * 35}px), calc(-50% + ${moveY * 20}px))`;
}
});
// ==========================================================
// 5. NAVEGAÇÃO POR SCROLL (WHEEL)
// ==========================================================
let scrollCooldown = false;
window.addEventListener('wheel', (e) => {
// Se a sacola ou modal estiverem abertos, não muda o slide pelo scroll
if (cartDrawer.classList.contains('open') || nutritionModal.classList.contains('open')) return;
if (scrollCooldown || isAnimating) return;
if (e.deltaY > 35) {
scrollCooldown = true;
showSlide(activeIndex + 1);
setTimeout(() => { scrollCooldown = false; }, 750);
} else if (e.deltaY < -35) {
scrollCooldown = true;
showSlide(activeIndex - 1);
setTimeout(() => { scrollCooldown = false; }, 750);
}
}, { passive: true });
// ==========================================================
// 6. GAVETA DA SACOLA (CART DRAWER & CHECKOUT)
// ==========================================================
function openCart() {
cartOverlay.classList.add('open');
cartDrawer.classList.add('open');
playBubblePopSound();
}
function closeCart() {
cartOverlay.classList.remove('open');
cartDrawer.classList.remove('open');
}
btnCart.addEventListener('click', openCart);
btnCloseCart.addEventListener('click', closeCart);
cartOverlay.addEventListener('click', closeCart);
// Adiciona o item do slide atual à sacola
function handleBuyCurrentSlide() {
const activeItem = items[activeIndex];
const flavor = activeItem.getAttribute('data-flavor');
const basePrice = parseFloat(activeItem.getAttribute('data-base-price')) || 7.90;
const activePackBtn = activeItem.querySelector('.pack-btn.active');
const packLabel = activePackBtn ? activePackBtn.getAttribute('data-label') : 'Lata 350ml';
const mult = activePackBtn ? parseFloat(activePackBtn.getAttribute('data-mult')) : 1;
const finalPrice = parseFloat((basePrice * mult).toFixed(2));
const imgCan = activeItem.getAttribute('data-img-can');
addToCart(flavor, packLabel, finalPrice, imgCan);
}
document.getElementById('btnHeaderBuy').addEventListener('click', handleBuyCurrentSlide);
function addToCart(flavor, packLabel, price, imgCan) {
playCanOpenSound();
// Verifica se item com mesmo sabor e pack já existe
const existingIndex = cart.findIndex(i => i.flavor === flavor && i.packLabel === packLabel);
if (existingIndex > -1) {
cart[existingIndex].qty += 1;
} else {
cart.push({
id: Date.now() + Math.random(),
flavor,
packLabel,
price,
qty: 1,
imgCan
});
}
renderCart();
// Feedback Toast
toastMsg.textContent = `${flavor} (${packLabel}) adicionado!`;
toast.classList.add('show');
setTimeout(() => { toast.classList.remove('show'); }, 2600);
}
function renderCart() {
// Total de itens
const totalQty = cart.reduce((acc, item) => acc + item.qty, 0);
cartCount.textContent = totalQty;
cartBadgeTotal.textContent = `${totalQty} ${totalQty === 1 ? 'item' : 'itens'}`;
if (cart.length === 0) {
cartItemsList.innerHTML = `
<div class="cart-empty">
<span class="cart-empty-icon">🛒</span>
<p>Sua sacola está vazia.</p>
<small>Escolha um sabor refrescante e adicione aqui!</small>
</div>
`;
cartSubtotal.textContent = 'R$ 0,00';
cartTotal.textContent = 'R$ 0,00';
cartDiscountRow.style.display = 'none';
return;
}
// Renderiza cada card de produto
cartItemsList.innerHTML = cart.map(item => `
<div class="cart-item-card">
<img src="${item.imgCan}" class="cart-item-img" alt="${item.flavor}">
<div class="cart-item-info">
<div class="cart-item-name">${item.flavor}</div>
<div class="cart-item-pack">${item.packLabel}</div>
<div class="cart-item-price">R$ ${(item.price * item.qty).toFixed(2).replace('.', ',')}</div>
</div>
<div class="cart-qty-ctrls">
<button class="btn-qty" onclick="changeCartQty(${item.id}, -1)">−</button>
<span class="qty-val">${item.qty}</span>
<button class="btn-qty" onclick="changeCartQty(${item.id}, 1)">+</button>
</div>
<button class="btn-remove-item" onclick="removeCartItem(${item.id})" title="Remover">✕</button>
</div>
`).join('');
// Cálculo de Valores
const rawSubtotal = cart.reduce((acc, item) => acc + (item.price * item.qty), 0);
cartSubtotal.textContent = `R$ ${rawSubtotal.toFixed(2).replace('.', ',')}`;
if (appliedDiscount > 0) {
const discountVal = rawSubtotal * appliedDiscount;
const finalTotal = rawSubtotal - discountVal;
cartDiscountRow.style.display = 'flex';
cartDiscount.textContent = `- R$ ${discountVal.toFixed(2).replace('.', ',')}`;
cartTotal.textContent = `R$ ${finalTotal.toFixed(2).replace('.', ',')}`;
} else {
cartDiscountRow.style.display = 'none';
cartTotal.textContent = `R$ ${rawSubtotal.toFixed(2).replace('.', ',')}`;
}
}
window.changeCartQty = (id, delta) => {
const item = cart.find(i => i.id === id);
if (!item) return;
item.qty += delta;
if (item.qty <= 0) {
cart = cart.filter(i => i.id !== id);
}
playBubblePopSound();
renderCart();
};
window.removeCartItem = (id) => {
cart = cart.filter(i => i.id !== id);
playBubblePopSound();
renderCart();
};
// Cupom de Desconto
btnApplyCoupon.addEventListener('click', () => {
const code = couponInput.value.trim().toUpperCase();
if (code === 'DEV10' || code === 'DEVCLUB10') {
appliedDiscount = 0.10; // 10% de desconto
couponFeedback.className = 'coupon-feedback success';
couponFeedback.textContent = '✓ Cupom DEV10 aplicado: 10% de desconto!';
playSuccessChime();
} else if (code === '') {
appliedDiscount = 0;
couponFeedback.textContent = '';
} else {
couponFeedback.className = 'coupon-feedback error';
couponFeedback.textContent = '✕ Cupom inválido. Tente DEV10';
}
renderCart();
});
// Finalizar Pedido (Checkout com Confetes!)
btnCheckout.addEventListener('click', () => {
if (cart.length === 0) {
alert('Sua sacola está vazia! Adicione um refrigerante antes de finalizar.');
return;
}
playSuccessChime();
startConfetti();
toastMsg.textContent = '🎉 Pedido realizado com sucesso!';
toast.classList.add('show');
setTimeout(() => {
cart = [];
appliedDiscount = 0;
couponInput.value = '';
couponFeedback.textContent = '';
renderCart();
closeCart();
toast.classList.remove('show');
}, 2800);
});
// ==========================================================
// 7. MODAL DE TABELA NUTRICIONAL
// ==========================================================
function openNutritionModal() {
const activeItem = items[activeIndex];
modalFlavorBadge.textContent = activeItem.getAttribute('data-flavor');
modalOrigin.textContent = `Origem: ${activeItem.getAttribute('data-origin')}`;
nutriCal.textContent = activeItem.getAttribute('data-calories');
nutriCarbs.textContent = activeItem.getAttribute('data-carbs');
nutriSugar.textContent = activeItem.getAttribute('data-sugar');
nutriSodium.textContent = activeItem.getAttribute('data-sodium');
nutriVitamin.textContent = activeItem.getAttribute('data-vitamin');
nutritionModalOverlay.classList.add('open');
nutritionModal.classList.add('open');
playBubblePopSound();
}
function closeNutritionModal() {
nutritionModalOverlay.classList.remove('open');
nutritionModal.classList.remove('open');
}
window.openNutritionModal = openNutritionModal;
btnCloseNutrition.addEventListener('click', closeNutritionModal);
nutritionModalOverlay.addEventListener('click', closeNutritionModal);
navNutrition.addEventListener('click', openNutritionModal);
// ==========================================================
// 8. GERADOR DE PARTÍCULAS EFERVESCENTES (GÁS)
// ==========================================================
function createBubble() {
if (!bubblesContainer) return;
const bubble = document.createElement('div');
bubble.classList.add('bubble');
const size = Math.random() * 14 + 6;
const left = Math.random() * 100;
const duration = Math.random() * 4 + 4;
bubble.style.width = `${size}px`;
bubble.style.height = `${size}px`;
bubble.style.left = `${left}%`;
bubble.style.animationDuration = `${duration}s`;
bubblesContainer.appendChild(bubble);
setTimeout(() => {
bubble.remove();
}, duration * 1000);
}
setInterval(createBubble, 350);
function createFizzyBurst() {
for (let i = 0; i < 16; i++) {
setTimeout(createBubble, i * 35);
}
}
// ==========================================================
// 9. MOTOR DE CONFETES EM CANVAS (CHECKOUT CELEBRATION)
// ==========================================================
const canvas = document.getElementById('confettiCanvas');
const ctx = canvas.getContext('2d');
let confettiParticles = [];
let confettiAnimationId = null;
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
function createConfettiPiece() {
const colors = ['#EA3D41', '#2D5643', '#E7A043', '#ffffff', '#10b981', '#f59e0b', '#3b82f6'];
return {
x: Math.random() * canvas.width,
y: -20,
size: Math.random() * 8 + 6,
color: colors[Math.floor(Math.random() * colors.length)],
velX: (Math.random() - 0.5) * 6,
velY: Math.random() * 5 + 4,
rot: Math.random() * 360,
rotSpeed: (Math.random() - 0.5) * 10
};
}
function startConfetti() {
confettiParticles = [];
for (let i = 0; i < 150; i++) {
confettiParticles.push(createConfettiPiece());
}
if (confettiAnimationId) cancelAnimationFrame(confettiAnimationId);
animateConfetti();
setTimeout(() => {
confettiParticles = [];
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (confettiAnimationId) cancelAnimationFrame(confettiAnimationId);
}, 4000);
}
function animateConfetti() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
confettiParticles.forEach(p => {
p.x += p.velX;
p.y += p.velY;
p.rot += p.rotSpeed;
ctx.save();
ctx.translate(p.x, p.y);
ctx.rotate((p.rot * Math.PI) / 180);
ctx.fillStyle = p.color;
ctx.fillRect(-p.size / 2, -p.size / 2, p.size, p.size * 0.6);
ctx.restore();
});
if (confettiParticles.length > 0) {
confettiAnimationId = requestAnimationFrame(animateConfetti);
}
}